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

- -

- -libtesla is the interface between the Tesla overlay loader and user-made Overlays. It handles all layer creation, UI creation, drawing and input management. -It's main goal is to make sure all overlays look and feel similar and don't differenciate themselves from the switch's native overlays. - -## Screenshots - -
- - -
- -`Overlays do NOT show up on Screenshots. These pictures were taken using a capture card` - -## Example - -An example for how to use libtesla can be found here: https://github.com/WerWolv/libtesla/tree/master/example -To create your own Overlay, please consider creating a new repository using the official Tesla overlay template: https://github.com/WerWolv/Tesla-Template - -**Please Note:** While it is possible to create overlays without libtesla, it's highly recommended to not do so. libtesla handles showing and hiding of overlays, button combo detection, layer creation and a lot more. Not using it will lead to an inconsistent user experience when using multiple different overlays ultimately making it worse for the end user. If something's missing, please consider opening a PR here. - -## Credits - -- **switchbrew** for nx-hbloader which is used as basis for overlay loading -- **kardch** for the amazing icon -- **All the devs on AtlasNX, RetroNX and Switchbrew** for their feedback -- **All overlay devs** for making something awesome out of this :) - diff --git a/Source/sys-clk/overlay/lib/libultrahand/libtesla/example/Makefile b/Source/sys-clk/overlay/lib/libultrahand/libtesla/example/Makefile deleted file mode 100644 index cdb011ae..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libtesla/example/Makefile +++ /dev/null @@ -1,209 +0,0 @@ -#--------------------------------------------------------------------------------- -.SUFFIXES: -#--------------------------------------------------------------------------------- - -ifeq ($(strip $(DEVKITPRO)),) -$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=/devkitpro") -endif - -TOPDIR ?= $(CURDIR) -include $(DEVKITPRO)/libnx/switch_rules - -#--------------------------------------------------------------------------------- -# TARGET is the name of the output -# BUILD is the directory where object files & intermediate files will be placed -# SOURCES is a list of directories containing source code -# DATA is a list of directories containing data files -# INCLUDES is a list of directories containing header files -# ROMFS is the directory containing data to be added to RomFS, relative to the Makefile (Optional) -# -# NO_ICON: if set to anything, do not use icon. -# NO_NACP: if set to anything, no .nacp file is generated. -# APP_TITLE is the name of the app stored in the .nacp file (Optional) -# APP_AUTHOR is the author of the app stored in the .nacp file (Optional) -# APP_VERSION is the version of the app stored in the .nacp file (Optional) -# APP_TITLEID is the titleID of the app stored in the .nacp file (Optional) -# ICON is the filename of the icon (.jpg), relative to the project folder. -# If not set, it attempts to use one of the following (in this order): -# - .jpg -# - icon.jpg -# - /default_icon.jpg -# -# CONFIG_JSON is the filename of the NPDM config file (.json), relative to the project folder. -# If not set, it attempts to use one of the following (in this order): -# - .json -# - config.json -# If a JSON file is provided or autodetected, an ExeFS PFS0 (.nsp) is built instead -# of a homebrew executable (.nro). This is intended to be used for sysmodules. -# NACP building is skipped as well. -#--------------------------------------------------------------------------------- - -APP_TITLE := Tesla Example -APP_VERSION := 1.3.0 - -TARGET := $(notdir $(CURDIR)) -BUILD := build -SOURCES := source -DATA := data -INCLUDES := ../include - -NO_ICON := 1 - -#--------------------------------------------------------------------------------- -# options for code generation -#--------------------------------------------------------------------------------- -ARCH := -march=armv8-a+crc+crypto -mtune=cortex-a57 -mtp=soft -fPIE - -CFLAGS := -g -Wall -O2 -ffunction-sections \ - $(ARCH) $(DEFINES) - -CFLAGS += $(INCLUDE) -D__SWITCH__ - -CXXFLAGS := $(CFLAGS) -fno-exceptions -std=c++20 - -ASFLAGS := -g $(ARCH) -LDFLAGS = -specs=$(DEVKITPRO)/libnx/switch.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map) - -LIBS := -lnx - -#--------------------------------------------------------------------------------- -# list of directories containing libraries, this must be the top level containing -# include and lib -#--------------------------------------------------------------------------------- -LIBDIRS := $(PORTLIBS) $(LIBNX) - - -#--------------------------------------------------------------------------------- -# no real need to edit anything past this point unless you need to add additional -# rules for different file extensions -#--------------------------------------------------------------------------------- -ifneq ($(BUILD),$(notdir $(CURDIR))) -#--------------------------------------------------------------------------------- - -export OUTPUT := $(CURDIR)/$(TARGET) -export TOPDIR := $(CURDIR) - -export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ - $(foreach dir,$(DATA),$(CURDIR)/$(dir)) - -export DEPSDIR := $(CURDIR)/$(BUILD) - -CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c))) -CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp))) -SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s))) -BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) - -#--------------------------------------------------------------------------------- -# use CXX for linking C++ projects, CC for standard C -#--------------------------------------------------------------------------------- -ifeq ($(strip $(CPPFILES)),) -#--------------------------------------------------------------------------------- - export LD := $(CC) -#--------------------------------------------------------------------------------- -else -#--------------------------------------------------------------------------------- - export LD := $(CXX) -#--------------------------------------------------------------------------------- -endif -#--------------------------------------------------------------------------------- - -export OFILES_BIN := $(addsuffix .o,$(BINFILES)) -export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o) -export OFILES := $(OFILES_BIN) $(OFILES_SRC) -export HFILES_BIN := $(addsuffix .h,$(subst .,_,$(BINFILES))) - -export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ - $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ - -I$(CURDIR)/$(BUILD) - -export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib) - -ifeq ($(strip $(CONFIG_JSON)),) - jsons := $(wildcard *.json) - ifneq (,$(findstring $(TARGET).json,$(jsons))) - export APP_JSON := $(TOPDIR)/$(TARGET).json - else - ifneq (,$(findstring config.json,$(jsons))) - export APP_JSON := $(TOPDIR)/config.json - endif - endif -else - export APP_JSON := $(TOPDIR)/$(CONFIG_JSON) -endif - -ifeq ($(strip $(ICON)),) - icons := $(wildcard *.jpg) - ifneq (,$(findstring $(TARGET).jpg,$(icons))) - export APP_ICON := $(TOPDIR)/$(TARGET).jpg - else - ifneq (,$(findstring icon.jpg,$(icons))) - export APP_ICON := $(TOPDIR)/icon.jpg - endif - endif -else - export APP_ICON := $(TOPDIR)/$(ICON) -endif - -ifeq ($(strip $(NO_ICON)),) - export NROFLAGS += --icon=$(APP_ICON) -endif - -ifeq ($(strip $(NO_NACP)),) - export NROFLAGS += --nacp=$(CURDIR)/$(TARGET).nacp -endif - -ifneq ($(APP_TITLEID),) - export NACPFLAGS += --titleid=$(APP_TITLEID) -endif - -ifneq ($(ROMFS),) - export NROFLAGS += --romfsdir=$(CURDIR)/$(ROMFS) -endif - -.PHONY: $(BUILD) clean all - -#--------------------------------------------------------------------------------- -all: $(BUILD) - - -$(BUILD): - @[ -d $@ ] || mkdir -p $@ - @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile - -#--------------------------------------------------------------------------------- -clean: - @rm -fr $(BUILD) $(TARGET).ovl $(TARGET).nro $(TARGET).nacp $(TARGET).elf - - -#--------------------------------------------------------------------------------- -else -.PHONY: all - -DEPENDS := $(OFILES:.o=.d) - -#--------------------------------------------------------------------------------- -# main targets -#--------------------------------------------------------------------------------- -all : $(OUTPUT).ovl - -$(OUTPUT).ovl : $(OUTPUT).elf $(OUTPUT).nacp - @elf2nro $< $@ $(NROFLAGS) - @echo "built ... $(notdir $(OUTPUT).ovl)" - -$(OUTPUT).elf : $(OFILES) - -$(OFILES_SRC) : $(HFILES_BIN) - -#--------------------------------------------------------------------------------- -# you need a rule like this for each extension you use as binary data -#--------------------------------------------------------------------------------- -%.bin.o %_bin.h : %.bin -#--------------------------------------------------------------------------------- - @echo $(notdir $<) - @$(bin2o) - --include $(DEPENDS) - -#--------------------------------------------------------------------------------------- -endif -#--------------------------------------------------------------------------------------- diff --git a/Source/sys-clk/overlay/lib/libultrahand/libtesla/example/source/main.cpp b/Source/sys-clk/overlay/lib/libultrahand/libtesla/example/source/main.cpp deleted file mode 100644 index bf4c2522..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libtesla/example/source/main.cpp +++ /dev/null @@ -1,100 +0,0 @@ -#define TESLA_INIT_IMPL // If you have more than one file using the tesla header, only define this in the main one -#include // The Tesla Header - - -class GuiSecondary : public tsl::Gui { -public: - GuiSecondary() {} - - virtual tsl::elm::Element* createUI() override { - auto *rootFrame = new tsl::elm::OverlayFrame("Tesla Example", "v1.3.2 - Secondary Gui"); - - rootFrame->setContent(new tsl::elm::DebugRectangle(tsl::Color{ 0x8, 0x3, 0x8, 0xF })); - - return rootFrame; - } -}; - -class GuiTest : public tsl::Gui { -public: - GuiTest(u8 arg1, u8 arg2, bool arg3) { } - - // Called when this Gui gets loaded to create the UI - // Allocate all elements on the heap. libtesla will make sure to clean them up when not needed anymore - virtual tsl::elm::Element* createUI() override { - // A OverlayFrame is the base element every overlay consists of. This will draw the default Title and Subtitle. - // If you need more information in the header or want to change it's look, use a HeaderOverlayFrame. - auto frame = new tsl::elm::OverlayFrame("Tesla Example", "v1.3.2"); - - // A list that can contain sub elements and handles scrolling - auto list = new tsl::elm::List(); - - // List Items - list->addItem(new tsl::elm::CategoryHeader("List items")); - - auto *clickableListItem = new tsl::elm::ListItem("Clickable List Item", "..."); - clickableListItem->setClickListener([](u64 keys) { - if (keys & HidNpadButton_A) { - tsl::changeTo(); - return true; - } - - return false; - }); - - list->addItem(clickableListItem); - list->addItem(new tsl::elm::ListItem("Default List Item")); - list->addItem(new tsl::elm::ListItem("Default List Item with an extra long name to trigger truncation and scrolling")); - list->addItem(new tsl::elm::ToggleListItem("Toggle List Item", true)); - - // Custom Drawer, a element that gives direct access to the renderer - list->addItem(new tsl::elm::CategoryHeader("Custom Drawer", true)); - list->addItem(new tsl::elm::CustomDrawer([](tsl::gfx::Renderer *renderer, s32 x, s32 y, s32 w, s32 h) { - renderer->drawCircle(x + 40, y + 40, 20, true, renderer->a(0xF00F)); - renderer->drawCircle(x + 50, y + 50, 20, true, renderer->a(0xF0F0)); - renderer->drawRect(x + 130, y + 30, 60, 40, renderer->a(0xFF00)); - renderer->drawString("Hello :)", false, x + 250, y + 70, 20, renderer->a(0xFF0F)); - renderer->drawRect(x + 40, y + 90, 300, 10, renderer->a(0xF0FF)); - }), 100); - - // Track bars - list->addItem(new tsl::elm::CategoryHeader("Track bars")); - list->addItem(new tsl::elm::TrackBar("\u2600")); - list->addItem(new tsl::elm::StepTrackBar("\uE13C", 20)); - list->addItem(new tsl::elm::NamedStepTrackBar("\uE132", { "Selection 1", "Selection 2", "Selection 3" })); - - // Add the list to the frame for it to be drawn - frame->setContent(list); - - // Return the frame to have it become the top level element of this Gui - return frame; - } - - // Called once every frame to update values - virtual void update() override { - - } - - // Called once every frame to handle inputs not handled by other UI elements - virtual bool handleInput(u64 keysDown, u64 keysHeld, const HidTouchState &touchPos, HidAnalogStickState joyStickPosLeft, HidAnalogStickState joyStickPosRight) override { - return false; // Return true here to signal the inputs have been consumed - } -}; - -class OverlayTest : public tsl::Overlay { -public: - // libtesla already initialized fs, hid, pl, pmdmnt, hid:sys and set:sys - virtual void initServices() override {} // Called at the start to initialize all services necessary for this Overlay - virtual void exitServices() override {} // Called at the end to clean up all services previously initialized - - virtual void onShow() override {} // Called before overlay wants to change from invisible to visible state - virtual void onHide() override {} // Called before overlay wants to change from visible to invisible state - - virtual std::unique_ptr loadInitialGui() override { - return initially(1, 2, true); // Initial Gui to load. It's possible to pass arguments to it's constructor like this - } -}; - -int main(int argc, char **argv) { - return tsl::loop(argc, argv); -} diff --git a/Source/sys-clk/overlay/lib/libultrahand/libtesla/include/stb_truetype.h b/Source/sys-clk/overlay/lib/libultrahand/libtesla/include/stb_truetype.h deleted file mode 100644 index 392ca11d..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libtesla/include/stb_truetype.h +++ /dev/null @@ -1,5265 +0,0 @@ -// stb_truetype.h - v1.26 - public domain -// authored from 2009-2021 by Sean Barrett / RAD Game Tools -// -// ======================================================================= -// -// NO SECURITY GUARANTEE -- DO NOT USE THIS ON UNTRUSTED FONT FILES -// -// This library does no range checking of the offsets found in the file, -// meaning an attacker can use it to read arbitrary memory. -// -// ======================================================================= -// -// This library processes TrueType files: -// parse files -// extract glyph metrics -// extract glyph shapes -// render glyphs to one-channel bitmaps with antialiasing (box filter) -// render glyphs to one-channel SDF bitmaps (signed-distance field/function) -// -// Todo: -// non-MS cmaps -// crashproof on bad data -// hinting? (no longer patented) -// cleartype-style AA? -// optimize: use simple memory allocator for intermediates -// optimize: build edge-list directly from curves -// optimize: rasterize directly from curves? -// -// ADDITIONAL CONTRIBUTORS -// -// Mikko Mononen: compound shape support, more cmap formats -// Tor Andersson: kerning, subpixel rendering -// Dougall Johnson: OpenType / Type 2 font handling -// Daniel Ribeiro Maciel: basic GPOS-based kerning -// -// Misc other: -// Ryan Gordon -// Simon Glass -// github:IntellectualKitty -// Imanol Celaya -// Daniel Ribeiro Maciel -// -// Bug/warning reports/fixes: -// "Zer" on mollyrocket Fabian "ryg" Giesen github:NiLuJe -// Cass Everitt Martins Mozeiko github:aloucks -// stoiko (Haemimont Games) Cap Petschulat github:oyvindjam -// Brian Hook Omar Cornut github:vassvik -// Walter van Niftrik Ryan Griege -// David Gow Peter LaValle -// David Given Sergey Popov -// Ivan-Assen Ivanov Giumo X. Clanjor -// Anthony Pesch Higor Euripedes -// Johan Duparc Thomas Fields -// Hou Qiming Derek Vinyard -// Rob Loach Cort Stratton -// Kenney Phillis Jr. Brian Costabile -// Ken Voskuil (kaesve) Yakov Galka -// -// VERSION HISTORY -// -// 1.26 (2021-08-28) fix broken rasterizer -// 1.25 (2021-07-11) many fixes -// 1.24 (2020-02-05) fix warning -// 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS) -// 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined -// 1.21 (2019-02-25) fix warning -// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() -// 1.19 (2018-02-11) GPOS kerning, STBTT_fmod -// 1.18 (2018-01-29) add missing function -// 1.17 (2017-07-23) make more arguments const; doc fix -// 1.16 (2017-07-12) SDF support -// 1.15 (2017-03-03) make more arguments const -// 1.14 (2017-01-16) num-fonts-in-TTC function -// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts -// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual -// 1.11 (2016-04-02) fix unused-variable warning -// 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef -// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly -// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges -// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; -// variant PackFontRanges to pack and render in separate phases; -// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); -// fixed an assert() bug in the new rasterizer -// replace assert() with STBTT_assert() in new rasterizer -// -// Full history can be found at the end of this file. -// -// LICENSE -// -// See end of file for license information. -// -// USAGE -// -// Include this file in whatever places need to refer to it. In ONE C/C++ -// file, write: -// #define STB_TRUETYPE_IMPLEMENTATION -// before the #include of this file. This expands out the actual -// implementation into that C/C++ file. -// -// To make the implementation private to the file that generates the implementation, -// #define STBTT_STATIC -// -// Simple 3D API (don't ship this, but it's fine for tools and quick start) -// stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture -// stbtt_GetBakedQuad() -- compute quad to draw for a given char -// -// Improved 3D API (more shippable): -// #include "stb_rect_pack.h" -- optional, but you really want it -// stbtt_PackBegin() -// stbtt_PackSetOversampling() -- for improved quality on small fonts -// stbtt_PackFontRanges() -- pack and renders -// stbtt_PackEnd() -// stbtt_GetPackedQuad() -// -// "Load" a font file from a memory buffer (you have to keep the buffer loaded) -// stbtt_InitFont() -// stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections -// stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections -// -// Render a unicode codepoint to a bitmap -// stbtt_GetCodepointBitmap() -- allocates and returns a bitmap -// stbtt_MakeCodepointBitmap() -- renders into bitmap you provide -// stbtt_GetCodepointBitmapBox() -- how big the bitmap must be -// -// Character advance/positioning -// stbtt_GetCodepointHMetrics() -// stbtt_GetFontVMetrics() -// stbtt_GetFontVMetricsOS2() -// stbtt_GetCodepointKernAdvance() -// -// Starting with version 1.06, the rasterizer was replaced with a new, -// faster and generally-more-precise rasterizer. The new rasterizer more -// accurately measures pixel coverage for anti-aliasing, except in the case -// where multiple shapes overlap, in which case it overestimates the AA pixel -// coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If -// this turns out to be a problem, you can re-enable the old rasterizer with -// #define STBTT_RASTERIZER_VERSION 1 -// which will incur about a 15% speed hit. -// -// ADDITIONAL DOCUMENTATION -// -// Immediately after this block comment are a series of sample programs. -// -// After the sample programs is the "header file" section. This section -// includes documentation for each API function. -// -// Some important concepts to understand to use this library: -// -// Codepoint -// Characters are defined by unicode codepoints, e.g. 65 is -// uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is -// the hiragana for "ma". -// -// Glyph -// A visual character shape (every codepoint is rendered as -// some glyph) -// -// Glyph index -// A font-specific integer ID representing a glyph -// -// Baseline -// Glyph shapes are defined relative to a baseline, which is the -// bottom of uppercase characters. Characters extend both above -// and below the baseline. -// -// Current Point -// As you draw text to the screen, you keep track of a "current point" -// which is the origin of each character. The current point's vertical -// position is the baseline. Even "baked fonts" use this model. -// -// Vertical Font Metrics -// The vertical qualities of the font, used to vertically position -// and space the characters. See docs for stbtt_GetFontVMetrics. -// -// Font Size in Pixels or Points -// The preferred interface for specifying font sizes in stb_truetype -// is to specify how tall the font's vertical extent should be in pixels. -// If that sounds good enough, skip the next paragraph. -// -// Most font APIs instead use "points", which are a common typographic -// measurement for describing font size, defined as 72 points per inch. -// stb_truetype provides a point API for compatibility. However, true -// "per inch" conventions don't make much sense on computer displays -// since different monitors have different number of pixels per -// inch. For example, Windows traditionally uses a convention that -// there are 96 pixels per inch, thus making 'inch' measurements have -// nothing to do with inches, and thus effectively defining a point to -// be 1.333 pixels. Additionally, the TrueType font data provides -// an explicit scale factor to scale a given font's glyphs to points, -// but the author has observed that this scale factor is often wrong -// for non-commercial fonts, thus making fonts scaled in points -// according to the TrueType spec incoherently sized in practice. -// -// DETAILED USAGE: -// -// Scale: -// Select how high you want the font to be, in points or pixels. -// Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute -// a scale factor SF that will be used by all other functions. -// -// Baseline: -// You need to select a y-coordinate that is the baseline of where -// your text will appear. Call GetFontBoundingBox to get the baseline-relative -// bounding box for all characters. SF*-y0 will be the distance in pixels -// that the worst-case character could extend above the baseline, so if -// you want the top edge of characters to appear at the top of the -// screen where y=0, then you would set the baseline to SF*-y0. -// -// Current point: -// Set the current point where the first character will appear. The -// first character could extend left of the current point; this is font -// dependent. You can either choose a current point that is the leftmost -// point and hope, or add some padding, or check the bounding box or -// left-side-bearing of the first character to be displayed and set -// the current point based on that. -// -// Displaying a character: -// Compute the bounding box of the character. It will contain signed values -// relative to . I.e. if it returns x0,y0,x1,y1, -// then the character should be displayed in the rectangle from -// to = 32 && *text < 128) { - stbtt_aligned_quad q; - stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9 - glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y0); - glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y0); - glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y1); - glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y1); - } - ++text; - } - glEnd(); -} -#endif -// -// -////////////////////////////////////////////////////////////////////////////// -// -// Complete program (this compiles): get a single bitmap, print as ASCII art -// -#if 0 -#include -#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation -#include "stb_truetype.h" - -char ttf_buffer[1<<25]; - -int main(int argc, char **argv) -{ - stbtt_fontinfo font; - unsigned char *bitmap; - int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20); - - fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb")); - - stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0)); - bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0); - - for (j=0; j < h; ++j) { - for (i=0; i < w; ++i) - putchar(" .:ioVM@"[bitmap[j*w+i]>>5]); - putchar('\n'); - } - return 0; -} -#endif -// -// Output: -// -// .ii. -// @@@@@@. -// V@Mio@@o -// :i. V@V -// :oM@@M -// :@@@MM@M -// @@o o@M -// :@@. M@M -// @@@o@@@@ -// :M@@V:@@. -// -////////////////////////////////////////////////////////////////////////////// -// -// Complete program: print "Hello World!" banner, with bugs -// -#if 0 -char buffer[24<<20]; -unsigned char screen[20][79]; - -int main(int arg, char **argv) -{ - stbtt_fontinfo font; - int i,j,ascent,baseline,ch=0; - float scale, xpos=2; // leave a little padding in case the character extends left - char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness - - fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb")); - stbtt_InitFont(&font, buffer, 0); - - scale = stbtt_ScaleForPixelHeight(&font, 15); - stbtt_GetFontVMetrics(&font, &ascent,0,0); - baseline = (int) (ascent*scale); - - while (text[ch]) { - int advance,lsb,x0,y0,x1,y1; - float x_shift = xpos - (float) floor(xpos); - stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb); - stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1); - stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]); - // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong - // because this API is really for baking character bitmaps into textures. if you want to render - // a sequence of characters, you really need to render each bitmap to a temp buffer, then - // "alpha blend" that into the working buffer - xpos += (advance * scale); - if (text[ch+1]) - xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]); - ++ch; - } - - for (j=0; j < 20; ++j) { - for (i=0; i < 78; ++i) - putchar(" .:ioVM@"[screen[j][i]>>5]); - putchar('\n'); - } - - return 0; -} -#endif - - -////////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////////// -//// -//// INTEGRATION WITH YOUR CODEBASE -//// -//// The following sections allow you to supply alternate definitions -//// of C library functions used by stb_truetype, e.g. if you don't -//// link with the C runtime library. - -#ifdef STB_TRUETYPE_IMPLEMENTATION - // #define your own (u)stbtt_int8/16/32 before including to override this - #ifndef stbtt_uint8 - typedef unsigned char stbtt_uint8; - typedef signed char stbtt_int8; - typedef unsigned short stbtt_uint16; - typedef signed short stbtt_int16; - typedef unsigned int stbtt_uint32; - typedef signed int stbtt_int32; - #endif - - typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1]; - typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1]; - - // e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h - #ifndef STBTT_ifloor - #include - #define STBTT_ifloor(x) ((int) floor(x)) - #define STBTT_iceil(x) ((int) ceil(x)) - #endif - - #ifndef STBTT_sqrt - #include - #define STBTT_sqrt(x) sqrt(x) - #define STBTT_pow(x,y) pow(x,y) - #endif - - #ifndef STBTT_fmod - #include - #define STBTT_fmod(x,y) fmod(x,y) - #endif - - #ifndef STBTT_cos - #include - #define STBTT_cos(x) cos(x) - #define STBTT_acos(x) acos(x) - #endif - - #ifndef STBTT_fabs - #include - #define STBTT_fabs(x) fabs(x) - #endif - - // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h - #ifndef STBTT_malloc - #include - #define STBTT_malloc(x,u) ((void)(u),malloc(x)) - #define STBTT_free(x,u) ((void)(u),free(x)) - #endif - - //ifndef STBTT_assert - //include - //define STBTT_assert(x) assert(x) - //endif - - #ifndef STBTT_strlen - #include - #define STBTT_strlen(x) strlen(x) - #endif - - #ifndef STBTT_memcpy - #include - #define STBTT_memcpy memcpy - #define STBTT_memset memset - #endif -#endif - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -//// -//// INTERFACE -//// -//// - -#ifndef __STB_INCLUDE_STB_TRUETYPE_H__ -#define __STB_INCLUDE_STB_TRUETYPE_H__ - -#ifdef STBTT_STATIC -#define STBTT_DEF static -#else -#define STBTT_DEF extern -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -// private structure -typedef struct -{ - unsigned char *data; - int cursor; - int size; -} stbtt__buf; - -////////////////////////////////////////////////////////////////////////////// -// -// TEXTURE BAKING API -// -// If you use this API, you only have to call two functions ever. -// - -typedef struct -{ - unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap - float xoff,yoff,xadvance; -} stbtt_bakedchar; - -STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) - float pixel_height, // height of font in pixels - unsigned char *pixels, int pw, int ph, // bitmap to be filled in - int first_char, int num_chars, // characters to bake - stbtt_bakedchar *chardata); // you allocate this, it's num_chars long -// if return is positive, the first unused row of the bitmap -// if return is negative, returns the negative of the number of characters that fit -// if return is 0, no characters fit and no rows were used -// This uses a very crappy packing. - -typedef struct -{ - float x0,y0,s0,t0; // top-left - float x1,y1,s1,t1; // bottom-right -} stbtt_aligned_quad; - -STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, // same data as above - int char_index, // character to display - float *xpos, float *ypos, // pointers to current position in screen pixel space - stbtt_aligned_quad *q, // output: quad to draw - int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier -// Call GetBakedQuad with char_index = 'character - first_char', and it -// creates the quad you need to draw and advances the current position. -// -// The coordinate system used assumes y increases downwards. -// -// Characters will extend both above and below the current position; -// see discussion of "BASELINE" above. -// -// It's inefficient; you might want to c&p it and optimize it. - -STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap); -// Query the font vertical metrics without having to create a font first. - - -////////////////////////////////////////////////////////////////////////////// -// -// NEW TEXTURE BAKING API -// -// This provides options for packing multiple fonts into one atlas, not -// perfectly but better than nothing. - -typedef struct -{ - unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap - float xoff,yoff,xadvance; - float xoff2,yoff2; -} stbtt_packedchar; - -typedef struct stbtt_pack_context stbtt_pack_context; -typedef struct stbtt_fontinfo stbtt_fontinfo; -#ifndef STB_RECT_PACK_VERSION -typedef struct stbrp_rect stbrp_rect; -#endif - -STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context); -// Initializes a packing context stored in the passed-in stbtt_pack_context. -// Future calls using this context will pack characters into the bitmap passed -// in here: a 1-channel bitmap that is width * height. stride_in_bytes is -// the distance from one row to the next (or 0 to mean they are packed tightly -// together). "padding" is the amount of padding to leave between each -// character (normally you want '1' for bitmaps you'll use as textures with -// bilinear filtering). -// -// Returns 0 on failure, 1 on success. - -STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc); -// Cleans up the packing context and frees all memory. - -#define STBTT_POINT_SIZE(x) (-(x)) - -STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, - int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range); -// Creates character bitmaps from the font_index'th font found in fontdata (use -// font_index=0 if you don't know what that is). It creates num_chars_in_range -// bitmaps for characters with unicode values starting at first_unicode_char_in_range -// and increasing. Data for how to render them is stored in chardata_for_range; -// pass these to stbtt_GetPackedQuad to get back renderable quads. -// -// font_size is the full height of the character from ascender to descender, -// as computed by stbtt_ScaleForPixelHeight. To use a point size as computed -// by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE() -// and pass that result as 'font_size': -// ..., 20 , ... // font max minus min y is 20 pixels tall -// ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall - -typedef struct -{ - float font_size; - int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint - int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints - int num_chars; - stbtt_packedchar *chardata_for_range; // output - unsigned char h_oversample, v_oversample; // don't set these, they're used internally -} stbtt_pack_range; - -STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges); -// Creates character bitmaps from multiple ranges of characters stored in -// ranges. This will usually create a better-packed bitmap than multiple -// calls to stbtt_PackFontRange. Note that you can call this multiple -// times within a single PackBegin/PackEnd. - -STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample); -// Oversampling a font increases the quality by allowing higher-quality subpixel -// positioning, and is especially valuable at smaller text sizes. -// -// This function sets the amount of oversampling for all following calls to -// stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given -// pack context. The default (no oversampling) is achieved by h_oversample=1 -// and v_oversample=1. The total number of pixels required is -// h_oversample*v_oversample larger than the default; for example, 2x2 -// oversampling requires 4x the storage of 1x1. For best results, render -// oversampled textures with bilinear filtering. Look at the readme in -// stb/tests/oversample for information about oversampled fonts -// -// To use with PackFontRangesGather etc., you must set it before calls -// call to PackFontRangesGatherRects. - -STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip); -// If skip != 0, this tells stb_truetype to skip any codepoints for which -// there is no corresponding glyph. If skip=0, which is the default, then -// codepoints without a glyph recived the font's "missing character" glyph, -// typically an empty box by convention. - -STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, // same data as above - int char_index, // character to display - float *xpos, float *ypos, // pointers to current position in screen pixel space - stbtt_aligned_quad *q, // output: quad to draw - int align_to_integer); - -STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); -STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects); -STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); -// Calling these functions in sequence is roughly equivalent to calling -// stbtt_PackFontRanges(). If you more control over the packing of multiple -// fonts, or if you want to pack custom data into a font texture, take a look -// at the source to of stbtt_PackFontRanges() and create a custom version -// using these functions, e.g. call GatherRects multiple times, -// building up a single array of rects, then call PackRects once, -// then call RenderIntoRects repeatedly. This may result in a -// better packing than calling PackFontRanges multiple times -// (or it may not). - -// this is an opaque structure that you shouldn't mess with which holds -// all the context needed from PackBegin to PackEnd. -struct stbtt_pack_context { - void *user_allocator_context; - void *pack_info; - int width; - int height; - int stride_in_bytes; - int padding; - int skip_missing; - unsigned int h_oversample, v_oversample; - unsigned char *pixels; - void *nodes; -}; - -////////////////////////////////////////////////////////////////////////////// -// -// FONT LOADING -// -// - -STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data); -// This function will determine the number of fonts in a font file. TrueType -// collection (.ttc) files may contain multiple fonts, while TrueType font -// (.ttf) files only contain one font. The number of fonts can be used for -// indexing with the previous function where the index is between zero and one -// less than the total fonts. If an error occurs, -1 is returned. - -STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index); -// Each .ttf/.ttc file may have more than one font. Each font has a sequential -// index number starting from 0. Call this function to get the font offset for -// a given index; it returns -1 if the index is out of range. A regular .ttf -// file will only define one font and it always be at offset 0, so it will -// return '0' for index 0, and -1 for all other indices. - -// The following structure is defined publicly so you can declare one on -// the stack or as a global or etc, but you should treat it as opaque. -struct stbtt_fontinfo -{ - void * userdata; - unsigned char * data; // pointer to .ttf file - int fontstart; // offset of start of font - - int numGlyphs; // number of glyphs, needed for range checking - - int loca,head,glyf,hhea,hmtx,kern,gpos,svg; // table locations as offset from start of .ttf - int index_map; // a cmap mapping for our chosen character encoding - int indexToLocFormat; // format needed to map from glyph index to glyph - - stbtt__buf cff; // cff font data - stbtt__buf charstrings; // the charstring index - stbtt__buf gsubrs; // global charstring subroutines index - stbtt__buf subrs; // private charstring subroutines index - stbtt__buf fontdicts; // array of font dicts - stbtt__buf fdselect; // map from glyph to fontdict -}; - -STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset); -// Given an offset into the file that defines a font, this function builds -// the necessary cached info for the rest of the system. You must allocate -// the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't -// need to do anything special to free it, because the contents are pure -// value data with no additional data structures. Returns 0 on failure. - - -////////////////////////////////////////////////////////////////////////////// -// -// CHARACTER TO GLYPH-INDEX CONVERSIOn - -STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint); -// If you're going to perform multiple operations on the same character -// and you want a speed-up, call this function with the character you're -// going to process, then use glyph-based functions instead of the -// codepoint-based functions. -// Returns 0 if the character codepoint is not defined in the font. - - -////////////////////////////////////////////////////////////////////////////// -// -// CHARACTER PROPERTIES -// - -STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels); -// computes a scale factor to produce a font whose "height" is 'pixels' tall. -// Height is measured as the distance from the highest ascender to the lowest -// descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics -// and computing: -// scale = pixels / (ascent - descent) -// so if you prefer to measure height by the ascent only, use a similar calculation. - -STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels); -// computes a scale factor to produce a font whose EM size is mapped to -// 'pixels' tall. This is probably what traditional APIs compute, but -// I'm not positive. - -STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap); -// ascent is the coordinate above the baseline the font extends; descent -// is the coordinate below the baseline the font extends (i.e. it is typically negative) -// lineGap is the spacing between one row's descent and the next row's ascent... -// so you should advance the vertical position by "*ascent - *descent + *lineGap" -// these are expressed in unscaled coordinates, so you must multiply by -// the scale factor for a given size - -STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap); -// analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2 -// table (specific to MS/Windows TTF files). -// -// Returns 1 on success (table present), 0 on failure. - -STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1); -// the bounding box around all possible characters - -STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing); -// leftSideBearing is the offset from the current horizontal position to the left edge of the character -// advanceWidth is the offset from the current horizontal position to the next horizontal position -// these are expressed in unscaled coordinates - -STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2); -// an additional amount to add to the 'advance' value between ch1 and ch2 - -STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1); -// Gets the bounding box of the visible part of the glyph, in unscaled coordinates - -STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing); -STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2); -STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); -// as above, but takes one or more glyph indices for greater efficiency - -typedef struct stbtt_kerningentry -{ - int glyph1; // use stbtt_FindGlyphIndex - int glyph2; - int advance; -} stbtt_kerningentry; - -STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info); -STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length); -// Retrieves a complete list of all of the kerning pairs provided by the font -// stbtt_GetKerningTable never writes more than table_length entries and returns how many entries it did write. -// The table will be sorted by (a.glyph1 == b.glyph1)?(a.glyph2 < b.glyph2):(a.glyph1 < b.glyph1) - -////////////////////////////////////////////////////////////////////////////// -// -// GLYPH SHAPES (you probably don't need these, but they have to go before -// the bitmaps for C declaration-order reasons) -// - -#ifndef STBTT_vmove // you can predefine these to use different values (but why?) - enum { - STBTT_vmove=1, - STBTT_vline, - STBTT_vcurve, - STBTT_vcubic - }; -#endif - -#ifndef stbtt_vertex // you can predefine this to use different values - // (we share this with other code at RAD) - #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file - typedef struct - { - stbtt_vertex_type x,y,cx,cy,cx1,cy1; - unsigned char type,padding; - } stbtt_vertex; -#endif - -STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index); -// returns non-zero if nothing is drawn for this glyph - -STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices); -STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices); -// returns # of vertices and fills *vertices with the pointer to them -// these are expressed in "unscaled" coordinates -// -// The shape is a series of contours. Each one starts with -// a STBTT_moveto, then consists of a series of mixed -// STBTT_lineto and STBTT_curveto segments. A lineto -// draws a line from previous endpoint to its x,y; a curveto -// draws a quadratic bezier from previous endpoint to -// its x,y, using cx,cy as the bezier control point. - -STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices); -// frees the data allocated above - -STBTT_DEF unsigned char *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl); -STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg); -STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg); -// fills svg with the character's SVG data. -// returns data size or 0 if SVG not found. - -////////////////////////////////////////////////////////////////////////////// -// -// BITMAP RENDERING -// - -STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata); -// frees the bitmap allocated below - -STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff); -// allocates a large-enough single-channel 8bpp bitmap and renders the -// specified character/glyph at the specified scale into it, with -// antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque). -// *width & *height are filled out with the width & height of the bitmap, -// which is stored left-to-right, top-to-bottom. -// -// xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap - -STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff); -// the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel -// shift for the character - -STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint); -// the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap -// in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap -// is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the -// width and height and positioning info for it first. - -STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint); -// same as stbtt_MakeCodepointBitmap, but you can specify a subpixel -// shift for the character - -STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint); -// same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering -// is performed (see stbtt_PackSetOversampling) - -STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); -// get the bbox of the bitmap centered around the glyph origin; so the -// bitmap width is ix1-ix0, height is iy1-iy0, and location to place -// the bitmap top left is (leftSideBearing*scale,iy0). -// (Note that the bitmap uses y-increases-down, but the shape uses -// y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.) - -STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); -// same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel -// shift for the character - -// the following functions are equivalent to the above functions, but operate -// on glyph indices instead of Unicode codepoints (for efficiency) -STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff); -STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff); -STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph); -STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph); -STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int glyph); -STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); -STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); - - -// @TODO: don't expose this structure -typedef struct -{ - int w,h,stride; - unsigned char *pixels; -} stbtt__bitmap; - -// rasterize a shape with quadratic beziers into a bitmap -STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into - float flatness_in_pixels, // allowable error of curve in pixels - stbtt_vertex *vertices, // array of vertices defining shape - int num_verts, // number of vertices in above array - float scale_x, float scale_y, // scale applied to input vertices - float shift_x, float shift_y, // translation applied to input vertices - int x_off, int y_off, // another translation applied to input - int invert, // if non-zero, vertically flip shape - void *userdata); // context for to STBTT_MALLOC - -////////////////////////////////////////////////////////////////////////////// -// -// Signed Distance Function (or Field) rendering - -STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata); -// frees the SDF bitmap allocated below - -STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); -STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); -// These functions compute a discretized SDF field for a single character, suitable for storing -// in a single-channel texture, sampling with bilinear filtering, and testing against -// larger than some threshold to produce scalable fonts. -// info -- the font -// scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap -// glyph/codepoint -- the character to generate the SDF for -// padding -- extra "pixels" around the character which are filled with the distance to the character (not 0), -// which allows effects like bit outlines -// onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character) -// pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale) -// if positive, > onedge_value is inside; if negative, < onedge_value is inside -// width,height -- output height & width of the SDF bitmap (including padding) -// xoff,yoff -- output origin of the character -// return value -- a 2D array of bytes 0..255, width*height in size -// -// pixel_dist_scale & onedge_value are a scale & bias that allows you to make -// optimal use of the limited 0..255 for your application, trading off precision -// and special effects. SDF values outside the range 0..255 are clamped to 0..255. -// -// Example: -// scale = stbtt_ScaleForPixelHeight(22) -// padding = 5 -// onedge_value = 180 -// pixel_dist_scale = 180/5.0 = 36.0 -// -// This will create an SDF bitmap in which the character is about 22 pixels -// high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled -// shape, sample the SDF at each pixel and fill the pixel if the SDF value -// is greater than or equal to 180/255. (You'll actually want to antialias, -// which is beyond the scope of this example.) Additionally, you can compute -// offset outlines (e.g. to stroke the character border inside & outside, -// or only outside). For example, to fill outside the character up to 3 SDF -// pixels, you would compare against (180-36.0*3)/255 = 72/255. The above -// choice of variables maps a range from 5 pixels outside the shape to -// 2 pixels inside the shape to 0..255; this is intended primarily for apply -// outside effects only (the interior range is needed to allow proper -// antialiasing of the font at *smaller* sizes) -// -// The function computes the SDF analytically at each SDF pixel, not by e.g. -// building a higher-res bitmap and approximating it. In theory the quality -// should be as high as possible for an SDF of this size & representation, but -// unclear if this is true in practice (perhaps building a higher-res bitmap -// and computing from that can allow drop-out prevention). -// -// The algorithm has not been optimized at all, so expect it to be slow -// if computing lots of characters or very large sizes. - - - -////////////////////////////////////////////////////////////////////////////// -// -// Finding the right font... -// -// You should really just solve this offline, keep your own tables -// of what font is what, and don't try to get it out of the .ttf file. -// That's because getting it out of the .ttf file is really hard, because -// the names in the file can appear in many possible encodings, in many -// possible languages, and e.g. if you need a case-insensitive comparison, -// the details of that depend on the encoding & language in a complex way -// (actually underspecified in truetype, but also gigantic). -// -// But you can use the provided functions in two possible ways: -// stbtt_FindMatchingFont() will use *case-sensitive* comparisons on -// unicode-encoded names to try to find the font you want; -// you can run this before calling stbtt_InitFont() -// -// stbtt_GetFontNameString() lets you get any of the various strings -// from the file yourself and do your own comparisons on them. -// You have to have called stbtt_InitFont() first. - - -STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags); -// returns the offset (not index) of the font that matches, or -1 if none -// if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold". -// if you use any other flag, use a font name like "Arial"; this checks -// the 'macStyle' header field; i don't know if fonts set this consistently -#define STBTT_MACSTYLE_DONTCARE 0 -#define STBTT_MACSTYLE_BOLD 1 -#define STBTT_MACSTYLE_ITALIC 2 -#define STBTT_MACSTYLE_UNDERSCORE 4 -#define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0 - -STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2); -// returns 1/0 whether the first string interpreted as utf8 is identical to -// the second string interpreted as big-endian utf16... useful for strings from next func - -STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID); -// returns the string (which may be big-endian double byte, e.g. for unicode) -// and puts the length in bytes in *length. -// -// some of the values for the IDs are below; for more see the truetype spec: -// http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html -// http://www.microsoft.com/typography/otspec/name.htm - -enum { // platformID - STBTT_PLATFORM_ID_UNICODE =0, - STBTT_PLATFORM_ID_MAC =1, - STBTT_PLATFORM_ID_ISO =2, - STBTT_PLATFORM_ID_MICROSOFT =3 -}; - -enum { // encodingID for STBTT_PLATFORM_ID_UNICODE - STBTT_UNICODE_EID_UNICODE_1_0 =0, - STBTT_UNICODE_EID_UNICODE_1_1 =1, - STBTT_UNICODE_EID_ISO_10646 =2, - STBTT_UNICODE_EID_UNICODE_2_0_BMP=3, - STBTT_UNICODE_EID_UNICODE_2_0_FULL=4 -}; - -enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT - STBTT_MS_EID_SYMBOL =0, - STBTT_MS_EID_UNICODE_BMP =1, - STBTT_MS_EID_SHIFTJIS =2, - STBTT_MS_EID_UNICODE_FULL =10 -}; - -enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes - STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4, - STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5, - STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6, - STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7 -}; - -enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID... - // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs - STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410, - STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411, - STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412, - STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419, - STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409, - STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D -}; - -enum { // languageID for STBTT_PLATFORM_ID_MAC - STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11, - STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23, - STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32, - STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 , - STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 , - STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33, - STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19 -}; - -#ifdef __cplusplus -} -#endif - -#endif // __STB_INCLUDE_STB_TRUETYPE_H__ - -/////////////////////////////////////////////////////////////////////////////// -/////////////////////////////////////////////////////////////////////////////// -//// -//// IMPLEMENTATION -//// -//// - -#ifdef STB_TRUETYPE_IMPLEMENTATION - -#ifndef STBTT_MAX_OVERSAMPLE -#define STBTT_MAX_OVERSAMPLE 8 -#endif - -#if STBTT_MAX_OVERSAMPLE > 255 -#error "STBTT_MAX_OVERSAMPLE cannot be > 255" -#endif - -typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1]; - -#ifndef STBTT_RASTERIZER_VERSION -#define STBTT_RASTERIZER_VERSION 2 -#endif - -#ifdef _MSC_VER -#define STBTT__NOTUSED(v) (void)(v) -#else -#define STBTT__NOTUSED(v) (void)sizeof(v) -#endif - -////////////////////////////////////////////////////////////////////////// -// -// stbtt__buf helpers to parse data from file -// - -static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b) -{ - if (b->cursor >= b->size) - return 0; - return b->data[b->cursor++]; -} - -static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b) -{ - if (b->cursor >= b->size) - return 0; - return b->data[b->cursor]; -} - -static void stbtt__buf_seek(stbtt__buf *b, int o) -{ - //STBTT_assert(!(o > b->size || o < 0)); - b->cursor = (o > b->size || o < 0) ? b->size : o; -} - -static void stbtt__buf_skip(stbtt__buf *b, int o) -{ - stbtt__buf_seek(b, b->cursor + o); -} - -static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n) -{ - stbtt_uint32 v = 0; - int i; - //STBTT_assert(n >= 1 && n <= 4); - for (i = 0; i < n; i++) - v = (v << 8) | stbtt__buf_get8(b); - return v; -} - -static stbtt__buf stbtt__new_buf(const void *p, size_t size) -{ - stbtt__buf r; - //STBTT_assert(size < 0x40000000); - r.data = (stbtt_uint8*) p; - r.size = (int) size; - r.cursor = 0; - return r; -} - -#define stbtt__buf_get16(b) stbtt__buf_get((b), 2) -#define stbtt__buf_get32(b) stbtt__buf_get((b), 4) - -static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s) -{ - stbtt__buf r = stbtt__new_buf(NULL, 0); - if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r; - r.data = b->data + o; - r.size = s; - return r; -} - -static stbtt__buf stbtt__cff_get_index(stbtt__buf *b) -{ - int count, start, offsize; - start = b->cursor; - count = stbtt__buf_get16(b); - if (count) { - offsize = stbtt__buf_get8(b); - //STBTT_assert(offsize >= 1 && offsize <= 4); - stbtt__buf_skip(b, offsize * count); - stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1); - } - return stbtt__buf_range(b, start, b->cursor - start); -} - -static stbtt_uint32 stbtt__cff_int(stbtt__buf *b) -{ - int b0 = stbtt__buf_get8(b); - if (b0 >= 32 && b0 <= 246) return b0 - 139; - else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108; - else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108; - else if (b0 == 28) return stbtt__buf_get16(b); - else if (b0 == 29) return stbtt__buf_get32(b); - //STBTT_assert(0); - return 0; -} - -static void stbtt__cff_skip_operand(stbtt__buf *b) { - if (stbtt__buf_peek8(b) == 30) { - ++b->cursor; // Direct increment instead of skip - int v; - do { - v = stbtt__buf_get8(b); - } while ((v & 0xF) != 0xF && (v >> 4) != 0xF && b->cursor < b->size); - } else { - stbtt__cff_int(b); - } -} - -static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key) { - // Variables moved outside the loop for better performance - int start; - int end; - int op; - - b->cursor = 0; // Direct assignment instead of seek - - while (b->cursor < b->size) { - start = b->cursor; - - while (stbtt__buf_peek8(b) >= 28) - stbtt__cff_skip_operand(b); - - end = b->cursor; // Capture end BEFORE reading operator - op = stbtt__buf_get8(b); - if (op == 12) op = stbtt__buf_get8(b) | 0x100; - if (op == key) return stbtt__buf_range(b, start, end - start); - } - - // Return empty range - stbtt__buf empty = {b->data, 0, 0}; - return empty; -} - -static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out) { - stbtt__buf operands = stbtt__dict_get(b, key); - - // Unroll small common cases - switch (outcount) { - case 1: - if (operands.cursor < operands.size) out[0] = stbtt__cff_int(&operands); - break; - case 2: - if (operands.cursor < operands.size) out[0] = stbtt__cff_int(&operands); - if (operands.cursor < operands.size) out[1] = stbtt__cff_int(&operands); - break; - default: - for (int i = 0; i < outcount && operands.cursor < operands.size; i++) - out[i] = stbtt__cff_int(&operands); - } -} - -static int stbtt__cff_index_count(stbtt__buf *b) -{ - stbtt__buf_seek(b, 0); - return stbtt__buf_get16(b); -} - -static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i) -{ - int count, offsize, start, end; - stbtt__buf_seek(&b, 0); - count = stbtt__buf_get16(&b); - offsize = stbtt__buf_get8(&b); - //STBTT_assert(i >= 0 && i < count); - //STBTT_assert(offsize >= 1 && offsize <= 4); - stbtt__buf_skip(&b, i*offsize); - start = stbtt__buf_get(&b, offsize); - end = stbtt__buf_get(&b, offsize); - return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start); -} - -////////////////////////////////////////////////////////////////////////// -// -// accessors to parse data from file -// - -// on platforms that don't allow misaligned reads, if we want to allow -// truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE - -#define ttBYTE(p) (* (stbtt_uint8 *) (p)) -#define ttCHAR(p) (* (stbtt_int8 *) (p)) -#define ttFixed(p) ttLONG(p) - -static stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } -static stbtt_int16 ttSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } -static stbtt_uint32 ttULONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } -static stbtt_int32 ttLONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } - -#define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3)) -#define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3]) - -static int stbtt__isfont(stbtt_uint8 *font) -{ - // check the version number - if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1 - if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this! - if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF - if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0 - if (stbtt_tag(font, "true")) return 1; // Apple specification for TrueType fonts - return 0; -} - -// @OPTIMIZE: binary search -static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag) -{ - stbtt_int32 num_tables = ttUSHORT(data+fontstart+4); - stbtt_uint32 tabledir = fontstart + 12; - stbtt_int32 i; - stbtt_uint32 loc; - for (i=0; i < num_tables; ++i) { - loc = tabledir + 16*i; - if (stbtt_tag(data+loc+0, tag)) - return ttULONG(data+loc+8); - } - return 0; -} - -static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index) -{ - // if it's just a font, there's only one valid index - if (stbtt__isfont(font_collection)) - return index == 0 ? 0 : -1; - - // check if it's a TTC - if (stbtt_tag(font_collection, "ttcf")) { - // version 1? - if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { - stbtt_int32 n = ttLONG(font_collection+8); - if (index >= n) - return -1; - return ttULONG(font_collection+12+index*4); - } - } - return -1; -} - -static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection) -{ - // if it's just a font, there's only one valid font - if (stbtt__isfont(font_collection)) - return 1; - - // check if it's a TTC - if (stbtt_tag(font_collection, "ttcf")) { - // version 1? - if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { - return ttLONG(font_collection+8); - } - } - return 0; -} - -static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict) -{ - stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 }; - stbtt__buf pdict; - stbtt__dict_get_ints(&fontdict, 18, 2, private_loc); - if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0); - pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]); - stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff); - if (!subrsoff) return stbtt__new_buf(NULL, 0); - stbtt__buf_seek(&cff, private_loc[1]+subrsoff); - return stbtt__cff_get_index(&cff); -} - -// since most people won't use this, find this table the first time it's needed -static int stbtt__get_svg(stbtt_fontinfo *info) -{ - stbtt_uint32 t; - if (info->svg < 0) { - t = stbtt__find_table(info->data, info->fontstart, "SVG "); - if (t) { - stbtt_uint32 offset = ttULONG(info->data + t + 2); - info->svg = t + offset; - } else { - info->svg = 0; - } - } - return info->svg; -} - -static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart) -{ - stbtt_uint32 cmap, t; - stbtt_int32 i,numTables; - - info->data = data; - info->fontstart = fontstart; - info->cff = stbtt__new_buf(NULL, 0); - - cmap = stbtt__find_table(data, fontstart, "cmap"); // required - info->loca = stbtt__find_table(data, fontstart, "loca"); // required - info->head = stbtt__find_table(data, fontstart, "head"); // required - info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required - info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required - info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required - info->kern = stbtt__find_table(data, fontstart, "kern"); // not required - info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required - - if (!cmap || !info->head || !info->hhea || !info->hmtx) - return 0; - if (info->glyf) { - // required for truetype - if (!info->loca) return 0; - } else { - // initialization for CFF / Type2 fonts (OTF) - stbtt__buf b, topdict, topdictidx; - stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0; - stbtt_uint32 cff; - - cff = stbtt__find_table(data, fontstart, "CFF "); - if (!cff) return 0; - - info->fontdicts = stbtt__new_buf(NULL, 0); - info->fdselect = stbtt__new_buf(NULL, 0); - - // @TODO this should use size from table (not 512MB) - info->cff = stbtt__new_buf(data+cff, 512*1024*1024); - b = info->cff; - - // read the header - stbtt__buf_skip(&b, 2); - stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize - - // @TODO the name INDEX could list multiple fonts, - // but we just use the first one. - stbtt__cff_get_index(&b); // name INDEX - topdictidx = stbtt__cff_get_index(&b); - topdict = stbtt__cff_index_get(topdictidx, 0); - stbtt__cff_get_index(&b); // string INDEX - info->gsubrs = stbtt__cff_get_index(&b); - - stbtt__dict_get_ints(&topdict, 17, 1, &charstrings); - stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype); - stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff); - stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff); - info->subrs = stbtt__get_subrs(b, topdict); - - // we only support Type 2 charstrings - if (cstype != 2) return 0; - if (charstrings == 0) return 0; - - if (fdarrayoff) { - // looks like a CID font - if (!fdselectoff) return 0; - stbtt__buf_seek(&b, fdarrayoff); - info->fontdicts = stbtt__cff_get_index(&b); - info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff); - } - - stbtt__buf_seek(&b, charstrings); - info->charstrings = stbtt__cff_get_index(&b); - } - - t = stbtt__find_table(data, fontstart, "maxp"); - if (t) - info->numGlyphs = ttUSHORT(data+t+4); - else - info->numGlyphs = 0xffff; - - info->svg = -1; - - // find a cmap encoding table we understand *now* to avoid searching - // later. (todo: could make this installable) - // the same regardless of glyph. - numTables = ttUSHORT(data + cmap + 2); - info->index_map = 0; - stbtt_uint32 encoding_record; - for (i=0; i < numTables; ++i) { - encoding_record = cmap + 4 + 8 * i; - // find an encoding we understand: - switch(ttUSHORT(data+encoding_record)) { - case STBTT_PLATFORM_ID_MICROSOFT: - switch (ttUSHORT(data+encoding_record+2)) { - case STBTT_MS_EID_UNICODE_BMP: - case STBTT_MS_EID_UNICODE_FULL: - // MS/Unicode - info->index_map = cmap + ttULONG(data+encoding_record+4); - break; - } - break; - case STBTT_PLATFORM_ID_UNICODE: - // Mac/iOS has these - // all the encodingIDs are unicode, so we don't bother to check it - info->index_map = cmap + ttULONG(data+encoding_record+4); - break; - } - } - if (info->index_map == 0) - return 0; - - info->indexToLocFormat = ttUSHORT(data+info->head + 50); - return 1; -} - -// Inline helper functions for better performance - avoid function call overhead -#define FAST_USHORT(p) (((stbtt_uint16)(p)[0] << 8) | (p)[1]) -#define FAST_ULONG(p) (((stbtt_uint32)(p)[0] << 24) | ((stbtt_uint32)(p)[1] << 16) | ((stbtt_uint32)(p)[2] << 8) | (p)[3]) -#define FAST_SHORT(p) ((stbtt_int16)FAST_USHORT(p)) - -// Force inline for maximum performance -static inline int stbtt_FindGlyphIndex_impl(stbtt_uint8 *data, stbtt_uint32 index_map, int unicode_codepoint) -{ - // 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 deleted file mode 100644 index 2bcc7b72..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libtesla/include/tesla.hpp +++ /dev/null @@ -1,13881 +0,0 @@ -/******************************************************************************** - * Custom Fork Information - * - * File: tesla.hpp - * Author: ppkantorski - * Description: - * This file serves as the core logic for the Ultrahand Overlay project's custom fork - * of libtesla, an overlay executor. Within this file, you will find a collection of - * functions, menu structures, and interaction logic designed to facilitate the - * smooth execution and flexible customization of overlays within the project. - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Copyright (c) 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 - -#if !IS_LAUNCHER_DIRECTIVE -#include // unused, but preserved for projects that might need it -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -//#include // despite being commented out, it must still be being imported via other libs -#include -#include -#include -//#include - - -// Define this makro before including tesla.hpp in your main file. If you intend -// to use the tesla.hpp header in more than one source file, only define it once! -// #define TESLA_INIT_IMPL - -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-function" - -#ifdef TESLA_INIT_IMPL - #define STB_TRUETYPE_IMPLEMENTATION -#endif -#include "stb_truetype.h" - -#pragma GCC diagnostic pop - -#define ELEMENT_BOUNDS(elem) elem->getX(), elem->getY(), elem->getWidth(), elem->getHeight() - -#define ASSERT_EXIT(x) if (R_FAILED(x)) std::exit(1) -#define ASSERT_FATAL(x) if (Result res = x; R_FAILED(res)) fatalThrow(res) - -#define PACKED __attribute__((packed)) -#define ALWAYS_INLINE inline __attribute__((always_inline)) - -/// Evaluates an expression that returns a result, and returns the result if it would fail. -#define TSL_R_TRY(resultExpr) \ - ({ \ - const auto result = resultExpr; \ - if (R_FAILED(result)) { \ - return result; \ - } \ - }) - -using namespace std::literals::string_literals; -using namespace std::literals::chrono_literals; // potentially unused, restored for softare compatibility - -#if IS_STATUS_MONITOR_DIRECTIVE -//struct GlyphInfo { -// u8* pointer; -// int width; -// int height; -//}; - -struct KeyPairHash { - std::size_t operator()(const std::pair& key) const { - // Combine hashes of both components - union returnValue { - char c[8]; - std::size_t s; - } value; - memcpy(&value.c[0], &key.first, 4); - memcpy(&value.c[4], &key.second, 4); - return value.s; - } -}; - -// Custom equality comparison for int-float pairs -struct KeyPairEqual { - bool operator()(const std::pair& lhs, const std::pair& rhs) const { - //static constexpr float epsilon = 0.00001f; - return lhs.first == rhs.first && - std::abs(lhs.second - rhs.second) < 0.00001f; - } -}; - -//std::unordered_map, GlyphInfo, KeyPairHash, KeyPairEqual> cache; - -u8 TeslaFPS = 60; -//u8 alphabackground = 0xD; -volatile bool triggerExitNow = false; -volatile bool isRendering = false; -volatile bool delayUpdate = false; -volatile bool pendingExit = false; -volatile bool wasRendering = false; - -LEvent renderingStopEvent; -bool FullMode = true; -bool deactivateOriginalFooter = false; -//bool fontCache = true; -bool disableJumpTo = false; - -// Check for mini/micro mode flags -//bool isMiniOrMicroMode = false; -inline std::string lastMode; -inline std::set overlayModes = {"full", "mini", "micro", "fps_graph", "fps_counter", "game_resolutions"}; - -bool isValidOverlayMode() { - return overlayModes.count(lastMode) > 0; -} - -#endif - -#if USING_FPS_INDICATOR_DIRECTIVE -float fps = 0.0; -int frameCount = 0; -double elapsedTime; -#endif - - -// Custom variables -//static bool jumpToListItem = false; -inline std::atomic jumpToTop{false}; -inline std::atomic jumpToBottom{false}; -inline std::atomic skipUp{false}; -inline std::atomic skipDown{false}; -inline u32 offsetWidthVar = 112; -inline std::string g_overlayFilename;; -inline std::string lastOverlayFilename; -inline std::string lastOverlayMode; - -inline std::mutex jumpItemMutex; -inline std::string jumpItemName; -inline std::string jumpItemValue; -inline std::atomic jumpItemExactMatch{true}; - -inline std::atomic s_onLeftPage{false}; -inline std::atomic s_onRightPage{false}; -inline std::atomic screenshotsAreDisabled{false}; -inline std::atomic screenshotsAreForceDisabled{false}; - -//#if IS_LAUNCHER_DIRECTIVE -inline bool hideHidden = false; -//#endif - -//inline std::atomic isLaunchingNextOverlay{false}; -inline std::atomic mainComboHasTriggered{false}; -inline std::atomic launchComboHasTriggered{false}; - - - -// Sound triggering variables -inline std::atomic triggerNavigationSound{false}; -inline std::atomic triggerEnterSound{false}; -inline std::atomic triggerExitSound{false}; -inline std::atomic triggerWallSound{false}; -inline std::atomic triggerOnSound{false}; -inline std::atomic triggerOffSound{false}; -inline std::atomic triggerSettingsSound{false}; -inline std::atomic triggerMoveSound{false}; -inline std::atomic disableSound{false}; -//inline std::atomic clearSoundCacheNow{false}; -inline std::atomic reloadSoundCacheNow{false}; - -// Haptic triggering variables -inline std::atomic triggerRumbleClick{false}; -inline std::atomic triggerRumbleDoubleClick{false}; - - -static inline void triggerNavigationFeedback() { - triggerRumbleClick.store(true, std::memory_order_release); - triggerNavigationSound.store(true, std::memory_order_release); -} - -static inline void triggerEnterFeedback() { - triggerRumbleClick.store(true, std::memory_order_release); - triggerEnterSound.store(true, std::memory_order_release); -} - -static inline void triggerExitFeedback() { - triggerRumbleDoubleClick.store(true, std::memory_order_release); - triggerExitSound.store(true, std::memory_order_release); -} - - -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 notificationTextColor = RGB888(ult::whiteColor); - static Color headerTextColor = RGB888(ult::whiteColor); - static Color headerSeparatorColor = RGB888(ult::whiteColor); - static Color starColor = RGB888(ult::whiteColor); - static Color selectionStarColor = RGB888(ult::whiteColor); - static Color buttonColor = RGB888(ult::whiteColor); - static Color bottomTextColor = RGB888(ult::whiteColor); - static Color bottomSeparatorColor = RGB888(ult::whiteColor); - static Color topSeparatorColor = RGB888("404040"); - - static Color defaultOverlayColor = RGB888(ult::whiteColor); - static Color defaultPackageColor = RGB888(ult::whiteColor);//RGB888("#00FF00"); - static Color defaultScriptColor = RGB888("FF33FF"); - static Color clockColor = RGB888(ult::whiteColor); - static Color temperatureColor = RGB888(ult::whiteColor); - static Color batteryColor = RGB888("ffff45"); - static Color batteryChargingColor = RGB888("00FF00"); - static Color batteryLowColor = RGB888("FF0000"); - static size_t widgetBackdropAlpha = 15; - static Color widgetBackdropColor = RGB888(ult::blackColor, widgetBackdropAlpha); - - static Color overlayTextColor = RGB888(ult::whiteColor); - static Color ultOverlayTextColor = RGB888("9ed0ff"); - static Color packageTextColor = RGB888(ult::whiteColor); - static Color ultPackageTextColor = RGB888("9ed0ff"); - - static Color bannerVersionTextColor = RGB888(ult::greyColor); - static Color overlayVersionTextColor = RGB888(ult::greyColor); - static Color ultOverlayVersionTextColor = RGB888("00FFDD"); - static Color packageVersionTextColor = RGB888(ult::greyColor); - static Color ultPackageVersionTextColor = RGB888("00FFDD"); - static Color onTextColor = RGB888("00FFDD"); - static Color offTextColor = RGB888(ult::greyColor); - - #if IS_LAUNCHER_DIRECTIVE - static Color dynamicLogoRGB1 = RGB888("00E669"); - static Color dynamicLogoRGB2 = RGB888("8080EA"); - #endif - - //static bool disableSelectionBG = false; - //static bool disableSelectionValueColor = false; - static bool invertBGClickColor = false; - - static size_t selectionBGAlpha = 11; - static Color selectionBGColor = RGB888(ult::blackColor, selectionBGAlpha); - - static Color highlightColor1 = RGB888("2288CC"); - static Color highlightColor2 = RGB888("88FFFF"); - static Color highlightColor3 = RGB888("FFFF45"); - static Color highlightColor4 = RGB888("F7253E"); - - static Color highlightColor = tsl::style::color::ColorHighlight; - - static size_t clickAlpha = 7; - static Color clickColor = RGB888("3E25F7", clickAlpha); - - static size_t progressAlpha = 7; - static Color progressColor = RGB888("253EF7", progressAlpha); - - static Color 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() { - auto themeData = ult::getParsedDataFromIniFile(ult::THEME_CONFIG_INI_PATH); - if (themeData.count(ult::THEME_STR) == 0) return; - - auto& themeSection = themeData[ult::THEME_STR]; - - auto getValue = [&](const char* key) -> const std::string& { - auto it = themeSection.find(key); - return it != themeSection.end() ? it->second : ult::defaultThemeSettingsMap[key]; - }; - - auto getColor = [&](const char* key, size_t alpha = 15) { - return RGB888(getValue(key), alpha); - }; - - auto getAlpha = [&](const char* key) { - const auto& alphaStr = getValue(key); - return ult::stoi(alphaStr); - }; - - #if IS_LAUNCHER_DIRECTIVE - logoColor1 = getColor("logo_color_1"); - logoColor2 = getColor("logo_color_2"); - dynamicLogoRGB1 = getColor("dynamic_logo_color_1"); - dynamicLogoRGB2 = getColor("dynamic_logo_color_2"); - #endif - - defaultBackgroundAlpha = getAlpha("bg_alpha"); - defaultBackgroundColor = getColor("bg_color", defaultBackgroundAlpha); - defaultTextColor = getColor("text_color"); - notificationTextColor = getColor("notification_text_color"); - headerTextColor = getColor("header_text_color"); - headerSeparatorColor = getColor("header_separator_color"); - starColor = getColor("star_color"); - selectionStarColor = getColor("selection_star_color"); - buttonColor = getColor("bottom_button_color"); - bottomTextColor = getColor("bottom_text_color"); - bottomSeparatorColor = getColor("bottom_separator_color"); - topSeparatorColor = getColor("top_separator_color"); - defaultOverlayColor = getColor("default_overlay_color"); - defaultPackageColor = getColor("default_package_color"); - defaultScriptColor = getColor("default_script_color"); - clockColor = getColor("clock_color"); - temperatureColor = getColor("temperature_color"); - batteryColor = getColor("battery_color"); - batteryChargingColor = getColor("battery_charging_color"); - batteryLowColor = getColor("battery_low_color"); - widgetBackdropAlpha = getAlpha("widget_backdrop_alpha"); - widgetBackdropColor = getColor("widget_backdrop_color", widgetBackdropAlpha); - overlayTextColor = getColor("overlay_text_color"); - ultOverlayTextColor = getColor("ult_overlay_text_color"); - packageTextColor = getColor("package_text_color"); - ultPackageTextColor = getColor("ult_package_text_color"); - bannerVersionTextColor = getColor("banner_version_text_color"); - overlayVersionTextColor = getColor("overlay_version_text_color"); - ultOverlayVersionTextColor = getColor("ult_overlay_version_text_color"); - packageVersionTextColor = getColor("package_version_text_color"); - ultPackageVersionTextColor = getColor("ult_package_version_text_color"); - onTextColor = getColor("on_text_color"); - offTextColor = getColor("off_text_color"); - invertBGClickColor = (getValue("invert_bg_click_color") == ult::TRUE_STR); - selectionBGAlpha = getAlpha("selection_bg_alpha"); - selectionBGColor = getColor("selection_bg_color", selectionBGAlpha); - highlightColor1 = getColor("highlight_color_1"); - highlightColor2 = getColor("highlight_color_2"); - highlightColor3 = getColor("highlight_color_3"); - highlightColor4 = getColor("highlight_color_4"); - clickAlpha = getAlpha("click_alpha"); - clickColor = getColor("click_color", clickAlpha); - progressAlpha = getAlpha("progress_alpha"); - progressColor = getColor("progress_color", progressAlpha); - 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::useSoundEffects = getBoolValue("sound_effects", false); - ult::useHapticFeedback = getBoolValue("haptic_feedback", false); - - ult::useSwipeToOpen = getBoolValue("swipe_to_open", true); // TRUE_STR default - ult::useOpaqueScreenshots = getBoolValue("opaque_screenshots", true); // TRUE_STR default - - ultrahandSection.clear(); - - const std::string langFile = ult::LANG_PATH+defaultLang+".json"; - if (ult::isFileOrDirectory(langFile)) - ult::parseLanguage(langFile); - } - #endif - - - // Declarations - - /** - * @brief Direction in which focus moved before landing on - * the currently focused element - */ - enum class FocusDirection { - None, ///< Focus was placed on the element programatically without user input - Up, ///< Focus moved upwards - Down, ///< Focus moved downwards - Left, ///< Focus moved from left to rigth - Right ///< Focus moved from right to left - }; - - /** - * @brief Current input controll mode - * - */ - enum class InputMode { - Controller, ///< Input from controller - Touch, ///< Touch input - TouchScroll ///< Moving/scrolling touch input - }; - - class Overlay; - namespace elm { class Element; } - - namespace impl { - - /** - * @brief Overlay launch parameters - */ - enum class LaunchFlags : u8 { - None = 0, ///< Do nothing special at launch - CloseOnExit = BIT(0) ///< Close the overlay the last Gui gets poped from the stack - }; - - static constexpr LaunchFlags operator|(LaunchFlags lhs, LaunchFlags rhs) { - return static_cast(u8(lhs) | u8(rhs)); - } - - - - } - - static void goBack(u32 count = 1); - - static void pop(u32 count = 1); - - static void setNextOverlay(const std::string& ovlPath, std::string args = ""); - - template - int loop(int argc, char** argv); - - // Helpers - - namespace hlp { - - /** - * @brief Wrapper for service initialization - * - * @param f wrapped function - */ - template - static inline void doWithSmSession(F f) { - smInitialize(); - f(); - smExit(); - } - - /** - * @brief Wrapper for sd card access using stdio - * @note Consider using raw fs calls instead as they are faster and need less space - * - * @param f wrapped function - */ - template - static inline void doWithSDCardHandle(F f) { - fsdevMountSdmc(); - f(); - fsdevUnmountDevice("sdmc"); - } - - /** - * @brief Guard that will execute a passed function at the end of the current scope - * - * @param f wrapped function - */ - template - class ScopeGuard { - ScopeGuard(const ScopeGuard&) = delete; - ScopeGuard& operator=(const ScopeGuard&) = delete; - private: - F f; - bool canceled = false; - public: - ALWAYS_INLINE ScopeGuard(F f) : f(std::move(f)) { } - ALWAYS_INLINE ~ScopeGuard() { if (!canceled) { f(); } } - void dismiss() { canceled = true; } - }; - - /** - * @brief libnx hid:sys shim that gives or takes away frocus to or from the process with the given aruid - * - * @param enable Give focus or take focus - * @param aruid Aruid of the process to focus/unfocus - * @return Result Result - */ - static Result hidsysEnableAppletToGetInput(bool enable, u64 aruid) { - const struct { - u8 permitInput; - u64 appletResourceUserId; - } in = { enable != 0, aruid }; - - return serviceDispatchIn(hidsysGetServiceSession(), 503, in); - } - - static Result viAddToLayerStack(ViLayer *layer, ViLayerStack stack) { - const struct { - u32 stack; - u64 layerId; - } in = { stack, layer->layer_id }; - - return serviceDispatchIn(viGetSession_IManagerDisplayService(), 6000, in); - } - - /** - * @brief Remove layer from layer stack - */ - static Result viRemoveFromLayerStack(ViLayer *layer, ViLayerStack stack) { - const struct { - u32 stack; - u64 layerId; - } in = { stack, layer->layer_id }; - - // Service command 6001 is commonly used for remove operations - // If this doesn't work, try 6002, 6010, or other nearby values - return serviceDispatchIn(viGetSession_IManagerDisplayService(), 6001, in); - } - - /** - * @brief Toggles focus between the Tesla overlay and the rest of the system - * - * @param enabled Focus Tesla? - */ - static void requestForeground(bool enabled, bool updateGlobalFlag = true) { - if (updateGlobalFlag) - ult::currentForeground.store(enabled, std::memory_order_release); - - u64 applicationAruid = 0, appletAruid = 0; - - for (u64 programId = 0x0100000000001000UL; programId < 0x0100000000001020UL; programId++) { - pmdmntGetProcessId(&appletAruid, programId); - - if (appletAruid != 0) - hidsysEnableAppletToGetInput(!enabled, appletAruid); - } - - - pmdmntGetApplicationProcessId(&applicationAruid); - hidsysEnableAppletToGetInput(!enabled, applicationAruid); - - hidsysEnableAppletToGetInput(true, 0); - } - - - - namespace ini { - - /** - * @brief Ini file type - */ - using IniData = std::map>; - - /** - * @brief Parses a ini string - * - * @param str String to parse - * @return Parsed data - * // Modified to be "const std" instead of just "std" - */ - static IniData parseIni(const std::string &str) { - //IniData iniData; - // - //auto lines = split(str, '\n'); - // - //std::string lastHeader = ""; - //for (auto& line : lines) { - // line.erase(std::remove_if(line.begin(), line.end(), ::isspace), line.end()); - // - // if (line[0] == '[' && line[line.size() - 1] == ']') { - // lastHeader = line.substr(1, line.size() - 2); - // iniData.emplace(lastHeader, std::map{}); - // } - // else if (auto keyValuePair = split(line, '='); keyValuePair.size() == 2) { - // iniData[lastHeader].emplace(keyValuePair[0], keyValuePair[1]); - // } - //} - - return ult::parseIni(str); - } - - /** - * @brief Unparses ini data into a string - * - * @param iniData Ini data - * @return Ini string - */ - static std::string unparseIni(const IniData &iniData) { - std::string result; - bool addSectionGap = false; - - for (const auto §ion : iniData) { - if (addSectionGap) { - result += '\n'; - } - result += '[' + section.first + "]\n"; - for (const auto &keyValue : section.second) { - result += keyValue.first + '=' + keyValue.second + '\n'; - } - addSectionGap = true; - } - - return result; - } - - - /** - * @brief Read Tesla settings file - * - * @return Settings data - */ - static IniData readOverlaySettings(auto& CONFIG_FILE) { - /* Open Sd card filesystem. */ - FsFileSystem fsSdmc; - if (R_FAILED(fsOpenSdCardFileSystem(&fsSdmc))) - return {}; - hlp::ScopeGuard fsGuard([&] { fsFsClose(&fsSdmc); }); - - /* Open config file. */ - FsFile fileConfig; - if (R_FAILED(fsFsOpenFile(&fsSdmc, CONFIG_FILE, FsOpenMode_Read, &fileConfig))) - return {}; - hlp::ScopeGuard fileGuard([&] { fsFileClose(&fileConfig); }); - - /* Get config file size. */ - s64 configFileSize; - if (R_FAILED(fsFileGetSize(&fileConfig, &configFileSize))) - return {}; - - /* Read and parse config file. */ - std::string configFileData(configFileSize, '\0'); - u64 readSize; - Result rc = fsFileRead(&fileConfig, 0, configFileData.data(), configFileSize, FsReadOption_None, &readSize); - if (R_FAILED(rc) || readSize != static_cast(configFileSize)) - return {}; - - return ult::parseIni(configFileData); - } - - /** - * @brief Replace Tesla settings file with new data - * - * @param iniData new data - */ - static void writeOverlaySettings(IniData const &iniData, auto& CONFIG_FILE) { - /* Open Sd card filesystem. */ - FsFileSystem fsSdmc; - if (R_FAILED(fsOpenSdCardFileSystem(&fsSdmc))) - return; - hlp::ScopeGuard fsGuard([&] { fsFsClose(&fsSdmc); }); - - /* Open config file. */ - FsFile fileConfig; - if (R_FAILED(fsFsOpenFile(&fsSdmc, CONFIG_FILE, FsOpenMode_Write, &fileConfig))) - return; - hlp::ScopeGuard fileGuard([&] { fsFileClose(&fileConfig); }); - - const std::string iniString = unparseIni(iniData); - - fsFileWrite(&fileConfig, 0, iniString.c_str(), iniString.length(), FsWriteOption_Flush); - } - - /** - * @brief Merge and save changes into Tesla settings file - * - * @param changes setting values to add or update - */ - static void updateOverlaySettings(IniData const &changes, auto& CONFIG_FILE) { - hlp::ini::IniData iniData = hlp::ini::readOverlaySettings(CONFIG_FILE); - for (auto §ion : changes) { - for (auto &keyValue : section.second) { - iniData[section.first][keyValue.first] = keyValue.second; - } - } - writeOverlaySettings(iniData, CONFIG_FILE); - } - - } - - /** - * @brief Decodes a key string into it's key code - * - * @param value Key string - * @return Key code - */ - static u64 stringToKeyCode(const std::string& value) { - for (const auto& keyInfo : ult::KEYS_INFO) { - if (strcasecmp(value.c_str(), keyInfo.name) == 0) - return keyInfo.key; - } - return 0; - } - - - /** - * @brief Decodes a combo string into key codes - * - * @param value Combo string - * @return Key codes - */ - static u64 comboStringToKeys(const std::string &value) { - u64 keyCombo = 0x00; - for (std::string key : ult::split(ult::removeWhiteSpaces(value), '+')) { // CUSTOM MODIFICATION (bug fix) - keyCombo |= hlp::stringToKeyCode(key); - } - return keyCombo; - } - - /** - * @brief Encodes key codes into a combo string - * - * @param keys Key codes - * @return Combo string - */ - static std::string keysToComboString(u64 keys) { - if (keys == 0) return ""; // Early return for empty input - - std::string result; - bool first = true; - - for (const auto &keyInfo : ult::KEYS_INFO) { - if (keys & keyInfo.key) { - if (!first) { - result += "+"; - } - result += keyInfo.name; - first = false; - } - } - - return result; - } - - inline static std::mutex comboMutex; - - // Function to load key combo mappings from both overlays.ini and packages.ini - static void loadEntryKeyCombos() { - std::lock_guard lock(comboMutex); - ult::g_entryCombos.clear(); - - // Load overlay combos from overlays.ini - auto overlayData = ult::getParsedDataFromIniFile(ult::OVERLAYS_INI_FILEPATH); - std::string fullPath; - u64 keys; - - std::vector modeList, comboList; - for (auto& [fileName, settings] : overlayData) { - fullPath = ult::OVERLAY_PATH + fileName; - - // 1) main key_combo - if (auto it = settings.find(ult::KEY_COMBO_STR); it != settings.end() && !it->second.empty()) { - keys = hlp::comboStringToKeys(it->second); - if (keys) ult::g_entryCombos[keys] = { fullPath, "" }; - } - - // 2) per-mode combos - auto modesIt = settings.find("mode_args"); - auto argsIt = settings.find("mode_combos"); - if (modesIt != settings.end()) { - modeList = ult::splitIniList(modesIt->second); - comboList = (argsIt != settings.end()) - ? ult::splitIniList(argsIt->second) - : std::vector(); - if (comboList.size() < modeList.size()) - comboList.resize(modeList.size()); - - for (size_t i = 0; i < modeList.size(); ++i) { - const std::string& comboStr = comboList[i]; - if (comboStr.empty()) continue; - keys = hlp::comboStringToKeys(comboStr); - if (!keys) continue; - // launchArg is the *mode* (i.e. modeList[i]) - ult::g_entryCombos[keys] = { fullPath, modeList[i] }; - } - } - } - - // Load package combos from packages.ini - auto packageData = ult::getParsedDataFromIniFile(ult::PACKAGES_INI_FILEPATH); - for (auto& [packageName, settings] : packageData) { - // Only handle main key_combo for packages (no modes for packages) - if (auto it = settings.find(ult::KEY_COMBO_STR); it != settings.end() && !it->second.empty()) { - keys = hlp::comboStringToKeys(it->second); - //std::string tmpPackageName = packageName; - //ult::removeQuotes(packageName); - if (keys) ult::g_entryCombos[keys] = { ult::OVERLAY_PATH + "ovlmenu.ovl", "--package " + packageName}; - } - } - } - - // Function to check if a key combination matches any overlay key combo - static OverlayCombo getEntryForKeyCombo(u64 keys) { - std::lock_guard lock(comboMutex); - if (auto it = ult::g_entryCombos.find(keys); it != ult::g_entryCombos.end()) - return it->second; - return { "", "" }; - } - - } - - - - // Renderer - - namespace gfx { - - extern "C" u64 __nx_vi_layer_id; - - - struct ScissoringConfig { - u32 x, y, w, h, x_max, y_max; - }; - - - // Forward declarations - class Renderer; - - - #ifdef UI_OVERRIDE_PATH - inline static std::shared_mutex s_translationCacheMutex; - #endif - class FontManager { - public: - struct Glyph { - stbtt_fontinfo *currFont; - float currFontSize; - int bounds[4]; - int xAdvance; - u8 *glyphBmp; - int width, height; - - // Add destructor to ensure cleanup - ~Glyph() { - if (glyphBmp) { - stbtt_FreeBitmap(glyphBmp, nullptr); - glyphBmp = nullptr; - } - } - - // Prevent copying to avoid double-free - Glyph(const Glyph&) = delete; - Glyph& operator=(const Glyph&) = delete; - - // Allow moving - Glyph(Glyph&& other) noexcept - : currFont(other.currFont), currFontSize(other.currFontSize) - , xAdvance(other.xAdvance), glyphBmp(other.glyphBmp) - , width(other.width), height(other.height) { - memcpy(bounds, other.bounds, sizeof(bounds)); - other.glyphBmp = nullptr; // Prevent double-free - } - - Glyph& operator=(Glyph&& other) noexcept { - if (this != &other) { - if (glyphBmp) { - stbtt_FreeBitmap(glyphBmp, nullptr); - } - currFont = other.currFont; - currFontSize = other.currFontSize; - xAdvance = other.xAdvance; - glyphBmp = other.glyphBmp; - width = other.width; - height = other.height; - memcpy(bounds, other.bounds, sizeof(bounds)); - other.glyphBmp = nullptr; - } - return *this; - } - - Glyph() : currFont(nullptr), currFontSize(0.0f), xAdvance(0), - glyphBmp(nullptr), width(0), height(0) { - std::memset(bounds, 0, sizeof(bounds)); - } - }; - - struct FontMetrics { - int ascent, descent, lineGap; - int lineHeight; // ascent - descent + lineGap - stbtt_fontinfo* font; - float fontSize; - - FontMetrics() : ascent(0), descent(0), lineGap(0), lineHeight(0), font(nullptr), fontSize(0.0f) {} - - FontMetrics(stbtt_fontinfo* f, float size) : font(f), fontSize(size) { - if (font) { - stbtt_GetFontVMetrics(font, &ascent, &descent, &lineGap); - const float scale = stbtt_ScaleForPixelHeight(font, fontSize); - ascent = static_cast(ascent * scale); - descent = static_cast(descent * scale); - lineGap = static_cast(lineGap * scale); - lineHeight = ascent - descent + lineGap; - } else { - ascent = descent = lineGap = lineHeight = 0; - } - } - }; - - enum class CacheType { - Regular, - Notification, - Persistent - }; - - private: - inline static std::shared_mutex s_cacheMutex; - inline static std::mutex s_initMutex; - - // Existing caches - inline static std::unordered_map> s_sharedGlyphCache; - //inline static std::unordered_map> s_persistentGlyphCache; - - // NEW: Notification-specific cache - inline static std::unordered_map> s_notificationGlyphCache; - - // Font metrics cache - inline static std::unordered_map s_fontMetricsCache; - - // Add cache size limits - static constexpr size_t MAX_CACHE_SIZE = 600; - static constexpr size_t CLEANUP_THRESHOLD = 500; - static constexpr size_t MAX_NOTIFICATION_CACHE_SIZE = 200; // Separate limit for notifications - - // font handles & state - inline static stbtt_fontinfo* s_stdFont = nullptr; - inline static stbtt_fontinfo* s_localFont = nullptr; - inline static stbtt_fontinfo* s_extFont = nullptr; - inline static bool s_hasLocalFont = false; - inline static bool s_initialized = false; - - // Fix cache key generation to prevent collisions - static u64 generateCacheKey(u32 character, bool monospace, u32 fontSize) { - // Use more bits for fontSize and separate monospace bit - u64 key = static_cast(character); - key = (key << 32) | static_cast(fontSize); - if (monospace) { - key |= (1ULL << 63); // Use the highest bit for monospace - } - return key; - } - - // Generate cache key for font metrics - static u64 generateFontMetricsCacheKey(stbtt_fontinfo* font, u32 fontSize) { - // Use pointer address as font identifier and fontSize - const u64 fontKey = reinterpret_cast(font); - return (fontKey << 32) | static_cast(fontSize); - } - - // Cleanup old entries when cache gets too large - static void cleanupOldEntries() { - if (s_sharedGlyphCache.size() <= CLEANUP_THRESHOLD) return; - - // Simple cleanup: remove oldest entries - // In a real implementation, you might want LRU or other strategies - const size_t toRemove = s_sharedGlyphCache.size() - CLEANUP_THRESHOLD; - auto it = s_sharedGlyphCache.begin(); - for (size_t i = 0; i < toRemove && it != s_sharedGlyphCache.end(); ++i) { - it = s_sharedGlyphCache.erase(it); - } - } - - // NEW: Cleanup notification cache when it gets too large - static void cleanupNotificationCache() { - if (s_notificationGlyphCache.size() <= MAX_NOTIFICATION_CACHE_SIZE) return; - - const size_t toRemove = s_notificationGlyphCache.size() - (MAX_NOTIFICATION_CACHE_SIZE / 2); - auto it = s_notificationGlyphCache.begin(); - for (size_t i = 0; i < toRemove && it != s_notificationGlyphCache.end(); ++i) { - it = s_notificationGlyphCache.erase(it); - } - } - - // NEW: Internal unified glyph creation method - static std::shared_ptr getOrCreateGlyphInternal(u32 character, bool monospace, u32 fontSize, CacheType cacheType) { - const u64 key = generateCacheKey(character, monospace, fontSize); - - // Select target cache based on type - std::unordered_map>* targetCache; - switch (cacheType) { - case CacheType::Notification: - targetCache = &s_notificationGlyphCache; - break; - //case CacheType::Persistent: - // targetCache = &s_persistentGlyphCache; - // break; - default: - targetCache = &s_sharedGlyphCache; - break; - } - - // First, try to find in target cache with shared lock - { - std::shared_lock readLock(s_cacheMutex); - - if (!s_initialized) return nullptr; - - // Check target cache first - auto it = targetCache->find(key); - if (it != targetCache->end()) { - return it->second; - } - - // For notification cache, also check persistent cache (but not regular cache) - // For regular cache, also check persistent cache (existing behavior) - //if (cacheType != CacheType::Persistent) { - // auto persistentIt = s_persistentGlyphCache.find(key); - // if (persistentIt != s_persistentGlyphCache.end()) { - // return persistentIt->second; - // } - //} - } - - // Glyph not found, need to create it with exclusive lock - std::unique_lock writeLock(s_cacheMutex); - - if (!s_initialized) return nullptr; - - // Double-check pattern for target cache - auto it = targetCache->find(key); - if (it != targetCache->end()) { - return it->second; - } - - // Double-check persistent cache - //if (cacheType != CacheType::Persistent) { - // auto persistentIt = s_persistentGlyphCache.find(key); - // if (persistentIt != s_persistentGlyphCache.end()) { - // return persistentIt->second; - // } - //} - - // Check cache size and cleanup if needed - if (cacheType == CacheType::Regular && s_sharedGlyphCache.size() >= MAX_CACHE_SIZE) { - cleanupOldEntries(); - } else if (cacheType == CacheType::Notification && s_notificationGlyphCache.size() >= MAX_NOTIFICATION_CACHE_SIZE) { - cleanupNotificationCache(); - } - - // Create new glyph - auto glyph = std::make_shared(); - glyph->currFont = selectFontForCharacterUnsafe(character); - if (!glyph->currFont) { - return nullptr; - } - - glyph->currFontSize = stbtt_ScaleForPixelHeight(glyph->currFont, fontSize); - - stbtt_GetCodepointBitmapBoxSubpixel(glyph->currFont, character, - glyph->currFontSize, glyph->currFontSize, 0, 0, - &glyph->bounds[0], &glyph->bounds[1], &glyph->bounds[2], &glyph->bounds[3]); - - s32 yAdvance = 0; - stbtt_GetCodepointHMetrics(glyph->currFont, monospace ? 'W' : character, - &glyph->xAdvance, &yAdvance); - - glyph->glyphBmp = stbtt_GetCodepointBitmap(glyph->currFont, - glyph->currFontSize, glyph->currFontSize, character, - &glyph->width, &glyph->height, nullptr, nullptr); - - // Store in target cache - (*targetCache)[key] = glyph; - - return glyph; - } - - public: - // NEW: Preload and persist specific characters - //static void preloadPersistentGlyphs(const std::string& characters, u32 fontSize, bool monospace = false) { - // std::unique_lock writeLock(s_cacheMutex); - // - // if (!s_initialized) return; - // - // // Convert UTF-8 string to UTF-32 codepoints - // #pragma GCC diagnostic push - // #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - // - // std::wstring_convert, char32_t> converter; - // const std::u32string codepoints = converter.from_bytes(characters); - // - // #pragma GCC diagnostic pop - // - // s32 yAdvance; - // for (char32_t character : codepoints) { - // const u64 key = generateCacheKey(character, monospace, fontSize); - // - // if (s_persistentGlyphCache.find(key) != s_persistentGlyphCache.end()) { - // continue; - // } - // - // auto glyph = std::make_shared(); - // glyph->currFont = selectFontForCharacterUnsafe(character); - // if (!glyph->currFont) continue; - // - // glyph->currFontSize = stbtt_ScaleForPixelHeight(glyph->currFont, fontSize); - // - // stbtt_GetCodepointBitmapBoxSubpixel(glyph->currFont, character, - // glyph->currFontSize, glyph->currFontSize, 0, 0, - // &glyph->bounds[0], &glyph->bounds[1], &glyph->bounds[2], &glyph->bounds[3]); - // - // yAdvance = 0; - // stbtt_GetCodepointHMetrics(glyph->currFont, monospace ? 'W' : character, - // &glyph->xAdvance, &yAdvance); - // - // glyph->glyphBmp = stbtt_GetCodepointBitmap(glyph->currFont, - // glyph->currFontSize, glyph->currFontSize, character, - // &glyph->width, &glyph->height, nullptr, nullptr); - // - // s_persistentGlyphCache[key] = glyph; - // } - //} - - - static void initializeFonts(stbtt_fontinfo* stdFont, stbtt_fontinfo* localFont, - stbtt_fontinfo* extFont, bool hasLocalFont) { - std::lock_guard initLock(s_initMutex); - std::unique_lock cacheLock(s_cacheMutex); - - s_stdFont = stdFont; - s_localFont = localFont; - s_extFont = extFont; - s_hasLocalFont = hasLocalFont; - s_initialized = true; - } - - static stbtt_fontinfo* selectFontForCharacter(u32 character) { - std::shared_lock lock(s_cacheMutex); - - if (!s_initialized) return nullptr; - - if (stbtt_FindGlyphIndex(s_extFont, character)) { - return s_extFont; - } else if (s_hasLocalFont && stbtt_FindGlyphIndex(s_localFont, character) != 0) { - 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 { - // Don't insert anything, just fallback to original string - text = originalString; - } - } - #else - text = originalString; - #endif - - // CRITICAL: Use the same data types as drawString - s32 maxWidth = 0; - s32 currentLineWidth = 0; - ssize_t codepointWidth; - u32 currCharacter = 0; - - // Convert fontSize to u32 to match drawString behavior - const u32 fontSizeInt = static_cast(fontSize); - - auto itStrEnd = text.cend(); - auto itStr = text.cbegin(); - - // Fast ASCII check - bool isAsciiOnly = true; - for (unsigned char c : text) { - if (c > 127) { - isAsciiOnly = false; - break; - } - } - - while (itStr != itStrEnd) { - // Decode UTF-8 codepoint - if (isAsciiOnly) { - currCharacter = static_cast(*itStr); - codepointWidth = 1; - } else { - codepointWidth = decode_utf8(&currCharacter, reinterpret_cast(&(*itStr))); - if (codepointWidth <= 0) break; - } - - itStr += codepointWidth; - - // Handle newlines - if (currCharacter == '\n') { - maxWidth = std::max(currentLineWidth, maxWidth); - currentLineWidth = 0; - continue; - } - - // Use u32 fontSize to match drawString - now thread-safe - std::shared_ptr glyph = FontManager::getOrCreateGlyph(currCharacter, monospace, fontSizeInt); - if (!glyph) continue; - - // CRITICAL: Use the same calculation as drawString - currentLineWidth += static_cast(glyph->xAdvance * glyph->currFontSize); - } - - // Final width calculation - maxWidth = std::max(currentLineWidth, maxWidth); - return static_cast(maxWidth); - } - - static std::pair getUnderscanPixels(); - - /** - * @brief Manages the Tesla layer and draws raw data to the screen - */ - class Renderer final { - public: - - using Glyph = FontManager::Glyph; - - Renderer& operator=(Renderer&) = delete; - - friend class tsl::Overlay; - - /** - * @brief Gets the renderer instance - * - * @return Renderer - */ - inline static Renderer& get() { - static Renderer renderer; - - return renderer; - } - - stbtt_fontinfo m_stdFont, m_localFont, m_extFont; - bool m_hasLocalFont = false; - - /** - * @brief Handles opacity of drawn colors for fadeout. Pass all colors through this function in order to apply opacity properly - * - * @param c Original color - * @return Color with applied opacity - */ - static inline Color a(const Color& c) { - const u8 opacity_limit = static_cast(0xF * Renderer::s_opacity); - return (c.rgba & 0x0FFF) | (static_cast( - ult::disableTransparency - ? (ult::useOpaqueScreenshots - ? 0xF // fully opaque when both flags on - : (c.a > 0xE ? c.a : 0xE)) // clamp to 14, keep lower values - : (c.a < opacity_limit ? c.a : opacity_limit) // normal fade logic - ) << 12); - } - - static inline Color aWithOpacity(const Color& c) { - const u8 opacity_limit = static_cast(0xF * Renderer::s_opacity); - return (c.rgba & 0x0FFF) | (static_cast( - ult::disableTransparency - ? 0xF // fully opaque when both flags on - : (c.a < opacity_limit ? c.a : opacity_limit) // normal fade logic - ) << 12); - } - - static inline Color a2(const Color& c) { - const u8 opacity_limit = static_cast(0xF); - return (c.rgba & 0x0FFF) | (static_cast( - ult::disableTransparency - ? (ult::useOpaqueScreenshots - ? 0xF // fully opaque when both flags on - : (c.a > 0xE ? c.a : 0xE)) // clamp to 14, keep lower values - : (c.a < opacity_limit ? c.a : opacity_limit) // normal fade logic - ) << 12); - } - - /** - * @brief Enables scissoring, discarding of any draw outside the given boundaries - * - * @param x x pos - * @param y y pos - * @param w Width - * @param h Height - */ - inline void enableScissoring(const u32 x, const u32 y, const u32 w, const u32 h) { - this->m_scissoringStack.emplace(x, y, w, h, x+w, y+h); - } - - /** - * @brief Disables scissoring - */ - inline void disableScissoring() { - this->m_scissoringStack.pop(); - } - - - // Drawing functions - - /** - * @brief Draw a single pixel onto the screen - * - * @param x X pos - * @param y Y pos - * @param color Color - */ - inline void setPixel(const u32 x, const u32 y, const Color& color) { - const u32 offset = this->getPixelOffset(x, y); - if (offset != UINT32_MAX) [[likely]] { - Color* framebuffer = static_cast(this->getCurrentFramebuffer()); - framebuffer[offset] = color; - } - } - - inline void setPixelAtOffset(const u32 offset, const Color& color) { - Color* framebuffer = static_cast(this->getCurrentFramebuffer()); - framebuffer[offset] = color; - } - - - - /** - * @brief Blends two colors - * - * @param src Source color - * @param dst Destination color - * @param alpha Opacity - * @return Blended color - */ - static constexpr u8 inv_alpha_table[16] = {15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0}; - - inline u8 __attribute__((always_inline)) blendColor(const u8 src, const u8 dst, const u8 alpha) { - return ((src * inv_alpha_table[alpha]) + (dst * alpha)) >> 4; - } - - /** - * @brief Draws a single source blended pixel onto the screen - * - * @param x X pos - * @param y Y pos - * @param color Color - */ - inline void setPixelBlendSrc(const u32 x, const u32 y, const Color& color) { - const u32 offset = this->getPixelOffset(x, y); - if (offset == UINT32_MAX) [[unlikely]] - return; - - Color* framebuffer = static_cast(this->getCurrentFramebuffer()); - const Color src = framebuffer[offset]; - - // Direct write instead of calling setPixel - framebuffer[offset] = Color( - blendColor(src.r, color.r, color.a), - blendColor(src.g, color.g, color.a), - blendColor(src.b, color.b, color.a), - src.a - ); - } - - - // Compromise version - keep framebuffer lookup but inline the rest - inline void setPixelBlendDst(const u32 x, const u32 y, const Color& color) { - const u32 offset = this->getPixelOffset(x, y); - if (offset == UINT32_MAX) [[unlikely]] - return; - - Color* framebuffer = static_cast(this->getCurrentFramebuffer()); - const Color src = framebuffer[offset]; - - // Direct write instead of calling setPixel - framebuffer[offset] = Color( - blendColor(src.r, color.r, color.a), - blendColor(src.g, color.g, color.a), - blendColor(src.b, color.b, color.a), - (color.a + (src.a * (0xF - color.a) >> 4)) - ); - } - - // Batch version for setPixelBlendDst - inline void setPixelBlendDstBatch(const u32 baseX, const u32 baseY, - const u8 red[16], const u8 green[16], - const u8 blue[16], const u8 alpha[16], - const s32 count) { - // 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) { - for (x_curr = row_start; x_curr < row_end; ++x_curr) { - - const u32 offset = this->getPixelOffset((u32)x_curr, (u32)y_curr); - if (offset == UINT32_MAX) continue; - - this->setPixelAtOffset(offset, color); - } - } else { - for (x_curr = row_start; x_curr < row_end; ++x_curr) { - - const u32 offset = this->getPixelOffset((u32)x_curr, (u32)y_curr); - if (offset == UINT32_MAX) continue; - - // you can keep using the existing blended helper which already checks UINT32_MAX - this->setPixelBlendDst((u32)x_curr, (u32)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 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 - } - - 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; - #if defined(UI_OVERRIDE_PATH)// && (!defined(IS_STATUS_MONITOR) || (IS_STATUS_MONITOR == 0)) - { - std::shared_lock readLock(s_translationCacheMutex); - auto translatedIt = ult::translationCache.find(originalString); - if (translatedIt != ult::translationCache.end()) { - text = translatedIt->second; - } else { - // Don't insert anything, just fallback to original string - text = originalString; - } - } - #else - text = originalString; - #endif - - if (text.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 { - // Don't insert anything, just fallback to original string - text = originalString; - } - } - #else - text = originalString; - #endif - - if (text.size() < 2) return text; - - // Get ellipsis width using shared cache (now thread-safe) - static constexpr u32 ellipsisChar = 0x2026; - std::shared_ptr ellipsisGlyph = FontManager::getOrCreateGlyph(ellipsisChar, monospace, fontSize); - if (!ellipsisGlyph) return text; - - // Fixed: Use consistent s32 calculation like other functions - const s32 ellipsisWidth = static_cast(ellipsisGlyph->xAdvance * ellipsisGlyph->currFontSize); - const s32 maxWidthWithoutEllipsis = maxLength - ellipsisWidth; - - if (maxWidthWithoutEllipsis <= 0) { - return "…"; // If there's no room for text, just return ellipsis - } - - // Calculate width incrementally - s32 currX = 0; - auto itStr = text.cbegin(); - const auto itStrEnd = text.cend(); - auto lastValidPos = itStr; - - // Fast ASCII check - bool isAsciiOnly = true; - for (unsigned char c : text) { - if (c > 127) { - isAsciiOnly = false; - break; - } - } - - // Move variable declarations outside the loop - u32 currCharacter; - ssize_t codepointWidth; - s32 charWidth; - size_t bytePos; - - while (itStr != itStrEnd) { - // Decode UTF-8 codepoint - if (isAsciiOnly) { - currCharacter = static_cast(*itStr); - codepointWidth = 1; - } else { - codepointWidth = decode_utf8(&currCharacter, reinterpret_cast(&(*itStr))); - if (codepointWidth <= 0) break; - } - - // FontManager::getOrCreateGlyph is now thread-safe - std::shared_ptr glyph = FontManager::getOrCreateGlyph(currCharacter, monospace, fontSize); - if (!glyph) { - itStr += codepointWidth; - continue; - } - - // Fixed: Use consistent s32 calculation - charWidth = static_cast(glyph->xAdvance * glyph->currFontSize); - - if (currX + charWidth > maxWidthWithoutEllipsis) { - // Calculate the byte position for substring - bytePos = std::distance(text.cbegin(), lastValidPos); - return text.substr(0, bytePos) + "…"; - } - - currX += charWidth; - itStr += codepointWidth; - lastValidPos = itStr; - } - - return text; - } - - inline void setLayerPos(u32 x, u32 y) { - //const float ratio = 1.5; - //u32 maxX = cfg::ScreenWidth - (int)(ratio * cfg::FramebufferWidth); - //u32 maxY = cfg::ScreenHeight - (int)(ratio * cfg::FramebufferHeight); - if (x > cfg::ScreenWidth - (int)(1.5 * cfg::FramebufferWidth) || y > cfg::ScreenHeight - (int)(1.5 * cfg::FramebufferHeight)) { - return; - } - setLayerPosImpl(x, y); - } - - void updateLayerSize() { - const auto [horizontalUnderscanPixels, verticalUnderscanPixels] = getUnderscanPixels(); - - // Recalculate layer dimensions with new underscan values - cfg::LayerWidth = cfg::ScreenWidth * (float(cfg::FramebufferWidth) / float(cfg::LayerMaxWidth)); - cfg::LayerHeight = cfg::ScreenHeight * (float(cfg::FramebufferHeight) / float(cfg::LayerMaxHeight)); - - // Apply underscan adjustments - if (ult::DefaultFramebufferWidth == 1280 && ult::DefaultFramebufferHeight == 28) { - cfg::LayerHeight += cfg::ScreenHeight/720. * verticalUnderscanPixels; - } else if (ult::correctFrameSize) { - cfg::LayerWidth += horizontalUnderscanPixels; - } - - // Update position if using right alignment - if (ult::useRightAlignment && ult::correctFrameSize) { - ult::layerEdge = (1280 - 448); - } - - // Update the existing layer with new dimensions - viSetLayerSize(&this->m_layer, cfg::LayerWidth, cfg::LayerHeight); - - // Update position if using right alignment - if (ult::useRightAlignment && ult::correctFrameSize) { - viSetLayerPosition(&this->m_layer, 1280-32 - horizontalUnderscanPixels, 0); - viSetLayerSize(&this->m_layer, cfg::LayerWidth, cfg::LayerHeight); - viSetLayerPosition(&this->m_layer, 1280-32 - horizontalUnderscanPixels, 0); - } - // ADD THIS: Update position for micro mode bottom positioning - else if (ult::DefaultFramebufferWidth == 1280 && ult::DefaultFramebufferHeight == 28 && cfg::LayerPosY > 500) { - // Only adjust if already positioned at bottom (LayerPosY > 500 indicates bottom positioning) - const u32 targetY = !verticalUnderscanPixels ? 1038 : 1038- (cfg::ScreenHeight/720. * verticalUnderscanPixels) +0.5; - viSetLayerPosition(&this->m_layer, 0, targetY); - viSetLayerSize(&this->m_layer, cfg::LayerWidth, cfg::LayerHeight); - viSetLayerPosition(&this->m_layer, 0, targetY); - } - } - - static Renderer& getRenderer() { - return get(); - } - - inline void setLayerPosImpl(u32 x, u32 y) { - // Get the underscan pixel values for both horizontal and vertical borders - //const auto [horizontalUnderscanPixels, verticalUnderscanPixels] = getUnderscanPixels(); - - // Simply set the position to what was requested - no automatic right alignment - cfg::LayerPosX = x; - cfg::LayerPosY = y; - - ASSERT_FATAL(viSetLayerPosition(&this->m_layer, cfg::LayerPosX, cfg::LayerPosY)); - } - - - #if USING_WIDGET_DIRECTIVE - // Method to draw clock, temperatures, and battery percentage - inline 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(bool forceDisable = true) { - tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Screenshot); - tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Recording); - screenshotsAreDisabled.store(false, std::memory_order_release); - if (forceDisable) - screenshotsAreForceDisabled.store(false, std::memory_order_release); - } - - /** - * @brief Removes the layer from screenshot and recording stacks - */ - inline void removeScreenshotStacks(bool forceDisable = true) { - tsl::hlp::viRemoveFromLayerStack(&this->m_layer, ViLayerStack_Screenshot); - tsl::hlp::viRemoveFromLayerStack(&this->m_layer, ViLayerStack_Recording); - screenshotsAreDisabled.store(true, std::memory_order_release); - if (forceDisable) - screenshotsAreForceDisabled.store(true, std::memory_order_release); - } - - private: - Renderer() { - updateDrawFunction(); - } - - /** - * @brief Sets the opacity of the layer - * - * @param opacity Opacity - */ - inline static void setOpacity(float opacity) { - opacity = std::clamp(opacity, 0.0F, 1.0F); - - Renderer::s_opacity = opacity; - } - - bool m_initialized = false; - ViDisplay m_display; - ViLayer m_layer; - Event m_vsyncEvent; - - NWindow m_window; - Framebuffer m_framebuffer; - void *m_currentFramebuffer = nullptr; - - std::stack m_scissoringStack; - - - static inline float s_opacity = 1.0F; - - - /** - * @brief Get the current framebuffer address - * - * @return Framebuffer address - */ - inline void* getCurrentFramebuffer() { - return this->m_currentFramebuffer; - } - - /** - * @brief Get the next framebuffer address - * - * @return Next framebuffer address - */ - inline void* getNextFramebuffer() { - return static_cast(this->m_framebuffer.buf) + this->getNextFramebufferSlot() * this->getFramebufferSize(); - } - - /** - * @brief Get the framebuffer size - * - * @return Framebuffer size - */ - inline size_t getFramebufferSize() { - return this->m_framebuffer.fb_size; - } - - /** - * @brief Get the number of framebuffers in use - * - * @return Number of framebuffers - */ - inline size_t getFramebufferCount() { - return this->m_framebuffer.num_fbs; - } - - /** - * @brief Get the currently used framebuffer's slot - * - * @return Slot - */ - inline u8 getCurrentFramebufferSlot() { - return this->m_window.cur_slot; - } - - /** - * @brief Get the next framebuffer's slot - * - * @return Next slot - */ - inline u8 getNextFramebufferSlot() { - return (this->getCurrentFramebufferSlot() + 1) % this->getFramebufferCount(); - } - - /** - * @brief Waits for the vsync event - * - */ - inline void waitForVSync() { - eventWait(&this->m_vsyncEvent, UINT64_MAX); - } - - /** - * @brief Decodes a x and y coordinate into a offset into the swizzled framebuffer - * - * @param x X pos - * @param y Y Pos - * @return Offset - */ - - inline u32 __attribute__((always_inline)) getPixelOffset(const u32 x, const u32 y) { - // Check for scissoring boundaries - if (!this->m_scissoringStack.empty()) { - const auto& currScissorConfig = this->m_scissoringStack.top(); - if (x < currScissorConfig.x || y < currScissorConfig.y || - x >= currScissorConfig.x_max || - y >= currScissorConfig.y_max) { - return UINT32_MAX; - } - } - - return ((((y & 127) >> 4) + ((x >> 5) << 3) + ((y >> 7) * offsetWidthVar)) << 9) + - ((y & 8) << 5) + ((x & 16) << 3) + ((y & 6) << 4) + - ((x & 8) << 1) + ((y & 1) << 3) + (x & 7); - } - - - /** - * @brief Initializes the renderer and layers - * - */ - void init() { - // Get the underscan pixel values for both horizontal and vertical borders - const auto [horizontalUnderscanPixels, verticalUnderscanPixels] = getUnderscanPixels(); - //int horizontalUnderscanPixels = 0; - - - ult::useRightAlignment = (ult::parseValueFromIniSection(ult::ULTRAHAND_CONFIG_INI_PATH, ult::ULTRAHAND_PROJECT_NAME, "right_alignment") == ult::TRUE_STR); - - //cfg::LayerPosX = 1280-32; - cfg::LayerPosX = 0; - cfg::LayerPosY = 0; - cfg::FramebufferWidth = ult::DefaultFramebufferWidth; - cfg::FramebufferHeight = ult::DefaultFramebufferHeight; - - offsetWidthVar = (((cfg::FramebufferWidth / 2) >> 4) << 3); - - ult::correctFrameSize = (cfg::FramebufferWidth == 448 && cfg::FramebufferHeight == 720); // for detecting the correct Overlay display size - if (ult::useRightAlignment && ult::correctFrameSize) { - cfg::LayerPosX = 1280-32 - horizontalUnderscanPixels; - ult::layerEdge = (1280-448); - } - - cfg::LayerWidth = cfg::ScreenWidth * (float(cfg::FramebufferWidth) / float(cfg::LayerMaxWidth)); - cfg::LayerHeight = cfg::ScreenHeight * (float(cfg::FramebufferHeight) / float(cfg::LayerMaxHeight)); - - // Apply underscanning offset - if (ult::DefaultFramebufferWidth == 1280 && ult::DefaultFramebufferHeight == 28) // for status monitor micro mode - cfg::LayerHeight += cfg::ScreenHeight/720. *verticalUnderscanPixels; - else if (ult::correctFrameSize) - cfg::LayerWidth += horizontalUnderscanPixels; - - // NEW: Scale down to 1/4 size (0.5x in each dimension) - //static constexpr float scaleFactor = 0.5f; - //cfg::LayerWidth *= scaleFactor; - //cfg::LayerHeight *= scaleFactor; - - if (this->m_initialized) - return; - - //s32 layerZ = 0; - - tsl::hlp::doWithSmSession([this, horizontalUnderscanPixels]{ - - ASSERT_FATAL(viInitialize(ViServiceType_Manager)); - ASSERT_FATAL(viOpenDefaultDisplay(&this->m_display)); - ASSERT_FATAL(viGetDisplayVsyncEvent(&this->m_display, &this->m_vsyncEvent)); - ASSERT_FATAL(viCreateManagedLayer(&this->m_display, static_cast(0), 0, &__nx_vi_layer_id)); - ASSERT_FATAL(viCreateLayer(&this->m_display, &this->m_layer)); - ASSERT_FATAL(viSetLayerScalingMode(&this->m_layer, ViScalingMode_FitToLayer)); - - //if (s32 layerZ = 0; R_SUCCEEDED(viGetZOrderCountMax(&this->m_display, &layerZ)) && layerZ > 0) - // ASSERT_FATAL(viSetLayerZ(&this->m_layer, layerZ)); - - if (horizontalUnderscanPixels == 0) { - s32 layerZ = 0; - if (R_SUCCEEDED(viGetZOrderCountMax(&this->m_display, &layerZ)) && layerZ > 0) { - ASSERT_FATAL(viSetLayerZ(&this->m_layer, layerZ)); - } - else { - ASSERT_FATAL(viSetLayerZ(&this->m_layer, 255)); // max value 255 as fallback - } - } else { - ASSERT_FATAL(viSetLayerZ(&this->m_layer, 34)); // 34 is the edge for underscanning - } - - ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Default)); - ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Screenshot)); - ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Recording)); - ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Arbitrary)); - ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_LastFrame)); - ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Null)); - ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_ApplicationForDebug)); - ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Lcd)); - - ASSERT_FATAL(viSetLayerSize(&this->m_layer, cfg::LayerWidth, cfg::LayerHeight)); - ASSERT_FATAL(viSetLayerPosition(&this->m_layer, cfg::LayerPosX, cfg::LayerPosY)); - ASSERT_FATAL(nwindowCreateFromLayer(&this->m_window, &this->m_layer)); - ASSERT_FATAL(framebufferCreate(&this->m_framebuffer, &this->m_window, cfg::FramebufferWidth, cfg::FramebufferHeight, PIXEL_FORMAT_RGBA_4444, 2)); - ASSERT_FATAL(setInitialize()); - ASSERT_FATAL(this->initFonts()); - setExit(); - }); - - this->m_initialized = true; - } - - /** - * @brief Exits the renderer and layer - * - */ - void exit() { - if (!this->m_initialized) - return; - - // Cleanup shared font manager - FontManager::cleanup(); - - framebufferClose(&this->m_framebuffer); - nwindowClose(&this->m_window); - viDestroyManagedLayer(&this->m_layer); - viCloseDisplay(&this->m_display); - eventClose(&this->m_vsyncEvent); - viExit(); - } - - /** - * @brief Initializes Nintendo's shared fonts. Default and Extended - * - * @return Result - */ - Result initFonts() { - PlFontData stdFontData, localFontData, extFontData; - - // Nintendo's default font - TSL_R_TRY(plGetSharedFontByType(&stdFontData, PlSharedFontType_Standard)); - - u8 *fontBuffer = reinterpret_cast(stdFontData.address); - stbtt_InitFont(&this->m_stdFont, fontBuffer, stbtt_GetFontOffsetForIndex(fontBuffer, 0)); - - u64 languageCode; - if (R_SUCCEEDED(setGetSystemLanguage(&languageCode))) { - // Check if need localization font - SetLanguage setLanguage; - TSL_R_TRY(setMakeLanguage(languageCode, &setLanguage)); - this->m_hasLocalFont = true; - switch (setLanguage) { - case SetLanguage_ZHCN: - case SetLanguage_ZHHANS: - 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 - if (isRendering) { - static u32 lastFPS = 0; - static u64 cachedIntervalNs = 1000000000ULL / 60; // Default to 60 FPS - - u32 fps = TeslaFPS; - if (__builtin_expect(fps != lastFPS, 0)) { - cachedIntervalNs = (fps > 0) ? (1000000000ULL / fps) : cachedIntervalNs; - lastFPS = fps; - } - - // Frame pacing before VSync - leventWait(&renderingStopEvent, cachedIntervalNs); - } - #endif - - // Then hardware sync - this->waitForVSync(); - framebufferEnd(&this->m_framebuffer); - this->m_currentFramebuffer = nullptr; - - if (tsl::clearGlyphCacheNow.exchange(false)) { - tsl::gfx::FontManager::clearCache(); - } - } - - - }; - - static std::pair getUnderscanPixels() { - if (!ult::consoleIsDocked()) { - return {0, 0}; - } - - // Retrieve the TV settings - SetSysTvSettings tvSettings; - Result res = setsysGetTvSettings(&tvSettings); - if (R_FAILED(res)) { - // Handle error: return default underscan or log error - return {0, 0}; - } - - // The underscan value might not be a percentage, we need to interpret it correctly - const u32 underscanValue = tvSettings.underscan; - - // Convert the underscan value to a fraction. Assuming 0 means no underscan and larger values represent - // greater underscan. Adjust this formula based on actual observed behavior or documentation. - const float underscanPercentage = 1.0f - (underscanValue / 100.0f); - - // Original dimensions of the full 720p image (1280x720) - const float originalWidth = 1280; - const float originalHeight = 720; - - // Adjust the width and height based on the underscan percentage - const float adjustedWidth = (originalWidth * underscanPercentage); - const float adjustedHeight = (originalHeight * underscanPercentage); - - // Calculate the underscan in pixels (left/right and top/bottom) - const int horizontalUnderscanPixels = (originalWidth - adjustedWidth); - const int verticalUnderscanPixels = (originalHeight - adjustedHeight); - - return {horizontalUnderscanPixels, verticalUnderscanPixels}; - } - - } - - - // Elements - - namespace elm { - - enum class TouchEvent { - Touch, - Hold, - Scroll, - Release, - None - }; - - /** - * @brief The top level Element of the libtesla UI library - * @note When creating your own elements, extend from this or one of it's sub classes - */ - class Element { - public: - - Element() {} - virtual ~Element() { - m_clickListener = {}; // frees captures immediately - } - - bool m_isTable = false; // Default to false for non-table elements - bool m_isItem = true; - - - u64 t_ns; // Changed from chrono::duration to nanoseconds - u8 saturation; - float progress; - - s32 x, y; - s32 amplitude; - u64 m_animationStartTime; // Changed from chrono::time_point to nanoseconds - - virtual bool isTable() const { - return m_isTable; - } - - virtual bool isItem() const { - return m_isItem; - } - - /** - * @brief Handles focus requesting - * @note This function should return the element to focus. - * When this element should be focused, return `this`. - * When one of it's child should be focused, return `this->child->requestFocus(oldFocus, direction)` - * When this element is not focusable, return `nullptr` - * - * @param oldFocus Previously focused element - * @param direction Direction in which focus moved. \ref FocusDirection::None is passed for the initial load - * @return Element to focus - */ - virtual inline Element* requestFocus(Element *oldFocus, FocusDirection direction) { - return nullptr; - } - - /** - * @brief Function called when a joycon button got pressed - * - * @param keys Keys pressed in the last frame - * @return true when button press has been consumed - * @return false when button press should be passed on to the parent - */ - virtual inline bool onClick(u64 keys) { - return m_clickListener(keys); - } - - /** - * @brief Called once per frame with the latest HID inputs - * - * @param keysDown Buttons pressed in the last frame - * @param keysHeld Buttons held down longer than one frame - * @param touchInput Last touch position - * @param leftJoyStick Left joystick position - * @param rightJoyStick Right joystick position - * @return Weather or not the input has been consumed - */ - virtual inline bool handleInput(u64 keysDown, u64 keysHeld, const HidTouchState &touchPos, HidAnalogStickState joyStickPosLeft, HidAnalogStickState joyStickPosRight) { - return false; - } - - /** - * @brief Function called when the element got touched - * @todo Not yet implemented - * - * @param x X pos - * @param y Y pos - * @return true when touch input has been consumed - * @return false when touch input should be passed on to the parent - */ - virtual inline bool onTouch(TouchEvent event, s32 currX, s32 currY, s32 prevX, s32 prevY, s32 initialX, s32 initialY) { - return false; - } - - /** - * @brief Called once per frame to draw the element - * @warning Do not call this yourself. Use \ref Element::frame(gfx::Renderer *renderer) - * - * @param renderer Renderer - */ - virtual void draw(gfx::Renderer *renderer) = 0; - - /** - * @brief Called when the underlying Gui gets created and after calling \ref Gui::invalidate() to calculate positions and boundaries of the element - * @warning Do not call this yourself. Use \ref Element::invalidate() - * - * @param parentX Parent X pos - * @param parentY Parent Y pos - * @param parentWidth Parent Width - * @param parentHeight Parent Height - */ - virtual inline void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) = 0; - - /** - * @brief Draws highlighting and the element itself - * @note When drawing children of a element in \ref Element::draw(gfx::Renderer *renderer), use `this->child->frame(renderer)` instead of calling draw directly - * - * @param renderer - */ - void inline frame(gfx::Renderer *renderer) { - - if (this->m_focused) { - renderer->enableScissoring(0, ult::activeHeaderHeight, tsl::cfg::FramebufferWidth, tsl::cfg::FramebufferHeight-73-ult::activeHeaderHeight); - this->drawFocusBackground(renderer); - this->drawHighlight(renderer); - renderer->disableScissoring(); - } - - this->draw(renderer); - } - - /** - * @brief Forces a layout recreation of a element - * - */ - void inline invalidate() { - const auto& parent = this->getParent(); - - if (parent == nullptr) - this->layout(0, 0, cfg::FramebufferWidth, cfg::FramebufferHeight); - else - this->layout(ELEMENT_BOUNDS(parent)); - } - - /** - * @brief Shake the highlight in the given direction to signal that the focus cannot move there - * - * @param direction Direction to shake highlight in - */ - void inline shakeHighlight(FocusDirection direction) { - this->m_highlightShaking = true; - this->m_highlightShakingDirection = direction; - this->m_highlightShakingStartTime = armTicksToNs(armGetSystemTick()); // Changed - if (direction != FocusDirection::None && m_isItem) { - triggerRumbleClick.store(true, std::memory_order_release); - triggerWallSound.store(true, std::memory_order_release); - } - } - - /** - * @brief Triggers the blue click animation to signal a element has been clicked on - * - */ - void inline triggerClickAnimation() { - this->m_clickAnimationProgress = tsl::style::ListItemHighlightLength; - this->m_animationStartTime = armTicksToNs(armGetSystemTick()); // Changed - } - - - - /** - * @brief Resets the click animation progress, canceling the animation - */ - void inline resetClickAnimation() { - this->m_clickAnimationProgress = 0; - } - - /** - * @brief Draws the blue highlight animation when clicking on a button - * @note Override this if you have a element that e.g requires a non-rectangular animation or a different color - * - * @param renderer Renderer - */ - virtual void drawClickAnimation(gfx::Renderer *renderer) { - if (!m_isItem) - return; - if (ult::useSelectionBG) { - if (ult::expandedMemory) - renderer->drawRectMultiThreaded(this->getX() + x + 4, this->getY() + y, this->getWidth() - 8, this->getHeight(), aWithOpacity(selectionBGColor)); // CUSTOM MODIFICATION - else - renderer->drawRect(this->getX() + x + 4, this->getY() + y, this->getWidth() - 8, this->getHeight(), aWithOpacity(selectionBGColor)); - } - - saturation = tsl::style::ListItemHighlightSaturation * (float(this->m_clickAnimationProgress) / float(tsl::style::ListItemHighlightLength)); - - Color animColor = {0xF,0xF,0xF,0xF}; - if (invertBGClickColor) { - const u8 inverted = 15-saturation; - animColor = {inverted, inverted, inverted, selectionBGColor.a}; - } else { - animColor = {saturation, saturation, saturation, selectionBGColor.a}; - } - if (ult::expandedMemory) - renderer->drawRectMultiThreaded(ELEMENT_BOUNDS(this), aWithOpacity(animColor)); - else - renderer->drawRect(ELEMENT_BOUNDS(this), aWithOpacity(animColor)); - - // Cache time calculation - only compute once - static u64 lastTimeUpdate = 0; - static double cachedProgress = 0.0; - const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); - - // Only recalculate progress if enough time has passed (reduce computation frequency) - if (currentTime_ns - lastTimeUpdate > 16666666) { // ~60 FPS update rate - //double time_seconds = currentTime_ns / 1000000000.0; - cachedProgress = (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 - 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; }; - }; - - /** - * @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; - }; - - - #if IS_LAUNCHER_DIRECTIVE - // Simple utility function to draw the dynamic "Ultra" part of the logo - static s32 drawDynamicUltraText(gfx::Renderer* renderer, s32 startX, s32 y, u32 fontSize, - const tsl::Color& staticColor, bool useNotificationMethod = false) { - static constexpr double cycleDuration = 1.6; - s32 currentX = startX; - - if (ult::useDynamicLogo) { - const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); - const double currentTimeCount = static_cast(currentTime_ns) / 1000000000.0; - const double timeBase = std::fmod(currentTimeCount, cycleDuration); - const double waveScale = 2.0 * ult::_M_PI / cycleDuration; - static constexpr double phaseShift = ult::_M_PI / 2.0; - - float countOffset = 0; - for (const char letter : ult::SPLIT_PROJECT_NAME_1) { - const double wavePhase = waveScale * (timeBase + static_cast(countOffset)); - const double rawProgress = 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); - if (useNotificationMethod) { - //const auto [letterWidth, letterHeight] = renderer->drawNotificationString(letterStr, false, currentX, y, fontSize, highlightColor); - currentX += renderer->drawNotificationString(letterStr, false, currentX, y, fontSize, highlightColor).first; - } else { - currentX += renderer->drawString(letterStr, false, currentX, y, fontSize, highlightColor).first; - } - countOffset -= static_cast(cycleDuration / 8.0); - } - } else { - // Static rendering - for (const char letter : ult::SPLIT_PROJECT_NAME_1) { - const std::string letterStr(1, letter); - if (useNotificationMethod) { - //const auto [letterWidth, letterHeight] = renderer->drawNotificationString(letterStr, false, currentX, y, fontSize, staticColor); - currentX += renderer->drawNotificationString(letterStr, false, currentX, y, fontSize, staticColor).first; - } else { - currentX += renderer->drawString(letterStr, false, currentX, y, fontSize, staticColor).first; - } - } - } - - return currentX; - } - - // Utility function to calculate width of the Ultra text (for notification centering) - static s32 calculateUltraTextWidth(gfx::Renderer* renderer, u32 fontSize, bool useNotificationMethod = false) { - s32 totalWidth = 0; - - if (ult::useDynamicLogo) { - // Calculate width by measuring each character for dynamic rendering - for (const char letter : ult::SPLIT_PROJECT_NAME_1) { - const std::string letterStr(1, letter); - if (useNotificationMethod) { - //const auto [lw, lh] = renderer->getNotificationTextDimensions(letterStr, false, fontSize); - totalWidth += renderer->getNotificationTextDimensions(letterStr, false, fontSize).first; - } else { - //const auto [lw, lh] = renderer->getTextDimensions(letterStr, false, fontSize); - totalWidth += renderer->getTextDimensions(letterStr, false, fontSize).first; - } - } - } else { - // Static rendering - measure the whole string at once - if (useNotificationMethod) { - //const auto [uw, uh] = renderer->getNotificationTextDimensions(ult::SPLIT_PROJECT_NAME_1, false, fontSize); - totalWidth = renderer->getNotificationTextDimensions(ult::SPLIT_PROJECT_NAME_1, false, fontSize).first; - } else { - //const auto [uw, uh] = renderer->getTextDimensions(ult::SPLIT_PROJECT_NAME_1, false, fontSize); - totalWidth = renderer->getTextDimensions(ult::SPLIT_PROJECT_NAME_1, false, fontSize).first; - } - } - - return totalWidth; - } - - #endif - - struct TopCache { - std::string title; - std::string subtitle; - tsl::Color titleColor{0xF, 0xF, 0xF, 0xF}; // white by default - bool widgetDrawn = false; - bool useDynamicLogo = false; - bool disabled = false; - }; - - struct BottomCache { - std::string bottomText; - float backWidth = 0.0f; - float selectWidth = 0.0f; - float nextPageWidth = 0.0f; - bool disabled = false; - }; - - // Global or namespace-level variable - inline TopCache g_cachedTop; - inline BottomCache g_cachedBottom; - - inline std::atomic g_disableMenuCacheOnReturn = false; - - /** - * @brief The base frame which can contain another view - * - */ - class OverlayFrame : public Element { - public: - /** - * @brief Constructor - * - * @param title Name of the Overlay drawn bolt at the top - * @param subtitle Subtitle drawn bellow the title e.g version number - */ - std::string m_title; - std::string m_subtitle; - - bool m_noClickableItems; - - #if IS_LAUNCHER_DIRECTIVE - std::string m_menuMode; // CUSTOM MODIFICATION - std::string m_colorSelection; // CUSTOM MODIFICATION - std::string m_pageLeftName; // CUSTOM MODIFICATION - std::string m_pageRightName; // CUSTOM MODIFICATION - - - tsl::Color titleColor = {0xF,0xF,0xF,0xF}; - float letterWidth; - #endif - - #if USING_WIDGET_DIRECTIVE - bool m_showWidget = false; - #endif - - float x, y; - int offset, y_offset; - int fontSize; - - #if IS_LAUNCHER_DIRECTIVE - OverlayFrame(const std::string& title, const std::string& subtitle, const bool& _noClickableItems=false, const std::string& menuMode = "", const std::string& colorSelection = "", const std::string& pageLeftName = "", const std::string& pageRightName = "") - : Element(), m_title(title), m_subtitle(subtitle), m_noClickableItems(_noClickableItems), m_menuMode(menuMode), m_colorSelection(colorSelection), m_pageLeftName(pageLeftName), m_pageRightName(pageRightName) { - #else - OverlayFrame(const std::string& title, const std::string& subtitle, const bool& _noClickableItems=false) - : Element(), m_title(title), m_subtitle(subtitle), m_noClickableItems(_noClickableItems) { - #endif - ult::activeHeaderHeight = 97; - ult::loadWallpaperFileWhenSafe(); - m_isItem = false; - disableSound.store(false, std::memory_order_release); - } - - ~OverlayFrame() { - delete m_contentElement; - - // Check if returning from a list that disabled caching - if (g_disableMenuCacheOnReturn.exchange(false, std::memory_order_acq_rel)) { - g_cachedTop.disabled = true; - g_cachedBottom.disabled = true; - } - } - - #if USING_FPS_INDICATOR_DIRECTIVE - // Function to calculate FPS - inline float updateFPS(double currentTimeCount) { - static double lastUpdateTime = currentTimeCount; - static int frameCount = 0; - static float fps = 0.0f; - - ++frameCount; - const double elapsedTime = currentTimeCount - lastUpdateTime; - - if (elapsedTime >= 1.0) { // Update FPS every second - fps = frameCount / static_cast(elapsedTime); - lastUpdateTime = currentTimeCount; - frameCount = 0; - } - return fps; - } - #endif - - // CUSTOM SECTION START - void draw(gfx::Renderer *renderer) override { - if (!ult::themeIsInitialized.exchange(true, std::memory_order_acq_rel)) { - tsl::initializeThemeVars(); - } - - - renderer->fillScreen(a(defaultBackgroundColor)); - renderer->drawWallpaper(); - - y = 50; - offset = 0; - - #if IS_LAUNCHER_DIRECTIVE - // Current interpreter state (atomic) - const bool interpreterIsRunningNow = ult::runningInterpreter.load(std::memory_order_acquire) && (ult::downloadPercentage.load(std::memory_order_acquire) != -1 || ult::unzipPercentage.load(std::memory_order_acquire) != -1 || ult::copyPercentage.load(std::memory_order_acquire) != -1); - - if (m_noClickableItems != ult::noClickableItems.load(std::memory_order_acquire)) { - ult::noClickableItems.store(m_noClickableItems, std::memory_order_release); - } - - 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); - - // Determine if we should use cached data (first frame of new overlay) - const bool useCachedTop = !g_cachedTop.disabled && - !g_cachedTop.title.empty() && - (g_cachedTop.title != m_title || g_cachedTop.subtitle != m_subtitle); - - // Use cached or current data for rendering - const std::string& renderTitle = useCachedTop ? g_cachedTop.title : m_title; - const std::string& renderSubtitle = useCachedTop ? g_cachedTop.subtitle : m_subtitle; - const tsl::Color& renderTitleColor = useCachedTop ? g_cachedTop.titleColor : titleColor; - const bool renderUseDynamicLogo = useCachedTop ? g_cachedTop.useDynamicLogo : ult::useDynamicLogo; - - const bool renderIsUltrahandMenu = (renderTitle == ult::CAPITAL_ULTRAHAND_PROJECT_NAME && - renderSubtitle.find("Ultrahand Package") == std::string::npos && - renderSubtitle.find("Ultrahand Script") == std::string::npos); - - if (renderIsUltrahandMenu) { - #if USING_WIDGET_DIRECTIVE - if (useCachedTop) { - if (g_cachedTop.widgetDrawn) { - renderer->drawWidget(); - } - } else { - 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; - - if (renderUseDynamicLogo) { - x = drawDynamicUltraText(renderer, x, y + offset, fontSize, logoColor1, false); - } else { - for (const char letter : ult::SPLIT_PROJECT_NAME_1) { - const std::string letterStr(1, letter); - x += renderer->drawString(letterStr, false, x, y + offset, fontSize, logoColor1).first; - } - } - - renderer->drawString(ult::SPLIT_PROJECT_NAME_2, false, x, y + offset, fontSize, (logoColor2)); - - } else { - if (useCachedTop) { - if (g_cachedTop.widgetDrawn) { - renderer->drawWidget(); - } - } else { - if (m_showWidget) { - renderer->drawWidget(); - } - } - - x = 20; - y = 52 - 2; - fontSize = 32; - - if (renderSubtitle.find("Ultrahand Script") != std::string::npos) { - renderer->drawString(renderTitle, false, x, y, fontSize, (defaultScriptColor)); - } else { - tsl::Color drawColor = defaultPackageColor; // Default to green - - if (!useCachedTop) { - // Calculate color only if not using cache - 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.compare("green") == 0) { - drawColor = {0x0, 0xF, 0x0, 0xF}; - } - break; - case 'r': // red - if (len == 3 && m_colorSelection.compare("red") == 0) { - drawColor = RGB888("#F7253E"); - } - break; - case 'b': // blue - if (len == 4 && m_colorSelection.compare("blue") == 0) { - drawColor = {0x7, 0x7, 0xF, 0xF}; - } - break; - case 'y': // yellow - if (len == 6 && m_colorSelection.compare("yellow") == 0) { - drawColor = {0xF, 0xF, 0x0, 0xF}; - } - break; - case 'o': // orange - if (len == 6 && m_colorSelection.compare("orange") == 0) { - drawColor = {0xFF, 0xA5, 0x00, 0xFF}; - } - break; - case 'p': // pink or purple - if (len == 4 && m_colorSelection.compare("pink") == 0) { - drawColor = {0xFF, 0x69, 0xB4, 0xFF}; - } else if (len == 6 && m_colorSelection.compare("purple") == 0) { - drawColor = {0x80, 0x00, 0x80, 0xFF}; - } - break; - case 'w': // white - if (len == 5 && m_colorSelection.compare("white") == 0) { - drawColor = {0xF, 0xF, 0xF, 0xF}; - } - break; - case '#': // hex color - if (len == 7 && ult::isValidHexColor(m_colorSelection.substr(1))) { - drawColor = RGB888(m_colorSelection.substr(1)); - } - break; - } - } - titleColor = drawColor; - } else { - drawColor = renderTitleColor; - } - - renderer->drawString(renderTitle, false, x, y, fontSize, (drawColor)); - y += 2; - } - } - - static const std::vector specialChars2 = {""}; - if (renderTitle == ult::CAPITAL_ULTRAHAND_PROJECT_NAME) { - renderer->drawStringWithColoredSections(ult::versionLabel, false, specialChars2, 20, y+25, 15, (bannerVersionTextColor), textSeparatorColor); - } else { - std::string subtitle = renderSubtitle; - 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); - } - - // Update top cache after rendering for next frame - g_cachedTop.title = m_title; - g_cachedTop.subtitle = m_subtitle; - g_cachedTop.titleColor = titleColor; - g_cachedTop.useDynamicLogo = ult::useDynamicLogo; - // Store whether widget was ACTUALLY drawn this frame - if (isUltrahandMenu) { - g_cachedTop.widgetDrawn = true; // Ultrahand menu always shows widget - } else { - g_cachedTop.widgetDrawn = m_showWidget; // Other menus use m_showWidget - } - g_cachedTop.disabled = false; - - #else - // NON-LAUNCHER PATH WITH CACHE SUPPORT - if (m_noClickableItems != ult::noClickableItems.load(std::memory_order_acquire)) { - ult::noClickableItems.store(m_noClickableItems, std::memory_order_release); - } - - // Determine if we should use cached data (first frame of new overlay) - const bool useCachedTop = !g_cachedTop.disabled && - !g_cachedTop.title.empty() && - (g_cachedTop.title != m_title || g_cachedTop.subtitle != m_subtitle); - - // Use cached or current data for rendering - const std::string& renderTitle = useCachedTop ? g_cachedTop.title : m_title; - const std::string& renderSubtitle = useCachedTop ? g_cachedTop.subtitle : m_subtitle; - - #if USING_WIDGET_DIRECTIVE - if (useCachedTop) { - if (g_cachedTop.widgetDrawn) { - renderer->drawWidget(); - } - } else { - if (m_showWidget) - renderer->drawWidget(); - } - #endif - - renderer->drawString(renderTitle, false, 20, 52-2, 32, (defaultOverlayColor)); - renderer->drawString(renderSubtitle, false, 20, y+2+23+2, 15, (bannerVersionTextColor)); - - // Update top cache after rendering for next frame - g_cachedTop.title = m_title; - g_cachedTop.subtitle = m_subtitle; - g_cachedTop.titleColor = {0xF, 0xF, 0xF, 0xF}; - #if USING_WIDGET_DIRECTIVE - g_cachedTop.widgetDrawn = m_showWidget; - #else - g_cachedTop.widgetDrawn = false; - #endif - g_cachedTop.useDynamicLogo = false; - g_cachedTop.disabled = false; - #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.compare("packages") == 0) ? - (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 - std::string currentBottomLine = - "\uE0E1" + ult::GAP_2 + - (interpreterIsRunningNow ? ult::HIDE : ult::BACK) + ult::GAP_1 + - (!m_noClickableItems && !interpreterIsRunningNow - ? "\uE0E0" + ult::GAP_2 + ult::OK + ult::GAP_1 - : "") + - (interpreterIsRunningNow - ? "\uE0E5" + ult::GAP_2 + ult::CANCEL + ult::GAP_1 - : "") + - (!interpreterIsRunningNow - ? (!ult::usePageSwap - ? ((m_menuMode.compare("packages") == 0) - ? "\uE0ED" + ult::GAP_2 + ult::OVERLAYS_ABBR - : (m_menuMode.compare("overlays") == 0) - ? "\uE0EE" + ult::GAP_2 + ult::PACKAGES - : "") - : ((m_menuMode.compare("packages") == 0) - ? "\uE0EE" + ult::GAP_2 + ult::OVERLAYS_ABBR - : (m_menuMode.compare("overlays") == 0) - ? "\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 - std::string currentBottomLine = - "\uE0E1" + ult::GAP_2 + ult::BACK + ult::GAP_1 + - (!m_noClickableItems - ? "\uE0E0" + ult::GAP_2 + ult::OK + ult::GAP_1 - : ""); - #endif - - // Determine if we should use cached bottom text (first frame of new overlay) - const bool useCachedBottom = !g_cachedBottom.disabled && - !g_cachedBottom.bottomText.empty() && - g_cachedBottom.bottomText != currentBottomLine; - - const std::string& menuBottomLine = useCachedBottom ? g_cachedBottom.bottomText : currentBottomLine; - - // 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)); - - // Update bottom cache after rendering for next frame - g_cachedBottom.bottomText = currentBottomLine; - g_cachedBottom.backWidth = _backWidth; - g_cachedBottom.selectWidth = _selectWidth; - #if IS_LAUNCHER_DIRECTIVE - g_cachedBottom.nextPageWidth = ult::nextPageWidth.load(std::memory_order_acquire); - #else - g_cachedBottom.nextPageWidth = 0.0f; - #endif - g_cachedBottom.disabled = false; - - #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(250'000); // sleep thread for initial values to auto-load - - m_isItem = false; - } - - virtual ~HeaderOverlayFrame() { - if (this->m_contentElement != nullptr) - delete this->m_contentElement; - - // Check if returning from a list that disabled caching - if (g_disableMenuCacheOnReturn.exchange(false, std::memory_order_acq_rel)) { - g_cachedTop.disabled = true; - g_cachedBottom.disabled = true; - } - } - - - virtual void draw(gfx::Renderer *renderer) override { - if (!ult::themeIsInitialized.load(std::memory_order_acquire) && FullMode) { - ult::themeIsInitialized.store(true, std::memory_order_release); - tsl::initializeThemeVars(); - } - - if (m_noClickableItems != ult::noClickableItems.load(std::memory_order_acquire)) { - ult::noClickableItems.store(m_noClickableItems, std::memory_order_release); - } - - - if (FullMode == true) { - renderer->fillScreen(a(defaultBackgroundColor)); - if (lastMode.empty() || (lastMode.compare("returning") == 0)) - renderer->drawWallpaper(); - } else { - renderer->fillScreen({ 0x0, 0x0, 0x0, 0x0}); - } - - y = 50; - offset = 0; - - // Determine if we should use cached data (first frame of new overlay) - const bool useCachedTop = !g_cachedTop.disabled && - !g_cachedTop.title.empty() && - (g_cachedTop.title != m_title || g_cachedTop.subtitle != m_subtitle); - - // Use cached or current data for rendering - const std::string& renderTitle = useCachedTop ? g_cachedTop.title : m_title; - const std::string& renderSubtitle = useCachedTop ? g_cachedTop.subtitle : m_subtitle; - - renderer->drawString(renderTitle, false, 20, 50, 32, (defaultOverlayColor)); - renderer->drawString(renderSubtitle, 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 - const auto gapWidth = renderer->getTextDimensions(ult::GAP_1, false, 23).first; - const float _halfGap = gapWidth / 2.0f; - if (_halfGap != ult::halfGap.load(std::memory_order_acquire)) - ult::halfGap.store(_halfGap, std::memory_order_release); - - // Calculate text dimensions for buttons without gaps - const auto backTextWidth = renderer->getTextDimensions("\uE0E1" + ult::GAP_2 + ult::BACK, false, 23).first; - const auto selectTextWidth = renderer->getTextDimensions("\uE0E0" + ult::GAP_2 + ult::OK, false, 23).first; - - // Update widths to include the half-gap padding on each side - const float _backWidth = backTextWidth + gapWidth; - if (_backWidth != ult::backWidth.load(std::memory_order_acquire)) - ult::backWidth.store(_backWidth, std::memory_order_release); - const float _selectWidth = selectTextWidth + gapWidth; - if (_selectWidth != ult::selectWidth.load(std::memory_order_acquire)) - ult::selectWidth.store(_selectWidth, std::memory_order_release); - - const float buttonY = static_cast(cfg::FramebufferHeight - 73 + 1); - - // Draw back button rectangle - if (ult::touchingBack.load(std::memory_order_acquire)) { - renderer->drawRoundedRect(buttonStartX+2 - _halfGap, buttonY, _backWidth-1, 73.0f, 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)); - } - } - - // Build current bottom line - const std::string currentBottomLine = - "\uE0E1" + ult::GAP_2 + ult::BACK + ult::GAP_1 + - (!m_noClickableItems - ? "\uE0E0" + ult::GAP_2 + ult::OK + ult::GAP_1 - : ""); - - // Determine if we should use cached bottom text (first frame of new overlay) - const bool useCachedBottom = !g_cachedBottom.disabled && - !g_cachedBottom.bottomText.empty() && - g_cachedBottom.bottomText != currentBottomLine; - - const std::string& menuBottomLine = useCachedBottom ? g_cachedBottom.bottomText : currentBottomLine; - - // Render the text with special character handling - if (!deactivateOriginalFooter) { - static const std::vector specialChars = {"\uE0E1","\uE0E0","\uE0ED","\uE0EE","\uE0E5"}; - renderer->drawStringWithColoredSections(menuBottomLine, false, specialChars, buttonStartX, 693, 23, (bottomTextColor), (buttonColor)); - } - - if (this->m_contentElement != nullptr) - this->m_contentElement->frame(renderer); - - if (FullMode) { - if (!ult::useRightAlignment) - renderer->drawRect(447, 0, 448, 720, a(edgeSeparatorColor)); - else - renderer->drawRect(0, 0, 1, 720, a(edgeSeparatorColor)); - } - - // Update top cache after rendering for next frame - g_cachedTop.title = m_title; - g_cachedTop.subtitle = m_subtitle; - g_cachedTop.titleColor = {0xF, 0xF, 0xF, 0xF}; // HeaderOverlayFrame uses default white - g_cachedTop.widgetDrawn = false; // HeaderOverlayFrame doesn't use widgets - g_cachedTop.useDynamicLogo = false; // HeaderOverlayFrame doesn't use dynamic logo - g_cachedTop.disabled = false; - - // Update bottom cache after rendering for next frame - g_cachedBottom.bottomText = currentBottomLine; - g_cachedBottom.backWidth = ult::backWidth.load(std::memory_order_acquire); - g_cachedBottom.selectWidth = ult::selectWidth.load(std::memory_order_acquire); - g_cachedBottom.nextPageWidth = 0.0f; // HeaderOverlayFrame doesn't use next page - g_cachedBottom.disabled = false; - } - - - - virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override { - this->setBoundaries(parentX, parentY, parentWidth, parentHeight); - - if (this->m_contentElement != nullptr) { - //this->m_contentElement->setBoundaries(parentX + 35, parentY + 140, parentWidth - 85, parentHeight - 73 - 105); // CUSTOM MODIFICATION - this->m_contentElement->setBoundaries(parentX + 35, parentY + ult::activeHeaderHeight, parentWidth - 85, parentHeight - 73 - 105); - this->m_contentElement->invalidate(); - } - } - virtual inline Element* requestFocus(Element *oldFocus, FocusDirection direction) override { - if (this->m_contentElement != nullptr) - return this->m_contentElement->requestFocus(oldFocus, direction); - else - return nullptr; - } - - virtual inline bool onTouch(TouchEvent event, s32 currX, s32 currY, s32 prevX, s32 prevY, s32 initialX, s32 initialY) { - // Discard touches outside bounds - if (!this->m_contentElement->inBounds(currX, currY)) - return false; - - if (this->m_contentElement != nullptr) - return this->m_contentElement->onTouch(event, currX, currY, prevX, prevY, initialX, initialY); - else return false; - } - - /** - * @brief Sets the content of the frame - * - * @param content Element - */ - inline void setContent(Element *content) { - if (this->m_contentElement != nullptr) - delete this->m_contentElement; - - this->m_contentElement = content; - - if (content != nullptr) { - this->m_contentElement->setParent(this); - this->invalidate(); - } - } - - /** - * @brief Changes the title of the menu - * - * @param title Title to change to - */ - inline void setTitle(const std::string &title) { - this->m_title = title; - } - - /** - * @brief Changes the subtitle of the menu - * - * @param title Subtitle to change to - */ - inline void setSubtitle(const std::string &subtitle) { - this->m_subtitle = subtitle; - } - - protected: - Element *m_contentElement = nullptr; - - //std::string m_title, m_subtitle; - }; - #else - /** - * @brief The base frame which can contain another view with a customizable header - * - */ - class HeaderOverlayFrame : public Element { - public: - #if USING_WIDGET_DIRECTIVE - bool m_showWidget = false; - #endif - - HeaderOverlayFrame(u16 headerHeight = 175) : Element(), m_headerHeight(headerHeight) { - ult::activeHeaderHeight = headerHeight; - // Load the bitmap file into memory - ult::loadWallpaperFileWhenSafe(); - m_isItem = false; - - } - virtual ~HeaderOverlayFrame() { - if (this->m_contentElement != nullptr) - delete this->m_contentElement; - - if (this->m_header != nullptr) - delete this->m_header; - } - - virtual void draw(gfx::Renderer *renderer) override { - if (!ult::themeIsInitialized.exchange(true, std::memory_order_acq_rel)) { - tsl::initializeThemeVars(); - } - - renderer->fillScreen(a(defaultBackgroundColor)); - renderer->drawWallpaper(); - //renderer->drawRect(tsl::cfg::FramebufferWidth - 1, 0, 1, tsl::cfg::FramebufferHeight, a(0xF222)); - renderer->drawRect(15, tsl::cfg::FramebufferHeight - 73, tsl::cfg::FramebufferWidth - 30, 1, a(bottomSeparatorColor)); - - #if USING_WIDGET_DIRECTIVE - if (m_showWidget) - renderer->drawWidget(); - #endif - - // Get the exact gap width from ult::GAP_1 - const float gapWidth = renderer->getTextDimensions(ult::GAP_1, false, 23).first; - const float _halfGap = gapWidth / 2.0f; - if (_halfGap != ult::halfGap.load(std::memory_order_acquire)) - ult::halfGap.store(_halfGap, std::memory_order_release); - - // Calculate text dimensions for buttons without gaps - const float backTextWidth = renderer->getTextDimensions("\uE0E1" + ult::GAP_2 + ult::BACK, false, 23).first; - const float selectTextWidth = renderer->getTextDimensions("\uE0E0" + ult::GAP_2 + ult::OK, false, 23).first; - - // Store final widths with gap padding included - const float _backWidth = backTextWidth + gapWidth; - if (_backWidth != ult::backWidth.load(std::memory_order_acquire)) - ult::backWidth.store(_backWidth, std::memory_order_release); - const float _selectWidth = selectTextWidth + gapWidth; - if (_selectWidth != ult::selectWidth.load(std::memory_order_acquire)) - ult::selectWidth.store(_selectWidth, std::memory_order_release); - - // Set initial button position - static constexpr float buttonStartX = 30; - const float buttonY = static_cast(cfg::FramebufferHeight - 73 + 1); - - // Draw back button rectangle - if (ult::touchingBack.load(std::memory_order_acquire)) { - renderer->drawRoundedRect(buttonStartX+2 - _halfGap, buttonY, _backWidth-1, 73.0f, 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.exchange(false, std::memory_order_acq_rel)) - return handleJumpToBottom(oldFocus); - - if (jumpToTop.exchange(false, std::memory_order_acq_rel)) - return handleJumpToTop(oldFocus); - - if (skipDown.exchange(false, std::memory_order_acq_rel)) - return handleSkipDown(oldFocus); - - if (skipUp.exchange(false, std::memory_order_acq_rel)) - return handleSkipUp(oldFocus); - - - if (direction == FocusDirection::None) { - return handleInitialFocus(oldFocus); - } - else if (direction == FocusDirection::Down) { - return handleDownFocus(oldFocus); - } - else if (direction == FocusDirection::Up) { - return handleUpFocus(oldFocus); - } - - return oldFocus; - } - - inline void jumpToItem(const std::string& text = "", const std::string& value = "", bool exactMatch=true) { - - if (!text.empty() || !value.empty()) { - m_pendingJump = true; - m_jumpToText = text; - m_jumpToValue = value; - m_jumpToExactMatch = exactMatch; - } - - } - - virtual Element* getItemAtIndex(u32 index) { - return (m_items.size() <= index) ? nullptr : m_items[index]; - } - - virtual s32 getIndexInList(Element *element) { - auto it = std::find(m_items.begin(), m_items.end(), element); - return (it == m_items.end()) ? -1 : static_cast(it - m_items.begin()); - } - - virtual s32 getLastIndex() { - return static_cast(m_items.size()) - 1; - } - - virtual void setFocusedIndex(u32 index) { - if (m_items.size() > index) { - m_focusedIndex = index; - updateScrollOffset(); - } - } - - inline void onDirectionalKeyReleased() { - m_hasWrappedInCurrentSequence = false; - m_lastNavigationResult = NavigationResult::None; - m_isHolding = false; - m_stoppedAtBoundary = false; - m_lastNavigationTime = 0; - m_lastScrollTime = 0; - } - - inline void disableCaching() { - m_cachingDisabled = true; - //clearFrameCache(); - g_disableMenuCacheOnReturn.store(true, std::memory_order_release); - } - - 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: - - // 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() { - - 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) { - const float emergencySpeed = (itemBottom < m_offset || itemTop > viewBottom) ? 0.9f : 0.6f; - - m_offset += diff * emergencySpeed; - m_scrollVelocity = diff * 0.3f; - s_currentScrollVelocity.store(m_scrollVelocity, std::memory_order_release); - - if (prevOffset != m_offset) { - invalidate(); - prevOffset = m_offset; - } - return; - } - } - - // Rest of your existing smooth scrolling logic... - const bool isLargeJump = distance > getHeight() * 1.5f; - const bool isFromRest = std::abs(m_scrollVelocity) < 2.0f; - - if (isLargeJump && isFromRest) { - static constexpr float gentleAcceleration = 0.08f; - static constexpr float gentleDamping = 0.85f; - - const float targetVelocity = diff * gentleAcceleration; - m_scrollVelocity += (targetVelocity - m_scrollVelocity) * gentleDamping; - } else { - const float urgency = std::min(distance / getHeight(), 1.0f); - const float accelerationFactor = 0.18f + (0.24f * urgency); - const float dampingFactor = 0.48f - (0.18f * urgency); - - const float targetVelocity = diff * accelerationFactor; - m_scrollVelocity += (targetVelocity - m_scrollVelocity) * dampingFactor; - } - - // Apply velocity - m_offset += m_scrollVelocity; - - // ENHANCED overshoot prevention with better boundary handling - if ((m_scrollVelocity > 0 && m_offset > m_nextOffset) || - (m_scrollVelocity < 0 && m_offset < m_nextOffset)) { - m_offset = m_nextOffset; - m_scrollVelocity = 0.0f; - } - - // ADDITIONAL: Force exact boundary values - if (m_nextOffset == 0.0f && m_offset < 1.0f) { - m_offset = 0.0f; - m_scrollVelocity = 0.0f; - } else if (m_nextOffset == maxOffset && m_offset > maxOffset - 1.0f) { - m_offset = maxOffset; - m_scrollVelocity = 0.0f; - } - - s_currentScrollVelocity.store(m_scrollVelocity, std::memory_order_release); - - } else if (Element::getInputMode() == InputMode::TouchScroll) { - // Your existing touch scroll logic... - m_offset = m_nextOffset; - m_scrollVelocity = 0.0f; - - if (m_touchScrollActive) { - const float viewCenter = m_offset + (getHeight() / 2.0f); - float accumHeight = 0.0f; - - //float itemHeight, itemCenter; - for (size_t i = 0; i < m_items.size(); ++i) { - const float itemHeight = m_items[i]->getHeight(); - const float itemCenter = accumHeight + (itemHeight / 2.0f); - - if (itemCenter >= viewCenter) { - m_focusedIndex = i; - break; - } - - accumHeight += itemHeight; - } - } - } - - if (prevOffset != m_offset) { - invalidate(); - prevOffset = m_offset; - } - } - - Element* handleInitialFocus(Element* oldFocus) { - const size_t itemCount = m_items.size(); - if (itemCount == 0) return nullptr; - - size_t startIndex = 0; - - // Calculate starting index based on current scroll position - if (!oldFocus && m_offset > 0) { - float elementHeight = 0.0f; - const size_t maxIndex = itemCount - 1; - while (elementHeight < m_offset && startIndex < maxIndex) { - elementHeight += m_items[startIndex]->getHeight(); - ++startIndex; - } - } - - //resetNavigationState(); - - // Save current offset to prevent scroll jumping - const float savedOffset = m_offset; - const float savedNextOffset = m_nextOffset; - - // Single loop with wraparound logic - visits each item exactly once - for (size_t count = 0; count < itemCount; ++count) { - const size_t i = (startIndex + count) % itemCount; - - if (!m_items[i]->isTable()) { - Element* const newFocus = m_items[i]->requestFocus(oldFocus, FocusDirection::None); - if (newFocus && newFocus != oldFocus) { - m_focusedIndex = i; - m_offset = savedOffset; - m_nextOffset = savedNextOffset; - return newFocus; - } - } - } - - return nullptr; - } - - - inline Element* handleDownFocus(Element* oldFocus) { - static bool triggerShakeOnce = true; - const bool atBottom = isAtBottom(); - 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); - } - } - - // If holding and at boundary, try to scroll first - if (m_isHolding && m_stoppedAtBoundary && !atBottom) { - scrollDown(); - m_stoppedAtBoundary = false; - return oldFocus; - } - - Element* result = navigateDown(oldFocus); - - if (result != oldFocus) { - m_lastNavigationResult = NavigationResult::Success; - m_stoppedAtBoundary = false; - triggerShakeOnce = true; // This resets it for THIS function - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - return result; - } - - // Check if we can still scroll down - if (!atBottom) { - scrollDown(); - triggerShakeOnce = true; // ADDED: Reset when scrolling away from boundary - return oldFocus; - } - - // At absolute bottom - check for wrapping (single tap) - if (!m_isHolding && !m_hasWrappedInCurrentSequence && atBottom) { - s_directionalKeyReleased.store(false, std::memory_order_release); - m_hasWrappedInCurrentSequence = true; - m_lastNavigationResult = NavigationResult::Wrapped; - - //if (result->m_isItem) { - triggerShakeOnce = true; // Reset when wrapping - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - //} - return handleJumpToTop(oldFocus); - } - - // Set boundary flag (for holding) - if (m_isHolding && atBottom) { - m_stoppedAtBoundary = true; - if (triggerShakeOnce) { - if (result->m_isItem) { - triggerRumbleClick.store(true, std::memory_order_release); - triggerWallSound.store(true, std::memory_order_release); - - for (ssize_t i = static_cast(m_focusedIndex); i >= 0; --i) { - if (m_items[i]->m_isItem) { - m_items[i]->shakeHighlight(FocusDirection::Down); - break; - } - } - } else { - triggerRumbleClick.store(true, std::memory_order_release); - triggerWallSound.store(true, std::memory_order_release); - } - triggerShakeOnce = false; - } - } else if (!m_isHolding) { - triggerShakeOnce = true; - } - - m_lastNavigationResult = NavigationResult::HitBoundary; - return oldFocus; - } - - inline Element* handleUpFocus(Element* oldFocus) { - static bool triggerShakeOnce = true; - const bool atTop = isAtTop(); - 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); - } - } - - // If holding and at boundary, try to scroll first - if (m_isHolding && m_stoppedAtBoundary && !atTop) { - scrollUp(); - m_stoppedAtBoundary = false; - return oldFocus; - } - - Element* result = navigateUp(oldFocus); - - if (result != oldFocus) { - m_lastNavigationResult = NavigationResult::Success; - m_stoppedAtBoundary = false; - triggerShakeOnce = true; // This resets it for THIS function - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - return result; - } - - // Check if we can still scroll up - if (!atTop) { - scrollUp(); - triggerShakeOnce = true; // ADDED: Reset when scrolling away from boundary - return oldFocus; - } - - // At absolute top - check for wrapping (single tap) - if (!m_isHolding && !m_hasWrappedInCurrentSequence && atTop) { - s_directionalKeyReleased.store(false, std::memory_order_release); - m_hasWrappedInCurrentSequence = true; - m_lastNavigationResult = NavigationResult::Wrapped; - - //if (result->m_isItem) { - triggerShakeOnce = true; // Reset when wrapping - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - //} - return handleJumpToBottom(oldFocus); - } - - // Set boundary flag (for holding) - if (m_isHolding && atTop) { - m_stoppedAtBoundary = true; - if (triggerShakeOnce) { - if (result->m_isItem) { - triggerRumbleClick.store(true, std::memory_order_release); - triggerWallSound.store(true, std::memory_order_release); - - for (size_t i = m_focusedIndex; i < m_items.size(); ++i) { - if (m_items[i]->m_isItem) { - m_items[i]->shakeHighlight(FocusDirection::Up); - break; - } - } - } else { - triggerRumbleClick.store(true, std::memory_order_release); - triggerWallSound.store(true, std::memory_order_release); - } - triggerShakeOnce = false; - } - } else if (!m_isHolding) { - 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); - } - - // Jump to Bottom (original behavior + fixed trigger condition) - Element* handleJumpToBottom(Element* oldFocus) { - if (m_items.empty()) return oldFocus; - - invalidate(); - resetNavigationState(); - jumpToBottom.store(false, std::memory_order_release); - - const float targetOffset = (m_listHeight > getHeight()) ? - static_cast(m_listHeight - getHeight()) : 0.0f; - static constexpr float tolerance = 5.0f; - - // Find last focusable item (search backward) - size_t lastFocusableIndex = m_items.size(); - for (ssize_t i = static_cast(m_items.size()) - 1; i >= 0; --i) { - Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); - if (test) { - lastFocusableIndex = static_cast(i); - break; - } - } - - if (lastFocusableIndex == m_items.size()) - return oldFocus; // no focusable items - - bool alreadyAtBottom = (m_focusedIndex == lastFocusableIndex) && - (std::abs(m_nextOffset - targetOffset) <= tolerance); - if (alreadyAtBottom) - return oldFocus; - - const float oldOffset = m_nextOffset; - m_focusedIndex = lastFocusableIndex; - m_nextOffset = targetOffset; - - Element* newFocus = m_items[lastFocusableIndex]->requestFocus(oldFocus, FocusDirection::None); - - // Trigger feedback if offset or focus changed - if ((newFocus && newFocus != oldFocus) || - (std::abs(m_nextOffset - oldOffset) > tolerance)) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - } - - return newFocus ? newFocus : oldFocus; - } - - - // Jump to Top (original behavior + fixed trigger condition) - Element* handleJumpToTop(Element* oldFocus) { - if (m_items.empty()) return oldFocus; - - invalidate(); - resetNavigationState(); - jumpToTop.store(false, std::memory_order_release); - - static constexpr float targetOffset = 0.0f; - static constexpr float tolerance = 5.0f; - - // Find first focusable item (search forward) - size_t firstFocusableIndex = m_items.size(); - for (size_t i = 0; i < m_items.size(); ++i) { - Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); - if (test) { - firstFocusableIndex = i; - break; - } - } - - if (firstFocusableIndex == m_items.size()) - return oldFocus; // no focusable items - - bool alreadyAtTop = (m_focusedIndex == firstFocusableIndex) && - (std::abs(m_nextOffset - targetOffset) <= tolerance); - if (alreadyAtTop) - return oldFocus; - - const float oldOffset = m_nextOffset; - m_focusedIndex = firstFocusableIndex; - m_nextOffset = targetOffset; - - Element* newFocus = m_items[firstFocusableIndex]->requestFocus(oldFocus, FocusDirection::None); - - // Trigger feedback if offset or focus changed - if ((newFocus && newFocus != oldFocus) || - (std::abs(m_nextOffset - oldOffset) > tolerance)) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - } - - return newFocus ? newFocus : oldFocus; - } - - Element* handleSkipDown(Element* oldFocus) { - if (m_items.empty()) return oldFocus; - - invalidate(); - resetNavigationState(); - - const float targetOffset = (m_listHeight > getHeight()) ? - static_cast(m_listHeight - getHeight()) : 0.0f; - static constexpr float tolerance = 0.0f; - - // Find last focusable item - size_t lastFocusableIndex = m_items.size(); - for (ssize_t i = static_cast(m_items.size()) - 1; i >= 0; --i) { - Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); - if (test) { - lastFocusableIndex = static_cast(i); - break; - } - } - - const bool alreadyAtBottom = (lastFocusableIndex < m_items.size()) && - (m_focusedIndex == lastFocusableIndex) && - (std::abs(m_nextOffset - targetOffset) <= tolerance); - - if (alreadyAtBottom) return oldFocus; - - const float viewHeight = static_cast(getHeight()); - const float maxOffset = (m_listHeight > viewHeight) ? static_cast(m_listHeight - viewHeight) : 0.0f; - const float targetViewportTop = std::min(m_offset + viewHeight, maxOffset); - - const float actualTravelDistance = targetViewportTop - m_offset; - const bool traveledFullViewport = (actualTravelDistance >= viewHeight - tolerance); - const float targetViewportCenter = targetViewportTop + (viewHeight / 2.0f + VIEW_CENTER_OFFSET); - - float itemTop = 0.0f; - size_t targetIndex = 0; - bool foundFocusable = false; - float bestDistance = std::numeric_limits::max(); - - for (size_t i = 0; i < m_items.size(); ++i) { - const float itemHeight = m_items[i]->getHeight(); - const float itemCenter = itemTop + (itemHeight / 2.0f); - const float distanceFromCenter = std::abs(itemCenter - targetViewportCenter); - - Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); - if (test && test->m_isItem && distanceFromCenter < bestDistance) { - targetIndex = i; - bestDistance = distanceFromCenter; - foundFocusable = true; - } - - itemTop += itemHeight; - } - - const float oldOffset = m_nextOffset; - - if (foundFocusable) { - bool nearBottom = true; - if (targetIndex > m_focusedIndex && traveledFullViewport) { - m_focusedIndex = targetIndex; - nearBottom = false; - } - isTableScrolling.store(false, std::memory_order_release); - updateScrollOffset(); - - Element* newFocus = m_items[targetIndex]->requestFocus(oldFocus, FocusDirection::None); - - if (newFocus && newFocus != oldFocus && !nearBottom && traveledFullViewport) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - return newFocus; - } else { - return handleJumpToBottom(oldFocus); - } - } else { - // Scroll viewport even if no focusable items - isTableScrolling.store(true, std::memory_order_release); - m_nextOffset = targetViewportTop; - - if (std::abs(m_nextOffset - oldOffset) > 0.0f) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - } - - // Focus last visible focusable item - float searchItemTop = 0.0f; - size_t lastVisibleFocusable = m_focusedIndex; - - for (size_t i = 0; i < m_items.size(); ++i) { - const float itemHeight = m_items[i]->getHeight(); - const float itemBottom = searchItemTop + itemHeight; - - if (searchItemTop >= targetViewportTop + viewHeight) break; - - if (itemBottom > targetViewportTop) { - Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); - if (test && test->m_isItem) lastVisibleFocusable = i; - } - - searchItemTop += itemHeight; - } - - if (lastVisibleFocusable != m_focusedIndex) { - m_focusedIndex = lastVisibleFocusable; - Element* newFocus = m_items[m_focusedIndex]->requestFocus(oldFocus, FocusDirection::None); - if (newFocus && newFocus != oldFocus) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - return newFocus; - } - } - } - - return oldFocus; - } - - Element* handleSkipUp(Element* oldFocus) { - if (m_items.empty()) return oldFocus; - - invalidate(); - resetNavigationState(); - - static constexpr float targetOffset = 0.0f; - static constexpr float tolerance = 0.0f; - - // Find first focusable item - size_t firstFocusableIndex = m_items.size(); - for (size_t i = 0; i < m_items.size(); ++i) { - Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); - if (test) { - firstFocusableIndex = i; - break; - } - } - - const bool alreadyAtTop = (firstFocusableIndex < m_items.size()) && - (m_focusedIndex == firstFocusableIndex) && - (std::abs(m_nextOffset - targetOffset) <= tolerance); - - if (alreadyAtTop) return oldFocus; - - const float viewHeight = static_cast(getHeight()); - const float targetViewportTop = std::max(0.0f, m_offset - viewHeight); - - const float actualTravelDistance = m_offset - targetViewportTop; - const bool traveledFullViewport = (actualTravelDistance >= viewHeight - tolerance); - const float targetViewportCenter = targetViewportTop + (viewHeight / 2.0f + VIEW_CENTER_OFFSET); - - float itemTop = 0.0f; - size_t targetIndex = 0; - bool foundFocusable = false; - float bestDistance = std::numeric_limits::max(); - - for (size_t i = 0; i < m_items.size(); ++i) { - const float itemHeight = m_items[i]->getHeight(); - const float itemCenter = itemTop + (itemHeight / 2.0f); - const float distanceFromCenter = std::abs(itemCenter - targetViewportCenter); - - Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); - if (test && test->m_isItem && distanceFromCenter < bestDistance) { - targetIndex = i; - bestDistance = distanceFromCenter; - foundFocusable = true; - } - - itemTop += itemHeight; - } - - const float oldOffset = m_nextOffset; - - if (foundFocusable) { - bool nearTop = true; - if (targetIndex < m_focusedIndex && traveledFullViewport) { - m_focusedIndex = targetIndex; - nearTop = false; - } - isTableScrolling.store(false, std::memory_order_release); - updateScrollOffset(); - - Element* newFocus = m_items[targetIndex]->requestFocus(oldFocus, FocusDirection::None); - - if (newFocus && newFocus != oldFocus && !nearTop && traveledFullViewport) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - return newFocus; - } else { - return handleJumpToTop(oldFocus); - } - } else { - // Scroll viewport even if no focusable items - isTableScrolling.store(true, std::memory_order_release); - m_nextOffset = targetViewportTop; - - if (std::abs(m_nextOffset - oldOffset) > 0.0f) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - } - - // Focus first visible focusable item - float searchItemTop = 0.0f; - size_t firstVisibleFocusable = m_focusedIndex; - - for (size_t i = 0; i < m_items.size(); ++i) { - const float itemHeight = m_items[i]->getHeight(); - const float itemBottom = searchItemTop + itemHeight; - - if (itemBottom > targetViewportTop && searchItemTop < targetViewportTop + viewHeight) { - Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); - if (test && test->m_isItem) { - firstVisibleFocusable = i; - break; - } - } - - searchItemTop += itemHeight; - } - - if (firstVisibleFocusable != m_focusedIndex) { - m_focusedIndex = firstVisibleFocusable; - Element* newFocus = m_items[m_focusedIndex]->requestFocus(oldFocus, FocusDirection::None); - if (newFocus && newFocus != oldFocus) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - return newFocus; - } - } - } - - return oldFocus; - } - - - inline void initializePrefixSums() { - prefixSums.clear(); - prefixSums.resize(m_items.size() + 1, 0.0f); - - for (size_t i = 1; i < prefixSums.size(); ++i) { - prefixSums[i] = prefixSums[i - 1] + m_items[i - 1]->getHeight(); - } - } - - - // Keep your EXACT original updateScrollOffset() method unchanged: - virtual void updateScrollOffset() { - if (Element::getInputMode() != InputMode::Controller) return; - - if (m_listHeight <= getHeight()) { - m_nextOffset = m_offset = 0; - return; - } - - // Calculate position of focused item - float itemPos = 0.0f; - for (size_t i = 0; i < m_focusedIndex && i < m_items.size(); ++i) { - itemPos += m_items[i]->getHeight(); - } - - // Get the focused item's height - const float itemHeight = (m_focusedIndex < m_items.size()) ? m_items[m_focusedIndex]->getHeight() : 0.0f; - - // Calculate viewport height - const float viewHeight = static_cast(getHeight()); - - // FIXED: Special handling for the first focusable item - //if (m_focusedIndex == 0 || itemPos <= viewHeight * 0.3f) { - // // For items at the very top or very close to top, snap to absolute zero - // m_nextOffset = 0.0f; - // return; - //} - - // FIXED: Special handling for items near the bottom - const float maxOffset = static_cast(m_listHeight - getHeight()); - //const float itemBottom = itemPos + itemHeight; - //if (itemBottom >= m_listHeight - (viewHeight * 0.3f)) { - // // For items near the bottom, snap to max offset - // m_nextOffset = maxOffset; - // return; - //} - - // For middle items, use centering logic - const float itemCenterPos = itemPos + (itemHeight / 2.0f); - const float viewportCenter = viewHeight / 2.0f + VIEW_CENTER_OFFSET + 0.5f; // add slight offset - //float idealOffset = itemCenterPos - viewportCenter; - - // Clamp to valid scroll bounds - const float idealOffset = std::max(0.0f, std::min(itemCenterPos - viewportCenter, maxOffset)); - - // Set target for smooth animation - m_nextOffset = idealOffset; - - //m_nextOffset = std::max(0.0f, std::min(itemPos + itemHeight * 0.5f - (viewHeight * 0.5f + 7.0f), maxOffset)); - } - - }; - - - - - /** - * @brief A item that goes into a list - * - */ - class ListItem : public Element { - public: - u32 width, height; - u64 m_touchStartTime_ns; - bool isLocked = false; - - #if IS_LAUNCHER_DIRECTIVE - ListItem(const std::string& text, const std::string& value = "", bool isMini = false, bool useScriptKey = true) - : Element(), m_text(text), m_value(value), m_listItemHeight(isMini ? tsl::style::MiniListItemDefaultHeight : tsl::style::ListItemDefaultHeight) { - m_isItem = true; - m_flags.m_useScriptKey = useScriptKey; - m_flags.m_useClickAnimation = true; - m_text_clean = m_text; - ult::removeTag(m_text_clean); - applyInitialTranslations(); - if (!value.empty()) applyInitialTranslations(true); - } - #else - ListItem(const std::string& text, const std::string& value = "", bool isMini = false) - : Element(), m_text(text), m_value(value), m_listItemHeight(isMini ? tsl::style::MiniListItemDefaultHeight : tsl::style::ListItemDefaultHeight) { - m_isItem = true; - m_flags.m_useClickAnimation = true; - m_text_clean = m_text; - ult::removeTag(m_text_clean); - applyInitialTranslations(); - if (!value.empty()) applyInitialTranslations(true); - } - #endif - - virtual ~ListItem() = default; - - virtual void draw(gfx::Renderer *renderer) override { - const bool useClickTextColor = m_flags.m_touched && Element::getInputMode() == InputMode::Touch && ult::touchInBounds; - - if (useClickTextColor) [[unlikely]] { - auto drawFunc = ult::expandedMemory ? &gfx::Renderer::drawRectMultiThreaded : &gfx::Renderer::drawRect; - (renderer->*drawFunc)(this->getX() + 4, this->getY(), this->getWidth() - 8, this->getHeight(), aWithOpacity(clickColor)); - } - - const s16 yOffset = ((tsl::style::ListItemDefaultHeight - m_listItemHeight) >> 1) + 1; - - if (!m_maxWidth) [[unlikely]] { - calculateWidths(renderer); - } - - // Optimized separator drawing - const float topBound = this->getTopBound(); - const float bottomBound = this->getBottomBound(); - static float lastBottomBound = 0.0f; - - if (lastBottomBound != topBound) [[unlikely]] { - renderer->drawRect(this->getX() + 4, topBound, this->getWidth() + 10, 1, a(separatorColor)); - } - renderer->drawRect(this->getX() + 4, bottomBound, this->getWidth() + 10, 1, a(separatorColor)); - lastBottomBound = bottomBound; - - #if IS_LAUNCHER_DIRECTIVE - static const std::vector specialChars = {ult::STAR_SYMBOL}; - #else - static const std::vector specialChars = {ult::DIVIDER_SYMBOL}; - #endif - // Fast path for non-truncated text - if (!m_flags.m_truncated) [[likely]] { - const Color textColor = m_focused - ? (!ult::useSelectionText - ? (m_flags.m_hasCustomTextColor ? m_customTextColor : defaultTextColor) - : (useClickTextColor - ? clickTextColor - : selectedTextColor)) - : (m_flags.m_hasCustomTextColor - ? m_customTextColor - : (useClickTextColor - ? clickTextColor - : defaultTextColor)); - #if IS_LAUNCHER_DIRECTIVE - renderer->drawStringWithColoredSections(m_text_clean, false, specialChars, this->getX() + 19, this->getY() + 45 - yOffset, 23, - textColor, (m_focused ? starColor : selectionStarColor)); - #else - renderer->drawStringWithColoredSections(m_text_clean, false, specialChars, this->getX() + 19, this->getY() + 45 - yOffset, 23, - textColor, textSeparatorColor); - #endif - } else { - drawTruncatedText(renderer, yOffset, useClickTextColor, specialChars); - } - - if (!m_value.empty()) [[likely]] { - drawValue(renderer, yOffset, useClickTextColor); - } - } - - virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override { - this->setBoundaries(this->getX() + 3, this->getY(), this->getWidth() + 9, m_listItemHeight); - } - - virtual bool onClick(u64 keys) override { - if (keys & KEY_A) [[likely]] { - triggerRumbleClick.store(true, std::memory_order_release); - - if (isLocked) - triggerWallSound.store(true, std::memory_order_release); - else if (m_value.find(ult::CAPITAL_ON_STR) != std::string::npos) - triggerOffSound.store(true, std::memory_order_release); - else if (m_value.find(ult::CAPITAL_OFF_STR) != std::string::npos) - triggerOnSound.store(true, std::memory_order_release); - else - triggerEnterSound.store(true, std::memory_order_release); - - if (m_flags.m_useClickAnimation) - triggerClickAnimation(); - } else if (keys & (KEY_UP | KEY_DOWN | KEY_LEFT | KEY_RIGHT)) [[unlikely]] { - m_clickAnimationProgress = 0; - } - //if (keys & KEY_B) { - // triggerRumbleDoubleClick.store(true, std::memory_order_release); - // triggerExitSound.store(true, std::memory_order_release); - // - //} - return Element::onClick(keys); - } - - virtual bool onTouch(TouchEvent event, s32 currX, s32 currY, s32 prevX, s32 prevY, s32 initialX, s32 initialY) override { - if (event == TouchEvent::Touch) [[likely]] { - if ((m_flags.m_touched = inBounds(currX, currY))) [[likely]] { - m_touchStartTime_ns = armTicksToNs(armGetSystemTick()); - } - return false; - } - - if (event == TouchEvent::Release && m_flags.m_touched) [[likely]] { - m_flags.m_touched = false; - if (Element::getInputMode() == InputMode::Touch) [[likely]] { - #if IS_LAUNCHER_DIRECTIVE - const s64 keyToUse = determineKeyOnTouchRelease(m_flags.m_useScriptKey); - #else - const s64 keyToUse = determineKeyOnTouchRelease(false); - #endif - const bool handled = onClick(keyToUse); - m_clickAnimationProgress = 0; - return handled; - } - } - return false; - } - - virtual void setFocused(bool state) override { - if (state != m_focused) [[likely]] { - m_flags.m_scroll = false; - m_scrollOffset = 0; - timeIn_ns = armTicksToNs(armGetSystemTick()); - Element::setFocused(state); - } - } - - virtual inline Element* requestFocus(Element *oldFocus, FocusDirection direction) override { - return this; - } - - inline void setText(const std::string& text) { - if (m_text != text) [[likely]] { - m_text = text; - m_text_clean = m_text; - ult::removeTag(m_text_clean); - resetTextProperties(); - applyInitialTranslations(); - } - } - - inline void setValue(const std::string& value, bool faint = false) { - if (m_value != value || m_flags.m_faint != faint) [[likely]] { - m_value = value; - m_flags.m_faint = faint; - m_maxWidth = 0; - if (!value.empty()) applyInitialTranslations(true); - } - } - - inline void setTextColor(Color color) { - m_customTextColor = color; - m_flags.m_hasCustomTextColor = true; - } - - inline void setValueColor(Color color) { - m_customValueColor = color; - m_flags.m_hasCustomValueColor = true; - } - - inline void clearTextColor() { - m_flags.m_hasCustomTextColor = false; - } - - inline void clearValueColor() { - m_flags.m_hasCustomValueColor = false; - } - - inline void disableClickAnimation() { - m_flags.m_useClickAnimation = false; - } - - inline void enableClickAnimation() { - m_flags.m_useClickAnimation = true; - } - - inline const std::string& getText() const noexcept { - return m_text; - } - - inline const std::string& getValue() const noexcept { - return m_value; - } - - virtual bool matchesJumpCriteria(const std::string& jumpText, const std::string& jumpValue, bool exactMatch=true) const { - if (jumpText.empty() && jumpValue.empty()) return false; - - bool textMatches, valueMatches; - if (exactMatch) { - textMatches = (m_text == jumpText); - valueMatches = (m_value == jumpValue); - } else { // contains check - textMatches = (m_text.find(jumpText) != std::string::npos); - valueMatches = (m_value.find(jumpValue) != std::string::npos); - } - - if (jumpText.empty() && !jumpValue.empty()) - return valueMatches; - else if (!jumpText.empty() && jumpValue.empty()) - return textMatches; - - return (textMatches && valueMatches); - } - - protected: - u64 timeIn_ns; - std::string m_text; - std::string m_text_clean; - std::string m_value; - std::string m_scrollText; - std::string m_ellipsisText; - u16 m_listItemHeight; // Changed from u32 to u16 - - - // Bitfield for boolean flags - saves ~7 bytes per instance - struct { - bool m_scroll : 1; - bool m_truncated : 1; - bool m_faint : 1; - bool m_touched : 1; - bool m_hasCustomTextColor : 1; - bool m_hasCustomValueColor : 1; - bool m_useClickAnimation : 1; - #if IS_LAUNCHER_DIRECTIVE - bool m_useScriptKey : 1; - #endif - } m_flags = {}; - - Color m_customTextColor = {0}; - Color m_customValueColor = {0}; - - float m_scrollOffset = 0.0f; - u16 m_maxWidth = 0; // Changed from u32 to u16 - u16 m_textWidth = 0; // Changed from u32 to u16 - - private: - // Consolidated scroll constants struct - struct ScrollConstants { - double totalCycleDuration; - double delayDuration; - double scrollDuration; - double accelTime; - double constantVelocityTime; - double maxVelocity; - double accelDistance; - double constantVelocityDistance; - double minScrollDistance; - double invAccelTime; - double invDecelTime; - double invBillion; - bool initialized = false; - }; - - void applyInitialTranslations(bool isValue = false) { - std::string& target = isValue ? m_value : m_text_clean; - ult::applyLangReplacements(target, isValue); - ult::convertComboToUnicode(target); - - #ifdef UI_OVERRIDE_PATH - { - const std::string originalKey = target; - - std::shared_lock readLock(tsl::gfx::s_translationCacheMutex); - auto translatedIt = ult::translationCache.find(originalKey); - if (translatedIt != ult::translationCache.end()) { - target = translatedIt->second; - } else { - readLock.unlock(); - std::unique_lock writeLock(tsl::gfx::s_translationCacheMutex); - - translatedIt = ult::translationCache.find(originalKey); - if (translatedIt != ult::translationCache.end()) { - target = translatedIt->second; - } else { - ult::translationCache[originalKey] = originalKey; - } - } - } - #endif - } - - void calculateWidths(gfx::Renderer* renderer) { - if (m_value.empty()) { - m_maxWidth = getWidth() - 62; - } else { - m_maxWidth = getWidth() - renderer->getTextDimensions(m_value, false, 20).first - 66; - } - - const u16 width = renderer->getTextDimensions(m_text_clean, false, 23).first; - m_flags.m_truncated = width > m_maxWidth + 20; - - if (m_flags.m_truncated) [[unlikely]] { - m_scrollText.clear(); - m_scrollText.reserve(m_text_clean.size() * 2 + 8); - - m_scrollText.append(m_text_clean).append(" "); - m_textWidth = renderer->getTextDimensions(m_scrollText, false, 23).first; - m_scrollText.append(m_text_clean); - - m_ellipsisText = renderer->limitStringLength(m_text_clean, false, 23, m_maxWidth); - } else { - m_textWidth = width; - } - } - - void drawTruncatedText(gfx::Renderer* renderer, s32 yOffset, bool useClickTextColor, const std::vector& specialSymbols = {}) { - if (m_focused) { - renderer->enableScissoring(getX() + 6, 97, m_maxWidth + (m_value.empty() ? 49 : 27), tsl::cfg::FramebufferHeight - 170); - #if IS_LAUNCHER_DIRECTIVE - renderer->drawStringWithColoredSections(m_scrollText, false, specialSymbols, getX() + 19 - static_cast(m_scrollOffset), getY() + 45 - yOffset, 23, - !ult::useSelectionText ? defaultTextColor: (useClickTextColor ? clickTextColor : selectedTextColor), (starColor)); - #else - renderer->drawStringWithColoredSections(m_scrollText, false, specialSymbols, getX() + 19 - static_cast(m_scrollOffset), getY() + 45 - yOffset, 23, - !ult::useSelectionText ? defaultTextColor: (useClickTextColor ? clickTextColor : selectedTextColor), (textSeparatorColor)); - #endif - renderer->disableScissoring(); - handleScrolling(); - } else { - #if IS_LAUNCHER_DIRECTIVE - renderer->drawStringWithColoredSections(m_ellipsisText, false, specialSymbols, getX() + 19, getY() + 45 - yOffset, 23, - m_flags.m_hasCustomTextColor ? m_customTextColor : (useClickTextColor ? clickTextColor : defaultTextColor), (starColor)); - #else - renderer->drawStringWithColoredSections(m_ellipsisText, false, specialSymbols, getX() + 19, getY() + 45 - yOffset, 23, - m_flags.m_hasCustomTextColor ? m_customTextColor : (useClickTextColor ? clickTextColor : defaultTextColor), (textSeparatorColor)); - #endif - } - } - - void handleScrolling() { - static ScrollConstants sc; - static u64 lastUpdateTime = 0; - static float cachedScrollOffset = 0.0f; - - const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); - const u64 elapsed_ns = currentTime_ns - timeIn_ns; - - if (!sc.initialized || sc.minScrollDistance != static_cast(m_textWidth)) { - sc.delayDuration = 2.0; - static constexpr double pauseDuration = 1.0; - sc.maxVelocity = 166.0; - sc.accelTime = 0.5; - static constexpr double decelTime = 0.5; - - sc.minScrollDistance = static_cast(m_textWidth); - sc.accelDistance = 0.5 * sc.maxVelocity * sc.accelTime; - const double decelDistance = 0.5 * sc.maxVelocity * decelTime; - sc.constantVelocityDistance = std::max(0.0, sc.minScrollDistance - sc.accelDistance - decelDistance); - sc.constantVelocityTime = sc.constantVelocityDistance / sc.maxVelocity; - sc.scrollDuration = sc.accelTime + sc.constantVelocityTime + decelTime; - sc.totalCycleDuration = sc.delayDuration + sc.scrollDuration + pauseDuration; - - sc.invAccelTime = 1.0 / sc.accelTime; - sc.invDecelTime = 1.0 / decelTime; - sc.invBillion = 1.0 / 1000000000.0; - - sc.initialized = true; - } - - const double elapsed_seconds = static_cast(elapsed_ns) * sc.invBillion; - - if (currentTime_ns - lastUpdateTime >= 8333333ULL) { - const double cyclePosition = std::fmod(elapsed_seconds, sc.totalCycleDuration); - - if (cyclePosition < sc.delayDuration) [[likely]] { - cachedScrollOffset = 0.0f; - } else if (cyclePosition < sc.delayDuration + sc.scrollDuration) [[likely]] { - const double scrollTime = cyclePosition - sc.delayDuration; - double distance; - - if (scrollTime <= sc.accelTime) { - const double t = scrollTime * sc.invAccelTime; - const double smoothT = t * t; - distance = smoothT * sc.accelDistance; - } else if (scrollTime <= sc.accelTime + sc.constantVelocityTime) { - const double constantTime = scrollTime - sc.accelTime; - distance = sc.accelDistance + (constantTime * sc.maxVelocity); - } else { - const double decelStartTime = sc.accelTime + sc.constantVelocityTime; - const double t = (scrollTime - decelStartTime) * sc.invDecelTime; - const double oneMinusT = 1.0 - t; - const double smoothT = 1.0 - oneMinusT * oneMinusT; - distance = sc.accelDistance + sc.constantVelocityDistance + (smoothT * (sc.minScrollDistance - sc.accelDistance - sc.constantVelocityDistance)); - } - - cachedScrollOffset = static_cast(distance < sc.minScrollDistance ? distance : sc.minScrollDistance); - } else [[unlikely]] { - cachedScrollOffset = static_cast(m_textWidth); - } - - lastUpdateTime = currentTime_ns; - } - - m_scrollOffset = cachedScrollOffset; - - if (elapsed_seconds >= sc.totalCycleDuration) [[unlikely]] { - timeIn_ns = currentTime_ns; - } - } - - void drawValue(gfx::Renderer* renderer, s32 yOffset, bool useClickTextColor) { - const s32 xPosition = getX() + m_maxWidth + 47; - const s32 yPosition = getY() + 45 - yOffset-1; - static constexpr s32 fontSize = 20; - - static bool lastRunningInterpreter = false; - const auto textColor = determineValueTextColor(useClickTextColor, lastRunningInterpreter); - - if (m_value != ult::INPROGRESS_SYMBOL) [[likely]] { - static const std::vector specialChars = {ult::DIVIDER_SYMBOL}; - renderer->drawStringWithColoredSections(m_value, false, specialChars, xPosition, yPosition, fontSize, textColor, textSeparatorColor); - } else { - drawThrobber(renderer, xPosition, yPosition, fontSize, textColor); - } - lastRunningInterpreter = ult::runningInterpreter.load(std::memory_order_acquire); - } - - Color determineValueTextColor(bool useClickTextColor, bool lastRunningInterpreter) const { - if (m_focused && ult::useSelectionValue) { - if (m_value == ult::DROPDOWN_SYMBOL || m_value == ult::OPTION_SYMBOL) { - return useClickTextColor ? (clickTextColor) : - (m_flags.m_faint ? offTextColor : (useClickTextColor ? clickTextColor : (ult::useSelectionText ? selectedTextColor : defaultTextColor))); - } - - const bool isRunning = ult::runningInterpreter.load(std::memory_order_acquire) || lastRunningInterpreter; - if (isRunning && (m_value.find(ult::DOWNLOAD_SYMBOL) != std::string::npos || - m_value.find(ult::UNZIP_SYMBOL) != std::string::npos || - m_value.find(ult::COPY_SYMBOL) != std::string::npos)) { - return m_flags.m_faint ? offTextColor : (inprogressTextColor); - } - - if (m_value == ult::INPROGRESS_SYMBOL) { - return m_flags.m_faint ? offTextColor : (inprogressTextColor); - } - - if (m_value == ult::CROSSMARK_SYMBOL) { - return m_flags.m_faint ? offTextColor : (invalidTextColor); - } - - return useClickTextColor ? clickTextColor : selectedValueTextColor; - } - - if (m_flags.m_hasCustomValueColor) { - return m_customValueColor; - } - - if (m_value == ult::DROPDOWN_SYMBOL || m_value == ult::OPTION_SYMBOL) { - return (m_focused ? (useClickTextColor ? clickTextColor : (m_flags.m_faint ? offTextColor : (ult::useSelectionText ? selectedTextColor : defaultTextColor))) : - (useClickTextColor ? clickTextColor : (m_flags.m_faint ? offTextColor : defaultTextColor))); - } - - const bool isRunning = ult::runningInterpreter.load(std::memory_order_acquire) || lastRunningInterpreter; - if (isRunning && (m_value.find(ult::DOWNLOAD_SYMBOL) != std::string::npos || - m_value.find(ult::UNZIP_SYMBOL) != std::string::npos || - m_value.find(ult::COPY_SYMBOL) != std::string::npos)) { - return m_flags.m_faint ? offTextColor : (inprogressTextColor); - } - - if (m_value == ult::INPROGRESS_SYMBOL) { - return m_flags.m_faint ? offTextColor : (inprogressTextColor); - } - - if (m_value == ult::CROSSMARK_SYMBOL) { - return m_flags.m_faint ? offTextColor : (invalidTextColor); - } - - return (m_flags.m_faint ? offTextColor : (onTextColor)); - } - - void drawThrobber(gfx::Renderer* renderer, s32 xPosition, s32 yPosition, s32 fontSize, Color textColor) { - static size_t throbberCounter = 0; - const auto& throbberSymbol = ult::THROBBER_SYMBOLS[(throbberCounter / 10) % ult::THROBBER_SYMBOLS.size()]; - throbberCounter = (throbberCounter + 1) % (10 * ult::THROBBER_SYMBOLS.size()); - renderer->drawString(throbberSymbol, false, xPosition, yPosition, fontSize, textColor); - } - - s64 determineKeyOnTouchRelease(bool useScriptKey) const { - const u64 touchDuration_ns = armTicksToNs(armGetSystemTick()) - m_touchStartTime_ns; - const float touchDurationInSeconds = static_cast(touchDuration_ns) * 1e-9f; - - #if IS_LAUNCHER_DIRECTIVE - if (touchDurationInSeconds >= 0.7f) [[unlikely]] { - ult::longTouchAndRelease.store(true, std::memory_order_release); - return useScriptKey ? SCRIPT_KEY : STAR_KEY; - } - #endif - if (touchDurationInSeconds >= 0.3f) [[unlikely]] { - ult::shortTouchAndRelease.store(true, std::memory_order_release); - return useScriptKey ? SCRIPT_KEY : SETTINGS_KEY; - } - return KEY_A; - } - - void resetTextProperties() { - m_scrollText.clear(); - m_ellipsisText.clear(); - m_maxWidth = 0; - } - }; - - class MiniListItem : public ListItem { - public: - #if IS_LAUNCHER_DIRECTIVE - // Constructor for MiniListItem, with no `isMini` boolean. - MiniListItem(const std::string& text, const std::string& value = "", bool useScriptKey = false) - : ListItem(text, value, true, useScriptKey) { // Call the parent constructor with `isMini = true` - #else - MiniListItem(const std::string& text, const std::string& value = "") - : ListItem(text, value, true) { // Call the parent constructor with `isMini = true` - #endif - - // Additional MiniListItem-specific initialization can go here, if necessary. - } - - // Destructor if needed (inherits default behavior from ListItem) - virtual ~MiniListItem() {} - }; - - /** - * @brief A 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 s32 xPosition = this->getX() + this->m_maxWidth + 44 + 3; - const s32 yPosition = this->getY() + 45 - yOffset; - static constexpr s32 fontSize = 20; - - - //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, bool delayedHandle=false) - : ListItem(text, "", isMini), m_state(initialState), m_onValue(onValue), m_offValue(offValue), m_delayedHandle(delayedHandle) { - this->setState(this->m_state); - } - - virtual ~ToggleListItem() {} - - virtual bool onClick(u64 keys) override { - - #if IS_LAUNCHER_DIRECTIVE - if (ult::runningInterpreter.load(std::memory_order_acquire)) - return false; - #endif - - // Handle KEY_A for toggling - if (keys & KEY_A) { - triggerRumbleClick.store(true, std::memory_order_release); - if (!this->m_state) - triggerOnSound.store(true, std::memory_order_release); - else - triggerOffSound.store(true, std::memory_order_release); - - - this->m_state = !this->m_state; - - if (!m_delayedHandle) - this->setState(this->m_state); - - this->m_stateChangedListener(this->m_state); - - - return true; - } - //if (keys & KEY_B) { - // triggerRumbleDoubleClick.store(true, std::memory_order_release); - // triggerExitSound.store(true, std::memory_order_release); - // - //} - - #if IS_LAUNCHER_DIRECTIVE - // Handle SCRIPT_KEY for executing script logic - else if (keys & SCRIPT_KEY) { - // Trigger the script key listener - if (this->m_scriptKeyListener) { - this->m_scriptKeyListener(this->m_state); // Pass the current state to the script key listener - } - return ListItem::onClick(keys); - } - #endif - return false; - } - - /** - * @brief Gets the current state of the toggle - * - * @return State - */ - virtual inline bool getState() { - return this->m_state; - } - - /** - * @brief Sets the current state of the toggle. Updates the Value - * - * @param state State - */ - virtual inline void setState(bool state) { - #if IS_LAUNCHER_DIRECTIVE - if (ult::runningInterpreter.load(std::memory_order_acquire)) - return; - #endif - - this->m_state = state; - this->setValue(state ? this->m_onValue : this->m_offValue, !state); - } - - /** - * @brief Adds a listener that gets called whenever the state of the toggle changes - * - * @param stateChangedListener Listener with the current state passed in as parameter - */ - void setStateChangedListener(std::function stateChangedListener) { - this->m_stateChangedListener = stateChangedListener; - } - - #if IS_LAUNCHER_DIRECTIVE - // Attach the script key listener for SCRIPT_KEY handling - void setScriptKeyListener(std::function scriptKeyListener) { - this->m_scriptKeyListener = scriptKeyListener; - } - #endif - - - protected: - bool m_state = true; - - std::string m_onValue, m_offValue; - bool m_delayedHandle = false; - - std::function m_stateChangedListener = [](bool){}; - - #if IS_LAUNCHER_DIRECTIVE - std::function m_scriptKeyListener = nullptr; // Script key listener (with state) - #endif - }; - - class MiniToggleListItem : public ToggleListItem { - public: - // Constructor for MiniToggleListItem, with no `isMini` boolean. - MiniToggleListItem(const std::string& text, bool initialState, const std::string& onValue = ult::ON, const std::string& offValue = ult::OFF) - : ToggleListItem(text, initialState, onValue, offValue, true) { - } - - // Destructor if needed (inherits default behavior from ListItem) - virtual ~MiniToggleListItem() {} - }; - - - class DummyListItem : public ListItem { - public: - DummyListItem() - : ListItem("") { // Use an empty string for the base class constructor - // Set the properties to indicate it's a dummy item - this->m_text = ""; - this->m_value = ""; - this->m_maxWidth = 0; - this->width = 0; - this->height = 0; - m_isItem = false; - } - - 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; - static bool triggerOnce = true; - - const bool touchInCircle = (std::abs(initialX - circleCenterX) <= circleRadius) && (std::abs(initialY - circleCenterY) <= circleRadius); - - if (event == TouchEvent::Release) { - triggerOnce = true; - triggerRumbleDoubleClick.store(true, std::memory_order_release); - triggerOffSound.store(true, std::memory_order_release); - touchInSliderBounds = false; - return false; - } - - if (touchInCircle || touchInSliderBounds) { - if (triggerOnce){ - triggerOnce = false; - triggerRumbleClick.store(true, std::memory_order_release); - triggerOnSound.store(true, std::memory_order_release); - } - - 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; - //} - } - - return false; - } - - - // Define drawBar function outside the draw method - void drawBar(gfx::Renderer *renderer, s32 x, s32 y, u16 width, Color& color, bool isRounded = true) { - if (isRounded) { - renderer->drawUniformRoundedRect(x, y, width, 7, a(color)); - } else { - renderer->drawRect(x, y, width, 7, a(color)); - } - } - - virtual void draw(gfx::Renderer *renderer) override { - //static float lastBottomBound; - - if (touchInSliderBounds) { - m_drawFrameless = true; - drawHighlight(renderer); - } else { - m_drawFrameless = false; - } - - - s32 xPos = this->getX() + 59; - s32 yPos = this->getY() + 40 + 16 - 1; - s32 width = this->getWidth() - 95; - 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 step tick marks if this is a step trackbar - if (m_usingStepTrackbar || m_usingNamedStepTrackbar) { - const u8 numSteps = m_numSteps; - const u16 baseX = xPos; - const u16 baseY = this->getY() + 44; - const u8 halfNumSteps = (numSteps - 1) / 2; - const u16 lastStepX = baseX + width - 1; - const float stepSpacing = static_cast(width) / (numSteps - 1); - const auto stepColor = a(trackBarEmptyColor); - - u16 stepX; - for (u8 i = 0; i < numSteps; i++) { - if (i == numSteps - 1) { - stepX = lastStepX; - } else { - stepX = baseX + static_cast(std::round(i * stepSpacing)); - if (i > halfNumSteps) { - stepX -= 1; - } - } - renderer->drawRect(stepX, baseY, 1, 8, stepColor); - } - } - - // Draw track bar background - drawBar(renderer, xPos, yPos-3, width, trackBarEmptyColor, !m_usingNamedStepTrackbar); - - if (!this->m_focused) { - drawBar(renderer, xPos, yPos-3, handlePos, trackBarFullColor, !m_usingNamedStepTrackbar); - renderer->drawCircle(xPos + handlePos, yPos, 16, true, a(m_drawFrameless ? highlightColor : trackBarSliderBorderColor)); - renderer->drawCircle(xPos + handlePos, yPos, 13, true, a((m_unlockedTrackbar || touchInSliderBounds) ? trackBarSliderMalleableColor : trackBarSliderColor)); - } else { - touchInSliderBounds = false; - if (m_unlockedTrackbar != ult::unlockedSlide.load(std::memory_order_acquire)) - ult::unlockedSlide.store(m_unlockedTrackbar, std::memory_order_release); - drawBar(renderer, xPos, yPos-3, handlePos, trackBarFullColor, !m_usingNamedStepTrackbar); - renderer->drawCircle(xPos + x + handlePos, yPos +y, 16, true, a(highlightColor)); - renderer->drawCircle(xPos + x + handlePos, yPos +y, 12, true, a((ult::allowSlide.load(std::memory_order_acquire) || m_unlockedTrackbar) ? trackBarSliderMalleableColor : trackBarSliderColor)); - } - - // Draw icon (original style) or label + value (V2 style) - if (m_useV2Style) { - // V2 Style: Draw label and value - std::string labelPart = this->m_label; - ult::removeTag(labelPart); - - std::string valuePart; - if (!m_usingNamedStepTrackbar) { - valuePart = (m_units.compare("%") == 0 || m_units.compare("°C") == 0 || m_units.compare("°F") == 0) - ? ult::to_string(m_value) + m_units - : ult::to_string(m_value) + (m_units.empty() ? "" : " ") + m_units; - } else { - valuePart = this->m_selection; - } - - const auto valueWidth = renderer->getTextDimensions(valuePart, false, 16).first; - - renderer->drawString(labelPart, false, this->getX() + 59, this->getY() + 14 + 16, 16, - ((!this->m_focused || !ult::useSelectionText) ? (defaultTextColor) : (selectedTextColor))); - - renderer->drawString(valuePart, false, this->getWidth() -17 - valueWidth, this->getY() + 14 + 16, 16, (this->m_focused && ult::useSelectionValue) ? selectedValueTextColor : onTextColor); - } else { - // Original Style: Draw icon - if (m_icon[0] != '\0') - renderer->drawString(this->m_icon, false, this->getX()+42, this->getY() + 50+2, 23, a(tsl::style::color::ColorText)); - } - - - if (m_lastBottomBound != this->getTopBound()) - renderer->drawRect(this->getX() + 4+20-1, this->getTopBound(), this->getWidth() + 6 + 10+20 +4, 1, a(separatorColor)); - renderer->drawRect(this->getX() + 4+20-1, this->getBottomBound(), this->getWidth() + 6 + 10+20 +4, 1, a(separatorColor)); - m_lastBottomBound = this->getBottomBound(); - } - - virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override { - this->setBoundaries(this->getX() - 16 , this->getY(), this->getWidth()+20+4, tsl::style::TrackBarDefaultHeight ); - } - - virtual void drawFocusBackground(gfx::Renderer *renderer) { - // No background drawn here in HOS - } - - virtual void drawHighlight(gfx::Renderer *renderer) override { - - // Get current time using ARM system tick for animation timing - const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); - - // High precision time calculation - matches standard cosine wave timing - const double time_seconds = static_cast(currentTime_ns) / 1000000000.0; - - // Standard cosine wave calculation with high precision - progress = (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 (!m_drawFrameless) { - if (ult::useSelectionBG) { - if (ult::expandedMemory) - renderer->drawRectMultiThreaded(this->getX() + x +19, this->getY() + y, this->getWidth()-11-4, this->getHeight(), aWithOpacity(selectionBGColor)); // CUSTOM MODIFICATION - else - renderer->drawRect(this->getX() + x +19, this->getY() + y, this->getWidth()-11-4, this->getHeight(), aWithOpacity(selectionBGColor)); // CUSTOM MODIFICATION - - - //renderer->drawRect(this->getX() + x +19, this->getY() + y, this->getWidth()-11-4, this->getHeight(), a(selectionBGColor)); // CUSTOM MODIFICATION - } - - renderer->drawBorderedRoundedRect(this->getX() + x +19, this->getY() + y, this->getWidth()-11, this->getHeight(), 5, 5, a(highlightColor)); - } else { - if (ult::useSelectionBG) { - if (ult::expandedMemory) - renderer->drawRectMultiThreaded(this->getX() + x +19, this->getY() + y, this->getWidth()-11-4, this->getHeight(), aWithOpacity(clickColor)); // CUSTOM MODIFICATION - else - renderer->drawRect(this->getX() + x +19, this->getY() + y, this->getWidth()-11-4, this->getHeight(), aWithOpacity(clickColor)); // CUSTOM MODIFICATION - } - } - - - ult::onTrackBar.exchange(true, std::memory_order_acq_rel); - } - - /** - * @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; - - u8 m_numSteps = 101; - // V2 Style properties - bool m_useV2Style = false; - std::string m_label; - std::string m_units; - std::string m_selection; // Used for named step trackbars - bool m_drawFrameless = false; - - float m_lastBottomBound; - }; - - - /** - * @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) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - this->m_value = std::max(this->m_value - (100 / (this->m_numSteps - 1)), 0); - } else if (keysHeld & KEY_RIGHT && this->m_value < 100) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - 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 { - const u16 trackBarWidth = this->getWidth() - 95; - const u16 handlePos = (trackBarWidth * this->m_value) / 100; - const s32 circleCenterX = this->getX() + 59 + handlePos; - const s32 circleCenterY = this->getY() + 40 + 16 - 1; - static constexpr s32 circleRadius = 16; - static bool triggerOnce = true; - - const bool touchInCircle = (std::abs(initialX - circleCenterX) <= circleRadius) && (std::abs(initialY - circleCenterY) <= circleRadius); - - if (event == TouchEvent::Release) { - triggerOnce = true; - triggerRumbleDoubleClick.store(true, std::memory_order_release); - triggerOffSound.store(true, std::memory_order_release); - touchInSliderBounds = false; - return false; - } - - if (touchInCircle || touchInSliderBounds) { - if (triggerOnce){ - triggerOnce = false; - triggerRumbleClick.store(true, std::memory_order_release); - triggerOnSound.store(true, std::memory_order_release); - } - - touchInSliderBounds = true; - //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) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - this->m_value = newValue; - this->m_valueChangedListener(this->getProgress()); - } - - return true; - //} - } - - return false; - } - - /** - * @brief Gets the current value of the trackbar - * - * @return State - */ - virtual inline u8 getProgress() override { - return this->m_value / (100 / (this->m_numSteps - 1)); - } - - /** - * @brief Sets the current state of the toggle. Updates the Value - * - * @param state State - */ - virtual void setProgress(u8 value) override { - value = std::min(value, u8(this->m_numSteps - 1)); - this->m_value = value * (100 / (this->m_numSteps - 1)); - } - - protected: - u8 m_numSteps = 1; - }; - - - /** - * @brief A customizable trackbar with multiple discrete steps with specific names. Name gets displayed above the bar - * - */ - class NamedStepTrackBar : public StepTrackBar { - public: - /** - * @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]; - } - m_numSteps = m_stepDescriptions.size(); - } - - 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 { - if (touchInSliderBounds) { - m_drawFrameless = true; - drawHighlight(renderer); - } else { - m_drawFrameless = false; - } - - s32 xPos = this->getX() + 59; - s32 yPos = this->getY() + 40 + 16 - 1; - s32 width = this->getWidth() - 95; - 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; - iconOffset = 14 + iconWidth; - xPos += iconOffset; - width -= iconOffset; - handlePos = (width) * (this->m_value) / (100); - } - - // Draw step tick marks if this is a step trackbar - { - const u8 numSteps = m_numSteps; - const u16 baseX = xPos; - const u16 baseY = this->getY() + 44; - const u8 halfNumSteps = (numSteps - 1) / 2; - const u16 lastStepX = baseX + width - 1; - const float stepSpacing = static_cast(width) / (numSteps - 1); - const auto stepColor = a(trackBarEmptyColor); - - u16 stepX; - for (u8 i = 0; i < numSteps; i++) { - if (i == numSteps - 1) { - stepX = lastStepX; - } else { - stepX = baseX + static_cast(std::round(i * stepSpacing)); - if (i > halfNumSteps) { - stepX -= 1; - } - } - renderer->drawRect(stepX, baseY, 1, 8, stepColor); - } - } - - // Draw track bar background - drawBar(renderer, xPos, yPos-3, width, trackBarEmptyColor, !m_usingNamedStepTrackbar); - - if (!this->m_focused) { - drawBar(renderer, xPos, yPos-3, handlePos, trackBarFullColor, !m_usingNamedStepTrackbar); - renderer->drawCircle(xPos + handlePos, yPos, 16, true, a(m_drawFrameless ? highlightColor : trackBarSliderBorderColor)); - renderer->drawCircle(xPos + handlePos, yPos, 13, true, a((m_unlockedTrackbar || touchInSliderBounds) ? trackBarSliderMalleableColor : trackBarSliderColor)); - } else { - touchInSliderBounds = false; - if (m_unlockedTrackbar != ult::unlockedSlide.load(std::memory_order_acquire)) - ult::unlockedSlide.store(m_unlockedTrackbar, std::memory_order_release); - drawBar(renderer, xPos, yPos-3, handlePos, trackBarFullColor, !m_usingNamedStepTrackbar); - renderer->drawCircle(xPos + x + handlePos, yPos +y, 16, true, a(highlightColor)); - renderer->drawCircle(xPos + x + handlePos, yPos +y, 12, true, a((ult::allowSlide.load(std::memory_order_acquire) || m_unlockedTrackbar) ? trackBarSliderMalleableColor : trackBarSliderColor)); - } - - // Draw icon (original style) or label + value (V2 style) - if (m_useV2Style) { - // V2 Style: Draw label and value - std::string labelPart = this->m_label; - ult::removeTag(labelPart); - - std::string valuePart; - if (!m_usingNamedStepTrackbar) { - valuePart = (m_units.compare("%") == 0 || m_units.compare("°C") == 0 || m_units.compare("°F") == 0) - ? ult::to_string(m_value) + m_units - : ult::to_string(m_value) + (m_units.empty() ? "" : " ") + m_units; - } else { - valuePart = this->m_selection; - } - - const auto valueWidth = renderer->getTextDimensions(valuePart, false, 16).first; - - renderer->drawString(labelPart, false, this->getX() + 59, this->getY() + 14 + 16, 16, - ((!this->m_focused || !ult::useSelectionText) ? (defaultTextColor) : (selectedTextColor))); - - renderer->drawString(valuePart, false, this->getWidth() -17 - valueWidth, this->getY() + 14 + 16, 16, (this->m_focused && ult::useSelectionValue) ? selectedValueTextColor : onTextColor); - } else { - // Original Style: Draw icon - if (m_icon[0] != '\0') - renderer->drawString(this->m_icon, false, this->getX()+42, this->getY() + 50+2, 23, a(tsl::style::color::ColorText)); - } - - if (m_lastBottomBound != this->getTopBound()) - renderer->drawRect(this->getX() + 4+20-1, this->getTopBound(), this->getWidth() + 6 + 10+20 +4, 1, a(separatorColor)); - renderer->drawRect(this->getX() + 4+20-1, this->getBottomBound(), this->getWidth() + 6 + 10+20 +4, 1, a(separatorColor)); - m_lastBottomBound = this->getBottomBound(); - } - - 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; - - void setScriptKeyListener(std::function listener) { - m_scriptKeyListener = std::move(listener); - } - - TrackBarV2(std::string label, std::string packagePath = "", s16 minValue = 0, s16 maxValue = 100, std::string units = "", - std::function>&&, const std::string&, const std::string&)> executeCommands = nullptr, - std::function>(const std::vector>&, const std::string&, size_t, const std::string&)> sourceReplacementFunc = nullptr, - std::vector> cmd = {}, const std::string& selCmd = "", bool usingStepTrackbar = false, bool usingNamedStepTrackbar = false, s16 numSteps = -1, bool unlockedTrackbar = false, bool executeOnEveryTick = false) - : m_label(label), m_packagePath(packagePath), m_minValue(minValue), m_maxValue(maxValue), m_units(units), - interpretAndExecuteCommands(executeCommands), getSourceReplacement(sourceReplacementFunc), commands(std::move(cmd)), selectedCommand(selCmd), - m_usingStepTrackbar(usingStepTrackbar), m_usingNamedStepTrackbar(usingNamedStepTrackbar), m_numSteps(numSteps), m_unlockedTrackbar(unlockedTrackbar), m_executeOnEveryTick(executeOnEveryTick) { - - m_isItem = true; - - if (maxValue < minValue) { - std::swap(minValue, maxValue); - m_minValue = minValue; - m_maxValue = maxValue; - } - - if ((!usingStepTrackbar && !usingNamedStepTrackbar) || numSteps == -1) { - m_numSteps = (maxValue - minValue) + 1; - } - - if (m_numSteps < 2) { - m_numSteps = 2; - } - - bool loadedValue = false; - - if (!m_packagePath.empty()) { - auto configIniData = ult::getParsedDataFromIniFile(m_packagePath + "config.ini"); - auto sectionIt = configIniData.find(m_label); - - if (sectionIt != configIniData.end()) { - auto indexIt = sectionIt->second.find("index"); - if (indexIt != sectionIt->second.end() && !indexIt->second.empty()) { - m_index = static_cast(ult::stoi(indexIt->second)); - } - - if (!m_usingNamedStepTrackbar) { - auto valueIt = sectionIt->second.find("value"); - if (valueIt != sectionIt->second.end() && !valueIt->second.empty()) { - m_value = static_cast(ult::stoi(valueIt->second)); - loadedValue = true; - } - } - } - } - - if (m_index >= m_numSteps) m_index = m_numSteps - 1; - if (m_index < 0) m_index = 0; - - if (!loadedValue) { - if (m_numSteps > 1) { - m_value = minValue + m_index * (static_cast(maxValue - minValue) / (m_numSteps - 1)); - } else { - m_value = minValue; - } - } - - if (m_value > maxValue) m_value = maxValue; - if (m_value < minValue) m_value = minValue; - - lastUpdate_ns = armTicksToNs(armGetSystemTick()); - } - - virtual ~TrackBarV2() {} - - virtual Element* requestFocus(Element *oldFocus, FocusDirection direction) { - return this; - } - - inline void updateAndExecute(bool updateIni = true) { - if (m_packagePath.empty()) { - return; - } - - const std::string indexStr = ult::to_string(m_index); - const std::string valueStr = m_usingNamedStepTrackbar ? m_selection : ult::to_string(m_value); - - if (updateIni) { - const std::string configPath = m_packagePath + "config.ini"; - ult::setIniFileValue(configPath, m_label, "index", indexStr); - ult::setIniFileValue(configPath, m_label, "value", valueStr); - } - bool success = false; - - static const std::string valuePlaceholder = "{value}"; - static const std::string indexPlaceholder = "{index}"; - static const size_t valuePlaceholderLen = valuePlaceholder.length(); - static const size_t indexPlaceholderLen = indexPlaceholder.length(); - const size_t valueStrLen = valueStr.length(); - const size_t indexStrLen = indexStr.length(); - - size_t tryCount = 0; - while (!success) { - if (interpretAndExecuteCommands) { - if (tryCount > 3) - break; - auto modifiedCmds = getSourceReplacement(commands, valueStr, m_index, m_packagePath); - - for (auto& cmd : modifiedCmds) { - for (auto& arg : cmd) { - for (size_t pos = 0; (pos = arg.find(valuePlaceholder, pos)) != std::string::npos; pos += valueStrLen) { - arg.replace(pos, valuePlaceholderLen, valueStr); - } - - if (m_usingNamedStepTrackbar) { - for (size_t pos = 0; (pos = arg.find(indexPlaceholder, pos)) != std::string::npos; pos += indexStrLen) { - arg.replace(pos, indexPlaceholderLen, indexStr); - } - } - } - } - - success = interpretAndExecuteCommands(std::move(modifiedCmds), m_packagePath, selectedCommand); - ult::resetPercentages(); - - if (success) - break; - tryCount++; - } - } - } - - virtual inline bool handleInput(u64 keysDown, u64 keysHeld, const HidTouchState &touchPos, HidAnalogStickState leftJoyStick, HidAnalogStickState rightJoyStick) override { - const u64 keysReleased = m_prevKeysHeld & ~keysHeld; - m_prevKeysHeld = keysHeld; - - const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); - const u64 elapsed_ns = currentTime_ns - lastUpdate_ns; - - m_keyRHeld = (keysHeld & KEY_R) != 0; - - if ((keysHeld & KEY_R)) { - if (keysDown & KEY_UP && !(keysHeld & ~KEY_UP & ~KEY_R & ALL_KEYS_MASK)) - this->shakeHighlight(FocusDirection::Up); - else if (keysDown & KEY_DOWN && !(keysHeld & ~KEY_DOWN & ~KEY_R & ALL_KEYS_MASK)) - this->shakeHighlight(FocusDirection::Down); - else if (keysDown & KEY_LEFT && !(keysHeld & ~KEY_LEFT & ~KEY_R & ALL_KEYS_MASK)){ - this->shakeHighlight(FocusDirection::Left); - } - else if (keysDown & KEY_RIGHT && !(keysHeld & ~KEY_RIGHT & ~KEY_R & ALL_KEYS_MASK)) { - this->shakeHighlight(FocusDirection::Right); - } - return true; - } - - if ((keysDown & KEY_A) && !(keysHeld & ~KEY_A & ALL_KEYS_MASK)) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerEnterSound.store(true, std::memory_order_release); - triggerEnterFeedback(); - - - if (!m_unlockedTrackbar) { - ult::atomicToggle(ult::allowSlide); - m_holding = false; - } - if (m_unlockedTrackbar || (!m_unlockedTrackbar && !ult::allowSlide.load(std::memory_order_acquire))) { - updateAndExecute(); - triggerClick = true; - } - return true; - } - - //if (keysDown & KEY_B && !(keysHeld & ~KEY_B & ALL_KEYS_MASK)) { - // triggerRumbleDoubleClick.store(true, std::memory_order_release); - // triggerExitSound.store(true, std::memory_order_release); - //} - - 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) { - // Handle key release - if (((keysReleased & KEY_LEFT) || (keysReleased & KEY_RIGHT))) { - // If we were holding and repeating, just stop - if (m_wasLastHeld) { - m_wasLastHeld = false; - //triggerNavigationSound.store(true, std::memory_order_release); - //triggerRumbleClick.store(true, std::memory_order_release); - - m_holding = false; - updateAndExecute(); - lastUpdate_ns = armTicksToNs(armGetSystemTick()); - return true; - } - // If it was a quick tap (no repeat happened), handle the single tick - else if (m_holding) { - m_holding = false; - //triggerNavigationSound.store(true, std::memory_order_release); - //triggerRumbleClick.store(true, std::memory_order_release); - updateAndExecute(); - lastUpdate_ns = armTicksToNs(armGetSystemTick()); - return true; - } - } - - // Ignore simultaneous left+right - if (keysDown & KEY_LEFT && keysDown & KEY_RIGHT) - return true; - if (keysHeld & KEY_LEFT && keysHeld & KEY_RIGHT) - return true; - - // Handle initial key press - if (keysDown & KEY_LEFT || keysDown & KEY_RIGHT) { - triggerRumbleClick.store(true, std::memory_order_release); - // Start tracking the hold - m_holding = true; - m_wasLastHeld = false; - m_holdStartTime_ns = armTicksToNs(armGetSystemTick()); - lastUpdate_ns = currentTime_ns; - - // Perform the initial single tick - if (keysDown & KEY_LEFT && this->m_value > m_minValue) { - this->m_index--; - this->m_value--; - this->m_valueChangedListener(this->m_value); - updateAndExecute(false); - } else if (keysDown & KEY_RIGHT && this->m_value < m_maxValue) { - this->m_index++; - this->m_value++; - this->m_valueChangedListener(this->m_value); - updateAndExecute(false); - } - return true; - } - - // Handle continued holding (after initial press) - if (m_holding && ((keysHeld & KEY_LEFT) || (keysHeld & KEY_RIGHT))) { - const u64 holdDuration_ns = currentTime_ns - m_holdStartTime_ns; - - // Initial delay before repeating starts (e.g., 300ms) - static constexpr u64 initialDelay_ns = 300000000ULL; - // Calculate interval with acceleration - static constexpr u64 initialInterval_ns = 67000000ULL; // ~67ms - static constexpr u64 shortInterval_ns = 10000000ULL; // ~10ms - static constexpr u64 transitionPoint_ns = 1000000000ULL; // 2 seconds - - // Trigger navigation sound every 100ms while holding - static u64 lastNavigationSound_ns = 0; - if (currentTime_ns - lastNavigationSound_ns >= 150'000'000ULL) { // 100ms - if (this->m_value > m_minValue && this->m_value < m_maxValue) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - - } - lastNavigationSound_ns = currentTime_ns; - } - - // If we haven't passed the initial delay, don't repeat yet - if (holdDuration_ns < initialDelay_ns) { - return true; - } - - const u64 holdDurationAfterDelay_ns = holdDuration_ns - initialDelay_ns; - const float t = std::min(1.0f, static_cast(holdDurationAfterDelay_ns) / static_cast(transitionPoint_ns)); - const u64 currentInterval_ns = static_cast((initialInterval_ns - shortInterval_ns) * (1.0f - t) + shortInterval_ns); - - if (elapsed_ns >= currentInterval_ns) { - if (keysHeld & KEY_LEFT && this->m_value > m_minValue) { - this->m_index--; - this->m_value--; - this->m_valueChangedListener(this->m_value); - if (m_executeOnEveryTick) { - updateAndExecute(false); - } - lastUpdate_ns = currentTime_ns; - m_wasLastHeld = true; - return true; - } - - if (keysHeld & KEY_RIGHT && this->m_value < m_maxValue) { - this->m_index++; - this->m_value++; - this->m_valueChangedListener(this->m_value); - if (m_executeOnEveryTick) { - updateAndExecute(false); - } - lastUpdate_ns = currentTime_ns; - m_wasLastHeld = true; - return true; - } - } - } else { - m_holding = false; - } - } - - return false; - } - - virtual bool onTouch(TouchEvent event, s32 currX, s32 currY, s32 prevX, s32 prevY, s32 initialX, s32 initialY) override { - const u16 trackBarWidth = this->getWidth() - 95; - const u16 handlePos = (trackBarWidth * (this->m_value - m_minValue)) / (m_maxValue - m_minValue); - const s32 circleCenterX = this->getX() + 59 + handlePos; - const s32 circleCenterY = this->getY() + 40 + 16 - 1; - static constexpr s32 circleRadius = 16; - static bool triggerOnce = true; - - 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; - - if (triggerOnce) { - triggerOnce = false; - triggerRumbleClick.store(true, std::memory_order_release); - triggerOnSound.store(true, std::memory_order_release); - } - - 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); - } - if (m_usingStepTrackbar || m_usingNamedStepTrackbar) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - } - } else { - if (event == TouchEvent::Release) { - triggerOnce = true; - updateAndExecute(); - if (event == TouchEvent::Release) - touchInSliderBounds = false; - - triggerRumbleDoubleClick.store(true, std::memory_order_release); - triggerOffSound.store(true, std::memory_order_release); - } - } - - return true; - } - - return false; - } - - void drawBar(gfx::Renderer *renderer, s32 x, s32 y, u16 width, Color& color, bool isRounded = true) { - if (isRounded) { - renderer->drawUniformRoundedRect(x, y, width, 7, a(color)); - } else { - renderer->drawRect(x, y, width, 7, a(color)); - } - } - - virtual void draw(gfx::Renderer *renderer) override { - const u16 handlePos = (this->getWidth() - 95) * (this->m_value - m_minValue) / (m_maxValue - m_minValue); - const s32 xPos = this->getX() + 59; - const s32 yPos = this->getY() + 40 + 16 - 1; - const s32 width = this->getWidth() - 95; - - const bool shouldAppearLocked = m_unlockedTrackbar && m_keyRHeld; - const bool visuallyUnlocked = (m_unlockedTrackbar && !m_keyRHeld) || touchInSliderBounds; - - if (visuallyUnlocked && touchInSliderBounds) { - m_drawFrameless = true; - drawHighlight(renderer); - } else { - m_drawFrameless = false; - } - - drawBar(renderer, xPos, yPos-3, width, trackBarEmptyColor, !m_usingNamedStepTrackbar); - - - if (!this->m_focused) { - drawBar(renderer, xPos, yPos-3, handlePos, trackBarFullColor, !m_usingNamedStepTrackbar); - renderer->drawCircle(xPos + handlePos, yPos, 16, true, a(!m_drawFrameless ? trackBarSliderBorderColor : highlightColor)); - renderer->drawCircle(xPos + handlePos, yPos, 13, true, a(visuallyUnlocked ? trackBarSliderMalleableColor : trackBarSliderColor)); - } else { - touchInSliderBounds = false; - if (m_unlockedTrackbar != ult::unlockedSlide.load(std::memory_order_acquire)) - ult::unlockedSlide.store(m_unlockedTrackbar, std::memory_order_release); - drawBar(renderer, xPos, yPos-3, handlePos, trackBarFullColor, !m_usingNamedStepTrackbar); - renderer->drawCircle(xPos + x + handlePos, yPos +y, 16, true, a(highlightColor)); - const bool focusedVisuallyUnlocked = (ult::allowSlide.load(std::memory_order_acquire) || m_unlockedTrackbar) && !shouldAppearLocked; - renderer->drawCircle(xPos + x + handlePos, yPos +y, 12, true, a(focusedVisuallyUnlocked ? trackBarSliderMalleableColor : trackBarSliderColor)); - } - - std::string labelPart = this->m_label; - ult::removeTag(labelPart); - - if (!m_usingNamedStepTrackbar) { - m_valuePart = (this->m_units.compare("%") == 0 || this->m_units.compare("°C") == 0 || this->m_units.compare("°F") == 0) - ? ult::to_string(this->m_value) + this->m_units - : ult::to_string(this->m_value) + (this->m_units.empty() ? "" : " ") + this->m_units; - } else - m_valuePart = this->m_selection; - - const auto valueWidth = renderer->getTextDimensions(m_valuePart, false, 16).first; - - renderer->drawString(labelPart, false, xPos, this->getY() + 14 + 16, 16, ((!this->m_focused || !ult::useSelectionText) ? (defaultTextColor) : (selectedTextColor))); - renderer->drawString(m_valuePart, false, this->getWidth() -17 - valueWidth, this->getY() + 14 + 16, 16, - (this->m_focused && ult::useSelectionValue) ? selectedValueTextColor : onTextColor); - - if (m_lastBottomBound != this->getTopBound()) - renderer->drawRect(this->getX() + 4+20-1, this->getTopBound(), this->getWidth() + 6 + 10+20 +4, 1, a(separatorColor)); - renderer->drawRect(this->getX() + 4+20-1, this->getBottomBound(), this->getWidth() + 6 + 10+20 +4, 1, a(separatorColor)); - m_lastBottomBound = this->getBottomBound(); - } - - virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override { - this->setBoundaries(this->getX() - 16 , this->getY(), this->getWidth()+20+4, tsl::style::TrackBarDefaultHeight ); - } - - virtual void drawFocusBackground(gfx::Renderer *renderer) { - } - - virtual void drawHighlight(gfx::Renderer *renderer) override { - const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); - const double timeInSeconds = static_cast(currentTime_ns) / 1000000000.0; - progress = ((std::cos(2.0 * ult::_M_PI * std::fmod(timeInSeconds, 1.0) - ult::_M_PI / 2) + 1.0) / 2.0); - - Color clickColor1 = highlightColor1; - Color clickColor2 = clickColor; - - if (triggerClick && !m_clickActive) { - m_clickStartTime_ns = currentTime_ns; - m_clickActive = true; - if (progress >= 0.5) { - clickColor1 = clickColor; - clickColor2 = highlightColor2; - } - } - - if (m_lastLabel != m_label) { - m_clickActive = false; - triggerClick = false; - } - m_lastLabel = m_label; - - if (m_clickActive) { - const u64 elapsedTime_ns = currentTime_ns - m_clickStartTime_ns; - if (elapsedTime_ns < 500000000ULL) { - highlightColor = { - static_cast((clickColor1.r - clickColor2.r) * progress + clickColor2.r + 0.5), - static_cast((clickColor1.g - clickColor2.g) * progress + clickColor2.g + 0.5), - static_cast((clickColor1.b - clickColor2.b) * progress + clickColor2.b + 0.5), - 0xF - }; - } else { - m_clickActive = false; - triggerClick = false; - } - } else { - const bool shouldAppearLocked = m_unlockedTrackbar && m_keyRHeld; - - if ((ult::allowSlide.load(std::memory_order_acquire) || m_unlockedTrackbar) && !shouldAppearLocked) { - highlightColor = { - static_cast((highlightColor1.r - highlightColor2.r) * progress + highlightColor2.r + 0.5), - static_cast((highlightColor1.g - highlightColor2.g) * progress + highlightColor2.g + 0.5), - static_cast((highlightColor1.b - highlightColor2.b) * progress + highlightColor2.b + 0.5), - 0xF - }; - } else { - highlightColor = { - static_cast((highlightColor3.r - highlightColor4.r) * progress + highlightColor4.r + 0.5), - static_cast((highlightColor3.g - highlightColor4.g) * progress + highlightColor4.g + 0.5), - static_cast((highlightColor3.b - highlightColor4.b) * progress + highlightColor4.b + 0.5), - 0xF - }; - } - } - - x = 0; - y = 0; - - if (this->m_highlightShaking) { - t_ns = currentTime_ns - this->m_highlightShakingStartTime; - if (t_ns >= 100000000ULL) - 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 (!m_drawFrameless) { - if (ult::useSelectionBG) { - if (ult::expandedMemory) - renderer->drawRectMultiThreaded(this->getX() + x +19, this->getY() + y, this->getWidth()-11-4, this->getHeight(), aWithOpacity(selectionBGColor)); - else - renderer->drawRect(this->getX() + x +19, this->getY() + y, this->getWidth()-11-4, this->getHeight(), aWithOpacity(selectionBGColor)); - } - - renderer->drawBorderedRoundedRect(this->getX() + x +19, this->getY() + y, this->getWidth()-11, this->getHeight(), 5, 5, a(highlightColor)); - } else { - if (ult::useSelectionBG) { - if (ult::expandedMemory) - renderer->drawRectMultiThreaded(this->getX() + x +19, this->getY() + y, this->getWidth()-11-4, this->getHeight(), aWithOpacity(clickColor)); - else - renderer->drawRect(this->getX() + x +19, this->getY() + y, this->getWidth()-11-4, this->getHeight(), aWithOpacity(clickColor)); - } - - } - - ult::onTrackBar.store(true, std::memory_order_release); - - if (m_clickActive) { - const u64 elapsedTime_ns = currentTime_ns - m_clickStartTime_ns; - - auto clickAnimationProgress = tsl::style::ListItemHighlightLength * (1.0f - (static_cast(elapsedTime_ns) / 500000000.0f)); - - if (clickAnimationProgress < 0.0f) { - clickAnimationProgress = 0.0f; - } - - if (clickAnimationProgress > 0.0f) { - const u8 saturation = tsl::style::ListItemHighlightSaturation * (float(clickAnimationProgress) / float(tsl::style::ListItemHighlightLength)); - - Color animColor = {0xF, 0xF, 0xF, 0xF}; - if (invertBGClickColor) { - animColor.r = 15 - saturation; - animColor.g = 15 - saturation; - animColor.b = 15 - saturation; - } else { - animColor.r = saturation; - animColor.g = saturation; - animColor.b = saturation; - } - animColor.a = selectionBGColor.a; - renderer->drawRect(this->getX() +22, this->getY(), this->getWidth() -22, this->getHeight(), aWithOpacity(animColor)); - } - } - } - - virtual inline u8 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 = 0; - s16 m_maxValue = 100; - std::string m_units; - bool m_interactionLocked = false; - bool m_keyRHeld = false; - - std::function m_valueChangedListener = [](u8) {}; - - std::function>&&, const std::string&, const std::string&)> interpretAndExecuteCommands; - std::function>(const std::vector>&, const std::string&, size_t, const std::string&)> getSourceReplacement; - std::vector> commands; - std::string selectedCommand; - - bool m_usingStepTrackbar = false; - bool m_usingNamedStepTrackbar = false; - s16 m_numSteps = 2; - s16 m_index = 0; - bool m_unlockedTrackbar = false; - bool m_executeOnEveryTick = false; - bool touchInSliderBounds = false; - bool triggerClick = false; - std::function m_scriptKeyListener; - - // Instance variables replacing static ones - float m_lastBottomBound = 0.0f; - std::string m_valuePart = ""; - u64 m_clickStartTime_ns = 0; - bool m_clickActive = false; - std::string m_lastLabel = ""; - bool m_holding = false; - u64 m_holdStartTime_ns = 0; - u64 m_prevKeysHeld = 0; - bool m_wasLastHeld = false; - bool m_drawFrameless = false; - }; - - - /** - * @brief A customizable analog trackbar going from 0% to 100% but using discrete steps (Like the volume slider) - * - */ - class StepTrackBarV2 : public TrackBarV2 { - public: - - /** - * @brief Constructor - * - * @param icon Icon shown next to the track bar - * @param numSteps Number of steps the track bar has - */ - StepTrackBarV2(std::string label, std::string packagePath, size_t numSteps, s16 minValue, s16 maxValue, std::string units, - std::function>&&, const std::string&, const std::string&)> executeCommands = nullptr, - std::function>(const std::vector>&, const std::string&, size_t, const std::string&)> sourceReplacementFunc = nullptr, - std::vector> cmd = {}, const std::string& selCmd = "", bool usingNamedStepTrackbar = false, bool unlockedTrackbar = false, bool executeOnEveryTick = false) - : TrackBarV2(label, packagePath, minValue, maxValue, units, executeCommands, sourceReplacementFunc, cmd, selCmd, !usingNamedStepTrackbar, usingNamedStepTrackbar, numSteps, unlockedTrackbar, executeOnEveryTick) {} - - virtual ~StepTrackBarV2() {} - - virtual inline bool handleInput(u64 keysDown, u64 keysHeld, const HidTouchState &touchPos, HidAnalogStickState leftJoyStick, HidAnalogStickState rightJoyStick) override { - static u32 tick = 0; - static bool holding = false; - static u64 prevKeysHeld = 0; - const u64 keysReleased = prevKeysHeld & ~keysHeld; - prevKeysHeld = keysHeld; - - static bool wasLastHeld = false; - - // ADD THIS LINE: Update KEY_R state for visual appearance - m_keyRHeld = (keysHeld & KEY_R) != 0; - - if ((keysHeld & KEY_R)) { - //auto currentFocus = currentGui->getFocusedElement(); - if (keysDown & KEY_UP && !(keysHeld & ~KEY_UP & ~KEY_R & ALL_KEYS_MASK)) - this->shakeHighlight(FocusDirection::Up); - else if (keysDown & KEY_DOWN && !(keysHeld & ~KEY_DOWN & ~KEY_R & ALL_KEYS_MASK)) - this->shakeHighlight(FocusDirection::Down); - else if (keysDown & KEY_LEFT && !(keysHeld & ~KEY_LEFT & ~KEY_R & ALL_KEYS_MASK)){ - this->shakeHighlight(FocusDirection::Left); - } - else if (keysDown & KEY_RIGHT && !(keysHeld & ~KEY_RIGHT & ~KEY_R & ALL_KEYS_MASK)) { - this->shakeHighlight(FocusDirection::Right); - } - return true; - } - - // Check if KEY_A is pressed to toggle ult::allowSlide - if ((keysDown & KEY_A) && !(keysHeld & ~KEY_A & ALL_KEYS_MASK)) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerEnterSound.store(true, std::memory_order_release); - triggerEnterFeedback(); - - - if (!m_unlockedTrackbar) { - ult::atomicToggle(ult::allowSlide); - holding = false; // Reset holding state when KEY_A is pressed - } - if (m_unlockedTrackbar || (!m_unlockedTrackbar && !ult::allowSlide.load(std::memory_order_acquire))) { - updateAndExecute(); - triggerClick = true; - } - return true; - } - - //if (keysDown & KEY_B && !(keysHeld & ~KEY_B & ALL_KEYS_MASK)) { - // triggerRumbleDoubleClick.store(true, std::memory_order_release); - // triggerExitSound.store(true, std::memory_order_release); - //} - - // Handle SCRIPT_KEY press - if ((keysDown & SCRIPT_KEY) && !(keysHeld & ~SCRIPT_KEY & ALL_KEYS_MASK)) { - if (m_scriptKeyListener) { - m_scriptKeyListener(); - } - return true; - } - - if (ult::allowSlide.load(std::memory_order_acquire) || m_unlockedTrackbar) { - if (((keysReleased & KEY_LEFT) || (keysReleased & KEY_RIGHT)) || - (wasLastHeld && !(keysHeld & (KEY_LEFT | KEY_RIGHT)))) { - updateAndExecute(); - holding = false; - wasLastHeld = false; - tick = 0; - return true; - } - - if (keysHeld & KEY_LEFT && keysHeld & KEY_RIGHT) { - tick = 0; - return true; - } - - if (keysHeld & (KEY_LEFT | KEY_RIGHT)) { - if (!holding) { - holding = true; - tick = 0; - } - - if ((tick == 0 || tick > 20) && (tick % 3) == 0) { - const float stepSize = static_cast(m_maxValue - m_minValue) / (this->m_numSteps - 1); - if (keysHeld & KEY_LEFT && this->m_index > 0) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - - this->m_index--; - this->m_value = static_cast(std::round(m_minValue + m_index * stepSize)); - } else if (keysHeld & KEY_RIGHT && this->m_index < this->m_numSteps-1) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - - this->m_index++; - this->m_value = static_cast(std::round(m_minValue + m_index * stepSize)); - } else { - return false; - } - this->m_valueChangedListener(this->getProgress()); - if (m_executeOnEveryTick) - updateAndExecute(false); - wasLastHeld = true; - } - tick++; - return true; - } else { - holding = false; - tick = 0; - } - } - - return false; - } - - - /** - * @brief Gets the current value of the trackbar - * - * @return State - */ - virtual inline u8 getProgress() override { - return this->m_value / (100 / (this->m_numSteps - 1)); - } - - /** - * @brief Sets the current state of the toggle. Updates the Value - * - * @param state State - */ - virtual void setProgress(u8 value) override { - value = std::min(value, u8(this->m_numSteps - 1)); - this->m_value = value * (100 / (this->m_numSteps - 1)); - } - - //protected: - //u8 m_numSteps = 1; - - }; - - - /** - * @brief A customizable trackbar with multiple discrete steps with specific names. Name gets displayed above the bar - * - */ - class NamedStepTrackBarV2 : public StepTrackBarV2 { - public: - u16 trackBarWidth, stepWidth, currentDescIndex; - u32 descWidth, descHeight; - - /** - * @brief Constructor - * - * @param icon Icon shown next to the track bar - * @param stepDescriptions Step names displayed above the track bar - */ - NamedStepTrackBarV2(std::string label, std::string packagePath, std::vector& stepDescriptions, - std::function>&&, const std::string&, const std::string&)> executeCommands = nullptr, - std::function>(const std::vector>&, const std::string&, size_t, const std::string&)> sourceReplacementFunc = nullptr, - std::vector> cmd = {}, const std::string& selCmd = "", bool unlockedTrackbar = false, bool executeOnEveryTick = false) - : StepTrackBarV2(label, packagePath, stepDescriptions.size(), 0, (stepDescriptions.size()-1), "", executeCommands, sourceReplacementFunc, cmd, selCmd, true, unlockedTrackbar, executeOnEveryTick), m_stepDescriptions(stepDescriptions) { - //usingNamedStepTrackbar = true; - //logMessage("on initialization"); - - // Initialize the selection with the current index - if (!m_stepDescriptions.empty() && m_index >= 0 && m_index < static_cast(m_stepDescriptions.size())) { - this->m_selection = m_stepDescriptions[m_index]; - currentDescIndex = m_index; - } - } - - virtual ~NamedStepTrackBarV2() {} - - virtual void draw(gfx::Renderer *renderer) override { - // Cache frequently used values - const u16 trackBarWidth = this->getWidth() - 95; - const u16 baseX = this->getX() + 59; - const u16 baseY = this->getY() + 44; // 50 - 3 - const u8 numSteps = this->m_numSteps; - const u8 halfNumSteps = (numSteps - 1) / 2; - const u16 lastStepX = baseX + trackBarWidth - 1; - - // Pre-calculate step spacing - const float stepSpacing = static_cast(trackBarWidth) / (numSteps - 1); - - // Cache color for multiple drawRect calls - const auto stepColor = a(trackBarEmptyColor); - - // Draw step rectangles - optimized loop - u16 stepX; - for (u8 i = 0; i < numSteps; i++) { - - if (i == numSteps - 1) { - // Last step - avoid overshooting - stepX = lastStepX; - } else { - stepX = baseX + static_cast(std::round(i * stepSpacing)); - // Adjust for steps on right side of center - if (i > halfNumSteps) { - stepX -= 1; - } - } - - renderer->drawRect(stepX, baseY, 1, 8, stepColor); - } - - // Update selection (only if index changed - optional optimization) - if (currentDescIndex != this->m_index) { - currentDescIndex = this->m_index; - this->m_selection = this->m_stepDescriptions[currentDescIndex]; - } - - // Draw the parent trackbar - StepTrackBarV2::draw(renderer); - } - - - protected: - std::vector m_stepDescriptions; - - }; - - } - - // Global state and event system - static inline Event notificationEvent; - static inline std::mutex notificationJsonMutex; - static inline std::atomic notificationGeneration{0}; - - struct NotificationFile { - std::string filename; - std::string fullPath; - time_t creationTime; - int priority; - }; - - class NotificationPrompt { - public: - NotificationPrompt() - : enabled_(true), - is_active_(false), - //pending_event_fire_(false), - generation_(notificationGeneration.load(std::memory_order_acquire)) - {} - - ~NotificationPrompt() { - shutdown(); // safe cleanup - } - - enum class PromptState { - Inactive, - SlidingIn, - Visible, - SlidingOut - }; - - struct NotificationData { - std::string text; - std::string fileName; - size_t fontSize = 28; - s32 promptWidth = 448; - s32 promptHeight = 88; - u32 durationMs = 2500; - u32 priority = 20; - u64 arrivalNs = 0; - - NotificationData() = default; - - NotificationData(const std::string& t, const std::string& f = "", - size_t fs = 28, s32 w = 448, s32 h = 88, - u32 dur = 2500, u32 prio = 20) - : text(t), fileName(f), fontSize(fs), promptWidth(w), promptHeight(h), - durationMs(dur), priority(prio), arrivalNs(0) {} - }; - - struct NotificationCompare { - bool operator()(const NotificationData& a, const NotificationData& b) const { - if (a.priority == b.priority) { - return a.arrivalNs > b.arrivalNs; // FIFO - } - return a.priority > b.priority; // Max-heap - } - }; - - struct NotificationState { - std::string activeText; - std::string fileName; - size_t fontSize = 28; - s32 promptWidth = 448; - s32 promptHeight = 88; - PromptState state = PromptState::Inactive; - u64 expireNs = 0; - u64 stateStartNs = 0; - - NotificationState() = default; - bool isTextEmpty() const { return activeText.empty(); } - }; - - // ---------------- Public Methods ---------------- - - void show(const std::string& msg, size_t fontSize = 26, u32 priority = 20, - const std::string& fileName = "", u32 durationMs = 2500, - s32 promptWidth = 448, s32 promptHeight = 88) - { - 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, notificationTextColor - ); - } - #else - // Draw normal line - const auto [lw, lh] = renderer->getNotificationTextDimensions(line, false, copy.fontSize); - renderer->drawNotificationString( - line, false, - x + (copy.promptWidth - lw) / 2, - startY + static_cast(i) * fm.lineHeight, - copy.fontSize, notificationTextColor - ); - #endif - } - } - - if (!ult::useRightAlignment) { - renderer->drawRect(x + copy.promptWidth - 1, y, 1, copy.promptHeight, edgeSeparatorColor); - renderer->drawRect(x, y + copy.promptHeight - 1, copy.promptWidth, 1, edgeSeparatorColor); - } else { - renderer->drawRect(x, y, 1, copy.promptHeight, edgeSeparatorColor); - renderer->drawRect(x, y + copy.promptHeight - 1, copy.promptWidth, 1, edgeSeparatorColor); - } - - renderer->disableScissoring(); - } - } - - #if IS_LAUNCHER_DIRECTIVE - void drawUltrahandLine(gfx::Renderer* renderer, const std::string& line, s32 x, s32 y, - u32 fontSize, s32 promptWidth) { - // Find position of "Ultrahand" in the line (case insensitive) - size_t ultrahandPos = std::string::npos; - std::string ultrahandToReplace; - - // Check for "Ultrahand" first - ultrahandPos = line.find(ult::CAPITAL_ULTRAHAND_PROJECT_NAME); - if (ultrahandPos != std::string::npos) { - ultrahandToReplace = ult::CAPITAL_ULTRAHAND_PROJECT_NAME; - } - - if (ultrahandPos == std::string::npos) { - // Fallback to normal drawing if not found - const auto [lw, lh] = renderer->getNotificationTextDimensions(line, false, fontSize); - renderer->drawNotificationString(line, false, x + (promptWidth - lw) / 2, y, fontSize, notificationTextColor); - return; - } - - // Split the line into parts - const std::string before = line.substr(0, ultrahandPos); - const std::string hand = ult::SPLIT_PROJECT_NAME_2; - const std::string after = line.substr(ultrahandPos + ultrahandToReplace.length()); - - // Calculate individual part widths to get accurate total width - s32 beforeWidth = 0, handWidth = 0, afterWidth = 0; - - if (!before.empty()) { - const auto [bw, bh] = renderer->getNotificationTextDimensions(before, false, fontSize); - beforeWidth = bw; - } - - if (!after.empty()) { - const auto [aw, ah] = renderer->getNotificationTextDimensions(after, false, fontSize); - afterWidth = aw; - } - - const auto [hw, hh] = renderer->getNotificationTextDimensions(hand, false, fontSize); - handWidth = hw; - - // Use shared utility to calculate Ultra width - const s32 ultraWidth = tsl::elm::calculateUltraTextWidth(renderer, fontSize, true); - - // Calculate total width and starting position for centering - const s32 totalWidth = beforeWidth + ultraWidth + handWidth + afterWidth; - s32 currentX = x + (promptWidth - totalWidth) / 2; - - // Draw each part in sequence - - // Draw "before" part - if (!before.empty()) { - renderer->drawNotificationString(before, false, currentX, y, fontSize, notificationTextColor); - currentX += beforeWidth; - } - - // Draw dynamic "Ultra" part using shared utility - currentX = tsl::elm::drawDynamicUltraText(renderer, currentX, y, fontSize, logoColor1, true); - - // Draw static "hand" part - renderer->drawNotificationString(hand, false, currentX, y, fontSize, logoColor2); - currentX += handWidth; - - // Draw "after" part - if (!after.empty()) { - renderer->drawNotificationString(after, false, currentX, y, fontSize, notificationTextColor); - } - } - #endif - - void update() { - if (!isActive()) { - return; - } - std::lock_guard lg(state_mutex_); - // Optional extra safety: skip if already inactive and queue empty - if (ult::launchingOverlay.load(std::memory_order_acquire) || - (!is_active_ && current_state_.activeText.empty() && pending_queue_.empty())) { - return; - } - - //std::lock_guard lg(state_mutex_); - if (generation_ != notificationGeneration.load(std::memory_order_acquire) || - !enabled_.load(std::memory_order_acquire)) - { - current_state_ = NotificationState{}; - is_active_ = false; - return; - } - - const u64 now = armTicksToNs(armGetSystemTick()); - const u64 elapsedMs = (current_state_.stateStartNs == 0) ? 0 : (now - current_state_.stateStartNs) / 1'000'000ULL; - - switch (current_state_.state) { - case PromptState::SlidingIn: - if (elapsedMs >= SLIDE_DURATION_MS) { - current_state_.state = PromptState::Visible; - current_state_.stateStartNs = now; - } - break; - case PromptState::Visible: - if (now >= current_state_.expireNs) { - current_state_.state = PromptState::SlidingOut; - current_state_.stateStartNs = now; - } - break; - case PromptState::SlidingOut: - if (elapsedMs >= SLIDE_DURATION_MS) { - const std::string fileToDelete = current_state_.fileName; - // Delete the JSON file safely - if (!fileToDelete.empty()) { - std::lock_guard lg(notificationJsonMutex); - const std::string fullPath = ult::NOTIFICATIONS_PATH + fileToDelete; - remove(fullPath.c_str()); // ignore errors for now - } - - current_state_ = NotificationState{}; - const bool hadNext = startNext_NoLock(); - if (!hadNext) { - is_active_ = false; - } - } - break; - default: break; - } - } - - bool isActive() const { - if (!ult::useNotifications) return false; - if (generation_ != notificationGeneration.load(std::memory_order_acquire)) return false; - std::lock_guard lg(state_mutex_); - if (is_active_) return true; - if (!pending_queue_.empty()) return true; - //if (pending_event_fire_.load(std::memory_order_acquire)) return true; - if (!current_state_.activeText.empty() && current_state_.state != PromptState::Inactive) return true; - return false; - } - - void shutdown() { - enabled_.store(false, std::memory_order_release); - notificationGeneration.fetch_add(1, std::memory_order_acq_rel); - generation_ = notificationGeneration.load(std::memory_order_acquire); - - std::lock_guard lg(state_mutex_); - while (!pending_queue_.empty()) pending_queue_.pop(); - current_state_ = NotificationState{}; - is_active_ = false; - //pending_event_fire_.store(false, std::memory_order_release); - } - - void forceShutdown() { - enabled_.store(false, std::memory_order_release); - //pending_event_fire_.store(false, std::memory_order_release); - } - - //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(); - triggerRumbleClick.store(true, std::memory_order_release); - - // reinitialize audio for changes from handheld to docked and vise versa - if (ult::expandedMemory && ult::useSoundEffects) - ult::AudioPlayer::reloadIfDockedChanged(); - - //if (auto& currGui = this->getCurrentGui(); currGui != nullptr) // TESTING DISABLED (EFFECTS NEED TO BE VERIFIED) - // currGui->restoreFocus(); - } - - /** - * @brief Hides the Gui - * - */ - void hide(bool useNoFade = false) { - - - if (useNoFade) { - // Immediately hide overlay - ult::isHidden.store(true); - this->m_shouldHide = true; - return; - } - - - #if IS_STATUS_MONITOR_DIRECTIVE - if (FullMode && !deactivateOriginalFooter) { - - if (this->m_disableNextAnimation) { - this->m_animationCounter = 0; - this->m_disableNextAnimation = false; - } - else { - this->m_fadeOutAnimationPlaying = true; - this->m_animationCounter = MAX_ANIMATION_COUNTER; - } - ult::isHidden.store(true); - this->onHide(); - } - #else - - if (this->m_disableNextAnimation) { - this->m_animationCounter = 0; - this->m_disableNextAnimation = false; - } - else { - this->m_fadeOutAnimationPlaying = true; - this->m_animationCounter = MAX_ANIMATION_COUNTER; - } - ult::isHidden.store(true); - this->onHide(); - #endif - triggerRumbleClick.store(true, std::memory_order_release); - } - - /** - * @brief Returns whether fade animation is playing - * - * @return whether fade animation is playing - */ - bool fadeAnimationPlaying() { - return this->m_fadeInAnimationPlaying || this->m_fadeOutAnimationPlaying; - } - - /** - * @brief Closes the Gui - * @note This makes the Tesla overlay exit and return back to the Tesla-Menu - * - */ - void close(bool forceClose = false) { - if (!forceClose && notification && notification->isActive()) { - this->closeAfter(); - this->hide(true); - return; - } - - this->m_shouldClose = true; - } - - /** - * @brief Closes the Gui - * @note This makes the Tesla overlay exit and return back to the Tesla-Menu - * - */ - void closeAfter() { - this->m_shouldCloseAfter = true; - - } - - /** - * @brief Gets the Overlay instance - * - * @return Overlay instance - */ - static inline Overlay* const get() { - return Overlay::s_overlayInstance; - } - - /** - * @brief Creates the initial Gui of an Overlay and moves the object to the Gui stack - * - * @tparam T - * @tparam Args - * @param args - * @return constexpr std::unique_ptr - */ - template - constexpr inline std::unique_ptr initially(Args&&... args) { - return std::make_unique(args...); - } - - private: - using GuiPtr = std::unique_ptr; - std::stack> m_guiStack; - static inline Overlay *s_overlayInstance = nullptr; - - bool m_fadeInAnimationPlaying = false, m_fadeOutAnimationPlaying = false; - u8 m_animationCounter = 0; - static constexpr int MAX_ANIMATION_COUNTER = 5; // Define the maximum animation counter value - - bool m_shouldHide = false; - bool m_shouldClose = false; - bool m_shouldCloseAfter = false; - - bool m_disableNextAnimation = false; - - bool m_closeOnExit; - - static inline std::atomic isNavigatingBackwards{false}; - bool justNavigated = false; - - /** - * @brief Initializes the Renderer - * - */ - void initScreen() { - gfx::Renderer::get().init(); - } - - /** - * @brief Exits the Renderer - * - */ - void exitScreen() { - gfx::Renderer::get().exit(); - } - - /** - * @brief Weather or not the Gui should get hidden - * - * @return should hide - */ - bool shouldHide() { - return this->m_shouldHide; - } - - /** - * @brief Weather or not hte Gui should get closed - * - * @return should close - */ - bool shouldClose() { - return this->m_shouldClose; - } - - /** - * @brief Weather or not hte Gui should get closed after - * - * @return should close after - */ - bool shouldCloseAfter() { - return this->m_shouldCloseAfter; - } - - - /** - * @brief Quadratic ease-in-out function - * - * @param t Normalized time (0 to 1) - * @return Eased value - */ - float calculateEaseInOut(float t) { - if (t < 0.5) { - return 2 * t * t; - } else { - return -1 + (4 - 2 * t) * t; - } - } - - /** - * @brief Handles fade in and fade out animations of the Overlay - * - */ - void animationLoop() { - - - if (this->m_fadeInAnimationPlaying) { - if (this->m_animationCounter < MAX_ANIMATION_COUNTER) { - this->m_animationCounter++; - } - - if (this->m_animationCounter >= MAX_ANIMATION_COUNTER) { - this->m_fadeInAnimationPlaying = false; - } - } - - if (this->m_fadeOutAnimationPlaying) { - if (this->m_animationCounter > 0) { - this->m_animationCounter--; - } - - if (this->m_animationCounter == 0) { - this->m_fadeOutAnimationPlaying = false; - this->m_shouldHide = true; - } - } - - // Calculate and set the opacity using an easing function - //float opacity = calculateEaseInOut(static_cast(this->m_animationCounter) / MAX_ANIMATION_COUNTER); - gfx::Renderer::setOpacity(calculateEaseInOut(static_cast(this->m_animationCounter) / MAX_ANIMATION_COUNTER)); - } - - - - /** - * @brief Overlay Main loop - * - */ - void loop(bool promptOnly = false) { - // Early exit check - avoid all work if shutting down - if (ult::launchingOverlay.load(std::memory_order_acquire)) { - return; - } - - // CRITICAL: Initialize to TRUE because stacks are added in init()! - static std::atomic screenshotStacksAdded{true}; - static std::atomic notificationCacheNeedsClearing{false}; - - auto& renderer = gfx::Renderer::get(); - renderer.startFrame(); - - // Handle main UI rendering - if (!promptOnly) { - - // In normal mode, ensure screenshots are enabled - // Only re-add if they were removed AND force-disable is not set - if (!screenshotStacksAdded.load(std::memory_order_acquire) && - !screenshotsAreForceDisabled.load(std::memory_order_acquire)) { - if (!screenshotStacksAdded.exchange(true, std::memory_order_acq_rel)) { - renderer.addScreenshotStacks(false); - } - } - - this->animationLoop(); - this->getCurrentGui()->update(); - this->getCurrentGui()->draw(&renderer); - - //notificationCacheNeedsClearing.store(true, std::memory_order_release); - } else { - // Prompt-only mode - temporarily remove screenshots - if (screenshotStacksAdded.load(std::memory_order_acquire) && - !screenshotsAreDisabled.load(std::memory_order_acquire) && - !screenshotsAreForceDisabled.load(std::memory_order_acquire)) { - - if (screenshotStacksAdded.exchange(false, std::memory_order_acq_rel)) { - renderer.removeScreenshotStacks(false); - } - } - renderer.clearScreen(); - } - - // Notification handling — safe, consistent, and null-guarded - { - if (notification && notification->isActive()) { - notification->update(); - notification->draw(&renderer, promptOnly); - - // Only set flag if it's not already set - notificationCacheNeedsClearing.exchange(true, std::memory_order_acq_rel); - - } else if (notificationCacheNeedsClearing.exchange(false, std::memory_order_acq_rel)) { - tsl::gfx::FontManager::clearNotificationCache(); - #if IS_STATUS_MONITOR_DIRECTIVE - if (wasRendering) { - wasRendering = false; - isRendering = true; - leventClear(&renderingStopEvent); - } - #endif - } - } - - renderer.endFrame(); - } - - // Calculate transition using ease-in-out curve instead of linear - float easeInOutCubic(float t) { - return t < 0.5f ? 4.0f * t * t * t : 1.0f - pow(-2.0f * t + 2.0f, 3.0f) / 2.0f; - } - - - - void handleInput(u64 keysDown, u64 keysHeld, bool touchDetected, const HidTouchState &touchPos, HidAnalogStickState joyStickPosLeft, HidAnalogStickState joyStickPosRight) { - if (!ult::internalTouchReleased.load(std::memory_order_acquire) || ult::launchingOverlay.load(std::memory_order_acquire)) - return; - - // Static variables to maintain state between function calls - static HidTouchState initialTouchPos = { 0 }; - static HidTouchState oldTouchPos = { 0 }; - static bool oldTouchDetected = false; - static elm::TouchEvent touchEvent, oldTouchEvent; - - static u64 buttonPressTime_ns = 0, lastKeyEventTime_ns = 0, keyEventInterval_ns = 67000000ULL; - static bool singlePressHandled = false; - static constexpr u64 CLICK_THRESHOLD_NS = 340000000ULL; // 340ms in nanoseconds - - - static bool hasScrolled = false; - static void* lastGuiPtr = nullptr; // Use void* instead - - auto& currentGui = this->getCurrentGui(); - - // Return early if current GUI is not available or internal touch is not released - if (!currentGui) { - - elm::Element::setInputMode(InputMode::Controller); - - oldTouchPos = { 0 }; - initialTouchPos = { 0 }; - touchEvent = elm::TouchEvent::None; - ult::stillTouching.store(false, std::memory_order_release); - ult::interruptedTouch.store(false, std::memory_order_release); - return; - } - - // Retrieve current focus and top/bottom elements of the GUI - auto currentFocus = currentGui->getFocusedElement(); - - - const bool interpreterIsRunning = ult::runningInterpreter.load(std::memory_order_acquire); - #if !IS_STATUS_MONITOR_DIRECTIVE - if (interpreterIsRunning) { - if (keysDown & KEY_UP && !(keysHeld & ~KEY_UP & ALL_KEYS_MASK)) { - currentFocus->shakeHighlight(FocusDirection::Up); - return; - } - else if (keysDown & KEY_DOWN && !(keysHeld & ~KEY_DOWN & ALL_KEYS_MASK)) { - currentFocus->shakeHighlight(FocusDirection::Down); - return; - } - else if (keysDown & KEY_LEFT && !(keysHeld & ~KEY_LEFT & ALL_KEYS_MASK)) { - currentFocus->shakeHighlight(FocusDirection::Left); - return; - } - else if (keysDown & KEY_RIGHT && !(keysHeld & ~KEY_RIGHT & ALL_KEYS_MASK)) { - currentFocus->shakeHighlight(FocusDirection::Right); - return; - } - } - #endif - - #if IS_STATUS_MONITOR_DIRECTIVE - if (FullMode && !deactivateOriginalFooter) { - if (ult::simulatedSelect.exchange(false, std::memory_order_acq_rel)) - keysDown |= KEY_A; - - if (ult::simulatedBack.exchange(false, std::memory_order_acq_rel)) - keysDown |= KEY_B; - - if (!overrideBackButton) { - if (keysDown & KEY_B && !(keysHeld & ~KEY_B & ALL_KEYS_MASK)) { - if (!currentGui->handleInput(KEY_B,0,{},{},{})) { - this->goBack(); - if (this->m_guiStack.size() >= 1) { - //triggerRumbleDoubleClick.store(true, std::memory_order_release); - //triggerExitSound.store(true, std::memory_order_release); - triggerExitFeedback(); - } - //ult::simulatedBackComplete = true; - } - return; - } - } - } else { - ult::simulatedSelect.exchange(false, std::memory_order_acq_rel); - ult::simulatedBack.exchange(false, std::memory_order_acq_rel); - } - #else - if (ult::simulatedSelect.exchange(false, std::memory_order_acq_rel)) - keysDown |= KEY_A; - - if (ult::simulatedBack.exchange(false, std::memory_order_acq_rel)) - keysDown |= KEY_B; - - if (!overrideBackButton) { - if (keysDown & KEY_B && !(keysHeld & ~KEY_B & ALL_KEYS_MASK)) { - if (!currentGui->handleInput(KEY_B,0,{},{},{})) { - this->goBack(); - if (this->m_guiStack.size() >= 1 && !interpreterIsRunning) { - //triggerRumbleDoubleClick.store(true, std::memory_order_release); - //triggerExitSound.store(true, std::memory_order_release); - triggerExitFeedback(); - } - //ult::simulatedBackComplete = true; - } - return; - } - } else { - if (keysDown & KEY_B && !(keysHeld & ~KEY_B & ALL_KEYS_MASK)) { - if (this->m_guiStack.size() >= 1 && !interpreterIsRunning) { - //triggerRumbleDoubleClick.store(true, std::memory_order_release); - //triggerExitSound.store(true, std::memory_order_release); - triggerExitFeedback(); - } - } - } - #endif - - // Reset touch state when GUI changes - if (currentGui.get() != lastGuiPtr) { // or just currentGui != lastGuiPtr if it's not a smart pointer - hasScrolled = false; - oldTouchEvent = elm::TouchEvent::None; - oldTouchDetected = false; - oldTouchPos = { 0 }; - initialTouchPos = { 0 }; - lastGuiPtr = currentGui.get(); // or just currentGui - } - - auto topElement = currentGui->getTopElement(); - - const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); - - if (!currentFocus && !ult::simulatedBack.load(std::memory_order_acquire) && !ult::stillTouching.load(std::memory_order_acquire) && !oldTouchDetected && !interpreterIsRunning) { - if (!topElement) return; - - if (!currentGui->initialFocusSet() || keysDown & (KEY_UP | KEY_DOWN | KEY_LEFT | KEY_RIGHT)) { - currentGui->requestFocus(topElement, FocusDirection::None); - currentGui->markInitialFocusSet(); - } - } - if (isNavigatingBackwards.load(std::memory_order_acquire) && !currentFocus && topElement && keysDown & (KEY_UP | KEY_DOWN | KEY_LEFT | KEY_RIGHT)) { - currentGui->requestFocus(topElement, FocusDirection::None); - currentGui->markInitialFocusSet(); - isNavigatingBackwards.store(false, std::memory_order_release); - - // Reset navigation timing to prevent fast scrolling - buttonPressTime_ns = currentTime_ns; - lastKeyEventTime_ns = buttonPressTime_ns; - singlePressHandled = false; - } - - - - if (!currentFocus && !touchDetected && (!oldTouchDetected || oldTouchEvent == elm::TouchEvent::Scroll)) { - if (!isNavigatingBackwards.load(std::memory_order_acquire) && - !ult::shortTouchAndRelease.load(std::memory_order_acquire) && - !ult::longTouchAndRelease.load(std::memory_order_acquire) && - !ult::simulatedSelect.load(std::memory_order_acquire) && - !ult::simulatedBack.load(std::memory_order_acquire) && - !ult::simulatedNextPage.load(std::memory_order_acquire) - && topElement) { - - if (oldTouchEvent == elm::TouchEvent::Scroll) { - hasScrolled = true; - } - if (!hasScrolled) { - currentGui->removeFocus(); - currentGui->requestFocus(topElement, FocusDirection::None); - } - } else if (ult::longTouchAndRelease.exchange(false, std::memory_order_acq_rel)) { - hasScrolled = true; - } else if (ult::shortTouchAndRelease.exchange(false, std::memory_order_acq_rel)) { - hasScrolled = true; - } - } - - bool handled = false; - elm::Element* parentElement = currentFocus; - - while (!handled && parentElement) { - handled = parentElement->onClick(keysDown) || parentElement->handleInput(keysDown, keysHeld, touchPos, joyStickPosLeft, joyStickPosRight); - parentElement = parentElement->getParent(); - } - - if (currentGui != this->getCurrentGui()) return; - - handled |= currentGui->handleInput(keysDown, keysHeld, touchPos, joyStickPosLeft, joyStickPosRight); - - - // Navigational boundary cases for handling wrapping - static bool lastDirectionPressed = true; - const bool directionPressed = ((keysHeld & KEY_UP) || (keysHeld & KEY_DOWN) || (keysHeld & KEY_LEFT) || (keysHeld & KEY_RIGHT)); - - if (!directionPressed && lastDirectionPressed) - tsl::elm::s_directionalKeyReleased.store(true, std::memory_order_release); - else if (directionPressed && lastDirectionPressed) - tsl::elm::s_directionalKeyReleased.store(false, std::memory_order_release); - - lastDirectionPressed = directionPressed; - - const float currentScrollVelocity = tsl::elm::s_currentScrollVelocity.load(std::memory_order_acquire); - - if (hasScrolled) { - const bool singleArrowKeyPress = ((keysHeld & KEY_UP) != 0) + ((keysHeld & KEY_DOWN) != 0) + ((keysHeld & KEY_LEFT) != 0) + ((keysHeld & KEY_RIGHT) != 0) == 1 && !(keysHeld & ~((currentScrollVelocity != 0.0f ? KEY_A | KEY_UP : KEY_UP) | KEY_DOWN | KEY_LEFT | KEY_RIGHT) & ALL_KEYS_MASK); - - if (singleArrowKeyPress) { - // const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); - buttonPressTime_ns = currentTime_ns; - lastKeyEventTime_ns = currentTime_ns; - hasScrolled = false; - isNavigatingBackwards.store(false, std::memory_order_release); - } - } else { - if (!touchDetected && !oldTouchDetected && !handled && currentFocus && !ult::stillTouching.load(std::memory_order_acquire) && !interpreterIsRunning) { - static bool shouldShake = true; - const bool singleArrowKeyPress = ((keysHeld & KEY_UP) != 0) + ((keysHeld & KEY_DOWN) != 0) + ((keysHeld & KEY_LEFT) != 0) + ((keysHeld & KEY_RIGHT) != 0) == 1 && !(keysHeld & ~((currentScrollVelocity != 0.0f ? KEY_A | KEY_UP: KEY_UP) | KEY_DOWN | KEY_LEFT | KEY_RIGHT) & ALL_KEYS_MASK); - - if (singleArrowKeyPress) { - //const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); - - if (keysDown) { - buttonPressTime_ns = currentTime_ns; - lastKeyEventTime_ns = currentTime_ns; - singlePressHandled = false; - // Immediate single press action - if (keysHeld & KEY_UP && !(keysHeld & ~KEY_UP & ALL_KEYS_MASK)) - currentGui->requestFocus(topElement, FocusDirection::Up, shouldShake); - else if (keysHeld & KEY_DOWN && !(keysHeld & ~KEY_DOWN & ALL_KEYS_MASK)) { - currentGui->requestFocus(currentFocus->getParent(), FocusDirection::Down, shouldShake); - //isTopElement = false; - } - else if (keysHeld & KEY_LEFT && !(keysHeld & ~KEY_LEFT & ALL_KEYS_MASK)) - currentGui->requestFocus(currentFocus->getParent(), FocusDirection::Left, shouldShake); - else if (keysHeld & KEY_RIGHT && !(keysHeld & ~KEY_RIGHT & ALL_KEYS_MASK)) - currentGui->requestFocus(currentFocus->getParent(), FocusDirection::Right, shouldShake); - } - - if (keysHeld & ~KEY_DOWN & ~KEY_UP & ~KEY_LEFT & ~KEY_RIGHT & ALL_KEYS_MASK) // reset - buttonPressTime_ns = currentTime_ns; - - const u64 durationSincePress_ns = currentTime_ns - buttonPressTime_ns; - const u64 durationSinceLastEvent_ns = currentTime_ns - lastKeyEventTime_ns; - - if (!singlePressHandled && durationSincePress_ns >= CLICK_THRESHOLD_NS) { - singlePressHandled = true; - } - - if (!tsl::elm::isTableScrolling.load(std::memory_order_acquire)) { - // Calculate transition factor (t) from 0 to 1 based on how far we are from the transition point - static constexpr u64 transitionPoint_ns = 2000000000ULL; // 2000ms in nanoseconds - static constexpr u64 initialInterval_ns = 67000000ULL; // 67ms in nanoseconds - static constexpr u64 shortInterval_ns = 10000000ULL; // 10ms in nanoseconds - - const float t = (durationSincePress_ns >= transitionPoint_ns) ? 1.0f : - (float)durationSincePress_ns / (float)transitionPoint_ns; - // Smooth transition between intervals using linear interpolation - keyEventInterval_ns = ((1.0f - t) * initialInterval_ns + t * shortInterval_ns); - } else { - // Table scrolling - faster timing - static constexpr u64 transitionPoint_ns = 200000000ULL; // 300ms (faster transition) - static constexpr u64 initialInterval_ns = 33000000ULL; // 33ms (faster initial) - static constexpr u64 shortInterval_ns = 5000000ULL; // 5ms (faster sustained) - - const float t = (durationSincePress_ns >= transitionPoint_ns) ? 1.0f : - (float)durationSincePress_ns / (float)transitionPoint_ns; - // Smooth transition between intervals using linear interpolation - keyEventInterval_ns = ((1.0f - t) * initialInterval_ns + t * shortInterval_ns); - } - - - - if (singlePressHandled && durationSinceLastEvent_ns >= keyEventInterval_ns) { - lastKeyEventTime_ns = currentTime_ns; - if (keysHeld & KEY_UP && !(keysHeld & ~((currentScrollVelocity != 0.0f ? KEY_A | KEY_UP: KEY_UP)) & ALL_KEYS_MASK)) - currentGui->requestFocus(topElement, FocusDirection::Up, false); - else if (keysHeld & KEY_DOWN && !(keysHeld & ~((currentScrollVelocity != 0.0f ? KEY_A | KEY_DOWN: KEY_DOWN)) & ALL_KEYS_MASK)) { - currentGui->requestFocus(currentFocus->getParent(), FocusDirection::Down, false); - //isTopElement = false; - } - else if (keysHeld & KEY_LEFT && !(keysHeld & ~KEY_LEFT & ALL_KEYS_MASK)) - currentGui->requestFocus(currentFocus->getParent(), FocusDirection::Left, false); - else if (keysHeld & KEY_RIGHT && !(keysHeld & ~KEY_RIGHT & ALL_KEYS_MASK)) - currentGui->requestFocus(currentFocus->getParent(), FocusDirection::Right, false); - } - #if !IS_STATUS_MONITOR_DIRECTIVE - } else { - buttonPressTime_ns = lastKeyEventTime_ns = currentTime_ns; - #endif - } - } - } - - #if !IS_STATUS_MONITOR_DIRECTIVE - if (!touchDetected && !interpreterIsRunning && topElement) { - #else - if (!disableJumpTo && !touchDetected && !interpreterIsRunning && topElement) { - #endif - // Shared constants used by ZL/ZR buttons - static constexpr u64 INITIAL_HOLD_THRESHOLD_NS = 400000000ULL; - static constexpr u64 HOLD_THRESHOLD_NS = 300000000ULL; // 300ms to start continuous - static constexpr u64 RAPID_CLICK_WINDOW_NS = 500000000ULL; // 500ms window for rapid clicking - static constexpr u64 RAPID_MODE_TIMEOUT_NS = 1000000000ULL; // 1s timeout to exit rapid mode - // Acceleration timing constants - static constexpr u64 ACCELERATION_POINT_NS = 1500000000ULL; // 1.5s transition point - static constexpr u64 INITIAL_INTERVAL_NS = 67000000ULL; // 67ms initial interval - static constexpr u64 FAST_INTERVAL_NS = 10000000ULL; // 10ms fast interval - - //const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); - - // Detect PHYSICAL key states (whether key is actually pressed) - const bool lKeyPressed = (keysHeld & KEY_L); - const bool rKeyPressed = (keysHeld & KEY_R); - const bool zlKeyPressed = (keysHeld & KEY_ZL); - const bool zrKeyPressed = (keysHeld & KEY_ZR); - - // Detect if other keys are pressed (for preventing timer resets) - const bool notlKeyPressed = (keysHeld & ~KEY_L & ALL_KEYS_MASK); - const bool notrKeyPressed = (keysHeld & ~KEY_R & ALL_KEYS_MASK); - const bool notzlKeyPressed = (keysHeld & ~KEY_ZL & ALL_KEYS_MASK); - const bool notzrKeyPressed = (keysHeld & ~KEY_ZR & ALL_KEYS_MASK); - - // Handle L button (simple jump to top on release, but not if held too long) - { - static bool lKeyWasPressed = false; - static bool lWasIsolated = false; // Track if L was isolated when first pressed - static u64 lButtonPressStart_ns = 0; - - if (lKeyPressed) { - - if (!lKeyWasPressed) { - // L key physically pressed for the first time (start timer) - lButtonPressStart_ns = currentTime_ns; - lWasIsolated = !notlKeyPressed; // Remember if it started isolated - } - // Don't reset timer if other keys are pressed after L was already held - lKeyWasPressed = true; - } else { - if (lKeyWasPressed) { - // L key physically released - only jump to top if was isolated when first pressed and not held too long - if (lWasIsolated && !(keysHeld & ~KEY_L & ALL_KEYS_MASK)) { // Was isolated initially and no other keys held at release - const u64 holdDuration = currentTime_ns - lButtonPressStart_ns; - if (holdDuration < INITIAL_HOLD_THRESHOLD_NS) { - jumpToTop.store(true, std::memory_order_release); - currentGui->requestFocus(topElement, FocusDirection::None); - } - } - } - lKeyWasPressed = false; - lWasIsolated = false; - } - } - - // Handle R button (simple jump to bottom on release, but not if held too long) - { - static bool rKeyWasPressed = false; - static bool rWasIsolated = false; // Track if R was isolated when first pressed - static u64 rButtonPressStart_ns = 0; - - if (rKeyPressed) { - if (!rKeyWasPressed) { - // R key physically pressed for the first time (start timer) - rButtonPressStart_ns = currentTime_ns; - rWasIsolated = !notrKeyPressed; // Remember if it started isolated - } - // Don't reset timer if other keys are pressed after R was already held - rKeyWasPressed = true; - } else { - if (rKeyWasPressed) { - // R key physically released - only jump to bottom if was isolated when first pressed and not held too long - if (rWasIsolated && !(keysHeld & ~KEY_R & ALL_KEYS_MASK)) { // Was isolated initially and no other keys held at release - const u64 holdDuration = currentTime_ns - rButtonPressStart_ns; - if (holdDuration < INITIAL_HOLD_THRESHOLD_NS) { - jumpToBottom.store(true, std::memory_order_release); - currentGui->requestFocus(topElement, FocusDirection::None); - } - } - } - rKeyWasPressed = false; - rWasIsolated = false; - } - } - - // Handle ZL button (skip up with hold) - { - static u64 zlLastClickTime_ns = 0; - static bool zlKeyWasPressed = false; - static bool zlWasIsolated = false; // Track if ZL was isolated when first pressed - static bool zlInRapidClickMode = false; - static u64 zlFirstClickPressStart_ns = 0; // Track timing for first clicks only - - // Check if we should exit rapid click mode due to timeout - if (zlInRapidClickMode && (currentTime_ns - zlLastClickTime_ns) > RAPID_MODE_TIMEOUT_NS) { - zlInRapidClickMode = false; - } - - if (zlKeyPressed) { - if (!zlKeyWasPressed) { - // ZL key physically pressed for the first time - const u64 timeSinceLastClick = currentTime_ns - zlLastClickTime_ns; - - zlWasIsolated = !notzlKeyPressed; // Remember if it started isolated - - // Track press start time for first clicks (when not in rapid mode) - if (!zlInRapidClickMode) { - zlFirstClickPressStart_ns = currentTime_ns; - } - - // Enter rapid click mode if clicking within window - if (timeSinceLastClick <= RAPID_CLICK_WINDOW_NS) { - zlInRapidClickMode = true; - } - - // Only trigger immediately if in rapid click mode AND was isolated initially - if (zlInRapidClickMode && zlWasIsolated) { - skipUp.store(true, std::memory_order_release); - currentGui->requestFocus(topElement, FocusDirection::None); - zlLastClickTime_ns = currentTime_ns; - } - } - - // Check for hold behavior - ONLY if in rapid click mode AND was isolated initially - if (zlInRapidClickMode && zlWasIsolated) { - static u64 zlButtonPressStart_ns = 0; - static u64 zlLastHoldTrigger_ns = 0; - static bool zlHoldTriggered = false; - - // Initialize on new press - if (!zlKeyWasPressed) { - zlButtonPressStart_ns = currentTime_ns; - zlLastHoldTrigger_ns = currentTime_ns; - zlHoldTriggered = false; - } - - const u64 holdDuration = currentTime_ns - zlButtonPressStart_ns; - - if (holdDuration >= HOLD_THRESHOLD_NS) { - // Calculate dynamic interval based on hold duration (accelerating) - const float t = (holdDuration >= ACCELERATION_POINT_NS) ? 1.0f : - (float)holdDuration / (float)ACCELERATION_POINT_NS; - const u64 currentInterval = ((1.0f - t) * INITIAL_INTERVAL_NS + t * FAST_INTERVAL_NS); - - const u64 timeSinceLastHoldTrigger = currentTime_ns - zlLastHoldTrigger_ns; - - if (!zlHoldTriggered || timeSinceLastHoldTrigger >= currentInterval) { - // Trigger skip - skipUp.store(true, std::memory_order_release); - currentGui->requestFocus(topElement, FocusDirection::None); - zlHoldTriggered = true; - zlLastHoldTrigger_ns = currentTime_ns; - zlLastClickTime_ns = currentTime_ns; // Keep rapid mode active - } - } - } - - zlKeyWasPressed = true; - } else { - if (zlKeyWasPressed) { - // ZL key physically released - only trigger if was isolated initially and no other keys held at release - if (!zlInRapidClickMode && zlWasIsolated && !(keysHeld & ~KEY_ZL & ALL_KEYS_MASK)) { - const u64 holdDuration = currentTime_ns - zlFirstClickPressStart_ns; - - // Only trigger if not held too long - if (holdDuration < INITIAL_HOLD_THRESHOLD_NS) { - skipUp.store(true, std::memory_order_release); - currentGui->requestFocus(topElement, FocusDirection::None); - zlLastClickTime_ns = currentTime_ns; - zlInRapidClickMode = true; // Enter rapid mode after first release - } - } - } - zlKeyWasPressed = false; - zlWasIsolated = false; - } - } - - // Handle ZR button (skip down with hold) - { - static u64 zrLastClickTime_ns = 0; - static bool zrKeyWasPressed = false; - static bool zrWasIsolated = false; // Track if ZR was isolated when first pressed - static bool zrInRapidClickMode = false; - static u64 zrFirstClickPressStart_ns = 0; // Track timing for first clicks only - - // Check if we should exit rapid click mode due to timeout - if (zrInRapidClickMode && (currentTime_ns - zrLastClickTime_ns) > RAPID_MODE_TIMEOUT_NS) { - zrInRapidClickMode = false; - } - - if (zrKeyPressed) { - if (!zrKeyWasPressed) { - // ZR key physically pressed for the first time - const u64 timeSinceLastClick = currentTime_ns - zrLastClickTime_ns; - - zrWasIsolated = !notzrKeyPressed; // Remember if it started isolated - - // Track press start time for first clicks (when not in rapid mode) - if (!zrInRapidClickMode) { - zrFirstClickPressStart_ns = currentTime_ns; - } - - // Enter rapid click mode if clicking within window - if (timeSinceLastClick <= RAPID_CLICK_WINDOW_NS) { - zrInRapidClickMode = true; - } - - // Only trigger immediately if in rapid click mode AND was isolated initially - if (zrInRapidClickMode && zrWasIsolated) { - skipDown.store(true, std::memory_order_release); - currentGui->requestFocus(topElement, FocusDirection::None); - zrLastClickTime_ns = currentTime_ns; - } - } - - // Check for hold behavior - ONLY if in rapid click mode AND was isolated initially - if (zrInRapidClickMode && zrWasIsolated) { - static u64 zrButtonPressStart_ns = 0; - static u64 zrLastHoldTrigger_ns = 0; - static bool zrHoldTriggered = false; - - // Initialize on new press - if (!zrKeyWasPressed) { - zrButtonPressStart_ns = currentTime_ns; - zrLastHoldTrigger_ns = currentTime_ns; - zrHoldTriggered = false; - } - - const u64 holdDuration = currentTime_ns - zrButtonPressStart_ns; - - if (holdDuration >= HOLD_THRESHOLD_NS) { - // Calculate dynamic interval based on hold duration (accelerating) - const float t = (holdDuration >= ACCELERATION_POINT_NS) ? 1.0f : - (float)holdDuration / (float)ACCELERATION_POINT_NS; - const u64 currentInterval = ((1.0f - t) * INITIAL_INTERVAL_NS + t * FAST_INTERVAL_NS); - - const u64 timeSinceLastHoldTrigger = currentTime_ns - zrLastHoldTrigger_ns; - - if (!zrHoldTriggered || timeSinceLastHoldTrigger >= currentInterval) { - // Trigger skip - skipDown.store(true, std::memory_order_release); - currentGui->requestFocus(topElement, FocusDirection::None); - zrHoldTriggered = true; - zrLastHoldTrigger_ns = currentTime_ns; - zrLastClickTime_ns = currentTime_ns; // Keep rapid mode active - } - } - } - - zrKeyWasPressed = true; - } else { - if (zrKeyWasPressed) { - // ZR key physically released - only trigger if was isolated initially and no other keys held at release - if (!zrInRapidClickMode && zrWasIsolated && !(keysHeld & ~KEY_ZR & ALL_KEYS_MASK)) { - const u64 holdDuration = currentTime_ns - zrFirstClickPressStart_ns; - - // Only trigger if not held too long - if (holdDuration < INITIAL_HOLD_THRESHOLD_NS) { - skipDown.store(true, std::memory_order_release); - currentGui->requestFocus(topElement, FocusDirection::None); - zrLastClickTime_ns = currentTime_ns; - zrInRapidClickMode = true; // Enter rapid mode after first release - } - } - } - zrKeyWasPressed = false; - zrWasIsolated = false; - } - } - } - - //if (keysDown & KEY_ZL) { - // //while (tsl::notification && tsl::notification->isActive()) { - // // tsl::notification->update(true, true); // No file ops, allow state transitions - // // svcSleepThread(10'000'000); // 1ms sleep - // //} - // if (notification) - // notification->forceShutdown(); - //} - - - if (!touchDetected && oldTouchDetected && currentGui && topElement) { - topElement->onTouch(elm::TouchEvent::Release, oldTouchPos.x, oldTouchPos.y, oldTouchPos.x, oldTouchPos.y, initialTouchPos.x, initialTouchPos.y); - } - - // Cache common calculations - // Use consistent edge padding equal to halfGap (matching drawing code) - const float edgePadding = ult::halfGap.load(std::memory_order_acquire) - 5; - const float buttonStartX = edgePadding; - - // Calculate button positions matching the drawing code - const float backLeftEdge = buttonStartX + ult::layerEdge; - const float backRightEdge = backLeftEdge + ult::backWidth.load(std::memory_order_acquire); - const float selectLeftEdge = backRightEdge; - const float selectRightEdge = selectLeftEdge + ult::selectWidth.load(std::memory_order_acquire); - const float nextPageLeftEdge = ult::noClickableItems.load(std::memory_order_acquire) ? backRightEdge : selectRightEdge; - const float nextPageRightEdge = nextPageLeftEdge + ult::nextPageWidth.load(std::memory_order_acquire); - - const float menuRightEdge = 245.0f + ult::layerEdge - 13; - const u32 footerY = cfg::FramebufferHeight - 73U + 1; - static std::vector lastSimulatedTouch = {false, false, false, false}; - - // Touch region calculations - const bool backTouched = (touchPos.x >= backLeftEdge && touchPos.x < backRightEdge && touchPos.y > footerY) && - (initialTouchPos.x >= backLeftEdge && initialTouchPos.x < backRightEdge && initialTouchPos.y > footerY); - - const bool selectTouched = !ult::noClickableItems.load(std::memory_order_acquire) && - (touchPos.x >= selectLeftEdge && touchPos.x < selectRightEdge && touchPos.y > footerY) && - (initialTouchPos.x >= selectLeftEdge && initialTouchPos.x < selectRightEdge && initialTouchPos.y > footerY); - - const bool nextPageTouched = (touchPos.x >= nextPageLeftEdge && touchPos.x < nextPageRightEdge && touchPos.y > footerY) && - (initialTouchPos.x >= nextPageLeftEdge && initialTouchPos.x < nextPageRightEdge && initialTouchPos.y > footerY); - - const bool menuTouched = (touchPos.x > ult::layerEdge+7U && touchPos.x <= menuRightEdge && touchPos.y > 10U && touchPos.y <= 83U) && - (initialTouchPos.x > ult::layerEdge+7U && initialTouchPos.x <= menuRightEdge && initialTouchPos.y > 10U && initialTouchPos.y <= 83U); - - ult::touchingBack.store(backTouched, std::memory_order_release); - ult::touchingSelect.store(selectTouched, std::memory_order_release); - ult::touchingNextPage.store(nextPageTouched, std::memory_order_release); - ult::touchingMenu.store(menuTouched, std::memory_order_release); - - 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) { - tsl::elm::g_disableMenuCacheOnReturn.store(true, std::memory_order_release); - - // If there is exactly one GUI and an active notification, handle that first - if (this->m_guiStack.size() == 1 && notification && notification->isActive()) { - this->close(); - return; - } - - isNavigatingBackwards.store(true, std::memory_order_release); - - // Clamp count to available stack size to prevent underflow - const u32 actualCount = std::min(count, static_cast(this->m_guiStack.size())); - - // Special case: if we don't close on exit and popping everything would leave us with 0 or 1 GUI - if (!this->m_closeOnExit && this->m_guiStack.size() <= actualCount) { - this->hide(); - return; - } - - if (actualCount > 1) - tsl::elm::skipDeconstruction.store(true, std::memory_order_release); - - // Pop the specified number of GUIs - for (u32 i = 0; i < actualCount && !this->m_guiStack.empty(); ++i) { - this->m_guiStack.pop(); - } - - tsl::elm::skipDeconstruction.exchange(false, std::memory_order_acq_rel); - - // Close overlay if stack is empty - if (this->m_guiStack.empty()) { - this->close(); - } else { - //triggerRumbleDoubleClick.store(true, std::memory_order_release); - //triggerExitSound.store(true, std::memory_order_release); - } - - } - - void pop(u32 count = 1) { - 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); - - //ult::initRumble(); // initialize rumble - - enum WaiterObject { - WaiterObject_HomeButton, - WaiterObject_PowerButton, - WaiterObject_CaptureButton, - WaiterObject_Count - }; - - // Construct waiter - Waiter objects[3] = { - [WaiterObject_HomeButton] = waiterForEvent(&homeButtonPressEvent), - [WaiterObject_PowerButton] = waiterForEvent(&powerButtonPressEvent), - [WaiterObject_CaptureButton] = waiterForEvent(&captureButtonPressEvent), - }; - - u64 currentTouchTick = 0; - auto lastTouchX = 0; - auto lastTouchY = 0; - - // Preset touch boundaries - constexpr int SWIPE_RIGHT_BOUND = 16; // 16 + 80 - constexpr int SWIPE_LEFT_BOUND = (1280 - 16); - constexpr u64 TOUCH_THRESHOLD_NS = 150'000'000ULL; // 150ms in nanoseconds - constexpr u64 FAST_SWAP_THRESHOLD_NS = 150'000'000ULL; - - // Global underscan monitoring - run at most once every 300ms - auto lastUnderscanPixels = std::make_pair(0, 0); - bool firstUnderscanCheck = true; - u64 lastUnderscanCheckNs = 0; // store last execution in nanoseconds - constexpr u64 UNDERSCAN_INTERVAL_NS = 300'000'000ULL; // 300ms in ns - - s32 idx; - Result rc; - - std::string currentTitleID; - - u64 lastPollTick = 0; - u64 resetStartTick = armGetSystemTick(); - const u64 startNs = armTicksToNs(resetStartTick); - - ult::lastTitleID = ult::getTitleIdAsString(); - - //u64 elapsedTime_ns; - - // Notification variables - u64 lastNotifCheck = 0; - std::vector shownFiles; - std::string text; - int fontSize; - int priority; - time_t creationTime; - - - while (shData->running.load(std::memory_order_acquire)) { - - 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 - { - - // Poll Title ID every 1 seconds - if (!ult::resetForegroundCheck.load(std::memory_order_acquire)) { - const u64 elapsedNs = armTicksToNs(nowTick - lastPollTick); - if (elapsedNs >= 1'000'000'000ULL) { - lastPollTick = nowTick; - - currentTitleID = ult::getTitleIdAsString(); - if (currentTitleID != ult::lastTitleID) { - ult::lastTitleID = currentTitleID; - ult::resetForegroundCheck.store(true, std::memory_order_release); - resetStartTick = nowTick; - } - } - } - - // If a reset is scheduled, trigger after 3.5s delay - if (ult::resetForegroundCheck.load(std::memory_order_acquire)) { - const u64 resetElapsedNs = armTicksToNs(nowTick - resetStartTick); - if (resetElapsedNs >= 3'500'000'000ULL) { - if (shData->overlayOpen && ult::currentForeground.load(std::memory_order_acquire)) { - #if IS_STATUS_MONITOR_DIRECTIVE - if (!isValidOverlayMode()) - hlp::requestForeground(true, false); - #else - hlp::requestForeground(true, false); - #endif - } - ult::resetForegroundCheck.store(false, std::memory_order_release); - } - } - - if (firstUnderscanCheck || (nowNs - lastUnderscanCheckNs) >= UNDERSCAN_INTERVAL_NS) { - 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); - - if (armTicksToNs(nowTick - lastNotifCheck) >= 300'000'000ULL) { - lastNotifCheck = nowTick; - - DIR* dir = opendir(ult::NOTIFICATIONS_PATH.c_str()); - if (dir) { - - if (ult::useNotifications) { - const std::string& notifPath = ult::NOTIFICATIONS_PATH; - - // --- Prune missing files from shownFiles --- - for (auto it = shownFiles.begin(); it != shownFiles.end();) { - const std::string fullPath = notifPath + *it; - if (access(fullPath.c_str(), F_OK) != 0) { - it = shownFiles.erase(it); - } else { - ++it; - } - } - - // Reuse existing variables - track best file as we scan - static std::string bestFilename; - static std::string bestFullPath; - static time_t bestCreationTime; - static int bestPriority; - - bestFilename.clear(); - bestFullPath.clear(); - bestPriority = -1; - bestCreationTime = 0; - bool foundAny = false; - - struct dirent* entry; - - // --- Find the best notification file in one pass --- - while ((entry = readdir(dir)) != nullptr) { - if (entry->d_type != DT_REG) continue; - - const char* fname = entry->d_name; - const size_t filenameLen = strlen(fname); - - // Must end with ".notify" - if (filenameLen <= 7 || strcmp(fname + filenameLen - 7, ".notify") != 0) - continue; - - // Skip if already shown - if (std::find(shownFiles.begin(), shownFiles.end(), fname) != shownFiles.end()) - continue; - - // --- Build path --- - static std::string fullPath; - fullPath = notifPath; - fullPath += fname; - - // --- Get file creation/modification time --- - struct stat fileStat; - creationTime = 0; - if (stat(fullPath.c_str(), &fileStat) == 0) { - creationTime = fileStat.st_mtime; - } - - // --- Read priority from JSON --- - priority = 20; // default (reuse existing variable) - std::unique_ptr root( - ult::readJsonFromFile(fullPath), ult::JsonDeleter()); - if (root) { - cJSON* croot = reinterpret_cast(root.get()); - cJSON* priorityObj = cJSON_GetObjectItemCaseSensitive(croot, "priority"); - if (priorityObj && cJSON_IsNumber(priorityObj)) { - priority = static_cast(priorityObj->valuedouble); - } - } - - // --- Is this better than current best? --- - const bool isBetter = !foundAny || - (priority > bestPriority) || - (priority == bestPriority && creationTime < bestCreationTime); - - if (isBetter) { - bestFilename = fname; - bestFullPath = fullPath; - bestCreationTime = creationTime; - bestPriority = priority; - foundAny = true; - } - } - - closedir(dir); - - // --- Process the best file --- - if (foundAny) { - text = ult::getStringFromJsonFile(bestFullPath, "text"); - if (!text.empty()) { - fontSize = 28; // default (reuse existing variable) - - std::unique_ptr root( - ult::readJsonFromFile(bestFullPath), ult::JsonDeleter()); - if (root) { - cJSON* croot = reinterpret_cast(root.get()); - cJSON* fontSizeObj = cJSON_GetObjectItemCaseSensitive(croot, "font_size"); - if (fontSizeObj && cJSON_IsNumber(fontSizeObj)) { - fontSize = std::clamp(static_cast(fontSizeObj->valuedouble), 1, 34); - } - } - - // --- Show notification safely --- - if (notification) { - notification->show(text, fontSize, bestPriority, bestFilename); - } - - // Mark file as shown - shownFiles.push_back(bestFilename); - } - } - - } else { - // --- Notifications disabled: delete all files --- - struct dirent* entry; - static std::string fullPath; - - while ((entry = readdir(dir)) != nullptr) { - if (entry->d_type != DT_REG) continue; - - const char* fname = entry->d_name; - const size_t len = strlen(fname); - - if (len > 7 && strcmp(fname + len - 7, ".notify") == 0) { - fullPath.clear(); - fullPath = ult::NOTIFICATIONS_PATH; - fullPath.append(fname, len); - - remove(fullPath.c_str()); - } - } - closedir(dir); - } - } - } - } - - - if (ult::launchingOverlay.load(std::memory_order_acquire)) - break; - std::scoped_lock lock(shData->dataMutex); - if (ult::launchingOverlay.load(std::memory_order_acquire)) - break; - - // Flush any pending rumble triggers when feedback is off - if (!ult::useHapticFeedback) { - triggerRumbleClick.exchange(false, std::memory_order_acq_rel); - triggerRumbleDoubleClick.exchange(false, std::memory_order_acq_rel); - } else { - ult::checkAndReinitRumble(); - - if (triggerRumbleDoubleClick.exchange(false)) { - if (!ult::doubleClickActive.load(std::memory_order_acquire)) { - ult::rumbleDoubleClick(); - } - triggerRumbleClick.exchange(false); - } else if (triggerRumbleClick.exchange(false)) { - ult::rumbleClick(); - } - - //const u64 _nowNs = armTicksToNs(armGetSystemTick()); - - ult::processRumbleStop(nowNs); - ult::processRumbleDoubleClick(nowNs); - } - - // Flush any pending sound triggers when effects are off - - if (ult::expandedMemory) { - if (!ult::useSoundEffects || disableSound.load(std::memory_order_acquire)) { - triggerNavigationSound.exchange(false, std::memory_order_acq_rel); - triggerEnterSound.exchange(false, std::memory_order_acq_rel); - triggerExitSound.exchange(false, std::memory_order_acq_rel); - triggerWallSound.exchange(false, std::memory_order_acq_rel); - triggerOnSound.exchange(false, std::memory_order_acq_rel); - triggerOffSound.exchange(false, std::memory_order_acq_rel); - triggerSettingsSound.exchange(false, std::memory_order_acq_rel); - triggerMoveSound.exchange(false, std::memory_order_acq_rel); - } else { - if (reloadSoundCacheNow.exchange(false, std::memory_order_acq_rel)) { - ult::AudioPlayer::reloadAllSounds(); - } - - if (triggerNavigationSound.exchange(false)) { - ult::AudioPlayer::playNavigateSound(); - } else if (triggerEnterSound.exchange(false)) { - ult::AudioPlayer::playEnterSound(); - } else if (triggerExitSound.exchange(false)) { - ult::AudioPlayer::playExitSound(); - } else if (triggerWallSound.exchange(false)) { - ult::AudioPlayer::playWallSound(); - } else if (triggerOnSound.exchange(false)) { - ult::AudioPlayer::playOnSound(); - } else if (triggerOffSound.exchange(false)) { - ult::AudioPlayer::playOffSound(); - } else if (triggerSettingsSound.exchange(false)) { - ult::AudioPlayer::playSettingsSound(); - } else if (triggerMoveSound.exchange(false)) { - ult::AudioPlayer::playMoveSound(); - } - - //if (clearSoundCacheNow.exchange(false, std::memory_order_acq_rel)) { - // //ult::AudioPlayer::unloadAllSounds(ult::AudioPlayer::SoundType::Wall); - // ult::AudioPlayer::unloadAllSounds({ult::AudioPlayer::SoundType::Wall}); - // //ult::AudioPlayer::unloadAllSounds(); - // //clearSoundCacheNow.store(false, std::memory_order_release); - // clearSoundCacheNow.notify_all(); - //} - } - } - - //else if (triggerNavigationSound.exchange(false)) { - // ult::AudioPlayer::playSlideSound(); - //} - - // Combine inputs from both controllers - const u64 kDown_p1 = padGetButtonsDown(&pad_p1); - const u64 kHeld_p1 = padGetButtons(&pad_p1); - const u64 kDown_handheld = padGetButtonsDown(&pad_handheld); - const u64 kHeld_handheld = padGetButtons(&pad_handheld); - - shData->keysDown = kDown_p1 | kDown_handheld; - shData->keysHeld = kHeld_p1 | kHeld_handheld; - - // For joysticks, prioritize handheld if available, otherwise use P1 - const HidAnalogStickState leftStick_handheld = padGetStickPos(&pad_handheld, 0); - const HidAnalogStickState rightStick_handheld = padGetStickPos(&pad_handheld, 1); - - // Check if handheld has any stick input (not at center position) - const bool handheldHasInput = (leftStick_handheld.x != 0 || leftStick_handheld.y != 0 || - rightStick_handheld.x != 0 || rightStick_handheld.y != 0); - - if (handheldHasInput) { - shData->joyStickPosLeft = leftStick_handheld; - shData->joyStickPosRight = rightStick_handheld; - } else { - shData->joyStickPosLeft = padGetStickPos(&pad_p1, 0); - shData->joyStickPosRight = padGetStickPos(&pad_p1, 1); - } - - - // Read in touch positions - if (hidGetTouchScreenStates(&shData->touchState, 1) > 0) { // Check if any touch event is present - if (!shData->overlayOpen) { - //ult::internalTouchReleased = false; - ult::internalTouchReleased.store(false, std::memory_order_release); - } - - const HidTouchState& currentTouch = shData->touchState.touches[0]; // Correct type is HidTouchPoint - - - const u64 elapsedTime_ns = armTicksToNs(nowTick - currentTouchTick); - - // Check if the touch is within bounds for left-to-right swipe within the time window - if (ult::useSwipeToOpen && elapsedTime_ns <= TOUCH_THRESHOLD_NS) { - if ((lastTouchX != 0 && lastTouchY != 0) && (currentTouch.x != 0 || currentTouch.y != 0)) { - if (ult::layerEdge == 0 && currentTouch.x > SWIPE_RIGHT_BOUND + 84 && lastTouchX <= SWIPE_RIGHT_BOUND) { - eventFire(&shData->comboEvent); - mainComboHasTriggered.store(true, std::memory_order_release); - } - // Check if the touch is within bounds for right-to-left swipe within the time window - else if (ult::layerEdge > 0 && currentTouch.x < SWIPE_LEFT_BOUND - 84 && lastTouchX >= SWIPE_LEFT_BOUND) { - eventFire(&shData->comboEvent); - mainComboHasTriggered.store(true, std::memory_order_release); - } - } - } - - // Handle touch release state - if (currentTouch.x == 0 && currentTouch.y == 0) { - ult::internalTouchReleased.store(true, std::memory_order_release); - //ult::internalTouchReleased = true; // Indicate that the touch has been released - //ult::internalTouchReleased.store(true, std::memory_order_release); - lastTouchX = 0; - lastTouchY = 0; - } - - // If this is the first touch of a gesture, store lastTouchX - else if ((lastTouchX == 0 && lastTouchY == 0) && (currentTouch.x != 0 || currentTouch.y != 0)) { - currentTouchTick = nowTick; - lastTouchX = currentTouch.x; - lastTouchY = currentTouch.y; - } - - } else { - // Reset touch state if no touch is present - shData->touchState = { 0 }; - //ult::internalTouchReleased = true; - ult::internalTouchReleased.store(true, std::memory_order_release); - //ult::internalTouchReleased.store(true, std::memory_order_release); - - // Reset touch history to invalid state - lastTouchX = 0; - lastTouchY = 0; - - // Reset time tracking - //currentTouchTick = nowTick; - } - - #if IS_STATUS_MONITOR_DIRECTIVE - if (triggerExitNow) { - ult::launchingOverlay.store(true, std::memory_order_release); - ult::setIniFileValue( - ult::ULTRAHAND_CONFIG_INI_PATH, - ult::ULTRAHAND_PROJECT_NAME, - ult::IN_OVERLAY_STR, - ult::FALSE_STR - ); - tsl::setNextOverlay( - ult::OVERLAY_PATH + "ovlmenu.ovl" - ); - tsl::Overlay::get()->close(); - //tsl::goBack(); - //triggerExitNow = false; - break; - } - #endif - //if ((shData->keysDown & KEY_ZL && shData->keysHeld & KEY_L) || (shData->keysDown & KEY_L && shData->keysHeld & KEY_ZL)) { - // notification->show("Hello world! ¯\\_(ツ)_/¯"); - // eventFire(&shData->notificationEvent); // wake the loop - //} - - - // Check main launch combo first (highest priority) - if ((((shData->keysHeld & tsl::cfg::launchCombo) == tsl::cfg::launchCombo) && shData->keysDown & tsl::cfg::launchCombo)) { - #if IS_LAUNCHER_DIRECTIVE - if (ult::updateMenuCombos) { - ult::setIniFileValue(ult::ULTRAHAND_CONFIG_INI_PATH, ult::ULTRAHAND_PROJECT_NAME, ult::KEY_COMBO_STR , ult::ULTRAHAND_COMBO_STR); - ult::setIniFileValue(ult::TESLA_CONFIG_INI_PATH, ult::TESLA_STR, ult::KEY_COMBO_STR , ult::ULTRAHAND_COMBO_STR); - ult::updateMenuCombos = false; - } - #endif - - #if IS_STATUS_MONITOR_DIRECTIVE - isRendering = false; - leventSignal(&renderingStopEvent); - #endif - - if (shData->overlayOpen) { - 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 --comboReturn"); - tsl::Overlay::get()->close(); - eventFire(&shData->comboEvent); - launchComboHasTriggered.store(true, std::memory_order_release); - return; - } - - // Compose launch args - std::string finalArgs; - if (!modeArg.empty()) { - finalArgs = modeArg; - } else { - // Only check overlay-specific launch args for non-ovlmenu entries - if (overlayFileName.compare("ovlmenu.ovl") != 0) { - // OPTIMIZED: Single INI read for both values - auto overlaysIniData = ult::getParsedDataFromIniFile(ult::OVERLAYS_INI_FILEPATH); - std::string useArgs = ""; - std::string launchArgs = ""; - - auto sectionIt = overlaysIniData.find(overlayFileName); - if (sectionIt != overlaysIniData.end()) { - auto useArgsIt = sectionIt->second.find(ult::USE_LAUNCH_ARGS_STR); - if (useArgsIt != sectionIt->second.end()) { - useArgs = useArgsIt->second; - } - - auto argsIt = sectionIt->second.find(ult::LAUNCH_ARGS_STR); - if (argsIt != sectionIt->second.end()) { - launchArgs = argsIt->second; - } - } - - if (useArgs == ult::TRUE_STR) { - finalArgs = launchArgs; - ult::removeQuotes(finalArgs); - } - } - } - if (finalArgs.empty()) { - finalArgs = "--direct"; - } else { - finalArgs += " --direct"; - } - - if (overlayFileName.compare("ovlmenu.ovl") == 0) { - finalArgs += " --comboReturn"; - ult::setIniFileValue( - ult::ULTRAHAND_CONFIG_INI_PATH, - ult::ULTRAHAND_PROJECT_NAME, - ult::IN_OVERLAY_STR, - ult::TRUE_STR - ); - } - - //shData->overlayOpen = false; - //hidExit(); - eventClose(&homeButtonPressEvent); - eventClose(&powerButtonPressEvent); - eventClose(&captureButtonPressEvent); - - ult::launchingOverlay.store(true, std::memory_order_release); - tsl::setNextOverlay(overlayPath, finalArgs); - tsl::Overlay::get()->close(); - eventFire(&shData->comboEvent); - launchComboHasTriggered.store(true, std::memory_order_release); - return; - } - } - } - //#endif - - shData->keysDownPending |= shData->keysDown; - } - - //20 ms - //s32 idx = 0; - rc = waitObjects(&idx, objects, WaiterObject_Count, 20'000'000ul); - if (R_SUCCEEDED(rc)) { - - #if IS_STATUS_MONITOR_DIRECTIVE - if (idx == WaiterObject_HomeButton || idx == WaiterObject_PowerButton) { // Changed condition to exclude capture button - if (shData->overlayOpen && !isValidOverlayMode()) { - tsl::Overlay::get()->hide(); - shData->overlayOpen = false; - } - } - #else - if (idx == WaiterObject_HomeButton || idx == WaiterObject_PowerButton) { // Changed condition to exclude capture button - if (shData->overlayOpen) { - tsl::Overlay::get()->hide(); - shData->overlayOpen = false; - } - } - #endif - - switch (idx) { - case WaiterObject_HomeButton: - eventClear(&homeButtonPressEvent); - break; - case WaiterObject_PowerButton: - eventClear(&powerButtonPressEvent); - - // Perform any necessary cleanup - hidExit(); - - // Reinitialize resources - ASSERT_FATAL(hidInitialize()); // Reinitialize HID to reset states - - // Reinitialize both controllers - padInitialize(&pad_p1, HidNpadIdType_No1); - padInitialize(&pad_handheld, HidNpadIdType_Handheld); - hidInitializeTouchScreen(); - - // Update both controllers - padUpdate(&pad_p1); - padUpdate(&pad_handheld); - break; - - - case WaiterObject_CaptureButton: - if (screenshotsAreDisabled) { - eventClear(&captureButtonPressEvent); - break; - } - - #if IS_STATUS_MONITOR_DIRECTIVE - bool inOverlayMode = isValidOverlayMode(); - if (inOverlayMode) { - delayUpdate = true; - isRendering = false; - leventSignal(&renderingStopEvent); - } - #endif - - ult::disableTransparency = true; - eventClear(&captureButtonPressEvent); - svcSleepThread(1'500'000'000); - ult::disableTransparency = false; - - #if IS_STATUS_MONITOR_DIRECTIVE - if (inOverlayMode) { - isRendering = true; - leventClear(&renderingStopEvent); - delayUpdate = false; - } - #endif - - break; - } - } else if (rc != KERNELRESULT(TimedOut)) { - ASSERT_FATAL(rc); - } - } - //hidExit(); - - eventClose(&homeButtonPressEvent); - eventClose(&powerButtonPressEvent); - eventClose(&captureButtonPressEvent); - - } - } - - /** - * @brief Creates a new Gui and changes to it - * - * @tparam G Gui to create - * @tparam Args Arguments to pass to the Gui - * @param args Arguments to pass to the Gui - * @return Reference to the newly created Gui - */ - template - std::unique_ptr& changeTo(Args&&... args) { - return Overlay::get()->changeTo(std::forward(args)...); - } - - template - std::unique_ptr& swapTo(Args&&... args) { - return Overlay::get()->swapTo(std::forward(args)...); - } - - template - std::unique_ptr& swapTo(SwapDepth depth, Args&&... args) { - return Overlay::get()->swapTo(depth, std::forward(args)...); - } - - - /** - * @brief Pops the top Gui from the stack and goes back to the last one - * @note The Overlay gets closed once there are no more Guis on the stack - */ - void goBack(u32 count) { - Overlay::get()->goBack(count); - } - - void pop(u32 count) { - Overlay::get()->pop(count); - } - - - static inline std::mutex setNextOverlayMutex; - - static inline std::string nextOverlayName; - static void setNextOverlay(const std::string& ovlPath, std::string origArgs) { - std::lock_guard lk(setNextOverlayMutex); - char buffer[512]; - char* p = buffer; - char* bufferEnd = buffer + sizeof(buffer) - 1; // Leave room for null terminator - - // Store filename and copy it - const std::string filenameStr = ult::getNameFromPath(ovlPath); - nextOverlayName = filenameStr; - - const char* filename = filenameStr.c_str(); - while (*filename && p < bufferEnd) *p++ = *filename++; - if (p < bufferEnd) *p++ = ' '; - - // Single-pass argument filtering - const char* src = origArgs.c_str(); - const char* end = src + origArgs.length(); - bool hasSkipCombo = false; - - while (src < end && p < bufferEnd) { - // Skip whitespace - while (src < end && *src == ' ' && p < bufferEnd) { - *p++ = *src++; - } - - if (src >= end || p >= bufferEnd) break; - - // Check for flags to filter/detect - if (src[0] == '-' && src[1] == '-') { - - // Check what flag this is - if (strncmp(src, "--skipCombo", 11) == 0 && (src[11] == ' ' || src[11] == '\0')) { - hasSkipCombo = true; - // Copy this flag - while (src < end && *src != ' ' && p < bufferEnd) *p++ = *src++; - } - else if (strncmp(src, "--foregroundFix", 15) == 0) { - // Skip this flag and its value - src += 15; - while (src < end && *src == ' ') src++; // Skip spaces - if (src < end && (*src == '0' || *src == '1')) src++; // Skip value - } - else if (strncmp(src, "--lastTitleID", 13) == 0) { - // Skip this flag and its value - src += 13; - while (src < end && *src == ' ') src++; // Skip spaces - while (src < end && *src != ' ' && *src != '\0') src++; // Skip title ID - } - else { - // Copy unknown flag - while (src < end && *src != ' ' && p < bufferEnd) *p++ = *src++; - } - } - else { - // Copy regular argument - while (src < end && *src != ' ' && p < bufferEnd) *p++ = *src++; - } - } - - // Add required flags with bounds checking - if (!hasSkipCombo && (p + 12) < bufferEnd) { - memcpy(p, " --skipCombo", 12); - p += 12; - } - - // Add foreground flag with bounds checking - if ((p + 17) < bufferEnd) { - memcpy(p, " --foregroundFix ", 17); - p += 17; - if (p < bufferEnd) { - *p++ = (ult::resetForegroundCheck.load(std::memory_order_acquire) || ult::lastTitleID != ult::getTitleIdAsString()) ? '1' : '0'; - } - } - - // Add last title ID with bounds checking - if ((p + 15 + ult::lastTitleID.length()) < bufferEnd) { - memcpy(p, " --lastTitleID ", 15); - p += 15; - const char* titleId = ult::lastTitleID.c_str(); - while (*titleId && p < bufferEnd) *p++ = *titleId++; - } - - // Safety check - if we're at the end, we might have truncated - if (p >= bufferEnd) { - p = bufferEnd; - } - - *p = '\0'; - - //isLaunchingNextOverlay.store(true, std::memory_order_release); - envSetNextLoad(ovlPath.c_str(), buffer); - } - - - - struct option_entry { - const char* name; - u8 len; - u8 action; - }; - - static const struct option_entry options[] = { - {"direct", 6, 1}, - {"skipCombo", 9, 2}, - {"lastTitleID", 11, 3}, - {"foregroundFix", 13, 4}, - {"package", 7, 5}, - {"lastSelectedItem", 16, 6}, - {"comboReturn", 11, 7} // new option - }; - - - /** - * @brief libtesla's main function - * @note Call it directly from main passing in argc and argv and returning it e.g `return tsl::loop(argc, argv);` - * - * @tparam TOverlay Your overlay class - * @tparam launchFlags \ref LaunchFlags - * @param argc argc - * @param argv argv - * @return int result - */ - template - static inline int loop(int argc, char** argv) { - static_assert(std::is_base_of_v, "tsl::loop expects a type derived from tsl::Overlay"); - - #if IS_STATUS_MONITOR_DIRECTIVE - leventClear(&renderingStopEvent); - #endif - - // 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/2; - 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]; - - skip = false; - - if (arg > 1) { - const char* prev = argv[arg - 1]; - if (prev[0] == '-' && prev[1] == '-') { - if (strcmp(prev, "--lastTitleID") == 0 || strcmp(prev, "--foregroundFix") == 0) { - skip = true; - } - } - } - - if (!skip && s[0] == '-' && s[1] == '-') { - if (strcmp(s, "--direct") == 0 || - strcmp(s, "--skipCombo") == 0 || - strcmp(s, "--lastTitleID") == 0 || - strcmp(s, "--foregroundFix") == 0) { - skip = true; - } - } - - if (!skip) { - if (strcmp(s, "--package") == 0) { - lastOverlayMode = "--package"; - arg++; - if (arg < argc) { - lastOverlayMode += " "; - lastOverlayMode += argv[arg]; - arg++; - while (arg < argc && argv[arg][0] != '-') { - lastOverlayMode += " "; - lastOverlayMode += argv[arg]; - arg++; - } - } - } else { - lastOverlayMode = s; - } - break; - } - } - } - - bool skipCombo = false; - #if IS_LAUNCHER_DIRECTIVE - bool comboReturn = false; - bool directMode = true; - #else - bool directMode = false; - #endif - bool usingPackageLauncher = false; - - - for (u8 arg = 0; arg < argc; arg++) { - const char* s = argv[arg]; - if (s[0] != '-' || s[1] != '-') continue; - const char* opt = s + 2; - - for (u8 i = 0; i < 7; i++) { // now 6 instead of 5 - if (memcmp(opt, options[i].name, options[i].len) == 0 && opt[options[i].len] == '\0') { - switch (options[i].action) { - case 1: // direct - directMode = true; - g_overlayFilename = ""; - jumpItemName = ""; - jumpItemValue = ""; - jumpItemExactMatch.store(true, std::memory_order_release); - break; - case 2: // skipCombo - skipCombo = true; - ult::firstBoot = false; - break; - case 3: // lastTitleID - if (++arg < argc) { - const char* providedID = argv[arg]; - if (ult::getTitleIdAsString() != providedID) { - ult::resetForegroundCheck.store(true, std::memory_order_release); - } - } - break; - case 4: // foregroundFix - if (++arg < argc) { - ult::resetForegroundCheck.store( - ult::resetForegroundCheck.load(std::memory_order_acquire) || - (argv[arg][0] == '1'), std::memory_order_release); - } - break; - case 5: // package - usingPackageLauncher = true; - break; - case 6: // lastSelectedItem - #if IS_STATUS_MONITOR_DIRECTIVE - lastMode = "returning"; - #endif - break; - case 7: // comboReturn - #if IS_LAUNCHER_DIRECTIVE - comboReturn = true; - #endif - break; - } - } - } - } - - impl::SharedThreadData shData; - shData.running.store(true, std::memory_order_release); - - Thread backgroundThread; - threadCreate(&backgroundThread, impl::backgroundEventPoller, &shData, nullptr, 0x2000, 0x2c, -2); - threadStart(&backgroundThread); - - eventCreate(&shData.comboEvent, false); - - 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 - - // Initialize the audio service - if (ult::useSoundEffects && ult::expandedMemory) { - ult::AudioPlayer::initialize(); - } - - - - overlay->initScreen(); - overlay->changeTo(overlay->loadInitialGui()); - - - bool shouldFireEvent = false; - - #if IS_LAUNCHER_DIRECTIVE - - { - bool inOverlay; - - 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 - { - - auto configData = ult::getParsedDataFromIniFile(ult::ULTRAHAND_CONFIG_INI_PATH); - - auto projectIt = configData.find(ult::ULTRAHAND_PROJECT_NAME); - if (projectIt != configData.end()) { - auto overlayIt = projectIt->second.find(ult::IN_OVERLAY_STR); - const bool inOverlay = (overlayIt == projectIt->second.end() || overlayIt->second != ult::FALSE_STR); - - if (inOverlay && directMode) { - configData[ult::ULTRAHAND_PROJECT_NAME][ult::IN_OVERLAY_STR] = ult::FALSE_STR; - ult::saveIniFileData(ult::ULTRAHAND_CONFIG_INI_PATH, configData); - } - } - } - - if (skipCombo) { - eventFire(&shData.comboEvent); - shouldFireEvent = true; - } - #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.exchange(false, std::memory_order_acq_rel)) { - comboBreakout = true; - exitAfterPrompt = false; - break; - } - - if (launchComboHasTriggered.load(std::memory_order_acquire)) { - exitAfterPrompt = true; - usingPackageLauncher = false; - directMode = false; - break; - } - - if (!(notification && notification->isActive())) { - break; - } - } - - if (!comboBreakout || !shData.running.load(std::memory_order_acquire)) { - { - //std::scoped_lock lock(shData.dataMutex); - if (!ult::launchingOverlay.load(std::memory_order_acquire)) { - overlay->clearScreen(); - } - } - if (exitAfterPrompt) { - std::scoped_lock lock(shData.dataMutex); - exitAfterPrompt = false; - shData.running.store(false, std::memory_order_release); - shData.overlayOpen.store(false, std::memory_order_release); - ult::launchingOverlay.store(true, std::memory_order_release); - launchComboHasTriggered.store(true, std::memory_order_release); // for isolating sound effect - - if (usingPackageLauncher || directMode) { - tsl::setNextOverlay(ult::OVERLAY_PATH + "ovlmenu.ovl"); - } - - hlp::requestForeground(false); - break; - } - continue; - } - } - - { - //std::scoped_lock lock(shData.dataMutex); - if (ult::launchingOverlay.load(std::memory_order_acquire)) { - shData.running.store(false, std::memory_order_release); - shData.overlayOpen.store(false, std::memory_order_release); - break; - } - firstLoop = false; - shData.overlayOpen.store(true, std::memory_order_release); - - #if IS_STATUS_MONITOR_DIRECTIVE - if (!isValidOverlayMode()) - hlp::requestForeground(true); - #else - hlp::requestForeground(true); - #endif - - overlay->show(); - if (!comboBreakout && !(notification && notification->isActive())) - overlay->clearScreen(); - - { - std::scoped_lock lock(shData.dataMutex); - // Clear derived states that the overlay loop will use - shData.keysDown = 0; - shData.keysHeld = 0; - // Clear any queued pending keys so nothing gets processed one frame late - shData.keysDownPending = 0; - } - } - - while (shData.running.load(std::memory_order_acquire)) { - { - - if (ult::launchingOverlay.load(std::memory_order_acquire)) { - shData.running.store(false, std::memory_order_release); - shData.overlayOpen.store(false, std::memory_order_release); - break; - } - overlay->loop(); - { - std::scoped_lock lock(shData.dataMutex); - if (!overlay->fadeAnimationPlaying()) { - overlay->handleInput(shData.keysDownPending, shData.keysHeld, shData.touchState.count, shData.touchState.touches[0], shData.joyStickPosLeft, shData.joyStickPosRight); - } - shData.keysDownPending = 0; - } - #if IS_LAUNCHER_DIRECTIVE - if (shouldFireEvent) { - shouldFireEvent = false; - - if (!comboReturn) { - //triggerRumbleDoubleClick.store(true, std::memory_order_release); - //triggerExitSound.store(true, std::memory_order_release); - triggerExitFeedback(); - //} else { - // triggerRumbleClick.store(true, std::memory_order_release); - } - } - #else - if (!directMode && shouldFireEvent) { - shouldFireEvent = false; - #if IS_STATUS_MONITOR_DIRECTIVE - if (lastMode.compare("returning") == 0) { - //triggerRumbleDoubleClick.store(true, std::memory_order_release); - //triggerExitSound.store(true, std::memory_order_release); - triggerExitFeedback(); - } else { - //triggerRumbleClick.store(true, std::memory_order_release); - triggerEnterSound.store(true, std::memory_order_release); - } - #else - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerEnterSound.store(true, std::memory_order_release); - triggerEnterFeedback(); - #endif - } - #endif - } - - #if IS_STATUS_MONITOR_DIRECTIVE - if (pendingExit && wasRendering) { - pendingExit = false; - wasRendering = false; - isRendering = true; - leventClear(&renderingStopEvent); - } - #endif - - if (overlay->shouldHide()) { - if (overlay->shouldCloseAfter()) { - if (!directMode) { - //std::scoped_lock lock(shData.dataMutex); - shData.running.store(false, std::memory_order_release); - shData.overlayOpen.store(false, std::memory_order_release); - break; - } else { - exitAfterPrompt = true; - #if IS_STATUS_MONITOR_DIRECTIVE - pendingExit = true; - #endif - } - } - break; - } - - if (overlay->shouldClose()) { - //std::scoped_lock lock(shData.dataMutex); - shData.running.store(false, std::memory_order_release); - shData.overlayOpen.store(false, std::memory_order_release); - - break; - } - } - - if (shData.running.load(std::memory_order_acquire)) { - //std::scoped_lock lock(shData.dataMutex); - if (!(notification && notification->isActive())) - overlay->clearScreen(); - overlay->resetFlags(); - hlp::requestForeground(false); - shData.overlayOpen.store(false, std::memory_order_release); - mainComboHasTriggered.store(false, std::memory_order_acquire); - launchComboHasTriggered.store(false, std::memory_order_acquire); - eventClear(&shData.comboEvent); - } - } - - // Ensure background thread is fully stopped before overlay cleanup - shData.running.store(false, std::memory_order_release); - threadWaitForExit(&backgroundThread); - threadClose(&backgroundThread); - - - // Cleanup overlay resources - tsl::elm::fullDeconstruction.store(true, std::memory_order_release); - hlp::requestForeground(false); - overlay->exitScreen(); - overlay->exitServices(); - delete overlay; - - - eventClose(&shData.comboEvent); - - - if (directMode && !launchComboHasTriggered.load(std::memory_order_acquire)) { - if (!disableSound.load(std::memory_order_acquire) && ult::useSoundEffects) - ult::AudioPlayer::playExitSound(); - if (ult::useHapticFeedback) { - ult::rumbleDoubleClickStandalone(); - } - } - - - // Brief delay to ensure thread quiescence before nx-ovlloader transition - //svcSleepThread(100'000'000); // 100ms - - return 0; - } - } - -} - - -#ifdef TESLA_INIT_IMPL - -namespace tsl::cfg { - - u16 LayerWidth = 0; - u16 LayerHeight = 0; - u16 LayerPosX = 0; - u16 LayerPosY = 0; - u16 FramebufferWidth = 0; - u16 FramebufferHeight = 0; - u64 launchCombo = KEY_ZL | KEY_ZR | KEY_DDOWN; - u64 launchCombo2 = KEY_L | KEY_DDOWN | KEY_RSTICK; -} -extern "C" void __libnx_init_time(void); - -extern "C" { - - u32 __nx_applet_type = AppletType_None; - u32 __nx_fs_num_sessions = 1; - u32 __nx_nv_transfermem_size = 0x15000; - ViLayerFlags __nx_vi_stray_layer_flags = (ViLayerFlags)0; - - /** - * @brief libtesla service initializing function to override libnx's - * - */ - void __appInit(void) { - ASSERT_FATAL(smInitialize()); // needed to prevent issues with powering device into sleep - - //tsl::hlp::doWithSmSession([]{ - - ASSERT_FATAL(fsInitialize()); - ASSERT_FATAL(hidInitialize()); // Controller inputs and Touch - if (hosversionAtLeast(16,0,0)) { - ASSERT_FATAL(plInitialize(PlServiceType_User)); // Font data. Use pl:u for 16.0.0+ - } else { - ASSERT_FATAL(plInitialize(PlServiceType_System)); // Use pl:s for 15.0.1 and below to prevent qlaunch/overlaydisp session exhaustion - } - ASSERT_FATAL(pmdmntInitialize()); // PID querying - ASSERT_FATAL(hidsysInitialize()); // Focus control - ASSERT_FATAL(setsysInitialize()); // Settings querying - - // Time initializations - if R_SUCCEEDED(timeInitialize()) { - __libnx_init_time(); - timeExit(); - } - - #if USING_WIDGET_DIRECTIVE - ult::powerInit(); - i2cInitialize(); - #endif - - fsdevMountSdmc(); - splInitialize(); - spsmInitialize(); - //i2cInitialize(); - //ASSERT_FATAL(socketInitializeDefault()); - //ASSERT_FATAL(nifmInitialize(NifmServiceType_User)); - - //}); - - - - - #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); - - //deinitRumble(); - if (ult::expandedMemory) - ult::AudioPlayer::exit(); - - - //socketExit(); - //nifmExit(); - spsmExit(); - splExit(); - fsdevUnmountAll(); - - #if USING_WIDGET_DIRECTIVE - i2cExit(); - ult::powerExit(); // CUSTOM MODIFICATION - #endif - - fsExit(); - hidExit(); - plExit(); - pmdmntExit(); - hidsysExit(); - setsysExit(); - smExit(); - - // Final cleanup - tsl::gfx::FontManager::cleanup(); - } - -} - -#endif diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/LICENSE b/Source/sys-clk/overlay/lib/libultrahand/libultra/LICENSE deleted file mode 100644 index d159169d..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/LICENSE +++ /dev/null @@ -1,339 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/README.md b/Source/sys-clk/overlay/lib/libultrahand/libultra/README.md deleted file mode 100644 index 9966139d..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/README.md +++ /dev/null @@ -1,69 +0,0 @@ -# libultra - -![Ultrahand Logo](https://github.com/ppkantorski/Ultrahand-Overlay/blob/main/.pics/ultrahand.png) - - -## Overview - -`libultra` is a powerful collection of helper functions designed specifically for the Ultrahand Overlay project. This library offers a comprehensive set of utilities aimed at simplifying common tasks and enhancing the efficiency of your projects within the Ultrahand Overlay ecosystem. - -## Features - -### [Ultra Header](/libultra/include/ultra.hpp) - -- **ultra.hpp**: The main header file for the `libultra` library, including all essential functions and declarations for seamless integration into your projects. - -### [Debug Functions](/libultra/include/debug_funcs.hpp) - -- **debug_funcs.hpp**: A collection of functions tailored for debugging purposes, aiding in identifying and resolving issues within your codebase. - -### [Download Functions](/libultra/include/download_funcs.hpp) - -- **download_funcs.hpp**: Utilities for managing file downloads, enabling seamless retrieval of resources from external sources. - -### [Get Functions](/libultra/include/get_funcs.hpp) - -- **get_funcs.hpp**: Functions for retrieving data from various sources, simplifying the process of fetching information within your applications. - -### [Hex Functions](/libultra/include/hex_funcs.hpp) - -- **hex_funcs.hpp**: Tools for working with hexadecimal data, facilitating operations such as conversion and manipulation of hexadecimal values. - -### [INI Functions](/libultra/include/ini_funcs.hpp) - -- **ini_funcs.hpp**: Helper functions for handling INI configuration files, offering a convenient way to manage application settings. - -### [JSON Functions](/libultra/include/json_funcs.hpp) - -- **json_funcs.hpp**: Utilities for parsing and manipulating JSON data, providing easy integration with JSON-based APIs and services. - -### [List Functions](/libultra/include/list_funcs.hpp) - -- **list_funcs.hpp**: Functions for working with lists and arrays, offering essential operations like sorting, searching, and manipulation of list elements. - -### [Mod Functions](/libultra/include/mod_funcs.hpp) - -- **mod_funcs.hpp**: Functions for manipulating game mods, facilitating operations and management tasks related to modifications in gaming environments. - -### [Path Functions](/libultra/include/path_funcs.hpp) - -- **path_funcs.hpp**: Tools for working with file paths and directories, simplifying file system operations within your applications. - -### [String Functions](/libultra/include/string_funcs.hpp) - -- **string_funcs.hpp**: A collection of string manipulation functions, providing utilities for tasks such as formatting, searching, and modification of strings. - - -## Usage - -To build Ultrahand overlays with `libultra` + `libtesla`, simply add the `lib` folder to your project, then import `tesla.hpp`. - -## Contribution - -Contributions to `libultra` are welcome. If you have ideas for additional helper functions or improvements to existing ones, feel free to submit a pull request or open an issue on GitHub. - -## License - -Licensed under both [GPLv2](LICENSE) and [CC-BY-4.0](SUB_LICENSE). - -Copyright (c) 2024 ppkantorski diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/SUB_LICENSE b/Source/sys-clk/overlay/lib/libultrahand/libultra/SUB_LICENSE deleted file mode 100644 index 2f244ac8..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/SUB_LICENSE +++ /dev/null @@ -1,395 +0,0 @@ -Attribution 4.0 International - -======================================================================= - -Creative Commons Corporation ("Creative Commons") is not a law firm and -does not provide legal services or legal advice. Distribution of -Creative Commons public licenses does not create a lawyer-client or -other relationship. Creative Commons makes its licenses and related -information available on an "as-is" basis. Creative Commons gives no -warranties regarding its licenses, any material licensed under their -terms and conditions, or any related information. Creative Commons -disclaims all liability for damages resulting from their use to the -fullest extent possible. - -Using Creative Commons Public Licenses - -Creative Commons public licenses provide a standard set of terms and -conditions that creators and other rights holders may use to share -original works of authorship and other material subject to copyright -and certain other rights specified in the public license below. The -following considerations are for informational purposes only, are not -exhaustive, and do not form part of our licenses. - - Considerations for licensors: Our public licenses are - intended for use by those authorized to give the public - permission to use material in ways otherwise restricted by - copyright and certain other rights. Our licenses are - irrevocable. Licensors should read and understand the terms - and conditions of the license they choose before applying it. - Licensors should also secure all rights necessary before - applying our licenses so that the public can reuse the - material as expected. Licensors should clearly mark any - material not subject to the license. This includes other CC- - licensed material, or material used under an exception or - limitation to copyright. More considerations for licensors: - wiki.creativecommons.org/Considerations_for_licensors - - Considerations for the public: By using one of our public - licenses, a licensor grants the public permission to use the - licensed material under specified terms and conditions. If - the licensor's permission is not necessary for any reason--for - example, because of any applicable exception or limitation to - copyright--then that use is not regulated by the license. Our - licenses grant only permissions under copyright and certain - other rights that a licensor has authority to grant. Use of - the licensed material may still be restricted for other - reasons, including because others have copyright or other - rights in the material. A licensor may make special requests, - such as asking that all changes be marked or described. - Although not required by our licenses, you are encouraged to - respect those requests where reasonable. More_considerations - for the public: - wiki.creativecommons.org/Considerations_for_licensees - -======================================================================= - -Creative Commons Attribution 4.0 International Public License - -By exercising the Licensed Rights (defined below), You accept and agree -to be bound by the terms and conditions of this Creative Commons -Attribution 4.0 International Public License ("Public License"). To the -extent this Public License may be interpreted as a contract, You are -granted the Licensed Rights in consideration of Your acceptance of -these terms and conditions, and the Licensor grants You such rights in -consideration of benefits the Licensor receives from making the -Licensed Material available under these terms and conditions. - - -Section 1 -- Definitions. - - a. Adapted Material means material subject to Copyright and Similar - Rights that is derived from or based upon the Licensed Material - and in which the Licensed Material is translated, altered, - arranged, transformed, or otherwise modified in a manner requiring - permission under the Copyright and Similar Rights held by the - Licensor. For purposes of this Public License, where the Licensed - Material is a musical work, performance, or sound recording, - Adapted Material is always produced where the Licensed Material is - synched in timed relation with a moving image. - - b. Adapter's License means the license You apply to Your Copyright - and Similar Rights in Your contributions to Adapted Material in - accordance with the terms and conditions of this Public License. - - c. Copyright and Similar Rights means copyright and/or similar rights - closely related to copyright including, without limitation, - performance, broadcast, sound recording, and Sui Generis Database - Rights, without regard to how the rights are labeled or - categorized. For purposes of this Public License, the rights - specified in Section 2(b)(1)-(2) are not Copyright and Similar - Rights. - - d. Effective Technological Measures means those measures that, in the - absence of proper authority, may not be circumvented under laws - fulfilling obligations under Article 11 of the WIPO Copyright - Treaty adopted on December 20, 1996, and/or similar international - agreements. - - e. Exceptions and Limitations means fair use, fair dealing, and/or - any other exception or limitation to Copyright and Similar Rights - that applies to Your use of the Licensed Material. - - f. Licensed Material means the artistic or literary work, database, - or other material to which the Licensor applied this Public - License. - - g. Licensed Rights means the rights granted to You subject to the - terms and conditions of this Public License, which are limited to - all Copyright and Similar Rights that apply to Your use of the - Licensed Material and that the Licensor has authority to license. - - h. Licensor means the individual(s) or entity(ies) granting rights - under this Public License. - - i. Share means to provide material to the public by any means or - process that requires permission under the Licensed Rights, such - as reproduction, public display, public performance, distribution, - dissemination, communication, or importation, and to make material - available to the public including in ways that members of the - public may access the material from a place and at a time - individually chosen by them. - - j. Sui Generis Database Rights means rights other than copyright - resulting from Directive 96/9/EC of the European Parliament and of - the Council of 11 March 1996 on the legal protection of databases, - as amended and/or succeeded, as well as other essentially - equivalent rights anywhere in the world. - - k. You means the individual or entity exercising the Licensed Rights - under this Public License. Your has a corresponding meaning. - - -Section 2 -- Scope. - - a. License grant. - - 1. Subject to the terms and conditions of this Public License, - the Licensor hereby grants You a worldwide, royalty-free, - non-sublicensable, non-exclusive, irrevocable license to - exercise the Licensed Rights in the Licensed Material to: - - a. reproduce and Share the Licensed Material, in whole or - in part; and - - b. produce, reproduce, and Share Adapted Material. - - 2. Exceptions and Limitations. For the avoidance of doubt, where - Exceptions and Limitations apply to Your use, this Public - License does not apply, and You do not need to comply with - its terms and conditions. - - 3. Term. The term of this Public License is specified in Section - 6(a). - - 4. Media and formats; technical modifications allowed. The - Licensor authorizes You to exercise the Licensed Rights in - all media and formats whether now known or hereafter created, - and to make technical modifications necessary to do so. The - Licensor waives and/or agrees not to assert any right or - authority to forbid You from making technical modifications - necessary to exercise the Licensed Rights, including - technical modifications necessary to circumvent Effective - Technological Measures. For purposes of this Public License, - simply making modifications authorized by this Section 2(a) - (4) never produces Adapted Material. - - 5. Downstream recipients. - - a. Offer from the Licensor -- Licensed Material. Every - recipient of the Licensed Material automatically - receives an offer from the Licensor to exercise the - Licensed Rights under the terms and conditions of this - Public License. - - b. No downstream restrictions. You may not offer or impose - any additional or different terms or conditions on, or - apply any Effective Technological Measures to, the - Licensed Material if doing so restricts exercise of the - Licensed Rights by any recipient of the Licensed - Material. - - 6. No endorsement. Nothing in this Public License constitutes or - may be construed as permission to assert or imply that You - are, or that Your use of the Licensed Material is, connected - with, or sponsored, endorsed, or granted official status by, - the Licensor or others designated to receive attribution as - provided in Section 3(a)(1)(A)(i). - - b. Other rights. - - 1. Moral rights, such as the right of integrity, are not - licensed under this Public License, nor are publicity, - privacy, and/or other similar personality rights; however, to - the extent possible, the Licensor waives and/or agrees not to - assert any such rights held by the Licensor to the limited - extent necessary to allow You to exercise the Licensed - Rights, but not otherwise. - - 2. Patent and trademark rights are not licensed under this - Public License. - - 3. To the extent possible, the Licensor waives any right to - collect royalties from You for the exercise of the Licensed - Rights, whether directly or through a collecting society - under any voluntary or waivable statutory or compulsory - licensing scheme. In all other cases the Licensor expressly - reserves any right to collect such royalties. - - -Section 3 -- License Conditions. - -Your exercise of the Licensed Rights is expressly made subject to the -following conditions. - - a. Attribution. - - 1. If You Share the Licensed Material (including in modified - form), You must: - - a. retain the following if it is supplied by the Licensor - with the Licensed Material: - - i. identification of the creator(s) of the Licensed - Material and any others designated to receive - attribution, in any reasonable manner requested by - the Licensor (including by pseudonym if - designated); - - ii. a copyright notice; - - iii. a notice that refers to this Public License; - - iv. a notice that refers to the disclaimer of - warranties; - - v. a URI or hyperlink to the Licensed Material to the - extent reasonably practicable; - - b. indicate if You modified the Licensed Material and - retain an indication of any previous modifications; and - - c. indicate the Licensed Material is licensed under this - Public License, and include the text of, or the URI or - hyperlink to, this Public License. - - 2. You may satisfy the conditions in Section 3(a)(1) in any - reasonable manner based on the medium, means, and context in - which You Share the Licensed Material. For example, it may be - reasonable to satisfy the conditions by providing a URI or - hyperlink to a resource that includes the required - information. - - 3. If requested by the Licensor, You must remove any of the - information required by Section 3(a)(1)(A) to the extent - reasonably practicable. - - 4. If You Share Adapted Material You produce, the Adapter's - License You apply must not prevent recipients of the Adapted - Material from complying with this Public License. - - -Section 4 -- Sui Generis Database Rights. - -Where the Licensed Rights include Sui Generis Database Rights that -apply to Your use of the Licensed Material: - - a. for the avoidance of doubt, Section 2(a)(1) grants You the right - to extract, reuse, reproduce, and Share all or a substantial - portion of the contents of the database; - - b. if You include all or a substantial portion of the database - contents in a database in which You have Sui Generis Database - Rights, then the database in which You have Sui Generis Database - Rights (but not its individual contents) is Adapted Material; and - - c. You must comply with the conditions in Section 3(a) if You Share - all or a substantial portion of the contents of the database. - -For the avoidance of doubt, this Section 4 supplements and does not -replace Your obligations under this Public License where the Licensed -Rights include other Copyright and Similar Rights. - - -Section 5 -- Disclaimer of Warranties and Limitation of Liability. - - a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE - EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS - AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF - ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, - IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, - WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR - PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, - ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT - KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT - ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. - - b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE - TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, - NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, - INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, - COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR - USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN - ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR - DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR - IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. - - c. The disclaimer of warranties and limitation of liability provided - above shall be interpreted in a manner that, to the extent - possible, most closely approximates an absolute disclaimer and - waiver of all liability. - - -Section 6 -- Term and Termination. - - a. This Public License applies for the term of the Copyright and - Similar Rights licensed here. However, if You fail to comply with - this Public License, then Your rights under this Public License - terminate automatically. - - b. Where Your right to use the Licensed Material has terminated under - Section 6(a), it reinstates: - - 1. automatically as of the date the violation is cured, provided - it is cured within 30 days of Your discovery of the - violation; or - - 2. upon express reinstatement by the Licensor. - - For the avoidance of doubt, this Section 6(b) does not affect any - right the Licensor may have to seek remedies for Your violations - of this Public License. - - c. For the avoidance of doubt, the Licensor may also offer the - Licensed Material under separate terms or conditions or stop - distributing the Licensed Material at any time; however, doing so - will not terminate this Public License. - - d. Sections 1, 5, 6, 7, and 8 survive termination of this Public - License. - - -Section 7 -- Other Terms and Conditions. - - a. The Licensor shall not be bound by any additional or different - terms or conditions communicated by You unless expressly agreed. - - b. Any arrangements, understandings, or agreements regarding the - Licensed Material not stated herein are separate from and - independent of the terms and conditions of this Public License. - - -Section 8 -- Interpretation. - - a. For the avoidance of doubt, this Public License does not, and - shall not be interpreted to, reduce, limit, restrict, or impose - conditions on any use of the Licensed Material that could lawfully - be made without permission under this Public License. - - b. To the extent possible, if any provision of this Public License is - deemed unenforceable, it shall be automatically reformed to the - minimum extent necessary to make it enforceable. If the provision - cannot be reformed, it shall be severed from this Public License - without affecting the enforceability of the remaining terms and - conditions. - - c. No term or condition of this Public License will be waived and no - failure to comply consented to unless expressly agreed to by the - Licensor. - - d. Nothing in this Public License constitutes or may be interpreted - as a limitation upon, or waiver of, any privileges and immunities - that apply to the Licensor or You, including from the legal - processes of any jurisdiction or authority. - - -======================================================================= - -Creative Commons is not a party to its public -licenses. Notwithstanding, Creative Commons may elect to apply one of -its public licenses to material it publishes and in those instances -will be considered the “Licensor.” The text of the Creative Commons -public licenses is dedicated to the public domain under the CC0 Public -Domain Dedication. Except for the limited purpose of indicating that -material is shared under a Creative Commons public license or as -otherwise permitted by the Creative Commons policies published at -creativecommons.org/policies, Creative Commons does not authorize the -use of the trademark "Creative Commons" or any other trademark or logo -of Creative Commons without its prior written consent including, -without limitation, in connection with any unauthorized modifications -to any of its public licenses or any other arrangements, -understandings, or agreements concerning use of licensed material. For -the avoidance of doubt, this paragraph does not form part of the -public licenses. - -Creative Commons may be contacted at creativecommons.org. diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/audio_player.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/audio_player.hpp deleted file mode 100644 index d9e9765e..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/audio_player.hpp +++ /dev/null @@ -1,96 +0,0 @@ -/******************************************************************************** - * File: audio_player.hpp - * Author: ppkantorski - * Description: - * This header defines the AudioPlayer class and related structures used for - * handling sound playback within the Ultrahand Overlay. It provides interfaces - * for loading, caching, and playing WAV audio through libnx’s audout service, - * along with basic sound type management and synchronization support. - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 2025 ppkantorski - ********************************************************************************/ - -#pragma once -#include -#include -#include -#include -#include -#include -#include - -namespace ult { - class AudioPlayer { - public: - enum class SoundType : uint8_t { // <- uint8_t saves space - Navigate, - Enter, - Exit, - Wall, - On, - Off, - Settings, - Move, - Count - }; - - struct CachedSound { - void* buffer = nullptr; - uint32_t bufferSize = 0; - uint32_t dataSize = 0; - }; - - static bool initialize(); - static void exit(); - static void playSound(SoundType type); - - // Inline wrappers - same API, zero overhead - static inline void playNavigateSound() { playSound(SoundType::Navigate); } - static inline void playEnterSound() { playSound(SoundType::Enter); } - static inline void playExitSound() { playSound(SoundType::Exit); } - static inline void playWallSound() { playSound(SoundType::Wall); } - static inline void playOnSound() { playSound(SoundType::On); } - static inline void playOffSound() { playSound(SoundType::Off); } - static inline void playSettingsSound() { playSound(SoundType::Settings); } - static inline void playMoveSound() { playSound(SoundType::Move); } - - static void setMasterVolume(float volume); - static void setEnabled(bool enabled); - static bool isEnabled(); - static bool isDocked(); - static bool reloadIfDockedChanged(); - static void reloadAllSounds(); - static void unloadAllSounds(const std::initializer_list& excludeSounds = {}); - static std::mutex m_audioMutex; - - private: - static bool m_initialized; - static std::atomic m_enabled; // <- atomic for lock-free reads - static float m_masterVolume; - static std::vector m_cachedSounds; - - static bool m_lastDockedState; - - inline static constexpr const char* m_soundPaths[static_cast(SoundType::Count)] = { - "sdmc:/config/ultrahand/sounds/tick.wav", - "sdmc:/config/ultrahand/sounds/enter.wav", - "sdmc:/config/ultrahand/sounds/exit.wav", - "sdmc:/config/ultrahand/sounds/wall.wav", - "sdmc:/config/ultrahand/sounds/on.wav", - "sdmc:/config/ultrahand/sounds/off.wav", - "sdmc:/config/ultrahand/sounds/settings.wav", - "sdmc:/config/ultrahand/sounds/move.wav" - }; - - //static void playAudioBuffer(void* buffer, uint32_t bufferSize); - static bool loadSoundFromWav(SoundType type, const char* path); - - }; -} \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/debug_funcs.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/debug_funcs.hpp deleted file mode 100644 index aa0a045d..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/debug_funcs.hpp +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************** - * File: debug_funcs.hpp - * Author: ppkantorski - * Description: - * This header file contains debugging functions for the Ultrahand Overlay project. - * These functions allow logging messages with timestamps to a log file. - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 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 char* message); - void logMessage(const std::string& message); - #endif -} - -#endif // DEBUG_FUNCS_HPP diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/download_funcs.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/download_funcs.hpp deleted file mode 100644 index 240db66c..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/download_funcs.hpp +++ /dev/null @@ -1,83 +0,0 @@ -/******************************************************************************** - * File: download_funcs.hpp - * Author: ppkantorski - * Description: - * This header file contains functions for downloading and extracting files - * using libcurl and miniz. It includes functions for downloading files from URLs, - * writing received data to a file, and extracting files from ZIP archives. - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 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; - - - // Thread-safe callback functions - //#if !USING_FSTREAM_DIRECTIVE - //size_t writeCallback(void* ptr, size_t size, size_t nmemb, FILE* stream); - //#else - //size_t writeCallback(void* ptr, size_t size, size_t nmemb, std::ostream* stream); - //#endif - - //int progressCallback(void* ptr, curl_off_t totalToDownload, curl_off_t nowDownloaded, curl_off_t totalToUpload, curl_off_t nowUploaded); - - - // Thread-safe initialization and cleanup functions - //void initializeCurl(); - //void cleanupCurl(); - - // Main API functions - thread-safe and optimized - bool downloadFile(const std::string& url, const std::string& toDestination, bool noPercentagePolling=false); - bool unzipFile(const std::string& zipFilePath, const std::string& extractTo); -} - -#endif // DOWNLOAD_FUNCS_HPP \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/get_funcs.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/get_funcs.hpp deleted file mode 100644 index f2ad167d..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/get_funcs.hpp +++ /dev/null @@ -1,160 +0,0 @@ -/******************************************************************************** - * File: get_funcs.hpp - * Author: ppkantorski - * Description: - * This header file contains functions for retrieving information and data - * from various sources, including file system and JSON files. It includes - * functions for obtaining overlay module information, reading file contents, - * and parsing JSON data. - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 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 deleted file mode 100644 index 26ea2aef..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/global_vars.hpp +++ /dev/null @@ -1,173 +0,0 @@ -/******************************************************************************** - * File: global_vars.hpp - * Author: ppkantorski - * Description: - * This header file provides the definitions of global constants and paths used - * throughout the Ultrahand Overlay project. These constants are essential for - * file management and configuration settings within the application. - * - * For the latest updates and contributions, visit the project's GitHub repository: - * GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay - * - * Note: This notice is integral to the project's documentation and must not be - * altered or removed. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 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 SOUNDS_PATH; - extern const std::string FLAGS_PATH; - extern const std::string NOTIFICATIONS_PATH; - extern const std::string PAYLOADS_PATH; - extern const std::string HB_APPSTORE_JSON; - - // Can be overriden with APPEARANCE_OVERRIDE_PATH directive - extern std::string THEME_CONFIG_INI_PATH; - extern std::string WALLPAPER_PATH; - - - //#if IS_LAUNCHER_DIRECTIVE - extern const std::string SPLIT_PROJECT_NAME_1; - extern const std::string SPLIT_PROJECT_NAME_2; - extern const std::string BOOT_PACKAGE_FILENAME; - extern const std::string EXIT_PACKAGE_FILENAME; - extern const std::string PACKAGE_FILENAME; - - extern const std::string DOWNLOADS_PATH; - extern const std::string EXPANSION_PATH; - extern const std::string FUSE_DATA_INI_PATH; - extern const std::string PACKAGE_PATH; - extern const std::string OVERLAY_PATH; - extern const std::string OVERLAYS_INI_FILEPATH; - extern const std::string PACKAGES_INI_FILEPATH; - - extern const std::string NOTIFICATIONS_FLAG_FILEPATH; - - extern const std::set PROTECTED_FILES; - - extern const std::string ULTRAHAND_REPO_URL; - extern const std::string INCLUDED_THEME_FOLDER_URL; - extern const std::string LATEST_RELEASE_INFO_URL; - extern const std::string NX_OVLLOADER_ZIP_URL; - extern const std::string NX_OVLLOADER_PLUS_ZIP_URL; - extern const std::string OLD_NX_OVLLOADER_ZIP_URL; - extern const std::string OLD_NX_OVLLOADER_PLUS_ZIP_URL; - extern const std::string UPDATER_PAYLOAD_URL; - extern const std::string SOUND_EFFECTS_URL; - - extern const std::string LAUNCH_ARGS_STR; - extern const std::string USE_LAUNCH_ARGS_STR; - extern const std::string USE_QUICK_LAUNCH_STR; - extern const std::string USE_BOOT_PACKAGE_STR; - extern const std::string USE_EXIT_PACKAGE_STR; - extern const std::string USE_LOGGING_STR; - - //#endif - - extern const std::string TESLA_COMBO_STR; - extern const std::string ULTRAHAND_COMBO_STR; - - extern const std::string FUSE_STR; - extern const std::string TESLA_STR; - extern const std::string ERISTA_STR; - extern const std::string MARIKO_STR; - extern const std::string KEY_COMBO_STR; - extern const std::string DEFAULT_LANG_STR; - - - extern const std::string LIST_STR; - extern const std::string LIST_FILE_STR; - extern const std::string JSON_STR; - extern const std::string JSON_FILE_STR; - extern const std::string INI_FILE_STR; - extern const std::string HEX_FILE_STR; - extern const std::string PACKAGE_STR; - extern const std::string PACKAGES_STR; - extern const std::string OVERLAY_STR; - extern const std::string OVERLAYS_STR; - extern const std::string IN_OVERLAY_STR; - extern const std::string IN_HIDDEN_OVERLAY_STR; - extern const std::string IN_HIDDEN_PACKAGE_STR; - extern const std::string FILE_STR; - extern const std::string SYSTEM_STR; - extern const std::string MODE_STR; - extern const std::string GROUPING_STR; - extern const std::string FOOTER_STR; - extern const std::string TOGGLE_STR; - extern const std::string LEFT_STR; - extern const std::string RIGHT_STR; - extern const std::string CENTER_STR; - extern const std::string HIDE_STR; - extern const std::string STAR_STR; - extern const std::string PRIORITY_STR; - extern const std::string ON_STR; - extern const std::string OFF_STR; - extern const std::string CAPITAL_ON_STR; - extern const std::string CAPITAL_OFF_STR; - extern const std::string TRUE_STR; - extern const std::string FALSE_STR; - extern const std::string GLOBAL_STR; - extern const std::string DEFAULT_STR; - extern const std::string 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/haptics.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/haptics.hpp deleted file mode 100644 index 1b887295..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/haptics.hpp +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************** - * File: haptics.hpp - * Author: ppkantorski - * Description: - * This header declares functions and shared flags for managing haptic feedback - * in the Ultrahand Overlay. It includes routines for initializing vibration - * devices, sending rumble and double-click patterns, and controlling timing - * for single and double pulse haptics. Atomic flags ensure safe access across - * threads. - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 2025 ppkantorski - ********************************************************************************/ - -#pragma once -#include -#include -#include - -namespace ult { - - //extern bool rumbleInitialized; - extern std::atomic rumbleActive; - extern std::atomic doubleClickActive; - - //void initRumble(); - void deinitRumble(); - void checkAndReinitRumble(); - - void rumbleClick(); - void rumbleDoubleClick(); - void processRumbleStop(u64 nowNs); - void processRumbleDoubleClick(u64 nowNs); - void rumbleDoubleClickStandalone(); -} \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/hex_funcs.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/hex_funcs.hpp deleted file mode 100644 index bdd29144..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/hex_funcs.hpp +++ /dev/null @@ -1,211 +0,0 @@ -/******************************************************************************** - * File: hex_funcs.hpp - * Author: ppkantorski - * Description: - * This header file provides functions for working with hexadecimal data in C++. - * It includes functions for converting between ASCII and hexadecimal strings, - * finding hexadecimal data offsets in a file, and editing hexadecimal data in a file. - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 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 deleted file mode 100644 index c85da275..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/ini_funcs.hpp +++ /dev/null @@ -1,344 +0,0 @@ -/******************************************************************************** - * File: ini_funcs.hpp - * Author: ppkantorski - * Description: - * This header file provides functions for working with INI (Initialization) files - * in C++. It includes functions for reading, parsing, and editing INI files, - * as well as cleaning INI file formatting. - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 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 deleted file mode 100644 index 5995cc7d..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/json_funcs.hpp +++ /dev/null @@ -1,107 +0,0 @@ -/******************************************************************************** - * File: json_funcs.hpp - * Author: ppkantorski - * Description: - * This header file provides functions for working with JSON files in C++ using - * the `cJSON` library. It includes a function to read JSON data from a file. - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 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& appID, const std::string& text, size_t fontSize=28); -} -#endif \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/list_funcs.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/list_funcs.hpp deleted file mode 100644 index b1b8aabb..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/list_funcs.hpp +++ /dev/null @@ -1,110 +0,0 @@ -/******************************************************************************** - * File: list_funcs.hpp - * Author: ppkantorski - * Description: - * This header file contains function declarations and utility functions related - * to working with lists and vectors of strings. These functions are used in the - * Ultrahand Overlay project to perform various operations on lists, such as - * removing entries, filtering, and more. - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 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 deleted file mode 100644 index b5b04315..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/mod_funcs.hpp +++ /dev/null @@ -1,121 +0,0 @@ -/******************************************************************************** - * File: mod_funcs.hpp - * Author: ppkantorski - * Description: - * This header file contains function declarations and utility functions for IPS - * binary generations. These functions are used in the Ultrahand Overlay project - * to convert `.pchtxt` mods into `.ips` binaries. - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 2024 ppkantorski - ********************************************************************************/ - -#pragma once - -#ifndef MOD_FUNCS_HPP -#define MOD_FUNCS_HPP - -#if !USING_FSTREAM_DIRECTIVE // For not using fstream (needs implementing) -#include -#else -#include -#endif - -//#include -#include -#include -#include -#include "debug_funcs.hpp" -#include "path_funcs.hpp" -#include "hex_funcs.hpp" -#include // Include this header for std::setw and std::setfill - -namespace ult { - inline constexpr const char* IPS32_HEAD_MAGIC = "IPS32"; - inline constexpr const char* IPS32_FOOT_MAGIC = "EEOF"; - - //const std::string CHEAT_HEADER = "// auto generated by pchtxt2cheat\n\n"; - //extern const std::string CHEAT_TYPE; - //extern const std::string CHEAT_EXT; - //extern const std::string CHEAT_ENCODING; - - /** - * @brief Checks if a cheat already exists in the cheat file. - * @param cheatFilePath The path to the cheat file. - * @param newCheat The new cheat to check. - * @return True if the cheat exists, otherwise false. - */ - bool cheatExists(const std::string &cheatFilePath, const std::string &newCheat); - - /** - * @brief Appends a new cheat to the cheat file. - * @param cheatFilePath The path to the cheat file. - * @param newCheat The new cheat to append. - */ - void appendCheatToFile(const std::string &cheatFilePath, const std::string &newCheat); - - /** - * @brief Extracts the cheat name from the given file path. - * @param filePath The full file path. - * @return The extracted cheat name. - */ - std::string extractCheatName(const std::string &filePath); - - // Helper function to determine if a string is a valid title ID - bool isValidTitleID(const std::string &str); - - // Function to find the title ID in the text, avoiding the @nsobid- line - std::string findTitleID(const std::string &text); - - /** - * @brief Converts a .pchtxt file to a cheat file. - * @param pchtxtPath The file path to the .pchtxt file. - * @param cheatName The name of the cheat. - * @param outCheatPath The file path for the output cheat file. - * @return True if the conversion was successful, false otherwise. - */ - bool pchtxt2cheat(const std::string &pchtxtPath, std::string cheatName = "", std::string outCheatPath = ""); - - // Corrected helper function to convert values to big-endian format - //uint32_t toBigEndian(uint32_t value); - // - //uint16_t toBigEndian(uint16_t value); - - // Corrected helper function to convert values to big-endian format - inline uint32_t toBigEndian(uint32_t value) { - return ((value & 0x000000FF) << 24) | - ((value & 0x0000FF00) << 8) | - ((value & 0x00FF0000) >> 8) | - ((value & 0xFF000000) >> 24); - } - - inline uint16_t toBigEndian(uint16_t value) { - return ((value & 0x00FF) << 8) | - ((value & 0xFF00) >> 8); - } - - // Helper function to convert a vector of bytes to a hex string for logging - - //std::string hexToString(const std::vector& bytes); - - - /** - * @brief Converts a .pchtxt file to an IPS file using fstream. - * - * This function reads the contents of a .pchtxt file, extracts the address-value pairs, - * and generates an IPS file with the provided output folder. - * - * @param pchtxtPath The file path to the .pchtxt file. - * @param outputFolder The folder path for the output IPS file. - * @return True if the conversion was successful, false otherwise. - */ - bool pchtxt2ips(const std::string& pchtxtPath, const std::string& outputFolder); -} - -#endif \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/path_funcs.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/path_funcs.hpp deleted file mode 100644 index 2eea6781..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/path_funcs.hpp +++ /dev/null @@ -1,279 +0,0 @@ -/******************************************************************************** - * File: path_funcs.hpp - * Author: ppkantorski - * Description: - * This header file contains function declarations and utility functions related - * to file and directory path manipulation. These functions are used in the - * Ultrahand Overlay project to handle file operations, such as creating - * directories, moving files, and more. - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 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 deleted file mode 100644 index 71696d07..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/string_funcs.hpp +++ /dev/null @@ -1,274 +0,0 @@ -/******************************************************************************** - * File: string_funcs.hpp - * Author: ppkantorski - * Description: - * This header file contains function declarations and utility functions for string - * manipulation. These functions are used in the Ultrahand Overlay project to - * perform operations like trimming whitespaces, removing quotes, replacing - * multiple slashes, and more. - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 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); - - extern bool canConvertToInt(const std::string& str); - - /** - * @brief A lightweight string stream class that mimics basic functionality of std::istringstream. - */ - class StringStream { - public: - StringStream() : position(0), hexMode(false), validState(true) {} - - - // Add this constructor to accept a string - StringStream(const std::string& input) : data(input), position(0), hexMode(false) {} - - // Set hex mode - StringStream& hex() { - hexMode = true; - return *this; - } - - // Reset hex mode - StringStream& resetHex() { - hexMode = false; - return *this; - } - - // Mimics std::getline() with a delimiter - bool getline(std::string& output, char delimiter); - - // Mimics operator >> to split by whitespace - StringStream& operator>>(std::string& output); - - // Overload the << operator to insert strings and integers - StringStream& operator<<(const std::string& input); - StringStream& operator<<(const char* input); - StringStream& operator<<(char input); - StringStream& operator<<(int input); // Handles int insertion with hex support - StringStream& operator<<(long long input); // for long long - - // Conversion to bool for checking stream state (success/failure) - explicit operator bool() const { - return validState; - } - - std::string str() const; - void clear() { data.clear(); position = 0; } // Add clear function - - private: - std::string data; - size_t position; - bool hexMode; - bool validState; // Track if the stream is in a valid state - }; - - - - /** - * @brief Trims leading and trailing whitespaces from a string. - * - * This function removes leading and trailing whitespaces, tabs, newlines, carriage returns, form feeds, - * and vertical tabs from the input string. - * - * @param str The input string to trim. - * @return The trimmed string. - */ - void trim(std::string& str); - - - - // Function to trim newline characters from the end of a string - void trimNewline(std::string& str); - - - /** - * @brief Removes all white spaces from a string. - * - * This function removes all white spaces, including spaces, tabs, newlines, carriage returns, form feeds, - * and vertical tabs from the input string. - * - * @param str The input string to remove white spaces from. - * @return The string with white spaces removed. - */ - std::string removeWhiteSpaces(const std::string& str); - - - - /** - * @brief Removes quotes from a string. - * - * This function removes single and double quotes from the beginning and end of the input string. - * - * @param str The input string to remove quotes from. - * @return The string with quotes removed. - */ - void removeQuotes(std::string& str); - - - /** - * @brief Replaces multiple consecutive slashes with a single slash in a string. - * - * This function replaces sequences of two or more consecutive slashes with a single slash in the input string. - * - * @param input The input string to process. - * @return The string with multiple slashes replaced. - */ - std::string replaceMultipleSlashes(const std::string& input); - - - void resolveDirectoryTraversal(std::string& path); - - /** - * @brief Preprocesses a path string by replacing multiple slashes and adding "sdmc:" prefix. - * - * This function preprocesses a path string by removing multiple consecutive slashes, - * adding the "sdmc:" prefix if not present, and modifying the input string in place. - * - * @param path The input path string to preprocess, passed by reference. - */ - void preprocessPath(std::string& path, const std::string& packagePath = ""); - - /** - * @brief Preprocesses a URL string by adding "https://" prefix. - * - * This function preprocesses a URL string by adding the "https://" prefix if not already present. - * - * @param path The input URL string to preprocess, passed by reference and modified in-place. - */ - void preprocessUrl(std::string& path); - - /** - * @brief Drops the file extension from a filename. - * - * This function removes the file extension (characters after the last dot) from the input filename string. - * - * @param filename The input filename from which to drop the extension, passed by reference and modified in-place. - */ - void dropExtension(std::string& filename); - - /** - * @brief Checks if a string starts with a given prefix. - * - * This function checks if the input string starts with the specified prefix. - * - * @param str The input string to check. - * @param prefix The prefix to check for. - * @return True if the string starts with the prefix, false otherwise. - */ - bool startsWith(const std::string& str, const std::string& prefix); - - - // Helper function to check if a string is a valid integer - bool isValidNumber(const std::string& str); - - // For properly handling placeholder replacements - std::string returnOrNull(const std::string& value); - - - // Function to slice a string from start to end index - std::string sliceString(const std::string& str, size_t start, size_t end); - - - /** - * @brief Converts a string to lowercase. - * - * This function takes a string as input and returns a lowercase version of that string. - * - * @param str The input string to convert to lowercase. - * @return The lowercase version of the input string. - */ - - std::string stringToLowercase(const std::string& str); - - - /** - * @brief Converts a string to uppercase. - * - * This function takes a string as input and returns an uppercase version of that string. - * - * @param str The input string to convert to uppercase. - * @return The uppercase version of the input string. - */ - - std::string stringToUppercase(const std::string& str); - - /** - * @brief Formats a priority string to a desired width. - * - * This function takes a priority string and formats it to a specified desired width by padding with '0's if it's shorter - * or truncating with '9's if it's longer. - * - * @param priority The input priority string to format. - * @param desiredWidth The desired width of the formatted string (default is 4). - * @return A formatted priority string. - */ - std::string formatPriorityString(const std::string& priority, int desiredWidth = 4); - - - - /** - * @brief Removes the part of the string after the first occurrence of '?' character. - * - * This function takes a string and removes the portion of the string that appears after - * the first '?' character, if found. If no '?' character is present, the string remains unchanged. - * - * @param input The input string from which to remove the tag, passed by reference and modified in-place. - */ - void removeTag(std::string &input); - - std::string getFirstLongEntry(const std::string& input, size_t minLength = 8); - - - // This will take a string like "v1.3.5-abasdfasdfa" and output "1.3.5". string could also look like "test-1.3.5-1" or "v1.3.5" and we will only want "1.3.5" - std::string cleanVersionLabel(const std::string& input); - - - std::string extractTitle(const std::string& input); - - - std::vector splitString(const std::string& str, const std::string& delimiter); - - - // Function to split a string by a delimiter and return a specific index - std::string splitStringAtIndex(const std::string& str, const std::string& delimiter, size_t index); - - - std::string customAlign(int number); - - #if IS_LAUNCHER_DIRECTIVE - std::string inputExists(const std::string& input); - #endif -} - -#endif \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/tsl_utils.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/tsl_utils.hpp deleted file mode 100644 index 4baabffe..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/tsl_utils.hpp +++ /dev/null @@ -1,726 +0,0 @@ -/******************************************************************************** - * File: tsl_utils.hpp - * Author: ppkantorski - * Description: - * 'tsl_utils.hpp' is a central utility header for the Ultrahand Overlay project, - * containing a variety of functions and definitions related to system status, - * input handling, and application-specific behavior on the Nintendo Switch. - * This header provides essential utilities for interacting with the system, - * managing key input, and enhancing overlay functionality. - * - * The utilities defined here are designed to operate independently, facilitating - * robust system interaction capabilities required for custom overlays. - * - * For the latest updates and contributions, visit the project's GitHub repository: - * GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay - * - * Note: This notice is integral to the project's documentation and must not be - * altered or removed. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 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 getBuildIdAsString(); - - std::string getTitleIdAsString(); - - extern std::string lastTitleID; - extern std::atomic resetForegroundCheck; - - - //extern bool isLauncher; - extern std::atomic internalTouchReleased; - extern u32 layerEdge; - extern bool useRightAlignment; - extern bool useSwipeToOpen; - extern bool useLaunchCombos; - extern bool useNotifications; - extern bool useSoundEffects; - extern bool useHapticFeedback; - extern bool usePageSwap; - extern std::atomic noClickableItems; - - extern bool useDynamicLogo; - extern bool useSelectionBG; - extern bool useSelectionText; - extern bool useSelectionValue; - - - - // Define the duration boundaries (for smooth scrolling) - //extern const std::chrono::milliseconds initialInterval; // Example initial interval - //extern const std::chrono::milliseconds shortInterval; // Short interval after long hold - //extern const std::chrono::milliseconds transitionPoint; // Point at which the shortest interval is reached - - - - //constexpr std::chrono::milliseconds initialInterval = std::chrono::milliseconds(67); // Example initial interval - //constexpr std::chrono::milliseconds shortInterval = std::chrono::milliseconds(10); // Short interval after long hold - //constexpr std::chrono::milliseconds transitionPoint = std::chrono::milliseconds(2000); // Point at which the shortest interval is reached - - // Function to interpolate between two durations - //std::chrono::milliseconds interpolateDuration(std::chrono::milliseconds start, std::chrono::milliseconds end, float t); - -#if IS_LAUNCHER_DIRECTIVE - extern std::atomic overlayLaunchRequested; - extern std::string requestedOverlayPath; - extern std::string requestedOverlayArgs; - extern std::mutex overlayLaunchMutex; -#endif - - - //#include // Comment out filesystem - - // CUSTOM SECTION START - //extern float backWidth, selectWidth, nextPageWidth; - extern std::atomic backWidth; - extern std::atomic selectWidth; - extern std::atomic nextPageWidth; - extern std::atomic inMainMenu; - extern std::atomic inOverlaysPage; - extern std::atomic inPackagesPage; - - extern bool firstBoot; // for detecting first boot - - //static std::unordered_map hexSumCache; - - // Define an atomic bool for interpreter completion - extern std::atomic threadFailure; - extern std::atomic runningInterpreter; - extern std::atomic shakingProgress; - - extern std::atomic isHidden; - extern std::atomic externalAbortCommands; - - //bool progressAnimation = false; - extern bool disableTransparency; - //bool useCustomWallpaper = false; - extern bool useMemoryExpansion; - extern bool useOpaqueScreenshots; - - extern std::atomic onTrackBar; - extern std::atomic allowSlide; - extern std::atomic unlockedSlide; - - void atomicToggle(std::atomic& b); - - /** - * @brief Shutdown modes for the Ultrahand-Overlay project. - * - * These macros define the shutdown modes used in the Ultrahand-Overlay project: - * - `SpsmShutdownMode_Normal`: Normal shutdown mode. - * - `SpsmShutdownMode_Reboot`: Reboot mode. - */ - #define SpsmShutdownMode_Normal 0 - #define SpsmShutdownMode_Reboot 1 - - /** - * @brief Key mapping macros for button keys. - * - * These macros define button keys for the Ultrahand-Overlay project to simplify key mappings. - * For example, `KEY_A` represents the `HidNpadButton_A` key. - */ - #define KEY_A HidNpadButton_A - #define KEY_B HidNpadButton_B - #define KEY_X HidNpadButton_X - #define KEY_Y HidNpadButton_Y - #define KEY_L HidNpadButton_L - #define KEY_R HidNpadButton_R - #define KEY_ZL HidNpadButton_ZL - #define KEY_ZR HidNpadButton_ZR - #define KEY_PLUS HidNpadButton_Plus - #define KEY_MINUS HidNpadButton_Minus - #define KEY_DUP HidNpadButton_Up - #define KEY_DDOWN HidNpadButton_Down - #define KEY_DLEFT HidNpadButton_Left - #define KEY_DRIGHT HidNpadButton_Right - #define KEY_SL HidNpadButton_AnySL - #define KEY_SR HidNpadButton_AnySR - #define KEY_LSTICK HidNpadButton_StickL - #define KEY_RSTICK HidNpadButton_StickR - #define KEY_UP HidNpadButton_AnyUp - #define KEY_DOWN HidNpadButton_AnyDown - #define KEY_LEFT HidNpadButton_AnyLeft - #define KEY_RIGHT HidNpadButton_AnyRight - - #define SCRIPT_KEY HidNpadButton_Minus - #define SYSTEM_SETTINGS_KEY HidNpadButton_Plus - #define SETTINGS_KEY HidNpadButton_Y - #define STAR_KEY HidNpadButton_X - - - // Define a mask with all possible key flags - #define ALL_KEYS_MASK (KEY_A | KEY_B | KEY_X | KEY_Y | KEY_DUP | KEY_DDOWN | KEY_DLEFT | KEY_DRIGHT | KEY_L | KEY_R | KEY_ZL | KEY_ZR | KEY_SL | KEY_SR | KEY_LSTICK | KEY_RSTICK | KEY_PLUS | KEY_MINUS) - - - extern bool updateMenuCombos; - - /** - * @brief Ultrahand-Overlay Input Macros - * - * This block of code defines macros for handling input in the Ultrahand-Overlay project. - * These macros simplify the mapping of input events to corresponding button keys and - * provide aliases for touch and joystick positions. - * - * The macros included in this block are: - * - * - `touchPosition`: An alias for a constant `HidTouchState` pointer. - * - `touchInput`: An alias for `&touchPos`, representing touch input. - * - `JoystickPosition`: An alias for `HidAnalogStickState`, representing joystick input. - * - * These macros are utilized within the Ultrahand-Overlay project to manage and interpret - * user input, including touch and joystick events. - */ - #define touchPosition const HidTouchState - #define touchInput &touchPos - #define JoystickPosition HidAnalogStickState - - //void convertComboToUnicode(std::string& combo); - - /** - * @brief Combo key mapping - */ - struct KeyInfo { - u64 key; - const char* name; - const char* glyph; - }; - - /** - * @brief Combo key mappings - * - * Ordered as they should be displayed - */ - extern std::array KEYS_INFO; - - std::unordered_map createButtonCharMap(); - - extern std::unordered_map buttonCharMap; - - - void convertComboToUnicode(std::string& combo); - - - // English string definitions - - extern const std::string whiteColor; - extern const std::string blackColor; - extern const std::string greyColor; - - extern std::atomic languageWasChanged; - - inline constexpr double _M_PI = 3.14159265358979323846; // For double precision - inline constexpr double RAD_TO_DEG = 180.0f / _M_PI; - - #if IS_LAUNCHER_DIRECTIVE - extern std::string ENGLISH; - extern std::string SPANISH; - extern std::string FRENCH; - extern std::string GERMAN; - extern std::string JAPANESE; - extern std::string KOREAN; - extern std::string ITALIAN; - extern std::string DUTCH; - extern std::string PORTUGUESE; - extern std::string RUSSIAN; - extern std::string UKRAINIAN; - extern std::string POLISH; - extern std::string SIMPLIFIED_CHINESE; - extern std::string TRADITIONAL_CHINESE; - - extern std::string OVERLAYS; //defined in libTesla now - extern std::string OVERLAYS_ABBR; - extern std::string OVERLAY; - extern std::string HIDDEN_OVERLAYS; - extern std::string PACKAGES; //defined in libTesla now - extern std::string PACKAGE; - extern std::string HIDDEN_PACKAGES; - extern std::string HIDDEN; - extern std::string HIDE_OVERLAY; - extern std::string HIDE_PACKAGE; - extern std::string LAUNCH_ARGUMENTS; - extern std::string 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 SOUND_EFFECTS; - extern std::string HAPTIC_FEEDBACK; - extern std::string OPAQUE_SCREENSHOTS; - - extern std::string PACKAGE_INFO; - extern std::string _TITLE; - extern std::string _VERSION; - extern std::string _CREATOR; - extern std::string _ABOUT; - extern std::string _CREDITS; - - extern std::string USERGUIDE_OFFSET; - extern std::string SETTINGS_MENU; - extern std::string SCRIPT_OVERLAY; - extern std::string STAR_FAVORITE; - extern std::string APP_SETTINGS; - extern std::string ON_MAIN_MENU; - extern std::string ON_A_COMMAND; - extern std::string ON_OVERLAY_PACKAGE; - extern std::string FEATURES; - extern std::string SWIPE_TO_OPEN; - - extern std::string THEME_SETTINGS; - extern std::string DYNAMIC_LOGO; - extern std::string SELECTION_BACKGROUND; - extern std::string SELECTION_TEXT; - extern std::string SELECTION_VALUE; - extern std::string LIBULTRAHAND_TITLES; - extern std::string LIBULTRAHAND_VERSIONS; - extern std::string PACKAGE_TITLES; - - extern std::string ULTRAHAND_HAS_STARTED; - extern std::string NEW_UPDATE_IS_AVAILABLE; - extern std::string REBOOT_IS_REQUIRED; - extern std::string HOLD_A_TO_DELETE; - extern std::string 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 refreshWallpaperNow; - extern std::atomic refreshWallpaper; - extern std::vector wallpaperData; - extern std::atomic inPlot; - - extern std::mutex wallpaperMutex; - extern std::condition_variable cv; - - - - // Function to load the RGBA file into memory and modify wallpaperData directly - void loadWallpaperFile(const std::string& filePath, s32 width = 448, s32 height = 720); - void loadWallpaperFileWhenSafe(); - - void reloadWallpaper(); - - // Global variables for FPS calculation - //extern double lastTimeCount; - //extern int frameCount; - //extern float fps; - //extern double elapsedTime; - - - extern std::atomic themeIsInitialized; - - // Variables for touch commands - extern std::atomic touchingBack; - extern std::atomic touchingSelect; - extern std::atomic touchingNextPage; - extern std::atomic touchingMenu; - extern std::atomic shortTouchAndRelease; - extern std::atomic longTouchAndRelease; - extern std::atomic simulatedBack; - //extern bool simulatedBackComplete; - extern std::atomic simulatedSelect; - //extern bool simulatedSelectComplete; - extern std::atomic simulatedNextPage; - //extern std::atomic simulatedNextPageComplete; - extern std::atomic simulatedMenu; - //extern bool simulatedMenuComplete; - extern std::atomic stillTouching; - extern std::atomic interruptedTouch; - extern std::atomic touchInBounds; - - -#if USING_WIDGET_DIRECTIVE - // Battery implementation - extern bool powerInitialized; - extern bool powerCacheInitialized; - extern uint32_t powerCacheCharge; - extern bool powerCacheIsCharging; - extern PsmSession powerSession; - - // Define variables to store previous battery charge and time - //extern uint32_t prevBatteryCharge; - //extern s64 timeOut; - - - extern std::atomic batteryCharge; - extern std::atomic isCharging; - - //constexpr std::chrono::seconds min_delay = std::chrono::seconds(3); // Minimum delay between checks - - bool powerGetDetails(uint32_t *_batteryCharge, bool *_isCharging); - - void powerInit(void); - - void powerExit(void); -#endif - - // Temperature Implementation - extern std::atomic PCB_temperature; - extern std::atomic SOC_temperature; - - /* - I2cReadRegHandler was taken from Switch-OC-Suite source code made by KazushiMe - Original repository link (Deleted, last checked 15.04.2023): https://github.com/KazushiMe/Switch-OC-Suite - */ - - Result I2cReadRegHandler(u8 reg, I2cDevice dev, u16 *out); - - - #define TMP451_SOC_TEMP_REG 0x01 // Register for SOC temperature integer part - #define TMP451_SOC_TMP_DEC_REG 0x10 // Register for SOC temperature decimal part - #define TMP451_PCB_TEMP_REG 0x00 // Register for PCB temperature integer part - #define TMP451_PCB_TMP_DEC_REG 0x15 // Register for PCB temperature decimal part - - // Common helper function to read temperature (integer and fractional parts) - Result ReadTemperature(float *temperature, u8 integerReg, u8 fractionalReg, bool integerOnly); - - // Function to get the SOC temperature - Result ReadSocTemperature(float *temperature, bool integerOnly = true); - - // Function to get the PCB temperature - Result ReadPcbTemperature(float *temperature, bool integerOnly = true); - - - - // Time implementation - - extern const std::string DEFAULT_DT_FORMAT; - extern std::string datetimeFormat; - - - // Widget settings - //static std::string hideClock, hideBattery, hidePCBTemp, hideSOCTemp; - extern bool hideClock, hideBattery, hidePCBTemp, hideSOCTemp, dynamicWidgetColors; - extern bool hideWidgetBackdrop, centerWidgetAlignment, extendedWidgetBackdrop; - - #if IS_LAUNCHER_DIRECTIVE - void reinitializeWidgetVars(); - #endif - - extern bool cleanVersionLabels, hideOverlayVersions, hidePackageVersions, useLibultrahandTitles, useLibultrahandVersions, usePackageTitles, usePackageVersions; - - 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 deleted file mode 100644 index c0d1f1f8..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/ultra.hpp +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************** - * File: ultra.hpp - * Author: ppkantorski - * Description: - * 'ultra.hpp' serves as a central include header for the Ultrahand Overlay project, - * bringing together a comprehensive suite of utility functions essential for the - * development and operation of custom overlays on the Nintendo Switch. This header - * provides consolidated access to functions facilitating debugging, string processing, - * file management, JSON manipulation, and more, enhancing the modularity and - * reusability of code within the project. - * - * These utilities are designed to operate independently, providing robust tools to - * support complex overlay functionalities and interactions. - * - * For the latest updates and contributions, visit the project's GitHub repository: - * GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay - * - * Note: This notice is integral to the project's documentation and must not be - * altered or removed. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 2024 ppkantorski - ********************************************************************************/ -#pragma once - -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-function" - -#ifndef ULTRA_HPP -#define ULTRA_HPP - -// Include all functional headers used in the libUltra library - -#include "global_vars.hpp" -#include "debug_funcs.hpp" -#include "string_funcs.hpp" -#include "get_funcs.hpp" -#include "path_funcs.hpp" -#include "list_funcs.hpp" -#include "json_funcs.hpp" -#include "ini_funcs.hpp" -#include "hex_funcs.hpp" -#include "download_funcs.hpp" -#include "mod_funcs.hpp" -#include "tsl_utils.hpp" -#include "audio_player.hpp" -#include "haptics.hpp" - -#endif // ULTRA_HPP \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/audio_player.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/audio_player.cpp deleted file mode 100644 index b9246519..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/audio_player.cpp +++ /dev/null @@ -1,312 +0,0 @@ -/******************************************************************************** - * File: audio_player.cpp - * Author: ppkantorski - * Description: - * Memory-optimized version with reduced allocation overhead and chunked I/O. - * Key changes: - * - Eliminated temporary vector allocations (saves 50% memory during load) - * - Chunked file reading to reduce peak memory usage - * - Reduced alignment padding (saves ~3-4KB per sound) - * - Added lazy loading option via unloadAllSounds() - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 2025 ppkantorski - ********************************************************************************/ - -#include "audio_player.hpp" - -namespace ult { - bool AudioPlayer::m_initialized = false; - std::atomic AudioPlayer::m_enabled{true}; - float AudioPlayer::m_masterVolume = 0.6f; - bool AudioPlayer::m_lastDockedState = false; - std::vector AudioPlayer::m_cachedSounds; - std::mutex AudioPlayer::m_audioMutex; - - bool AudioPlayer::initialize() { - std::lock_guard lock(m_audioMutex); - - if (m_initialized) return true; - - if (R_FAILED(audoutInitialize()) || R_FAILED(audoutStartAudioOut())) { - audoutExit(); - return false; - } - - m_initialized = true; - m_cachedSounds.resize(static_cast(SoundType::Count)); - m_lastDockedState = isDocked(); - reloadAllSounds(); - - return true; - } - - void AudioPlayer::exit() { - std::lock_guard lock(m_audioMutex); - - // Free all cached sound buffers - for (auto& cached : m_cachedSounds) { - if (cached.buffer) { - free(cached.buffer); - cached.buffer = nullptr; - } - cached.bufferSize = 0; - cached.dataSize = 0; - } - - if (m_initialized) { - audoutStopAudioOut(); - audoutExit(); - m_initialized = false; - } - } - - void AudioPlayer::reloadAllSounds() { - for (uint32_t i = 0; i < static_cast(SoundType::Count); ++i) { - loadSoundFromWav(static_cast(i), m_soundPaths[i]); - } - } - - void AudioPlayer::unloadAllSounds(const std::initializer_list& excludeSounds) { - std::lock_guard lock(m_audioMutex); - if (!m_initialized) return; - - for (uint32_t i = 0; i < m_cachedSounds.size(); ++i) { - SoundType current = static_cast(i); - - // Skip if this sound is in the exclude list - if (std::find(excludeSounds.begin(), excludeSounds.end(), current) != excludeSounds.end()) { - continue; - } - - auto& cached = m_cachedSounds[i]; - if (cached.buffer) { - free(cached.buffer); - cached.buffer = nullptr; - } - cached.bufferSize = 0; - cached.dataSize = 0; - } - } - - bool AudioPlayer::reloadIfDockedChanged() { - if (!m_initialized) return false; - - const bool currentDocked = isDocked(); - if (currentDocked == m_lastDockedState) return false; - - std::lock_guard lock(m_audioMutex); - m_lastDockedState = currentDocked; - reloadAllSounds(); - - return true; - } - - bool AudioPlayer::loadSoundFromWav(SoundType type, const char* path) { - const uint32_t idx = static_cast(type); - if (!m_initialized || idx >= static_cast(SoundType::Count)) return false; - - // Free existing buffer - free(m_cachedSounds[idx].buffer); - m_cachedSounds[idx] = { nullptr, 0, 0 }; - - FILE* f = fopen(path, "rb"); - if (!f) return false; - - // Parse WAV header - char hdr[12]; - if (fread(hdr, 1, 12, f) != 12 || memcmp(hdr, "RIFF", 4) || memcmp(hdr + 8, "WAVE", 4)) { - fclose(f); - return false; - } - - u16 fmt = 0, ch = 0, bits = 0; - u32 rate = 0, dSize = 0; - long dPos = 0; - - // Find fmt and data chunks - while (fread(hdr, 1, 8, f) == 8) { - const u32 sz = *(u32*)(hdr + 4); - if (!memcmp(hdr, "fmt ", 4)) { - fread(&fmt, 2, 1, f); - fread(&ch, 2, 1, f); - fread(&rate, 4, 1, f); - fseek(f, 6, SEEK_CUR); - fread(&bits, 2, 1, f); - fseek(f, sz - 16, SEEK_CUR); - } else if (!memcmp(hdr, "data", 4)) { - dSize = sz; - dPos = ftell(f); - break; - } else { - fseek(f, sz, SEEK_CUR); - } - } - - // Validate format - if (!dSize || fmt != 1 || ch == 0 || ch > 2 || (bits != 8 && bits != 16)) { - fclose(f); - return false; - } - - // Calculate buffer sizes - // Note: audout REQUIRES stereo (2 channels), so we must duplicate mono - const bool mono = (ch == 1); - const uint32_t inSamples = dSize / (bits / 8); - const uint32_t outSamples = mono ? inSamples * 2 : inSamples; // Duplicate mono to stereo - const uint32_t outSize = outSamples * 2; // 16-bit samples - - // Use smaller alignment to reduce waste (256 bytes instead of 4KB) - const uint32_t align = 0x100; - const uint32_t bufSize = (outSize + align - 1) & ~(align - 1); - - // Allocate output buffer - void* buf = aligned_alloc(align, bufSize); - if (!buf) { - fclose(f); - return false; - } - - fseek(f, dPos, SEEK_SET); - s16* out = (s16*)buf; - - // Calculate volume scaling - float effectiveVolume = m_masterVolume; - if (m_lastDockedState) { - effectiveVolume *= 0.5f; - } - const float scale = std::clamp(effectiveVolume, 0.0f, 1.0f); - - // Process audio in chunks to minimize memory usage - // This eliminates the need for temporary vectors - constexpr uint32_t CHUNK_SIZE = 512; - - if (bits == 8) { - // 8-bit audio: read and convert in chunks - const int32_t scaleInt = static_cast(scale * 256.0f); - u8 chunk[CHUNK_SIZE]; - uint32_t remaining = inSamples; - uint32_t outIdx = 0; - - while (remaining > 0) { - const uint32_t toRead = std::min(remaining, CHUNK_SIZE); - if (fread(chunk, 1, toRead, f) != toRead) { - free(buf); - fclose(f); - return false; - } - - for (uint32_t i = 0; i < toRead; ++i) { - const s16 sample = static_cast((chunk[i] - 128) * scaleInt); - if (mono) { - // Duplicate to both L and R channels for stereo output - out[outIdx++] = sample; // Left - out[outIdx++] = sample; // Right - } else { - out[outIdx++] = sample; - } - } - remaining -= toRead; - } - } else { - // 16-bit audio: read and convert in chunks - s16 chunk[CHUNK_SIZE]; - uint32_t remaining = inSamples; - uint32_t outIdx = 0; - - while (remaining > 0) { - const uint32_t toRead = std::min(remaining, CHUNK_SIZE); - if (fread(chunk, sizeof(s16), toRead, f) != toRead) { - free(buf); - fclose(f); - return false; - } - - for (uint32_t i = 0; i < toRead; ++i) { - const s16 sample = static_cast(chunk[i] * scale); - if (mono) { - // Duplicate to both L and R channels for stereo output - out[outIdx++] = sample; // Left - out[outIdx++] = sample; // Right - } else { - out[outIdx++] = sample; - } - } - remaining -= toRead; - } - } - - fclose(f); - - // Zero-fill any padding - if (outSize < bufSize) { - memset((u8*)buf + outSize, 0, bufSize - outSize); - } - - m_cachedSounds[idx] = { buf, bufSize, outSize }; - return true; - } - - void AudioPlayer::playSound(SoundType type) { - // Lock-free check - SAFE with atomic - if (!m_enabled.load(std::memory_order_relaxed)) return; - - const uint32_t idx = static_cast(type); - if (idx >= static_cast(SoundType::Count)) return; - - std::lock_guard lock(m_audioMutex); - - // Check again under lock - if (!m_initialized) return; - - auto& cached = m_cachedSounds[idx]; - if (!cached.buffer) return; - - // Release any finished buffers - AudioOutBuffer* releasedBuffers = nullptr; - u32 releasedCount = 0; - audoutGetReleasedAudioOutBuffer(&releasedBuffers, &releasedCount); - - // Static buffer is safe with mutex protection - static AudioOutBuffer audioBuffer = {}; - audioBuffer = {}; - audioBuffer.buffer = cached.buffer; - audioBuffer.buffer_size = cached.bufferSize; - audioBuffer.data_size = cached.dataSize; - audioBuffer.data_offset = 0; - audioBuffer.next = nullptr; - - AudioOutBuffer* rel = nullptr; - audoutPlayBuffer(&audioBuffer, &rel); - } - - void AudioPlayer::setMasterVolume(float v) { - std::lock_guard lock(m_audioMutex); - m_masterVolume = std::clamp(v, 0.0f, 1.0f); - } - - void AudioPlayer::setEnabled(bool e) { - m_enabled.store(e, std::memory_order_relaxed); - } - - bool AudioPlayer::isEnabled() { - return m_enabled.load(std::memory_order_relaxed); - } - - bool AudioPlayer::isDocked() { - Result rc = apmInitialize(); - if (R_FAILED(rc)) return false; - - ApmPerformanceMode perfMode = ApmPerformanceMode_Invalid; - rc = apmGetPerformanceMode(&perfMode); - apmExit(); - - return R_SUCCEEDED(rc) && (perfMode == ApmPerformanceMode_Boost); - } -} \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/debug_funcs.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/debug_funcs.cpp deleted file mode 100644 index 0ec0fbd2..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/debug_funcs.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************** - * 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 char* message) { - std::time_t currentTime = std::time(nullptr); - std::tm* timeInfo = std::localtime(¤tTime); - char timestamp[30]; - strftime(timestamp, sizeof(timestamp), "[%Y-%m-%d %H:%M:%S] ", timeInfo); - - #if !USING_FSTREAM_DIRECTIVE - { - std::lock_guard lock(logMutex); - - FILE* file = fopen(logFilePath.c_str(), "a"); - if (file != nullptr) { - fputs(timestamp, file); - fputs(message, file); - fputc('\n', file); - fclose(file); - } - } - #else - { - std::lock_guard lock(logMutex); - - std::ofstream file(logFilePath.c_str(), std::ios::app); - if (file.is_open()) { - file << timestamp << message << "\n"; - } - } - #endif - } - - // Overload for std::string - void logMessage(const std::string& message) { - logMessage(message.c_str()); - } - #endif -} \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/download_funcs.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/download_funcs.cpp deleted file mode 100644 index 3ff0216e..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/download_funcs.cpp +++ /dev/null @@ -1,879 +0,0 @@ -/******************************************************************************** - * File: download_funcs.cpp - * Author: ppkantorski - * Description: - * This source file provides implementations for the functions declared in - * download_funcs.hpp. These functions utilize libcurl for downloading files - * from the internet and minizip-ng for extracting ZIP archives with proper - * 64-bit file support. - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 2024 ppkantorski - ********************************************************************************/ - -#include "download_funcs.hpp" - - -namespace ult { - -// Base loader definitions -size_t DOWNLOAD_READ_BUFFER = 8*1024;//64 * 1024;//4096*10; -size_t DOWNLOAD_WRITE_BUFFER = 8*1024;//64 * 1024; -size_t UNZIP_READ_BUFFER = 32*1024;//131072*2;//4096*4; -size_t UNZIP_WRITE_BUFFER = 16*1024;//131072*2;//4096*4; - - -// Path to the CA certificate -//const std::string cacertPath = "sdmc:/config/ultrahand/cacert.pem"; -//const std::string cacertURL = "https://curl.se/ca/cacert.pem"; - -// User agent string for curl requests -static constexpr const char* userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"; - -// Shared atomic flag to indicate whether to abort the download operation -std::atomic abortDownload(false); -// Define an atomic bool for interpreter completion -std::atomic abortUnzip(false); -std::atomic downloadPercentage(-1); -std::atomic unzipPercentage(-1); - -// Thread-safe curl initialization -static std::mutex curlInitMutex; -static std::atomic curlInitialized(false); - - -// Definition of CurlDeleter -struct CurlDeleter { - void operator()(CURL* curl) const noexcept { - if (curl) { - curl_easy_cleanup(curl); - } - } -}; - -struct FileDeleter { - void operator()(FILE* f) const { - if (f) { - fclose(f); - } - } -}; - -// Callback function to write received data to a file. -#if !USING_FSTREAM_DIRECTIVE -// Using stdio.h functions (FILE*, fwrite) -size_t writeCallback(void* ptr, size_t size, size_t nmemb, FILE* stream) { - if (!ptr || !stream) return 0; - //size_t totalBytes = size * nmemb; - //size_t writtenBytes = fwrite(ptr, 1, totalBytes, stream); - //return writtenBytes; - return fwrite(ptr, 1, size * nmemb, stream); -} -#else -// Using std::ofstream for writing -size_t writeCallback(void* ptr, size_t size, size_t nmemb, std::ostream* stream) { - if (!ptr || !stream) return 0; - auto& file = *static_cast(stream); - const size_t totalBytes = size * nmemb; - file.write(static_cast(ptr), totalBytes); - return totalBytes; -} -#endif - -// Your C function -int progressCallback(void *ptr, curl_off_t totalToDownload, curl_off_t nowDownloaded, curl_off_t totalToUpload, curl_off_t nowUploaded) { - if (!ptr) return 1; - - auto percentage = static_cast*>(ptr); - - if (totalToDownload > 0) { - //int newProgress = static_cast((static_cast(nowDownloaded) / static_cast(totalToDownload)) * 100.0); - percentage->store(static_cast((static_cast(nowDownloaded) / static_cast(totalToDownload)) * 100.0), std::memory_order_release); - } - - if (abortDownload.load(std::memory_order_acquire)) { - percentage->store(-1, std::memory_order_release); - return 1; // Abort the download - } - - return 0; // Continue the download -} - -// Global initialization function -//void initializeCurl() { -// std::lock_guard lock(curlInitMutex); -// if (!curlInitialized.load(std::memory_order_acquire)) { -// const CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT); -// if (res != CURLE_OK) { -// #if USING_LOGGING_DIRECTIVE -// if (!disableLogging) -// logMessage("curl_global_init() failed: " + std::string(curl_easy_strerror(res))); -// #endif -// // Handle error appropriately, possibly exit the program -// } else { -// curlInitialized.store(true, std::memory_order_release); -// } -// } -//} - -// Global cleanup function -//void cleanupCurl() { -// std::lock_guard lock(curlInitMutex); -// if (curlInitialized.load(std::memory_order_acquire)) { -// curl_global_cleanup(); -// curlInitialized.store(false, std::memory_order_release); -// } -//} - -std::unique_ptr globalWriteBuffer; - -/** - * @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 globalWriteBuffer; - if (DOWNLOAD_WRITE_BUFFER > 0) { - //if (!globalWriteBuffer) - globalWriteBuffer = std::make_unique(DOWNLOAD_WRITE_BUFFER); - // _IOFBF = full buffering, _IOLBF = line buffering, _IONBF = no buffering - setvbuf(file.get(), globalWriteBuffer.get(), _IOFBF, DOWNLOAD_WRITE_BUFFER); - } - - //setvbuf(file.get(), NULL, _IOFBF, DOWNLOAD_WRITE_BUFFER); -#endif - - // Ensure curl is initialized - //initializeCurl(); - - //if (!R_SUCCEEDED(socketInitializeDefault())) { - // #if USING_LOGGING_DIRECTIVE - // if (!disableLogging) - // logMessage("Failed to initialize socket."); - // #endif - // return false; - //} - - std::unique_ptr curl(curl_easy_init()); - if (!curl) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error initializing curl."); - #endif -#if USING_FSTREAM_DIRECTIVE - file.close(); -#else - file.reset(); - globalWriteBuffer.reset(); -#endif - return false; - } - - // Only initialize downloadPercentage if we're tracking progress - if (!noPercentagePolling) { - downloadPercentage.store(0, std::memory_order_release); - } - - curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str()); - curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, writeCallback); -#if USING_FSTREAM_DIRECTIVE - curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &file); -#else - curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, file.get()); -#endif - - // Conditionally set up progress callback based on noPercentagePolling - if (noPercentagePolling) { - // Disable progress function entirely - curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 1L); - } else { - // Enable progress callback for percentage updates - curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 0L); - curl_easy_setopt(curl.get(), CURLOPT_XFERINFOFUNCTION, progressCallback); - curl_easy_setopt(curl.get(), CURLOPT_XFERINFODATA, &downloadPercentage); - } - - curl_easy_setopt(curl.get(), CURLOPT_USERAGENT, userAgent); - curl_easy_setopt(curl.get(), CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); // Enable HTTP/2 - curl_easy_setopt(curl.get(), CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); - curl_easy_setopt(curl.get(), CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); // Force TLS 1.2 - - curl_easy_setopt(curl.get(), CURLOPT_FOLLOWLOCATION, 1L); - curl_easy_setopt(curl.get(), CURLOPT_BUFFERSIZE, DOWNLOAD_READ_BUFFER); // Increase buffer size - - // Add timeout options - curl_easy_setopt(curl.get(), CURLOPT_CONNECTTIMEOUT, 10L); // 10 seconds to connect - curl_easy_setopt(curl.get(), CURLOPT_LOW_SPEED_LIMIT, 1L); // 1 byte/s (virtually any progress) - curl_easy_setopt(curl.get(), CURLOPT_LOW_SPEED_TIME, 60L); // 1 minutes of no progress - - //curl_easy_setopt(curl.get(), CURLOPT_DNS_USE_GLOBAL_CACHE, 0L); - //curl_easy_setopt(curl.get(), CURLOPT_FORBID_REUSE, 1L); - //curl_easy_setopt(curl.get(), CURLOPT_CLOSESOCKETDATA, NULL); // ensure no dangling sockets - //curl_easy_setopt(curl.get(), CURLOPT_TCP_NODELAY, 1L); - - CURLcode result = curl_easy_perform(curl.get()); - - // Detect if download was aborted - //const bool wasAborted = (result == CURLE_ABORTED_BY_CALLBACK || - // abortDownload.load(std::memory_order_acquire)); - - -#if USING_FSTREAM_DIRECTIVE - file.close(); -#else - file.reset(); - globalWriteBuffer.reset(); -#endif - - curl.reset(); - - // Always cleanup global state - //curl_global_cleanup(); - // - //// Sleep to let cleanup finish - //for (int i = 0; i < 10; ++i) { - // svcSleepThread(50'000'000ULL); - //} - // - //// Explicitly reinitialize for next download - //curl_global_init(CURL_GLOBAL_DEFAULT); - - // CRITICAL: For aborted downloads, give curl time to clean up network/SSL state - // before destroying the handle. This prevents memory leaks in the global heap. - //if (wasAborted) { - // for (int i = 0; i < 10; ++i) { - // svcSleepThread(50'000'000ULL); // 50ms x 10 = 500ms total - // } - //} - - //cleanupCurl(); - - //socketExit(); - - if (result != CURLE_OK) { - #if USING_LOGGING_DIRECTIVE - if (result == CURLE_ABORTED_BY_CALLBACK) { - if (!disableLogging) - logMessage("Download aborted by user: " + url); - } else if (result == CURLE_OPERATION_TIMEDOUT) { - if (!disableLogging) - logMessage("Download timed out: " + url); - } else if (result == CURLE_COULDNT_CONNECT) { - if (!disableLogging) - logMessage("Could not connect to: " + url); - } else { - if (!disableLogging) - logMessage("Error downloading file: " + std::string(curl_easy_strerror(result))); - } - #endif - deleteFileOrDirectory(tempFilePath); - if (!noPercentagePolling) { - downloadPercentage.store(-1, std::memory_order_release); - } - return false; - } - -#if USING_FSTREAM_DIRECTIVE - std::ifstream checkFile(tempFilePath); - if (!checkFile || checkFile.peek() == std::ifstream::traits_type::eof()) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error downloading file: Empty file"); - #endif - deleteFileOrDirectory(tempFilePath); - // Only update percentage if we're tracking it - if (!noPercentagePolling) { - downloadPercentage.store(-1, std::memory_order_release); - } - checkFile.close(); - return false; - } - checkFile.close(); -#else - // Alternative method for checking if the file is empty (POSIX example) - struct stat fileStat; - if (stat(tempFilePath.c_str(), &fileStat) != 0 || fileStat.st_size == 0) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error downloading file: Empty file"); - #endif - deleteFileOrDirectory(tempFilePath); - // Only update percentage if we're tracking it - if (!noPercentagePolling) { - downloadPercentage.store(-1, std::memory_order_release); - } - return false; - } -#endif - - // Only update percentage if we're tracking it - if (!noPercentagePolling) { - downloadPercentage.store(100, std::memory_order_release); - } - - // CHECK FOR PROTECTED FILES AND ADD .ultra EXTENSION IF NEEDED - if (PROTECTED_FILES.find(destination) != PROTECTED_FILES.end()) { - destination += ".ultra"; - - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Protected file detected, renaming download to: " + destination); - #endif - } - - moveFile(tempFilePath, destination); - return true; -} - - -/** - * @brief Custom I/O function for opening files with larger buffer - */ -static voidpf ZCALLBACK fopen64_file_func_custom(voidpf opaque, const void* filename, int mode) { - FILE* file = nullptr; - const char* mode_fopen = nullptr; - - if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER) == ZLIB_FILEFUNC_MODE_READ) - mode_fopen = "rb"; - else if (mode & ZLIB_FILEFUNC_MODE_EXISTING) - mode_fopen = "r+b"; - else if (mode & ZLIB_FILEFUNC_MODE_CREATE) - mode_fopen = "wb"; - - if ((filename != nullptr) && (mode_fopen != nullptr)) { - file = fopen((const char*)filename, mode_fopen); - if (file && ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER) == ZLIB_FILEFUNC_MODE_READ)) { - // Set 64KB buffer for reading the ZIP file - reduces syscalls - //static const size_t zipReadBufferSize = UNZIP_READ_BUFFER; - setvbuf(file, nullptr, _IOFBF, UNZIP_READ_BUFFER); - } - } - return file; -} - -static int ZCALLBACK fclose64_file_func_custom(voidpf opaque, voidpf stream) { - int ret = EOF; - if (stream != nullptr) { - ret = fclose((FILE*)stream); - } - return ret; -} - -/** - * @brief Extracts files from a ZIP archive to a specified destination. - * - * Ultra-optimized single-pass extraction with smooth byte-based progress reporting - * using miniz with proper 64-bit file support and streaming extraction. - * Fixed memory leaks with RAII for proper resource cleanup on abort. - * - * @param zipFilePath The path to the ZIP archive file. - * @param toDestination The destination directory where files should be extracted. - * @return True if the extraction was successful, false otherwise. - */ -bool unzipFile(const std::string& zipFilePath, const std::string& toDestination) { - abortUnzip.store(false, std::memory_order_release); - unzipPercentage.store(0, std::memory_order_release); - - // Time-based abort checking - pre-calculated constants - //u64 lastAbortCheck = armTicksToNs(armGetSystemTick()); - //u64 currentNanos; // Reused for all tick operations - bool success = true; - - // RAII wrapper for unzFile - struct UnzFileManager { - unzFile file = nullptr; - - UnzFileManager(const std::string& path) { - zlib_filefunc64_def ffunc; - fill_fopen64_filefunc(&ffunc); - ffunc.zopen64_file = fopen64_file_func_custom; - ffunc.zclose_file = fclose64_file_func_custom; - file = unzOpen2_64(path.c_str(), &ffunc); - } - - ~UnzFileManager() { - if (file) { - unzClose(file); - file = nullptr; - } - } - - bool is_valid() const { return file != nullptr; } - operator unzFile() const { return file; } - }; - - // RAII wrapper for output file - struct OutputFileManager { - #if !USING_FSTREAM_DIRECTIVE - FILE* file = nullptr; - std::unique_ptr buffer; - size_t bufferSize; - - OutputFileManager(size_t bufSize) : bufferSize(bufSize) { - buffer = std::make_unique(bufferSize); - } - - bool open(const std::string& path) { - close(); - file = fopen(path.c_str(), "wb"); - if (file) { - setvbuf(file, buffer.get(), _IOFBF, bufferSize); - } - return file != nullptr; - } - - void close() { - if (file) { - fclose(file); - file = nullptr; - } - } - - bool is_open() const { return file != nullptr; } - - size_t write(const void* data, size_t size) { - return file ? fwrite(data, 1, size, file) : 0; - } - - ~OutputFileManager() { close(); } - #else - std::ofstream file; - - OutputFileManager(size_t bufSize) { - // Constructor for consistency with FILE* version - } - - bool open(const std::string& path) { - close(); - file.open(path, std::ios::binary); - if (file.is_open()) { - file.rdbuf()->pubsetbuf(nullptr, UNZIP_WRITE_BUFFER); - } - return file.is_open(); - } - - void close() { - if (file.is_open()) { - file.close(); - } - } - - bool is_open() const { return file.is_open(); } - - size_t write(const void* data, size_t size) { - if (file.is_open()) { - file.write(static_cast(data), size); - return file.good() ? size : 0; - } - return 0; - } - #endif - }; - - UnzFileManager zipFile(zipFilePath); - if (!zipFile.is_valid()) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Failed to open zip file: " + zipFilePath); - #endif - return false; - } - - // Get global info about the ZIP file - unz_global_info64 globalInfo; - if (unzGetGlobalInfo64(zipFile, &globalInfo) != UNZ_OK) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Failed to get zip file info"); - #endif - return false; - } - - const uLong numFiles = globalInfo.number_entry; - if (numFiles == 0) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("No files found in archive"); - #endif - return false; - } - - // ALWAYS calculate total size for accurate byte-based progress - ZPOS64_T totalUncompressedSize = 0; - char tempFilenameBuffer[512]; - unz_file_info64 fileInfo; - - // First pass: calculate total uncompressed size - int result = unzGoToFirstFile(zipFile); - while (result == UNZ_OK) { - // Time-based abort check at start of each file (only if 2+ seconds have passed) - //currentNanos = armTicksToNs(armGetSystemTick()); - //if ((currentNanos - lastAbortCheck) >= 2000000000ULL) { - // if (abortUnzip.load(std::memory_order_relaxed)) { - // unzipPercentage.store(-1, std::memory_order_release); - // #if USING_LOGGING_DIRECTIVE - // logMessage("Extraction aborted during size calculation"); - // #endif - // abortUnzip.store(false, std::memory_order_release); - // return false; - // } - // lastAbortCheck = currentNanos; - //} - if (abortUnzip.load(std::memory_order_relaxed)) { - unzipPercentage.store(-1, std::memory_order_release); - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Extraction aborted during size calculation"); - #endif - abortUnzip.store(false, std::memory_order_release); - return false; - } - - if (unzGetCurrentFileInfo64(zipFile, &fileInfo, tempFilenameBuffer, sizeof(tempFilenameBuffer), - nullptr, 0, nullptr, 0) == UNZ_OK) { - const size_t nameLen = strlen(tempFilenameBuffer); - if (nameLen > 0 && tempFilenameBuffer[nameLen - 1] != '/') { - totalUncompressedSize += std::max(fileInfo.uncompressed_size, static_cast(1)); - } - } - result = unzGoToNextFile(zipFile); - } - - // Fallback to 1 if no actual data (avoid division by zero) - if (totalUncompressedSize == 0) { - totalUncompressedSize = 1; - } - - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) { - logMessage("Processing " + std::to_string(numFiles) + " files, " + - std::to_string(totalUncompressedSize) + " total bytes from archive"); - } - - #endif - - // Pre-allocate ALL reusable strings and variables outside the main loop - std::string fileName, extractedFilePath, directoryPath; - //fileName.reserve(512); - //extractedFilePath.reserve(1024); - //directoryPath.reserve(1024); - - // Single large buffer for extraction - reused for all files - const size_t bufferSize = UNZIP_WRITE_BUFFER; - //std::unique_ptr buffer = std::make_unique(bufferSize); - - globalWriteBuffer = 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, globalWriteBuffer.get(), bufferSize)) > 0) { - if (abortUnzip.load(std::memory_order_relaxed)) { - extractSuccess = false; - break; // RAII will handle cleanup - } - - // Write data to file - if (outputFile.write(globalWriteBuffer.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); - } - - globalWriteBuffer.reset(); - - // Check final abort state - if (abortUnzip.load(std::memory_order_relaxed)) { - unzipPercentage.store(-1, std::memory_order_release); - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Extraction aborted by user"); - #endif - abortUnzip.store(false, std::memory_order_release); - return false; - } - - if (success && filesProcessed > 0) { - abortUnzip.store(false, std::memory_order_release); - unzipPercentage.store(100, std::memory_order_release); - - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) { - logMessage("Extraction completed: " + std::to_string(filesProcessed) + " files, " + - std::to_string(totalBytesProcessed) + " bytes"); - } - #endif - - return true; - } else { - abortUnzip.store(false, std::memory_order_release); - unzipPercentage.store(-1, std::memory_order_release); - return false; - } -} -} \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/get_funcs.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/get_funcs.cpp deleted file mode 100644 index 84f117e3..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/get_funcs.cpp +++ /dev/null @@ -1,506 +0,0 @@ -/******************************************************************************** - * File: get_funcs.cpp - * Author: ppkantorski - * Description: - * This source file provides the implementations of functions declared in - * get_funcs.hpp. These functions are responsible for retrieving and handling - * data from the file system and JSON files, including parsing overlay module - * information, reading file contents, and accessing structured data used - * in the Ultrahand Overlay project. - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 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 deleted file mode 100644 index 777b89fd..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/global_vars.cpp +++ /dev/null @@ -1,180 +0,0 @@ -/******************************************************************************** - * File: global_vars.cpp - * Author: ppkantorski - * Description: - * This source file provides the definitions of global constants and paths used - * throughout the Ultrahand Overlay project. These constants are essential for - * file management and configuration settings within the application. - * - * For the latest updates and contributions, visit the project's GitHub repository: - * GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay - * - * Note: This notice is integral to the project's documentation and must not be - * altered or removed. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 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 SOUNDS_PATH = BASE_CONFIG_PATH + "sounds/"; - const std::string FLAGS_PATH = BASE_CONFIG_PATH + "flags/"; - const std::string NOTIFICATIONS_PATH = BASE_CONFIG_PATH + "notifications/"; - const std::string PAYLOADS_PATH = BASE_CONFIG_PATH + "payloads/"; - const std::string HB_APPSTORE_JSON = SWITCH_PATH + "appstore/.get/packages/UltrahandOverlay/info.json"; - std::string THEME_CONFIG_INI_PATH = BASE_CONFIG_PATH + THEME_FILENAME; - std::string WALLPAPER_PATH = BASE_CONFIG_PATH + WALLPAPER_FILENAME; - const std::string DOWNLOADS_PATH = BASE_CONFIG_PATH + "downloads/"; - const std::string EXPANSION_PATH = BASE_CONFIG_PATH + "expansion/"; - const std::string FUSE_DATA_INI_PATH = BASE_CONFIG_PATH + FUSE_FILENAME; - const std::string PACKAGE_PATH = SWITCH_PATH + ".packages/"; - const std::string OVERLAY_PATH = SWITCH_PATH + ".overlays/"; - const std::string OVERLAYS_INI_FILEPATH = BASE_CONFIG_PATH + OVERLAYS_INI_FILENAME; - const std::string PACKAGES_INI_FILEPATH = BASE_CONFIG_PATH + PACKAGES_INI_FILENAME; - const std::string NOTIFICATIONS_FLAG_FILEPATH = FLAGS_PATH + NOTIFICATIONS_FLAG_FILENAME; - - // Protected files - const std::set PROTECTED_FILES = { - ROOT_PATH + "atmosphere/package3", - ROOT_PATH + "atmosphere/stratosphere.romfs" - }; - - // GitHub URLs - const std::string GITHUB_BASE_URL = "https://github.com/ppkantorski/"; - const std::string GITHUB_RAW_BASE_URL = "https://raw.githubusercontent.com/ppkantorski/"; - const std::string ULTRAHAND_REPO_URL = GITHUB_BASE_URL + "Ultrahand-Overlay/"; - const std::string INCLUDED_THEME_FOLDER_URL = GITHUB_RAW_BASE_URL + "Ultrahand-Overlay/main/themes/"; - const std::string LATEST_RELEASE_INFO_URL = GITHUB_RAW_BASE_URL + "Ultrahand-Overlay/main/RELEASE.ini"; - const std::string NX_OVLLOADER_ZIP_URL = GITHUB_BASE_URL + "nx-ovlloader/releases/latest/download/nx-ovlloader.zip"; - const std::string NX_OVLLOADER_PLUS_ZIP_URL = GITHUB_BASE_URL + "nx-ovlloader/releases/latest/download/nx-ovlloader+.zip"; - const std::string OLD_NX_OVLLOADER_ZIP_URL = GITHUB_BASE_URL + "nx-ovlloader/releases/download/v1.0.8/nx-ovlloader.zip"; - const std::string OLD_NX_OVLLOADER_PLUS_ZIP_URL = GITHUB_BASE_URL + "nx-ovlloader/releases/download/v1.0.8/nx-ovlloader+.zip"; - const std::string UPDATER_PAYLOAD_URL = GITHUB_RAW_BASE_URL + "Ultrahand-Overlay/main/payloads/ultrahand_updater.bin"; - const std::string SOUND_EFFECTS_URL = GITHUB_RAW_BASE_URL + "Ultrahand-Overlay/main/sounds/sounds.zip"; - - // Launch options - const std::string LAUNCH_ARGS_STR = "launch_args"; - const std::string USE_LAUNCH_ARGS_STR = "use_launch_args"; - const std::string USE_QUICK_LAUNCH_STR = "use_quick_launch"; - const std::string USE_BOOT_PACKAGE_STR = "use_boot_package"; - const std::string USE_EXIT_PACKAGE_STR = "use_exit_package"; - const std::string USE_LOGGING_STR = "use_logging"; - - // Combos - CONSTEXPR_STRING std::string TESLA_COMBO_STR = "L+DDOWN+RS"; - CONSTEXPR_STRING std::string ULTRAHAND_COMBO_STR = "ZL+ZR+DDOWN"; - - // System / mode strings - CONSTEXPR_STRING std::string FUSE_STR = "fuse"; - CONSTEXPR_STRING std::string TESLA_STR = "tesla"; - CONSTEXPR_STRING std::string ERISTA_STR = "erista"; - CONSTEXPR_STRING std::string MARIKO_STR = "mariko"; - CONSTEXPR_STRING std::string KEY_COMBO_STR = "key_combo"; - CONSTEXPR_STRING std::string DEFAULT_LANG_STR = "default_lang"; - - // Generic strings - CONSTEXPR_STRING std::string LIST_STR = "list"; - CONSTEXPR_STRING std::string LIST_FILE_STR = "list_file"; - CONSTEXPR_STRING std::string JSON_STR = "json"; - CONSTEXPR_STRING std::string JSON_FILE_STR = "json_file"; - CONSTEXPR_STRING std::string INI_FILE_STR = "ini_file"; - CONSTEXPR_STRING std::string HEX_FILE_STR = "hex_file"; - CONSTEXPR_STRING std::string PACKAGE_STR = "package"; - CONSTEXPR_STRING std::string PACKAGES_STR = "packages"; - CONSTEXPR_STRING std::string OVERLAY_STR = "overlay"; - CONSTEXPR_STRING std::string OVERLAYS_STR = "overlays"; - const std::string IN_OVERLAY_STR = "in_overlay"; - const std::string IN_HIDDEN_OVERLAY_STR = "in_hidden_overlay"; - const std::string IN_HIDDEN_PACKAGE_STR = "in_hidden_package"; - CONSTEXPR_STRING std::string FILE_STR = "file"; - CONSTEXPR_STRING std::string SYSTEM_STR = "system"; - CONSTEXPR_STRING std::string MODE_STR = "mode"; - CONSTEXPR_STRING std::string GROUPING_STR = "grouping"; - CONSTEXPR_STRING std::string FOOTER_STR = "footer"; - CONSTEXPR_STRING std::string TOGGLE_STR = "toggle"; - CONSTEXPR_STRING std::string LEFT_STR = "left"; - CONSTEXPR_STRING std::string RIGHT_STR = "right"; - CONSTEXPR_STRING std::string CENTER_STR = "center"; - CONSTEXPR_STRING std::string HIDE_STR = "hide"; - CONSTEXPR_STRING std::string STAR_STR = "star"; - CONSTEXPR_STRING std::string PRIORITY_STR = "priority"; - CONSTEXPR_STRING std::string ON_STR = "on"; - CONSTEXPR_STRING std::string OFF_STR = "off"; - CONSTEXPR_STRING std::string CAPITAL_ON_STR = "On"; - CONSTEXPR_STRING std::string CAPITAL_OFF_STR = "Off"; - CONSTEXPR_STRING std::string TRUE_STR = "true"; - CONSTEXPR_STRING std::string FALSE_STR = "false"; - CONSTEXPR_STRING std::string GLOBAL_STR = "global"; - CONSTEXPR_STRING std::string DEFAULT_STR = "default"; - CONSTEXPR_STRING std::string 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/haptics.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/haptics.cpp deleted file mode 100644 index 59a4b5cd..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/haptics.cpp +++ /dev/null @@ -1,202 +0,0 @@ -/******************************************************************************** - * File: haptics.cpp - * Author: ppkantorski - * Description: - * This source file provides implementations for the functions declared in - * haptics.hpp. These functions manage haptic feedback for the Ultrahand Overlay - * using libnx’s vibration interfaces. It includes routines for initializing - * rumble devices, sending vibration patterns, and handling single or double - * click feedback with timing control. Thread safety is maintained through - * atomic operations and synchronization mechanisms. - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 2025 ppkantorski - ********************************************************************************/ - -#include "haptics.hpp" - -namespace ult { - - // ===== Internal state (private to this file) ===== - //bool rumbleInitialized = false; - static HidVibrationDeviceHandle vibHandheld; - static HidVibrationDeviceHandle vibPlayer1Left; - static HidVibrationDeviceHandle vibPlayer1Right; - static u64 rumbleStartTick = 0; - static u64 doubleClickTick = 0; - static u8 doubleClickPulse = 0; - - // ===== Shared flags (accessible globally) ===== - std::atomic rumbleActive{false}; - std::atomic doubleClickActive{false}; - - // ===== Constants ===== - static constexpr u64 RUMBLE_DURATION_NS = 30'000'000ULL; - static constexpr u64 DOUBLE_CLICK_PULSE_DURATION_NS = 30'000'000ULL; - static constexpr u64 DOUBLE_CLICK_GAP_NS = 100'000'000ULL; - - static constexpr HidVibrationValue clickDocked = { - .amp_low = 0.20f, - .freq_low = 100.0f, - .amp_high = 0.80f, - .freq_high = 300.0f - }; - - static constexpr HidVibrationValue clickHandheld = { - .amp_low = 0.25f, - .freq_low = 100.0f, - .amp_high = 1.0f, - .freq_high = 300.0f - }; - - static constexpr HidVibrationValue vibrationStop{0}; - - // ===== Internal helpers ===== - static void initController(HidNpadIdType npad, HidVibrationDeviceHandle* handles, int count) { - const u32 styleMask = hidGetNpadStyleSet(npad); - if (styleMask) - hidInitializeVibrationDevices(handles, count, npad, static_cast(styleMask)); - } - - static void sendVibration(const HidVibrationValue* value) { - if (hidGetNpadStyleSet(HidNpadIdType_Handheld)) - hidSendVibrationValue(vibHandheld, value); - - if (hidGetNpadStyleSet(HidNpadIdType_No1)) { - hidSendVibrationValue(vibPlayer1Left, value); - hidSendVibrationValue(vibPlayer1Right, value); - } - } - - // ===== Public API ===== - void initRumble() { - //if (rumbleInitialized) return; - - // Try to initialize whatever is available - // Don't check if controllers exist - let initController handle it - initController(HidNpadIdType_Handheld, &vibHandheld, 1); - - HidVibrationDeviceHandle handles[2]; - initController(HidNpadIdType_No1, handles, 2); - vibPlayer1Left = handles[0]; - vibPlayer1Right = handles[1]; - - // Only mark as initialized if at least one controller was found - hidGetNpadStyleSet(HidNpadIdType_Handheld); - hidGetNpadStyleSet(HidNpadIdType_No1); - - //rumbleInitialized = (handheldStyle || player1Style); - - // If neither exist, stay uninitialized so we retry later - } - - //void deinitRumble() { - // rumbleInitialized = false; - //} - - void checkAndReinitRumble() { - static u32 lastHandheldStyle = 0; - static u32 lastPlayer1Style = 0; - - const u32 currentHandheldStyle = hidGetNpadStyleSet(HidNpadIdType_Handheld); - const u32 currentPlayer1Style = hidGetNpadStyleSet(HidNpadIdType_No1); - - // If not initialized but controllers exist, try to init - // This handles the boot race condition where HID reports controllers - // but vibration subsystem isn't ready yet - //if (!rumbleInitialized && (currentHandheldStyle || currentPlayer1Style)) { - // initRumble(); - //} - - // Reinit if controller configuration changed - if (currentHandheldStyle != lastHandheldStyle || currentPlayer1Style != lastPlayer1Style) { - //rumbleInitialized = false; - initRumble(); - } - // Update last style tracking regardless - lastHandheldStyle = currentHandheldStyle; - lastPlayer1Style = currentPlayer1Style; - } - - void rumbleClick() { - //if (!rumbleInitialized) { - // initRumble(); - // if (!rumbleInitialized) return; - //} - - sendVibration(hidGetNpadStyleSet(HidNpadIdType_Handheld) ? &clickHandheld : &clickDocked); - rumbleActive.store(true, std::memory_order_release); - rumbleStartTick = armGetSystemTick(); - } - - void rumbleDoubleClick() { - //if (!rumbleInitialized) { - // initRumble(); - // if (!rumbleInitialized) return; - //} - - sendVibration(hidGetNpadStyleSet(HidNpadIdType_Handheld) ? &clickHandheld : &clickDocked); - doubleClickActive.store(true, std::memory_order_release); - doubleClickPulse = 1; - doubleClickTick = armGetSystemTick(); - } - - void processRumbleStop(u64 nowNs) { - if (rumbleActive.load(std::memory_order_acquire) && - nowNs - armTicksToNs(rumbleStartTick) >= RUMBLE_DURATION_NS) { - sendVibration(&vibrationStop); - rumbleActive.store(false, std::memory_order_release); - } - } - - void processRumbleDoubleClick(u64 nowNs) { - if (!doubleClickActive.load(std::memory_order_acquire)) return; - - const u64 elapsed = nowNs - armTicksToNs(doubleClickTick); - - switch (doubleClickPulse) { - case 1: - if (elapsed >= DOUBLE_CLICK_PULSE_DURATION_NS) { - sendVibration(&vibrationStop); - doubleClickPulse = 2; - doubleClickTick = armGetSystemTick(); - } - break; - - case 2: - if (elapsed >= DOUBLE_CLICK_GAP_NS) { - sendVibration(hidGetNpadStyleSet(HidNpadIdType_Handheld) ? &clickHandheld : &clickDocked); - doubleClickPulse = 3; - doubleClickTick = armGetSystemTick(); - } - break; - - case 3: - if (elapsed >= DOUBLE_CLICK_PULSE_DURATION_NS) { - sendVibration(&vibrationStop); - doubleClickActive.store(false, std::memory_order_release); - doubleClickPulse = 0; - } - break; - } - } - - void rumbleDoubleClickStandalone() { - sendVibration(hidGetNpadStyleSet(HidNpadIdType_Handheld) ? &clickHandheld : &clickDocked); - svcSleepThread(DOUBLE_CLICK_PULSE_DURATION_NS); - - sendVibration(&vibrationStop); - svcSleepThread(DOUBLE_CLICK_GAP_NS); - - sendVibration(hidGetNpadStyleSet(HidNpadIdType_Handheld) ? &clickHandheld : &clickDocked); - svcSleepThread(DOUBLE_CLICK_PULSE_DURATION_NS); - - sendVibration(&vibrationStop); - } -} \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/hex_funcs.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/hex_funcs.cpp deleted file mode 100644 index c795f23c..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/hex_funcs.cpp +++ /dev/null @@ -1,881 +0,0 @@ -/******************************************************************************** - * File: hex_funcs.cpp - * Author: ppkantorski - * Description: - * This source file implements the functions declared in hex_funcs.hpp. - * These functions provide support for manipulating hexadecimal data, - * including conversions between ASCII and hexadecimal strings, - * locating specific hex patterns within files, and editing file contents - * at hex offsets. - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 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 deleted file mode 100644 index 47551c5a..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/ini_funcs.cpp +++ /dev/null @@ -1,2465 +0,0 @@ -/******************************************************************************** - * File: ini_funcs.cpp - * Author: ppkantorski - * Description: - * This source file implements the functions declared in ini_funcs.hpp. - * These functions provide support for working with INI (Initialization) files - * in C++. Functionality includes reading and parsing INI files, editing values, - * and cleaning formatting to ensure consistent structure. - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 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()); - } - fputc('\n', file); // 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 deleted file mode 100644 index b4acb50e..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/json_funcs.cpp +++ /dev/null @@ -1,400 +0,0 @@ -/******************************************************************************** - * File: json_funcs.cpp - * Author: ppkantorski - * Description: - * This source file provides functions for working with JSON files in C++ using - * the `cJSON` library. It includes a function to read JSON data from a file. - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 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& appID, const std::string& text, size_t fontSize) { - u64 tick = armGetSystemTick(); - std::string filename = appID + "-" + std::to_string(tick) + ".notify"; // priority 20 default - - // Build full path - const std::string fullPath = NOTIFICATIONS_PATH + filename; - - // Create JSON object - cJSON* notif = cJSON_CreateObject(); - if (!notif) return; - - cJSON_AddStringToObject(notif, "text", text.c_str()); - cJSON_AddNumberToObject(notif, "font_size", static_cast(fontSize)); - //cJSON_AddNumberToObject(notif, "arrival_ns", static_cast(armTicksToNs(tick))); - - // Serialize JSON - char* rendered = cJSON_PrintUnformatted(notif); - if (!rendered) { - cJSON_Delete(notif); - return; - } - - // Write to file (C-style) - FILE* file = fopen(fullPath.c_str(), "wb"); - if (file) { - fwrite(rendered, 1, strlen(rendered), file); - fclose(file); - } - - cJSON_free(rendered); - cJSON_Delete(notif); - } -} \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/list_funcs.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/list_funcs.cpp deleted file mode 100644 index b18edabf..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/list_funcs.cpp +++ /dev/null @@ -1,514 +0,0 @@ -/******************************************************************************** - * File: list_funcs.cpp - * Author: ppkantorski - * Description: - * This source file contains function declarations and utility functions related - * to working with lists and vectors of strings. These functions are used in the - * Ultrahand Overlay project to perform various operations on lists, such as - * removing entries, filtering, and more. - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 2024 ppkantorski - ********************************************************************************/ - -#include -#include - -namespace ult { - static constexpr const char* UNABLE_TO_OPEN_FILE = "Unable to open file: "; - - // Thread-safe file access mutex - static std::mutex file_access_mutex; - - std::vector splitIniList(const std::string& value) { - std::vector result; - std::string trimmed = value; - trim(trimmed); - if (trimmed.size() > 2 && trimmed.front() == '(' && trimmed.back() == ')') { - trimmed = trimmed.substr(1, trimmed.size() - 2); - ult::StringStream ss(trimmed); - std::string token; - while (ss.getline(token, ',')) { - trim(token); - result.push_back(token); - } - } - return result; - } - - std::string joinIniList(const std::vector& list) { - std::string result = ""; - for (size_t i = 0; i < list.size(); ++i) { - result += list[i]; - if (i + 1 < list.size()) { - result += ", "; - } - } - return result; - } - - - /** - * @brief Removes entries from a vector of strings that match a specified entry. - * - * This function removes entries from the `itemsList` vector of strings that match the `entry`. - * - * @param entry The entry to be compared against the elements in `itemsList`. - * @param itemsList The vector of strings from which matching entries will be removed. - */ - void removeEntryFromList(const std::string& entry, std::vector& itemsList) { - itemsList.erase(std::remove_if(itemsList.begin(), itemsList.end(), [&](const std::string& item) { - return item.compare(0, entry.length(), entry) == 0; - }), itemsList.end()); - } - - /** - * @brief Filters a list of strings based on a specified filter list. - * - * This function filters a list of strings (`itemsList`) by removing entries that match any - * of the criteria specified in the `filterList`. It uses the `removeEntryFromList` function - * to perform the removal. - * - * @param filterList The list of entries to filter by. Entries in `itemsList` matching any entry in this list will be removed. - * @param itemsList The list of strings to be filtered. - */ - void filterItemsList(const std::vector& filterList, std::vector& itemsList) { - for (const auto& entry : filterList) { - removeEntryFromList(entry, itemsList); - } - } - - - // Function to read file into a vector of strings with optional cap - 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(UNABLE_TO_OPEN_FILE + filePath); - #endif - return; - } - - for (const auto& entry : fileSet) { - fprintf(file, "%s\n", entry.c_str()); - } - - fclose(file); - #else - std::ofstream file(filePath); - if (!file.is_open()) { - #if USING_LOGGING_DIRECTIVE - logMessage(UNABLE_TO_OPEN_FILE + filePath); - #endif - return; - } - - for (const auto& entry : fileSet) { - file << entry << '\n'; - } - - file.close(); - #endif - } - - // Helper function for streaming comparison - void streamCompareAndWrite(const std::string& streamFilePath, - const std::unordered_set& compareSet, - const std::string& outputTxtFilePath) { - std::lock_guard lock(file_access_mutex); - - #if !USING_FSTREAM_DIRECTIVE - FILE* streamFile = fopen(streamFilePath.c_str(), "r"); - if (!streamFile) return; - - FILE* outputFile = fopen(outputTxtFilePath.c_str(), "w"); - if (!outputFile) { - fclose(streamFile); - return; - } - - static constexpr size_t BUFFER_SIZE = 8192; - char buffer[BUFFER_SIZE]; - size_t len; - - while (fgets(buffer, BUFFER_SIZE, streamFile)) { - len = strlen(buffer); - if (len > 0 && buffer[len - 1] == '\n') { - buffer[len - 1] = '\0'; - } - - if (compareSet.count(std::string(buffer))) { - fprintf(outputFile, "%s\n", buffer); - } - } - - fclose(streamFile); - fclose(outputFile); - - #else - std::ifstream streamFile(streamFilePath); - if (!streamFile.is_open()) return; - - std::ofstream outputFile(outputTxtFilePath); - if (!outputFile.is_open()) return; - - std::string line; - while (std::getline(streamFile, line)) { - if (compareSet.count(line)) { - outputFile << line << '\n'; - } - } - #endif - } - - // Function to compare two file lists and save duplicates to an output file - void compareFilesLists(const std::string& txtFilePath1, const std::string& txtFilePath2, const std::string& outputTxtFilePath) { - // Read files into sets - std::unordered_set fileSet1 = readSetFromFile(txtFilePath1); - std::unordered_set fileSet2 = readSetFromFile(txtFilePath2); - - // Always work with the smaller set for better performance - if (fileSet1.size() <= fileSet2.size()) { - // fileSet1 is smaller or equal - modify it - for (auto it = fileSet1.begin(); it != fileSet1.end();) { - if (fileSet2.count(*it) == 0) { - it = fileSet1.erase(it); - } else { - ++it; - } - } - writeSetToFile(fileSet1, outputTxtFilePath); - } else { - // fileSet2 is smaller - modify it instead - for (auto it = fileSet2.begin(); it != fileSet2.end();) { - if (fileSet1.count(*it) == 0) { - it = fileSet2.erase(it); - } else { - ++it; - } - } - writeSetToFile(fileSet2, outputTxtFilePath); - } - } - - void compareWildcardFilesLists( - const std::string& wildcardPatternFilePath, - const std::string& txtFilePath, - const std::string& outputTxtFilePath - ) { - std::unordered_set targetLines = readSetFromFile(txtFilePath); - std::unordered_set duplicates; - - auto wildcardFiles = getFilesListByWildcards(wildcardPatternFilePath); - - static constexpr size_t BUFFER_SIZE = 8192; - - for (auto& filePath : wildcardFiles) { - if (filePath == txtFilePath || targetLines.empty()) { - filePath = ""; // Clear early - continue; - } - - std::lock_guard lock(file_access_mutex); - - #if !USING_FSTREAM_DIRECTIVE - FILE* file = fopen(filePath.c_str(), "r"); - if (!file) { - #if USING_LOGGING_DIRECTIVE - logMessage(UNABLE_TO_OPEN_FILE + filePath); - #endif - continue; - } - - - char buffer[BUFFER_SIZE]; - - while (fgets(buffer, BUFFER_SIZE, file) && !targetLines.empty()) { // Early exit! - char* newlinePos = strchr(buffer, '\n'); - if (newlinePos) *newlinePos = '\0'; - - auto it = targetLines.find(std::string(buffer)); - if (it != targetLines.end()) { - duplicates.emplace(std::move(*it)); // Move instead of copy - targetLines.erase(it); - } - } - fclose(file); - - #else - std::ifstream file(filePath); - if (!file.is_open()) { - #if USING_LOGGING_DIRECTIVE - logMessage(UNABLE_TO_OPEN_FILE + filePath); - #endif - continue; - } - - std::string line; - while (std::getline(file, line) && !targetLines.empty()) { // Early exit! - auto it = targetLines.find(line); - if (it != targetLines.end()) { - duplicates.emplace(std::move(*it)); // Move instead of copy - targetLines.erase(it); - } - } - #endif - filePath = ""; // Clear after processing - reduces vector memory footprint - } - - writeSetToFile(duplicates, outputTxtFilePath); - } -} \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/mod_funcs.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/mod_funcs.cpp deleted file mode 100644 index aacede6e..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/mod_funcs.cpp +++ /dev/null @@ -1,736 +0,0 @@ -/******************************************************************************** - * File: mod_funcs.cpp - * Author: ppkantorski - * Description: - * This source file provides the implementations of functions declared in - * mod_funcs.hpp. These functions handle the conversion of `.pchtxt` mod files - * into `.ips` binary patches used by the Ultrahand Overlay project. This includes - * parsing, validating, and encoding patch data into the IPS format. - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 2024 ppkantorski - ********************************************************************************/ - -#include - -namespace ult { - - //const std::string CHEAT_HEADER = "// auto generated by pchtxt2cheat\n\n"; - static const std::string CHEAT_TYPE = "04000000"; - static const std::string CHEAT_EXT = ".txt"; - static const std::string CHEAT_ENCODING = "ascii"; - - - - /** - * @brief Checks if a cheat already exists in the cheat file. - * @param cheatFilePath The path to the cheat file. - * @param newCheat The new cheat to check. - * @return True if the cheat exists, otherwise false. - */ - bool cheatExists(const std::string& cheatFilePath, const std::string& newCheat) { - #if !USING_FSTREAM_DIRECTIVE - FILE* cheatFile = fopen(cheatFilePath.c_str(), "r"); // Open the cheat file in read mode - if (!cheatFile) { - return false; // Return false if the file cannot be opened - } - - //size_t len; - char buffer[1024]; // Buffer to store each line - while (fgets(buffer, sizeof(buffer), cheatFile)) { - // Remove newline character, if present - const size_t len = strlen(buffer); - if (len > 0 && buffer[len - 1] == '\n') { - buffer[len - 1] = '\0'; - } - if (newCheat == buffer) { - fclose(cheatFile); // Close the file before returning - return true; // Cheat exists - } - } - - fclose(cheatFile); // Close the file after processing - return false; // Cheat does not exist - #else - std::ifstream cheatFile(cheatFilePath); - if (!cheatFile) { - return false; // Return false if the file cannot be opened - } - - std::string line; - while (std::getline(cheatFile, line)) { - if (line == newCheat) { - return true; // Cheat exists - } - } - return false; // Cheat does not exist - #endif - } - - /** - * @brief Appends a new cheat to the cheat file. - * @param cheatFilePath The path to the cheat file. - * @param newCheat The new cheat to append. - */ - void appendCheatToFile(const std::string& cheatFilePath, const std::string& newCheat) { - #if !USING_FSTREAM_DIRECTIVE - FILE* cheatFile = fopen(cheatFilePath.c_str(), "a"); // Open the cheat file in append mode - if (!cheatFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Failed to open cheat file for appending: " + cheatFilePath); - #endif - return; // Handle the error accordingly - } - - fprintf(cheatFile, "%s\n", newCheat.c_str()); // Write the new cheat followed by a newline - fclose(cheatFile); // Close the file - #else - std::ofstream cheatFile(cheatFilePath, std::ios::app); - if (!cheatFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Failed to open cheat file for appending: " + cheatFilePath); - #endif - return; // Handle the error accordingly - } - - cheatFile << newCheat << std::endl; // Write the new cheat - #endif - } - - - /** - * @brief Extracts the cheat name from the given file path. - * @param filePath The full file path. - * @return The extracted cheat name. - */ - std::string extractCheatName(const std::string &filePath) { - const size_t lastSlash = filePath.find_last_of("/\\"); - if (lastSlash == std::string::npos) { - return ""; - } - const size_t secondLastSlash = filePath.find_last_of("/\\", lastSlash - 1); - if (secondLastSlash == std::string::npos) { - return ""; - } - const std::string lastDir = filePath.substr(secondLastSlash + 1, lastSlash - secondLastSlash - 1); - std::string fileName = filePath.substr(lastSlash + 1); - const size_t dotPos = fileName.find_last_of('.'); - if (dotPos != std::string::npos) { - fileName = fileName.substr(0, dotPos); - } - - // If lastDir contains " - ", extract the part after " - " - const size_t dashPos = lastDir.find(" - "); - std::string cheatName = lastDir; - if (dashPos != std::string::npos) { - cheatName = lastDir.substr(dashPos + 3); - } - - return cheatName + " " + fileName; - } - - // Helper function to determine if a string is a valid title ID - bool isValidTitleID(const std::string &str) { - if (str.length() != 16) return false; - for (char c : str) { - if (!std::isxdigit(c)) return false; // Check if each character is a hexadecimal digit - } - return true; - } - - // Function to find the title ID in the text, avoiding the @nsobid- line - std::string findTitleID(const std::string &text) { - const size_t nsobidPos = text.find("@nsobid-"); - const size_t startPos = (nsobidPos != std::string::npos) ? nsobidPos + 40 + 8 : 0; // Skip past @nsobid- and its value - - std::string potentialID; - for (size_t i = startPos; i <= text.length() - 16; ++i) { - potentialID = text.substr(i, 16); - if (isValidTitleID(potentialID)) { - return potentialID; - } - } - return ""; - } - - - /** - * @brief Converts a .pchtxt file to a cheat file. - * @param pchtxtPath The file path to the .pchtxt file. - * @param cheatName The name of the cheat. - * @param outCheatPath The file path for the output cheat file. - * @return True if the conversion was successful, false otherwise. - */ - bool pchtxt2cheat(const std::string &pchtxtPath, std::string cheatName, std::string outCheatPath) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Starting pchtxt2cheat with pchtxtPath: " + pchtxtPath); - #endif - - #if !USING_FSTREAM_DIRECTIVE - FILE* pchtxtFile = fopen(pchtxtPath.c_str(), "r"); - if (!pchtxtFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Unable to open file " + pchtxtPath); - #endif - return false; - } - - // Read the entire file into a string - std::string pchtxt; - char buffer[4096]; - while (fgets(buffer, sizeof(buffer), pchtxtFile)) { - pchtxt += buffer; - } - fclose(pchtxtFile); - #else - std::ifstream pchtxtFile(pchtxtPath); - if (!pchtxtFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Unable to open file " + pchtxtPath); - #endif - return false; - } - - std::string pchtxt((std::istreambuf_iterator(pchtxtFile)), std::istreambuf_iterator()); - #endif - - const size_t nsobidPos = pchtxt.find("@nsobid-"); - if (nsobidPos == std::string::npos) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Could not find bid in pchtxt file, the file is likely invalid."); - #endif - return false; - } - - const std::string bid = pchtxt.substr(nsobidPos + 8, 40); - const std::string bidShort = bid.substr(0, 16); - - const std::string tid = findTitleID(pchtxt); - if (tid.empty()) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Could not find TID in pchtxt file, the file is likely invalid."); - #endif - return false; - } - - std::string cheatFilePath; - - if (outCheatPath.empty()) { - const std::string folderPath = "sdmc:/atmosphere/contents/" + tid + "/cheats/"; - createDirectory(folderPath); - cheatFilePath = folderPath + bidShort + CHEAT_EXT; - } else { - cheatFilePath = outCheatPath; - } - - #if !USING_FSTREAM_DIRECTIVE - FILE* existingCheatFile = fopen(cheatFilePath.c_str(), "r"); - bool cheatNameExists = false; - if (existingCheatFile) { - char line[256]; - while (fgets(line, sizeof(line), existingCheatFile)) { - if (std::string(line) == "[" + cheatName + "]\n") { - cheatNameExists = true; - break; - } - } - fclose(existingCheatFile); - } - #else - std::ifstream existingCheatFile(cheatFilePath); - bool cheatNameExists = false; - if (existingCheatFile) { - std::string line; - while (std::getline(existingCheatFile, line)) { - if (line == "[" + cheatName + "]") { - cheatNameExists = true; - break; - } - } - } - existingCheatFile.close(); - #endif - - // Open output cheat file - #if !USING_FSTREAM_DIRECTIVE - FILE* outCheatFile = fopen(cheatFilePath.c_str(), "a"); - if (!outCheatFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Unable to create cheat file " + cheatFilePath); - #endif - return false; - } - #else - std::ofstream outCheatFile(cheatFilePath, std::ios::app); - if (!outCheatFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Unable to create cheat file " + cheatFilePath); - #endif - return false; - } - #endif - - if (!cheatNameExists) { - #if !USING_FSTREAM_DIRECTIVE - fprintf(outCheatFile, "[%s]\n", cheatName.c_str()); - #else - outCheatFile << "[" << cheatName << "]\n"; - #endif - } - - int offset = 0; - bool enabled = true; - int validCheatsProcessed = 0; // ADDED: Track number of valid cheats processed - StringStream iss(pchtxt); // Use your custom StringStream - std::string line; - - std::string addrStr, valStr; - size_t spacePos; - int codeOffset; - std::string cheatLine; - char offsetBuffer[9]; - - // Use your custom getline method instead of std::getline - while (iss.getline(line, '\n')) { // Custom getline with newline as the delimiter - - // strip inline C++-style comments - const auto slashPos = line.find("//"); - if (slashPos != std::string::npos) - line = line.substr(0, slashPos); - - // strip inline hash comments (but leave full-line # for headers) - const auto hashPos = line.find('#'); - if (hashPos != std::string::npos && hashPos > 0) - line = line.substr(0, hashPos); - - trim(line); - if (line.empty() || line[0] == '#') continue; - - if (line.find("@flag offset_shift ") == 0) { - const std::string offsetStr = line.substr(19); - offset = (offsetStr.find("0x") == 0 ? std::strtol(offsetStr.c_str(), nullptr, 16) : std::strtol(offsetStr.c_str(), nullptr, 10)) - 0x100; - continue; - } - - if (line.find("@enabled") == 0) { - enabled = true; - continue; - } - - if (line.find("@disabled") == 0) { - enabled = false; - continue; - } - - if (line.find("@stop") == 0) { - break; - } - - if (!enabled) { - continue; - } - - spacePos = line.find(' '); - if (spacePos == std::string::npos) { - continue; - } - - addrStr = line.substr(0, spacePos); - valStr = line.substr(spacePos + 1); - - if (addrStr.find_first_not_of("0123456789abcdefABCDEF") != std::string::npos || valStr.find_first_not_of("0123456789abcdefABCDEF") != std::string::npos) { - continue; - } - - codeOffset = std::strtol(valStr.c_str(), nullptr, 16) + offset; - snprintf(offsetBuffer, sizeof(offsetBuffer), "%08X", codeOffset); - cheatLine = CHEAT_TYPE + " " + addrStr + " " + hexToReversedHex(offsetBuffer); - - #if !USING_FSTREAM_DIRECTIVE - // Check if cheat already exists - FILE* checkFile = fopen(cheatFilePath.c_str(), "r"); - bool exists = false; - if (checkFile) { - char checkLine[256]; - while (fgets(checkLine, sizeof(checkLine), checkFile)) { - if (std::string(checkLine) == cheatLine + "\n") { - exists = true; - break; - } - } - fclose(checkFile); - } - - if (!exists) { - fprintf(outCheatFile, "%s\n", cheatLine.c_str()); - validCheatsProcessed++; // ADDED: Increment counter for new cheats - } - #else - if (!cheatExists(cheatFilePath, cheatLine)) { - outCheatFile << cheatLine << "\n"; - validCheatsProcessed++; // ADDED: Increment counter for new cheats - } - #endif - } - - #if !USING_FSTREAM_DIRECTIVE - fclose(outCheatFile); - #else - outCheatFile.close(); - #endif - - // ADDED: Check if any valid cheats were processed - if (validCheatsProcessed == 0) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Warning: No valid patch data found to convert to cheats in " + pchtxtPath); - #endif - return false; - } - - return true; - } - - - // Corrected helper function to convert values to big-endian format - //uint32_t toBigEndian(uint32_t value) { - // return ((value & 0x000000FF) << 24) | - // ((value & 0x0000FF00) << 8) | - // ((value & 0x00FF0000) >> 8) | - // ((value & 0xFF000000) >> 24); - //} - // - //uint16_t toBigEndian(uint16_t value) { - // return ((value & 0x00FF) << 8) | - // ((value & 0xFF00) >> 8); - //} - - // Helper function to convert a vector of bytes to a hex string for logging - - //std::string hexToString(const std::vector& bytes) { - // StringStream oss; // Use your custom StringStream - // oss.hex(); // Enable hex mode for the stream - // - // for (uint8_t byte : bytes) { - // if (byte < 0x10) { - // oss << "0"; // Append leading zero for single-digit hex values - // } - // oss << static_cast(byte); // Convert byte to int and then append it - // } - // - // return oss.str(); // Return the final hex string - //} - - - - - - /** - * @brief Converts a .pchtxt file to an IPS file using fstream. - * - * This function reads the contents of a .pchtxt file, extracts the address-value pairs, - * and generates an IPS file with the provided output folder. - * - * @param pchtxtPath The file path to the .pchtxt file. - * @param outputFolder The folder path for the output IPS file. - * @return True if the conversion was successful, false otherwise. - */ - bool pchtxt2ips(const std::string& pchtxtPath, const std::string& outputFolder) { - #if !USING_FSTREAM_DIRECTIVE - // Use FILE* for reading - FILE* pchtxtFile = fopen(pchtxtPath.c_str(), "r"); - if (!pchtxtFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Unable to open file " + pchtxtPath); - #endif - return false; - } - - std::vector>> patches; - char lineBuffer[512]; // Fixed: Use char buffer for fgets - std::string line; - uint32_t lineNum = 0; - std::string nsobid; - int offset = 0; // Default offset - bool enabled = true; - - uint32_t address; - uint8_t byte; - std::vector valueBytes; - std::string offsetStr; - - while (fgets(lineBuffer, sizeof(lineBuffer), pchtxtFile) != nullptr) { - line = lineBuffer; // Convert to string - ++lineNum; - if (line.empty() || line.front() == '@' || !enabled) { - if (line.find("@nsobid-") == 0) { - nsobid = line.substr(8); - } - if (line.find("@flag offset_shift ") == 0) { - offsetStr = line.substr(19); - offset = (offsetStr.find("0x") == 0 ? std::strtol(offsetStr.c_str(), nullptr, 16) : std::strtol(offsetStr.c_str(), nullptr, 10)); - } - if (line.find("@enabled") == 0) { - enabled = true; - continue; - } - if (line.find("@disabled") == 0) { - enabled = false; - continue; - } - if (line.find("@stop") == 0) { - break; - } - continue; // Skip empty lines and lines starting with '@' - } - - StringStream iss(line); - std::string addressStr, valueStr; - - if (!(iss >> addressStr >> valueStr)) { - continue; - } - - char* endPtr; - address = std::strtoul(addressStr.c_str(), &endPtr, 16) + offset; // Adjust address by offset - if (*endPtr != '\0') { - continue; - } - - for (size_t i = 0; i < valueStr.length(); i += 2) { - byte = ult::stoi(valueStr.substr(i, 2), nullptr, 16); - valueBytes.push_back(byte); - } - - if (valueBytes.empty()) { - continue; - } - - patches.push_back(std::make_pair(address, valueBytes)); - valueBytes.clear(); - } - - fclose(pchtxtFile); - - #else - // Use fstream for reading - std::ifstream pchtxtFile(pchtxtPath); - if (!pchtxtFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Unable to open file " + pchtxtPath); - #endif - return false; - } - - std::vector>> patches; - std::string line; - uint32_t lineNum = 0; - std::string nsobid; - int offset = 0; // Default offset - - uint32_t address; - uint8_t byte; - std::vector valueBytes; - std::string offsetStr; - - while (std::getline(pchtxtFile, line)) { - ++lineNum; - if (line.empty() || line.front() == '@') { - if (line.find("@nsobid-") == 0) { - nsobid = line.substr(8); - } - if (line.find("@flag offset_shift ") == 0) { - offsetStr = line.substr(19); - offset = (offsetStr.find("0x") == 0 ? std::strtol(offsetStr.c_str(), nullptr, 16) : std::strtol(offsetStr.c_str(), nullptr, 10)); - } - if (line.find("@stop") == 0) { - break; - } - continue; // Skip empty lines and lines starting with '@' - } - - StringStream iss(line); - std::string addressStr, valueStr; - - if (!(iss >> addressStr >> valueStr)) { - continue; - } - - char* endPtr; - address = std::strtoul(addressStr.c_str(), &endPtr, 16) + offset; // Adjust address by offset - if (*endPtr != '\0') { - continue; - } - - for (size_t i = 0; i < valueStr.length(); i += 2) { - byte = ult::stoi(valueStr.substr(i, 2), nullptr, 16); - valueBytes.push_back(byte); - } - - if (valueBytes.empty()) { - continue; - } - - patches.push_back(std::make_pair(address, valueBytes)); - valueBytes.clear(); - } - - pchtxtFile.close(); - #endif - - // CHECK: Return false if no patches were found - if (patches.empty()) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Warning: No valid patches found in " + pchtxtPath); - #endif - return false; - } - - if (nsobid.empty()) { - nsobid = pchtxtPath.substr(pchtxtPath.find_last_of("/\\") + 1); - nsobid = nsobid.substr(0, nsobid.find_last_of(".")); - } - - // Trim any newline characters from nsobid - trim(nsobid); - trimNewline(nsobid); - - const std::string ipsFileName = nsobid + ".ips"; - const std::string ipsFilePath = outputFolder + ipsFileName; - - #if !USING_FSTREAM_DIRECTIVE - // Use FILE* for writing - FILE* ipsFile = fopen(ipsFilePath.c_str(), "wb"); - if (!ipsFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Unable to create IPS file " + ipsFilePath); - #endif - return false; - } - - fwrite(IPS32_HEAD_MAGIC, sizeof(char), std::strlen(IPS32_HEAD_MAGIC), ipsFile); - - uint16_t valueLength; - uint32_t bigEndianAddress; - - for (const auto& patch : patches) { - bigEndianAddress = toBigEndian(patch.first); // Convert address to big-endian - fwrite(&bigEndianAddress, sizeof(bigEndianAddress), 1, ipsFile); // Write address - - valueLength = toBigEndian(static_cast(patch.second.size())); // Convert length to big-endian - fwrite(&valueLength, sizeof(valueLength), 1, ipsFile); // Write length of value - - fwrite(patch.second.data(), sizeof(uint8_t), patch.second.size(), ipsFile); // Write value - } - - fwrite(IPS32_FOOT_MAGIC, sizeof(char), std::strlen(IPS32_FOOT_MAGIC), ipsFile); - fclose(ipsFile); - - - FILE* _pchtxtFile = fopen(pchtxtPath.c_str(), "r"); - if (!_pchtxtFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Unable to open file " + pchtxtPath); - #endif - return false; // Changed: Return false if we can't read the file for title ID - } - - // Read the entire file into a string - std::string pchtxt; - char buffer[4096]; - while (fgets(buffer, sizeof(buffer), _pchtxtFile)) { - pchtxt += buffer; - } - fclose(_pchtxtFile); - - - const std::string tid = findTitleID(pchtxt); - if (!tid.empty()) { - const std::string tidFilePath = outputFolder + tid; - FILE* tidFile = fopen(tidFilePath.c_str(), "w"); - if (tidFile) { - fclose(tidFile); // Creates an empty file - } - } else { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Warning: Could not find Title ID in " + pchtxtPath); - #endif - } - #else - // Use fstream for writing - std::ofstream ipsFile(ipsFilePath, std::ios::binary); - if (!ipsFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Unable to create IPS file " + ipsFilePath); - #endif - return false; - } - - ipsFile.write(IPS32_HEAD_MAGIC, std::strlen(IPS32_HEAD_MAGIC)); - - uint16_t valueLength; - uint32_t bigEndianAddress; - for (const auto& patch : patches) { - bigEndianAddress = toBigEndian(patch.first); // Convert address to big-endian - ipsFile.write(reinterpret_cast(&bigEndianAddress), sizeof(bigEndianAddress)); // Write address - - valueLength = toBigEndian(static_cast(patch.second.size())); // Convert length to big-endian - ipsFile.write(reinterpret_cast(&valueLength), sizeof(valueLength)); // Write length of value - - ipsFile.write(reinterpret_cast(patch.second.data()), patch.second.size()); // Write value - } - - ipsFile.write(IPS32_FOOT_MAGIC, std::strlen(IPS32_FOOT_MAGIC)); - ipsFile.close(); - - - std::ifstream _pchtxtFile(pchtxtPath); - if (!_pchtxtFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Unable to open file " + pchtxtPath); - #endif - return false; // Changed: Return false if we can't read the file for title ID - } - - std::string pchtxt((std::istreambuf_iterator(_pchtxtFile)), std::istreambuf_iterator()); - - const std::string tid = findTitleID(pchtxt); - if (!tid.empty()) { - const std::string tidFilePath = outputFolder + tid; - std::ofstream tidFile(tidFilePath); - tidFile.close(); // Creates an empty file - } else { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Warning: Could not find Title ID in " + pchtxtPath); - #endif - } - #endif - - return true; - } - -} diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/path_funcs.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/path_funcs.cpp deleted file mode 100644 index fed30684..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/path_funcs.cpp +++ /dev/null @@ -1,1487 +0,0 @@ -/******************************************************************************** - * File: path_funcs.cpp - * Author: ppkantorski - * Description: - * This source file implements the functions declared in path_funcs.hpp. - * These utility functions are focused on file and directory path manipulation - * for the Ultrahand Overlay project. Functionality includes creating directories, - * checking existence of files or paths, moving or copying files, and normalizing - * file system paths for cross-platform compatibility. - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 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) - - static std::vector fileList; - - // RAII wrapper for FILE* to ensure proper cleanup - class FileGuard { - private: - FILE* file; - public: - FileGuard(FILE* f) : file(f) {} - ~FileGuard() { if (file) fclose(file); } - FILE* get() { return file; } - FILE* release() { FILE* f = file; file = nullptr; return f; } - }; - - /** - * @brief Checks if a path points to a directory. - * - * This function checks if the specified path points to a directory. - * - * @param path The path to check. - * @return True if the path is a directory, false otherwise. - */ - bool isDirectory(const std::string& path) { - struct stat pathStat; - return (stat(path.c_str(), &pathStat) == 0 && S_ISDIR(pathStat.st_mode)); - } - - /** - * @brief Checks if a path points to a file. - * - * This function checks if the specified path points to a file. - * - * @param path The path to check. - * @return True if the path is a file, false otherwise. - */ - bool isFile(const std::string& path) { - struct stat pathStat; - return (stat(path.c_str(), &pathStat) == 0 && S_ISREG(pathStat.st_mode)); - } - - /** - * @brief Checks if a path points to a file or directory. - * - * This function checks if the specified path points to either a file or a directory. - * - * @param path The path to check. - * @return True if the path points to a file or directory, false otherwise. - */ - bool isFileOrDirectory(const std::string& path) { - struct stat pathStat; - return (stat(path.c_str(), &pathStat) == 0); - } - - // Helper function to check if directory is empty - bool isDirectoryEmpty(const std::string& dirPath) { - DIR* dir = opendir(dirPath.c_str()); - if (!dir) return false; // Can't open, assume not empty - - dirent* entry; - while ((entry = readdir(dir)) != nullptr) { - if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) { - closedir(dir); - return false; // Found a file/directory - } - } - closedir(dir); - return true; // Empty directory - } - - - /** - * @brief Creates a single directory if it doesn't exist. - * - * This function checks if the specified directory exists, and if not, it creates the directory. - * - * @param directoryPath The path of the directory to be created. - */ - void createSingleDirectory(const std::string& directoryPath) { - // mkdir is generally thread-safe, returns EEXIST if already exists - if (mkdir(directoryPath.c_str(), 0777) != 0) { - // Only log error if it's not EEXIST - if (errno != EEXIST) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Failed to create directory: " + directoryPath + " - " + std::string(strerror(errno))); - #endif - } - } - } - - /** - * @brief Creates a directory and its parent directories if they don't exist. - * - * This function creates a directory specified by `directoryPath` and also creates any parent directories - * if they don't exist. It handles nested directory creation. - * - * @param directoryPath The path of the directory to be created. - */ - void createDirectory(const std::string& directoryPath) { - const std::string volume = ROOT_PATH; - std::string path = directoryPath; - - // Remove leading "sdmc:/" if present - if (path.compare(0, volume.size(), volume) == 0) { - path = path.substr(volume.size()); - } - - std::string parentPath = volume; - size_t pos = 0, nextPos; - - // Iterate through the path and create each directory level if it doesn't exist - while ((nextPos = path.find('/', pos)) != std::string::npos) { - if (nextPos != pos) { - parentPath.append(path, pos, nextPos - pos); - parentPath += '/'; - createSingleDirectory(parentPath); // Create the parent directory - } - pos = nextPos + 1; - } - - // Create the final directory level if it doesn't exist - if (pos < path.size()) { - parentPath += path.substr(pos); - createSingleDirectory(parentPath); // Create the final directory - } - } - - #if !USING_FSTREAM_DIRECTIVE - void writeLog(FILE* logFile, const std::string& line) { - if (logFile) { - std::lock_guard lock(logMutex2); - fprintf(logFile, "%s\n", line.c_str()); - fflush(logFile); // Ensure data is written immediately - } else { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Failed to write to log file."); - #endif - } - } - #else - void writeLog(std::ofstream& logFile, const std::string& line) { - if (logFile.is_open()) { - std::lock_guard lock(logMutex2); - logFile << line << std::endl; - logFile.flush(); // Ensure data is written immediately - } else { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Failed to write to log file."); - #endif - } - } - #endif - - /** - * @brief Creates a text file with the specified content. - * - * This function creates a text file specified by `filePath` and writes the given `content` to the file. - * - * @param filePath The path of the text file to be created. - * @param content The content to be written to the text file. - */ - void createTextFile(const std::string& filePath, const std::string& content) { - // Create parent directory first - createDirectory(getParentDirFromPath(filePath)); - - #if !USING_FSTREAM_DIRECTIVE - FileGuard file(fopen(filePath.c_str(), "w")); - if (file.get()) { - fputs(content.c_str(), file.get()); - } else { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Unable to create file " + filePath); - #endif - } - #else - std::ofstream file(filePath); - if (file.is_open()) { - file << content; - file.close(); - } else { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Unable to create file " + filePath); - #endif - } - #endif - } - - - /** - * @brief Deletes a file or directory. - * - * 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); - fileList = getFilesListByWildcards(pathPattern); - - for (auto& path : fileList) { - //logMessage("path: "+path); - deleteFileOrDirectory(path, logSource); - path = ""; - } - fileList.clear(); - fileList.shrink_to_fit(); - } - - // Helper function to reverse a log file safely - void reverseLogFile(const std::string& logFilePath) { - std::vector lines; - - #if !USING_FSTREAM_DIRECTIVE - FILE* file = fopen(logFilePath.c_str(), "r"); - if (!file) return; - - setvbuf(file, nullptr, _IOFBF, 8192); - - static constexpr size_t BUFFER_SIZE = 8192; - char buffer[BUFFER_SIZE]; - - while (fgets(buffer, BUFFER_SIZE, file)) { - size_t len = strlen(buffer); - if (len > 0 && buffer[len - 1] == '\n') buffer[len - 1] = '\0'; - lines.emplace_back(buffer); // std::string constructor ensures proper termination - } - fclose(file); - - FILE* outFile = fopen(logFilePath.c_str(), "w"); - if (outFile) { - setvbuf(outFile, nullptr, _IOFBF, 8192); - for (auto it = lines.rbegin(); it != lines.rend(); ++it) { - // Use fprintf instead of fputs to avoid any residual buffer issues - fprintf(outFile, "%s\n", it->c_str()); - } - fflush(outFile); - fclose(outFile); - } - #else - std::ifstream file(logFilePath); - if (!file.is_open()) return; - - static char readBuffer[8192]; - file.rdbuf()->pubsetbuf(readBuffer, sizeof(readBuffer)); - - std::string line; - while (std::getline(file, line)) lines.push_back(std::move(line)); - file.close(); - - std::ofstream outFile(logFilePath); - if (outFile.is_open()) { - static char writeBuffer[8192]; - outFile.rdbuf()->pubsetbuf(writeBuffer, sizeof(writeBuffer)); - - for (auto it = lines.rbegin(); it != lines.rend(); ++it) { - outFile << *it << '\n'; - } - outFile.flush(); - outFile.close(); - } - #endif - } - - void moveDirectory(const std::string& sourcePath, const std::string& destinationPath, - const std::string& logSource, const std::string& logDestination) { - - struct stat sourceInfo; - if (stat(sourcePath.c_str(), &sourceInfo) != 0) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) logMessage("Source directory doesn't exist: " + sourcePath); - #endif - return; - } - - if (mkdir(destinationPath.c_str(), 0777) != 0 && errno != EEXIST) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) logMessage("Failed to create destination directory: " + destinationPath); - #endif - return; - } - - bool needsLogging = !logSource.empty() || !logDestination.empty(); - - { - std::vector> stack; - std::vector directoriesToRemove; - - stack.push_back({sourcePath, destinationPath}); - - #if !USING_FSTREAM_DIRECTIVE - FILE* logSrcFile = nullptr; - FILE* logDestFile = nullptr; - - if (needsLogging && !logSource.empty()) { - createDirectory(getParentDirFromPath(logSource)); - logSrcFile = fopen(logSource.c_str(), "w"); - if (logSrcFile) setvbuf(logSrcFile, nullptr, _IOFBF, 8192); - } - if (needsLogging && !logDestination.empty()) { - createDirectory(getParentDirFromPath(logDestination)); - logDestFile = fopen(logDestination.c_str(), "w"); - if (logDestFile) setvbuf(logDestFile, nullptr, _IOFBF, 8192); - } - #else - std::unique_ptr logSrcFile, logDestFile; - static char srcBuffer[8192], destBuffer[8192]; - - if (needsLogging && !logSource.empty()) { - createDirectory(getParentDirFromPath(logSource)); - logSrcFile = std::make_unique(logSource); - if (logSrcFile->is_open()) logSrcFile->rdbuf()->pubsetbuf(srcBuffer, sizeof(srcBuffer)); - } - if (needsLogging && !logDestination.empty()) { - createDirectory(getParentDirFromPath(logDestination)); - logDestFile = std::make_unique(logDestination); - if (logDestFile->is_open()) logDestFile->rdbuf()->pubsetbuf(destBuffer, sizeof(destBuffer)); - } - #endif - - std::string fullPathSrc, fullPathDst; - //fullPathSrc.reserve(1024); - //fullPathDst.reserve(1024); - - dirent* entry; - DIR* dir; - const char* name; - - 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[0] == '.' && (name[1] == '\0' || (name[1] == '.' && name[2] == '\0'))) continue; - - fullPathSrc.assign(currentSource); - if (!fullPathSrc.empty() && fullPathSrc.back() != '/') fullPathSrc += '/'; - fullPathSrc += name; - - fullPathDst.assign(currentDestination); - if (!fullPathDst.empty() && fullPathDst.back() != '/') fullPathDst += '/'; - 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.emplace_back(fullPathSrc, fullPathDst); - directoriesToRemove.emplace_back(fullPathSrc); - - if (needsLogging) { - #if !USING_FSTREAM_DIRECTIVE - if (logSrcFile) fprintf(logSrcFile, "%s/\n", fullPathSrc.c_str()), fflush(logSrcFile); - if (logDestFile) fprintf(logDestFile, "%s/\n", fullPathDst.c_str()), fflush(logDestFile); - #else - if (logSrcFile && logSrcFile->is_open()) { *logSrcFile << fullPathSrc << "/\n"; logSrcFile->flush(); } - if (logDestFile && logDestFile->is_open()) { *logDestFile << fullPathDst << "/\n"; logDestFile->flush(); } - #endif - } - } else { - remove(fullPathDst.c_str()); - if (rename(fullPathSrc.c_str(), fullPathDst.c_str()) == 0) { - if (needsLogging) { - #if !USING_FSTREAM_DIRECTIVE - if (logSrcFile) fprintf(logSrcFile, "%s\n", fullPathSrc.c_str()), fflush(logSrcFile); - if (logDestFile) fprintf(logDestFile, "%s\n", fullPathDst.c_str()), fflush(logDestFile); - #else - if (logSrcFile && logSrcFile->is_open()) { *logSrcFile << fullPathSrc << '\n'; logSrcFile->flush(); } - if (logDestFile && logDestFile->is_open()) { *logDestFile << fullPathDst << '\n'; logDestFile->flush(); } - #endif - } - } else { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) logMessage("Failed to move: " + fullPathSrc); - #endif - } - } - } - closedir(dir); - } - - #if !USING_FSTREAM_DIRECTIVE - if (logSrcFile) fclose(logSrcFile); - if (logDestFile) fclose(logDestFile); - #else - if (logSrcFile) { logSrcFile->flush(); logSrcFile->close(); } - if (logDestFile) { logDestFile->flush(); logDestFile->close(); } - #endif - - // Clean up directories - 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 - } - } - - // Safely reverse logs now - if (needsLogging) { - if (!logSource.empty()) reverseLogFile(logSource); - if (!logDestination.empty()) reverseLogFile(logDestination); - } - } - - - bool moveFile(const std::string& sourcePath, - const std::string& destinationPath, - const std::string& logSource, - const std::string& logDestination) { - if (!isFileOrDirectory(sourcePath)) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Source file doesn't exist or is not a regular file: " + sourcePath); - #endif - return false; - } - - std::string finalDestPath; - bool moveSuccess = false; - - if (destinationPath.back() == '/') { - // Destination is a directory - construct full destination path - if (!isDirectory(destinationPath)) { - createDirectory(destinationPath); - } - - finalDestPath = destinationPath + getFileName(sourcePath); - remove(finalDestPath.c_str()); - - if (rename(sourcePath.c_str(), finalDestPath.c_str()) == 0) { - moveSuccess = true; - } else { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Failed to move file to directory: " + sourcePath); - #endif - } - } else { - // Destination is a file path - directly rename the file - finalDestPath = destinationPath; - remove(finalDestPath.c_str()); - createDirectory(getParentDirFromPath(finalDestPath)); - - if (rename(sourcePath.c_str(), finalDestPath.c_str()) == 0) { - moveSuccess = true; - } else { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) { - logMessage("Failed to move file: " + sourcePath + " -> " + finalDestPath); - logMessage("Error: " + std::string(strerror(errno))); - } - #endif - } - } - - // Only write to log files if the move was successful - // This is the key optimization - logs are only opened when actually needed! - if (moveSuccess) { - #if !USING_FSTREAM_DIRECTIVE - if (!logSource.empty()) { - createDirectory(getParentDirFromPath(logSource)); - if (FILE* logFile = fopen(logSource.c_str(), "a")) { - writeLog(logFile, sourcePath); - fclose(logFile); - } - #if USING_LOGGING_DIRECTIVE - else { - if (!disableLogging) - logMessage("Failed to open source log file: " + logSource); - } - #endif - } - - if (!logDestination.empty()) { - createDirectory(getParentDirFromPath(logDestination)); - if (FILE* logFile = fopen(logDestination.c_str(), "a")) { - writeLog(logFile, finalDestPath); - fclose(logFile); - } - #if USING_LOGGING_DIRECTIVE - else { - if (!disableLogging) - logMessage("Failed to open destination log file: " + logDestination); - } - #endif - } - #else - if (!logSource.empty()) { - createDirectory(getParentDirFromPath(logSource)); - std::ofstream logSourceFile(logSource, std::ios::app); - if (logSourceFile.is_open()) { - writeLog(logSourceFile, sourcePath); - logSourceFile.close(); - } - #if USING_LOGGING_DIRECTIVE - else { - if (!disableLogging) - logMessage("Failed to open source log file: " + logSource); - } - #endif - } - - if (!logDestination.empty()) { - createDirectory(getParentDirFromPath(logDestination)); - std::ofstream logDestFile(logDestination, std::ios::app); - if (logDestFile.is_open()) { - writeLog(logDestFile, finalDestPath); - logDestFile.close(); - } - #if USING_LOGGING_DIRECTIVE - else { - if (!disableLogging) - logMessage("Failed to open destination log file: " + logDestination); - } - #endif - } - #endif - } - - return moveSuccess; - } - - /** - * @brief Moves a file or directory to a new destination. - * - * This function moves a file or directory from the `sourcePath` to the `destinationPath`. It can handle both - * files and directories and ensures that the destination directory exists before moving. - * - * @param sourcePath The path of the source file or directory. - * @param destinationPath The path of the destination where the file or directory will be moved. - */ - void moveFileOrDirectory(const std::string& sourcePath, const std::string& destinationPath, - const std::string& logSource, const std::string& logDestination) { - if (sourcePath.back() == '/' && destinationPath.back() == '/') { - moveDirectory(sourcePath, destinationPath, logSource, logDestination); - } else { - moveFile(sourcePath, destinationPath, logSource, logDestination); - } - } - - - /** - * @brief Moves files or directories matching a specified pattern to a destination directory. - * - * This function identifies files or directories that match the `sourcePathPattern` and moves them to the `destinationPath`. - * It processes each matching entry in the source directory pattern and moves them to the specified destination. - * - * @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) { - - 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, destinationPath, 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, fixedDestinationPath, logSource, logDestination); - } - sourceFileOrDirectory = ""; - } - //logMessage("post loop"); - - fileList.clear(); - fileList.shrink_to_fit(); - } - - /** - * @brief Copies a single file from the source path to the destination path. - * - * This function copies a single file specified by `fromFile` to the location specified by `toFile`. - * - * @param fromFile The path of the source file to be copied. - * @param toFile The path of the destination where the file will be copied. - */ - void copySingleFile(const std::string& fromFile, const std::string& toFile, long long& totalBytesCopied, - const long long totalSize, const std::string& logSource, const std::string& logDestination) { - static constexpr size_t maxRetries = 10; - const size_t bufferSize = COPY_BUFFER_SIZE; - - // Create destination directory once - createDirectory(getParentDirFromPath(toFile)); - - // Use heap allocation for the buffer to avoid stack overflow with large buffer sizes - std::unique_ptr buffer(new char[bufferSize]); - - #if !USING_FSTREAM_DIRECTIVE - FILE* srcFile = nullptr; - FILE* destFile = nullptr; - - // Retry loop for file opening - for (size_t retryCount = 0; retryCount <= maxRetries; ++retryCount) { - srcFile = fopen(fromFile.c_str(), "rb"); - if (!srcFile) { - if (retryCount == maxRetries) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Failed to open source file after " + std::to_string(maxRetries) + " retries"); - #endif - return; - } - continue; - } - - destFile = fopen(toFile.c_str(), "wb"); - if (!destFile) { - fclose(srcFile); - if (retryCount == maxRetries) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Failed to open destination file after " + std::to_string(maxRetries) + " retries"); - #endif - return; - } - continue; - } - - break; // Both files opened successfully - } - - // RAII cleanup - FileGuard srcGuard(srcFile); - FileGuard destGuard(destFile); - - // Main copy loop - optimized for performance - size_t bytesRead; - char* bufferPtr = buffer.get(); - size_t remainingBytes, written; - while ((bytesRead = fread(bufferPtr, 1, bufferSize, srcFile)) > 0) { - if (abortFileOp.load(std::memory_order_acquire)) { - remove(toFile.c_str()); - copyPercentage.store(-1, std::memory_order_release); - return; - } - - // Write all bytes - handle partial writes - char* writePtr = bufferPtr; - remainingBytes = bytesRead; - - while (remainingBytes > 0) { - written = fwrite(writePtr, 1, remainingBytes, destFile); - if (written == 0) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error writing to destination file"); - #endif - remove(toFile.c_str()); - copyPercentage.store(-1, std::memory_order_release); - return; - } - writePtr += written; - remainingBytes -= written; - } - - totalBytesCopied += bytesRead; - if (totalSize > 0) { - copyPercentage.store(static_cast(100 * totalBytesCopied / totalSize), std::memory_order_release); - } - } - - // Check for read errors - if (ferror(srcFile)) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error reading from source file"); - #endif - remove(toFile.c_str()); - copyPercentage.store(-1, std::memory_order_release); - return; - } - - #else - std::ifstream srcFile; - std::ofstream destFile; - - // Retry loop for file opening - for (size_t retryCount = 0; retryCount <= maxRetries; ++retryCount) { - srcFile.open(fromFile, std::ios::binary); - destFile.open(toFile, std::ios::binary); - - if (srcFile.is_open() && destFile.is_open()) { - break; - } - - srcFile.close(); - destFile.close(); - - if (retryCount == maxRetries) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Failed to open files after " + std::to_string(maxRetries) + " retries"); - #endif - return; - } - } - - // Main copy loop - char* bufferPtr = buffer.get(); - while (srcFile.read(bufferPtr, bufferSize) || srcFile.gcount() > 0) { - if (abortFileOp.load(std::memory_order_acquire)) { - srcFile.close(); - destFile.close(); - remove(toFile.c_str()); - copyPercentage.store(-1, std::memory_order_release); - return; - } - - std::streamsize bytesToWrite = srcFile.gcount(); - destFile.write(bufferPtr, bytesToWrite); - - if (!destFile.good()) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error writing to destination file"); - #endif - srcFile.close(); - destFile.close(); - remove(toFile.c_str()); - copyPercentage.store(-1, std::memory_order_release); - return; - } - - totalBytesCopied += bytesToWrite; - if (totalSize > 0) { - copyPercentage.store(static_cast(100 * totalBytesCopied / totalSize), std::memory_order_release); - } - } - - srcFile.close(); - destFile.close(); - #endif - - // Only open and write to log files if they're needed - this is the key optimization! - if (!logSource.empty()) { - createDirectory(getParentDirFromPath(logSource)); - if (FILE* logFile = fopen(logSource.c_str(), "a")) { - writeLog(logFile, fromFile); - fclose(logFile); - } - #if USING_LOGGING_DIRECTIVE - else { - if (!disableLogging) - logMessage("Failed to open source log file: " + logSource); - } - #endif - } - - if (!logDestination.empty()) { - createDirectory(getParentDirFromPath(logDestination)); - if (FILE* logFile = fopen(logDestination.c_str(), "a")) { - writeLog(logFile, toFile); - fclose(logFile); - } - #if USING_LOGGING_DIRECTIVE - else { - if (!disableLogging) - logMessage("Failed to open destination log file: " + logDestination); - } - #endif - } - } - - - /** - * Recursively calculates the total size of the given file or directory. - * @param path The path to the file or directory. - * @return The total size in bytes of all files within the directory or the size of a file. - */ - long long getTotalSize(const std::string& path) { - struct stat statbuf; - if (lstat(path.c_str(), &statbuf) != 0) { - return 0; // Cannot stat file - } - - if (S_ISREG(statbuf.st_mode)) { - return statbuf.st_size; - } - - if (S_ISDIR(statbuf.st_mode)) { - long long totalSize = 0; - 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) { - 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 = ""; - } - - fileList.clear(); - fileList.shrink_to_fit(); - //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) { - fileList = getFilesListFromDirectory(sourcePath); - std::string updatedPath; - long long totalSize = 0; - long long totalBytesCopied = 0; - - if (mode == "copy") { - // Calculate total size for progress tracking - for (const auto& path : fileList) { - if (path != targetPath + path.substr(sourcePath.size())) { - totalSize += getTotalSize(path); - } - } - } - - for (auto& path : fileList) { - // Generate the corresponding path in the target directory by replacing the source path - updatedPath = targetPath + path.substr(sourcePath.size()); - //logMessage("mirror-delete: "+path+" "+updatedPath); - if (mode == "delete") - deleteFileOrDirectory(updatedPath); - else if (mode == "copy") { - if (path != updatedPath) - copyFileOrDirectory(path, updatedPath, &totalBytesCopied, totalSize); - } - path = ""; - } - //fileList.clear(); - fileList.clear(); - fileList.shrink_to_fit(); - } - - /** - * @brief For each match of the wildcard pattern, creates an empty text file - * named basename.txt inside the output directory. - * Uses FILE* if !USING_FSTREAM_DIRECTIVE is defined, otherwise uses std::ofstream. - * - * @param wildcardPattern A path with a wildcard, such as /some/path/[*]. - * Each match results in a file named after the basename. - * @param outputDir Directory where the output files will be written. - * Created if it doesn't already exist. - */ - void createFlagFiles(const std::string& wildcardPattern, const std::string& outputDir) { - // 1) Gather all matches from the wildcard pattern - fileList = ult::getFilesListByWildcards(wildcardPattern); - if (fileList.empty()) { - return; // No matches, nothing to do - } - - // 2) Ensure the output directory exists - createDirectory(outputDir); - - // 3) Generate empty .txt files for each matched path - std::string outputPrefix = outputDir; - if (!outputPrefix.empty() && outputPrefix.back() != '/') - outputPrefix.push_back('/'); - - std::string baseName, outFile; - for (auto& fullPath : fileList) { - baseName = ult::getNameFromPath(fullPath); - if (baseName.empty()) { - fullPath = ""; - continue; - } - - outFile = outputPrefix + baseName; - - #if !USING_FSTREAM_DIRECTIVE - FileGuard fp(std::fopen(outFile.c_str(), "wb")); - // File automatically closed by FileGuard destructor - #else - std::ofstream ofs(outFile, std::ios::binary | std::ios::trunc); - ofs.close(); - #endif - fullPath = ""; - } - fileList.clear(); - fileList.shrink_to_fit(); - } - - /** - * @brief Removes all files starting with "._" from a directory and its subdirectories. - * - * This function recursively scans the specified directory and removes all files - * whose names start with "._" (commonly macOS metadata files). It processes - * all subdirectories recursively. - * - * @param sourcePath The path of the directory to clean. - */ - void dotCleanDirectory(const std::string& sourcePath) { - DIR* 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 deleted file mode 100644 index 3788eb23..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/string_funcs.cpp +++ /dev/null @@ -1,636 +0,0 @@ -/******************************************************************************** - * File: string_funcs.cpp - * Author: ppkantorski - * Description: - * This source file provides implementations for the string manipulation - * functions declared in string_funcs.hpp. These utility functions support - * operations such as trimming whitespace, removing quotes, normalizing - * slashes, and performing other string cleanup tasks used throughout - * the Ultrahand Overlay project. - * - * For the latest updates and contributions, visit the project's GitHub repository. - * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) - * - * Note: Please be aware that this notice cannot be altered or removed. It is a part - * of the project's documentation and must remain intact. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 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); - } - - - //bool canConvertToInt(const std::string& str) { - // if (str.empty()) { - // return false; - // } - // - // size_t start = 0; - // if (str[0] == '-' || str[0] == '+') { - // if (str.length() == 1) return false; - // start = 1; - // } - // - // for (size_t i = start; i < str.length(); ++i) { - // if (!std::isdigit(static_cast(str[i]))) { - // return false; - // } - // } - // - // return true; - //} - - - // Mimics std::getline() with a delimiter - bool StringStream::getline(std::string& output, char delimiter) { - if (position >= data.size()) { - return false; - } - - const size_t nextPos = data.find(delimiter, position); - - if (nextPos != std::string::npos) { - output.assign(data, position, nextPos - position); // No temporary string creation - position = nextPos + 1; - } else { - output.assign(data, position, data.size() - position); // No temporary string creation - position = data.size(); - } - - return true; - } - - // Mimics operator >> to split by whitespace - StringStream& StringStream::operator>>(std::string& output) { - // Skip leading whitespace - while (position < data.size() && std::isspace(data[position])) { - ++position; - } - - if (position >= data.size()) { - output.clear(); - validState = false; - return *this; - } - - size_t nextPos = position; - while (nextPos < data.size() && !std::isspace(data[nextPos])) { - ++nextPos; - } - - output.assign(data, position, nextPos - position); // Replace substr() with assign() - position = nextPos; - - validState = true; - return *this; - } - - // Overload << operator for std::string - StringStream& StringStream::operator<<(const std::string& input) { - data += input; - return *this; - } - - // Overload << operator for const char* - StringStream& StringStream::operator<<(const char* input) { - data += input; - return *this; - } - - // Overload << operator for char - StringStream& StringStream::operator<<(char input) { - data += input; - return *this; - } - - // Overload << operator for int (handles hex mode) - StringStream& StringStream::operator<<(int input) { - if (hexMode) { - char buffer[20]; // Buffer large enough for hex conversion - sprintf(buffer, "%x", input); // Convert integer to hex string - data += buffer; - } else { - data += ult::to_string(input); - } - return *this; - } - - // Define the new overload for long long - StringStream& StringStream::operator<<(long long input) { - data += std::to_string(input); - return *this; - } - - // Return the current buffer content - std::string StringStream::str() const { - return data; - } - - - - /** - * @brief Trims leading and trailing whitespaces from a string. - * - * This function removes leading and trailing whitespaces, tabs, newlines, carriage returns, form feeds, - * and vertical tabs from the input string. - * - * @param str The input string to trim. - * @return The trimmed string. - */ - void trim(std::string& str) { - const size_t first = str.find_first_not_of(" \t\n\r\f\v"); - if (first == std::string::npos) { - str.clear(); // Fix: clear all-whitespace strings - return; - } - - const size_t last = str.find_last_not_of(" \t\n\r\f\v"); - - // True in-place modification - no temporary string creation - if (last + 1 < str.length()) { - str.erase(last + 1); // Remove trailing whitespace - } - if (first > 0) { - str.erase(0, first); // Remove leading whitespace - } - } - - - // Function to trim newline characters from the end of a string - void trimNewline(std::string& str) { - const size_t end = str.find_last_not_of("\n"); - if (end == std::string::npos) { - str.clear(); // If the string consists entirely of newlines, clear it - } else { - str.erase(end + 1); // Remove all characters after the last non-newline character - } - } - - - /** - * @brief Removes all white spaces from a string. - * - * This function removes all white spaces, including spaces, tabs, newlines, carriage returns, form feeds, - * and vertical tabs from the input string. - * - * @param str The input string to remove white spaces from. - * @return The string with white spaces removed. - */ - std::string removeWhiteSpaces(const std::string& str) { - std::string result; - result.reserve(str.size()); // Reserve space for the result to avoid reallocations - - std::remove_copy_if(str.begin(), str.end(), std::back_inserter(result), [](unsigned char c) { - return std::isspace(c); - }); - - return result; - } - - - - /** - * @brief Removes quotes from a string. - * - * This function removes single and double quotes from the beginning and end of the input string. - * - * @param str The input string to remove quotes from. - * @return The string with quotes removed. - */ - void removeQuotes(std::string& str) { - 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); - - if (path.empty()) - return; - - // In-place multiple slash removal - size_t writePos = 0; - bool previousSlash = false; - - for (size_t i = 0, len = path.length(); i < len; ++i) { - const char c = path[i]; - if (c == '/') { - if (!previousSlash) { - path[writePos++] = '/'; - previousSlash = true; - } - } else { - path[writePos++] = c; - previousSlash = false; - } - } - path.resize(writePos); - - // Handle "./" replacement if present - if (!packagePath.empty() && path.length() >= 2 && path[0] == '.' && path[1] == '/') { - path.replace(0, 2, packagePath); - } - - // Handle "../" sequences - size_t dotDotPos; - size_t searchEnd; - while ((dotDotPos = path.find("../")) != std::string::npos) { - // Check if there's a trailing slash before "../" - searchEnd = dotDotPos; - if (searchEnd > 0 && path[searchEnd - 1] == '/') { - --searchEnd; - } - - // Find the previous slash - const size_t lastSlash = (searchEnd > 0) ? path.rfind('/', searchEnd - 1) : std::string::npos; - - if (lastSlash != std::string::npos) { - // Erase from after lastSlash to after "../" - path.erase(lastSlash + 1, dotDotPos + 3 - lastSlash - 1); - } else { - // No slash found, replace with root - path.erase(0, dotDotPos); - path.insert(0, "/"); - } - } - - // Check for sdmc: prefix - if (path.length() < 5 || - path[0] != 's' || path[1] != 'd' || path[2] != 'm' || path[3] != 'c' || path[4] != ':') { - path.insert(0, "sdmc:"); - } - } - - - /** - * @brief Preprocesses a URL string by adding "https://" prefix. - * - * This function preprocesses a URL string by adding the "https://" prefix if not already present. - * - * @param path The input URL string to preprocess, passed by reference and modified in-place. - */ - void preprocessUrl(std::string& path) { - removeQuotes(path); - - if (path.size() >= 7 && path[0] == 'h' && path[1] == 't' && - path[2] == 't' && path[3] == 'p') { - if ((path.size() >= 8 && path[4] == 's' && path[5] == ':') || - (path[4] == ':')) { - return; - } - } - - path.insert(0, "https://"); - } - - /** - * @brief Drops the file extension from a filename. - * - * This function removes the file extension (characters after the last dot) from the input filename string. - * - * @param filename The input filename from which to drop the extension, passed by reference and modified in-place. - */ - void dropExtension(std::string& filename) { - const size_t lastDotPos = filename.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()) { - return false; - } - - size_t start = 0; - if (str[0] == '-' || str[0] == '+') { - if (str.length() == 1) return false; - start = 1; - } - - for (size_t i = start; i < str.length(); ++i) { - if (!std::isdigit(static_cast(str[i]))) { - return false; - } - } - - return true; - } - - std::string returnOrNull(const std::string& value) { - return value.empty() ? NULL_STR : value; - } - - - // Function to slice a string from start to end index - std::string sliceString(const std::string& str, size_t start, size_t end) { - if (start < 0) start = 0; - if (end > static_cast(str.length())) end = str.length(); - if (start > end) start = end; - return str.substr(start, end - start); - } - - - - //std::string addQuotesIfNeeded(const std::string& str) { - // if (str.find(' ') != std::string::npos) { - // return "\"" + str + "\""; - // } - // return str; - //} - - - /** - * @brief Converts a string to lowercase. - * - * This function takes a string as input and returns a lowercase version of that string. - * - * @param str The input string to convert to lowercase. - * @return The lowercase version of the input string. - */ - - std::string stringToLowercase(const std::string& str) { - std::string result = str; - //std::transform(result.begin(), result.end(), result.begin(), - // [](unsigned char c) { return std::tolower(c); }); - //return result; - for (char& c : result) { - if (c >= 'A' && c <= 'Z') { - c += 32; - } - } - return result; - } - - /** - * @brief Converts a string to uppercase. - * - * This function takes a string as input and returns an uppercase version of that string. - * - * @param str The input string to convert to uppercase. - * @return The uppercase version of the input string. - */ - - std::string stringToUppercase(const std::string& str) { - std::string result = str; - for (char& c : result) { - if (c >= 'a' && c <= 'z') { - c -= 32; - } - } - return result; - } - - - - /** - * @brief Formats a priority string to a desired width. - * - * This function takes a priority string and formats it to a specified desired width by padding with '0's if it's shorter - * or truncating with '9's if it's longer. - * - * @param priority The input priority string to format. - * @param desiredWidth The desired width of the formatted string (default is 4). - * @return A formatted priority string. - */ - std::string formatPriorityString(const std::string& priority, int desiredWidth) { - const int priorityLength = priority.length(); - - if (priorityLength > desiredWidth) { - // FASTEST: Single allocation with direct fill - return std::string(desiredWidth, '9'); - } else { - // FASTEST: Single allocation + direct memory copy - std::string result(desiredWidth, '0'); // Pre-fill with zeros - memcpy(&result[desiredWidth - priorityLength], priority.data(), priorityLength); - return result; - } - } - - - - /** - * @brief Removes the part of the string after the first occurrence of '?' character. - * - * This function takes a string and removes the portion of the string that appears after - * the first '?' character, if found. If no '?' character is present, the string remains unchanged. - * - * @param input The input string from which to remove the tag, passed by reference and modified in-place. - */ - void removeTag(std::string &input) { - const 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 deleted file mode 100644 index 3518d190..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/tsl_utils.cpp +++ /dev/null @@ -1,1855 +0,0 @@ -/******************************************************************************** - * File: tsl_utils.cpp - * Author: ppkantorski - * Description: - * 'tsl_utils.cpp' provides the implementation of various utility functions - * defined in 'tsl_utils.hpp' for the Ultrahand Overlay project. This source file - * includes functionality for system checks, input handling, time-based interpolation, - * and other application-specific features essential for operating custom overlays - * on the Nintendo Switch. - * - * For the latest updates and contributions, visit the project's GitHub repository: - * GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay - * - * Note: This notice is integral to the project's documentation and must not be - * altered or removed. - * - * Licensed under both GPLv2 and CC-BY-4.0 - * Copyright (c) 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; - - auto normalizeNewlines = [](std::string &s) { - size_t n = 0; - while ((n = s.find("\\n", n)) != std::string::npos) { - s.replace(n, 2, "\n"); - n += 1; - } - }; - - while ((pos = content.find('"', pos)) != std::string::npos) { - keyStart = pos + 1; - keyEnd = content.find('"', keyStart); - if (keyEnd == std::string::npos) break; - - key = content.substr(keyStart, keyEnd - keyStart); - colonPos = content.find(':', keyEnd); - if (colonPos == std::string::npos) break; - - valueStart = content.find('"', colonPos); - valueEnd = content.find('"', valueStart + 1); - if (valueStart == std::string::npos || valueEnd == std::string::npos) break; - - value = content.substr(valueStart + 1, valueEnd - valueStart - 1); - - // 🔹 Convert escaped newlines (\\n) into real ones - normalizeNewlines(key); - normalizeNewlines(value); - - result[key] = value; - - key.clear(); - value.clear(); - pos = valueEnd + 1; // Move to next pair - } - } - - // Function to parse JSON key-value pairs into a map - bool parseJsonToMap(const std::string& filePath, std::unordered_map& result) { - std::string content; - if (!readFileContent(filePath, content)) { - return false; - } - - parseJsonContent(content, result); - return true; - } - - // Function to load translations from a JSON-like file into the translation cache - bool loadTranslationsFromJSON(const std::string& filePath) { - return parseJsonToMap(filePath, translationCache); - } - - - u16 activeHeaderHeight = 97; - - bool consoleIsDocked() { - Result rc; - 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 getProcessIdAsString() { - // u64 pid = 0; - // if (R_FAILED(pmdmntGetApplicationProcessId(&pid))) - // return NULL_STR; - // - // char pidStr[21]; // Max u64 is 20 digits + null terminator - // snprintf(pidStr, sizeof(pidStr), "%llu", pid); - // return std::string(pidStr); - //} - - std::string getBuildIdAsString() { - u64 pid = 0; - if (R_FAILED(pmdmntGetApplicationProcessId(&pid))) - return NULL_STR; - - Service srv; - if (R_FAILED(smGetService(&srv, "dmnt:cht"))) - return NULL_STR; - - if (R_FAILED(serviceDispatch(&srv, 65003))) { - serviceClose(&srv); - return NULL_STR; - } - - struct { - u64 process_id; - u64 title_id; - struct { u64 base; u64 size; } main_nso_extents; - struct { u64 base; u64 size; } heap_extents; - struct { u64 base; u64 size; } alias_extents; - struct { u64 base; u64 size; } address_space_extents; - u8 main_nso_build_id[0x20]; - } metadata; - - Result rc = serviceDispatchOut(&srv, 65002, metadata); - serviceClose(&srv); - - if (R_FAILED(rc)) - return NULL_STR; - - u64 buildid; - std::memcpy(&buildid, metadata.main_nso_build_id, sizeof(u64)); - - char buildIdStr[17]; - snprintf(buildIdStr, sizeof(buildIdStr), "%016lX", __builtin_bswap64(buildid)); - return std::string(buildIdStr); - } - - - std::string getTitleIdAsString() { - u64 pid = 0, tid = 0; - if (R_FAILED(pmdmntGetApplicationProcessId(&pid)) || - R_FAILED(pmdmntGetProgramId(&tid, pid))) - return NULL_STR; - - char tidStr[17]; - snprintf(tidStr, sizeof(tidStr), "%016lX", tid); - return std::string(tidStr); - } - - - std::string lastTitleID; - std::atomic resetForegroundCheck(false); // initialize as true - - - - - std::atomic internalTouchReleased(true); - u32 layerEdge = 0; - bool useRightAlignment = false; - bool useSwipeToOpen = true; - bool useLaunchCombos = true; - bool useNotifications = true; - bool useSoundEffects = true; - bool useHapticFeedback = false; - bool usePageSwap = false; - bool useDynamicLogo = true; - bool useSelectionBG = true; - bool useSelectionText = true; - bool useSelectionValue = false; - - std::atomic noClickableItems{false}; - - #if IS_LAUNCHER_DIRECTIVE - std::atomic overlayLaunchRequested{false}; - std::string requestedOverlayPath; - std::string requestedOverlayArgs; - std::mutex overlayLaunchMutex; - #endif - - // Define the duration boundaries (for smooth scrolling) - //const std::chrono::milliseconds initialInterval = std::chrono::milliseconds(67); // Example initial interval - //const std::chrono::milliseconds shortInterval = std::chrono::milliseconds(10); // Short interval after long hold - //const std::chrono::milliseconds transitionPoint = std::chrono::milliseconds(2000); // Point at which the shortest interval is reached - - // Function to interpolate between two durations - //std::chrono::milliseconds interpolateDuration(std::chrono::milliseconds start, std::chrono::milliseconds end, float t) { - // using namespace std::chrono; - // auto interpolated = start.count() + static_cast((end.count() - start.count()) * t); - // return milliseconds(interpolated); - //} - - - - //#include // Comment out filesystem - - // CUSTOM SECTION START - //float backWidth, selectWidth, nextPageWidth; - std::atomic backWidth; - std::atomic selectWidth; - std::atomic nextPageWidth; - std::atomic inMainMenu{false}; - std::atomic inOverlaysPage{false}; - std::atomic inPackagesPage{false}; - - bool firstBoot = true; // for detecting first boot - - //std::unordered_map hexSumCache; - - // Define an atomic bool for interpreter completion - std::atomic threadFailure(false); - std::atomic runningInterpreter(false); - std::atomic shakingProgress(true); - - std::atomic isHidden(false); - std::atomic externalAbortCommands(false); - - //bool progressAnimation = false; - bool disableTransparency = false; - //bool useCustomWallpaper = false; - bool useMemoryExpansion = false; - bool useOpaqueScreenshots = false; - - std::atomic onTrackBar(false); - std::atomic allowSlide(false); - std::atomic unlockedSlide(false); - - - - void atomicToggle(std::atomic& b) { - bool expected = b.load(std::memory_order_relaxed); - for (;;) { - const bool desired = !expected; - if (b.compare_exchange_weak(expected, desired, - std::memory_order_acq_rel, - std::memory_order_relaxed)) { - break; // success - } - // expected has been updated with the current value on failure; loop continues - } - } - - - bool updateMenuCombos = false; - - - //void convertComboToUnicode(std::string& combo); - - - std::array KEYS_INFO = {{ - { HidNpadButton_L, "L", "\uE0E4" }, { HidNpadButton_R, "R", "\uE0E5" }, - { HidNpadButton_ZL, "ZL", "\uE0E6" }, { HidNpadButton_ZR, "ZR", "\uE0E7" }, - { HidNpadButton_AnySL, "SL", "\uE0E8" }, { HidNpadButton_AnySR, "SR", "\uE0E9" }, - { HidNpadButton_Left, "DLEFT", "\uE0ED" }, { HidNpadButton_Up, "DUP", "\uE0EB" }, - { HidNpadButton_Right, "DRIGHT", "\uE0EE" }, { HidNpadButton_Down, "DDOWN", "\uE0EC" }, - { HidNpadButton_A, "A", "\uE0E0" }, { HidNpadButton_B, "B", "\uE0E1" }, - { HidNpadButton_X, "X", "\uE0E2" }, { HidNpadButton_Y, "Y", "\uE0E3" }, - { HidNpadButton_StickL, "LS", "\uE08A" }, { HidNpadButton_StickR, "RS", "\uE08B" }, - { HidNpadButton_Minus, "MINUS", "\uE0B6" }, { HidNpadButton_Plus, "PLUS", "\uE0B5" } - }}; - - std::unordered_map createButtonCharMap() { - std::unordered_map map; - for (const auto& keyInfo : KEYS_INFO) { - map[keyInfo.name] = keyInfo.glyph; - } - return map; - } - - std::unordered_map buttonCharMap = createButtonCharMap(); - - - void convertComboToUnicode(std::string& combo) { - // Quick check to see if the string contains a '+' - if (combo.find('+') == std::string::npos) { - return; // No '+' found, nothing to modify - } - - // Exit early if the combo contains any spaces - if (combo.find(' ') != std::string::npos) { - return; // Spaces found, return without modifying - } - - std::string unicodeCombo; - bool modified = false; - size_t start = 0; - const size_t length = combo.length(); - size_t end = 0; // Moved outside the loop - std::string token; // Moved outside the loop - auto it = buttonCharMap.end(); // Initialize iterator once outside the loop - - // Iterate through the combo string and split by '+' - for (size_t i = 0; i <= length; ++i) { - if (i == length || combo[i] == '+') { - // Get the current token (trimmed) - end = i; // Reuse the end variable - while (start < end && std::isspace(combo[start])) start++; // Trim leading spaces - while (end > start && std::isspace(combo[end - 1])) end--; // Trim trailing spaces - - token = combo.substr(start, end - start); // Reuse the token variable - it = buttonCharMap.find(token); // Reuse the iterator - - if (it != buttonCharMap.end()) { - unicodeCombo += it->second; // Append the mapped Unicode value - modified = true; - } else { - unicodeCombo += token; // Append the original token if not found - } - - if (i != length) { - unicodeCombo += "+"; // Only append '+' if we're not at the end - } - - start = i + 1; // Move to the next token - } - } - - // If a modification was made, update the original combo - if (modified) { - combo = unicodeCombo; - } - } - - - CONSTEXPR_STRING std::string whiteColor = "FFFFFF"; - CONSTEXPR_STRING std::string blackColor = "000000"; - CONSTEXPR_STRING std::string greyColor = "AAAAAA"; - - std::atomic languageWasChanged{false}; - - #if IS_LAUNCHER_DIRECTIVE - std::string ENGLISH = "English"; - std::string SPANISH = "Spanish"; - std::string FRENCH = "French"; - std::string GERMAN = "German"; - std::string JAPANESE = "Japanese"; - std::string KOREAN = "Korean"; - std::string ITALIAN = "Italian"; - std::string DUTCH = "Dutch"; - std::string PORTUGUESE = "Portuguese"; - std::string RUSSIAN = "Russian"; - std::string UKRAINIAN = "Ukrainian"; - std::string POLISH = "Polish"; - std::string SIMPLIFIED_CHINESE = "Simplified Chinese"; - std::string TRADITIONAL_CHINESE = "Traditional Chinese"; - std::string OVERLAYS = "Overlays"; //defined in libTesla now - std::string OVERLAYS_ABBR = "Overlays"; - std::string OVERLAY = "Overlay"; - std::string HIDDEN_OVERLAYS = "Hidden Overlays"; - std::string PACKAGES = "Packages"; //defined in libTesla now - std::string PACKAGE = "Package"; - std::string HIDDEN_PACKAGES = "Hidden Packages"; - std::string HIDDEN = "Hidden"; - std::string HIDE_OVERLAY = "Hide Overlay"; - std::string HIDE_PACKAGE = "Hide Package"; - std::string LAUNCH_ARGUMENTS = "Launch Arguments"; - std::string 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 SOUND_EFFECTS = "Sound Effects"; - std::string HAPTIC_FEEDBACK = "Haptic Feedback"; - std::string OPAQUE_SCREENSHOTS = "Opaque Screenshots"; - - std::string PACKAGE_INFO = "Package Info"; - std::string _TITLE = "Title"; - std::string _VERSION= "Version"; - std::string _CREATOR = "Creator(s)"; - std::string _ABOUT = "About"; - std::string _CREDITS = "Credits"; - - std::string USERGUIDE_OFFSET = "177"; - std::string SETTINGS_MENU = "Settings Menu"; - std::string SCRIPT_OVERLAY = "Script Overlay"; - std::string STAR_FAVORITE = "Star/Favorite"; - std::string APP_SETTINGS = "App Settings"; - std::string ON_MAIN_MENU = "on Main Menu"; - std::string ON_A_COMMAND = "on a command"; - std::string ON_OVERLAY_PACKAGE = "on overlay/package"; - std::string FEATURES = "Features"; - std::string SWIPE_TO_OPEN = "Swipe to Open"; - - std::string THEME_SETTINGS = "Theme Settings"; - std::string DYNAMIC_LOGO = "Dynamic Logo"; - std::string SELECTION_BACKGROUND = "Selection Background"; - std::string SELECTION_TEXT = "Selection Text"; - std::string SELECTION_VALUE = "Selection Value"; - std::string LIBULTRAHAND_TITLES = "libultrahand Titles"; - std::string LIBULTRAHAND_VERSIONS = "libultrahand Versions"; - std::string PACKAGE_TITLES = "Package Titles"; - - std::string ULTRAHAND_HAS_STARTED = "Ultrahand has started."; - std::string NEW_UPDATE_IS_AVAILABLE = "New update is available!"; - std::string REBOOT_IS_REQUIRED = "Reboot is required."; - std::string HOLD_A_TO_DELETE = "Hold \uE0E0 to Delete"; - std::string 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"; - SOUND_EFFECTS = "Sound Effects"; - HAPTIC_FEEDBACK = "Haptic Feedback"; - OPAQUE_SCREENSHOTS = "Opaque Screenshots"; - ON = "On"; - OFF = "Off"; - PACKAGE_INFO = "Package Info"; - _TITLE = "Title"; - _VERSION= "Version"; - _CREATOR = "Creator(s)"; - _ABOUT = "About"; - _CREDITS = "Credits"; - OK = "OK"; - BACK = "Back"; - HIDE = "Hide"; - CANCEL = "Cancel"; - - REBOOT_TO = "Reboot To"; - REBOOT = "Reboot"; - SHUTDOWN = "Shutdown"; - BOOT_ENTRY = "Boot Entry"; - GAP_1 = " "; - GAP_2 = " "; - - USERGUIDE_OFFSET = "177"; - SETTINGS_MENU = "Settings Menu"; - SCRIPT_OVERLAY = "Script Overlay"; - STAR_FAVORITE = "Star/Favorite"; - APP_SETTINGS = "App Settings"; - ON_MAIN_MENU = "on Main Menu"; - ON_A_COMMAND = "on a command"; - ON_OVERLAY_PACKAGE = "on overlay/package"; - FEATURES = "Features"; - SWIPE_TO_OPEN = "Swipe to Open"; - //PROGRESS_ANIMATION = "Progress Animation"; - - THEME_SETTINGS = "Theme Settings"; - DYNAMIC_LOGO = "Dynamic Logo"; - SELECTION_BACKGROUND = "Selection Background"; - SELECTION_TEXT = "Selection Text"; - SELECTION_VALUE = "Selection Value"; - LIBULTRAHAND_TITLES = "libultrahand Titles"; - LIBULTRAHAND_VERSIONS = "libultrahand Versions"; - PACKAGE_TITLES = "Package Titles"; - //PACKAGE_VERSIONS = "Package Versions"; - - ULTRAHAND_HAS_STARTED = "Ultrahand has started."; - NEW_UPDATE_IS_AVAILABLE = "New update is available!"; - REBOOT_IS_REQUIRED = "Reboot is required."; - HOLD_A_TO_DELETE = "Hold  to Delete"; - 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}, - {"SOUND_EFFECTS", &SOUND_EFFECTS}, - {"HAPTIC_FEEDBACK", &HAPTIC_FEEDBACK}, - {"OPAQUE_SCREENSHOTS", &OPAQUE_SCREENSHOTS}, - - {"PACKAGE_INFO", &PACKAGE_INFO}, - {"TITLE", &_TITLE}, - {"VERSION", &_VERSION}, - {"CREATOR", &_CREATOR}, - {"ABOUT", &_ABOUT}, - {"CREDITS", &_CREDITS}, - - {"USERGUIDE_OFFSET", &USERGUIDE_OFFSET}, - {"SETTINGS_MENU", &SETTINGS_MENU}, - {"SCRIPT_OVERLAY", &SCRIPT_OVERLAY}, - {"STAR_FAVORITE", &STAR_FAVORITE}, - {"APP_SETTINGS", &APP_SETTINGS}, - {"ON_MAIN_MENU", &ON_MAIN_MENU}, - {"ON_A_COMMAND", &ON_A_COMMAND}, - {"ON_OVERLAY_PACKAGE", &ON_OVERLAY_PACKAGE}, - {"FEATURES", &FEATURES}, - {"SWIPE_TO_OPEN", &SWIPE_TO_OPEN}, - - {"THEME_SETTINGS", &THEME_SETTINGS}, - {"DYNAMIC_LOGO", &DYNAMIC_LOGO}, - {"SELECTION_BACKGROUND", &SELECTION_BACKGROUND}, - {"SELECTION_TEXT", &SELECTION_TEXT}, - {"SELECTION_VALUE", &SELECTION_VALUE}, - {"LIBULTRAHAND_TITLES", &LIBULTRAHAND_TITLES}, - {"LIBULTRAHAND_VERSIONS", &LIBULTRAHAND_VERSIONS}, - {"PACKAGE_TITLES", &PACKAGE_TITLES}, - - {"ULTRAHAND_HAS_STARTED", &ULTRAHAND_HAS_STARTED}, - {"NEW_UPDATE_IS_AVAILABLE", &NEW_UPDATE_IS_AVAILABLE}, - {"REBOOT_IS_REQUIRED", &REBOOT_IS_REQUIRED}, - {"HOLD_A_TO_DELETE", &HOLD_A_TO_DELETE}, - {"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}, - {"notification_text_color", whiteColor}, - {"header_text_color", whiteColor}, - {"header_separator_color", whiteColor}, - {"star_color", whiteColor}, - {"selection_star_color", whiteColor}, - {"bottom_button_color", whiteColor}, - {"bottom_text_color", whiteColor}, - {"bottom_separator_color", whiteColor}, - {"top_separator_color", "404040"}, - {"table_bg_color", "2C2C2C"}, - {"table_bg_alpha", "14"}, - {"table_section_text_color", whiteColor}, - //{"table_info_text_color", "00FFDD"}, - {"table_info_text_color", "9ed0ff"}, - {"warning_text_color", "FF7777"}, - {"healthy_ram_text_color", "00FF00"}, - {"neutral_ram_text_color", "FFAA00"}, - {"bad_ram_text_color", "FF0000"}, - {"trackbar_slider_color", "606060"}, - {"trackbar_slider_border_color", "505050"}, - {"trackbar_slider_malleable_color", "A0A0A0"}, - {"trackbar_full_color", "00FFDD"}, - {"trackbar_empty_color", "404040"}, - {"overlay_text_color", whiteColor}, - {"ult_overlay_text_color", "9ed0ff"}, - {"package_text_color", whiteColor}, - {"ult_package_text_color", "9ed0ff"}, - {"banner_version_text_color", greyColor}, - {"overlay_version_text_color", greyColor}, - {"ult_overlay_version_text_color", "00FFDD"}, - {"package_version_text_color", greyColor}, - {"ult_package_version_text_color", "00FFDD"}, - {"on_text_color", "00FFDD"}, - {"off_text_color", greyColor}, - {"invalid_text_color", "FF0000"}, - {"inprogress_text_color", "FFFF45"}, - {"selection_text_color", "9ed0ff"}, - {"selection_value_text_color", "FF7777"}, - {"selection_bg_color", blackColor}, - {"selection_bg_alpha", "11"}, - {"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 refreshWallpaperNow(false); - 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; - // //if (reducedMemory) { - // // // Reuse wallpaperData to avoid double allocation - // // buffer.swap(wallpaperData); - // // buffer.resize(originalDataSize); - // //} else { - // buffer.resize(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; - // //if (reducedMemory) { - // // buffer.swap(wallpaperData); - // // buffer.resize(originalDataSize); - // //} else { - // buffer.resize(originalDataSize); - // //} - // - // file.read(reinterpret_cast(buffer.data()), originalDataSize); - // if (!file) { - // wallpaperData.clear(); - // return; - // } - // #endif - // - // // Compress RGBA8888 to RGBA4444 - // //if (reducedMemory) { - // // // In-place compression to save memory - // // size_t writeIndex = 0; - // // for (size_t i = 0; i < originalDataSize; i += 8, writeIndex += 4) { - // // uint8_t r1 = buffer[i] >> 4; - // // uint8_t g1 = buffer[i + 1] >> 4; - // // uint8_t b1 = buffer[i + 2] >> 4; - // // uint8_t a1 = buffer[i + 3] >> 4; - // // - // // uint8_t r2 = buffer[i + 4] >> 4; - // // uint8_t g2 = buffer[i + 5] >> 4; - // // uint8_t b2 = buffer[i + 6] >> 4; - // // uint8_t a2 = buffer[i + 7] >> 4; - // // - // // buffer[writeIndex] = (r1 << 4) | g1; - // // buffer[writeIndex + 1] = (b1 << 4) | a1; - // // buffer[writeIndex + 2] = (r2 << 4) | g2; - // // buffer[writeIndex + 3] = (b2 << 4) | a2; - // // } - // // buffer.resize(compressedDataSize); - // // wallpaperData.swap(buffer); - // //} else { - // 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) - // // const uint8_t r1 = input[i] >> 4; - // // const uint8_t g1 = input[i + 1] >> 4; - // // const uint8_t b1 = input[i + 2] >> 4; - // // const uint8_t a1 = input[i + 3] >> 4; - // // - // // const uint8_t r2 = input[i + 4] >> 4; - // // const uint8_t g2 = input[i + 5] >> 4; - // // const uint8_t b2 = input[i + 6] >> 4; - // // const uint8_t 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; - // //} - // - // for (size_t i = 0, j = 0; i < originalDataSize; i += 16, j += 8) { - // output[j] = ((input[i] >> 4) << 4) | (input[i + 1] >> 4); - // output[j + 1] = ((input[i + 2] >> 4) << 4) | (input[i + 3] >> 4); - // output[j + 2] = ((input[i + 4] >> 4) << 4) | (input[i + 5] >> 4); - // output[j + 3] = ((input[i + 6] >> 4) << 4) | (input[i + 7] >> 4); - // output[j + 4] = ((input[i + 8] >> 4) << 4) | (input[i + 9] >> 4); - // output[j + 5] = ((input[i + 10] >> 4) << 4) | (input[i + 11] >> 4); - // output[j + 6] = ((input[i + 12] >> 4) << 4) | (input[i + 13] >> 4); - // output[j + 7] = ((input[i + 14] >> 4) << 4) | (input[i + 15] >> 4); - // } - // //} - //} - - - void loadWallpaperFile(const std::string& filePath, s32 width, s32 height) { - const size_t originalDataSize = width * height * 4; - const size_t compressedDataSize = originalDataSize / 2; - - wallpaperData.resize(compressedDataSize); - - if (!isFileOrDirectory(filePath)) { - wallpaperData.clear(); - return; - } - - FILE* file = fopen(filePath.c_str(), "rb"); - if (!file) { - wallpaperData.clear(); - return; - } - - constexpr size_t chunkBytes = 64 * 1024; // 64 KB chunks - uint8_t chunkBuffer[chunkBytes]; - - size_t totalRead = 0; - size_t writeIndex = 0; - - size_t remaining, toRead, bytesRead; - - while (totalRead < originalDataSize) { - // Determine how much to read this iteration - remaining = originalDataSize - totalRead; - toRead = remaining < chunkBytes ? remaining : chunkBytes; - - bytesRead = fread(chunkBuffer, 1, toRead, file); - if (bytesRead == 0 || bytesRead % 8 != 0) { // must be multiple of 2 pixels - fclose(file); - wallpaperData.clear(); - return; - } - - // Compress each 2-pixel group in the chunk - for (size_t i = 0; i < bytesRead; i += 8, writeIndex += 4) { - wallpaperData[writeIndex] = (chunkBuffer[i] & 0xF0) | (chunkBuffer[i + 1] >> 4); - wallpaperData[writeIndex + 1] = (chunkBuffer[i + 2] & 0xF0) | (chunkBuffer[i + 3] >> 4); - wallpaperData[writeIndex + 2] = (chunkBuffer[i + 4] & 0xF0) | (chunkBuffer[i + 5] >> 4); - wallpaperData[writeIndex + 3] = (chunkBuffer[i + 6] & 0xF0) | (chunkBuffer[i + 7] >> 4); - } - - totalRead += bytesRead; - } - - fclose(file); - } - - - void loadWallpaperFileWhenSafe() { - if (expandedMemory && !inPlot.load(std::memory_order_acquire) && !refreshWallpaper.load(std::memory_order_acquire)) { - std::unique_lock lock(wallpaperMutex); - cv.wait(lock, [] { return !inPlot.load(std::memory_order_acquire) && !refreshWallpaper.load(std::memory_order_acquire); }); - if (wallpaperData.empty() && isFileOrDirectory(WALLPAPER_PATH)) { - loadWallpaperFile(WALLPAPER_PATH); - } - } - } - - - void reloadWallpaper() { - // Signal that wallpaper is being refreshed - refreshWallpaper.store(true, std::memory_order_release); - - // Lock the mutex for condition waiting - std::unique_lock lock(wallpaperMutex); - - // Wait for inPlot to be false before reloading the wallpaper - cv.wait(lock, [] { return !inPlot.load(std::memory_order_acquire); }); - - // Clear the current wallpaper data - wallpaperData.clear(); - - // Reload the wallpaper file - if (isFileOrDirectory(WALLPAPER_PATH)) { - loadWallpaperFile(WALLPAPER_PATH); - } - - // Signal that wallpaper has finished refreshing - refreshWallpaper.store(false, std::memory_order_release); - - // Notify any waiting threads - cv.notify_all(); - } - - - - // Global variables for FPS calculation - //double lastTimeCount = 0.0; - //int frameCount = 0; - //float fps = 0.0f; - //double elapsedTime = 0.0; - - std::atomic themeIsInitialized(false); // for loading the theme once in OverlayFrame / HeaderOverlayFrame - - // Variables for touch commands - std::atomic touchingBack(false); - std::atomic touchingSelect(false); - std::atomic touchingNextPage(false); - std::atomic touchingMenu(false); - std::atomic shortTouchAndRelease(false); - std::atomic longTouchAndRelease(false); - std::atomic simulatedBack(false); - //bool simulatedBackComplete = true; - std::atomic simulatedSelect(false); - //bool simulatedSelectComplete = true; - std::atomic simulatedNextPage(false); - //std::atomic simulatedNextPageComplete(true); - std::atomic simulatedMenu(false); - //bool simulatedMenuComplete = true; - std::atomic stillTouching(false); - std::atomic interruptedTouch(false); - std::atomic touchInBounds(false); - - -#if USING_WIDGET_DIRECTIVE - // Battery implementation - bool powerInitialized = false; - bool powerCacheInitialized; - uint32_t powerCacheCharge; - //float powerConsumption; - bool powerCacheIsCharging; - PsmSession powerSession; - - // Define variables to store previous battery charge and time - //uint32_t prevBatteryCharge = 0; - //s64 timeOut = 0; - - - std::atomic batteryCharge{0}; - std::atomic isCharging{false}; - //bool validPower; - - - - bool powerGetDetails(uint32_t *_batteryCharge, bool *_isCharging) { - static uint64_t last_call_ns = 0; - - // Ensure power system is initialized - if (!powerInitialized) { - return false; - } - - // Get the current time in nanoseconds - const uint64_t now_ns = armTicksToNs(armGetSystemTick()); - - // 3 seconds in nanoseconds - static constexpr uint64_t min_delay_ns = 3000000000ULL; - - // Check if enough time has elapsed or if cache is not initialized - const bool useCache = (now_ns - last_call_ns <= min_delay_ns) && powerCacheInitialized; - if (!useCache) { - PsmChargerType charger = PsmChargerType_Unconnected; - Result rc = psmGetBatteryChargePercentage(_batteryCharge); - bool hwReadsSucceeded = R_SUCCEEDED(rc); - - if (hwReadsSucceeded) { - rc = psmGetChargerType(&charger); - hwReadsSucceeded &= R_SUCCEEDED(rc); - *_isCharging = (charger != PsmChargerType_Unconnected); - - if (hwReadsSucceeded) { - // Update cache - powerCacheCharge = *_batteryCharge; - powerCacheIsCharging = *_isCharging; - powerCacheInitialized = true; - last_call_ns = now_ns; // Update last call time after successful hardware read - return true; - } - } - - // Use cached values if the hardware read fails - if (powerCacheInitialized) { - *_batteryCharge = powerCacheCharge; - *_isCharging = powerCacheIsCharging; - return hwReadsSucceeded; // Return false if hardware read failed but cache is valid - } - - // Return false if cache is not initialized and hardware read failed - return false; - } - - // Use cached values if not enough time has passed - *_batteryCharge = powerCacheCharge; - *_isCharging = powerCacheIsCharging; - return true; // Return true as cache is used - } - - - void powerInit(void) { - uint32_t charge = 0; - bool charging = false; - - powerCacheInitialized = false; - powerCacheCharge = 0; - powerCacheIsCharging = false; - - if (!powerInitialized) { - Result rc = psmInitialize(); - if (R_SUCCEEDED(rc)) { - rc = psmBindStateChangeEvent(&powerSession, 1, 1, 1); - - if (R_FAILED(rc)) - psmExit(); - - if (R_SUCCEEDED(rc)) { - powerInitialized = true; - ult::powerGetDetails(&charge, &charging); - ult::batteryCharge.store(charge, std::memory_order_release); - ult::isCharging.store(charging, std::memory_order_release); - //prevBatteryCharge = charge; // if needed - } - } - } - } - - void powerExit(void) { - if (powerInitialized) { - psmUnbindStateChangeEvent(&powerSession); - psmExit(); - powerInitialized = false; - powerCacheInitialized = false; - } - } -#endif - - - // Temperature Implementation - std::atomic PCB_temperature{0.0f}; - std::atomic SOC_temperature{0.0f}; - - /* - I2cReadRegHandler was taken from Switch-OC-Suite source code made by KazushiMe - Original repository link (Deleted, last checked 15.04.2023): https://github.com/KazushiMe/Switch-OC-Suite - */ - - Result I2cReadRegHandler(u8 reg, I2cDevice dev, u16 *out) { - struct readReg { - u8 send; - u8 sendLength; - u8 sendData; - u8 receive; - u8 receiveLength; - }; - - I2cSession _session; - - Result res = i2cOpenSession(&_session, dev); - if (res) - return res; - - u16 val; - - struct readReg readRegister = { - .send = 0 | (I2cTransactionOption_Start << 6), - .sendLength = sizeof(reg), - .sendData = reg, - .receive = 1 | (I2cTransactionOption_All << 6), - .receiveLength = sizeof(val), - }; - - res = i2csessionExecuteCommandList(&_session, &val, sizeof(val), &readRegister, sizeof(readRegister)); - if (res) { - i2csessionClose(&_session); - return res; - } - - *out = val; - i2csessionClose(&_session); - return 0; - } - - - // Common helper function to read temperature (integer and fractional parts) - Result ReadTemperature(float *temperature, u8 integerReg, u8 fractionalReg, bool integerOnly) { - u16 rawValue; - u8 val; - s32 integerPart = 0; - float fractionalPart = 0.0f; // Change this to a float to retain fractional precision - - // Read the integer part of the temperature - Result res = I2cReadRegHandler(integerReg, I2cDevice_Tmp451, &rawValue); - if (R_FAILED(res)) { - return res; // Error during I2C read - } - - val = (u8)rawValue; // Cast the value to an 8-bit unsigned integer - integerPart = val; // Integer part of temperature in Celsius - - if (integerOnly) - { - *temperature = static_cast(integerPart); // Ensure it's treated as a float - return 0; // Return only integer part if requested - } - - // Read the fractional part of the temperature - res = I2cReadRegHandler(fractionalReg, I2cDevice_Tmp451, &rawValue); - if (R_FAILED(res)) { - return res; // Error during I2C read - } - - val = (u8)rawValue; // Cast the value to an 8-bit unsigned integer - fractionalPart = static_cast(val >> 4) * 0.0625f; // Convert upper 4 bits into fractional part - - // Combine integer and fractional parts - *temperature = static_cast(integerPart) + fractionalPart; - - return 0; - } - - // Function to get the SOC temperature - Result ReadSocTemperature(float *temperature, bool integerOnly) { - return ReadTemperature(temperature, TMP451_SOC_TEMP_REG, TMP451_SOC_TMP_DEC_REG, integerOnly); - } - - // Function to get the PCB temperature - Result ReadPcbTemperature(float *temperature, bool integerOnly) { - return ReadTemperature(temperature, TMP451_PCB_TEMP_REG, TMP451_PCB_TMP_DEC_REG, integerOnly); - } - - - // Time implementation - CONSTEXPR_STRING std::string DEFAULT_DT_FORMAT = "'%a %T'"; - std::string datetimeFormat = "%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 deleted file mode 100644 index 4e0cc197..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/ultrahand.mk +++ /dev/null @@ -1,30 +0,0 @@ -#--------------------------------------------------------------------------------- -# Ultrahand Library Configuration -# Auto-detects libultrahand directory location -#--------------------------------------------------------------------------------- - -# Assume TOPDIR is the root project directory where you run make -TOPDIR ?= $(CURDIR) - -# Get the absolute path of this .mk file directory -ULTRA_ABS := $(patsubst %/,%,$(dir $(lastword $(MAKEFILE_LIST)))) - -# Convert absolute path to relative path from TOPDIR -ULTRA_DIR := $(subst $(TOPDIR)/,,$(ULTRA_ABS)) - -# If ULTRA_DIR equals ULTRA_ABS, then ULTRA_ABS is outside TOPDIR, -# fallback to just ULTRA_ABS (rare case) -ifeq ($(ULTRA_DIR),$(ULTRA_ABS)) - ULTRA_DIR := $(ULTRA_ABS) -endif - - -# Now add folder paths relative to TOPDIR (or absolute if fallback) -SOURCES += \ - $(ULTRA_DIR)/common \ - $(ULTRA_DIR)/libultra/source - -INCLUDES += \ - $(ULTRA_DIR)/common \ - $(ULTRA_DIR)/libultra/include \ - $(ULTRA_DIR)/libtesla/include diff --git a/Source/sys-clk/overlay/src/main.cpp b/Source/sys-clk/overlay/src/main.cpp index f2085057..60f39028 100644 --- a/Source/sys-clk/overlay/src/main.cpp +++ b/Source/sys-clk/overlay/src/main.cpp @@ -57,7 +57,7 @@ class AppOverlay : public tsl::Overlay if(!sysclkIpcRunning()) { return initially( - "Horizon OC is not running.\n\n" + "sys-clk is not running.\n\n" "\n" "Please make sure it is correctly\n\n" "installed and enabled.", @@ -68,7 +68,7 @@ class AppOverlay : public tsl::Overlay if(R_FAILED(sysclkIpcInitialize()) || R_FAILED(sysclkIpcGetAPIVersion(&apiVersion))) { return initially( - "Could not connect to Horizon OC.\n\n" + "Could not connect to sys-clk.\n\n" "\n" "Please make sure it is correctly\n\n" "installed and enabled.", @@ -80,7 +80,7 @@ class AppOverlay : public tsl::Overlay { return initially( "Overlay not compatible with\n\n" - "the running Horizon OC version.\n\n" + "the running sys-clk version.\n\n" "\n" "Please make sure everything is\n\n" "installed and up to date.", diff --git a/Source/sys-clk/overlay/src/ui/gui/base_gui.cpp b/Source/sys-clk/overlay/src/ui/gui/base_gui.cpp index 8513d2e2..545f402a 100644 --- a/Source/sys-clk/overlay/src/ui/gui/base_gui.cpp +++ b/Source/sys-clk/overlay/src/ui/gui/base_gui.cpp @@ -7,14 +7,14 @@ * * 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. + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * */ - + /* -------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * , , @@ -24,124 +24,37 @@ * -------------------------------------------------------------------------- */ + #include "base_gui.h" #include "../elements/base_frame.h" #include "logo_rgba_bin.h" -#include -#include -// ------------------------------------------------------------- -// Layout constants -// ------------------------------------------------------------- + #define LOGO_X 20 -#define LOGO_Y 50 -#define LOGO_LABEL_FONT_SIZE 45 +#define LOGO_Y 45 +#define LOGO_LABEL_FONT_SIZE 35 #define VERSION_X (LOGO_X + 250) -#define VERSION_Y (LOGO_Y - 40) +#define VERSION_Y LOGO_Y-40 #define VERSION_FONT_SIZE 15 -// ------------------------------------------------------------- -// Version string getter -// ------------------------------------------------------------- - std::string getVersionString() { - char buf[0x100] = ""; + 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 "HorizonOC-Misc"; + return "unknown"; } return std::string(buf); } -// ------------------------------------------------------------- -// Animated Ultra Text -// ------------------------------------------------------------- - -// Your animated wave colors (example placeholders) -static constexpr tsl::Color dynamicLogoRGB1 = tsl::Color(40, 255, 80, 255); -static constexpr tsl::Color dynamicLogoRGB2 = tsl::Color(120, 255, 160, 255); - -// Your project name rendered letter-by-letter -static constexpr const char* PROJECT_NAME = "Horizon OC Gaea"; - -// Fully corrected function signature -static s32 drawDynamicUltraText( - tsl::gfx::Renderer* renderer, - s32 startX, - s32 y, - u32 fontSize, - const tsl::Color& staticColor, - bool useNotificationMethod = false) -{ - static constexpr double cycleDuration = 1.6; - - const std::string name = "Horizon OC Gaea"; - s32 currentX = startX; - - const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); - const double timeNow = static_cast(currentTime_ns) / 1e9; - const double timeBase = fmod(timeNow, cycleDuration); - - // Controls wave spacing - const double waveScale = 2.0 * M_PI / cycleDuration; - - // Every character has its own index offset - for (size_t i = 0; i < name.size(); i++) - { - char letter = name[i]; - if (letter == '\0') break; - - // phase shift per character → THIS CREATES THE WAVE - double phase = waveScale * (timeBase + i * 0.12); - - double raw = cos(phase); - double n = (raw + 1.0) * 0.5; - - // Smoothstep ×2 (ultra smooth) - double s1 = n * n * (3.0 - 2.0 * n); - double s2 = s1 * s1 * (3.0 - 2.0 * s1); - - double blend = std::clamp(s2, 0.0, 1.0); - - tsl::Color color = { - static_cast(staticColor.r + (dynamicLogoRGB2.r - staticColor.r) * blend), - static_cast(staticColor.g + (dynamicLogoRGB2.g - staticColor.g) * blend), - static_cast(staticColor.b + (dynamicLogoRGB2.b - staticColor.b) * blend), - 255 - }; - - std::string ls(1, letter); - - if (useNotificationMethod) - currentX += renderer->drawNotificationString(ls, false, currentX, y, fontSize, color).first; - else - currentX += renderer->drawString(ls, false, currentX, y, fontSize, color).first; - } - - return currentX; -} - - -// ------------------------------------------------------------- -// Rendering functions -// ------------------------------------------------------------- - void BaseGui::preDraw(tsl::gfx::Renderer* renderer) { - static constexpr tsl::Color STATIC_GREEN = tsl::Color(80, 255, 120, 255); - - drawDynamicUltraText( - renderer, - LOGO_X, - LOGO_Y, - LOGO_LABEL_FONT_SIZE, - STATIC_GREEN, - false - ); +// renderer->drawBitmap(LOGO_X, LOGO_Y, LOGO_WIDTH, LOGO_HEIGHT, logo_rgba_bin); + renderer->drawString("Horizon OC overlay", false, LOGO_X, LOGO_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() 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 index 79b6418b..0adfc561 100644 --- a/Source/sys-clk/overlay/src/ui/gui/freq_choice_gui.cpp +++ b/Source/sys-clk/overlay/src/ui/gui/freq_choice_gui.cpp @@ -25,184 +25,154 @@ */ -#include "freq_choice_gui.h" - -#include "../format.h" -#include "fatal_gui.h" - -FreqChoiceGui::FreqChoiceGui(std::uint32_t selectedHz, - std::uint32_t* hzList, - std::uint32_t hzCount, - SysClkModule module, - FreqChoiceListener listener, - bool checkMax, - std::map labels) -{ - this->selectedHz = selectedHz; - this->hzList = hzList; - this->hzCount = hzCount; - this->module = module; - this->listener = listener; - this->checkMax = checkMax; - this->labels = labels; // NEW - this->configList = new SysClkConfigValueList {}; -} + #include "freq_choice_gui.h" + #include "../format.h" + #include "fatal_gui.h" + + FreqChoiceGui::FreqChoiceGui(std::uint32_t selectedHz, std::uint32_t *hzList, std::uint32_t hzCount, SysClkModule module, FreqChoiceListener listener, bool checkMax) + { + this->selectedHz = selectedHz; + this->hzList = hzList; + this->hzCount = hzCount; + this->module = module; + this->listener = listener; + this->checkMax = checkMax; + this->configList = new SysClkConfigValueList {}; + } FreqChoiceGui::~FreqChoiceGui() { delete this->configList; } -tsl::elm::ListItem* FreqChoiceGui::createFreqListItem(std::uint32_t hz, bool selected, int safety) -{ - std::string text = formatListFreqHz(hz); - if (selected) - text += " \uE14B"; - - // NEW: Right-side label - std::string rightText = ""; - auto it = labels.find(hz); - if (it != labels.end()) - rightText = it->second; - - tsl::elm::ListItem* listItem = - new tsl::elm::ListItem(text, rightText, false); - - switch (safety) - { - case 0: - listItem->setTextColor(tsl::Color(255, 255, 255, 255)); - listItem->setValueColor(tsl::Color(255, 255, 255, 255)); - break; - case 1: - listItem->setTextColor(tsl::Color(255, 165, 0, 255)); - listItem->setValueColor(tsl::Color(255, 165, 0, 255)); - break; - case 2: - listItem->setTextColor(tsl::Color(255, 0, 0, 255)); - listItem->setValueColor(tsl::Color(255, 0, 0, 255)); - break; - } - - // Make annotation grey - if (!rightText.empty()) - listItem->setValueColor(tsl::Color(180, 180, 180, 255)); - - listItem->setClickListener([this, hz](u64 keys) - { - if ((keys & HidNpadButton_A) == HidNpadButton_A && this->listener) { - if (this->listener(hz)) { - tsl::goBack(); + tsl::elm::ListItem* FreqChoiceGui::createFreqListItem(std::uint32_t hz, bool selected, int safety) + { + std::string text = formatListFreqHz(hz); + if (selected) text += " \uE14B"; + + tsl::elm::ListItem* listItem = new tsl::elm::ListItem(text, "", false); + + switch (safety) + { + case 0: + listItem->setTextColor(tsl::Color(255, 255, 255, 255)); + listItem->setValueColor(tsl::Color(255, 255, 255, 255)); + break; + case 1: + listItem->setTextColor(tsl::Color(255, 165, 0, 255)); + listItem->setValueColor(tsl::Color(255, 165, 0, 255)); + break; + case 2: + listItem->setTextColor(tsl::Color(255, 0, 0, 255)); + listItem->setValueColor(tsl::Color(255, 0, 0, 255)); + break; + } + + listItem->setClickListener([this, hz](u64 keys) + { + if ((keys & HidNpadButton_A) == HidNpadButton_A && this->listener) { + if (this->listener(hz)) { + tsl::goBack(); + } + return true; + } + return false; + }); + + return listItem; + } + + void FreqChoiceGui::listUI() + { + sysclkIpcGetConfigValues(this->configList); + // Add CategoryHeader based on module + std::string moduleName = sysclkFormatModule(this->module, false); + this->listElement->addItem(new tsl::elm::CategoryHeader(moduleName)); + + this->listElement->addItem(this->createFreqListItem(0, this->selectedHz == 0, false)); + std::uint32_t hz; + for (std::uint32_t i = 0; i < this->hzCount; i++) + { + hz = this->hzList[i]; + uint32_t mhz = hz / 1000000; + // Skip 204 MHz exactly + if(checkMax && IsMariko()) { + if (this->configList->values[HocClkConfigValue_MarikoMaxCpuClock] < mhz && moduleName == "cpu") { + continue; } - return true; - } - return false; - }); - - return listItem; -} - -void FreqChoiceGui::listUI() -{ - sysclkIpcGetConfigValues(this->configList); - - // Header based on CPU/GPU/MEM module - std::string moduleName = sysclkFormatModule(this->module, false); - this->listElement->addItem(new tsl::elm::CategoryHeader(moduleName)); - - // Default option - this->listElement->addItem( - this->createFreqListItem(0, this->selectedHz == 0, 0)); - - for (std::uint32_t i = 0; i < this->hzCount; i++) - { - std::uint32_t hz = this->hzList[i]; - uint32_t mhz = hz / 1000000; - - if (checkMax && IsMariko()) { - if (moduleName == "cpu" && - this->configList->values[HocClkConfigValue_MarikoMaxCpuClock] < mhz) + + if (this->configList->values[HocClkConfigValue_MarikoMaxGpuClock] < mhz && moduleName == "gpu") { continue; - - if (moduleName == "gpu" && - this->configList->values[HocClkConfigValue_MarikoMaxGpuClock] < mhz) + } + if (this->configList->values[HocClkConfigValue_MarikoMaxMemClock] < mhz && moduleName == "mem") { continue; - - if (moduleName == "mem" && - this->configList->values[HocClkConfigValue_MarikoMaxMemClock] < mhz) - continue; - + } } else if (checkMax && IsErista()) { - if (moduleName == "cpu" && - this->configList->values[HocClkConfigValue_EristaMaxCpuClock] < mhz) + if (this->configList->values[HocClkConfigValue_EristaMaxCpuClock] < mhz && moduleName == "cpu") { continue; - - if (moduleName == "gpu" && - this->configList->values[HocClkConfigValue_EristaMaxGpuClock] < mhz) + } + + if (this->configList->values[HocClkConfigValue_EristaMaxGpuClock] < mhz && moduleName == "gpu") { continue; - - if (moduleName == "mem" && - this->configList->values[HocClkConfigValue_EristaMaxMemClock] < mhz) + } + if (this->configList->values[HocClkConfigValue_EristaMaxMemClock] < mhz && moduleName == "mem") { continue; - } + } + } + if (moduleName == "mem" && mhz <= 600) + { + continue; + } + uint32_t unsafe_cpu; + uint32_t unsafe_gpu; + uint32_t danger_cpu; + uint32_t danger_gpu; + if (IsMariko()) + { + unsafe_cpu = 1964; + unsafe_gpu = 1076; + danger_cpu = 2398; + danger_gpu = 1306; + } + else + { + unsafe_cpu = 1786; + unsafe_gpu = 922; + danger_cpu = 2092; + danger_gpu = 999; + } - if (moduleName == "mem" && mhz <= 600) + if (moduleName == "cpu") { + if (mhz >= danger_cpu) { + this->listElement->addItem(this->createFreqListItem(hz, mhz == this->selectedHz / 1000000, 2)); + continue; + } + if (mhz >= unsafe_cpu) { + this->listElement->addItem(this->createFreqListItem(hz, mhz == this->selectedHz / 1000000, 1)); + continue; + } + if (mhz <= unsafe_cpu) { + this->listElement->addItem(this->createFreqListItem(hz, mhz == this->selectedHz / 1000000, 0)); + continue; + } + } else if (moduleName == "gpu") { + if (mhz >= danger_gpu) { + this->listElement->addItem(this->createFreqListItem(hz, mhz == this->selectedHz / 1000000, 2)); + continue; + } + if (mhz >= unsafe_gpu) { + this->listElement->addItem(this->createFreqListItem(hz, mhz == this->selectedHz / 1000000, 1)); + continue; + } + if (mhz <= unsafe_gpu) { + this->listElement->addItem(this->createFreqListItem(hz, mhz == this->selectedHz / 1000000, 0)); + continue; + } + } else if (moduleName == "mem") { + this->listElement->addItem(this->createFreqListItem(hz, mhz == this->selectedHz / 1000000, 0)); continue; - - uint32_t unsafe_cpu; - uint32_t unsafe_gpu; - uint32_t danger_cpu; - uint32_t danger_gpu; - - if (IsMariko()) - { - unsafe_cpu = 1964; - unsafe_gpu = 1076; - danger_cpu = 2398; - danger_gpu = 1306; - } - else - { - unsafe_cpu = 1786; - unsafe_gpu = 922; - danger_cpu = 2092; - danger_gpu = 999; - } - - int safety = 0; - - if (moduleName == "cpu") { - - if (mhz >= danger_cpu) - safety = 2; - else if (mhz >= unsafe_cpu) - safety = 1; - else - safety = 0; - - } else if (moduleName == "gpu") { - - if (mhz >= danger_gpu) - safety = 2; - else if (mhz >= unsafe_gpu) - safety = 1; - else - safety = 0; - - } else if (moduleName == "mem") { - - safety = 0; - - } - - this->listElement->addItem( - this->createFreqListItem( - hz, - (mhz == this->selectedHz / 1000000), - safety - ) - ); - } - - this->listElement->jumpToItem("", ""); -} \ No newline at end of file + } + + } + 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 index cf18095c..cc13e2e9 100644 --- a/Source/sys-clk/overlay/src/ui/gui/freq_choice_gui.h +++ b/Source/sys-clk/overlay/src/ui/gui/freq_choice_gui.h @@ -29,7 +29,6 @@ #include #include -#include #include "base_menu_gui.h" using FreqChoiceListener = std::function; @@ -43,24 +42,19 @@ protected: std::uint32_t selectedHz; std::uint32_t* hzList; std::uint32_t hzCount; - SysClkModule module; + SysClkModule module; // added module FreqChoiceListener listener; - bool checkMax; - - // NEW: Optional annotation labels - std::map labels; - + bool checkMax; // new member tsl::elm::ListItem* createFreqListItem(std::uint32_t hz, bool selected, int safety); public: + // Updated constructor with checkMaxValue FreqChoiceGui(std::uint32_t selectedHz, std::uint32_t* hzList, std::uint32_t hzCount, SysClkModule module, FreqChoiceListener listener, - bool checkMax = true, - std::map labels = {}); // NEW ARG - + bool checkMax = true); ~FreqChoiceGui(); void listUI() override; diff --git a/Source/sys-clk/overlay/src/ui/gui/misc_gui.cpp b/Source/sys-clk/overlay/src/ui/gui/misc_gui.cpp index 3aacd96d..89867f2d 100644 --- a/Source/sys-clk/overlay/src/ui/gui/misc_gui.cpp +++ b/Source/sys-clk/overlay/src/ui/gui/misc_gui.cpp @@ -59,8 +59,7 @@ void MiscGui::addConfigButton(SysClkConfigValue configVal, const char* altName, const ValueRange& range, const std::string& categoryName, - const ValueThresholds* thresholds, - const std::map& labels) + const ValueThresholds* thresholds) { const char* configName = altName ? altName : sysclkFormatConfigValue(configVal, true); @@ -83,7 +82,7 @@ void MiscGui::addConfigButton(SysClkConfigValue configVal, ValueThresholds thresholdsCopy = (thresholds ? *thresholds : ValueThresholds{}); listItem->setClickListener( - [this, configVal, range, categoryName, thresholdsCopy, labels](u64 keys) + [this, configVal, range, categoryName, thresholdsCopy](u64 keys) { if ((keys & HidNpadButton_A) == 0) return false; @@ -107,8 +106,7 @@ void MiscGui::addConfigButton(SysClkConfigValue configVal, return true; }, thresholdsCopy, - true, - labels // <── NEW + true ); } else { @@ -125,10 +123,7 @@ void MiscGui::addConfigButton(SysClkConfigValue configVal, } this->lastContextUpdate = armGetSystemTick(); return true; - }, - ValueThresholds(), - false, - labels // <── NEW + } ); } @@ -140,11 +135,7 @@ void MiscGui::addConfigButton(SysClkConfigValue configVal, this->configRanges[configVal] = range; } -void MiscGui::addFreqButton(SysClkConfigValue configVal, - const char* altName, - SysClkModule module, - const std::map& labels) -{ +void MiscGui::addFreqButton(SysClkConfigValue configVal, const char* altName, SysClkModule module) { const char* configName = altName ? altName : sysclkFormatConfigValue(configVal, true); tsl::elm::ListItem* listItem = new tsl::elm::ListItem(configName); @@ -154,48 +145,45 @@ void MiscGui::addFreqButton(SysClkConfigValue configVal, snprintf(valueText, sizeof(valueText), "%lu MHz", currentMHz); listItem->setValue(valueText); - listItem->setClickListener( - [this, configVal, module, labels](u64 keys) - { - if ((keys & HidNpadButton_A) == 0) - return false; + listItem->setClickListener([this, configVal, module](u64 keys) { + if ((keys & HidNpadButton_A) == 0) + return false; - std::uint32_t hzList[SYSCLK_FREQ_LIST_MAX]; - std::uint32_t hzCount; + std::uint32_t hzList[SYSCLK_FREQ_LIST_MAX]; + std::uint32_t hzCount; - Result rc = sysclkIpcGetFreqList(module, hzList, SYSCLK_FREQ_LIST_MAX, &hzCount); - if (R_FAILED(rc)) { - FatalGui::openWithResultCode("sysclkIpcGetFreqList", rc); - return false; - } + Result rc = sysclkIpcGetFreqList(module, hzList, SYSCLK_FREQ_LIST_MAX, &hzCount); + if (R_FAILED(rc)) { + FatalGui::openWithResultCode("sysclkIpcGetFreqList", rc); + return false; + } - std::uint32_t currentHz = this->configList->values[configVal] * 1'000'000; + std::uint32_t currentHz = this->configList->values[configVal] * 1'000'000; - tsl::changeTo( - currentHz, - hzList, - hzCount, - module, - [this, configVal](std::uint32_t hz) - { - uint64_t mhz = hz / 1'000'000; - this->configList->values[configVal] = mhz; + tsl::changeTo( + currentHz, + hzList, + hzCount, + module, + [this, configVal](std::uint32_t hz) { - Result rc = sysclkIpcSetConfigValues(this->configList); - if (R_FAILED(rc)) { - FatalGui::openWithResultCode("sysclkIpcSetConfigValues", rc); - return false; - } + uint64_t mhz = hz / 1'000'000; + this->configList->values[configVal] = mhz; - this->lastContextUpdate = armGetSystemTick(); - return true; - }, - false, - labels - ); + Result rc = sysclkIpcSetConfigValues(this->configList); + if (R_FAILED(rc)) { + FatalGui::openWithResultCode("sysclkIpcSetConfigValues", rc); + return false; + } - return true; - }); + this->lastContextUpdate = armGetSystemTick(); + return true; + }, + false + ); + + return true; + }); this->listElement->addItem(listItem); this->configButtons[configVal] = listItem; @@ -216,184 +204,46 @@ void MiscGui::listUI() addConfigToggle(HocClkConfigValue_UncappedClocks, nullptr); addConfigToggle(HocClkConfigValue_OverwriteBoostMode, nullptr); - // this->listElement->addItem(new tsl::elm::CategoryHeader("Experimental")); + this->listElement->addItem(new tsl::elm::CategoryHeader("Experimental")); addConfigToggle(HocClkConfigValue_ThermalThrottle, nullptr); addConfigToggle(HocClkConfigValue_HandheldTDP, nullptr); - addConfigToggle(HocClkConfigValue_EnforceBoardLimit, nullptr); - std::map labels_pwr_r = { - {8600, "Official Rating"} - }; - std::map labels_pwr_l = { - {6400, "Official Rating"} - }; + ValueThresholds tdpThresholds(8600, 9500); addConfigButton( HocClkConfigValue_HandheldTDPLimit, "TDP Threshold", - ValueRange(5000, 10000, 200, "mW", 1), + ValueRange(5000, 10000, 100, "mW", 1), "Power", - &tdpThresholds, - labels_pwr_r + &tdpThresholds ); ValueThresholds tdpThresholdsLite(6400, 7500); addConfigButton( HocClkConfigValue_LiteTDPLimit, "Lite TDP Threshold", - ValueRange(4000, 8000, 200, "mW", 1), + ValueRange(4000, 8000, 100, "mW", 1), "Power", - &tdpThresholdsLite, - labels_pwr_l + &tdpThresholdsLite ); ValueThresholds throttleThresholds(70, 80); addConfigButton( HocClkConfigValue_ThermalThrottleThreshold, "Thermal Throttle Limit", - ValueRange(50, 85, 5, "°C", 1), + ValueRange(50, 85, 1, "°C", 1), "Temp", &throttleThresholds ); - std::map cpu_freq_label_m = { - {612000000, "Sleep Mode"}, - {1020000000, "Stock"}, - {1224000000, "Dev OC"}, - {1785000000, "Boost Mode"}, - {1963000000, "Safe Max"}, - {2397000000, "Unsafe Max"}, - {2805000000, "Aboslute Max"}, - }; - - std::map cpu_freq_label_e = { - {612000000, "Sleep Mode"}, - {1020000000, "Stock"}, - {1224000000, "Dev OC"}, - {1785000000, "Boost Mode & Safe Max"}, - {2091000000, "Unsafe Max"}, - {2295000000, "Aboslute Max"}, - }; - - std::map gpu_freq_label_e = { - {76800000, "Boost Mode"}, - {307200000, "Handheld"}, - {384000000, "Handheld"}, - {460800000, "Handheld Safe Max"}, - {768000000, "Docked"}, - {844000000, "Safe Max"}, - {998400000, "Unsafe Max"}, - {1075200000, "Aboslute Max"}, - }; - - std::map gpu_freq_label_m = { - {76800000, "Boost Mode"}, - {307200000, "Handheld"}, - {384000000, "Handheld"}, - {460800000, "Handheld"}, - {614400000, "Handheld Safe Max"}, - {768000000, "Docked"}, - {1152200000, "Safe Max"}, - {1305600000, "Unsafe Max"}, - {1536000000, "Aboslute Max"}, - }; - - std::map emc_freq_label_e = { - {133120000, "Handheld"}, - {160000000, "Docked & Safe Max"}, - {213100000, "JEDEC Max"}, - {236000000, "Absolute Max"}, - }; - - - std::map emc_freq_label_m = { - {133120000, "Handheld"}, - {160000000, "Docked"}, - {186600000, "Safe Max (3733MT/s)"}, - {213300000, "Safe Max (4266MT/s)"}, - {320000000, "Absolute Max"}, - }; - - - this->listElement->addItem(new tsl::elm::CategoryHeader("Clocks")); + this->listElement->addItem(new tsl::elm::CategoryHeader("Max Clocks")); if(IsMariko()) { - addFreqButton(HocClkConfigValue_MarikoMaxCpuClock, nullptr, SysClkModule_CPU, cpu_freq_label_m); - addFreqButton(HocClkConfigValue_MarikoMaxGpuClock, nullptr, SysClkModule_GPU, gpu_freq_label_m); - addFreqButton(HocClkConfigValue_MarikoMaxMemClock, nullptr, SysClkModule_MEM, emc_freq_label_m); + addFreqButton(HocClkConfigValue_MarikoMaxCpuClock, nullptr, SysClkModule_CPU); + addFreqButton(HocClkConfigValue_MarikoMaxGpuClock, nullptr, SysClkModule_GPU); + addFreqButton(HocClkConfigValue_MarikoMaxMemClock, nullptr, SysClkModule_MEM); } else { - addFreqButton(HocClkConfigValue_EristaMaxCpuClock, nullptr, SysClkModule_CPU, cpu_freq_label_e); - addFreqButton(HocClkConfigValue_EristaMaxGpuClock, nullptr, SysClkModule_GPU, gpu_freq_label_e); - addFreqButton(HocClkConfigValue_EristaMaxMemClock, nullptr, SysClkModule_MEM, emc_freq_label_e); + addFreqButton(HocClkConfigValue_EristaMaxCpuClock, nullptr, SysClkModule_CPU); + addFreqButton(HocClkConfigValue_EristaMaxGpuClock, nullptr, SysClkModule_GPU); + addFreqButton(HocClkConfigValue_EristaMaxMemClock, nullptr, SysClkModule_MEM); } - - this->listElement->addItem(new tsl::elm::CategoryHeader("EMC")); - - addConfigToggle(HocClkConfigValue_EMCDVFS, nullptr); - - std::map emc_voltage_label_m = { - {1100000, "Default"}, - {1175000, "Rating"}, - {1212500, "Safe Max"}, - }; - - std::map emc_voltage_label_e = { - {1125000, "Default"}, - {1175000, "Rating"}, - {1237500, "Safe Max"}, - }; - - - if(IsMariko()) { - ValueThresholds emcUvThresholds(1212500, 1250000); - addConfigButton( - HocClkConfigValue_EMCVdd2VoltageUV, - "EMC VDD2 Voltage", - ValueRange(1100000, 1237500, 12500, "mV", 1000, 1), - "EMC VDD2 Voltage", - &emcUvThresholds, - emc_voltage_label_m - ); - addConfigButton( - HocClkConfigValue_EMCVdd2VoltageUVStockMariko, - "EMC Stock VDD2 Voltage", - ValueRange(912500, 1175000, 12500, "mV", 1000, 1), - "EMC Stock VDD2 Voltage", - &emcUvThresholds, - emc_voltage_label_m - ); - } else { - ValueThresholds emcUvThresholds(1237500, 1300000); - addConfigButton( - HocClkConfigValue_EMCVdd2VoltageUV, - "EMC VDD2 Voltage", - ValueRange(1100000, 1237500, 12500, "mV", 1000, 1), - "EMC VDD2 Voltage", - &emcUvThresholds, - emc_voltage_label_e - ); - addConfigButton( - HocClkConfigValue_EMCVdd2VoltageUVStockErista, - "EMC Stock VDD2 Voltage", - ValueRange(1000000, 1175000, 12500, "mV", 1000, 1), - "EMC Stock VDD2 Voltage", - &emcUvThresholds, - emc_voltage_label_e - ); - } - - tsl::elm::ListItem* applyBtn = new tsl::elm::ListItem("Apply EMC Regs"); - applyBtn->setClickListener([](u64 keys) { - if (keys & HidNpadButton_A) { - Result rc = hocClkIpcUpdateEmcRegs(); - if (R_FAILED(rc)) { - FatalGui::openWithResultCode("hocClkIpcUpdateEmcRegs", rc); - return false; - } - return true; - } - return false; - }); - this->listElement->addItem(applyBtn); - - } void MiscGui::refresh() { diff --git a/Source/sys-clk/overlay/src/ui/gui/misc_gui.h b/Source/sys-clk/overlay/src/ui/gui/misc_gui.h index d60fc617..0192b888 100644 --- a/Source/sys-clk/overlay/src/ui/gui/misc_gui.h +++ b/Source/sys-clk/overlay/src/ui/gui/misc_gui.h @@ -27,12 +27,8 @@ protected: const char* altName, const ValueRange& range, const std::string& categoryName, - const ValueThresholds* thresholds, - const std::map& labels = {}); - void addFreqButton(SysClkConfigValue configVal, - const char* altName, - SysClkModule module, - const std::map& labels = {}); + const ValueThresholds* thresholds = nullptr); + void addFreqButton(SysClkConfigValue configVal, const char* altName, SysClkModule module); void updateConfigToggles(); tsl::elm::ToggleListItem* enabledToggle; diff --git a/Source/sys-clk/overlay/src/ui/gui/value_choice_gui.cpp b/Source/sys-clk/overlay/src/ui/gui/value_choice_gui.cpp index 07074d51..ed5108df 100644 --- a/Source/sys-clk/overlay/src/ui/gui/value_choice_gui.cpp +++ b/Source/sys-clk/overlay/src/ui/gui/value_choice_gui.cpp @@ -1,121 +1,145 @@ -#include "value_choice_gui.h" -#include "../format.h" -#include "fatal_gui.h" -#include -#include +/* + * Copyright (c) Souldbminer and Horizon OC Contributors + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +/* -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ -ValueChoiceGui::ValueChoiceGui(std::uint32_t selectedValue, - const ValueRange& range, - const std::string& categoryName, - ValueChoiceListener listener, - const ValueThresholds& thresholds, - bool enableThresholds, - std::map labels) - : selectedValue(selectedValue), - range(range), - categoryName(categoryName), - listener(listener), - thresholds(thresholds), - enableThresholds(enableThresholds), - labels(labels) -{ -} -ValueChoiceGui::~ValueChoiceGui() -{ -} + #include "value_choice_gui.h" + #include "../format.h" + #include "fatal_gui.h" + #include + #include -std::string ValueChoiceGui::formatValue(std::uint32_t value) -{ - std::ostringstream oss; + ValueChoiceGui::ValueChoiceGui(std::uint32_t selectedValue, + const ValueRange& range, + const std::string& categoryName, + ValueChoiceListener listener, + const ValueThresholds& thresholds, + bool enableThresholds) + : selectedValue(selectedValue), + range(range), + categoryName(categoryName), + listener(listener), + thresholds(thresholds), + enableThresholds(enableThresholds) + { + } - if (value == 0) { - return VALUE_DEFAULT_TEXT; - } + ValueChoiceGui::~ValueChoiceGui() + { + } - double displayValue = static_cast(value) / static_cast(range.divisor); + std::string ValueChoiceGui::formatValue(std::uint32_t value) + { + std::ostringstream oss; - oss << std::fixed << std::setprecision(range.decimalPlaces) << displayValue; + if (value == 0) { - if (!range.suffix.empty()) { - oss << " " << range.suffix; - } - return oss.str(); -} + return VALUE_DEFAULT_TEXT; + } -int ValueChoiceGui::getSafetyLevel(std::uint32_t value) -{ - if (value > thresholds.danger) { - return 2; - } - if (value > thresholds.warning) { - return 1; - } - return 0; -} + std::uint32_t displayValue = value / range.divisor; -tsl::elm::ListItem* ValueChoiceGui::createValueListItem(std::uint32_t value, bool selected, int safety) -{ - std::string text = formatValue(value); - if (selected) { - text += " \uE14B"; - } + oss << displayValue; + if (!range.suffix.empty()) { + oss << " " << range.suffix; + } + return oss.str(); + } - std::string rightText = ""; - auto it = labels.find(value); - if (it != labels.end()) { - rightText = it->second; - } + int ValueChoiceGui::getSafetyLevel(std::uint32_t value) + { + if (!enableThresholds) { + return 0; + } - tsl::elm::ListItem* listItem = new tsl::elm::ListItem(text, rightText, false); + std::uint32_t scaledValue = value / range.divisor; - switch (safety) - { - case 0: - listItem->setTextColor(tsl::Color(255, 255, 255, 255)); - listItem->setValueColor(tsl::Color(255, 255, 255, 255)); - break; - case 1: - listItem->setTextColor(tsl::Color(255, 165, 0, 255)); - listItem->setValueColor(tsl::Color(255, 165, 0, 255)); - break; - case 2: - listItem->setTextColor(tsl::Color(255, 0, 0, 255)); - listItem->setValueColor(tsl::Color(255, 0, 0, 255)); - break; - } + if (scaledValue > thresholds.danger) { + return 2; + } + if (scaledValue > thresholds.warning) { + return 1; + } + return 0; + } - if (!rightText.empty()) - listItem->setValueColor(tsl::Color(180, 180, 180, 255)); + tsl::elm::ListItem* ValueChoiceGui::createValueListItem(std::uint32_t value, bool selected, int safety) + { + std::string text = formatValue(value); + if (selected) { + text += " \uE14B"; + } - listItem->setClickListener([this, value](u64 keys) - { - if ((keys & HidNpadButton_A) == HidNpadButton_A && this->listener) { - if (this->listener(value)) { - tsl::goBack(); - } - return true; - } - return false; - }); + tsl::elm::ListItem* listItem = new tsl::elm::ListItem(text, "", false); - return listItem; -} + switch (safety) + { + case 0: + listItem->setTextColor(tsl::Color(255, 255, 255, 255)); + listItem->setValueColor(tsl::Color(255, 255, 255, 255)); + break; + case 1: + listItem->setTextColor(tsl::Color(255, 165, 0, 255)); + listItem->setValueColor(tsl::Color(255, 165, 0, 255)); + break; + case 2: + listItem->setTextColor(tsl::Color(255, 0, 0, 255)); + listItem->setValueColor(tsl::Color(255, 0, 0, 255)); + break; + } -void ValueChoiceGui::listUI() -{ - if (!categoryName.empty()) { - this->listElement->addItem(new tsl::elm::CategoryHeader(categoryName)); - } + listItem->setClickListener([this, value](u64 keys) + { + if ((keys & HidNpadButton_A) == HidNpadButton_A && this->listener) { - this->listElement->addItem(this->createValueListItem(0, this->selectedValue == 0, 0)); + if (this->listener(value)) { + tsl::goBack(); + } + return true; + } + return false; + }); - for (std::uint32_t value = range.min; value <= range.max; value += range.step) - { - int safety = getSafetyLevel(value); - bool selected = (value == this->selectedValue); - this->listElement->addItem(this->createValueListItem(value, selected, safety)); - } + return listItem; + } - this->listElement->jumpToItem("", "\uE14B"); -} + void ValueChoiceGui::listUI() + { + + if (!categoryName.empty()) { + this->listElement->addItem(new tsl::elm::CategoryHeader(categoryName)); + } + + this->listElement->addItem(this->createValueListItem(0, this->selectedValue == 0, 0)); + + for (std::uint32_t value = range.min; value <= range.max; value += range.step) + { + int safety = getSafetyLevel(value); + bool selected = (value == this->selectedValue); + this->listElement->addItem(this->createValueListItem(value, selected, safety)); + } + + this->listElement->jumpToItem("", "\uE14B"); + } \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ui/gui/value_choice_gui.h b/Source/sys-clk/overlay/src/ui/gui/value_choice_gui.h index 278c8144..160de655 100644 --- a/Source/sys-clk/overlay/src/ui/gui/value_choice_gui.h +++ b/Source/sys-clk/overlay/src/ui/gui/value_choice_gui.h @@ -25,69 +25,62 @@ */ -#pragma once + #pragma once -#include -#include -#include -#include -#include "base_menu_gui.h" - -using ValueChoiceListener = std::function; - -#define VALUE_DEFAULT_TEXT "Default" - -struct ValueRange { - std::uint32_t min; - std::uint32_t max; - std::uint32_t step; - std::string suffix; - std::uint32_t divisor; - int decimalPlaces; - - ValueRange() - : min(0), max(0), step(1), suffix(""), divisor(1), decimalPlaces(0) {} - - ValueRange(std::uint32_t min, std::uint32_t max, std::uint32_t step, - const std::string& suffix = "", std::uint32_t divisor = 1, int decimalPlaces = 0) - : min(min), max(max), step(step), suffix(suffix), - divisor(divisor), decimalPlaces(decimalPlaces) {} -}; - -struct ValueThresholds { - std::uint32_t warning; - std::uint32_t danger; - - ValueThresholds(std::uint32_t warning = 0, std::uint32_t danger = 0) - : warning(warning), danger(danger) {} -}; - -class ValueChoiceGui : public BaseMenuGui -{ -protected: - std::uint32_t selectedValue; - ValueRange range; - std::string categoryName; - ValueChoiceListener listener; - ValueThresholds thresholds; - bool enableThresholds; - - // NEW — map of value → right-side text (like version numbers) - std::map labels; - - tsl::elm::ListItem* createValueListItem(std::uint32_t value, bool selected, int safety); - std::string formatValue(std::uint32_t value); - int getSafetyLevel(std::uint32_t value); - -public: - ValueChoiceGui(std::uint32_t selectedValue, - const ValueRange& range, - const std::string& categoryName, - ValueChoiceListener listener, - const ValueThresholds& thresholds = ValueThresholds(), - bool enableThresholds = false, - std::map labels = {}); - ~ValueChoiceGui(); - - void listUI() override; -}; + #include + #include + #include + #include "base_menu_gui.h" + + using ValueChoiceListener = std::function; + + #define VALUE_DEFAULT_TEXT "Default" + + struct ValueRange { + std::uint32_t min; + std::uint32_t max; + std::uint32_t step; + std::string suffix; + std::uint32_t divisor; // Divide input values by this for display + + // Default constructor + ValueRange() : min(0), max(0), step(1), suffix(""), divisor(1) {} + + ValueRange(std::uint32_t min, std::uint32_t max, std::uint32_t step, + const std::string& suffix = "", std::uint32_t divisor = 1) + : min(min), max(max), step(step), suffix(suffix), divisor(divisor) {} + }; + + struct ValueThresholds { + std::uint32_t warning; // Values >= this show orange + std::uint32_t danger; // Values >= this show red + + ValueThresholds(std::uint32_t warning = 0, std::uint32_t danger = 0) + : warning(warning), danger(danger) {} + }; + + class ValueChoiceGui : public BaseMenuGui + { + protected: + std::uint32_t selectedValue; + ValueRange range; + std::string categoryName; + ValueChoiceListener listener; + ValueThresholds thresholds; + bool enableThresholds; + + tsl::elm::ListItem* createValueListItem(std::uint32_t value, bool selected, int safety); + std::string formatValue(std::uint32_t value); + int getSafetyLevel(std::uint32_t value); + + public: + ValueChoiceGui(std::uint32_t selectedValue, + const ValueRange& range, + const std::string& categoryName, + ValueChoiceListener listener, + const ValueThresholds& thresholds = ValueThresholds(), + bool enableThresholds = false); + ~ValueChoiceGui(); + + void listUI() override; + }; \ No newline at end of file diff --git a/Source/sys-clk/sysmodule/Makefile b/Source/sys-clk/sysmodule/Makefile index ae8bfa66..cc97fab7 100644 --- a/Source/sys-clk/sysmodule/Makefile +++ b/Source/sys-clk/sysmodule/Makefile @@ -17,7 +17,7 @@ include $(DEVKITPRO)/libnx/switch_rules # INCLUDES is a list of directories containing header files # EXEFS_SRC is the optional input directory containing data copied into exefs, if anything this normally should only contain "main.npdm". #--------------------------------------------------------------------------------- -TARGET := horizon-oc +TARGET := sys-clk BUILD := build OUTDIR := out RESOURCES := res @@ -39,7 +39,7 @@ DEFINES := -DDISABLE_IPC -DTARGET="\"$(TARGET)\"" -DTARGET_VERSION="\"$(TARGET_V ARCH := -march=armv8-a+crc+crypto -mtune=cortex-a57 -mtp=soft -fPIE -CFLAGS := -g -Wall -Os -ffunction-sections \ +CFLAGS := -g -Wall -O2 -ffunction-sections \ $(ARCH) $(DEFINES) CFLAGS += $(INCLUDE) -D__SWITCH__ diff --git a/Source/sys-clk/sysmodule/perms.json b/Source/sys-clk/sysmodule/perms.json index e8959caa..a57e28e4 100644 --- a/Source/sys-clk/sysmodule/perms.json +++ b/Source/sys-clk/sysmodule/perms.json @@ -1,5 +1,5 @@ { - "name": "hoc:sys", + "name": "sys:clk", "title_id": "0x00FF0000636C6BFF", "title_id_range_min": "0x00FF0000636C6BFF", "title_id_range_max": "0x00FF0000636C6BFF", @@ -18,7 +18,7 @@ "*" ], "service_host": [ - "hoc:sys" + "sys:clk" ], "kernel_capabilities": [ { diff --git a/Source/sys-clk/sysmodule/src/board.cpp b/Source/sys-clk/sysmodule/src/board.cpp index 700af72f..f7b92991 100644 --- a/Source/sys-clk/sysmodule/src/board.cpp +++ b/Source/sys-clk/sysmodule/src/board.cpp @@ -31,10 +31,6 @@ #define HOSSVC_HAS_CLKRST (hosversionAtLeast(8,0,0)) #define HOSSVC_HAS_TC (hosversionAtLeast(5,0,0)) -#define NVGPU_GPU_IOCTL_PMU_GET_GPU_LOAD 0x80044715 - -Result nvCheck = 1; -u32 fd = 0; static SysClkSocType g_socType = SysClkSocType_Erista; @@ -121,11 +117,6 @@ void Board::Initialize() rc = tmp451Initialize(); ASSERT_RESULT_OK(rc, "tmp451Initialize"); - // u32 fd = 0; - - // if (R_SUCCEEDED(nvInitialize())) nvCheck = nvOpen(&fd, "/dev/nvhost-ctrl-gpu"); - - FetchHardwareInfos(); } @@ -150,7 +141,6 @@ void Board::Exit() max17050Exit(); tmp451Exit(); - nvExit(); } SysClkProfile Board::GetProfile() @@ -473,23 +463,16 @@ std::int32_t Board::GetPowerMw(SysClkPowerSensor sensor) return 0; } -std::uint32_t Board::GetPartLoad(SysClkPartLoad loadSource) +std::uint32_t Board::GetRamLoad(SysClkRamLoad loadSource) { - // u32 temp, GPU_Load_u = 0; - switch(loadSource) { - case SysClkPartLoad_EMC: + case SysClkRamLoad_All: return t210EmcLoadAll(); - case SysClkPartLoad_EMCCpu: + case SysClkRamLoad_Cpu: return t210EmcLoadCpu(); - // case HocClkPartLoad_GPU: - // #define gpu_samples_average 10 - // // nvIoctl(fd, NVGPU_GPU_IOCTL_PMU_GET_GPU_LOAD, &temp); - // GPU_Load_u = ((GPU_Load_u * (gpu_samples_average-1)) + temp) / gpu_samples_average; - // return GPU_Load_u / 10; default: - ASSERT_ENUM_VALID(SysClkPartLoad, loadSource); + ASSERT_ENUM_VALID(SysClkRamLoad, loadSource); } return 0; @@ -513,10 +496,15 @@ void Board::FetchHardwareInfos() switch(sku) { - case 2 ... 5: + case 2: + case 3: + case 5: g_socType = SysClkSocType_Mariko; break; + case 4: + g_socType = SysClkSocType_MarikoLite; + 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 index ae654d2f..21b9c227 100644 --- a/Source/sys-clk/sysmodule/src/board.h +++ b/Source/sys-clk/sysmodule/src/board.h @@ -51,7 +51,7 @@ class Board static void GetFreqList(SysClkModule module, std::uint32_t* outList, std::uint32_t maxCount, std::uint32_t* outCount); static std::uint32_t GetTemperatureMilli(SysClkThermalSensor sensor); static std::int32_t GetPowerMw(SysClkPowerSensor sensor); - static std::uint32_t GetPartLoad(SysClkPartLoad load); + static std::uint32_t GetRamLoad(SysClkRamLoad load); static SysClkSocType GetSocType(); protected: diff --git a/Source/sys-clk/sysmodule/src/clock_manager.cpp b/Source/sys-clk/sysmodule/src/clock_manager.cpp index bb338d7d..b82dd89d 100644 --- a/Source/sys-clk/sysmodule/src/clock_manager.cpp +++ b/Source/sys-clk/sysmodule/src/clock_manager.cpp @@ -24,7 +24,6 @@ * -------------------------------------------------------------------------- */ -#include "notification.h" #include "clock_manager.h" #include @@ -36,10 +35,6 @@ #define HOSPPC_HAS_BOOST (hosversionAtLeast(7,0,0)) -bool HAS_TDP_BEEN_FIRED = false; -bool HAS_EBL_BEEN_FIRED = false; -bool HAS_TT_BEEN_FIRED = false; - ClockManager *ClockManager::instance = NULL; ClockManager *ClockManager::GetInstance() @@ -233,92 +228,41 @@ void ClockManager::RefreshFreqTableRow(SysClkModule module) void ClockManager::Tick() { - - std::uint32_t mode = 0; - AppletOperationMode opMode = appletGetOperationMode(); - Result rc = apmExtGetCurrentPerformanceConfiguration(&mode); - ASSERT_RESULT_OK(rc, "apmExtGetCurrentPerformanceConfiguration"); - - - if(this->config->GetConfigValue(HocClkConfigValue_EMCDVFS)) { - - #define DEFAULT_FREQ_MHZ 1600 - #define DEFAULT_FREQ_MHZ_M 1862 - - int ram_mhz = Board::GetHz((SysClkModule)SysClkModule_MEM) / 1000000; - - if (Board::GetSocType() == SysClkSocType_Mariko) { - if(ram_mhz > DEFAULT_FREQ_MHZ_M) - set_sd1_voltage(this->config->GetConfigValue(HocClkConfigValue_EMCVdd2VoltageUV)); - else - set_sd1_voltage(this->config->GetConfigValue(HocClkConfigValue_EMCVdd2VoltageUVStockMariko)); - } else { - if(ram_mhz > DEFAULT_FREQ_MHZ) - set_sd1_voltage(this->config->GetConfigValue(HocClkConfigValue_EMCVdd2VoltageUV)); - else - set_sd1_voltage(this->config->GetConfigValue(HocClkConfigValue_EMCVdd2VoltageUVStockErista)); - } - } - - if(this->config->GetConfigValue(HocClkConfigValue_HandheldTDP) && opMode == AppletOperationMode_Handheld) { - if(Board::GetSocType() == SysClkSocType_MarikoLite) { - if(Board::GetPowerMw(SysClkPowerSensor_Avg) < -(int)this->config->GetConfigValue(HocClkConfigValue_LiteTDPLimit)) { - if(!HAS_TDP_BEEN_FIRED) - writeNotification("Horizon OC\nTDP has been activated"); - HAS_TDP_BEEN_FIRED = true; - ResetToStockClocks(); - return; - } else { - HAS_TDP_BEEN_FIRED = false; - } - } else { - if(Board::GetPowerMw(SysClkPowerSensor_Avg) < -(int)this->config->GetConfigValue(HocClkConfigValue_HandheldTDPLimit)) { - if(!HAS_TDP_BEEN_FIRED) - writeNotification("Horizon OC\nTDP has been activated"); - HAS_TDP_BEEN_FIRED = true; - ResetToStockClocks(); - return; - } else { - HAS_TDP_BEEN_FIRED = false; - } - } - } else if(opMode == AppletOperationMode_Console && this->config->GetConfigValue(HocClkConfigValue_EnforceBoardLimit)) { - if(Board::GetPowerMw(SysClkPowerSensor_Avg) < 0) { - if(!HAS_EBL_BEEN_FIRED) - writeNotification("Horizon OC\nBoard Limit has been exeeded"); - HAS_EBL_BEEN_FIRED = true; - ResetToStockClocks(); - return; - } else { - HAS_EBL_BEEN_FIRED = false; - } - } - - if(this->config->GetConfigValue(HocClkConfigValue_ThermalThrottle)) { - if(tmp451TempSoc() / 1000 > (int)this->config->GetConfigValue(HocClkConfigValue_ThermalThrottleThreshold)) { - if(!HAS_TT_BEEN_FIRED) - writeNotification("Horizon OC\nThermal Throttle has started"); - HAS_TT_BEEN_FIRED = true; - ResetToStockClocks(); - return; - } else { - HAS_TT_BEEN_FIRED = false; - } - } - 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; + std::uint32_t mode = 0; + + AppletOperationMode opMode = appletGetOperationMode(); + Result rc = apmExtGetCurrentPerformanceConfiguration(&mode); + ASSERT_RESULT_OK(rc, "apmExtGetCurrentPerformanceConfiguration"); + + if(this->config->GetConfigValue(HocClkConfigValue_HandheldTDP) && opMode == AppletOperationMode_Handheld) { + if(Board::GetSocType() == SysClkSocType_MarikoLite) { + if(Board::GetPowerMw(SysClkPowerSensor_Now) < -(int)this->config->GetConfigValue(HocClkConfigValue_LiteTDPLimit)) { + ResetToStockClocks(); + return; + } + } else { + if(Board::GetPowerMw(SysClkPowerSensor_Now) < -(int)this->config->GetConfigValue(HocClkConfigValue_HandheldTDPLimit)) { + ResetToStockClocks(); + return; + } + } + } if(apmExtIsBoostMode(mode) && !this->config->GetConfigValue(HocClkConfigValue_OverwriteBoostMode)) { ResetToStockClocks(); return; } - + if(((tmp451TempSoc() / 1000) > (int)this->config->GetConfigValue(HocClkConfigValue_ThermalThrottleThreshold)) && this->config->GetConfigValue(HocClkConfigValue_ThermalThrottle)) { + ResetToStockClocks(); + return; + } if(this->config->GetConfigValue(HocClkConfigValue_HandheldGovernor) && opMode == AppletOperationMode_Handheld) { } @@ -482,9 +426,9 @@ bool ClockManager::RefreshContext() } // ram load do not and should not force a refresh, hasChanged untouched - for (unsigned int loadSource = 0; loadSource < SysClkPartLoad_EnumMax; loadSource++) + for (unsigned int loadSource = 0; loadSource < SysClkRamLoad_EnumMax; loadSource++) { - this->context->partLoad[loadSource] = Board::GetPartLoad((SysClkPartLoad)loadSource); + this->context->ramLoad[loadSource] = Board::GetRamLoad((SysClkRamLoad)loadSource); } if (this->ConfigIntervalTimeout(SysClkConfigValue_CsvWriteIntervalMs, ns, &this->lastCsvWriteNs)) @@ -498,50 +442,4 @@ bool ClockManager::RefreshContext() void ClockManager::SetRNXRTMode(ReverseNXMode mode) { this->rnxSync->SetRTMode(mode); -} - -void ClockManager::set_sd1_voltage(uint32_t voltage_uv) -{ - // SD1 parameters - const u32 uv_step = 12500; - const u32 uv_min = 600000; - const u32 uv_max = 1237500; - const u8 volt_addr = 0x17; // MAX77620_REG_SD1 - const u8 volt_mask = 0x7F; // MAX77620_SD1_VOLT_MASK - - if (voltage_uv < uv_min || voltage_uv > uv_max) - return; - - u32 mult = (voltage_uv + uv_step - 1 - uv_min) / uv_step; - mult = mult & volt_mask; - - I2cSession session; - Result res = i2cOpenSession(&session, I2cDevice_Max77620Pmic); - if (R_FAILED(res)) { - return; - } - - u8 current_val = 0; - res = i2csessionSendAuto(&session, &volt_addr, 1, I2cTransactionOption_Start); - if (R_FAILED(res)) { - writeNotification("I2C write failed. This may be a hardware issue"); - i2csessionClose(&session); - return; - } - - res = i2csessionReceiveAuto(&session, ¤t_val, 1, I2cTransactionOption_Stop); - if (R_FAILED(res)) { - writeNotification("I2C write failed. This may be a hardware issue"); - i2csessionClose(&session); - return; - } - - // Mask in the new voltage bits, preserving other bits - u8 new_val = (current_val & ~volt_mask) | mult; - - // Write back register with START and STOP conditions - u8 write_buf[2] = {volt_addr, new_val}; - res = i2csessionSendAuto(&session, write_buf, sizeof(write_buf), I2cTransactionOption_All); - - i2csessionClose(&session); } \ No newline at end of file diff --git a/Source/sys-clk/sysmodule/src/clock_manager.h b/Source/sys-clk/sysmodule/src/clock_manager.h index 9fd92c00..c29681d8 100644 --- a/Source/sys-clk/sysmodule/src/clock_manager.h +++ b/Source/sys-clk/sysmodule/src/clock_manager.h @@ -70,7 +70,6 @@ class ClockManager bool ConfigIntervalTimeout(SysClkConfigValue intervalMsConfigValue, std::uint64_t ns, std::uint64_t* lastLogNs); void RefreshFreqTableRow(SysClkModule module); bool RefreshContext(); - void set_sd1_voltage(uint32_t voltage_uv); static ClockManager *instance; diff --git a/Source/sys-clk/sysmodule/src/config.cpp b/Source/sys-clk/sysmodule/src/config.cpp index 7faa4f2d..301515e3 100644 --- a/Source/sys-clk/sysmodule/src/config.cpp +++ b/Source/sys-clk/sysmodule/src/config.cpp @@ -15,8 +15,7 @@ * */ -/* - * -------------------------------------------------------------------------- +/* -------------------------------------------------------------------------- * "THE BEER-WARE LICENSE" (Revision 42): * , , * wrote this file. As long as you retain this notice you can do whatever you @@ -25,6 +24,7 @@ * -------------------------------------------------------------------------- */ + #include "config.h" #include #include @@ -197,24 +197,17 @@ bool Config::SetProfiles(std::uint64_t tid, SysClkTitleProfileList* profiles, bo 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); + // Use dynamic allocation + std::vector keys; + std::vector values; + keys.reserve(SysClkProfile_EnumMax * SysClkModule_EnumMax); + values.reserve(SysClkProfile_EnumMax * SysClkModule_EnumMax); + + std::uint32_t* mhz = &profiles->mhz[0]; + for(unsigned int profile = 0; profile < SysClkProfile_EnumMax; profile++) { for(unsigned int module = 0; module < SysClkModule_EnumMax; module++) @@ -223,34 +216,38 @@ bool Config::SetProfiles(std::uint64_t tid, SysClkTitleProfileList* profiles, bo { 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); + // Build key and value strings + std::string key = std::string(Board::GetProfileName((SysClkProfile)profile, false)) + + "_" + + Board::GetModuleName((SysClkModule)module, false); + std::string value = std::to_string(*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; + keys.push_back(key); + values.push_back(value); } - mhz++; } } - *ik = NULL; - *iv = NULL; + // Build pointer arrays + std::vector keyPointers; + std::vector valuePointers; + keyPointers.reserve(keys.size() + 1); + valuePointers.reserve(values.size() + 1); - if(!ini_putsection(section, (const char**)iniKeys, (const char**)iniValues, this->path.c_str())) + for(size_t i = 0; i < keys.size(); i++) { + keyPointers.push_back(keys[i].c_str()); + valuePointers.push_back(values[i].c_str()); + } + keyPointers.push_back(NULL); + valuePointers.push_back(NULL); + + if(!ini_putsection(section, keyPointers.data(), valuePointers.data(), this->path.c_str())) { return false; } - // Only actually apply changes in memory after a succesful save + // Only actually apply changes in memory after a successful save if(immediate) { mhz = &profiles->mhz[0]; @@ -431,46 +428,43 @@ 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]; + // Use dynamic allocation instead of fixed stack buffers + std::vector iniKeys; + std::vector iniValues; + + iniKeys.reserve(SysClkConfigValue_EnumMax + 1); + iniValues.reserve(SysClkConfigValue_EnumMax); for(unsigned int kval = 0; kval < SysClkConfigValue_EnumMax; kval++) { - if(!sysclkValidConfigValue((SysClkConfigValue)kval, configValues->values[kval]) || configValues->values[kval] == sysclkDefaultConfigValue((SysClkConfigValue)kval)) + 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++; + // Store as string in vector (automatically managed memory) + iniValues.push_back(std::to_string(configValues->values[kval])); + iniKeys.push_back(sysclkFormatConfigValue((SysClkConfigValue)kval, false)); } - *ik = NULL; - *iv = NULL; + // Null terminate + iniKeys.push_back(NULL); - if(!ini_putsection(CONFIG_VAL_SECTION, (const char**)iniKeys, (const char**)iniValues, this->path.c_str())) + // Build pointer array for ini function + std::vector valuePointers; + valuePointers.reserve(iniValues.size() + 1); + for(const auto& val : iniValues) { + valuePointers.push_back(val.c_str()); + } + valuePointers.push_back(NULL); + + if(!ini_putsection(CONFIG_VAL_SECTION, iniKeys.data(), valuePointers.data(), this->path.c_str())) { return false; } - // Only actually apply changes in memory after a succesful save + // Only actually apply changes in memory after a successful save if(immediate) { for(unsigned int kval = 0; kval < SysClkConfigValue_EnumMax; kval++) diff --git a/Source/sys-clk/overlay/lib/libultrahand/.gitmodules b/Source/sys-clk/sysmodule/src/emc.cpp similarity index 100% rename from Source/sys-clk/overlay/lib/libultrahand/.gitmodules rename to Source/sys-clk/sysmodule/src/emc.cpp diff --git a/Source/sys-clk/sysmodule/src/emc.h b/Source/sys-clk/sysmodule/src/emc.h new file mode 100644 index 00000000..e69de29b diff --git a/Source/sys-clk/sysmodule/src/emc_patcher.cpp b/Source/sys-clk/sysmodule/src/emc_patcher.cpp deleted file mode 100644 index 9e34bdac..00000000 --- a/Source/sys-clk/sysmodule/src/emc_patcher.cpp +++ /dev/null @@ -1,91 +0,0 @@ -#include "emc_patcher.h" -#include "file_utils.h" -#include "board.h" - - -#define MC_BASE 0x70019000 -#define EMC_BASE 0x7001B000 -#define MC_EMC_BASE_SIZE 0x1000 -#define EMC_TIMING_CONTROL_0 0x28 -#define EMC_RAS_0 0x34 -#define EMC_RAS_BIT_END 5 - -#define HOSSVC_HAS_MM (hosversionAtLeast(10,0,0)) - - -EMCpatcher* EMCpatcher::instance = nullptr; - -EMCpatcher* EMCpatcher::GetInstance() -{ - return instance; -} - -void EMCpatcher::Initialize() -{ - if (!instance) - { - instance = new EMCpatcher(); - FileUtils::LogLine("[emc] Initialized EMCpatcher"); - } -} - -Config *EMCpatcher::GetConfig() -{ - return this->config; -} - -void EMCpatcher::Exit() -{ - if (instance) - { - FileUtils::LogLine("[emc] Exiting EMCpatcher"); - delete instance; - instance = nullptr; - } -} - -EMCpatcher::EMCpatcher() -{ - this->config = Config::CreateDefault(); -} - - - -EMCpatcher::~EMCpatcher() -{ - delete this->config; -} - -void EMCpatcher::Run() -{ - std::scoped_lock lock{this->patcherMutex}; - this->config->Refresh(); - this->ApplyEMCPatch(); -} - - -void EMCpatcher::ApplyEMCPatch() -{ - // if(HOSSVC_HAS_MM) { // only for 10.0.0+, older versions need rewrites - // u64 mc_virt_addr = 0; - // u64 mc_out_size = 0; - // u64 emc_virt_addr = 0; - // u64 emc_out_size = 0; - // Result rc; - - // // rc = svcQueryMemoryMapping(&mc_virt_addr, &mc_out_size, MC_BASE, MC_EMC_BASE_SIZE); // map mc - // // ASSERT_RESULT_OK(rc, "svcQueryMemoryMapping"); - - // // rc = svcQueryMemoryMapping(&emc_virt_addr, &emc_out_size, EMC_BASE, MC_EMC_BASE_SIZE); // map emc - // // ASSERT_RESULT_OK(rc, "svcQueryMemoryMapping"); - - // write_reg64(EMC_BASE, EMC_RAS_0, 1); - - // write_reg64(EMC_BASE, EMC_TIMING_CONTROL_0, 0x1); // apply shadow regs - - - // // svcUnmapMemory((void *)mc_virt_addr, (void *)MC_BASE, MC_EMC_BASE_SIZE); // clean up - // // svcUnmapMemory((void *)emc_virt_addr, (void *)EMC_BASE, MC_EMC_BASE_SIZE); - - // } -} diff --git a/Source/sys-clk/sysmodule/src/emc_patcher.h b/Source/sys-clk/sysmodule/src/emc_patcher.h deleted file mode 100644 index f2f13935..00000000 --- a/Source/sys-clk/sysmodule/src/emc_patcher.h +++ /dev/null @@ -1,73 +0,0 @@ -#pragma once - -#include -#include -#include "config.h" -#include -#include "errors.h" - -// Read a 32-bit register via libnx SVC -static inline uint32_t read_reg64(uint64_t phys_addr, uint32_t offset) { - uint32_t value = 0; - Result rc = svcReadWriteRegister(&value, phys_addr + offset, 0, false); - if (R_FAILED(rc)) { - // Handle failure if needed - return 0; - } - return value; -} - -// Write a 32-bit register via libnx SVC -static inline void write_reg64(uint64_t phys_addr, uint32_t offset, uint32_t value) { - Result rc = svcReadWriteRegister(NULL, phys_addr + offset, value, true); - if (R_FAILED(rc)) { - // Handle failure if needed - } -} - -// Bitfield helper remains the same -static inline uint32_t set_bits(uint32_t reg_value, uint8_t start_bit, uint8_t end_bit, uint32_t value) -{ - if (end_bit < start_bit || end_bit > 31) - return reg_value; - - uint32_t mask = ((1u << (end_bit - start_bit + 1)) - 1u) << start_bit; - reg_value = (reg_value & ~mask) | ((value << start_bit) & mask); - return reg_value; -} - -/* Primary timings. */ -const std::array tRCD_values = {18, 17, 16, 15, 14, 13, 12, 11}; -const std::array tRP_values = {18, 17, 16, 15, 14, 13, 12, 11}; -const std::array tRAS_values = {42, 36, 34, 32, 30, 28, 26, 24, 22, 20}; - -/* Secondary timings. */ -const std::array tRRD_values = {10.0, 7.5, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0}; -const std::array tRFC_values = {140, 120, 100, 80, 60, 40}; -const std::array tRTW_values = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; /* Is this even correct? */ -const std::array tWTR_values = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; -const std::array tREFpb_values = {488, 732, 488 * 2, 488 * 3, 488 * 4, 488 * 6, 488 * 8}; /* TODO: Figure out if it's actually 8 and if this is even right. */ - -struct SOC_THERM_THERMCTL_LEVEL0_GROUP_CPU_0 { - -}; - -class EMCpatcher -{ -private: - static EMCpatcher* instance; - Config* config; - std::mutex patcherMutex; - -public: - static EMCpatcher* GetInstance(); - static void Initialize(); - Config *GetConfig(); - static void Exit(); - - EMCpatcher(); - ~EMCpatcher(); - - void Run(); - void ApplyEMCPatch(); -}; diff --git a/Source/sys-clk/sysmodule/src/ipc_service.cpp b/Source/sys-clk/sysmodule/src/ipc_service.cpp index c1ae6183..ba43f7d6 100644 --- a/Source/sys-clk/sysmodule/src/ipc_service.cpp +++ b/Source/sys-clk/sysmodule/src/ipc_service.cpp @@ -31,8 +31,6 @@ #include "file_utils.h" #include "errors.h" #include "clock_manager.h" -#include "emc_patcher.h" - IpcService::IpcService(ClockManager* clockMgr) { std::int32_t priority; @@ -191,9 +189,6 @@ Result IpcService::ServiceHandlerFunc(void* arg, const IpcServerRequest* r, u8* return ipcSrv->SetReverseNXRTMode(mode); } break; - case HocClkIpcCmd_UpdateEMCRegs: // Trigger, not data - return ipcSrv->PatchEmcRegs(); - break; } return SYSCLK_ERROR(Generic); @@ -230,7 +225,6 @@ Result IpcService::Exit() return 0; } - Result IpcService::GetProfileCount(std::uint64_t* tid, std::uint8_t* out_count) { Config* config = this->clockMgr->GetConfig(); @@ -269,7 +263,7 @@ Result IpcService::SetProfiles(SysClkIpc_SetProfiles_Args* args) if(!config->SetProfiles(args->tid, &profiles, true)) { - return SYSCLK_ERROR(ConfigSaveFailed); // 0x584 + return SYSCLK_ERROR(ConfigSaveFailed); } return 0; @@ -351,9 +345,3 @@ Result IpcService::SetReverseNXRTMode(ReverseNXMode mode) { ClockManager::GetInstance()->SetRNXRTMode(mode); return 0; } - - -Result IpcService::PatchEmcRegs() { - EMCpatcher::GetInstance()->Run(); - return 0; -} diff --git a/Source/sys-clk/sysmodule/src/ipc_service.h b/Source/sys-clk/sysmodule/src/ipc_service.h index 163aa29c..28fa5124 100644 --- a/Source/sys-clk/sysmodule/src/ipc_service.h +++ b/Source/sys-clk/sysmodule/src/ipc_service.h @@ -54,8 +54,6 @@ class IpcService Result SetConfigValues(SysClkConfigValueList* configValues); Result GetFreqList(SysClkIpc_GetFreqList_Args* args, std::uint32_t* out_list, std::size_t size, std::uint32_t* out_count); Result SetReverseNXRTMode(ReverseNXMode mode); - - Result PatchEmcRegs(); bool running; Thread thread; diff --git a/Source/sys-clk/sysmodule/src/main.cpp b/Source/sys-clk/sysmodule/src/main.cpp index d9e71919..5c10a49f 100644 --- a/Source/sys-clk/sysmodule/src/main.cpp +++ b/Source/sys-clk/sysmodule/src/main.cpp @@ -38,9 +38,7 @@ #include "clock_manager.h" #include "ipc_service.h" #include "fancontrol.h" -#include "emc_patcher.h" - -#define INNER_HEAP_SIZE 0x50000 +#define INNER_HEAP_SIZE 0x30000 extern "C" { @@ -68,22 +66,12 @@ extern "C" void __appInit(void) { - Result rc; if (R_FAILED(smInitialize())) { fatalThrow(MAKERESULT(Module_Libnx, LibnxError_InitFail_SM)); } - rc = fanInitialize(); - if (R_FAILED(rc)) - diagAbortWithResult(MAKERESULT(Module_Libnx, LibnxError_ShouldNotHappen)); - - rc = i2cInitialize(); - if (R_FAILED(rc)) - diagAbortWithResult(MAKERESULT(Module_Libnx, LibnxError_ShouldNotHappen)); - - - rc = setsysInitialize(); + Result rc = setsysInitialize(); if (R_SUCCEEDED(rc)) { SetSysFirmwareVersion fw; @@ -92,7 +80,14 @@ extern "C" hosversionSet(MAKEHOSVERSION(fw.major, fw.minor, fw.micro)); setsysExit(); } - + + rc = fanInitialize(); + if (R_FAILED(rc)) + diagAbortWithResult(MAKERESULT(Module_Libnx, LibnxError_ShouldNotHappen)); + + rc = i2cInitialize(); + if (R_FAILED(rc)) + diagAbortWithResult(MAKERESULT(Module_Libnx, LibnxError_ShouldNotHappen)); } void __appExit(void) @@ -101,8 +96,7 @@ extern "C" fanExit(); i2cExit(); fsExit(); - fsdevUnmountAll(); - smExit(); + fsdevUnmountAll(); } } @@ -125,7 +119,7 @@ int main(int argc, char** argv) ClockManager* clockMgr = new ClockManager(); IpcService* ipcSrv = new IpcService(clockMgr); - FileUtils::LogLine("Starting Horizon OC Sysmodule"); + FileUtils::LogLine("Ready"); clockMgr->SetRunning(true); clockMgr->GetConfig()->SetEnabled(true); diff --git a/Source/sys-clk/sysmodule/src/maxXXXXX.h b/Source/sys-clk/sysmodule/src/maxXXXXX.h deleted file mode 100644 index 2da06670..00000000 --- a/Source/sys-clk/sysmodule/src/maxXXXXX.h +++ /dev/null @@ -1,691 +0,0 @@ -/* - * Copyright (c) Souldbminer and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - - -/* - * Defining registers address and its bit definitions of MAX77620 and MAX20024 - * - * Copyright (c) 2019-2020 CTCaer - * - * 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. - */ - -#include - -#ifndef MAX77XXX_H -#define MAX77XXX_H - - -#define MAX17050_BOARD_CGAIN 2 /* Actual: 1.99993 */ -#define MAX17050_BOARD_SNS_RESISTOR_UOHM 5000 /* 0.005 Ohm */ - -#define MAX17050_STATUS_BattAbsent BIT(3) - -/* Consider RepCap which is less then 10 units below FullCAP full */ -#define MAX17050_FULL_THRESHOLD 10 - -#define MAX17050_CHARACTERIZATION_DATA_SIZE 48 - -#define MAXIM17050_I2C_ADDR 0x36 - -enum MAX17050_reg { - MAX17050_STATUS = 0x00, - MAX17050_VALRT_Th = 0x01, - MAX17050_TALRT_Th = 0x02, - MAX17050_SALRT_Th = 0x03, - MAX17050_AtRate = 0x04, - MAX17050_RepCap = 0x05, - MAX17050_RepSOC = 0x06, - MAX17050_Age = 0x07, - MAX17050_TEMP = 0x08, - MAX17050_VCELL = 0x09, - MAX17050_Current = 0x0A, - MAX17050_AvgCurrent = 0x0B, - - MAX17050_SOC = 0x0D, - MAX17050_AvSOC = 0x0E, - MAX17050_RemCap = 0x0F, - MAX17050_FullCAP = 0x10, - MAX17050_TTE = 0x11, - MAX17050_QRTbl00 = 0x12, - MAX17050_FullSOCThr = 0x13, - MAX17050_RSLOW = 0x14, - - MAX17050_AvgTA = 0x16, - MAX17050_Cycles = 0x17, - MAX17050_DesignCap = 0x18, - MAX17050_AvgVCELL = 0x19, - MAX17050_MinMaxTemp = 0x1A, - MAX17050_MinMaxVolt = 0x1B, - MAX17050_MinMaxCurr = 0x1C, - MAX17050_CONFIG = 0x1D, - MAX17050_ICHGTerm = 0x1E, - MAX17050_AvCap = 0x1F, - MAX17050_ManName = 0x20, - MAX17050_DevName = 0x21, - MAX17050_QRTbl10 = 0x22, - MAX17050_FullCAPNom = 0x23, - MAX17050_TempNom = 0x24, - MAX17050_TempLim = 0x25, - MAX17050_TempHot = 0x26, - MAX17050_AIN = 0x27, - MAX17050_LearnCFG = 0x28, - MAX17050_FilterCFG = 0x29, - MAX17050_RelaxCFG = 0x2A, - MAX17050_MiscCFG = 0x2B, - MAX17050_TGAIN = 0x2C, - MAX17050_TOFF = 0x2D, - MAX17050_CGAIN = 0x2E, - MAX17050_COFF = 0x2F, - - MAX17050_QRTbl20 = 0x32, - MAX17050_SOC_empty = 0x33, - MAX17050_T_empty = 0x34, - MAX17050_FullCAP0 = 0x35, - MAX17050_LAvg_empty = 0x36, - MAX17050_FCTC = 0x37, - MAX17050_RCOMP0 = 0x38, - MAX17050_TempCo = 0x39, - MAX17050_V_empty = 0x3A, - MAX17050_K_empty0 = 0x3B, - MAX17050_TaskPeriod = 0x3C, - MAX17050_FSTAT = 0x3D, - MAX17050_TIMER = 0x3E, - MAX17050_SHDNTIMER = 0x3F, - - MAX17050_QRTbl30 = 0x42, - - MAX17050_dQacc = 0x45, - MAX17050_dPacc = 0x46, - - MAX17050_VFSOC0 = 0x48, - - Max17050_QH0 = 0x4C, - MAX17050_QH = 0x4D, - MAX17050_QL = 0x4E, - - MAX17050_MinVolt = 0x50, // Custom ID. Not to be sent to i2c. - MAX17050_MaxVolt = 0x51, // Custom ID. Not to be sent to i2c. - - MAX17050_VFSOC0Enable = 0x60, - MAX17050_MODELEnable1 = 0x62, - MAX17050_MODELEnable2 = 0x63, - - MAX17050_MODELChrTbl = 0x80, - - MAX17050_OCV = 0xEE, - - MAX17050_OCVInternal = 0xFB, - - MAX17050_VFSOC = 0xFF, -}; - -#define MAX77620_I2C_ADDR 0x3C - -/* GLOBAL, PMIC, GPIO, FPS, ONOFFC, CID Registers */ -#define MAX77620_REG_CNFGGLBL1 0x00 -#define MAX77620_CNFGGLBL1_LBRSTEN BIT(0) -#define MAX77620_CNFGGLBL1_LBDAC_MASK 0x0E -#define MAX77620_CNFGGLBL1_LBDAC_2700 (0 << 1) -#define MAX77620_CNFGGLBL1_LBDAC_2800 (1 << 1) -#define MAX77620_CNFGGLBL1_LBDAC_2900 (2 << 1) -#define MAX77620_CNFGGLBL1_LBDAC_3000 (3 << 1) -#define MAX77620_CNFGGLBL1_LBDAC_3100 (4 << 1) -#define MAX77620_CNFGGLBL1_LBDAC_3200 (5 << 1) -#define MAX77620_CNFGGLBL1_LBDAC_3300 (6 << 1) -#define MAX77620_CNFGGLBL1_LBDAC_3400 (7 << 1) -#define MAX77620_CNFGGLBL1_LBHYST_100 (0 << 4) -#define MAX77620_CNFGGLBL1_LBHYST_200 (1 << 4) -#define MAX77620_CNFGGLBL1_LBHYST_300 (2 << 4) -#define MAX77620_CNFGGLBL1_LBHYST_400 (3 << 4) -#define MAX77620_CNFGGLBL1_MPPLD BIT(6) -#define MAX77620_CNFGGLBL1_LBDAC_EN BIT(7) - -#define MAX77620_REG_CNFGGLBL2 0x01 -#define MAX77620_TWD_MASK 0x3 -#define MAX77620_TWD_2s 0x0 -#define MAX77620_TWD_16s 0x1 -#define MAX77620_TWD_64s 0x2 -#define MAX77620_TWD_128s 0x3 -#define MAX77620_WDTEN BIT(2) -#define MAX77620_WDTSLPC BIT(3) -#define MAX77620_WDTOFFC BIT(4) -#define MAX77620_GLBL_LPM BIT(5) -#define MAX77620_I2CTWD_MASK 0xC0 -#define MAX77620_I2CTWD_DISABLED 0x00 -#define MAX77620_I2CTWD_1_33ms 0x40 -#define MAX77620_I2CTWD_35_7ms 0x80 -#define MAX77620_I2CTWD_41_7ms 0xC0 - -#define MAX77620_REG_CNFGGLBL3 0x02 -#define MAX77620_WDTC_MASK 0x3 - -#define MAX77620_REG_CNFG1_32K 0x03 -#define MAX77620_CNFG1_PWR_MD_32K_MASK 0x3 -#define MAX77620_CNFG1_32K_OUT0_EN BIT(2) -#define MAX77620_CNFG1_32KLOAD_MASK 0x30 -#define MAX77620_CNFG1_32K_OK BIT(7) - -#define MAX77620_REG_CNFGBBC 0x04 -#define MAX77620_CNFGBBC_ENABLE BIT(0) -#define MAX77620_CNFGBBC_CURRENT_MASK 0x06 -#define MAX77620_CNFGBBC_CURRENT_SHIFT 1 -#define MAX77620_CNFGBBC_VOLTAGE_MASK 0x18 -#define MAX77620_CNFGBBC_VOLTAGE_SHIFT 3 -#define MAX77620_CNFGBBC_LOW_CURRENT_DISABLE BIT(5) -#define MAX77620_CNFGBBC_RESISTOR_MASK 0xC0 -#define MAX77620_CNFGBBC_RESISTOR_SHIFT 6 -#define MAX77620_CNFGBBC_RESISTOR_100 (0 << MAX77620_CNFGBBC_RESISTOR_SHIFT) -#define MAX77620_CNFGBBC_RESISTOR_1K (1 << MAX77620_CNFGBBC_RESISTOR_SHIFT) -#define MAX77620_CNFGBBC_RESISTOR_3K (2 << MAX77620_CNFGBBC_RESISTOR_SHIFT) -#define MAX77620_CNFGBBC_RESISTOR_6K (3 << MAX77620_CNFGBBC_RESISTOR_SHIFT) - -#define MAX77620_REG_IRQTOP 0x05 -#define MAX77620_REG_IRQTOPM 0x0D -#define MAX77620_IRQ_TOP_ONOFF_MASK BIT(1) -#define MAX77620_IRQ_TOP_32K_MASK BIT(2) -#define MAX77620_IRQ_TOP_RTC_MASK BIT(3) -#define MAX77620_IRQ_TOP_GPIO_MASK BIT(4) -#define MAX77620_IRQ_TOP_LDO_MASK BIT(5) -#define MAX77620_IRQ_TOP_SD_MASK BIT(6) -#define MAX77620_IRQ_TOP_GLBL_MASK BIT(7) - -#define MAX77620_REG_INTLBT 0x06 -#define MAX77620_REG_INTENLBT 0x0E -#define MAX77620_IRQ_GLBLM_MASK BIT(0) -#define MAX77620_IRQ_TJALRM2_MASK BIT(1) -#define MAX77620_IRQ_TJALRM1_MASK BIT(2) -#define MAX77620_IRQ_LBM_MASK BIT(3) - -#define MAX77620_REG_IRQSD 0x07 -#define MAX77620_REG_IRQMASKSD 0x0F -#define MAX77620_IRQSD_PFI_SD3 BIT(4) -#define MAX77620_IRQSD_PFI_SD2 BIT(5) -#define MAX77620_IRQSD_PFI_SD1 BIT(6) -#define MAX77620_IRQSD_PFI_SD0 BIT(7) - -#define MAX77620_REG_IRQ_LVL2_L0_7 0x08 // LDO number that irq occurred. -#define MAX77620_REG_IRQ_MSK_L0_7 0x10 -#define MAX77620_REG_IRQ_LVL2_L8 \ - 0x09 // LDO number that irq occurred. Only bit0: LDO8 is valid. -#define MAX77620_REG_IRQ_MSK_L8 0x11 -#define MAX77620_REG_IRQ_LVL2_GPIO 0x0A // Edge detection interrupt. - -#define MAX77620_REG_ONOFFIRQ 0x0B -#define MAX77620_REG_ONOFFIRQM 0x12 -#define MAX77620_ONOFFIRQ_MRWRN BIT(0) -#define MAX77620_ONOFFIRQ_EN0_1SEC BIT(1) -#define MAX77620_ONOFFIRQ_EN0_F BIT(2) -#define MAX77620_ONOFFIRQ_EN0_R BIT(3) -#define MAX77620_ONOFFIRQ_LID_F BIT(4) -#define MAX77620_ONOFFIRQ_LID_R BIT(5) -#define MAX77620_ONOFFIRQ_ACOK_F BIT(6) -#define MAX77620_ONOFFIRQ_ACOK_R BIT(7) - -#define MAX77620_REG_NVERC 0x0C // Shutdown reason (non-volatile). -#define MAX77620_NVERC_SHDN BIT(0) -#define MAX77620_NVERC_WTCHDG BIT(1) -#define MAX77620_NVERC_HDRST BIT(2) -#define MAX77620_NVERC_TOVLD BIT(3) -#define MAX77620_NVERC_MBLSD BIT(4) -#define MAX77620_NVERC_MBO BIT(5) -#define MAX77620_NVERC_MBU BIT(6) -#define MAX77620_NVERC_RSTIN BIT(7) - -#define MAX77620_REG_STATLBT 0x13 -#define MAX77620_REG_STATSD 0x14 - -#define MAX77620_REG_ONOFFSTAT 0x15 -#define MAX77620_ONOFFSTAT_LID BIT(0) -#define MAX77620_ONOFFSTAT_ACOK BIT(1) -#define MAX77620_ONOFFSTAT_EN0 BIT(2) - -/* SD and LDO Registers */ -#define MAX77620_REG_SD0 0x16 -#define MAX77620_REG_SD1 0x17 -#define MAX77620_REG_SD2 0x18 -#define MAX77620_REG_SD3 0x19 -#define MAX77620_REG_SD4 0x1A -#define MAX77620_REG_DVSSD0 0x1B -#define MAX77620_REG_DVSSD1 0x1C -#define MAX77620_SDX_VOLT_MASK 0xFF -#define MAX77620_SD0_VOLT_MASK 0x7F // Max is 0x40. -#define MAX77620_SD1_VOLT_MASK 0x7F // Max is 0x4C. -#define MAX77620_LDO_VOLT_MASK 0x3F - -#define MAX77620_REG_SD0_CFG 0x1D -#define MAX77620_REG_SD1_CFG 0x1E -#define MAX77620_REG_SD2_CFG 0x1F -#define MAX77620_REG_SD3_CFG 0x20 -#define MAX77620_REG_SD4_CFG 0x21 -#define MAX77620_SD_SR_MASK 0xC0 -#define MAX77620_SD_SR_SHIFT 6 -#define MAX77620_SD_POWER_MODE_MASK 0x30 -#define MAX77620_SD_POWER_MODE_SHIFT 4 -#define MAX77620_SD_CFG1_ADE_MASK BIT(3) -#define MAX77620_SD_CFG1_ADE_DISABLE 0 -#define MAX77620_SD_CFG1_ADE_ENABLE BIT(3) -#define MAX77620_SD_FPWM_MASK 0x04 -#define MAX77620_SD_FPWM_SHIFT 2 -#define MAX77620_SD_FSRADE_MASK 0x01 -#define MAX77620_SD_FSRADE_SHIFT 0 -#define MAX77620_SD_CFG1_FPWM_SD_MASK BIT(2) -#define MAX77620_SD_CFG1_FPWM_SD_SKIP 0 -#define MAX77620_SD_CFG1_FPWM_SD_FPWM BIT(2) -#define MAX77620_SD_CFG1_MPOK_MASK BIT(1) -#define MAX77620_SD_CFG1_FSRADE_SD_MASK BIT(0) -#define MAX77620_SD_CFG1_FSRADE_SD_DISABLE 0 -#define MAX77620_SD_CFG1_FSRADE_SD_ENABLE BIT(0) - -#define MAX77620_REG_SD_CFG2 0x22 -#define MAX77620_SD_CNF2_RSVD BIT(0) -#define MAX77620_SD_CNF2_ROVS_EN_SD1 BIT(1) -#define MAX77620_SD_CNF2_ROVS_EN_SD0 BIT(2) - -#define MAX77620_REG_LDO0_CFG 0x23 -#define MAX77620_REG_LDO0_CFG2 0x24 -#define MAX77620_REG_LDO1_CFG 0x25 -#define MAX77620_REG_LDO1_CFG2 0x26 -#define MAX77620_REG_LDO2_CFG 0x27 -#define MAX77620_REG_LDO2_CFG2 0x28 -#define MAX77620_REG_LDO3_CFG 0x29 -#define MAX77620_REG_LDO3_CFG2 0x2A -#define MAX77620_REG_LDO4_CFG 0x2B -#define MAX77620_REG_LDO4_CFG2 0x2C -#define MAX77620_REG_LDO5_CFG 0x2D -#define MAX77620_REG_LDO5_CFG2 0x2E -#define MAX77620_REG_LDO6_CFG 0x2F -#define MAX77620_REG_LDO6_CFG2 0x30 -#define MAX77620_REG_LDO7_CFG 0x31 -#define MAX77620_REG_LDO7_CFG2 0x32 -#define MAX77620_REG_LDO8_CFG 0x33 -#define MAX77620_REG_LDO8_CFG2 0x34 -/*! LDO CFG */ -#define MAX77620_LDO_POWER_MODE_SHIFT 6 -#define MAX77620_LDO_POWER_MODE_MASK (3 << MAX77620_LDO_POWER_MODE_SHIFT) -#define MAX77620_POWER_MODE_NORMAL 3 -#define MAX77620_POWER_MODE_LPM 2 -#define MAX77620_POWER_MODE_GLPM 1 -#define MAX77620_POWER_MODE_DISABLE 0 -/*! LDO CFG2 */ -#define MAX77620_LDO_CFG2_SS_MASK (1 << 0) -#define MAX77620_LDO_CFG2_SS_FAST (0 << 0) -#define MAX77620_LDO_CFG2_SS_SLOW (1 << 0) -#define MAX77620_LDO_CFG2_ADE_MASK (1 << 1) -#define MAX77620_LDO_CFG2_ADE_DISABLE (0 << 1) -#define MAX77620_LDO_CFG2_ADE_ENABLE (1 << 1) -#define MAX77620_LDO_CFG2_MPOK_MASK BIT(2) -#define MAX77620_LDO_CFG2_POK_MASK BIT(3) -#define MAX77620_LDO_CFG2_COMP_SHIFT 4 -#define MAX77620_LDO_CFG2_COMP_MASK (3 << MAX77620_LDO_COMP_SHIFT) -#define MAX77620_LDO_CFG2_COMP_SLOW 3 -#define MAX77620_LDO_CFG2_COMP_MID_SLOW 2 -#define MAX77620_LDO_CFG2_COMP_MID_FAST 1 -#define MAX77620_LDO_CFG2_COMP_FAST 0 -#define MAX77620_LDO_CFG2_ALPM_EN_MASK BIT(6) -#define MAX77620_LDO_CFG2_OVCLMP_MASK BIT(7) - -#define MAX77620_REG_LDO_CFG3 0x35 -#define MAX77620_LDO_BIAS_EN BIT(0) -#define MAX77620_TRACK4_SHIFT 5 -#define MAX77620_TRACK4_MASK (1 << MAX77620_TRACK4_SHIFT) - -#define MAX77620_REG_GPIO0 0x36 -#define MAX77620_REG_GPIO1 0x37 -#define MAX77620_REG_GPIO2 0x38 -#define MAX77620_REG_GPIO3 0x39 -#define MAX77620_REG_GPIO4 0x3A -#define MAX77620_REG_GPIO5 0x3B -#define MAX77620_REG_GPIO6 0x3C -#define MAX77620_REG_GPIO7 0x3D -#define MAX77620_CNFG_GPIO_DRV_MASK (1 << 0) -#define MAX77620_CNFG_GPIO_DRV_PUSHPULL (1 << 0) -#define MAX77620_CNFG_GPIO_DRV_OPENDRAIN (0 << 0) -#define MAX77620_CNFG_GPIO_DIR_MASK (1 << 1) -#define MAX77620_CNFG_GPIO_DIR_INPUT (1 << 1) -#define MAX77620_CNFG_GPIO_DIR_OUTPUT (0 << 1) -#define MAX77620_CNFG_GPIO_INPUT_VAL_MASK (1 << 2) -#define MAX77620_CNFG_GPIO_OUTPUT_VAL_MASK (1 << 3) -#define MAX77620_CNFG_GPIO_OUTPUT_VAL_HIGH (1 << 3) -#define MAX77620_CNFG_GPIO_OUTPUT_VAL_LOW (0 << 3) -#define MAX77620_CNFG_GPIO_INT_MASK (0x3 << 4) -#define MAX77620_CNFG_GPIO_INT_FALLING (1 << 4) -#define MAX77620_CNFG_GPIO_INT_RISING (1 << 5) -#define MAX77620_CNFG_GPIO_DBNC_MASK (0x3 << 6) -#define MAX77620_CNFG_GPIO_DBNC_None (0x0 << 6) -#define MAX77620_CNFG_GPIO_DBNC_8ms (0x1 << 6) -#define MAX77620_CNFG_GPIO_DBNC_16ms (0x2 << 6) -#define MAX77620_CNFG_GPIO_DBNC_32ms (0x3 << 6) -#define MAX77620_GPIO_OUTPUT_DISABLE 0 -#define MAX77620_GPIO_OUTPUT_ENABLE 1 - -#define MAX77620_REG_PUE_GPIO 0x3E // Gpio Pullup resistor enable. -#define MAX77620_REG_PDE_GPIO 0x3F // Gpio Pulldown resistor enable. - -#define MAX77620_REG_AME_GPIO \ - 0x40 // Gpio pinmuxing. Clear bits are Standard GPIO. - -#define MAX77620_REG_ONOFFCNFG1 0x41 -#define MAX20024_ONOFFCNFG1_CLRSE 0x18 -#define MAX77620_ONOFFCNFG1_PWR_OFF BIT(1) -#define MAX77620_ONOFFCNFG1_SLPEN BIT(2) -#define MAX77620_ONOFFCNFG1_MRT_SHIFT 0x3 -#define MAX77620_ONOFFCNFG1_MRT_MASK 0x38 -#define MAX77620_ONOFFCNFG1_RSVD BIT(6) -#define MAX77620_ONOFFCNFG1_SFT_RST BIT(7) - -#define MAX77620_REG_ONOFFCNFG2 0x42 -#define MAX77620_ONOFFCNFG2_WK_EN0 BIT(0) -#define MAX77620_ONOFFCNFG2_WK_ALARM2 BIT(1) -#define MAX77620_ONOFFCNFG2_WK_ALARM1 BIT(2) -#define MAX77620_ONOFFCNFG2_WK_MBATT \ - BIT(3) // MBATT event generates a wakeup signal. use it in android/l4t? -#define MAX77620_ONOFFCNFG2_WK_ACOK BIT(4) -#define MAX77620_ONOFFCNFG2_SLP_LPM_MSK BIT(5) -#define MAX77620_ONOFFCNFG2_WD_RST_WK BIT(6) -#define MAX77620_ONOFFCNFG2_SFT_RST_WK BIT(7) - -/* FPS Registers */ -#define MAX77620_REG_FPS_CFG0 0x43 // FPS0. -#define MAX77620_REG_FPS_CFG1 0x44 // FPS1. -#define MAX77620_REG_FPS_CFG2 0x45 // FPS2. -#define MAX77620_FPS_ENFPS_SW_MASK 0x01 -#define MAX77620_FPS_ENFPS_SW 0x01 -#define MAX77620_FPS_EN_SRC_SHIFT 1 -#define MAX77620_FPS_EN_SRC_MASK 0x06 -#define MAX77620_FPS_TIME_PERIOD_SHIFT 3 -#define MAX77620_FPS_TIME_PERIOD_MASK 0x38 - -#define MAX77620_REG_FPS_LDO0 0x46 -#define MAX77620_REG_FPS_LDO1 0x47 -#define MAX77620_REG_FPS_LDO2 0x48 -#define MAX77620_REG_FPS_LDO3 0x49 -#define MAX77620_REG_FPS_LDO4 0x4A -#define MAX77620_REG_FPS_LDO5 0x4B -#define MAX77620_REG_FPS_LDO6 0x4C -#define MAX77620_REG_FPS_LDO7 0x4D -#define MAX77620_REG_FPS_LDO8 0x4E -#define MAX77620_REG_FPS_SD0 0x4F -#define MAX77620_REG_FPS_SD1 0x50 -#define MAX77620_REG_FPS_SD2 0x51 -#define MAX77620_REG_FPS_SD3 0x52 -#define MAX77620_REG_FPS_SD4 0x53 -#define MAX77620_REG_FPS_GPIO1 0x54 -#define MAX77620_REG_FPS_GPIO2 0x55 -#define MAX77620_REG_FPS_GPIO3 0x56 -#define MAX77620_REG_FPS_RSO 0x57 -#define MAX77620_FPS_PD_PERIOD_SHIFT 0 -#define MAX77620_FPS_PD_PERIOD_MASK 0x07 -#define MAX77620_FPS_PU_PERIOD_SHIFT 3 -#define MAX77620_FPS_PU_PERIOD_MASK 0x38 -#define MAX77620_FPS_SRC_SHIFT 6 -#define MAX77620_FPS_SRC_MASK 0xC0 - -#define MAX77620_FPS_COUNT 3 -#define MAX77620_FPS_PERIOD_MIN_US 40 -#define MAX77620_FPS_PERIOD_MAX_US 2560 - -#define MAX77620_REG_CID0 0x58 -#define MAX77620_REG_CID1 0x59 -#define MAX77620_REG_CID2 0x5A -#define MAX77620_REG_CID3 0x5B -#define MAX77620_REG_CID4 0x5C // OTP version. -#define MAX77620_REG_CID5 0x5D // ES version. -#define MAX77620_CID_DIDO_MASK 0xF -#define MAX77620_CID_DIDO_SHIFT 0 -#define MAX77620_CID_DIDM_MASK 0xF0 -#define MAX77620_CID_DIDM_SHIFT 4 - -/* Device Identification Metal */ -#define MAX77620_CID5_DIDM(n) (((n) >> 4) & 0xF) -/* Device Indentification OTP */ -#define MAX77620_CID5_DIDO(n) ((n) & 0xF) - -#define MAX77620_REG_DVSSD4 0x5E -#define MAX20024_REG_MAX_ADD 0x70 - -#define MAX77620_IRQ_LVL2_GPIO_EDGE0 BIT(0) -#define MAX77620_IRQ_LVL2_GPIO_EDGE1 BIT(1) -#define MAX77620_IRQ_LVL2_GPIO_EDGE2 BIT(2) -#define MAX77620_IRQ_LVL2_GPIO_EDGE3 BIT(3) -#define MAX77620_IRQ_LVL2_GPIO_EDGE4 BIT(4) -#define MAX77620_IRQ_LVL2_GPIO_EDGE5 BIT(5) -#define MAX77620_IRQ_LVL2_GPIO_EDGE6 BIT(6) -#define MAX77620_IRQ_LVL2_GPIO_EDGE7 BIT(7) - -/* Interrupts */ -enum { - MAX77620_IRQ_TOP_GLBL, /* Low-Battery */ - MAX77620_IRQ_TOP_SD, /* SD power fail */ - MAX77620_IRQ_TOP_LDO, /* LDO power fail */ - MAX77620_IRQ_TOP_GPIO, /* TOP GPIO internal int to MAX77620 */ - MAX77620_IRQ_TOP_RTC, /* RTC */ - MAX77620_IRQ_TOP_32K, /* 32kHz oscillator */ - MAX77620_IRQ_TOP_ONOFF, /* ON/OFF oscillator */ - MAX77620_IRQ_LBT_MBATLOW, /* Thermal alarm status, > 120C */ - MAX77620_IRQ_LBT_TJALRM1, /* Thermal alarm status, > 120C */ - MAX77620_IRQ_LBT_TJALRM2, /* Thermal alarm status, > 140C */ -}; - -/* GPIOs */ -enum { - MAX77620_GPIO0, - MAX77620_GPIO1, - MAX77620_GPIO2, - MAX77620_GPIO3, - MAX77620_GPIO4, - MAX77620_GPIO5, - MAX77620_GPIO6, - MAX77620_GPIO7, - MAX77620_GPIO_NR, -}; - -/* FPS Source */ -enum max77620_fps_src { - MAX77620_FPS_SRC_0, - MAX77620_FPS_SRC_1, - MAX77620_FPS_SRC_2, - MAX77620_FPS_SRC_NONE, - MAX77620_FPS_SRC_DEF, -}; - -#define MAX77812_PHASE31_CPU_I2C_ADDR \ - 0x31 // High power GPU. 2 Outputs: 3-phase M1 + 1-phase M4. -#define MAX77812_PHASE211_CPU_I2C_ADDR \ - 0x33 // Low power GPU. 3 Outputs: 2-phase M1 + 1-phase M3 + 1-phase M4. - -#define MAX77812_REG_RSET 0x00 -#define MAX77812_REG_INT_SRC 0x01 -#define MAX77812_REG_INT_SRC_M 0x02 -#define MAX77812_REG_TOPSYS_INT 0x03 -#define MAX77812_REG_TOPSYS_INT_M 0x04 -#define MAX77812_REG_TOPSYS_STAT 0x05 -#define MAX77812_REG_EN_CTRL 0x06 -#define MAX77812_EN_CTRL_ENABLE 1 -#define MAX77812_EN_CTRL_EN_M1_SHIFT 0 -#define MAX77812_EN_CTRL_EN_M1_MASK (1 << MAX77812_EN_CTRL_EN_M1_SHIFT) -#define MAX77812_EN_CTRL_EN_M2_SHIFT 2 -#define MAX77812_EN_CTRL_EN_M2_MASK (1 << MAX77812_EN_CTRL_EN_M2_SHIFT) -#define MAX77812_EN_CTRL_EN_M3_SHIFT 4 -#define MAX77812_EN_CTRL_EN_M3_MASK (1 << MAX77812_EN_CTRL_EN_M3_SHIFT) -#define MAX77812_EN_CTRL_EN_M4_SHIFT 6 -#define MAX77812_EN_CTRL_EN_M4_MASK (1 << MAX77812_EN_CTRL_EN_M4_SHIFT) -#define MAX77812_REG_STUP_DLY2 0x07 -#define MAX77812_REG_STUP_DLY3 0x08 -#define MAX77812_REG_STUP_DLY4 0x09 -#define MAX77812_REG_SHDN_DLY1 0x0A -#define MAX77812_REG_SHDN_DLY2 0x0B -#define MAX77812_REG_SHDN_DLY3 0x0C -#define MAX77812_REG_SHDN_DLY4 0x0D -#define MAX77812_REG_WDTRSTB_DEB 0x0E -#define MAX77812_REG_GPI_FUNC 0x0F -#define MAX77812_REG_GPI_DEB1 0x10 -#define MAX77812_REG_GPI_DEB2 0x11 -#define MAX77812_REG_GPI_PD_CTRL 0x12 -#define MAX77812_REG_PROT_CFG 0x13 -#define MAX77812_REG_VERSION 0x14 -#define MAX77812_REG_I2C_CFG 0x15 -#define MAX77812_REG_BUCK_INT 0x20 -#define MAX77812_REG_BUCK_INT_M 0x21 -#define MAX77812_REG_BUCK_STAT 0x22 -#define MAX77812_REG_M1_VOUT 0x23 // GPU. -#define MAX77812_REG_M2_VOUT 0x24 -#define MAX77812_REG_M3_VOUT 0x25 // DRAM on PHASE211. -#define MAX77812_REG_M4_VOUT 0x26 // CPU. -#define MAX77812_REG_M1_VOUT_D 0x27 -#define MAX77812_REG_M2_VOUT_D 0x28 -#define MAX77812_REG_M3_VOUT_D 0x29 -#define MAX77812_REG_M4_VOUT_D 0x2A -#define MAX77812_REG_M1_VOUT_S 0x2B -#define MAX77812_REG_M2_VOUT_S 0x2C -#define MAX77812_REG_M3_VOUT_S 0x2D -#define MAX77812_REG_M4_VOUT_S 0x2E -#define MAX77812_REG_M1_CFG 0x2F // HOS: M1_ILIM - 7.2A/4.8A. -#define MAX77812_REG_M2_CFG 0x30 // HOS: M2_ILIM - 7.2A/4.8A. -#define MAX77812_REG_M3_CFG 0x31 // HOS: M3_ILIM - 7.2A/4.8A. -#define MAX77812_REG_M4_CFG 0x32 // HOS: M4_ILIM - 7.2A/4.8A. -#define MAX77812_REG_GLB_CFG1 0x33 // HOS: B_SD_SR/B_SS_SR - 5mV/us. -#define MAX77812_REG_GLB_CFG2 0x34 // HOS: B_RD_SR/B_RU_SR - 5mV/us -#define MAX77812_REG_GLB_CFG3 0x35 - -/*! Protected area and settings only for MAX77812_ES2_VERSION */ -#define MAX77812_REG_GLB_CFG4 0x36 // QS: 0xBB. -#define MAX77812_REG_GLB_CFG5 0x37 // QS: 0x39. ES2: Set to 0x3E. -#define MAX77812_REG_GLB_CFG6 0x38 // QS: 0x88. ES2: Set to 0x90. -#define MAX77812_REG_GLB_CFG7 0x39 // QS: 0x04. -#define MAX77812_REG_GLB_CFG8 0x3A // QS: 0x3A. ES2: Set to 0x3A. - -#define MAX77812_REG_PROT_ACCESS 0xFD // 0x00: Lock, 0x5A: Unlock. -#define MAX77812_REG_UNKNOWN 0xFE - -#define MAX77812_REG_EN_CTRL_MASK(n) BIT(n) -#define MAX77812_START_SLEW_RATE_MASK 0x07 -#define MAX77812_SHDN_SLEW_RATE_MASK 0x70 -#define MAX77812_RAMPUP_SLEW_RATE_MASK 0x07 -#define MAX77812_RAMPDOWN_SLEW_RATE_MASK 0x70 -#define MAX77812_SLEW_RATE_SHIFT 4 - -#define MAX77812_OP_ACTIVE_DISCHARGE_MASK BIT(7) -#define MAX77812_PEAK_CURRENT_LMT_MASK 0x70 -#define MAX77812_SWITCH_FREQ_MASK 0x0C -#define MAX77812_FORCED_PWM_MASK BIT(1) -#define MAX77812_SLEW_RATE_CNTRL_MASK BIT(0) -#define MAX77812_START_SHD_DELAY_MASK 0x1F -#define MAX77812_VERSION_MASK 0x07 -#define MAX77812_ES2_VERSION 0x04 -#define MAX77812_QS_VERSION 0x05 - -#define MAX77812_BUCK_VOLT_MASK 0xFF - -#define BQ24193_I2C_ADDR 0x6B - -// REG 0 masks. -#define BQ24193_INCONFIG_INLIMIT_MASK (7 << 0) -#define BQ24193_INCONFIG_VINDPM_MASK 0x78 -#define BQ24193_INCONFIG_HIZ_EN_MASK (1 << 7) - -// REG 1 masks. -#define BQ24193_PORCONFIG_BOOST_MASK (1 << 0) -#define BQ24193_PORCONFIG_SYSMIN_MASK (7 << 1) // 3000uV HOS default. -#define BQ24193_PORCONFIG_CHGCONFIG_MASK (3 << 4) -#define BQ24193_PORCONFIG_CHGCONFIG_CHARGER_EN (1 << 4) -#define BQ24193_PORCONFIG_I2CWATCHDOG_MASK (1 << 6) -#define BQ24193_PORCONFIG_RESET_MASK (1 << 7) - -// REG 2 masks. -#define BQ24193_CHRGCURR_20PCT_MASK (1 << 0) -#define BQ24193_CHRGCURR_ICHG_MASK 0xFC - -// REG 3 masks. -#define BQ24193_PRECHRG_ITERM 0x0F -#define BQ24193_PRECHRG_IPRECHG 0xF0 - -// REG 4 masks. -#define BQ24193_CHRGVOLT_VTHRES (1 << 0) -#define BQ24193_CHRGVOLT_BATTLOW (1 << 1) -#define BQ24193_CHRGVOLT_VREG 0xFC - -// REG 5 masks. -#define BQ24193_CHRGTERM_ISET_MASK (1 << 0) -#define BQ24193_CHRGTERM_CHGTIMER_MASK (3 << 1) -#define BQ24193_CHRGTERM_ENTIMER_MASK (1 << 3) -#define BQ24193_CHRGTERM_WATCHDOG_MASK (3 << 4) -#define BQ24193_CHRGTERM_TERM_ST_MASK (1 << 6) -#define BQ24193_CHRGTERM_TERM_EN_MASK (1 << 7) - -// REG 6 masks. -#define BQ24193_IRTHERMAL_THERM_MASK (3 << 0) -#define BQ24193_IRTHERMAL_VCLAMP_MASK (7 << 2) -#define BQ24193_IRTHERMAL_BATTCOMP_MASK (7 << 5) - -// REG 7 masks. -#define BQ24193_MISC_INT_MASK (3 << 0) -#define BQ24193_MISC_VSET_MASK (1 << 4) -#define BQ24193_MISC_BATFET_DI_MASK (1 << 5) -#define BQ24193_MISC_TMR2X_EN_MASK (1 << 6) -#define BQ24193_MISC_DPDM_EN_MASK (1 << 7) - -// REG 8 masks. -#define BQ24193_STATUS_VSYS_MASK (1 << 0) -#define BQ24193_STATUS_THERM_MASK (1 << 1) -#define BQ24193_STATUS_PG_MASK (1 << 2) -#define BQ24193_STATUS_DPM_MASK (1 << 3) -#define BQ24193_STATUS_CHRG_MASK (3 << 4) -#define BQ24193_STATUS_VBUS_MASK (3 << 6) - -// REG 9 masks. -#define BQ24193_FAULT_THERM_MASK (7 << 0) -#define BQ24193_FAULT_BATT_OVP_MASK (1 << 3) -#define BQ24193_FAULT_CHARGE_MASK (3 << 4) -#define BQ24193_FAULT_BOOST_MASK (1 << 6) -#define BQ24193_FAULT_WATCHDOG_MASK (1 << 7) - -// REG A masks. -#define BQ24193_VENDORPART_DEV_MASK (3 << 0) -#define BQ24193_VENDORPART_PN_MASK (7 << 3) - -enum BQ24193_reg { - BQ24193_InputSource = 0x00, - BQ24193_PORConfig = 0x01, - BQ24193_ChrgCurr = 0x02, - BQ24193_PreChrgTerm = 0x03, - BQ24193_ChrgVolt = 0x04, - BQ24193_ChrgTermTimer = 0x05, - BQ24193_IRCompThermal = 0x06, - BQ24193_Misc = 0x07, - BQ24193_Status = 0x08, - BQ24193_FaultReg = 0x09, - BQ24193_VendorPart = 0x0A, -}; - -enum BQ24193_reg_prop { - BQ24193_InputVoltageLimit, // REG 0. - BQ24193_InputCurrentLimit, // REG 0. - BQ24193_SystemMinimumVoltage, // REG 1. - BQ24193_FastChargeCurrentLimit, // REG 2. - BQ24193_ChargeVoltageLimit, // REG 4. - BQ24193_RechargeThreshold, // REG 4. - BQ24193_ThermalRegulation, // REG 6. - BQ24193_ChargeStatus, // REG 8. - BQ24193_TempStatus, // REG 9. - BQ24193_DevID, // REG A. - BQ24193_ProductNumber, // REG A. -}; - -#endif /* MAX77XXX_H */ diff --git a/Source/sys-clk/sysmodule/src/notification.h b/Source/sys-clk/sysmodule/src/notification.h deleted file mode 100644 index 4000df1a..00000000 --- a/Source/sys-clk/sysmodule/src/notification.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once - -#include -#include -#include - -static void writeNotification(const std::string& message) { - const char* flagPath = "sdmc:/config/ultrahand/flags/NOTIFICATIONS.flag"; - - // Check if flag file exists - FILE* flagFile = fopen(flagPath, "r"); - if (!flagFile) { - // Flag file does not exist, do nothing - return; - } - fclose(flagFile); - - // Generate filename with timestamp - std::string filename = "Horzon OC -" + std::to_string(std::time(nullptr)) + ".notify"; - std::string fullPath = "sdmc:/config/ultrahand/notifications/" + filename; - - // Write JSON manually - FILE* file = fopen(fullPath.c_str(), "w"); - if (file) { - fprintf(file, "{\n"); - fprintf(file, " \"text\": \"%s\",\n", message.c_str()); - fprintf(file, " \"fontSize\": 28\n"); - fprintf(file, "}\n"); - fclose(file); - } - } diff --git a/Source/sys-clk/sysmodule/src/soctherm.h b/Source/sys-clk/sysmodule/src/soctherm.h deleted file mode 100644 index 24a2c755..00000000 --- a/Source/sys-clk/sysmodule/src/soctherm.h +++ /dev/null @@ -1,131 +0,0 @@ -/* * HOS soctherm driver by Souldbminer & Dominatorul * Licensed under the LGPLv3 */ -#ifndef _SOCTHERM_H_ -#define _SOCTHERM_H_ - -#include - -#define SOCTHERM_BASE 0x700E2000ULL - -#define SENSOR_TEMP1 0x1c8 -#define SENSOR_TEMP2 0x1cc - -#define SOC_THERM_THERMCTL_LEVEL0_GROUP_CPU_0 0x0 -#define SOC_THERM_THERMCTL_LEVEL0_GROUP_GPU_0 0x4 -#define SOC_THERM_THERMCTL_LEVEL0_GROUP_MEM_0 0x8 -#define SOC_THERM_THERMCTL_LEVEL0_GROUP_TSENSE_0 0xC - -#define SENSOR_CPU0_CONFIG0 0xC0 -#define SENSOR_CPU1_CONFIG0 0xE0 -#define SENSOR_CPU2_CONFIG0 0x100 -#define SENSOR_CPU3_CONFIG0 0x120 -#define SENSOR_GPU_CONFIG0 0x180 -#define SENSOR_PLLX_CONFIG0 0x1A0 - -#define SENSOR_CPU0_CONFIG1 0xC4 -#define SENSOR_CPU1_CONFIG1 0xE4 -#define SENSOR_CPU2_CONFIG1 0x104 -#define SENSOR_CPU3_CONFIG1 0x124 -#define SENSOR_GPU_CONFIG1 0x184 -#define SENSOR_PLLX_CONFIG1 0x1A4 - -#define SENSOR_CPU0_STATUS 0xC8 -#define SENSOR_GPU_STATUS 0x188 -#define SENSOR_PLLX_STATUS 0x1A8 - -#define SENSOR_CONFIG0_STOP_MASK (1U << 0) -#define SENSOR_CONFIG0_TALL_SHIFT 8 -#define SENSOR_CONFIG0_TALL_MASK (0xFFFFF << 8) - -#define SENSOR_CONFIG1_TEMP_ENABLE_MASK (1U << 31) -#define SENSOR_CONFIG1_TEN_COUNT_SHIFT 24 -#define SENSOR_CONFIG1_TEN_COUNT_MASK (0x3F << 24) -#define SENSOR_CONFIG1_TIDDQ_EN_SHIFT 15 -#define SENSOR_CONFIG1_TIDDQ_EN_MASK (0x3F << 15) -#define SENSOR_CONFIG1_TSAMPLE_SHIFT 0 -#define SENSOR_CONFIG1_TSAMPLE_MASK 0x3FF - -#define SENSOR_STATUS_VALID_MASK (1U << 31) - -#define TSENSOR_TALL_DEFAULT 16300 -#define TSENSOR_TIDDQ_EN_DEFAULT 1 -#define TSENSOR_TEN_COUNT_DEFAULT 1 -#define TSENSOR_TSAMPLE_DEFAULT 120 - -#define SENSOR_TEMP1_CPU_TEMP_MASK (0xFFFF << 16) -#define SENSOR_TEMP1_GPU_TEMP_MASK 0xFFFF -#define SENSOR_TEMP2_PLLX_TEMP_MASK 0xFFFF - -#define READBACK_VALUE_MASK 0xFF00 -#define READBACK_VALUE_SHIFT 8 -#define READBACK_ADD_HALF (1 << 7) -#define READBACK_NEGATE (1 << 0) - -#define REG_GET_MASK(r, m) (((r) & (m)) >> (__builtin_ffs(m) - 1)) - -// Timing constants (in microseconds) -#define SENSOR_STABILIZATION_DELAY_US 2000 // 2ms for sensor to stabilize -#define SENSOR_READ_DELAY_US 100 // 100us between config operations - -// Makes my life easier -#define BITMASK(bits) (0UL | (bits)) -#define BIT(n) (1UL << (n)) - -#define WRITE_REG_BIT(addr, bit, val) do { \ - u32 _tmp; \ - svcReadWriteRegister(&_tmp, (addr), 0, false); \ - if (val) \ - _tmp |= (1U << (bit)); /* set bit */ \ - else \ - _tmp &= ~(1U << (bit)); /* clear bit */ \ - svcReadWriteRegister(&_tmp, (addr), 0, true); \ -} while (0) - -typedef enum { - SENSOR_CPU = 0, - SENSOR_GPU = 1, - SENSOR_PLLX = 2, -} SocthermSensor; - -void socthermInit(void) { - WRITE_REG_BIT(SOCTHERM_BASE + SENSOR_CPU0_CONFIG0, 0, 0); // start cpu0 - WRITE_REG_BIT(SOCTHERM_BASE + SENSOR_CPU0_CONFIG1, 31, 1); // start cpu0 - - WRITE_REG_BIT(SOCTHERM_BASE + SENSOR_CPU1_CONFIG0, 0, 0); // start cpu1 - WRITE_REG_BIT(SOCTHERM_BASE + SENSOR_CPU1_CONFIG1, 31, 1); // start cpu1 - - WRITE_REG_BIT(SOCTHERM_BASE + SENSOR_CPU2_CONFIG0, 0, 0); // start cpu2 - WRITE_REG_BIT(SOCTHERM_BASE + SENSOR_CPU2_CONFIG1, 31, 1); // start cpu2 - - WRITE_REG_BIT(SOCTHERM_BASE + SENSOR_CPU3_CONFIG0, 0, 0); // start cpu3 - WRITE_REG_BIT(SOCTHERM_BASE + SENSOR_CPU3_CONFIG1, 31, 1); // start cpu3 - - WRITE_REG_BIT(SOCTHERM_BASE + SENSOR_GPU_CONFIG0, 0, 0); // start gpu - WRITE_REG_BIT(SOCTHERM_BASE + SENSOR_GPU_CONFIG1, 31, 1); // start gpu - - WRITE_REG_BIT(SOCTHERM_BASE + SENSOR_PLLX_CONFIG0, 0, 0); // start pllx - WRITE_REG_BIT(SOCTHERM_BASE + SENSOR_PLLX_CONFIG1, 31, 1); // start pllx -} - -int socthermRead(SocthermSensor sensor) { - switch(sensor) { - case SENSOR_CPU: { - u32 temp_reg; - svcReadWriteRegister(&temp_reg, SOCTHERM_BASE + SENSOR_TEMP1, 0, false); - return REG_GET_MASK(temp_reg, SENSOR_TEMP1_CPU_TEMP_MASK); - } - case SENSOR_GPU: { - u32 temp_reg; - svcReadWriteRegister(&temp_reg, SOCTHERM_BASE + SENSOR_TEMP1, 0, false); - return REG_GET_MASK(temp_reg, SENSOR_TEMP1_GPU_TEMP_MASK); - } - case SENSOR_PLLX: { - u32 temp_reg; - svcReadWriteRegister(&temp_reg, SOCTHERM_BASE + SENSOR_TEMP2, 0, false); - return REG_GET_MASK(temp_reg, SENSOR_TEMP2_PLLX_TEMP_MASK); - } - default: - return -1; // Invalid sensor - } -} - -#endif // _SOCTHERM_H_ \ No newline at end of file diff --git a/Source/sys-clk/sysmodule/toolbox.json b/Source/sys-clk/sysmodule/toolbox.json index 4874c6c7..83ac964c 100644 --- a/Source/sys-clk/sysmodule/toolbox.json +++ b/Source/sys-clk/sysmodule/toolbox.json @@ -1,5 +1,5 @@ { - "name" : "Horizon OC", + "name" : "hoc-clk", "tid" : "00FF0000636C6BFF", "requires_reboot": false } \ No newline at end of file