From 094cfd811e99655a6221eca42c8a31674272cb75 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Mon, 28 Sep 2026 18:56:01 -0500 Subject: [PATCH 01/61] Link iplController and iplControllerManager (#242) * link iplController translation unit * match controller manager read flow * link iplControllerManager translation unit --- configure.py | 4 +- include/system/iplController.h | 6 +- src/system/iplController.cpp | 88 +++++++++++++++++++++++++++++ src/system/iplControllerManager.cpp | 13 ++--- 4 files changed, 100 insertions(+), 11 deletions(-) diff --git a/configure.py b/configure.py index 46b142da..6bbcff16 100644 --- a/configure.py +++ b/configure.py @@ -624,8 +624,8 @@ config.libs = [ Object(Matching, "system/rvl_dec.c"), Object(Matching, "system/RIPL_BoardRecord.c"), Object(Matching, "system/iplSystem.cpp"), - Object(NonMatching, "system/iplController.cpp"), - Object(NonMatching, "system/iplControllerManager.cpp"), + Object(Matching, "system/iplController.cpp"), + Object(Matching, "system/iplControllerManager.cpp"), Object(Matching, "system/iplChannelManager.cpp"), Object(Matching, "system/iplChannelScriptManager.cpp"), Object(Matching, "system/iplNand.cpp"), diff --git a/include/system/iplController.h b/include/system/iplController.h index bba7b9a0..f637f3a2 100644 --- a/include/system/iplController.h +++ b/include/system/iplController.h @@ -63,10 +63,14 @@ namespace ipl { // clang-format on #ifdef IPL_CONTROLLER_NATIVE_HIERARCHY +#ifdef IPL_CONTROLLER_OUT_OF_LINE_INTERFACE +#define IPL_CONTROLLER_DEFAULT_VIRTUAL(signature, implementation) virtual signature; +#else #ifdef IPL_CONTROLLER_INLINE_INTERFACE #define IPL_CONTROLLER_DEFAULT_VIRTUAL(signature, implementation) virtual signature implementation #else #define IPL_CONTROLLER_DEFAULT_VIRTUAL(signature, implementation) virtual signature; +#endif #endif class Interface { public: @@ -79,7 +83,7 @@ namespace ipl { IPL_CONTROLLER_DEFAULT_VIRTUAL(int pinch() const, { return 0; }) IPL_CONTROLLER_DEFAULT_VIRTUAL(int pinchTrg() const, { return 0; }) IPL_CONTROLLER_DEFAULT_VIRTUAL(int pinchOffTrg() const, { return 0; }) - IPL_CONTROLLER_DEFAULT_VIRTUAL(int decide() const, { return 0; }) + virtual int decide() const = 0; IPL_CONTROLLER_DEFAULT_VIRTUAL(bool repeat(u32 button) const, { return false; }) IPL_CONTROLLER_DEFAULT_VIRTUAL(BOOL rumble(int type = 0), { return FALSE; }) IPL_CONTROLLER_DEFAULT_VIRTUAL(void cancelRumbling(), { }) diff --git a/src/system/iplController.cpp b/src/system/iplController.cpp index 70e13e6f..2449cbae 100644 --- a/src/system/iplController.cpp +++ b/src/system/iplController.cpp @@ -18,7 +18,9 @@ #define IPL_CONTROLLER_NATIVE_HIERARCHY #define IPL_CONTROLLER_INLINE_INTERFACE +#define IPL_CONTROLLER_OUT_OF_LINE_INTERFACE #include "system/iplController.h" +#undef IPL_CONTROLLER_OUT_OF_LINE_INTERFACE #undef IPL_CONTROLLER_INLINE_INTERFACE #undef IPL_CONTROLLER_NATIVE_HIERARCHY #include "system/iplSystem.h" @@ -91,6 +93,21 @@ namespace ipl { } } } + bool ipl::controller::Interface::isValidBtn() const { + return false; + } + bool ipl::controller::Interface::downTrg(u32 button) const { + return false; + } + int ipl::controller::Interface::pinch() const { + return 0; + } + bool ipl::controller::Interface::down(u32 button) const { + return false; + } + KPADStatus* ipl::controller::Interface::getKPADStatus() const { + return NULL; + } int ipl::controller::Base::decide() const { return unk_0x08 == 5; } @@ -325,9 +342,15 @@ namespace ipl { bool ipl::controller::Master::upTrg(u32 button) const { return call(button, kUpTrgMember); } + bool ipl::controller::Interface::upTrg(u32 button) const { + return false; + } bool ipl::controller::Master::repeat(u32 button) const { return call(button, kRepeatMember); } + bool ipl::controller::Interface::repeat(u32 button) const { + return false; + } int ipl::controller::Master::decide() const { bool current = false; bool ret = false; @@ -365,6 +388,71 @@ void ipl::controller::Master::setForceInvalid(bool flag) { } return ret; } + void ipl::controller::Interface::read() {} + int ipl::controller::Interface::getSubStickY() const { + return 0; + } + int ipl::controller::Interface::getSubStickX() const { + return 0; + } + int ipl::controller::Interface::getMainStickY() const { + return 0; + } + int ipl::controller::Interface::getMainStickX() const { + return 0; + } + bool ipl::controller::Interface::isValidDpd() const { + return false; + } + PADStatus* ipl::controller::Interface::getPADStatus() const { + return NULL; + } + f32 ipl::controller::Interface::getDpdDistance() const { + return 0.0f; + } + ipl::math::VEC2 ipl::controller::Interface::getHorizon() const { + return ipl::math::VEC2(0.0f, 0.0f); + } + ipl::math::VEC2 ipl::controller::Interface::getDpdProjectionPos() const { + return ipl::math::VEC2(0.0f, 0.0f); + } + ipl::math::VEC2 ipl::controller::Interface::getDpdPos() const { + return ipl::math::VEC2(0.0f, 0.0f); + } + int ipl::controller::Interface::getClassicReleaseFlag() const { + return 0; + } + int ipl::controller::Interface::getClassicTrigFlag() const { + return 0; + } + int ipl::controller::Interface::getClassicHoldFlag() const { + return 0; + } + int ipl::controller::Interface::getReleaseFlag() const { + return 0; + } + int ipl::controller::Interface::getTrigFlag() const { + return 0; + } + int ipl::controller::Interface::getHoldFlag() const { + return 0; + } + void ipl::controller::Interface::cancelRumbling() {} + BOOL ipl::controller::Interface::rumble(int type) { + return FALSE; + } + int ipl::controller::Interface::pinchOffTrg() const { + return 0; + } + int ipl::controller::Interface::pinchTrg() const { + return 0; + } + int ipl::controller::Interface::getChannel() const { + return -1; + } + int ipl::controller::Interface::getType() const { + return -1; + } void ipl::controller::Base::setForceInvalid(bool flag) { unk_0x1C = flag; } diff --git a/src/system/iplControllerManager.cpp b/src/system/iplControllerManager.cpp index 3daaec5d..eb8e0261 100644 --- a/src/system/iplControllerManager.cpp +++ b/src/system/iplControllerManager.cpp @@ -98,11 +98,7 @@ namespace ipl { probe_valid: { s32 read = KPADRead(chan, &mKPADStatus[chan], 1); - if (read > 0) { - if (mKPADStatus[chan].wpad_err == -4 || deviceType == 0xfd) { - goto store_null; - } - + if (read > 0 && mKPADStatus[chan].wpad_err != -4 && deviceType != 0xfd) { mInvalidCount[chan] = 0; if (mKPADStatus[chan].wpad_err == -7 || deviceType == 0 || deviceType == 0xfb || deviceType == 0xfc || deviceType == 0xff) { @@ -120,7 +116,10 @@ namespace ipl { } else { mControllers[chan] = NULL; } - } else if (read == 0) { + } else { + if (read != 0) { + goto store_null; + } mInvalidCount[chan]++; if (mInvalidCount[chan] > 0x3c) { mInvalidCount[chan] = 0x3c; @@ -129,8 +128,6 @@ namespace ipl { } mControllers[chan] = NULL; } - } else { - goto store_null; } } goto channel_done; -- 2.49.1 From b719ba47a5d65bc53944c051b2a0f9d19ea37ee5 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Mon, 28 Sep 2026 19:05:02 -0500 Subject: [PATCH 02/61] Decompile KPAD to 11/29 functions (#243) * decompile kpad unit * model kpad sample fields * refine kpad ring buffer matching * restore kpad sample history processing * match kpad sampling branches * restore probe callback branch * refine kpad acceleration clamps * refine kpad first object selection * match kpad object candidate loops * match kpad pointer based dpd scans * preserve dpd sample words * align kpad device sample handling * refine kpad acceleration format dispatch * match kpad init ring defaults * align kpad init field order * match kpad probe type dispatch * align kpad horizon calculation order * clean kpad field names and match repeat setup * name kpad calibration fields * match kpad ring buffer traversal * refine kpad ring buffer matching --- libs/RVL_SDK/src/kpad/KPAD.c | 1824 ++++++++++++++++++++++++++++++++++ 1 file changed, 1824 insertions(+) create mode 100644 libs/RVL_SDK/src/kpad/KPAD.c diff --git a/libs/RVL_SDK/src/kpad/KPAD.c b/libs/RVL_SDK/src/kpad/KPAD.c new file mode 100644 index 00000000..7766aa17 --- /dev/null +++ b/libs/RVL_SDK/src/kpad/KPAD.c @@ -0,0 +1,1824 @@ +#include +#include +#include +#include +#include + +typedef struct KPADSampleFS { + s16 accX; + s16 accY; + s16 accZ; + s8 stickX; + s8 stickY; +} KPADSampleFS; + +typedef struct KPADSampleCL { + u16 buttons; + s16 lStickX; + s16 lStickY; + s16 rStickX; + s16 rStickY; + u8 triggerL; + u8 triggerR; +} KPADSampleCL; + +typedef struct KPADSample { + u16 buttons; + s16 accX; + s16 accY; + s16 accZ; + DPDObject objects[WPAD_MAX_DPD_OBJECTS]; + u8 device; + s8 error; + union { + KPADSampleFS fs; + KPADSampleCL cl; + } extension; + u8 dataFormat; +} KPADSample; + +typedef struct KPADDPDObject { + f32 x; + f32 y; + union { + u32 value; + struct { + u8 flags; + u8 status; + } bytes; + } metadata; +} KPADDPDObject; + +typedef struct KPADInside { + KPADStatus status; + f32 posParamX; + f32 posParamY; + f32 value8C; + f32 value90; + f32 value94; + f32 value98; + f32 value9C; + f32 valueA0; + f32 referenceDistance; + f32 accelNormalX; + f32 accelNormalY; + f32 horizonTangentX; + f32 horizonTangentY; + f32 sensorBarCenterX; + f32 sensorBarCenterY; + f32 sensorBarScale; + struct { + KPADDPDObject objects[4]; + KPADDPDObject candidates[2]; + } dpdState; + u16 dpdCount; + u8 ringIndex; + u8 ringCount; + KPADSample ringData[16]; + f32 dpdObjectDistance; + f32 dpdObjectDirectionX; + f32 dpdObjectDirectionY; + f32 dpdReferenceDistance; + f32 dpdObjectScale; + f32 accelerationX; + f32 accelerationY; + f32 accelerationZ; + f32 dpdAxisX; + f32 dpdAxisY; + f32 horizonAxisX; + f32 horizonAxisY; + f32 horizonCircleX; + f32 horizonCircleY; + u16 horizonCircleCount; + u8 value4CA; + u16 repeatCount; + u16 repeatCount2; + u16 repeatDelay; + u16 repeatInterval; + u16 repeatCurrent; + u16 repeatCurrent2; + KPADCallback dpdCallback; + f32 value4DC; + f32 value4E0; + f32 value4E4; + f32 value4E8; + f32 value4EC; + f32 value4F0; + f32 value4F4; + f32 value4F8; + f32 value4FC; + f32 value500; + f32 value504; + f32 value508; + f32 value50C; + f32 value510; + f32 value514; + WPADSamplingCallback samplingCallback; + u8 samplingInProgress; + u8 flag51D; + u8 flag51E; + u8 flag51F; + u8 dpdEnable; + u8 dpdFormat; + u8 dpdCallbackFired; + u8 dpdCallbackPending; + u8 sensorHeightPending; + u8 sensorBarPosition; + u16 freeStyleAccelRotation; +} KPADInside; + +static KPADInside inside_kpads[4]; +f32 initial_rotation_matrix[16]; + +static const char kpadVersion[] = "<< RVL_SDK - KPAD \trelease build: Apr 20 2010 11:20:37 (0x4199_60831) >>"; +const char* __KPADVersion = kpadVersion; +static const u8 dpdModeTable[12] = {0, 1, 3, 2, 0, 4, 1, 5, 0, 7, 1, 8}; + +static f32 idist_org = 1.0f; +static Vec2 iaccXY_nrm_hori = {0.0f, -1.0f}; +static Vec2 isec_nrm_hori = {1.0f, 0.0f}; +f32 kp_obj_interval = 0.2f; +f32 kp_acc_horizon_pw = 0.05f; +f32 kp_ah_circle_radius = 0.07f; +f32 kp_ah_circle_pw = 0.06f; +u16 kp_ah_circle_ct = 100; +f32 kp_err_outside_frame = 0.05f; +f32 kp_err_dist_max = 3.0f; +f32 kp_err_dist_speed = 0.04f; +f32 kp_err_first_inpr = 0.9f; +f32 kp_err_next_inpr = 0.9f; +f32 kp_err_acc_inpr = 0.9f; +f32 kp_err_up_inpr = 0.7f; +f32 kp_err_near_pos = 0.1f; +static u32 kp_fs_fstick_min = 15; +static u32 kp_fs_fstick_max = 71; +static u32 kp_cl_stick_min = 60; +static u32 kp_cl_stick_max = 308; +static u32 kp_cl_trigger_min = 30; +static u32 kp_cl_trigger_max = 180; +static f32 kp_rm_acc_max = 3.4f; +static f32 kp_fs_acc_max = 2.1f; +f32 sensor_bar_angle_degrees = 24.0f; + +static Vec2 icenter_org; +u32 kp_stick_clamp_cross; +static Vec2 Vec2_0; +static f32 kp_dist_vv1; +f32 kp_err_dist_min; + +static void KPADiSamplingCallback(s32 chan); +static void KPADiControlDpdCallback(s32 chan, s32 result); +static void calc_dpd_variable(KPADInside* kpad, s8 valid); + +static void* get_ring_buffer_by_kpad1_style(s32 chan, void* buffer, s32 style) { + KPADInside* kpad = &inside_kpads[chan]; + u32 i; + s32 index; + s32 latest; + int enabled; + s32 size; + u32 type; + switch (style) { + case 0: + size = 0x2A; + goto process; + case 1: + size = 0x32; + goto process; + case 2: + size = 0x36; + goto process; + default: + return buffer; + } +process: + enabled = OSDisableInterrupts(); + index = kpad->ringIndex - 1; + latest = WPADGetLatestIndexInBuf(chan); + for (i = 0; i < 16; i++) { + if (index < 0) { + index = 15; + } + if (latest < 0) { + latest = 15; + } + type = kpad->ringData[index].device; + switch (type) { + case 0: + case 0xFB: + case 0xFC: + case 0xFF: + type = 0; + break; + case 1: + type = 1; + break; + case 2: + type = 2; + break; + default: + type = 0xFF; + break; + } + if (type == style) { + if (WPADGetStatus() != 3) { + kpad->ringData[index].error = 0xFC; + } + memcpy((u8*)buffer + latest * size, &kpad->ringData[index], size); + } + index--; + latest--; + } + OSRestoreInterrupts(enabled); + return buffer; +} + +void* KPADGetWPADRingBuffer(s32 chan) { + static u8 status[0x2A0]; + return get_ring_buffer_by_kpad1_style(chan, status, 0); +} + +void* KPADGetWPADFSRingBuffer(s32 chan) { + static u8 status[0x320]; + return get_ring_buffer_by_kpad1_style(chan, status, 1); +} + +void* KPADGetWPADCLRingBuffer(s32 chan) { + static u8 status[0x360]; + return get_ring_buffer_by_kpad1_style(chan, status, 2); +} + +void KPADSetBtnRepeat(s32 chan, f32 delay, f32 pulse) { + KPADInside* kpad = &inside_kpads[chan]; + if (pulse) { + kpad->repeatDelay = (u16)(0.5f + 200.0f * delay); + kpad->repeatInterval = (u16)(0.5f + 200.0f * pulse); + } else { + kpad->repeatDelay = 40000; + kpad->repeatInterval = 0; + } + kpad->repeatCount = 0; + kpad->repeatCount2 = kpad->repeatDelay; + kpad->repeatCurrent = 0; + kpad->repeatCurrent2 = kpad->repeatDelay; +} + +void KPADSetPosParam(s32 chan, f32 x, f32 y) { + KPADInside* kpad = &inside_kpads[chan]; + kpad->posParamX = x; + kpad->posParamY = y; +} + +static void calc_button_repeat(KPADInside* kpad, u8 extension, s32 elapsed) { + u16 count; + u16 threshold; + u16 current; + u16 next; + if (kpad->status.trig != 0 || kpad->status.release != 0) { + kpad->repeatCount = 0; + kpad->repeatCount2 = kpad->repeatDelay; + if (kpad->status.trig != 0 && kpad->repeatInterval != 0) { + kpad->status.hold |= 0x80000000; + } + } else if (kpad->status.hold != 0) { + count = kpad->repeatCount + elapsed; + kpad->repeatCount = count; + if (count >= 40000) { + kpad->repeatCount = count - 40000; + } + threshold = kpad->repeatCount2; + current = kpad->repeatCount; + if (current >= threshold) { + kpad->status.hold |= 0x80000000; + next = threshold + kpad->repeatInterval; + kpad->repeatCount2 = next; + if (current >= 20000) { + kpad->repeatCount = current - 20000; + kpad->repeatCount2 = next - 20000; + } + } + } + if (extension == 2) { + if (kpad->status.ex_status.cl.trig != 0 || kpad->status.ex_status.cl.release != 0) { + kpad->repeatCurrent = 0; + kpad->repeatCurrent2 = kpad->repeatDelay; + if (kpad->status.ex_status.cl.trig != 0 && kpad->repeatInterval != 0) { + kpad->status.ex_status.cl.hold |= 0x80000000; + } + } else if (kpad->status.ex_status.cl.hold != 0) { + count = kpad->repeatCurrent + elapsed; + kpad->repeatCurrent = count; + if (count >= 40000) { + kpad->repeatCurrent = count - 40000; + } + threshold = kpad->repeatCurrent2; + current = kpad->repeatCurrent; + if (current >= threshold) { + kpad->status.ex_status.cl.hold |= 0x80000000; + next = threshold + kpad->repeatInterval; + kpad->repeatCurrent2 = next; + if (current >= 20000) { + kpad->repeatCurrent = current - 20000; + kpad->repeatCurrent2 = next - 20000; + } + } + } + } +} + +static void calc_acc_horizon(KPADInside* kpad) { + f32 accelX = kpad->accelerationX; + f32 accelY = kpad->accelerationY; + f32 magnitude = (f32)sqrt(accelX * accelX + accelY * accelY); + f32 normalizedX; + f32 normalizedY; + f32 targetY; + f32 targetX; + f32 productX; + f32 oldX; + f32 oldY; + f32 blend; + f32 projectedX; + f32 smoothing; + f32 deltaX; + f32 nextX; + f32 nextY; + f32 normalized; + f32 unitX; + f32 oldCircleX; + f32 oldCircleY; + f32 unitY; + f32 circleX; + f32 deltaCircleX; + f32 circleY; + f32 deltaCircleY; + if (magnitude != 0.0f) { + if (magnitude >= 2.0f) { + return; + } + normalizedX = kpad->accelerationX / magnitude; + normalizedY = kpad->accelerationY / magnitude; + if (magnitude > 1.0f) { + magnitude = 2.0f - magnitude; + } + targetY = kpad->accelNormalY; + targetX = kpad->accelNormalX; + productX = targetX * normalizedX; + oldX = kpad->horizonAxisX; + oldY = kpad->horizonAxisY; + blend = magnitude * kp_acc_horizon_pw; + projectedX = productX + targetY * normalizedY; + smoothing = magnitude * blend; + deltaX = smoothing * (projectedX - oldX); + nextX = oldX + deltaX; + nextY = oldY + smoothing * (((targetY * normalizedX) - (targetX * normalizedY)) - oldY); + normalized = (f32)sqrt(nextX * nextX + nextY * nextY); + if (normalized != 0.0f) { + unitX = nextX / normalized; + oldCircleX = kpad->horizonCircleX; + oldCircleY = kpad->horizonCircleY; + unitY = nextY / normalized; + kpad->horizonAxisX = unitX; + kpad->horizonAxisY = unitY; + circleX = oldCircleX + kp_ah_circle_pw * (unitX - oldCircleX); + deltaCircleX = unitX - circleX; + kpad->horizonCircleX = circleX; + circleY = oldCircleY + kp_ah_circle_pw * (unitY - oldCircleY); + deltaCircleY = unitY - circleY; + kpad->horizonCircleY = circleY; + if (deltaCircleX * deltaCircleX + deltaCircleY * deltaCircleY == kpad->value50C) { + if (kpad->horizonCircleCount != 0) { + kpad->horizonCircleCount--; + } + } else { + kpad->horizonCircleCount = kp_ah_circle_ct; + } + } + } +} + +static void calc_acc_vertical(KPADInside* kpad) { + f32 horizontal; + f32 horizontalMagnitude; + f32 accelZ; + f32 blend; + f32 magnitude; + f32 normalizedX; + f32 nextZ; + f32 normalized; + horizontalMagnitude = kpad->accelerationX * kpad->accelerationX + kpad->accelerationY * kpad->accelerationY; + horizontal = (f32)sqrt(horizontalMagnitude); + accelZ = -kpad->accelerationZ; + magnitude = (f32)sqrt(horizontalMagnitude + accelZ * accelZ); + if (magnitude == 0.0f || magnitude >= 2.0f) { + return; + } + normalizedX = horizontal / magnitude; + accelZ /= magnitude; + if (magnitude > 1.0f) { + magnitude = 2.0f - magnitude; + } + blend = magnitude * kp_acc_horizon_pw; + magnitude *= blend; + horizontal = kpad->status.acc_vertical.x + magnitude * (normalizedX - kpad->status.acc_vertical.x); + nextZ = kpad->status.acc_vertical.y + magnitude * (accelZ - kpad->status.acc_vertical.y); + normalized = (f32)sqrt(horizontal * horizontal + nextZ * nextZ); + if (normalized != 0.0f) { + kpad->status.acc_vertical.x = horizontal / normalized; + kpad->status.acc_vertical.y = nextZ / normalized; + } +} + +static void read_kpad_acc(KPADInside* kpad, KPADSample* status) { + u8 format = status->dataFormat; + if (format == 6) { + return; + } + if (format < 6) { + if (format == 3) { + return; + } + if (format < 3 && format < 1) { + return; + } + } else if (format >= 9) { + return; + } + { + f32 oldX = kpad->status.acc.x; + f32 oldY = kpad->status.acc.y; + f32 oldZ = kpad->status.acc.z; + f32 target; + f32 delta; + f32 magnitude; + f32 blend; + f32 currentX; + f32 currentY; + f32 currentZ; + f32 limit; + limit = kp_rm_acc_max; + target = (f32)-(s32)status->accX * kpad->value4DC; + if (target < 0.0f) { + limit = -limit; + if (target >= limit) { + limit = target; + } + } else if (target <= limit) { + limit = target; + } + kpad->accelerationX = limit; + limit = kp_rm_acc_max; + target = (f32)-(s32)status->accZ * kpad->value4E4; + if (target < 0.0f) { + limit = -limit; + if (target >= limit) { + limit = target; + } + } else if (target <= limit) { + limit = target; + } + kpad->accelerationY = limit; + limit = kp_rm_acc_max; + target = (f32)status->accY * kpad->value4E0; + if (target < 0.0f) { + limit = -limit; + if (target >= limit) { + limit = target; + } + } else if (target <= limit) { + limit = target; + } + kpad->accelerationZ = limit; + delta = kpad->accelerationX - oldX; + magnitude = delta; + if (magnitude < 0.0f) { + magnitude = -magnitude; + } + if (magnitude == kpad->value9C) { + blend = 1.0f; + } else { + blend = magnitude / kpad->value9C; + blend *= blend; + blend *= blend; + } + kpad->status.acc.x = oldX + blend * kpad->valueA0 * delta; + delta = kpad->accelerationY - oldY; + magnitude = delta; + if (magnitude < 0.0f) { + magnitude = -magnitude; + } + if (magnitude == kpad->value9C) { + blend = 1.0f; + } else { + blend = magnitude / kpad->value9C; + blend *= blend; + blend *= blend; + } + kpad->status.acc.y = oldY + blend * kpad->valueA0 * delta; + delta = kpad->accelerationZ - oldZ; + magnitude = delta; + if (magnitude < 0.0f) { + magnitude = -magnitude; + } + if (magnitude == kpad->value9C) { + blend = 1.0f; + } else { + blend = magnitude / kpad->value9C; + blend *= blend; + blend *= blend; + } + kpad->status.acc.z = oldZ + blend * kpad->valueA0 * delta; + currentX = kpad->status.acc.x; + currentY = kpad->status.acc.y; + currentZ = kpad->status.acc.z; + kpad->status.acc_value = (f32)sqrt(currentX * currentX + (currentY * currentY + currentZ * currentZ)); + delta = currentX - oldX; + currentX = currentY - oldY; + currentY = currentZ - oldZ; + kpad->status.acc_speed = (f32)sqrt(delta * delta + (currentX * currentX + currentY * currentY)); + calc_acc_horizon(kpad); + calc_acc_vertical(kpad); + } + if (status->error != 0 || status->device != 1) { + return; + } + if (format != 4 && format != 5) { + return; + } + { + Vec raw; + f32* values = (f32*)&raw; + f32 oldX; + f32 oldY; + f32 oldZ; + f32 delta; + f32 magnitude; + f32 blend; + f32 currentX; + f32 currentY; + f32 currentZ; + f32 limit; + values[0] = (f32)-(s32)status->extension.fs.accX * kpad->value4E8; + limit = kp_fs_acc_max; + if (values[0] < -kp_fs_acc_max) { + limit = -kp_fs_acc_max; + } else if (values[0] <= limit) { + limit = values[0]; + } + values[0] = limit; + values[1] = (f32)-(s32)status->extension.fs.accZ * kpad->value4F0; + limit = kp_fs_acc_max; + if (values[1] < -kp_fs_acc_max) { + limit = -kp_fs_acc_max; + } else if (values[1] <= limit) { + limit = values[1]; + } + values[1] = limit; + values[2] = (f32)status->extension.fs.accY * kpad->value4EC; + limit = kp_fs_acc_max; + if (values[2] < -kp_fs_acc_max) { + limit = -kp_fs_acc_max; + } else if (values[2] <= limit) { + limit = values[2]; + } + values[2] = limit; + if (kpad->freeStyleAccelRotation != 0) { + PSMTXMultVec((const f32 (*)[4])initial_rotation_matrix, &raw, &raw); + } + oldX = kpad->status.ex_status.fs.acc.x; + oldY = kpad->status.ex_status.fs.acc.y; + oldZ = kpad->status.ex_status.fs.acc.z; + delta = values[0] - oldX; + magnitude = delta; + if (magnitude < 0.0f) { + magnitude = -magnitude; + } + if (magnitude == kpad->value9C) { + blend = 1.0f; + } else { + blend = magnitude / kpad->value9C; + blend *= blend; + blend *= blend; + } + kpad->status.ex_status.fs.acc.x = oldX + blend * kpad->valueA0 * delta; + delta = values[1] - oldY; + magnitude = delta; + if (magnitude < 0.0f) { + magnitude = -magnitude; + } + if (magnitude == kpad->value9C) { + blend = 1.0f; + } else { + blend = magnitude / kpad->value9C; + blend *= blend; + blend *= blend; + } + kpad->status.ex_status.fs.acc.y = oldY + blend * kpad->valueA0 * delta; + delta = values[2] - oldZ; + magnitude = delta; + if (magnitude < 0.0f) { + magnitude = -magnitude; + } + if (magnitude == kpad->value9C) { + blend = 1.0f; + } else { + blend = magnitude / kpad->value9C; + blend *= blend; + blend *= blend; + } + kpad->status.ex_status.fs.acc.z = oldZ + blend * kpad->valueA0 * delta; + currentX = kpad->status.ex_status.fs.acc.x; + currentY = kpad->status.ex_status.fs.acc.y; + currentZ = kpad->status.ex_status.fs.acc.z; + kpad->status.ex_status.fs.acc_value = (f32)sqrt(currentX * currentX + (currentY * currentY + currentZ * currentZ)); + delta = currentX - oldX; + currentX = currentY - oldY; + currentY = currentZ - oldZ; + kpad->status.ex_status.fs.acc_speed = (f32)sqrt(delta * delta + (currentX * currentX + currentY * currentY)); + } +} + +static s8 select_2obj_first(KPADInside* kpad) { + KPADDPDObject* objects = kpad->dpdState.objects; + KPADDPDObject* first = 0; + KPADDPDObject* second = 0; + f32 best = kp_err_first_inpr; + s32 i; + s32 j; + for (i = 0; i < 4; i++) { + if ((s8)objects[i].metadata.bytes.flags != 0) { + continue; + } + for (j = i + 1; j < 4; j++) { + f32 dx; + f32 dy; + f32 scale; + f32 nx; + f32 ny; + f32 dist; + f32 x; + f32 y; + f32 dot; + f32 score; + if ((s8)objects[j].metadata.bytes.flags != 0) { + continue; + } + dx = objects[j].x - objects[i].x; + dy = objects[j].y - objects[i].y; + scale = 1.0f / (f32)sqrt(dx * dx + dy * dy); + nx = dx * scale; + ny = dy * scale; + dist = kpad->value510 * scale; + if (dist == kpad->value514 || dist == kp_err_dist_max) { + continue; + } + x = kpad->horizonTangentX * nx + kpad->horizonTangentY * ny; + y = kpad->horizonTangentY * nx - kpad->horizonTangentX * ny; + dot = kpad->horizonAxisX * x + kpad->horizonAxisY * y; + score = dot; + if (score < 0.0f) { + score = -score; + if (score > best) { + best = score; + first = &objects[j]; + second = &objects[i]; + } + } else if (score > best) { + best = score; + first = &objects[i]; + second = &objects[j]; + } + } + } + if (best == kp_err_first_inpr) { + return 0; + } + ((u32*)&kpad->dpdState.candidates[0].x)[0] = ((u32*)first)[0]; + ((u32*)&kpad->dpdState.candidates[0].x)[1] = ((u32*)first)[1]; + ((u32*)&kpad->dpdState.candidates[0].x)[2] = ((u32*)first)[2]; + ((u32*)&kpad->dpdState.candidates[1].x)[0] = ((u32*)second)[0]; + ((u32*)&kpad->dpdState.candidates[1].x)[1] = ((u32*)second)[1]; + ((u32*)&kpad->dpdState.candidates[1].x)[2] = ((u32*)second)[2]; + return 2; +} + +static s8 select_2obj_continue(KPADInside* kpad) { + KPADDPDObject* objects = kpad->dpdState.objects; + KPADDPDObject* first = 0; + KPADDPDObject* second = 0; + f32 best = -1.0f; + s32 i; + s32 j; + for (i = 0; i < 4; i++) { + if ((s8)objects[i].metadata.bytes.flags != 0) { + continue; + } + for (j = i + 1; j < 4; j++) { + f32 dx; + f32 dy; + f32 scale; + f32 nx; + f32 ny; + f32 distance; + f32 distanceError; + f32 distanceScore; + f32 dot; + f32 score; + BOOL reverse; + if ((s8)objects[j].metadata.bytes.flags != 0) { + continue; + } + dx = objects[j].x - objects[i].x; + dy = objects[j].y - objects[i].y; + scale = 1.0f / (f32)sqrt(dx * dx + dy * dy); + distance = scale * kpad->value510; + nx = dx * scale; + ny = dy * scale; + if (distance == kpad->value514 || distance == kp_err_dist_max) { + continue; + } + distanceError = distance - kpad->dpdReferenceDistance; + if (distanceError < 0.0f) { + distanceScore = distanceError * kpad->value508; + } else { + distanceScore = distanceError * kpad->value504; + } + if (distanceScore == 1.0f) { + continue; + } + dot = kpad->dpdObjectDirectionX * nx + kpad->dpdObjectDirectionY * ny; + reverse = dot < 0.0f; + if (reverse) { + dot = -dot; + } + if (dot == kp_err_next_inpr) { + continue; + } + score = distanceScore + ((1.0f - dot) / (1.0f - kp_err_next_inpr)); + if (score < best || best < 0.0f) { + best = score; + if (reverse) { + first = &objects[j]; + second = &objects[i]; + } else { + first = &objects[i]; + second = &objects[j]; + } + } + } + } + if (best < 0.0f) { + return 0; + } + ((u32*)&kpad->dpdState.candidates[0].x)[0] = ((u32*)first)[0]; + ((u32*)&kpad->dpdState.candidates[0].x)[1] = ((u32*)first)[1]; + ((u32*)&kpad->dpdState.candidates[0].x)[2] = ((u32*)first)[2]; + ((u32*)&kpad->dpdState.candidates[1].x)[0] = ((u32*)second)[0]; + ((u32*)&kpad->dpdState.candidates[1].x)[1] = ((u32*)second)[1]; + ((u32*)&kpad->dpdState.candidates[1].x)[2] = ((u32*)second)[2]; + return 2; +} + +static s8 select_1obj_first(KPADInside* kpad) { + KPADDPDObject* objects = kpad->dpdState.objects; + KPADDPDObject* object; + KPADDPDObject* end = kpad->dpdState.candidates; + f32 xAxis = kpad->horizonTangentX; + f32 xNorm = kpad->horizonAxisX; + f32 yAxis = kpad->horizonTangentY; + f32 yNorm = kpad->horizonAxisY; + f32 scale = kpad->dpdObjectScale; + f32 offsetX = (xAxis * xNorm + yAxis * yNorm) * scale; + f32 offsetY = (yAxis * xNorm - xAxis * yNorm) * scale; + object = objects; + do { + if ((s8)object->metadata.bytes.flags == 0) { + f32 x = object->x; + f32 y = object->y; + f32 left = x - offsetX; + f32 bottom = y - offsetY; + f32 right = x + offsetX; + f32 top = y + offsetY; + f32 leftBound = kpad->value4F4; + f32 rightBound = kpad->value4FC; + f32 topBound = kpad->value4F8; + f32 bottomBound = kpad->value500; + if (left == leftBound || left == rightBound || bottom == topBound || bottom == bottomBound) { + if (right > leftBound && right < rightBound && top > topBound && top < bottomBound) { + u32* objectWords = (u32*)object; + u32* statusWords = (u32*)&kpad->dpdState.candidates[1].x; + statusWords[0] = objectWords[0]; + statusWords[1] = objectWords[1]; + statusWords[2] = objectWords[2]; + kpad->dpdState.candidates[0].x = left; + kpad->dpdState.candidates[0].y = bottom; + *(u32*)&kpad->dpdState.candidates[0].metadata.value = 0; + kpad->dpdState.candidates[0].metadata.bytes.status = 0xFF; + return -1; + } + } else if (right == leftBound || right == rightBound || top == topBound || top == bottomBound) { + u32* objectWords = (u32*)object; + u32* statusWords = (u32*)&*(u32*)&kpad->dpdState.candidates[0].metadata.value; + statusWords[0] = objectWords[0]; + statusWords[1] = objectWords[1]; + statusWords[2] = objectWords[2]; + kpad->dpdState.candidates[1].x = right; + kpad->dpdState.candidates[1].y = top; + *(u32*)&kpad->dpdState.candidates[1].metadata.value = 0; + kpad->dpdState.candidates[1].metadata.bytes.status = 0xFF; + return -1; + } + } + } while (++object < end); + return 0; +} + +static s8 select_1obj_continue(KPADInside* kpad) { + KPADDPDObject* objects = kpad->dpdState.objects; + KPADDPDObject* candidates = kpad->dpdState.candidates; + KPADDPDObject* matchedCandidate = 0; + KPADDPDObject* source = 0; + KPADDPDObject* candidate; + f32 best = kp_err_near_pos * kp_err_near_pos; + candidate = candidates; + do { + if ((s8)candidate->metadata.bytes.flags == 0 && (s8)candidate->metadata.bytes.status == 0) { + KPADDPDObject* object = objects; + do { + if ((s8)object->metadata.bytes.flags == 0) { + f32 dx = candidate->x - object->x; + f32 dy = candidate->y - object->y; + f32 distance = dx * dx + dy * dy; + if (distance < best) { + best = distance; + matchedCandidate = candidate; + source = object; + } + } + } while (++object < candidates); + } + } while (++candidate < (kpad->dpdState.candidates + 2)); + if (best == kp_err_near_pos * kp_err_near_pos) { + return 0; + } + ((u32*)matchedCandidate)[0] = ((u32*)source)[0]; + ((u32*)matchedCandidate)[1] = ((u32*)source)[1]; + ((u32*)matchedCandidate)[2] = ((u32*)source)[2]; + { + f32 axisX = kpad->horizonTangentX; + f32 normX = kpad->horizonAxisX; + f32 axisY = kpad->horizonTangentY; + f32 normY = kpad->horizonAxisY; + f32 distance = kpad->dpdObjectDistance; + f32 horizontal = axisX * normX; + f32 vertical = axisY * normX; + f32 offsetX; + f32 directionX; + f32 directionY; + f32 offsetY; + directionX = horizontal + axisY * normY; + directionY = vertical - axisX * normY; + offsetX = distance * directionX; + kpad->dpdObjectDirectionX = directionX; + offsetY = distance * directionY; + kpad->dpdObjectDirectionY = directionY; + if (matchedCandidate == candidates) { + kpad->dpdState.candidates[1].x = matchedCandidate->x + offsetX; + *(u32*)&kpad->dpdState.candidates[1].metadata.value = 0; + kpad->dpdState.candidates[1].metadata.bytes.status = 0xFF; + kpad->dpdState.candidates[1].y = matchedCandidate->y + offsetY; + } else { + kpad->dpdState.candidates[0].x = matchedCandidate->x - offsetX; + *(u32*)&kpad->dpdState.candidates[0].metadata.value = 0; + kpad->dpdState.candidates[0].metadata.bytes.status = 0xFF; + kpad->dpdState.candidates[0].y = matchedCandidate->y - offsetY; + } + } + if (kpad->status.dpd_valid_fg < 0) { + return -1; + } + return 1; +} + +static void read_kpad_dpd(KPADInside* kpad, KPADSample* status) { + KPADDPDObject* objects = kpad->dpdState.objects; + u8 format = status->dataFormat; + KPADDPDObject* object; + s8 selected = 0; + if (format == 2 || format == 5 || format == 8) { + DPDObject* source = &status->objects[3]; + object = objects + 3; + for (;;) { + if (source->size != 0) { + object->x = (f32)source->x * 0.001953125f - 0.9990234375f; + object->y = (f32)source->y * 0.001953125f - 0.7490234375f; + object->metadata.bytes.flags = 0; + object->metadata.bytes.status = 0; + } else { + object->metadata.bytes.flags = 0xFF; + } + if (object == objects) { + break; + } + object--; + source--; + } + } else { + object = objects + 3; + for (;;) { + object->metadata.bytes.flags = 0xFF; + if (object == objects) { + break; + } + object--; + } + } + object = objects + 3; + for (;;) { + if ((s8)object->metadata.bytes.flags >= 0 && + (object->x == kpad->value4F4 || object->x == kpad->value4FC || + object->y == kpad->value4F8 || object->y == kpad->value500)) { + object->metadata.bytes.flags |= 1; + } + if (object == objects) { + break; + } + object--; + } + for (object = objects; object < objects + 3; object++) { + if ((s8)object->metadata.bytes.flags == 0) { + KPADDPDObject* other = object + 1; + for (;;) { + if ((s8)other->metadata.bytes.flags == 0 && object->x == other->x && object->y == other->y) { + other->metadata.bytes.flags |= 2; + } + if (other == objects + 3) { + break; + } + other++; + } + } + } + kpad->dpdCount = 0; + object = objects + 3; + for (;;) { + if ((s8)object->metadata.bytes.flags == 0) { + kpad->dpdCount++; + } + if (object == objects) { + break; + } + object--; + } + if (kpad->status.acc_vertical.x != kp_err_up_inpr) { + switch (kpad->status.dpd_valid_fg) { + case 2: + case -2: + if (kpad->dpdCount >= 2) { + selected = select_2obj_continue(kpad); + } + if (selected == 0 && kpad->dpdCount >= 1) { + selected = select_1obj_continue(kpad); + } + break; + case 1: + case -1: + if (kpad->dpdCount >= 2) { + selected = select_2obj_first(kpad); + } + if (selected == 0 && kpad->dpdCount >= 1) { + selected = select_1obj_continue(kpad); + } + break; + default: + if (kpad->dpdCount >= 2) { + selected = select_2obj_first(kpad); + } + if (selected == 0 && kpad->dpdCount == 1) { + selected = select_1obj_first(kpad); + } + break; + } + } + if (selected != 0) { + f32 dx = kpad->dpdState.candidates[1].x - kpad->dpdState.candidates[0].x; + f32 dy = kpad->dpdState.candidates[1].y - kpad->dpdState.candidates[0].y; + f32 length = (f32)sqrt(dx * dx + dy * dy); + f32 scale = 1.0f / length; + f32 axisX; + f32 axisY; + kpad->dpdObjectDistance = length; + kpad->dpdObjectDirectionX = dx * scale; + kpad->dpdReferenceDistance = kpad->value510 * scale; + kpad->dpdObjectDirectionY = dy * scale; + axisX = kpad->horizonTangentX * kpad->dpdObjectDirectionX + kpad->horizonTangentY * kpad->dpdObjectDirectionY; + axisY = kpad->horizonTangentY * kpad->dpdObjectDirectionX - kpad->horizonTangentX * kpad->dpdObjectDirectionY; + kpad->dpdAxisX = axisX; + kpad->dpdAxisY = axisY; + if (kpad->horizonCircleCount == 0 && axisX * kpad->horizonAxisX + axisY * kpad->horizonAxisY == kp_err_acc_inpr) { + selected = 0; + *(u32*)&kpad->dpdState.candidates[1].metadata.value = 1; + *(u32*)&kpad->dpdState.candidates[0].metadata.value = 1; + } + if (kpad->status.dpd_valid_fg == 2 && selected == 2) { + if (kpad->value4CA == 0xC8) { + kpad->dpdObjectScale = kpad->dpdObjectDistance; + } else { + kpad->value4CA++; + } + } else { + kpad->value4CA = 0; + } + } else { + kpad->value4CA = 0; + } + calc_dpd_variable(kpad, selected); +} + +static void clamp_stick_circle(Vec2* stick, s32 x, s32 y, s32 minimum, s32 maximum) { + f32 axisX = x; + f32 axisY = y; + f32 minimumValue = minimum; + f32 maximumValue = maximum; + f32 radius = (f32)sqrt(axisX * axisX + axisY * axisY); + if (radius <= minimumValue) { + stick->y = 0.0f; + stick->x = 0.0f; + return; + } + if (radius >= maximumValue) { + stick->x = axisX / radius; + stick->y = axisY / radius; + return; + } + radius = ((radius - minimumValue) / (maximumValue - minimumValue)) / radius; + stick->x = axisX * radius; + stick->y = axisY * radius; +} + +static void clamp_stick_cross(Vec2* stick, s32 x, s32 y, s32 minimum, s32 maximum) { + f32 value; + f32 scale; + s32 magnitude; + if (x < 0) { + magnitude = -x; + if (magnitude <= minimum) { + stick->x = 0.0f; + } else if (magnitude >= maximum) { + stick->x = 1.0f; + } else { + stick->x = (f32)-(x + minimum) / (maximum - minimum); + } + stick->x = -stick->x; + } else if (x <= minimum) { + stick->x = 0.0f; + } else if (x >= maximum) { + stick->x = 1.0f; + } else { + stick->x = (f32)(x - minimum) / (maximum - minimum); + } + if (y < 0) { + magnitude = -y; + if (magnitude <= minimum) { + stick->y = 0.0f; + } else if (magnitude >= maximum) { + stick->y = 1.0f; + } else { + stick->y = (f32)-(y + minimum) / (maximum - minimum); + } + stick->y = -stick->y; + } else if (y <= minimum) { + stick->y = 0.0f; + } else if (y >= maximum) { + stick->y = 1.0f; + } else { + stick->y = (f32)(y - minimum) / (maximum - minimum); + } + value = stick->x; + scale = stick->y; + if (value * value + scale * scale > 1.0f) { + f32 length = (f32)sqrt(value * value + scale * scale); + stick->x /= length; + stick->y /= length; + } +} + +static void read_kpad_stick(KPADInside* kpad, KPADSample* status) { + typedef void (*StickClamp)(Vec2*, s32, s32, s32, s32); + StickClamp clamp = clamp_stick_cross; + KPADEXStatus* extension = &kpad->status.ex_status; + u8 device; + u8 format; + if (kp_stick_clamp_cross != 0) { + clamp = clamp_stick_circle; + } + device = status->device; + format = status->dataFormat; + switch (device) { + case 1: + if ((u8)(format + 0xFD) <= 2) { + if (kpad->flag51E != 0) { + kpad->flag51E = 0; + extension->fs.stick = Vec2_0; + extension->fs.acc.z = 0.0f; + extension->fs.acc.x = 0.0f; + extension->fs.acc.y = -1.0f; + extension->fs.acc_value = 1.0f; + extension->fs.acc_speed = 0.0f; + } + clamp(&extension->fs.stick, status->extension.fs.stickX, status->extension.fs.stickY, kp_fs_fstick_min, kp_fs_fstick_max); + } + break; + case 2: + if ((u8)(format + 0xFA) > 2) { + break; + } + if (kpad->flag51E != 0) { + kpad->flag51E = 0; + extension->cl.lstick = Vec2_0; + extension->cl.rstick = Vec2_0; + extension->cl.rtrigger = 0.0f; + extension->cl.ltrigger = 0.0f; + extension->cl.release = 0; + extension->cl.trig = 0; + extension->cl.hold = 0; + kpad->repeatCurrent = 0; + kpad->repeatCurrent2 = kpad->repeatDelay; + } + clamp(&extension->cl.lstick, status->extension.cl.lStickX, status->extension.cl.lStickY, kp_cl_stick_min, kp_cl_stick_max); + clamp(&extension->cl.rstick, (s8)status->extension.cl.rStickX, (s8)status->extension.cl.rStickY, kp_cl_stick_min, kp_cl_stick_max); + if (status->extension.cl.triggerL <= kp_cl_trigger_min) { + extension->cl.ltrigger = 0.0f; + } else if (status->extension.cl.triggerL >= kp_cl_trigger_max) { + extension->cl.ltrigger = 1.0f; + } else { + extension->cl.ltrigger = (f32)(status->extension.cl.triggerL - kp_cl_trigger_min) / (kp_cl_trigger_max - kp_cl_trigger_min); + } + if (status->extension.cl.triggerR <= kp_cl_trigger_min) { + extension->cl.rtrigger = 0.0f; + break; + } + if (status->extension.cl.triggerR >= kp_cl_trigger_max) { + extension->cl.rtrigger = 1.0f; + break; + } + extension->cl.rtrigger = (f32)(status->extension.cl.triggerR - kp_cl_trigger_min) / (kp_cl_trigger_max - kp_cl_trigger_min); + break; + default: + break; + } +} + +static void reset_kpad(KPADInside* kpad) { + f32 distanceValue; + f32 sensorDistance; + u32* words; + KPADDPDObject* object; + sensorDistance = kpad->referenceDistance; + kpad->flag51D = 0; + kpad->value4F4 = -1.0f + kp_err_outside_frame; + kpad->value4FC = 1.0f - kp_err_outside_frame; + kpad->value4F8 = -0.75f + kp_err_outside_frame; + kpad->value500 = 0.75f - kp_err_outside_frame; + kpad->value504 = 1.0f / kp_err_dist_speed; + kpad->value508 = -1.0f / kp_err_dist_speed; + kpad->value50C = kp_ah_circle_radius * kp_ah_circle_radius; + kpad->value514 = kp_err_dist_min; + distanceValue = kp_dist_vv1 / sensorDistance; + kpad->value510 = kp_dist_vv1; + kpad->status.release = 0; + kpad->status.trig = 0; + kpad->status.hold = 0; + kpad->repeatCount = 0; + kpad->repeatCount2 = kpad->repeatDelay; + kpad->status.dpd_valid_fg = 0; + kpad->value4CA = 0; + kpad->horizonAxisX = 1.0f; + kpad->horizonAxisY = 0.0f; + kpad->status.vec = Vec2_0; + kpad->status.pos = Vec2_0; + kpad->status.speed = 0.0f; + kpad->dpdAxisX = 1.0f; + kpad->status.horizon.x = 1.0f; + kpad->dpdAxisY = 0.0f; + kpad->status.horizon.y = 0.0f; + kpad->status.hori_speed = 0.0f; + kpad->status.acc.z = 0.0f; + kpad->status.acc.x = 0.0f; + words = (u32*)&kpad->status.acc; + kpad->status.acc.y = -1.0f; + kpad->status.hori_vec = Vec2_0; + kpad->status.dist_speed = 0.0f; + kpad->status.acc_vertical.x = 1.0f; + kpad->status.acc_vertical.y = 0.0f; + kpad->status.dist = sensorDistance; + kpad->status.dist_vec = 0.0f; + kpad->dpdReferenceDistance = sensorDistance; + kpad->dpdObjectScale = distanceValue; + kpad->dpdObjectDistance = distanceValue; + kpad->dpdObjectDirectionX = kpad->horizonTangentX; + kpad->dpdObjectDirectionY = kpad->horizonTangentY; + kpad->status.acc_value = 1.0f; + kpad->status.acc_speed = 0.0f; + *(u32*)&kpad->accelerationX = words[0]; + *(u32*)&kpad->accelerationY = words[1]; + *(u32*)&kpad->accelerationZ = words[2]; + *(u32*)&kpad->horizonCircleX = *(u32*)&kpad->horizonAxisX; + *(u32*)&kpad->horizonCircleY = *(u32*)&kpad->horizonAxisY; + kpad->horizonCircleCount = kp_ah_circle_ct; + kpad->dpdCount = 0; + object = &kpad->dpdState.objects[4]; + do { + --object; + object->metadata.bytes.flags = 0xFF; + } while (object != kpad->dpdState.objects); + object = &kpad->dpdState.candidates[2]; + do { + --object; + object->metadata.bytes.flags = 0xFF; + } while (object != kpad->dpdState.candidates); + kpad->ringCount = 0; + kpad->flag51E = 1; +} + +void KPADGetProjectionPos(Vec2* dest, Vec2* src, const Rect* rect, f32 scale) { + f64 scaled; + f32 height = rect->bottom - rect->top; + f32 halfHeight = height * 0.5f; + f32 x = src->x * halfHeight; + f32 y = src->y * halfHeight; + x *= 1.2f; + y *= 1.2f; + scaled = 0.908 * scale; + dest->y = y; + dest->x = (f32)(x * scaled); +} + +void KPADSetSensorHeight(s32 chan, f32 sensorHeight) { + KPADInside* kpad; + f32 halfHeight; + f32 halfWidth; + f32 negativeSensorHeight; + f32 halfWidthSquared; + f32 halfHeightSquared; + f32 barDiagonalSquared; + f32 barOffsetX; + f32 barDiagonal; + halfWidth = 1.0f; + kpad = &inside_kpads[chan]; + halfHeight = 0.75f; + negativeSensorHeight = -sensorHeight; + halfWidthSquared = halfWidth * halfWidth; + halfHeightSquared = halfHeight * halfHeight; + kpad->sensorBarCenterX = 0.0f; + kpad->sensorBarCenterY = negativeSensorHeight; + barDiagonalSquared = halfWidthSquared + halfHeightSquared; + barDiagonal = (f32)sqrt(barDiagonalSquared); + barOffsetX = kpad->sensorBarCenterX; + if (barOffsetX < 0.0f) { + halfWidth = halfWidth + barOffsetX; + } else { + halfWidth = halfWidth - barOffsetX; + } + negativeSensorHeight = kpad->sensorBarCenterY; + if (negativeSensorHeight < 0.0f) { + halfHeight = halfHeight + negativeSensorHeight; + } else { + halfHeight = halfHeight - negativeSensorHeight; + } + if (halfWidth >= halfHeight) { + halfWidth = halfHeight; + } + kpad->sensorBarScale = barDiagonal / halfWidth; +} + +static void calc_dpd_variable(KPADInside* kpad, s8 valid) { + if (valid == 0) { + kpad->status.dpd_valid_fg = 0; + return; + } + { + f32 x = kpad->horizonTangentX * kpad->dpdObjectDirectionX + kpad->horizonTangentY * kpad->dpdObjectDirectionY; + f32 y = kpad->horizonTangentY * kpad->dpdObjectDirectionX - kpad->horizonTangentX * kpad->dpdObjectDirectionY; + if (kpad->status.dpd_valid_fg == 0) { + kpad->status.horizon.x = x; + kpad->status.horizon.y = y; + kpad->status.hori_vec = Vec2_0; + kpad->status.hori_speed = 0.0f; + } else { + f32 dx = x - kpad->status.horizon.x; + f32 dy = y - kpad->status.horizon.y; + f32 length = (f32)sqrt(dx * dx + dy * dy); + f32 amount; + if (length == kpad->value8C) { + amount = 1.0f; + } else { + amount = length / kpad->value8C; + amount *= amount; + amount *= amount; + } + amount *= kpad->value90; + x = kpad->status.horizon.x + amount * dx; + y = kpad->status.horizon.y + amount * dy; + length = (f32)sqrt(x * x + y * y); + x /= length; + y /= length; + kpad->status.hori_vec.x = x - kpad->status.horizon.x; + kpad->status.hori_vec.y = y - kpad->status.horizon.y; + kpad->status.horizon.x = x; + kpad->status.horizon.y = y; + kpad->status.hori_speed = (f32)sqrt(kpad->status.hori_vec.x * kpad->status.hori_vec.x + kpad->status.hori_vec.y * kpad->status.hori_vec.y); + } + } + { + f32 value = kpad->value510 / kpad->dpdObjectDistance; + if (kpad->status.dpd_valid_fg == 0) { + kpad->status.dist = value; + kpad->status.dist_vec = 0.0f; + kpad->status.dist_speed = 0.0f; + } else { + f32 dx = value - kpad->status.dist; + f32 magnitude = dx; + f32 amount; + f32 next; + if (magnitude < 0.0f) { + magnitude = -magnitude; + } + if (magnitude == kpad->value94) { + amount = 1.0f; + } else { + amount = magnitude / kpad->value94; + amount *= amount; + amount *= amount; + } + next = amount * kpad->value98 * dx; + kpad->status.dist_vec = next; + if (next < 0.0f) { + kpad->status.dist_speed = -next; + } else { + kpad->status.dist_speed = next; + } + kpad->status.dist += kpad->status.dist_vec; + } + } + { + f32 rotatedX = kpad->dpdObjectDirectionX * kpad->horizonTangentX + kpad->dpdObjectDirectionY * kpad->horizonTangentY; + f32 rotatedY = -kpad->dpdObjectDirectionY * kpad->horizonTangentX + kpad->dpdObjectDirectionX * kpad->horizonTangentY; + f32 scaleX = 0.5f * (kpad->dpdState.candidates[0].x + kpad->dpdState.candidates[1].x); + f32 scaleY = 0.5f * (kpad->dpdState.candidates[0].y + kpad->dpdState.candidates[1].y); + f32 pointX = kpad->sensorBarScale * (kpad->sensorBarCenterX - (rotatedX * scaleX - rotatedY * scaleY)); + f32 pointY = kpad->sensorBarScale * (kpad->sensorBarCenterY - (rotatedY * scaleX + rotatedX * scaleY)); + f32 x = -kpad->accelNormalY * pointX + kpad->accelNormalX * pointY; + f32 y = -kpad->accelNormalX * pointX - kpad->accelNormalY * pointY; + if (kpad->status.dpd_valid_fg == 0) { + kpad->status.pos.x = x; + kpad->status.pos.y = y; + kpad->status.vec = Vec2_0; + kpad->status.speed = 0.0f; + } else { + f32 dx = x - kpad->status.pos.x; + f32 dy = y - kpad->status.pos.y; + f32 length = (f32)sqrt(dx * dx + dy * dy); + f32 amount; + if (length == kpad->posParamX) { + amount = 1.0f; + } else { + amount = length / kpad->posParamX; + amount *= amount; + amount *= amount; + } + amount *= kpad->posParamY; + kpad->status.vec.x = amount * dx; + kpad->status.vec.y = amount * dy; + kpad->status.speed = (f32)sqrt(kpad->status.vec.x * kpad->status.vec.x + kpad->status.vec.y * kpad->status.vec.y); + kpad->status.pos.x += kpad->status.vec.x; + kpad->status.pos.y += kpad->status.vec.y; + } + } + kpad->status.dpd_valid_fg = valid; +} + +void KPADDisableDPD(s32 chan) { + inside_kpads[chan].dpdEnable = 0; +} + +void KPADEnableDPD(s32 chan) { + inside_kpads[chan].dpdEnable = 1; +} + +void KPADSetControlDpdCallback(s32 chan, KPADCallback* callback) { + BOOL enabled; + enabled = OSDisableInterrupts(); + inside_kpads[chan].dpdCallback = (KPADCallback)callback; + OSRestoreInterrupts(enabled); +} + +s32 KPADRead(s32 chan, KPADStatus* statuses, u32 count) { + KPADInside* kpad = &inside_kpads[chan]; + s32 probe; + u16 interruptState; + u32 available; + u32 ringCount; + s32 start; + u32 sampleIndex; + u32 remaining; + u32 remainingSamples; + u32 outputIndex; + u32 buttons; + u32 previousButtons; + u32 changed; + u16 extensionButtons; + u16 coreButtons; + u8 device; + KPADSample latestSample; + KPADSample* sample; + KPADStatus* output; + WPADAccGravityUnit gravity; + if (WPADGetStatus() != 3) { + return 0; + } + interruptState = OSDisableInterrupts(); + if (kpad->samplingInProgress != 0) { + OSRestoreInterrupts(interruptState); + return 0; + } + kpad->samplingInProgress = 1; + probe = WPADProbe(chan, 0); + if (probe == -1 && kpad->dpdCallback != 0 && kpad->dpdCallbackFired != 0 && kpad->dpdCallbackPending == 0) { + if (kpad->dpdCallback == 0) { + kpad->dpdCallbackPending = 1; + kpad->dpdCallback(chan, 1); + kpad->dpdCallbackFired = 0; + } + kpad->flag51F = 0; + } + OSRestoreInterrupts(interruptState); + if (kpad->flag51D != 0) { + kpad->status.wpad_err = probe; + reset_kpad(kpad); + } + WPADSetSamplingCallback(chan, KPADiSamplingCallback); + if (kpad->ringCount == 0 || statuses == 0 || count == 0) { + kpad->samplingInProgress = 0; + return 0; + } + interruptState = OSDisableInterrupts(); + ringCount = kpad->ringCount; + available = ringCount; + if (available > count) { + available = count; + } + kpad->ringCount = 0; + start = kpad->ringIndex - available; + if (start < 0) { + start += 16; + } + sampleIndex = start; + remaining = available; + output = &statuses[available - 1]; + while (--remaining != 0) { + output--; + *(KPADSample*)output = kpad->ringData[sampleIndex]; + sampleIndex++; + if (sampleIndex >= 16) { + sampleIndex = 0; + } + } + latestSample = kpad->ringData[sampleIndex]; + OSRestoreInterrupts(interruptState); + WPADGetAccGravityUnit(chan, WPAD_ACC_GRAVITY_UNIT_CORE, &gravity); + if (gravity.z * gravity.x * gravity.y != 0) { + kpad->value4DC = 1.0f / gravity.x; + kpad->value4E0 = 1.0f / gravity.y; + kpad->value4E4 = 1.0f / gravity.z; + } else { + kpad->value4DC = 0.01f; + kpad->value4E0 = 0.01f; + kpad->value4E4 = 0.01f; + } + WPADGetAccGravityUnit(chan, WPAD_ACC_GRAVITY_UNIT_FS, &gravity); + if (gravity.z * gravity.x * gravity.y != 0) { + kpad->value4E8 = 1.0f / gravity.x; + kpad->value4EC = 1.0f / gravity.y; + kpad->value4F0 = 1.0f / gravity.z; + } else { + kpad->value4E8 = 0.005f; + kpad->value4EC = 0.005f; + kpad->value4F0 = 0.005f; + } + remainingSamples = available; + output = &statuses[available - 1]; + device = 0xFD; + coreButtons = 0xFFFF; + extensionButtons = 0xFFFF; + buttons = 0xFFFF; + while (remainingSamples != 0) { + output--; + sample = remainingSamples > 1 ? (KPADSample*)output : &latestSample; + switch (sample->error) { + case 0: + device = sample->device; + if (device == 1) { + coreButtons = sample->buttons; + extensionButtons = 0; + } else if (device == 2) { + coreButtons = 0; + extensionButtons = sample->extension.cl.buttons; + } else { + coreButtons = 0; + extensionButtons = 0; + } + buttons = sample->buttons; + break; + case -2: + case -7: + buttons = sample->buttons; + break; + } + remainingSamples--; + } + if (buttons == 0xFFFF) { + output = statuses; + remaining = available; + while (remaining != 0) { + *output++ = kpad->status; + remaining--; + } + } else { + if (coreButtons == 0xFFFF) { + coreButtons = kpad->status.hold; + } + if (extensionButtons == 0xFFFF) { + extensionButtons = kpad->status.ex_status.cl.hold; + } + buttons = (buttons & 0x9FFF & ~0x6000) | (coreButtons & 0x6000); + previousButtons = kpad->status.hold; + changed = previousButtons ^ buttons; + kpad->status.hold = buttons; + kpad->status.trig = changed & buttons; + kpad->status.release = changed & previousButtons; + if (device == 2) { + previousButtons = kpad->status.ex_status.cl.hold; + kpad->status.ex_status.cl.hold = extensionButtons; + changed = previousButtons ^ extensionButtons; + kpad->status.ex_status.cl.trig = changed & extensionButtons; + kpad->status.ex_status.cl.release = changed & previousButtons; + } + calc_button_repeat(kpad, device, ringCount); + remainingSamples = available; + outputIndex = available - 1; + output = &statuses[outputIndex]; + while (remainingSamples != 0) { + output--; + sample = remainingSamples > 1 ? (KPADSample*)output : &latestSample; + kpad->status.wpad_err = sample->error; + if (kpad->status.dev_type != sample->device && (u8)(sample->error + 2) <= 2) { + kpad->status.dev_type = sample->device; + kpad->flag51E = 1; + } + kpad->status.data_format = sample->dataFormat; + switch (sample->error) { + case 0: + read_kpad_stick(kpad, sample); + case -7: + read_kpad_acc(kpad, sample); + read_kpad_dpd(kpad, sample); + break; + default: + kpad->status.dpd_valid_fg = 0; + } + statuses[outputIndex] = kpad->status; + outputIndex--; + remainingSamples--; + } + } + kpad->samplingInProgress = 0; + return available; +} + +void KPADInit(void) { + KPADInside* kpad; + f32 distanceValue; + f32 sensorDistance; + f32 rotationElement; + f32 referenceWidth; + f32 referenceHeight; + f32 objectInterval; + f32 zero; + f32 degreesToRadians; + f32 one; + f32 adjustedWidth; + f32 adjustedHeight; + f32* matrix; + u32 i; + s32 chan; + BOOL enabled; + WPADInit(); + memset(inside_kpads, 0, 0x14A0); + matrix = initial_rotation_matrix; + chan = 0; + one = 1.0f; + zero = 0.0f; + degreesToRadians = 0.017453292f; + kp_err_dist_max = one + (f32)WPADGetDpdSensitivity(); + kpad = inside_kpads; + do { + kpad->dpdEnable = 1; + referenceWidth = 1.0f; + kpad->dpdFormat = 0; + referenceHeight = 0.75f; + kpad->status.dev_type = 0xFD; + kpad->status.data_format = 0; + kpad->referenceDistance = idist_org; + *(u32*)&kpad->accelNormalX = ((u32*)&iaccXY_nrm_hori)[0]; + *(u32*)&kpad->accelNormalY = ((u32*)&iaccXY_nrm_hori)[1]; + *(u32*)&kpad->horizonTangentX = ((u32*)&isec_nrm_hori)[0]; + *(u32*)&kpad->horizonTangentY = ((u32*)&isec_nrm_hori)[1]; + *(u32*)&kpad->sensorBarCenterX = ((u32*)&icenter_org)[0]; + *(u32*)&kpad->sensorBarCenterY = ((u32*)&icenter_org)[1]; + distanceValue = kpad->sensorBarCenterX; + sensorDistance = (f32)sqrt(referenceWidth * referenceWidth + referenceHeight * referenceHeight); + if (distanceValue < zero) { + adjustedWidth = referenceWidth + distanceValue; + } else { + adjustedWidth = referenceWidth - distanceValue; + } + distanceValue = kpad->sensorBarCenterY; + if (distanceValue < zero) { + adjustedHeight = referenceHeight + distanceValue; + } else { + adjustedHeight = referenceHeight - distanceValue; + } + if (adjustedWidth < adjustedHeight) { + } else { + adjustedWidth = adjustedHeight; + } + matrix[0] = one; + matrix[1] = zero; + matrix[2] = zero; + matrix[3] = zero; + kpad->sensorBarScale = sensorDistance / adjustedWidth; + kpad->value9C = zero; + kpad->value94 = zero; + kpad->value8C = zero; + kpad->posParamX = zero; + kpad->valueA0 = one; + kpad->value98 = one; + kpad->value90 = one; + kpad->posParamY = one; + kpad->repeatDelay = 40000; + kpad->repeatInterval = 0; + kpad->repeatCount = 0; + kpad->repeatCount2 = 40000; + kpad->repeatCurrent = 0; + kpad->repeatCurrent2 = 40000; + kpad->sensorHeightPending = 1; + kpad->sensorBarPosition = 1; + kpad->freeStyleAccelRotation = 0; + matrix[4] = zero; + rotationElement = (f32)cos(degreesToRadians * sensor_bar_angle_degrees); + matrix[5] = rotationElement; + matrix[7] = zero; + matrix[8] = zero; + rotationElement = (f32)-sin(degreesToRadians * sensor_bar_angle_degrees); + matrix[6] = rotationElement; + rotationElement = (f32)sin(degreesToRadians * sensor_bar_angle_degrees); + matrix[9] = rotationElement; + rotationElement = (f32)cos(degreesToRadians * sensor_bar_angle_degrees); + matrix[10] = rotationElement; + matrix[11] = zero; + { + KPADSample* record = kpad->ringData; + i = 0; + do { + i++; + record->error = -1; + record++; + } while (i < 16); + } + chan++; + kpad++; + } while (chan < 4); + objectInterval = kp_obj_interval; + enabled = OSDisableInterrupts(); + kp_obj_interval = objectInterval; + distanceValue = objectInterval / 0.383864f; + kp_err_dist_min = distanceValue; + kp_dist_vv1 = distanceValue; + OSRestoreInterrupts(enabled); + chan = 3; + kpad = &inside_kpads[3]; + do { + if (WPADGetStatus() == 3) { + WPADControlMotor(chan, 0); + } + chan--; + kpad->flag51D = 1; + kpad--; + } while (chan >= 0); + OSRegisterVersion(__KPADVersion); +} + +static void KPADiSamplingCallback(s32 chan) { + KPADInside* kpad = &inside_kpads[chan]; + u32 device; + if (WPADProbe(chan, &device) != -1) { + u8 index = kpad->ringIndex; + KPADSample* status; + u32 tier; + u32 enabled; + u32 tableIndex; + if (index >= 16) { + index = 0; + } + status = &kpad->ringData[index]; + WPADRead(chan, (WPADStatus*)status); + status->dataFormat = WPADGetDataFormat(chan); + kpad->ringIndex = index + 1; + if (kpad->ringCount < 16) { + kpad->ringCount++; + } + if (kpad->sensorHeightPending != 0) { + f32 sensor = 0.0f; + f32 angle; + f32 height = 0.75f; + f32 distance; + f32 x = 1.0f; + f32 y; + if (kpad->sensorBarPosition != 0) { + if (WPADGetSensorBarPosition() == 1) { + sensor = 0.2f; + } else { + sensor = -0.2f; + } + } + y = -sensor; + kpad->sensorBarCenterX = 0.0f; + kpad->sensorBarCenterY = y; + angle = (f32)sqrt(x * x + height * height); + if (kpad->sensorBarCenterX < 0.0f) { + x += kpad->sensorBarCenterX; + } else { + x -= kpad->sensorBarCenterX; + } + if (kpad->sensorBarCenterY < 0.0f) { + height += kpad->sensorBarCenterY; + } else { + height -= kpad->sensorBarCenterY; + } + if (x >= height) { + x = height; + } + distance = angle / x; + kpad->sensorBarScale = distance; + kpad->sensorHeightPending = 0; + } + switch (device) { + case 0xFF: + tier = 0; + break; + case 1: + tier = 2; + break; + case 2: + tier = 4; + break; + default: + tier = 0; + break; + } + if (kpad->dpdEnable != 0) { + tier++; + } + enabled = WPADIsDpdEnabled(chan) != 0 ? kpad->dpdFormat : 0; + tableIndex = tier * 2; + if (enabled != dpdModeTable[tableIndex]) { + if (kpad->dpdCallback != 0 && kpad->dpdCallbackFired == 0) { + kpad->dpdCallbackFired = 1; + kpad->dpdCallback(chan, 0); + kpad->dpdCallbackPending = 0; + } + if (kpad->flag51F == 0) { + kpad->flag51F = 1; + if (WPADControlDpd(chan, dpdModeTable[tableIndex], KPADiControlDpdCallback) == 0) { + kpad->dpdFormat = dpdModeTable[tableIndex]; + } + } + } else if (status->dataFormat != dpdModeTable[tableIndex + 1]) { + WPADSetDataFormat(chan, dpdModeTable[tableIndex + 1]); + } + } + if (kpad->samplingCallback != 0) { + kpad->samplingCallback(chan); + } +} + +static void KPADiControlDpdCallback(s32 chan, s32 result) { + KPADInside* kpad = &inside_kpads[chan]; + if (result == 0 && kpad->dpdCallback != 0 && kpad->dpdCallbackPending == 0) { + kpad->dpdCallbackPending = 1; + kpad->dpdCallback(chan, 1); + kpad->dpdCallbackFired = 0; + } + kpad->flag51F = 0; +} -- 2.49.1 From 0421e7e9bee3dac1349faf619b3c569c75db1343 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 00:07:30 +0000 Subject: [PATCH 03/61] start decompiling setting scene --- include/scene/setting/iplSetting.h | 59 +++++++++++++++++++++++++++++- src/scene/setting/iplSetting.cpp | 46 +++++++++++++++++++++++ 2 files changed, 104 insertions(+), 1 deletion(-) create mode 100644 src/scene/setting/iplSetting.cpp diff --git a/include/scene/setting/iplSetting.h b/include/scene/setting/iplSetting.h index e3152884..7fde5b5e 100644 --- a/include/scene/setting/iplSetting.h +++ b/include/scene/setting/iplSetting.h @@ -3,14 +3,47 @@ #include "iplSceneHeader.h" +#ifdef IPL_SETTING_IMPLEMENTATION +#include +#endif + namespace ipl { namespace scene { +#ifdef IPL_SETTING_IMPLEMENTATION + class APEvent { + public: + u8 unknown[4]; + u8 eventType; + }; + + struct SettingAnimation { + u8 unknown[0x14]; + int state; + }; +#endif + FADER_SCENE_CLASS(Setting) { public: Setting(EGG::Heap * heap, int arg); - void setInitializeResult(bool, int); +#ifdef IPL_SETTING_IMPLEMENTATION + virtual ~Setting(); + + bool isAnimating(); + void getFuncMsgQ(); + void resetFuncMsgQ(); + virtual void destroy(); + virtual void prepare(); + virtual void create(); + virtual void calc(); + virtual void draw(); + virtual FaderSceneCommand calcFadein(); + virtual FaderSceneCommand calcNormal(); + virtual FaderSceneCommand calcFadeout(); + virtual BOOL isResetAcceptable() const; +#endif u16 getProfileID(); + void setInitializeResult(bool, int); void setConnectTestResult(int, int, bool, int); int getUpdateTiming(); @@ -25,7 +58,31 @@ namespace ipl { }; private: +#ifdef IPL_SETTING_IMPLEMENTATION + int mUpdateTiming; + u8 unk_0x5C[0x24]; + int mProfileIDMode; + u8 unk_0x84[0xC]; + int mFuncMsgPending; + u8 unk_0x94[0x38]; + SettingAnimation* mpFirstAnimation; + SettingAnimation* mpSecondAnimation; + u8 unk_0xD4[0xC]; + void* mpResource1; + void* mpResource2; + u8 unk_0xE8[0x840]; + APEvent* mpAPEvent; + u8 unk_0x92C[0x230]; + u8 mIsResetAcceptable; + u8 unk_0xB5D[3]; + OSMessageQueue mFuncMessageQueue; + u8 unk_0xB80[0x18]; + int mState; + u8 unk_0xB9C[0x24]; +#else u8 unk_0x58[0xB68]; +#endif + }; } // namespace scene } // namespace ipl diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp new file mode 100644 index 00000000..2027ed48 --- /dev/null +++ b/src/scene/setting/iplSetting.cpp @@ -0,0 +1,46 @@ +#define IPL_SETTING_IMPLEMENTATION +#include "scene/setting/iplSetting.h" + +#include "scene/setting/iplNCDSetting.h" + +namespace ipl { + namespace scene { + bool Setting::isAnimating() { + return mpSecondAnimation->state == 1 || mpFirstAnimation->state == 1 || mState != 20; + } + + void Setting::getFuncMsgQ() { + OSMessage message = 0; + if (mFuncMsgPending == 0 && OSReceiveMessage(&mFuncMessageQueue, &message, 0)) { + mFuncMsgPending = 1; + mpAPEvent->eventType = (u8)message; + } + } + + void Setting::resetFuncMsgQ() { + mpAPEvent->eventType = 0; + mFuncMsgPending = 0; + } + + u16 Setting::getProfileID() { + if (mProfileIDMode < 3) { + return ncd::NCDSetting::getID(); + } + + u16 profileID = ncd::NCDSetting::getUseProfileID(); + ncd::NCDSetting::initSetID(profileID & 0xFF); + if ((profileID & 0xFF) == 3) { + profileID = 0; + } + return profileID; + } + + int Setting::getUpdateTiming() { + return mUpdateTiming; + } + + BOOL Setting::isResetAcceptable() const { + return mIsResetAcceptable; + } + } // namespace scene +} // namespace ipl -- 2.49.1 From b1e91f7a7f034133b974e20352ba48314297c263 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 00:09:04 +0000 Subject: [PATCH 04/61] match basic setting scene helpers --- src/scene/setting/iplSetting.cpp | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 2027ed48..9a7abfc3 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -23,14 +23,15 @@ namespace ipl { } u16 Setting::getProfileID() { - if (mProfileIDMode < 3) { - return ncd::NCDSetting::getID(); - } - - u16 profileID = ncd::NCDSetting::getUseProfileID(); - ncd::NCDSetting::initSetID(profileID & 0xFF); - if ((profileID & 0xFF) == 3) { - profileID = 0; + u16 profileID; + if (mProfileIDMode >= 3) { + profileID = ncd::NCDSetting::getUseProfileID(); + ncd::NCDSetting::initSetID(profileID & 0xFF); + if ((u8)profileID == 3) { + profileID = 0; + } + } else { + profileID = ncd::NCDSetting::getID(); } return profileID; } -- 2.49.1 From 615e8c93bdc303f6522059466703c3944d530611 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 00:11:08 +0000 Subject: [PATCH 05/61] match setting constructor and storage --- include/scene/setting/iplSetting.h | 47 +++++++++++++++++++++++++----- src/scene/setting/iplSetting.cpp | 41 ++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 7 deletions(-) diff --git a/include/scene/setting/iplSetting.h b/include/scene/setting/iplSetting.h index 7fde5b5e..81c2ee74 100644 --- a/include/scene/setting/iplSetting.h +++ b/include/scene/setting/iplSetting.h @@ -60,25 +60,58 @@ namespace ipl { private: #ifdef IPL_SETTING_IMPLEMENTATION int mUpdateTiming; - u8 unk_0x5C[0x24]; + u8 unk_0x5C; + u8 unk_0x5D[3]; + int unk_0x60; + int unk_0x64; + int unk_0x68; + int unk_0x6C; + u8 unk_0x70[4]; + int unk_0x74; + int unk_0x78; + int unk_0x7C; int mProfileIDMode; - u8 unk_0x84[0xC]; + int unk_0x84; + u8 unk_0x88[8]; int mFuncMsgPending; - u8 unk_0x94[0x38]; + int unk_0x94; + u8 unk_0x98[0x24]; + int unk_0xBC; + u8 unk_0xC0[0xC]; SettingAnimation* mpFirstAnimation; SettingAnimation* mpSecondAnimation; u8 unk_0xD4[0xC]; void* mpResource1; void* mpResource2; - u8 unk_0xE8[0x840]; + u8 unk_0xE8[0x82C]; + int unk_0x914; + int unk_0x918; + u8 unk_0x91C[4]; + u8 unk_0x920[8]; APEvent* mpAPEvent; - u8 unk_0x92C[0x230]; + u8 unk_0x92C; + u8 unk_0x92D[3]; + int unk_0x930; + u8 unk_0x934[0x207]; + u8 unk_0xB3B; + u8 unk_0xB3C[0x10]; + int mInitialArgument; + int mAspectRatio; + int mProgressiveMode; + int mEuRgb60Mode; u8 mIsResetAcceptable; u8 unk_0xB5D[3]; OSMessageQueue mFuncMessageQueue; - u8 unk_0xB80[0x18]; + u8 unk_0xB80[0x14]; + int unk_0xB94; int mState; - u8 unk_0xB9C[0x24]; + int unk_0xB9C; + u8 unk_0xBA0[0xC]; + u8 unk_0xBAC; + u8 unk_0xBAD[3]; + u8 unk_0xBB0[0x10]; + static void* mem1Buffer_; + static void* mem2Buffer_; #else u8 unk_0x58[0xB68]; #endif diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 9a7abfc3..bce860db 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -5,6 +5,47 @@ namespace ipl { namespace scene { + NCDAossConfig m_AOSSConfig; + NCDRakuApConfig m_RakuConfig; + + void* Setting::mem1Buffer_; + void* Setting::mem2Buffer_; + + Setting::Setting(EGG::Heap* heap, int arg) : FaderSceneBase(heap) { + unk_0x5C = 0; + unk_0x60 = 0; + unk_0x64 = 0; + unk_0x68 = 0; + unk_0x6C = 0; + unk_0xBC = 0; + unk_0xB3B = 0; + setSceneParentFlags(3); + unk_0x74 = 0; + mInitialArgument = arg; + unk_0x78 = 1; + unk_0x84 = 1; + mProfileIDMode = 0; + mUpdateTiming = 0; + unk_0x914 = 0; + unk_0x918 = -1; + unk_0x91C[0] = 0; + unk_0x91C[1] = 0; + unk_0x91C[2] = 0; + unk_0x91C[3] = 0; + unk_0x7C = 0; + unk_0xB9C = 0; + unk_0x92C = 0; + unk_0x930 = 0; + mIsResetAcceptable = 1; + mFuncMsgPending = 0; + mAspectRatio = SCGetAspectRatio(); + mProgressiveMode = SCGetProgressiveMode(); + mEuRgb60Mode = SCGetEuRgb60Mode(); + unk_0xB94 = 0; + unk_0xBAC = 0; + unk_0x94 = 0; + } + bool Setting::isAnimating() { return mpSecondAnimation->state == 1 || mpFirstAnimation->state == 1 || mState != 20; } -- 2.49.1 From 195be9e73463114881ba1410db51882059b01e36 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 00:21:49 +0000 Subject: [PATCH 06/61] match setting lookup helpers --- include/scene/setting/iplSetting.h | 2 ++ src/scene/setting/iplSetting.cpp | 45 ++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/include/scene/setting/iplSetting.h b/include/scene/setting/iplSetting.h index 81c2ee74..4343dc1c 100644 --- a/include/scene/setting/iplSetting.h +++ b/include/scene/setting/iplSetting.h @@ -31,6 +31,8 @@ namespace ipl { bool isAnimating(); void getFuncMsgQ(); void resetFuncMsgQ(); + int get_arw_no(const char* paneName); + int get_ap_no(const char* buttonName); virtual void destroy(); virtual void prepare(); virtual void create(); diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index bce860db..fb3a2a5a 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -5,6 +5,29 @@ namespace ipl { namespace scene { + static const char* sSettingAPButtonNames[] = { + "B_AP2", "B_AP3", "B_AP4", "B_AP5", "T_Name1", "T_Name2", "T_Name3", "T_Name4", + "T_Name5", "T_Name6", "N_AP1", "N_AP2", "N_AP3", "N_AP4", "N_AP5", "N_AP6", + }; + + static const char* sSettingArrowNames[] = {"B_ArwA", "B_ArwB"}; + + static const char* sSettingAPPaneNames[] = { + "G_ListUpDown", "G_ListInOut", "G_ArwA", "G_ArwB", "G_Denpa", "G_Lock", "G_AP0", + "G_AP1", "G_AP2", "G_AP3", "G_AP4", "G_AP5", "G_AP6", "G_AP7", + "G_Denpa1", "G_Denpa2", "G_Denpa3", "G_Denpa4", "G_Denpa5", "G_Denpa6", + "G_Lock1", "G_Lock2", "G_Lock3", "G_Lock4", "G_Lock5", "G_Lock6", + }; + + static const char* sSettingAPAnimations[] = { + "my_AP_a_ArwAppear.brlan", "my_AP_a_ArwLost.brlan", "my_AP_a_ArwFocusOn.brlan", + "my_AP_a_ArwFocusOff.brlan", "my_AP_a_ArwSelect.brlan", "my_AP_a_ScrollUp.brlan", + "my_AP_a_ScrollDown.brlan", "my_AP_a_BtnFocusOn.brlan", "my_AP_a_BtnFocusOff.brlan", + "my_AP_a_ListAppear.brlan", "my_AP_a_ListLost.brlan", "my_AP_a_Denpa0.brlan", + "my_AP_a_Denpa1.brlan", "my_AP_a_Denpa2.brlan", "my_AP_a_Denpa3.brlan", + "my_AP_a_LockOff.brlan", "my_AP_a_LockOn.brlan", + }; + NCDAossConfig m_AOSSConfig; NCDRakuApConfig m_RakuConfig; @@ -81,6 +104,28 @@ namespace ipl { return mUpdateTiming; } + int Setting::get_arw_no(const char* paneName) { + int result = -1; + for (int index = 0; index < 2; index++) { + if (strcmp(sSettingArrowNames[index], paneName) == 0) { + result = index; + break; + } + } + return result; + } + + int Setting::get_ap_no(const char* buttonName) { + int result = -1; + for (int index = 0; index < 4; index++) { + if (strcmp(sSettingAPButtonNames[index], buttonName) == 0) { + result = index; + break; + } + } + return result; + } + BOOL Setting::isResetAcceptable() const { return mIsResetAcceptable; } -- 2.49.1 From 8b3f5ea4b6a64e132dd332b5ea13367e44e7ca3b Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 00:26:42 +0000 Subject: [PATCH 07/61] match setting cleanup methods --- include/scene/setting/iplSetting.h | 16 ++++++----- src/scene/setting/iplSetting.cpp | 44 +++++++++++++++++++++++++++--- 2 files changed, 49 insertions(+), 11 deletions(-) diff --git a/include/scene/setting/iplSetting.h b/include/scene/setting/iplSetting.h index 4343dc1c..5f6f86b0 100644 --- a/include/scene/setting/iplSetting.h +++ b/include/scene/setting/iplSetting.h @@ -5,6 +5,8 @@ #ifdef IPL_SETTING_IMPLEMENTATION #include +#include "system/iplNand.h" +#include "utility/iplThread.h" #endif namespace ipl { @@ -64,11 +66,11 @@ namespace ipl { int mUpdateTiming; u8 unk_0x5C; u8 unk_0x5D[3]; - int unk_0x60; - int unk_0x64; - int unk_0x68; - int unk_0x6C; - u8 unk_0x70[4]; + nand::Base* mpBrowserFile; + nand::Base* mpLanguageFile; + nand::Base* mpNandFile; + nand::Base* mpStringFile; + nand::Base* mpMessageFile; int unk_0x74; int unk_0x78; int unk_0x7C; @@ -83,8 +85,8 @@ namespace ipl { SettingAnimation* mpFirstAnimation; SettingAnimation* mpSecondAnimation; u8 unk_0xD4[0xC]; - void* mpResource1; - void* mpResource2; + utility::ut_thread* mpAOSSThread; + utility::ut_thread* mpRakuRakuThread; u8 unk_0xE8[0x82C]; int unk_0x914; int unk_0x918; diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index fb3a2a5a..e88b11df 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -2,6 +2,7 @@ #include "scene/setting/iplSetting.h" #include "scene/setting/iplNCDSetting.h" +#include "system/iplSystem.h" namespace ipl { namespace scene { @@ -36,10 +37,10 @@ namespace ipl { Setting::Setting(EGG::Heap* heap, int arg) : FaderSceneBase(heap) { unk_0x5C = 0; - unk_0x60 = 0; - unk_0x64 = 0; - unk_0x68 = 0; - unk_0x6C = 0; + mpBrowserFile = 0; + mpLanguageFile = 0; + mpNandFile = 0; + mpStringFile = 0; unk_0xBC = 0; unk_0xB3B = 0; setSceneParentFlags(3); @@ -86,6 +87,41 @@ namespace ipl { mFuncMsgPending = 0; } + Setting::~Setting() { + OSReport("***Destruct!!\n"); + if (mem1Buffer_) { + System::createMem1AppHeap()->free(mem1Buffer_); + mem1Buffer_ = 0; + } + if (mem2Buffer_) { + System::getMem2App()->free(mem2Buffer_); + mem2Buffer_ = 0; + } + if (mpBrowserFile) { + delete mpBrowserFile; + } + if (mpLanguageFile) { + delete mpLanguageFile; + } + if (mpNandFile) { + delete mpNandFile; + } + if (mpStringFile) { + delete mpStringFile; + } + if (mpMessageFile) { + delete mpMessageFile; + } + System::destroyMem1AppHeap(); + System::getBS2Manager()->restart(); + OSReport(" ... bs2 manager restarted\n"); + } + + void Setting::destroy() { + delete mpAOSSThread; + delete mpRakuRakuThread; + } + u16 Setting::getProfileID() { u16 profileID; if (mProfileIDMode >= 3) { -- 2.49.1 From 258f4a6f911be249e17023962307324d34b74337 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Mon, 28 Sep 2026 19:31:31 -0500 Subject: [PATCH 08/61] iplAddressEdit: 77/94 functions, no inline asm left (#244) * remove stale address edit externs * use keyboard input form member * use nigaoe name member * decompile address edit fade-in * decompile address edit normal init * decompile address edit fadeout init * decompile address edit common calc * decompile address edit normal state * decompile delete message fade-in * decompile friend info removal * decompile delete result transition * decompile delete result state * decompile input wait fade-in * decompile input normal state * decompile address edit draw * model string owner pointer * decompile friend code formatting * decompile duplicate friend code check * decompile own friend code check * decompile Wii ID formatting * decompile address edit fadeout * decompile address edit button fade-in * remove stale address edit symbols * match address edit event dispatch * simplify address edit pane access * match address edit decision animations * match address edit event dispatch * match address edit button fadeout * match address edit delete animation * match address edit mii fadeout * simplify address edit state handlers * simplify address edit state dispatch * simplify address edit scene creation --- include/scene/address/iplAddressEdit.h | 4 +- src/scene/address/iplAddressEdit.cpp | 1137 ++++++------------------ 2 files changed, 277 insertions(+), 864 deletions(-) diff --git a/include/scene/address/iplAddressEdit.h b/include/scene/address/iplAddressEdit.h index 501c89bf..20f4f466 100644 --- a/include/scene/address/iplAddressEdit.h +++ b/include/scene/address/iplAddressEdit.h @@ -114,6 +114,8 @@ namespace ipl { void setName(const wchar_t* value); void setEMail(const wchar_t* value); void setWiiNo(const wchar_t* value); + BOOL isDupCode() const; + BOOL isMyCode() const; wchar_t mValue[0x102]; wchar_t mName[0x0c]; @@ -121,6 +123,7 @@ namespace ipl { bool mbValidMail; bool mbNameNotEmpty; bool mbHasWiiNo; + AddressEdit* mpCallbackOwner; }; enum { @@ -144,7 +147,6 @@ namespace ipl { TextBalloon* mpBalloon; nand::LayoutFile* mpBalloonFile; String mString; - AddressEdit* mpCallbackOwner; bool mbParentalOK; nigaoe::Object* mpNigaoe; RFLCreateID mCreateID; diff --git a/src/scene/address/iplAddressEdit.cpp b/src/scene/address/iplAddressEdit.cpp index 791c5145..271ffeab 100644 --- a/src/scene/address/iplAddressEdit.cpp +++ b/src/scene/address/iplAddressEdit.cpp @@ -65,9 +65,6 @@ namespace ipl { } } -extern "C" u8 __vt__Q33ipl5scene11AddressEdit[]; -extern "C" void __dl__FPv(void*); - ipl::keyboard::Manager::KeyboardSetting::KeyboardSetting( ipl::keyboard::Manager::KeyboardType keyboardType, const wchar_t* value, u32 limit, u32 rows) { type = keyboardType; @@ -82,7 +79,7 @@ ipl::scene::AddressEdit::AddressEdit(EGG::Heap* heap, int friendCode) mSelectedButton = -1; mSubState = -1; mSelectedFriend = 0; - mpCallbackOwner = this; + mString.mpCallbackOwner = this; mString.clear(); mbParentalOK = false; mpNigaoe = NULL; @@ -140,29 +137,11 @@ void ipl::scene::AddressEdit::reset_gui() { } -extern "C" u8 __vt__Q33ipl5scene16AddressEditEvent[]; -extern "C" u8 __vt__Q33ipl5scene17AddressInputEvent[]; extern "C" void* __nw__FUl(u32); extern "C" BOOL RFLSearchOfficialData(const RFLCreateID*, u16*); extern "C" NWC24FriendInfo sFriendInfo__Q23ipl5scene; -extern "C" char smArg__Q23ipl6System; extern "C" const char* smButtonName__Q33ipl5scene6Button[]; -extern "C" void readLayoutAsync__Q33ipl4nand7ManagerFPQ23EGG4HeapPCcb(); -extern "C" void List_GetNth__Q24nw4r2utFPCQ34nw4r2ut4ListUs(); -extern "C" void getScene__Q33ipl5scene7ManagerFi(); -extern "C" void UTF16ToANSI__Q33ipl7utility13CharacterCodeFPUcPCwl(); -extern "C" void reset_friend__Q33ipl5scene7AddressFv(); -extern "C" void callBtn1__Q23ipl12DialogWindowFUlUl(); -extern "C" void setEventHandler__Q33ipl5scene6ButtonFPQ23gui12EventHandlerPQ23gui12EventHandler(); -extern "C" void calc__Q33ipl5scene11TextBalloonFv(); -extern "C" void calc__Q33ipl6layout6ObjectFv(); -extern "C" void isActive__Q33ipl5scene6ButtonCFv(); -extern "C" void update__Q33ipl5scene6ButtonFv(); -extern "C" void update__Q33ipl3gui11PaneManagerFv(); -extern "C" void setOrtho__Q33ipl7utility8GraphicsFUl(); -extern "C" void draw__Q33ipl6layout6ObjectFv(); -extern "C" void draw__Q33ipl5scene11TextBalloonFv(); @@ -174,12 +153,6 @@ extern "C" void draw__Q33ipl5scene11TextBalloonFv(); int ipl::scene::AddressEdit::get_button_no(const char*); -extern "C" void callS2Btn2__Q23ipl12DialogWindowFUlUlb(); -extern "C" void reserveText__Q33ipl5scene6ButtonFiUl(); -extern "C" void reserveAnm__Q33ipl5scene6ButtonFi(); -extern "C" void initFrame__Q33ipl7utility15FrameControllerFv(); -extern "C" void getMessage__Q33ipl7message7MessageCFUl(); -extern "C" void del__Q33ipl5scene15FriendListCacheFUl(); @@ -189,21 +162,6 @@ extern "C" void del__Q33ipl5scene15FriendListCacheFUl(); extern "C" NWC24Err NWC24CheckPublicMailAddr_(const char*); -extern "C" void __div2u(); -extern "C" void __mod2u(); -extern "C" u64 utf16_wiiid__Q33ipl5scene11AddressEditFPCw(const wchar_t*); -extern "C" void isValidId__Q33ipl5scene15FriendListCacheFRCUx(); -extern "C" void isDupId__Q33ipl5scene15FriendListCacheFRCUx(); -extern "C" void isDupMail__Q33ipl5scene15FriendListCacheFPCc(); - - - -extern "C" void _savegpr_29(); -extern "C" void _restgpr_29(); -extern "C" void _savegpr_23(); -extern "C" void _savegpr_27(); -extern "C" void _restgpr_23(); -extern "C" void _restgpr_27(); @@ -351,33 +309,6 @@ const wchar_t* ipl::scene::AddressEdit::String::getDispCodeLong() const { return mDisplayText; } -extern "C" asm const wchar_t* getName__Q33ipl6nigaoe6ObjectCFv(void*) { - nofralloc - stwu r1, -0x10(r1) - mflr r0 - stw r0, 0x14(r1) - lwz r0, 0x3c(r3) - cmpwi r0, 0 - blt getName_L1 - clrlwi r3, r0, 16 - bl RFLiGetCharData - addi r3, r3, 2 - b getName_L2 -getName_L1: - li r3, 0 -getName_L2: - lwz r0, 0x14(r1) - mtlr r0 - addi r1, r1, 0x10 - blr -} - -extern "C" asm void getInputForm__Q29textinput7ManagerFv() { - nofralloc - lwz r3, 0x1c(r3) - blr -} - void ipl::scene::AddressEdit::String::clear() { memset(mValue, 0, sizeof(mValue)); memset(mName, 0, sizeof(mName)); @@ -405,156 +336,52 @@ void ipl::scene::AddressEdit::String::setEMail(const wchar_t* value) { mbValidMail = !NWC24CheckPublicMailAddr_(reinterpret_cast(address)); } -extern "C" asm void setWiiNo__Q43ipl5scene11AddressEdit6StringFPCw(void*, const wchar_t*) { - nofralloc - stwu r1, -0x20(r1) - mflr r0 - stw r0, 0x24(r1) - addi r11, r1, 0x20 - bl _savegpr_29 - li r0, 1 - mr r31, r4 - stb r0, 0x422(r3) - mr r30, r3 - li r4, 0 - li r5, 0x204 - bl memset - mr r3, r30 - mr r4, r31 - li r5, 0x10 - bl wcsncpy - addi r3, r30, 0x21c - li r4, 0 - li r5, 0x204 - bl memset - li r0, 0x10 - li r7, 0 - li r3, 0 - li r5, 0x3f - mtctr r0 -setWiiNo_L1: - lhzx r6, r31, r3 - cmplwi r6, 0x30 - blt setWiiNo_L2 - cmplwi r6, 0x39 - bgt setWiiNo_L2 - srawi r0, r7, 2 - addze r0, r0 - add r0, r7, r0 - slwi r0, r0, 1 - add r4, r30, r0 - sth r6, 0x21c(r4) - b setWiiNo_L3 -setWiiNo_L2: - srawi r0, r7, 2 - addze r0, r0 - add r0, r7, r0 - slwi r0, r0, 1 - add r4, r30, r0 - sth r5, 0x21c(r4) -setWiiNo_L3: - addi r7, r7, 1 - addi r3, r3, 2 - bdnz setWiiNo_L1 - li r0, 0x20 - mr r3, r31 - sth r0, 0x238(r30) - li r29, 0 - sth r0, 0x22e(r30) - sth r0, 0x224(r30) - bl wcslen - cmplwi r3, 0x10 - bne setWiiNo_L4 - mr r3, r31 - bl utf16_wiiid__Q33ipl5scene11AddressEditFPCw - stw r4, 0xc(r1) - addi r4, r1, 8 - stw r3, 8(r1) - lwz r3, 0x424(r30) - lwz r3, 0x4ec(r3) - bl isValidId__Q33ipl5scene15FriendListCacheFRCUx - cmpwi r3, 0 - beq setWiiNo_L4 - li r29, 1 -setWiiNo_L4: - stb r29, 0x420(r30) - addi r11, r1, 0x20 - bl _restgpr_29 - lwz r0, 0x24(r1) - mtlr r0 - addi r1, r1, 0x20 - blr +void ipl::scene::AddressEdit::String::setWiiNo(const wchar_t* value) { + mbHasWiiNo = true; + memset(mValue, 0, sizeof(mValue)); + wcsncpy(mValue, value, 0x10); + memset(mDisplayText, 0, sizeof(mDisplayText)); + + for (s32 i = 0; i < 0x10; ++i) { + wchar_t digit = value[i]; + if (digit >= L'0' && digit <= L'9') { + mDisplayText[i + i / 4] = digit; + } else { + mDisplayText[i + i / 4] = L'?'; + } + } + mDisplayText[14] = L' '; + mDisplayText[9] = L' '; + mDisplayText[4] = L' '; + + bool valid = false; + if (wcslen(value) == 0x10) { + u64 userId = AddressEdit::utf16_wiiid(value); + if (mpCallbackOwner->mpFriendCache->isValidId(userId)) { + valid = true; + } + } + mbValidMail = valid; } -extern "C" asm int isDupCode__Q43ipl5scene11AddressEdit6StringCFv(void*) { - nofralloc - stwu r1, -0x120(r1) - mflr r0 - stw r0, 0x124(r1) - lbz r0, 0x422(r3) - stw r31, 0x11c(r1) - mr r31, r3 - cmpwi r0, 0 - beq isDupCode_L1 - bl utf16_wiiid__Q33ipl5scene11AddressEditFPCw - stw r4, 0xc(r1) - addi r4, r1, 8 - lwz r5, 0x424(r31) - stw r3, 8(r1) - lwz r3, 0x4ec(r5) - bl isDupId__Q33ipl5scene15FriendListCacheFRCUx - b isDupCode_L2 -isDupCode_L1: - addi r3, r1, 0x10 - li r4, 0 - li r5, 0x101 - bl memset - mr r4, r31 - addi r3, r1, 0x10 - li r5, 0x100 - bl UTF16ToANSI__Q33ipl7utility13CharacterCodeFPUcPCwl - lwz r3, 0x424(r31) - addi r4, r1, 0x10 - lwz r3, 0x4ec(r3) - bl isDupMail__Q33ipl5scene15FriendListCacheFPCc -isDupCode_L2: - lwz r0, 0x124(r1) - lwz r31, 0x11c(r1) - mtlr r0 - addi r1, r1, 0x120 - blr +BOOL ipl::scene::AddressEdit::String::isDupCode() const { + if (mbHasWiiNo) { + u64 userId = AddressEdit::utf16_wiiid(mValue); + return mpCallbackOwner->mpFriendCache->isDupId(userId); + } + + u8 mail[0x101]; + memset(mail, 0, sizeof(mail)); + ipl::utility::CharacterCode::UTF16ToANSI(mail, mValue, 0x100); + return mpCallbackOwner->mpFriendCache->isDupMail(reinterpret_cast(mail)); } -extern "C" asm int isMyCode__Q43ipl5scene11AddressEdit6StringCFv(void*) { - nofralloc - stwu r1, -0x10(r1) - mflr r0 - stw r0, 0x14(r1) - lbz r0, 0x422(r3) - stw r31, 0xc(r1) - cmpwi r0, 0 - stw r30, 8(r1) - beq isMyCode_L1 - lwz r4, 0x424(r3) - lwz r4, 0x4ec(r4) - lwz r31, 0x7d68(r4) - lwz r30, 0x7d6c(r4) - bl utf16_wiiid__Q33ipl5scene11AddressEditFPCw - xor r4, r30, r4 - xor r0, r31, r3 - or r0, r4, r0 - cntlzw r0, r0 - srwi r3, r0, 5 - b isMyCode_L2 -isMyCode_L1: - li r3, 0 -isMyCode_L2: - lwz r0, 0x14(r1) - lwz r31, 0xc(r1) - lwz r30, 8(r1) - mtlr r0 - addi r1, r1, 0x10 - blr +BOOL ipl::scene::AddressEdit::String::isMyCode() const { + if (mbHasWiiNo) { + NWC24UserId myUserId = mpCallbackOwner->mpFriendCache->getMyUserId(); + return AddressEdit::utf16_wiiid(mValue) == myUserId; + } + return false; } void ipl::scene::AddressEdit::prepare() { @@ -564,14 +391,11 @@ void ipl::scene::AddressEdit::prepare() { void ipl::scene::AddressEdit::create() { - ipl::layout::Object* bLayout; - ipl::scene::Board* board = static_cast(ipl::System::getScene(4)); - ipl::nand::LayoutFile* boardFile = board->getLayoutFile(); + ipl::nand::LayoutFile* boardFile = + static_cast(ipl::System::getScene(4))->getLayoutFile(); - bLayout = reinterpret_cast(__nw__FUl(0x580)); - if (bLayout != NULL) { - bLayout = new (bLayout) ipl::layout::Object(getHeap(), boardFile, "arc", "th_Adress_b.brlyt"); - } + ipl::layout::Object* bLayout = + new ipl::layout::Object(getHeap(), boardFile, "arc", "th_Adress_b.brlyt"); bLayout->bindToGroup("th_Adress_b_card_strt.brlan", "card_strt_fnsh", false, true); bLayout->bindToGroup("th_Adress_b_btn_in.brlan", "crd_btn_00", false, true); bLayout->bindToGroup("th_Adress_b_btn_in.brlan", "crd_btn_10", false, false); @@ -605,15 +429,9 @@ void ipl::scene::AddressEdit::create() { bLayout->bindToGroup("th_Adress_b_card_fnsh.brlan", "card_strt_fnsh", false, false); bLayout->finishBinding(); - ipl::scene::AddressEditEvent* editEvent = static_cast(__nw__FUl(sizeof(ipl::scene::AddressEditEvent))); - if (editEvent != NULL) { - new (editEvent) ipl::scene::AddressEditEvent(this); - } - void* editManagerMemory = __nw__FUl(0x34); - ipl::gui::PaneManager* editManager = reinterpret_cast(editManagerMemory); - if (editManagerMemory != NULL) { - editManager = new (editManagerMemory) ipl::gui::PaneManager(static_cast< ::gui::EventHandler*>(editEvent), bLayout->getDrawInfo(), NULL, NULL, false); - } + ipl::scene::AddressEditEvent* editEvent = new ipl::scene::AddressEditEvent(this); + ipl::gui::PaneManager* editManager = new ipl::gui::PaneManager( + static_cast< ::gui::EventHandler*>(editEvent), bLayout->getDrawInfo(), NULL, NULL, false); editManager->setupScene(bLayout); editManager->setAllComponentTriggerTarget(false); for (s32 i = 0; i < 5; i++) { @@ -646,10 +464,8 @@ void ipl::scene::AddressEdit::create() { ->getNW4RLyt()->GetRootPane()->FindPaneByName("T_frnd_crd_00", true); set_textbox(textPane, L""); - ipl::layout::Object* cLayout = reinterpret_cast(__nw__FUl(0x580)); - if (cLayout != NULL) { - cLayout = new (cLayout) ipl::layout::Object(getHeap(), boardFile, "arc", "th_Adress_c.brlyt"); - } + ipl::layout::Object* cLayout = + new ipl::layout::Object(getHeap(), boardFile, "arc", "th_Adress_c.brlyt"); cLayout->bindToGroup("th_Adress_c_card_strt.brlan", "G_card_strt_fnsh", false, true); cLayout->bindToGroup("th_Adress_c_question_alp_in.brlan", "G_question_00", false, true); cLayout->bindToGroup("th_Adress_c_name_alp_in.brlan", "G_name_00", false, true); @@ -662,15 +478,9 @@ void ipl::scene::AddressEdit::create() { cLayout->bindToGroup("th_Adress_c_card_fnsh.brlan", "G_card_strt_fnsh", false, false); cLayout->finishBinding(); - ipl::scene::AddressInputEvent* inputEvent = static_cast(__nw__FUl(sizeof(ipl::scene::AddressInputEvent))); - if (inputEvent != NULL) { - new (inputEvent) ipl::scene::AddressInputEvent(this); - } - void* inputManagerMemory = __nw__FUl(0x34); - ipl::gui::PaneManager* inputManager = reinterpret_cast(inputManagerMemory); - if (inputManagerMemory != NULL) { - inputManager = new (inputManagerMemory) ipl::gui::PaneManager(static_cast< ::gui::EventHandler*>(inputEvent), cLayout->getDrawInfo(), NULL, NULL, false); - } + ipl::scene::AddressInputEvent* inputEvent = new ipl::scene::AddressInputEvent(this); + ipl::gui::PaneManager* inputManager = new ipl::gui::PaneManager( + static_cast< ::gui::EventHandler*>(inputEvent), cLayout->getDrawInfo(), NULL, NULL, false); inputManager->setupScene(cLayout); inputManager->setAllComponentTriggerTarget(false); textPane = cLayout->getNW4RLyt()->GetRootPane()->FindPaneByName(sInputPaneName, true); @@ -679,10 +489,8 @@ void ipl::scene::AddressEdit::create() { mpInputEvent = inputEvent; mpInputGui = inputManager; - ipl::layout::Object* background = reinterpret_cast(__nw__FUl(0x580)); - if (background != NULL) { - background = new (background) ipl::layout::Object(getHeap(), boardFile, "arc", "my_Back_a.brlyt"); - } + ipl::layout::Object* background = + new ipl::layout::Object(getHeap(), boardFile, "arc", "my_Back_a.brlyt"); mpBackgroundLayout = background; background->bind("my_Back_a_Apear.brlan", "Picture_00", false, true); (mpBackgroundLayout) @@ -800,7 +608,7 @@ void ipl::scene::AddressEdit::stt_wait_decide_anm() { ipl::scene::Button* button = static_cast(ipl::System::getScene(5)); for (s32 i = 0; i < 5; ++i) { u16 index = static_cast(mSelectedButton + 6); - complete = complete && !mpCodeLayout->getAnim(index)->isPlaying(); + complete = (complete & !mpCodeLayout->getAnim(index)->isPlaying()) != 0; } if (!complete) { return; @@ -808,16 +616,16 @@ void ipl::scene::AddressEdit::stt_wait_decide_anm() { switch (mSelectedButton) { case 2: { - u32 friendIndex = mSelectedFriend; - ipl::layout::Animator* animator; - if (mpFriendCache->getInfo(friendIndex).attr.status == 2) { - animator = mpCodeLayout->getAnim(0x15); + if (mpFriendCache->getInfo(mSelectedFriend).attr.status == 2) { + ipl::layout::Animator* statusAnimator = mpCodeLayout->getAnim(0x15); + statusAnimator->initFrame(); + statusAnimator->restart(); } else { - animator = mpCodeLayout->getAnim(0x1b); + ipl::layout::Animator* statusAnimator = mpCodeLayout->getAnim(0x1b); + statusAnimator->initFrame(); + statusAnimator->restart(); } - animator->initFrame(); - animator->restart(); - animator = mpCodeLayout->getAnim(0x16); + ipl::layout::Animator* animator = mpCodeLayout->getAnim(0x16); animator->initFrame(); animator->restart(); animator = mpCodeLayout->getAnim(0x17); @@ -1108,13 +916,11 @@ void ipl::scene::AddressEdit::stt_add_mii_input() { } void ipl::scene::AddressEdit::stt_add_mii_fadeout() { - if (mpNameLayout->getAnim(9)->isPlaying() || - mpNameLayout->getAnim(5)->isPlaying() || - mpNameLayout->getAnim(8)->isPlaying()) { - return; - } - - if (mSubState == 5) { + if (!mpNameLayout->getAnim(9)->isPlaying() && + !mpNameLayout->getAnim(5)->isPlaying() && + !mpNameLayout->getAnim(8)->isPlaying()) { + switch (mSubState) { + case 5: { ipl::layout::Animator* animator = mpNameLayout->getAnim(1); animator->initFrame(); animator->restart(); @@ -1130,10 +936,10 @@ void ipl::scene::AddressEdit::stt_add_mii_fadeout() { pane = mpNameLayout->getNW4RLyt()->GetRootPane()->FindPaneByName("T_msg_00", true); set_textbox(pane, ipl::System::getMessage(0x49)); mState = 0x18; - return; + break; } - if (mSubState == 7) { + case 7: { ipl::layout::Animator* animator = mpCodeLayout->getAnim(0); animator->initFrame(); animator->restart(); @@ -1152,6 +958,11 @@ void ipl::scene::AddressEdit::stt_add_mii_fadeout() { pane = mpCodeLayout->getNW4RLyt()->GetRootPane()->FindPaneByName("T_frnd_crd_00", true); set_textbox(pane, mString.mDisplayText); mState = 0x21; + break; + } + default: + break; + } } } @@ -1170,15 +981,16 @@ void ipl::scene::AddressEdit::stt_wait_del_msg_fadeout() { if (!mpCodeLayout->getAnim(0x1d)->isPlaying()) { u32 friendIndex = mSelectedFriend; u32 status = mpFriendCache->getInfo(friendIndex).attr.status; - ipl::layout::Animator* animator; if (status == 2) { - animator = mpCodeLayout->getAnim(0x10); + ipl::layout::Animator* animator = mpCodeLayout->getAnim(0x10); + animator->initFrame(); + animator->restart(); } else { - animator = mpCodeLayout->getAnim(0x1a); + ipl::layout::Animator* animator = mpCodeLayout->getAnim(0x1a); + animator->initFrame(); + animator->restart(); } - animator->initFrame(); - animator->restart(); - animator = mpCodeLayout->getAnim(0x11); + ipl::layout::Animator* animator = mpCodeLayout->getAnim(0x11); animator->initFrame(); animator->restart(); animator = mpCodeLayout->getAnim(0x12); @@ -1203,26 +1015,28 @@ void ipl::scene::AddressEdit::stt_msg_no_mii() { } void ipl::scene::AddressEdit::stt_add_confirm_fadeout() { - if (!mpCodeLayout->getAnim(0x1e)->isPlaying()) { - ipl::scene::Button* button = static_cast(ipl::System::getScene(5)); - switch (mSubState) { - case 5: { - ipl::layout::Animator* animator = mpNameLayout->getAnim(0); - animator->initFrame(); - animator->restart(); - mState = 0x1c; - break; - } - case 7: - add_friendinfo(); - button->reserveText(1, 0x29); - static_cast(ipl::System::getScene(0x14))->reset_friend(); - ipl::System::getDialog()->callBtn1(0x4a, 0x2e); - mState = 0x26; - break; - default: - break; - } + if (mpCodeLayout->getAnim(0x1e)->isPlaying()) { + return; + } + + ipl::scene::Button* button = static_cast(ipl::System::getScene(5)); + switch (mSubState) { + case 5: { + ipl::layout::Animator* animator = mpNameLayout->getAnim(0); + animator->initFrame(); + animator->restart(); + mState = 0x1c; + break; + } + case 7: + add_friendinfo(); + button->reserveText(1, 0x29); + static_cast(ipl::System::getScene(0x14))->reset_friend(); + ipl::System::getDialog()->callBtn1(0x4a, 0x2e); + mState = 0x26; + break; + default: + break; } } @@ -1436,17 +1250,23 @@ void ipl::scene::AddressEditEvent::onEvent(u32 componentId, u32 event, void* dat static_cast< ::gui::PaneComponent*>(manager->getComponent(componentId)); const char* paneName = component->getPane()->GetName(); - if (signedEvent == 1) { + switch (signedEvent) { + case 1: if (data != NULL) { mpParent->start_point_event(paneName, static_cast(data)); } - } else if (signedEvent >= 1) { - if (signedEvent < 3) { - mpParent->start_left_event(paneName); + break; + case 2: + mpParent->start_left_event(paneName); + break; + case 0: + if (data != NULL && + static_cast(data)->downTrg(0x100800)) { + mpParent->start_trig_event(paneName); } - } else if (signedEvent >= 0 && data != NULL && - static_cast(data)->downTrg(0x100800)) { - mpParent->start_trig_event(paneName); + break; + default: + break; } } @@ -1456,18 +1276,29 @@ void ipl::scene::AddressInputEvent::onEvent(u32 componentId, u32 event, void* da ::gui::PaneComponent* component = static_cast< ::gui::PaneComponent*>(manager->getComponent(componentId)); const char* paneName = component->getPane()->GetName(); - ipl::controller::Interface* controller = static_cast(data); - if (signedEvent == 1) { - if (controller != NULL) { - mpParent->start_ipt_point_event(paneName, controller->getChannel()); + switch (signedEvent) { + case 0: + if (data != NULL && + static_cast(data)->downTrg(0x100800)) { + mpParent->start_ipt_trig_event( + paneName, static_cast(data)->getChannel()); } - } else if (signedEvent >= 1) { - if (signedEvent < 3 && controller != NULL) { - mpParent->start_ipt_left_event(paneName, controller->getChannel()); + break; + case 1: + if (data != NULL) { + mpParent->start_ipt_point_event( + paneName, static_cast(data)->getChannel()); } - } else if (signedEvent >= 0 && controller != NULL && controller->downTrg(0x100800)) { - mpParent->start_ipt_trig_event(paneName, controller->getChannel()); + break; + case 2: + if (data != NULL) { + mpParent->start_ipt_left_event( + paneName, static_cast(data)->getChannel()); + } + break; + default: + break; } } @@ -1499,64 +1330,16 @@ void ipl::scene::AddressEdit::nigaoe_create_callback_add(ipl::nigaoe::Object* ob self->mpBalloon->init(object->getName(), 0xa); } -extern "C" asm void calcFadein__Q33ipl5scene11AddressEditFv() { - nofralloc - stwu r1, -0x10(r1) - mflr r0 - li r4, 0 - stw r0, 0x14(r1) - stw r31, 0xc(r1) - li r31, 0 - stw r30, 8(r1) - mr r30, r3 - lwz r5, 0x68(r3) - addi r3, r5, 0x28c - bl List_GetNth__Q24nw4r2utFPCQ34nw4r2ut4ListUs - lwz r0, 0x14(r3) - cmpwi r0, 1 - beq calcFadein_L1 - lwz r3, 0x74(r30) - li r4, 0 - addi r3, r3, 0x28c - bl List_GetNth__Q24nw4r2utFPCQ34nw4r2ut4ListUs - lwz r0, 0x14(r3) - cmpwi r0, 1 - beq calcFadein_L1 - li r31, 1 -calcFadein_L1: - mr r3, r31 - lwz r31, 0xc(r1) - lwz r30, 8(r1) - lwz r0, 0x14(r1) - mtlr r0 - addi r1, r1, 0x10 - blr +ipl::scene::FaderSceneCommand ipl::scene::AddressEdit::calcFadein() { + FaderSceneCommand command = FADER_SCN_CONTINUE; + if (!mpCodeLayout->getAnim(0)->isPlaying() && !mpNameLayout->getAnim(0)->isPlaying()) { + command = FADER_SCN_NEXT; + } + return command; } -extern "C" asm void initCalcNormal__Q33ipl5scene11AddressEditFv() { - nofralloc - stwu r1, -0x10(r1) - mflr r0 - cmpwi r3, 0 - stw r0, 0x14(r1) - stw r31, 0xc(r1) - mr r31, r3 - beq initCalcNormal_L1 - addi r31, r3, 0x58 -initCalcNormal_L1: - lis r3, smArg__Q23ipl6System@ha - li r4, 5 - addi r3, r3, smArg__Q23ipl6System@l - lwz r3, 0x64(r3) - bl getScene__Q33ipl5scene7ManagerFi - mr r4, r31 - li r5, 0 - bl setEventHandler__Q33ipl5scene6ButtonFPQ23gui12EventHandlerPQ23gui12EventHandler - lwz r0, 0x14(r1) - lwz r31, 0xc(r1) - mtlr r0 - addi r1, r1, 0x10 - blr +void ipl::scene::AddressEdit::initCalcNormal() { + static_cast(ipl::System::getScene(5))->setEventHandler(this); } ipl::scene::FaderSceneCommand ipl::scene::AddressEdit::calcNormal() { @@ -1822,137 +1605,38 @@ void ipl::scene::AddressEdit::stt_add_name_fadeout() { } } -extern "C" asm void initCalcFadeout__Q33ipl5scene11AddressEditFv() { - nofralloc - stwu r1, -0x10(r1) - mflr r0 - lis r5, smArg__Q23ipl6System@ha - li r4, 5 - stw r0, 0x14(r1) - addi r5, r5, smArg__Q23ipl6System@l - stw r31, 0xc(r1) - mr r31, r3 - lwz r3, 0x64(r5) - bl getScene__Q33ipl5scene7ManagerFi - li r4, 0 - li r5, 0 - bl setEventHandler__Q33ipl5scene6ButtonFPQ23gui12EventHandlerPQ23gui12EventHandler - lwz r3, 0xa8(r31) - bl calc__Q33ipl5scene11TextBalloonFv - lwz r0, 0x14(r1) - lwz r31, 0xc(r1) - mtlr r0 - addi r1, r1, 0x10 - blr +void ipl::scene::AddressEdit::initCalcFadeout() { + static_cast(ipl::System::getScene(5))->setEventHandler(NULL); + mpBalloon->calc(); } -extern "C" asm void calcCommonAfter__Q33ipl5scene11AddressEditFv() { - nofralloc - stwu r1, -0x10(r1) - mflr r0 - stw r0, 0x14(r1) - stw r31, 0xc(r1) - mr r31, r3 - lwz r3, 0x70(r3) - lwz r12, 0(r3) - lwz r12, 0x10(r12) - mtctr r12 - bctrl - lwz r3, 0x68(r31) - bl calc__Q33ipl6layout6ObjectFv - lwz r3, 0x7c(r31) - lwz r12, 0(r3) - lwz r12, 0x10(r12) - mtctr r12 - bctrl - lwz r3, 0x74(r31) - bl calc__Q33ipl6layout6ObjectFv - lwz r3, 0x80(r31) - bl calc__Q33ipl6layout6ObjectFv - lwz r0, 0x14(r1) - lwz r31, 0xc(r1) - mtlr r0 - addi r1, r1, 0x10 - blr +void ipl::scene::AddressEdit::calcCommonAfter() { + mpEditGui->calc(); + mpCodeLayout->calc(); + mpInputGui->calc(); + mpNameLayout->calc(); + mpBackgroundLayout->calc(); } -extern "C" asm void stt_normal__Q33ipl5scene11AddressEditFv(ipl::scene::AddressEdit*) { - nofralloc - stwu r1, -0x10(r1) - mflr r0 - lis r5, smArg__Q23ipl6System@ha - li r4, 5 - stw r0, 0x14(r1) - addi r5, r5, smArg__Q23ipl6System@l - stw r31, 0xc(r1) - stw r30, 8(r1) - mr r30, r3 - lwz r3, 0x64(r5) - bl getScene__Q33ipl5scene7ManagerFi - mr r31, r3 - bl isActive__Q33ipl5scene6ButtonCFv - cmpwi r3, 0 - beq stt_normal_L1 - mr r3, r31 - bl update__Q33ipl5scene6ButtonFv -stt_normal_L1: - lwz r0, 0x64(r30) - cmpwi r0, 0 - bne stt_normal_L2 - lwz r3, 0x70(r30) - bl update__Q33ipl3gui11PaneManagerFv -stt_normal_L2: - lwz r0, 0x14(r1) - lwz r31, 0xc(r1) - lwz r30, 8(r1) - mtlr r0 - addi r1, r1, 0x10 - blr +void ipl::scene::AddressEdit::stt_normal() { + ipl::scene::Button* button = static_cast(ipl::System::getScene(5)); + if (button->isActive()) { + button->update(); + } + if (mState == 0) { + mpEditGui->update(); + } } -extern "C" asm void stt_wait_del_msg_fadein__Q33ipl5scene11AddressEditFv(ipl::scene::AddressEdit*) { - nofralloc - stwu r1, -0x10(r1) - mflr r0 - li r4, 0x1c - stw r0, 0x14(r1) - stw r31, 0xc(r1) - mr r31, r3 - lwz r5, 0x68(r3) - addi r3, r5, 0x28c - bl List_GetNth__Q24nw4r2utFPCQ34nw4r2ut4ListUs - lwz r0, 0x14(r3) - cmpwi r0, 1 - beq stt_wait_del_msg_fadein_L1 - li r0, 7 - stw r0, 0x64(r31) -stt_wait_del_msg_fadein_L1: - lwz r0, 0x14(r1) - lwz r31, 0xc(r1) - mtlr r0 - addi r1, r1, 0x10 - blr +void ipl::scene::AddressEdit::stt_wait_del_msg_fadein() { + if (!mpCodeLayout->getAnim(0x1c)->isPlaying()) { + mState = 7; + } } -extern "C" asm void delete_friendinfo__Q33ipl5scene11AddressEditFv(void* self) { - nofralloc - stwu r1, -0x10(r1) - mflr r0 - mr r4, r3 - stw r0, 0x14(r1) - lwz r3, 0x4ec(r3) - lwz r4, 0xa4(r4) - bl del__Q33ipl5scene15FriendListCacheFUl - lis r3, smArg__Q23ipl6System@ha - li r4, 0x14 - addi r3, r3, smArg__Q23ipl6System@l - lwz r3, 0x64(r3) - bl getScene__Q33ipl5scene7ManagerFi - bl reset_friend__Q33ipl5scene7AddressFv - lwz r0, 0x14(r1) - mtlr r0 - addi r1, r1, 0x10 - blr +void ipl::scene::AddressEdit::delete_friendinfo() { + mpFriendCache->del(mSelectedFriend); + static_cast(ipl::System::getScene(0x14))->reset_friend(); } u64 ipl::scene::AddressEdit::utf16_wiiid(const wchar_t* value) { @@ -1965,51 +1649,13 @@ u64 ipl::scene::AddressEdit::utf16_wiiid(const wchar_t* value) { return result; } -extern "C" asm void wiiid_utf16__Q33ipl5scene11AddressEditFUxPw(u64, wchar_t*) { - nofralloc - stwu r1, -0x30(r1) - mflr r0 - stw r0, 0x34(r1) - addi r11, r1, 0x30 - bl _savegpr_23 - mr r24, r3 - mr r23, r4 - mr r25, r5 - li r27, 1 - li r28, 0 - li r26, 0 - li r29, 0x30 - li r30, 0 - li r31, 0xa -wiiid_utf16_L1: - mr r3, r24 - mr r4, r23 - mr r5, r28 - mr r6, r27 - bl __div2u - li r6, 0xa - li r5, 0 - bl __mod2u - addc r5, r4, r29 - adde r3, r3, r30 - subfic r3, r26, 0xf - addi r26, r26, 1 - slwi r4, r3, 1 - mulhwu r0, r27, r31 - cmpwi r26, 0x10 - sthx r5, r25, r4 - mullw r3, r28, r31 - mulli r27, r27, 0xa - add r28, r0, r3 - blt wiiid_utf16_L1 - li r0, 0 - addi r11, r1, 0x30 - sth r0, 0x20(r25) - bl _restgpr_23 - lwz r0, 0x34(r1) - mtlr r0 - addi r1, r1, 0x30 - blr +void ipl::scene::AddressEdit::wiiid_utf16(u64 value, wchar_t* output) { + u64 multiplier = 1; + for (int i = 0; i < 0x10; ++i) { + output[0xf - i] = static_cast((value / multiplier) % 10 + L'0'); + multiplier *= 10; + } + output[0x10] = 0; } void ipl::scene::AddressEdit::String::setName(const wchar_t* value) { @@ -2027,342 +1673,111 @@ void ipl::scene::AddressEdit::String::setName(const wchar_t* value) { } } -extern "C" asm void calcFadeout__Q33ipl5scene11AddressEditFv() { - nofralloc - stwu r1, -0x10(r1) - mflr r0 - stw r0, 0x14(r1) - stw r31, 0xc(r1) - stw r30, 8(r1) - mr r30, r3 - lwz r3, 0xa8(r3) - bl calc__Q33ipl5scene11TextBalloonFv - lis r31, smArg__Q23ipl6System@ha - addi r31, r31, smArg__Q23ipl6System@l - lwz r3, 0xc4(r31) - lwz r12, 0(r3) - lwz r12, 0xc(r12) - mtctr r12 - bctrl - cmpwi r3, 1 - bne calcFadeout_L1 - lwz r3, 0x68(r30) - li r31, 0 - li r4, 0x1e - addi r3, r3, 0x28c - bl List_GetNth__Q24nw4r2utFPCQ34nw4r2ut4ListUs - lwz r0, 0x14(r3) - cmpwi r0, 1 - beq calcFadeout_L2 - lwz r3, 0x74(r30) - li r4, 9 - addi r3, r3, 0x28c - bl List_GetNth__Q24nw4r2utFPCQ34nw4r2ut4ListUs - lwz r0, 0x14(r3) - cmpwi r0, 1 - beq calcFadeout_L2 - li r31, 1 -calcFadeout_L2: - mr r3, r31 - b calcFadeout_L3 -calcFadeout_L1: - lwz r3, 0xc4(r31) - lwz r12, 0(r3) - lwz r12, 0xc(r12) - mtctr r12 - bctrl - cntlzw r0, r3 - srwi r3, r0, 5 -calcFadeout_L3: - lwz r0, 0x14(r1) - lwz r31, 0xc(r1) - lwz r30, 8(r1) - mtlr r0 - addi r1, r1, 0x10 - blr +ipl::scene::FaderSceneCommand ipl::scene::AddressEdit::calcFadeout() { + mpBalloon->calc(); + if (ipl::System::getFader()->getStatus() == EGG::Fader::PREPARE_OUT) { + FaderSceneCommand command = FADER_SCN_CONTINUE; + if (!mpCodeLayout->getAnim(0x1e)->isPlaying() && !mpNameLayout->getAnim(9)->isPlaying()) { + command = FADER_SCN_NEXT; + } + return command; + } + return ipl::System::getFader()->getStatus() == EGG::Fader::PREPARE_IN ? FADER_SCN_NEXT + : FADER_SCN_CONTINUE; } -extern "C" asm void draw__Q33ipl5scene11AddressEditFv() { - nofralloc - stwu r1, -0x10(r1) - mflr r0 - lis r4, smArg__Q23ipl6System@ha - stw r0, 0x14(r1) - addi r4, r4, smArg__Q23ipl6System@l - stw r31, 0xc(r1) - mr r31, r3 - lwz r3, 0x64(r4) - lwz r0, 0x100(r3) - cmpwi r0, 1 - bne draw_L1 - li r3, 0 - bl setOrtho__Q33ipl7utility8GraphicsFUl - lwz r3, 0x68(r31) - bl draw__Q33ipl6layout6ObjectFv - lwz r3, 0x80(r31) - bl draw__Q33ipl6layout6ObjectFv - lwz r3, 0x74(r31) - bl draw__Q33ipl6layout6ObjectFv - lwz r3, 0xa8(r31) - bl draw__Q33ipl5scene11TextBalloonFv -draw_L1: - lwz r0, 0x14(r1) - lwz r31, 0xc(r1) - mtlr r0 - addi r1, r1, 0x10 - blr +void ipl::scene::AddressEdit::draw() { + if (ipl::System::onDefaultDrawLayer()) { + ipl::utility::Graphics::setOrtho(0); + mpCodeLayout->draw(); + mpBackgroundLayout->draw(); + mpNameLayout->draw(); + mpBalloon->draw(); + } } -extern "C" asm void stt_wait_btn_fadein__Q33ipl5scene11AddressEditFv(ipl::scene::AddressEdit*) { - nofralloc - stwu r1, -0x10(r1) - mflr r0 - stw r0, 0x14(r1) - stw r31, 0xc(r1) - mr r31, r3 - stw r30, 8(r1) - lwz r0, 0xa4(r3) - lwz r4, 0x4ec(r3) - mulli r0, r0, 0x140 - add r4, r4, r0 - lwz r0, 4(r4) - cmplwi r0, 2 - bne stt_wait_btn_fadein_L1 - lwz r3, 0x68(r3) - li r4, 0x10 - addi r3, r3, 0x28c - bl List_GetNth__Q24nw4r2utFPCQ34nw4r2ut4ListUs - lwz r3, 0x14(r3) - addi r3, r3, -1 - addic r0, r3, -1 - subfe r30, r0, r3 - b stt_wait_btn_fadein_L2 -stt_wait_btn_fadein_L1: - lwz r3, 0x68(r3) - li r4, 0x1a - addi r3, r3, 0x28c - bl List_GetNth__Q24nw4r2utFPCQ34nw4r2ut4ListUs - lwz r3, 0x14(r3) - addi r3, r3, -1 - addic r0, r3, -1 - subfe r30, r0, r3 -stt_wait_btn_fadein_L2: - lwz r3, 0x68(r31) - li r4, 0x11 - addi r3, r3, 0x28c - bl List_GetNth__Q24nw4r2utFPCQ34nw4r2ut4ListUs - lwz r5, 0x14(r3) - li r4, 0x12 - lwz r3, 0x68(r31) - addi r5, r5, -1 - addic r0, r5, -1 - addi r3, r3, 0x28c - subfe r0, r0, r5 - and r5, r30, r0 - addic r0, r5, -1 - subfe r30, r0, r5 - bl List_GetNth__Q24nw4r2utFPCQ34nw4r2ut4ListUs - lwz r3, 0x14(r3) - addi r3, r3, -1 - addic r0, r3, -1 - subfe r0, r0, r3 - and r3, r30, r0 - addic r0, r3, -1 - subfe. r0, r0, r3 - beq stt_wait_btn_fadein_L3 - li r0, 0 - stw r0, 0x64(r31) -stt_wait_btn_fadein_L3: - lwz r0, 0x14(r1) - lwz r31, 0xc(r1) - lwz r30, 8(r1) - mtlr r0 - addi r1, r1, 0x10 - blr +void ipl::scene::AddressEdit::stt_wait_btn_fadein() { + u32 friendStatus = mpFriendCache->getInfo(mSelectedFriend).attr.status; + bool finished; + if (friendStatus == 2) { + finished = !mpCodeLayout->getAnim(0x10)->isPlaying(); + } else { + finished = !mpCodeLayout->getAnim(0x1a)->isPlaying(); + } + finished = finished & !mpCodeLayout->getAnim(0x11)->isPlaying(); + finished = finished & !mpCodeLayout->getAnim(0x12)->isPlaying(); + if (finished) { + mState = 0; + } } void ipl::scene::AddressEdit::stt_wait_btn_fadeout() { - u32 index = mSelectedFriend; - u32 friendType = mpFriendCache->getInfo(index).attr.status; - u32 friendFinished; - if (friendType == 2) { + bool friendFinished; + if (mpFriendCache->getInfo(mSelectedFriend).attr.status == 2) { friendFinished = !mpCodeLayout->getAnim(0x15)->isPlaying(); } else { friendFinished = !mpCodeLayout->getAnim(0x1b)->isPlaying(); } - bool finished = friendFinished && !mpCodeLayout->getAnim(0x16)->isPlaying(); - finished = finished && !mpCodeLayout->getAnim(0x17)->isPlaying(); + friendFinished &= !mpCodeLayout->getAnim(0x16)->isPlaying(); + friendFinished &= !mpCodeLayout->getAnim(0x17)->isPlaying(); - if (finished) { + if (friendFinished) { nw4r::lyt::Pane* label = mpCodeLayout->getNW4RLyt()->GetRootPane()->FindPaneByName("T_card_msg_00", true); const wchar_t* message = ipl::System::getMessage(0x30); set_textbox(label, message); ipl::System::getDialog()->callS2Btn2(0x142, 0x141, true); - mpCodeLayout->getAnim(0x1c)->initFrame(); - mpCodeLayout->getAnim(0x1c)->restart(); + ipl::layout::Animator* animator = mpCodeLayout->getAnim(0x1c); + animator->initFrame(); + animator->restart(); mState = 4; } } -extern "C" asm void stt_wait_del_msg_fadeout_to_rlt__Q33ipl5scene11AddressEditFv(ipl::scene::AddressEdit*) { - nofralloc - stwu r1, -0x10(r1) - mflr r0 - li r4, 0x1d - stw r0, 0x14(r1) - stw r31, 0xc(r1) - mr r31, r3 - lwz r5, 0x68(r3) - addi r3, r5, 0x28c - bl List_GetNth__Q24nw4r2utFPCQ34nw4r2ut4ListUs - lwz r0, 0x14(r3) - cmpwi r0, 1 - beq stt_wait_del_msg_fadeout_to_rlt_L1 - li r0, 8 - lis r3, smArg__Q23ipl6System@ha - stw r0, 0x64(r31) - addi r3, r3, smArg__Q23ipl6System@l - li r4, 0x51 - li r5, 0x2e - lwz r3, 0xac(r3) - bl callBtn1__Q23ipl12DialogWindowFUlUl -stt_wait_del_msg_fadeout_to_rlt_L1: - lwz r0, 0x14(r1) - lwz r31, 0xc(r1) - mtlr r0 - addi r1, r1, 0x10 - blr +void ipl::scene::AddressEdit::stt_wait_del_msg_fadeout_to_rlt() { + if (!mpCodeLayout->getAnim(0x1d)->isPlaying()) { + mState = 8; + ipl::System::getDialog()->callBtn1(0x51, 0x2e); + } } -extern "C" asm void stt_msg_del_rlt__Q33ipl5scene11AddressEditFv(ipl::scene::AddressEdit*) { - nofralloc - stwu r1, -0x10(r1) - mflr r0 - li r4, 5 - stw r0, 0x14(r1) - stw r31, 0xc(r1) - lis r31, smArg__Q23ipl6System@ha - addi r31, r31, smArg__Q23ipl6System@l - stw r30, 8(r1) - mr r30, r3 - lwz r3, 0x64(r31) - bl getScene__Q33ipl5scene7ManagerFi - lwz r4, 0xac(r31) - mr r31, r3 - lwz r0, 0x24(r4) - cmpwi r0, 1 - beq stt_msg_del_rlt_L2 - b stt_msg_del_rlt_L1 -stt_msg_del_rlt_L2: - li r4, 1 - li r5, 0x29 - bl reserveText__Q33ipl5scene6ButtonFiUl - mr r3, r31 - li r4, 0xf - bl reserveAnm__Q33ipl5scene6ButtonFi - lwz r3, 0x68(r30) - li r4, 0x1e - addi r3, r3, 0x28c - bl List_GetNth__Q24nw4r2utFPCQ34nw4r2ut4ListUs - mr r31, r3 - bl initFrame__Q33ipl7utility15FrameControllerFv - li r3, 1 - li r0, 0x30 - stw r3, 0x14(r31) - stw r0, 0x64(r30) -stt_msg_del_rlt_L1: - lwz r0, 0x14(r1) - lwz r31, 0xc(r1) - lwz r30, 8(r1) - mtlr r0 - addi r1, r1, 0x10 - blr +void ipl::scene::AddressEdit::stt_msg_del_rlt() { + ipl::scene::Button* button = static_cast(ipl::System::getScene(5)); + switch (ipl::System::getDialog()->getLastResult()) { + case 1: + button->reserveText(1, 0x29); + button->reserveAnm(0xf); + ipl::layout::Animator* animator = mpCodeLayout->getAnim(0x1e); + animator->initFrame(); + animator->restart(); + mState = 0x30; + break; + default: + break; + } } -extern "C" asm void stt_ipt_wait_fadein__Q33ipl5scene11AddressEditFv(ipl::scene::AddressEdit*) { - nofralloc - stwu r1, -0x10(r1) - mflr r0 - li r4, 0 - stw r0, 0x14(r1) - stw r31, 0xc(r1) - mr r31, r3 - lwz r5, 0x74(r3) - addi r3, r5, 0x28c - bl List_GetNth__Q24nw4r2utFPCQ34nw4r2ut4ListUs - lwz r0, 0x14(r3) - cmpwi r0, 1 - beq stt_ipt_wait_fadein_L1 - lwz r3, 0x74(r31) - li r4, 1 - addi r3, r3, 0x28c - bl List_GetNth__Q24nw4r2utFPCQ34nw4r2ut4ListUs - lwz r0, 0x14(r3) - cmpwi r0, 1 - beq stt_ipt_wait_fadein_L1 - lwz r3, 0x74(r31) - li r4, 2 - addi r3, r3, 0x28c - bl List_GetNth__Q24nw4r2utFPCQ34nw4r2ut4ListUs - lwz r0, 0x14(r3) - cmpwi r0, 1 - beq stt_ipt_wait_fadein_L1 - lwz r3, 0x80(r31) - li r4, 0 - addi r3, r3, 0x28c - bl List_GetNth__Q24nw4r2utFPCQ34nw4r2ut4ListUs - lwz r0, 0x14(r3) - cmpwi r0, 1 - beq stt_ipt_wait_fadein_L1 - li r0, 0xd - stw r0, 0x64(r31) -stt_ipt_wait_fadein_L1: - lwz r0, 0x14(r1) - lwz r31, 0xc(r1) - mtlr r0 - addi r1, r1, 0x10 - blr +void ipl::scene::AddressEdit::stt_ipt_wait_fadein() { + if (!mpNameLayout->getAnim(0)->isPlaying() && !mpNameLayout->getAnim(1)->isPlaying() && + !mpNameLayout->getAnim(2)->isPlaying() && !mpBackgroundLayout->getAnim(0)->isPlaying()) { + mState = 0xd; + } } -extern "C" asm void stt_ipt_normal__Q33ipl5scene11AddressEditFv(ipl::scene::AddressEdit*) { - nofralloc - stwu r1, -0x10(r1) - mflr r0 - lis r5, smArg__Q23ipl6System@ha - li r4, 5 - stw r0, 0x14(r1) - addi r5, r5, smArg__Q23ipl6System@l - stw r31, 0xc(r1) - stw r30, 8(r1) - mr r30, r3 - lwz r3, 0x64(r5) - bl getScene__Q33ipl5scene7ManagerFi - mr r31, r3 - bl isActive__Q33ipl5scene6ButtonCFv - cmpwi r3, 0 - beq stt_ipt_normal_L1 - mr r3, r31 - bl update__Q33ipl5scene6ButtonFv -stt_ipt_normal_L1: - lwz r0, 0x64(r30) - cmpwi r0, 0xd - bne stt_ipt_normal_L2 - lwz r3, 0x7c(r30) - bl update__Q33ipl3gui11PaneManagerFv -stt_ipt_normal_L2: - lwz r0, 0x14(r1) - lwz r31, 0xc(r1) - lwz r30, 8(r1) - mtlr r0 - addi r1, r1, 0x10 - blr +void ipl::scene::AddressEdit::stt_ipt_normal() { + ipl::scene::Button* button = static_cast(ipl::System::getScene(5)); + if (button->isActive()) { + button->update(); + } + if (mState == 0xd) { + mpInputGui->update(); + } } void ipl::scene::AddressEdit::stt_ipt_input() { ipl::keyboard::Manager::State* state = ipl::System::getKeyboard()->getState(); - ipl::scene::Manager* sceneManager = ipl::System::getSceneManager(); - ipl::scene::Button* button = static_cast(sceneManager->getScene(5)); + ipl::scene::Button* button = + static_cast(ipl::System::getSceneManager()->getScene(5)); s32 keyboardType = state->iplType; if (keyboardType == ipl::keyboard::Manager::STATE_DISAPPEARING) { goto state_disappearing; @@ -2446,8 +1861,7 @@ void ipl::scene::AddressEdit::stt_add_code_input() { bool codeWasEmpty = mString.mValue[0] == 0; if (state->pressOK) { if (mMode == 1) { - setWiiNo__Q43ipl5scene11AddressEdit6StringFPCw( - &mString, state->wcString); + mString.setWiiNo(state->wcString); } else { mString.setEMail(state->wcString); } @@ -2474,8 +1888,8 @@ void ipl::scene::AddressEdit::stt_add_code_input() { pane->restart(); } if (mString.mbValidMail != 0 && - isDupCode__Q43ipl5scene11AddressEdit6StringCFv(&mString) == 0 && - isMyCode__Q43ipl5scene11AddressEdit6StringCFv(&mString) == 0) { + mString.isDupCode() == 0 && + mString.isMyCode() == 0) { button->reserveText(1, 0x2e); button->reserveAnm(0xf); } else { @@ -2488,12 +1902,10 @@ void ipl::scene::AddressEdit::stt_add_code_input() { if (state->pressOK) { if (mString.mValue[0] != 0) { if (mMode == 1) { - if (isMyCode__Q43ipl5scene11AddressEdit6StringCFv( - &mString) != 0) { + if (mString.isMyCode() != 0) { ipl::System::getDialog()->callBtn1(0x56, 0x2e); mState = 0x16; - } else if (isDupCode__Q43ipl5scene11AddressEdit6StringCFv( - &mString) != 0) { + } else if (mString.isDupCode() != 0) { ipl::System::getDialog()->callBtn1(0x52, 0x2e); mState = 0x14; } else if (mString.mbValidMail == 0) { @@ -2502,8 +1914,7 @@ void ipl::scene::AddressEdit::stt_add_code_input() { } else { mState = 0x11; } - } else if (isDupCode__Q43ipl5scene11AddressEdit6StringCFv( - &mString) != 0) { + } else if (mString.isDupCode() != 0) { ipl::System::getDialog()->callBtn1(0x53, 0x2e); mState = 0x15; } else if (mString.mbValidMail == 0) { @@ -2531,8 +1942,7 @@ void ipl::scene::AddressEdit::stt_add_code_input() { } void ipl::scene::AddressEdit::stt_add_code_fadeout() { - ipl::layout::Object* layout = mpNameLayout; - ipl::layout::Animator* pane = layout->getAnim(5); + ipl::layout::Animator* pane = mpNameLayout->getAnim(5); if (!pane->isPlaying()) { pane = mpNameLayout->getAnim(6); if (!pane->isPlaying()) { @@ -2811,8 +2221,7 @@ done: void ipl::scene::AddressEdit::start_left_event( const char* paneName) { int buttonNo = get_button_no(paneName); - s32 state = mState; - switch (state) { + switch (mState) { case 0x22: goto state22; case 0: @@ -3030,8 +2439,8 @@ void ipl::scene::AddressEdit::start_ipt_trig_event( } setDefaultTitleText(mString.mValue, false); if (mString.mbValidMail != 0 && - isDupCode__Q43ipl5scene11AddressEdit6StringCFv(&mString) == 0 && - isMyCode__Q43ipl5scene11AddressEdit6StringCFv(&mString) == 0) { + !mString.isDupCode() && + !mString.isMyCode()) { button->reserveAnm(0x10); } else { button->reserveAnm(0xc); @@ -3134,9 +2543,8 @@ void ipl::scene::AddressEdit::onEventDerived(u32 componentId, u32 event, const i nw4r::lyt::Pane* pane = component->getPane(); const char* paneName = pane->GetName(); - if (event != 0) { - return; - } + switch (event) { + case 0: { if (controller == NULL) { return; } @@ -3186,10 +2594,8 @@ void ipl::scene::AddressEdit::onEventDerived(u32 componentId, u32 event, const i requestSceneChange(getPreviousScene(), NULL); button->reserveAnm(0x1b); if (mString.mbValidMail != 0 && - isDupCode__Q43ipl5scene11AddressEdit6StringCFv( - &mString) == 0 && - isMyCode__Q43ipl5scene11AddressEdit6StringCFv( - &mString) == 0) { + mString.isDupCode() == 0 && + mString.isMyCode() == 0) { button->reserveAnm(0x10); } else { button->reserveAnm(0xc); @@ -3363,6 +2769,11 @@ void ipl::scene::AddressEdit::onEventDerived(u32 componentId, u32 event, const i } } } + break; + } + default: + break; + } } void ipl::scene::AddressEdit::start_ipt_left_event( @@ -3477,8 +2888,8 @@ void ipl::scene::AddressEdit::add_friendinfo() { } void ipl::scene::AddressEdit::get_friendinfo() { - const NWC24FriendInfo& friendInfo = mpFriendCache->getInfo(mSelectedFriend); - memcpy(&sFriendInfo__Q23ipl5scene, &friendInfo, sizeof(sFriendInfo__Q23ipl5scene)); + memcpy(&sFriendInfo__Q23ipl5scene, &mpFriendCache->getInfo(mSelectedFriend), + sizeof(sFriendInfo__Q23ipl5scene)); mString.setName(reinterpret_cast(sFriendInfo__Q23ipl5scene.attr.name)); const wchar_t* name = mString.mName; nw4r::lyt::Pane* namePane = -- 2.49.1 From 1cef1a089eb43c12a2404f3e62dbffbeaa0b88fc Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 00:41:04 +0000 Subject: [PATCH 09/61] restore setting scene name tables --- include/scene/setting/iplSetting.h | 17 +++-- src/scene/setting/iplSetting.cpp | 114 +++++++++++++++++++++++------ 2 files changed, 102 insertions(+), 29 deletions(-) diff --git a/include/scene/setting/iplSetting.h b/include/scene/setting/iplSetting.h index 5f6f86b0..c9489c30 100644 --- a/include/scene/setting/iplSetting.h +++ b/include/scene/setting/iplSetting.h @@ -66,11 +66,11 @@ namespace ipl { int mUpdateTiming; u8 unk_0x5C; u8 unk_0x5D[3]; - nand::Base* mpBrowserFile; - nand::Base* mpLanguageFile; - nand::Base* mpNandFile; - nand::Base* mpStringFile; - nand::Base* mpMessageFile; + nand::Base* mpWWWLibraryFile; + nand::Base* mpSettingHTMLFile; + nand::Base* mpWWWArchiveFile; + nand::Base* mpFontFile; + nand::Base* mpBackgroundTPLFile; int unk_0x74; int unk_0x78; int unk_0x7C; @@ -79,8 +79,11 @@ namespace ipl { u8 unk_0x88[8]; int mFuncMsgPending; int unk_0x94; - u8 unk_0x98[0x24]; - int unk_0xBC; + u8 unk_0x98[8]; + u32 mPrepareTick; + u8 mSettingData[0x16]; + u8 unk_0xBA[2]; + nand::LayoutFile* mpSettingLayoutFile; u8 unk_0xC0[0xC]; SettingAnimation* mpFirstAnimation; SettingAnimation* mpSecondAnimation; diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index e88b11df..d1fe3b8f 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -4,23 +4,29 @@ #include "scene/setting/iplNCDSetting.h" #include "system/iplSystem.h" +#include "iplwww/www_wiisetting.h" + +#include +#include + namespace ipl { namespace scene { - static const char* sSettingAPButtonNames[] = { - "B_AP2", "B_AP3", "B_AP4", "B_AP5", "T_Name1", "T_Name2", "T_Name3", "T_Name4", - "T_Name5", "T_Name6", "N_AP1", "N_AP2", "N_AP3", "N_AP4", "N_AP5", "N_AP6", - }; + const char* sSettingAPButtonNames[] = {"B_AP2", "B_AP3", "B_AP4", "B_AP5"}; - static const char* sSettingArrowNames[] = {"B_ArwA", "B_ArwB"}; + const char* sSettingArrowNames[] = {"B_ArwA", "B_ArwB"}; - static const char* sSettingAPPaneNames[] = { + const char* sSettingAPTextNames[] = {"T_Name1", "T_Name2", "T_Name3", "T_Name4", "T_Name5", "T_Name6"}; + + const char* sSettingAPNumberNames[] = {"N_AP1", "N_AP2", "N_AP3", "N_AP4", "N_AP5", "N_AP6"}; + + const char* sSettingAPPaneNames[] = { "G_ListUpDown", "G_ListInOut", "G_ArwA", "G_ArwB", "G_Denpa", "G_Lock", "G_AP0", "G_AP1", "G_AP2", "G_AP3", "G_AP4", "G_AP5", "G_AP6", "G_AP7", "G_Denpa1", "G_Denpa2", "G_Denpa3", "G_Denpa4", "G_Denpa5", "G_Denpa6", "G_Lock1", "G_Lock2", "G_Lock3", "G_Lock4", "G_Lock5", "G_Lock6", }; - static const char* sSettingAPAnimations[] = { + const char* sSettingAPAnimations[] = { "my_AP_a_ArwAppear.brlan", "my_AP_a_ArwLost.brlan", "my_AP_a_ArwFocusOn.brlan", "my_AP_a_ArwFocusOff.brlan", "my_AP_a_ArwSelect.brlan", "my_AP_a_ScrollUp.brlan", "my_AP_a_ScrollDown.brlan", "my_AP_a_BtnFocusOn.brlan", "my_AP_a_BtnFocusOff.brlan", @@ -37,11 +43,11 @@ namespace ipl { Setting::Setting(EGG::Heap* heap, int arg) : FaderSceneBase(heap) { unk_0x5C = 0; - mpBrowserFile = 0; - mpLanguageFile = 0; - mpNandFile = 0; - mpStringFile = 0; - unk_0xBC = 0; + mpWWWLibraryFile = 0; + mpSettingHTMLFile = 0; + mpWWWArchiveFile = 0; + mpFontFile = 0; + mpSettingLayoutFile = 0; unk_0xB3B = 0; setSceneParentFlags(3); unk_0x74 = 0; @@ -97,20 +103,20 @@ namespace ipl { System::getMem2App()->free(mem2Buffer_); mem2Buffer_ = 0; } - if (mpBrowserFile) { - delete mpBrowserFile; + if (mpWWWLibraryFile) { + delete mpWWWLibraryFile; } - if (mpLanguageFile) { - delete mpLanguageFile; + if (mpSettingHTMLFile) { + delete mpSettingHTMLFile; } - if (mpNandFile) { - delete mpNandFile; + if (mpWWWArchiveFile) { + delete mpWWWArchiveFile; } - if (mpStringFile) { - delete mpStringFile; + if (mpFontFile) { + delete mpFontFile; } - if (mpMessageFile) { - delete mpMessageFile; + if (mpBackgroundTPLFile) { + delete mpBackgroundTPLFile; } System::destroyMem1AppHeap(); System::getBS2Manager()->restart(); @@ -122,6 +128,70 @@ namespace ipl { delete mpRakuRakuThread; } + void Setting::prepare() { + bs2::Manager* bs2Manager = System::getBS2Manager(); + bs2Manager->abort(); + while (bs2Manager->getIPLState() != 8) { + bs2Manager->update(); + VIWaitForRetrace(); + } + + System::getUsbEtherMacAddr(); + mPrepareTick = OSGetTick(); + mpWWWLibraryFile = System::getNandManager()->readSharedAsync( + System::createMem1AppHeap(), "wwwlib-rvl.lz7", 2, 0, 0, 1, 2); + + char fontName[32]; + char htmlPath[64]; + char productArea = SCGetProductArea(); + if (productArea < 6) { + if (productArea != 4) { + if (productArea > 3) { + snprintf(fontName, sizeof(fontName), "WiiNTLG-Regular.ttc"); + snprintf(htmlPath, sizeof(htmlPath), "/html/%s/iplsetting.ash", "EU/EU"); + goto loadFiles; + } + if (productArea >= 0) { + snprintf(fontName, sizeof(fontName), "WiiNTLG-Regular.ttc"); + snprintf(htmlPath, sizeof(htmlPath), "/html/%s/iplsetting.ash", "FIX/US"); + goto loadFiles; + } + } + } else if (productArea == 6) { + snprintf(fontName, sizeof(fontName), "Wii-kr_Round Gothic B.ttf"); + snprintf(htmlPath, sizeof(htmlPath), "/html/%s/iplsetting.ash", "FIX/US"); + goto loadFiles; + } else if (productArea == 11) { + snprintf(fontName, sizeof(fontName), "Wii-cn_HeiTiW5.ttf"); + snprintf(htmlPath, sizeof(htmlPath), "/html/%s/iplsetting.ash", "FIX/US"); + goto loadFiles; + } + + snprintf(fontName, sizeof(fontName), "WiiNTLG-Regular.ttc"); + snprintf(htmlPath, sizeof(htmlPath), "/html/%s/iplsetting.ash", "FIX/US"); + + loadFiles: + mpSettingHTMLFile = System::getNandManager()->readAsync( + System::createMem1AppHeap(), htmlPath, 0, 0, false); + mpWWWArchiveFile = System::getNandManager()->readAsync( + System::createMem1AppHeap(), "/www.arc", 0, 0, false); + mpFontFile = System::getNandManager()->readSharedAsync( + System::createMem1AppHeap(), fontName, 3, 0, 0, 1, 2); + mpBackgroundTPLFile = System::getNandManager()->readAsync( + System::createMem1AppHeap(), "/html/BG_16x9.tpl", 0, 0, false); + mpSettingLayoutFile = System::getNandManager()->readLayoutAsync(getSceneHeap(), "setting.ash", false); + + if (mInitialArgument == 2) { + memset(mSettingData, 0, sizeof(mSettingData)); + mAspectRatio = 0; + www::wiisetting::setInitSetupFlag(1); + } else if (mInitialArgument == 5) { + www::wiisetting::setInitSetupFlag(1); + } else { + www::wiisetting::setInitSetupFlag(0); + } + } + u16 Setting::getProfileID() { u16 profileID; if (mProfileIDMode >= 3) { -- 2.49.1 From b2433c94396f1b9af6a97f9c54f43ca8d7f866f4 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 01:36:23 +0000 Subject: [PATCH 10/61] match setting fadein state copy --- include/scene/setting/iplSetting.h | 67 +++++- include/system/iplKeyboard.h | 7 + src/scene/setting/iplSetting.cpp | 340 ++++++++++++++++++++++++++--- 3 files changed, 377 insertions(+), 37 deletions(-) diff --git a/include/scene/setting/iplSetting.h b/include/scene/setting/iplSetting.h index c9489c30..85486dec 100644 --- a/include/scene/setting/iplSetting.h +++ b/include/scene/setting/iplSetting.h @@ -5,6 +5,10 @@ #ifdef IPL_SETTING_IMPLEMENTATION #include +#include "layout/iplGuiManager.h" +#include "layout/GUIManager.h" +#include "iplwww/www_wiisetting.h" +#include "system/iplKeyboard.h" #include "system/iplNand.h" #include "utility/iplThread.h" #endif @@ -12,10 +16,19 @@ namespace ipl { namespace scene { #ifdef IPL_SETTING_IMPLEMENTATION - class APEvent { + class Setting; + class APScanThread; + + class APEvent : public ::gui::EventHandler { public: - u8 unknown[4]; - u8 eventType; + APEvent(Setting* setting) : ::gui::EventHandler(), mpSetting(setting) {} + + virtual void onEvent(u32 componentID, u32 event, void* data); + + void setEventType(u8 eventType) { reinterpret_cast(mpManager) = eventType; } + + private: + Setting* mpSetting; }; struct SettingAnimation { @@ -33,6 +46,23 @@ namespace ipl { bool isAnimating(); void getFuncMsgQ(); void resetFuncMsgQ(); + void createBrowser(); + void initDirectUrl(); + void initString(); + void initWiiSettingData(); + void initNickName(); + void initSecurityKey(); + void initSSID(); + void initIP(); + void initDNS(); + void initProxy(); + void initBasic(); + void initMTU(); + void initSecA(); + void initVersion(); + void start_point_event(const char* pageName); + void start_trig_event(const char* pageName); + void start_left_event(const char* pageName); int get_arw_no(const char* paneName); int get_ap_no(const char* buttonName); virtual void destroy(); @@ -84,24 +114,36 @@ namespace ipl { u8 mSettingData[0x16]; u8 unk_0xBA[2]; nand::LayoutFile* mpSettingLayoutFile; - u8 unk_0xC0[0xC]; + layout::Object* mpChangeLayout; + layout::Object* mpMainLayout; + layout::Object* mpWaitLayout; SettingAnimation* mpFirstAnimation; SettingAnimation* mpSecondAnimation; - u8 unk_0xD4[0xC]; + APEvent* mpEventHandler; + gui::PaneManager* mpPaneManager; + void* mpUSBAPThread; utility::ut_thread* mpAOSSThread; utility::ut_thread* mpRakuRakuThread; - u8 unk_0xE8[0x82C]; + APScanThread* mpAPScanThread; + u8 unk_0xEC[0x818]; + void* mpMem1BrowserBuffer; + u32 unk_0x908; + void* mpMem2BrowserBuffer; + void* mpBrowserStringBuffer; int unk_0x914; int unk_0x918; u8 unk_0x91C[4]; - u8 unk_0x920[8]; + void* mpBrowserData; + u32 unk_0x924; APEvent* mpAPEvent; u8 unk_0x92C; u8 unk_0x92D[3]; int unk_0x930; - u8 unk_0x934[0x207]; - u8 unk_0xB3B; - u8 unk_0xB3C[0x10]; + www::wiisetting::SetStringBuf* mpStringBuffer; + u8 unk_0x938[0x202]; + u8 unk_0xB3A; + u8 mBrowserCreated; + keyboard::Manager::State mKeyboardState; int mInitialArgument; int mAspectRatio; int mProgressiveMode; @@ -109,11 +151,12 @@ namespace ipl { u8 mIsResetAcceptable; u8 unk_0xB5D[3]; OSMessageQueue mFuncMessageQueue; - u8 unk_0xB80[0x14]; + OSMessage mFuncMessages[5]; int unk_0xB94; int mState; int unk_0xB9C; - u8 unk_0xBA0[0xC]; + OSTime mCreatePageTime; + u32 unk_0xBA8; u8 unk_0xBAC; u8 unk_0xBAD[3]; u8 unk_0xBB0[0x10]; diff --git a/include/system/iplKeyboard.h b/include/system/iplKeyboard.h index 717d309d..a9f06df3 100644 --- a/include/system/iplKeyboard.h +++ b/include/system/iplKeyboard.h @@ -63,8 +63,15 @@ namespace ipl { textinput::MemoManager::StateType type; // 0x00 KeyboardState iplType; // 0x04 bool pressOK; // 0x08 +#ifdef IPL_SETTING_IMPLEMENTATION + u8 reservedByte; +#else u8 unused_0x09; +#endif wchar_t* wcString; // 0x0C +#ifdef IPL_SETTING_IMPLEMENTATION + State& operator=(const State& other); +#endif } State; Manager() : mpManager(NULL), mEvent(), mCurrentConChan(0), mbActivated(false), mpSaveFile(NULL) {} diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index d1fe3b8f..0c4d567d 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -2,15 +2,69 @@ #include "scene/setting/iplSetting.h" #include "scene/setting/iplNCDSetting.h" +#include "scene/setting/iplParental.h" +#include "system/iplErrorHandler.h" #include "system/iplSystem.h" #include "iplwww/www_wiisetting.h" +#include "iplwww/www_surface.h" #include #include +#include +#include +#include +#include + +namespace ipl { + namespace keyboard { + Manager::State& Manager::State::operator=(const Manager::State& other) { + type = other.type; + iplType = other.iplType; + pressOK = other.pressOK; + reservedByte = other.reservedByte; + wcString = other.wcString; + return *this; + } + } +} namespace ipl { namespace scene { + class APScanThread { + public: + APScanThread(); + }; + + class USBAPThread { + public: + USBAPThread(); + }; + + class AOSSThread { + public: + AOSSThread(EGG::Heap* heap); + }; + + class RakuRakuThread { + public: + RakuRakuThread(EGG::Heap* heap); + }; + + struct SettingAnimationBinding { + u16 animation; + u16 pane; + }; + + static const SettingAnimationBinding sSettingAnimationBindings[] = { + {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 2}, {2, 3}, {3, 2}, {3, 3}, {4, 2}, {4, 3}, + {5, 0}, {6, 0}, {7, 8}, {7, 9}, {7, 10}, {7, 11}, {8, 8}, {8, 9}, {8, 10}, {8, 11}, + {9, 1}, {10, 1}, {11, 14}, {11, 15}, {11, 16}, {11, 17}, {11, 18}, {11, 19}, {12, 14}, {12, 15}, + {12, 16}, {12, 17}, {12, 18}, {12, 19}, {13, 14}, {13, 15}, {13, 16}, {13, 17}, {13, 18}, {13, 19}, + {14, 14}, {14, 15}, {14, 16}, {14, 17}, {14, 18}, {14, 19}, {15, 20}, {15, 21}, {15, 22}, {15, 23}, + {15, 24}, {15, 25}, {16, 20}, {16, 21}, {16, 22}, {16, 23}, {16, 24}, {16, 25}, + }; + const char* sSettingAPButtonNames[] = {"B_AP2", "B_AP3", "B_AP4", "B_AP5"}; const char* sSettingArrowNames[] = {"B_ArwA", "B_ArwB"}; @@ -48,7 +102,7 @@ namespace ipl { mpWWWArchiveFile = 0; mpFontFile = 0; mpSettingLayoutFile = 0; - unk_0xB3B = 0; + mBrowserCreated = 0; setSceneParentFlags(3); unk_0x74 = 0; mInitialArgument = arg; @@ -84,12 +138,12 @@ namespace ipl { OSMessage message = 0; if (mFuncMsgPending == 0 && OSReceiveMessage(&mFuncMessageQueue, &message, 0)) { mFuncMsgPending = 1; - mpAPEvent->eventType = (u8)message; + mpAPEvent->setEventType((u8)message); } } void Setting::resetFuncMsgQ() { - mpAPEvent->eventType = 0; + mpAPEvent->setEventType(0); mFuncMsgPending = 0; } @@ -129,56 +183,64 @@ namespace ipl { } void Setting::prepare() { - bs2::Manager* bs2Manager = System::getBS2Manager(); - bs2Manager->abort(); - while (bs2Manager->getIPLState() != 8) { - bs2Manager->update(); + System::getBS2Manager()->abort(); + while (System::getBS2Manager()->getIPLState() != 8) { + System::getBS2Manager()->update(); VIWaitForRetrace(); } System::getUsbEtherMacAddr(); mPrepareTick = OSGetTick(); mpWWWLibraryFile = System::getNandManager()->readSharedAsync( - System::createMem1AppHeap(), "wwwlib-rvl.lz7", 2, 0, 0, 1, 2); + System::createMem1AppHeap(), "wwwlib-rvl.lz7", 2); char fontName[32]; char htmlPath[64]; char productArea = SCGetProductArea(); + if (productArea == 6) { + goto koreanFont; + } if (productArea < 6) { if (productArea != 4) { if (productArea > 3) { + goto europeFont; + } else if (productArea >= 0) { snprintf(fontName, sizeof(fontName), "WiiNTLG-Regular.ttc"); - snprintf(htmlPath, sizeof(htmlPath), "/html/%s/iplsetting.ash", "EU/EU"); - goto loadFiles; - } - if (productArea >= 0) { - snprintf(fontName, sizeof(fontName), "WiiNTLG-Regular.ttc"); - snprintf(htmlPath, sizeof(htmlPath), "/html/%s/iplsetting.ash", "FIX/US"); + snprintf(htmlPath, sizeof(htmlPath), "/html/%s/iplsetting.ash", "US2"); goto loadFiles; } } - } else if (productArea == 6) { - snprintf(fontName, sizeof(fontName), "Wii-kr_Round Gothic B.ttf"); - snprintf(htmlPath, sizeof(htmlPath), "/html/%s/iplsetting.ash", "FIX/US"); - goto loadFiles; } else if (productArea == 11) { - snprintf(fontName, sizeof(fontName), "Wii-cn_HeiTiW5.ttf"); - snprintf(htmlPath, sizeof(htmlPath), "/html/%s/iplsetting.ash", "FIX/US"); - goto loadFiles; + goto chineseFont; } snprintf(fontName, sizeof(fontName), "WiiNTLG-Regular.ttc"); - snprintf(htmlPath, sizeof(htmlPath), "/html/%s/iplsetting.ash", "FIX/US"); + snprintf(htmlPath, sizeof(htmlPath), "/html/%s/iplsetting.ash", "US2"); + goto loadFiles; + + koreanFont: + snprintf(fontName, sizeof(fontName), "Wii-kr_Round Gothic B.ttf"); + snprintf(htmlPath, sizeof(htmlPath), "/html/%s/iplsetting.ash", "US2"); + goto loadFiles; + + chineseFont: + snprintf(fontName, sizeof(fontName), "Wii-cn_HeiTiW5.ttf"); + snprintf(htmlPath, sizeof(htmlPath), "/html/%s/iplsetting.ash", "US2"); + goto loadFiles; + + europeFont: + snprintf(fontName, sizeof(fontName), "WiiNTLG-Regular.ttc"); + snprintf(htmlPath, sizeof(htmlPath), "/html/%s/iplsetting.ash", "TW2"); loadFiles: mpSettingHTMLFile = System::getNandManager()->readAsync( System::createMem1AppHeap(), htmlPath, 0, 0, false); mpWWWArchiveFile = System::getNandManager()->readAsync( - System::createMem1AppHeap(), "/www.arc", 0, 0, false); + System::getMem2App(), "/www.arc", 0, 0, false); mpFontFile = System::getNandManager()->readSharedAsync( - System::createMem1AppHeap(), fontName, 3, 0, 0, 1, 2); + System::getMem2App(), fontName, 3); mpBackgroundTPLFile = System::getNandManager()->readAsync( - System::createMem1AppHeap(), "/html/BG_16x9.tpl", 0, 0, false); + System::getMem2App(), "/html/BG_16x9.tpl", 0, 0, false); mpSettingLayoutFile = System::getNandManager()->readLayoutAsync(getSceneHeap(), "setting.ash", false); if (mInitialArgument == 2) { @@ -192,6 +254,233 @@ namespace ipl { } } + void Setting::create() { + nand::File* archiveFile = static_cast(mpWWWArchiveFile); + nand::File* writtenArchive = System::getNandManager()->write( + getSceneHeap(), "/tmp/www.arc", archiveFile->getBuffer(), archiveFile->getLength(), 0x30); + if (writtenArchive->isFatalError()) { + System::getErrorHandler()->log("NAND", writtenArchive->checkData(), "iplSetting.cpp", 0x178); + System::getErrorHandler()->set(ErrorHandler::DEFAULT, 2, NULL, 0, -1); + } + if (writtenArchive != NULL) { + writtenArchive->write(); + } + + mpChangeLayout = new layout::Object(getSceneHeap(), mpSettingLayoutFile, "arc", "SceenChange_b.brlyt"); + mpFirstAnimation = reinterpret_cast(mpChangeLayout->bind("SceenChange_b_Right.brlan")); + mpSecondAnimation = reinterpret_cast(mpChangeLayout->bind("SceenChange_b_Left.brlan")); + mpChangeLayout->finishBinding(); + + mpMainLayout = new layout::Object(getSceneHeap(), mpSettingLayoutFile, "arc", "my_AP_a.brlyt"); + for (int index = 0; index < 58; index++) { + const SettingAnimationBinding& binding = sSettingAnimationBindings[index]; + bool isSpecialAnimation = index == 10 || index == 20; + mpMainLayout->bindToGroup(sSettingAPAnimations[binding.animation], sSettingAPPaneNames[binding.pane], false, + isSpecialAnimation); + } + mpMainLayout->finishBinding(); + + mpWaitLayout = new layout::Object(getSceneHeap(), mpSettingLayoutFile, "arc", "it_Waiting_a.brlyt"); + mpWaitLayout->bindToGroup("it_Waiting_a_Wait.brlan", "G_Wait", false, false); + mpWaitLayout->finishBinding(); + mpWaitLayout->FindPaneByName("N_Wait")->SetVisible(false); + + mpBrowserData = ::operator new(0x20); + void* apScanThreadMemory = ::operator new(0x380); + mpAPScanThread = apScanThreadMemory != NULL ? new (apScanThreadMemory) APScanThread() : NULL; + void* usbThreadMemory = ::operator new(0x14); + mpUSBAPThread = usbThreadMemory != NULL ? new (usbThreadMemory) USBAPThread() : NULL; + ncd::NCDSetting::init(); + parental::Parental::init(); + + void* aossThreadMemory = ::operator new(0x5b0); + mpAOSSThread = aossThreadMemory != NULL + ? reinterpret_cast(new (aossThreadMemory) AOSSThread(getSceneHeap())) + : NULL; + void* rakuThreadMemory = ::operator new(0x348); + mpRakuRakuThread = rakuThreadMemory != NULL + ? reinterpret_cast(new (rakuThreadMemory) RakuRakuThread(getSceneHeap())) + : NULL; + + www::wiisetting::initWiiSetting(); + initWiiSettingData(); + initString(); + www::wiisetting::setStringBuf(mpStringBuffer); + OSInitMessageQueue(&mFuncMessageQueue, mFuncMessages, 5); + www::wiisetting::setMsgQueue(&mFuncMessageQueue); + + mpMem1BrowserBuffer = getSceneHeap()->alloc(0x1000, 0x20); + unk_0x908 = 0; + mpMem2BrowserBuffer = getSceneHeap()->alloc(0x800, 4); + memset(mpMem2BrowserBuffer, 0, 0x800); + mpBrowserStringBuffer = getSceneHeap()->alloc(0x79, 4); + memset(mpBrowserStringBuffer, 0, 0x79); + + mpEventHandler = new APEvent(this); + mpAPEvent = mpEventHandler; + mpPaneManager = new gui::PaneManager(mpEventHandler, mpMainLayout->getDrawInfo(), getSceneHeap(), NULL, false); + mpPaneManager->setupScene(mpMainLayout); + mpPaneManager->setAllBoundingBoxComponentTriggerTarget(false); + + for (int index = 0; index < 4; index++) { + mpPaneManager->setTriggerTarget(mpMainLayout->FindPaneByName(sSettingAPButtonNames[index]), true); + } + for (int index = 0; index < 2; index++) { + mpPaneManager->setTriggerTarget(mpMainLayout->FindPaneByName(sSettingArrowNames[index]), true); + } + + TPLBind(reinterpret_cast(static_cast(mpBackgroundTPLFile)->getBuffer())); + int tick = OSGetTick(); + OSReport("*** prepare costs: %dms\n", (tick - mPrepareTick) / (OS_TIMER_CLOCK / 4000)); + mPrepareTick = OSGetTick(); + } + + void Setting::createBrowser() { + static const char* urlFormats[] = {"marc:%s/%s/", "file:dvd/html/IPLSetting/%s/%s/"}; + static const char* pagePaths[] = { + "index01.html", "Internet/Internet_index.html", "Setup/startup_index1.html", + "Update/Update_index.html", "index02.html", "Setup/ScreenSave.html", + "Country/US_Country_flame.html", + }; + static const char* pageNames[] = {"Calendar", "Parental_Control", "Internet", "Wiiconnect24"}; + static const char* regionCodes[] = {"JP/JP", "FIX/US", "EU/EU", "TW/TW", "KR/KR", "CN/CN"}; + static const char* languageCodes[] = {"JPN", "ENG", "GER", "FRA", "SPA", "ITA", "DUT", "CHN", "KOR"}; + + EGG::Heap* mem1Heap = System::createMem1AppHeap(); + u32 mem1Size = mem1Heap->getAllocatableSize(4); + EGG::Heap* mem2Heap = System::getMem2App(); + u32 mem2Size = mem2Heap->getAllocatableSize(4) - 0x80000; + mem1Buffer_ = System::createMem1AppHeap()->alloc(mem1Size, 4); + mem2Buffer_ = mem2Heap->alloc(mem2Size, 4); + OSReport("Setting Scene: mem1: %d mem2: %d\n", mem1Size, mem2Size); + + nw4r::ut::Rect projection16x9; + nw4r::ut::Rect projection4x3; + System::getProjectionRect16x9(&projection16x9); + System::getProjectionRect4x3(&projection4x3); + int width = projection16x9.right - projection16x9.left; + int height = projection16x9.bottom - projection16x9.top; + + char basePath[100]; + char browserPath[100]; + memset(basePath, 0, sizeof(basePath)); + memset(browserPath, 0, sizeof(browserPath)); + strcpy(basePath, urlFormats[0]); + int pageIndex = mInitialArgument; + if (pageIndex < 0 || pageIndex >= 7) { + pageIndex = 0; + } + strcat(basePath, pagePaths[pageIndex]); + + int regionIndex = 1; + char productArea = SCGetProductArea(); + if (productArea >= 0 && productArea < 4) { + regionIndex = productArea > 2 ? 2 : 0; + } else if (productArea == 6) { + regionIndex = 4; + } else if (productArea == 11) { + regionIndex = 5; + } else if (productArea >= 7 && productArea < 11) { + regionIndex = 2; + } + + if (mInitialArgument == ARG_UNK_5) { + snprintf(browserPath, sizeof(browserPath), basePath, regionCodes[regionIndex], + languageCodes[System::getLanguage()], pagePaths[pageIndex]); + } else if (mInitialArgument == ARG_UNK_6) { + int directPage = 0; + for (int index = 0; index < 4; index++) { + if (strstr(reinterpret_cast(mpStringBuffer) + 0x60e, pageNames[index]) != NULL) { + directPage = index; + break; + } + } + if (directPage == 0) { + snprintf(browserPath, sizeof(browserPath), basePath, regionCodes[regionIndex], + languageCodes[System::getLanguage()], "index01.html"); + } else if (directPage == 1) { + snprintf(browserPath, sizeof(browserPath), basePath, regionCodes[regionIndex], + languageCodes[System::getLanguage()], "index02.html"); + } else { + snprintf(browserPath, sizeof(browserPath), basePath, regionCodes[regionIndex], + languageCodes[System::getLanguage()], "index03.html"); + } + } else { + snprintf(browserPath, sizeof(browserPath), basePath, regionCodes[regionIndex], + languageCodes[System::getLanguage()]); + } + + OSReport("***********************************\n"); + OSReport(" RSO PLACED : %p %d\n", static_cast(mpWWWLibraryFile)->getBuffer(), + static_cast(mpWWWLibraryFile)->getLength()); + ICInvalidateRange(static_cast(mpWWWLibraryFile)->getBuffer(), + static_cast(mpWWWLibraryFile)->getLength()); + ext_ead::www::SurfaceManager::CreateManager(width, height, width, height, mem1Buffer_, mem1Size, + mem2Buffer_, mem2Size, + static_cast(mpWWWLibraryFile)->getBuffer(), + browserPath); + ext_ead::www::SurfaceManager::RegisterArcFile(static_cast(mpWWWArchiveFile)->getBuffer()); + ext_ead::www::SurfaceManager::RegisterIniFile(static_cast(mpSettingHTMLFile)->getBuffer(), + static_cast(mpSettingHTMLFile)->getLength()); + ext_ead::www::SurfaceManager::RegisterFontFile(0, static_cast(mpFontFile)->getBuffer(), + static_cast(mpFontFile)->getLength()); + ext_ead::www::SurfaceManager::StartThread(); + } + + void Setting::initDirectUrl() { + if (mInitialArgument != ARG_UNK_6) { + return; + } + const char* settingArgument = System::getNetSettingArg(); + if (settingArgument != NULL) { + memcpy(reinterpret_cast(mpStringBuffer) + 0x60e, settingArgument, 0x80); + } + } + + void Setting::initString() { + mpStringBuffer = reinterpret_cast(getSceneHeap()->alloc(0x64e, 4)); + OSReport("HTML String Alloc Size:%d\n", 0x64e); + memset(mpStringBuffer, 0, 0x64e); + memset(unk_0x938, 0, 0x202); + initNickName(); + initSecurityKey(); + initSSID(); + initIP(); + initDNS(); + initProxy(); + initBasic(); + initMTU(); + initSecA(); + initVersion(); + initDirectUrl(); + } + + FaderSceneCommand Setting::calcFadein() { + if (System::hasCreatedAfter() && mBrowserCreated == 0) { + mBrowserCreated = 1; + createBrowser(); + OSReport("............browser created\n"); + } + + if (mBrowserCreated == 0) { + OSReport("wait first init\n"); + return FADER_SCN_CONTINUE; + } + + ext_ead::www::SurfaceManager* surfaceManager = ext_ead::www::SurfaceManager::GetInstance(); + ext_ead::www::BrowserThread* browserThread = surfaceManager->GetBrowserThread(); + if (browserThread == NULL || browserThread->GetTextureBuffer(0, NULL) == NULL || !System::hasCreatedAfter()) { + return FADER_SCN_CONTINUE; + } + + mKeyboardState = *System::getKeyboard()->getState(); + System::getFader()->fadeIn(); + mCreatePageTime = OSGetTime(); + OSReport("*** create page costs: %dms\n", + (OSGetTick() - mPrepareTick) / ((OS_TIMER_CLOCK / 4) / 1000)); + return FADER_SCN_NEXT; + } + u16 Setting::getProfileID() { u16 profileID; if (mProfileIDMode >= 3) { @@ -235,5 +524,6 @@ namespace ipl { BOOL Setting::isResetAcceptable() const { return mIsResetAcceptable; } + } // namespace scene } // namespace ipl -- 2.49.1 From fb81577a0fa6c2cc15aa3a8d6b209d9013c664b3 Mon Sep 17 00:00:00 2001 From: "devin-ai-integration[bot]" <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Tue, 29 Sep 2026 01:44:43 +0000 Subject: [PATCH 11/61] Link fa/pf_api_util + pf_w_api_util (clean subset) (#245) * fa: link pf_api_util + pf_w_api_util (genuine implementations, objdiff 100%) Co-Authored-By: wch * configure: flip fa/pf_api_util + fa/pf_w_api_util to Matching Co-Authored-By: wch --------- Co-authored-by: devin Co-authored-by: wch --- configure.py | 4 +- libs/RVL_SDK/src/fa/pf_api_util.c | 127 ++++++++++++++++++++++++++++ libs/RVL_SDK/src/fa/pf_w_api_util.c | 53 ++++++++++++ 3 files changed, 182 insertions(+), 2 deletions(-) create mode 100644 libs/RVL_SDK/src/fa/pf_api_util.c create mode 100644 libs/RVL_SDK/src/fa/pf_w_api_util.c diff --git a/configure.py b/configure.py index 6bbcff16..52f48215 100644 --- a/configure.py +++ b/configure.py @@ -1707,7 +1707,7 @@ config.libs = [ Object(NonMatching, "fa/pf_volume.c"), Object(NonMatching, "fa/pf_volume_apiadd.c"), Object(NonMatching, "fa/pf_cp932.c"), - Object(NonMatching, "fa/pf_api_util.c"), + Object(Matching, "fa/pf_api_util.c"), Object(NonMatching, "fa/pf_attach.c"), Object(NonMatching, "fa/pf_buffering.c"), Object(NonMatching, "fa/pf_cdelete.c"), @@ -1774,7 +1774,7 @@ config.libs = [ Object(NonMatching, "fa/pf_unmount.c"), Object(NonMatching, "fa/pf_unregctx.c"), Object(NonMatching, "fa/pf_xdivide.c"), - Object(NonMatching, "fa/pf_w_api_util.c"), + Object(Matching, "fa/pf_w_api_util.c"), Object(NonMatching, "fa/pf_w_cdelete.c"), Object(NonMatching, "fa/pf_w_chdir.c"), Object(NonMatching, "fa/pf_w_chdmod.c"), diff --git a/libs/RVL_SDK/src/fa/pf_api_util.c b/libs/RVL_SDK/src/fa/pf_api_util.c new file mode 100644 index 00000000..f70a9f9b --- /dev/null +++ b/libs/RVL_SDK/src/fa/pf_api_util.c @@ -0,0 +1,127 @@ +#include +#include + +static s32 pf_error_to_api_error[] = {FA_ERR_SUCCESS, FA_ERR_EINVAL, FA_ERR_EINVAL, FA_ERR_ENOENT, FA_ERR_EBUSY, FA_ERR_ENOTEMPTY, FA_ERR_ENOSPC, + FA_ERR_ENOEXEC, FA_ERR_EEXIST, FA_ERR_ENOEXEC, FA_ERR_EINVAL, FA_ERR_EWRTPROTECT, FA_ERR_ENOSYS, FA_ERR_ENOEXEC, + FA_ERR_ENOEXEC, FA_ERR_ENOEXEC, FA_ERR_EACCES, FA_ERR_EIO, FA_ERR_ENOEXEC, FA_ERR_EACCES, FA_ERR_ENOENT, + FA_ERR_ENFILE, FA_ERR_EMFILE, FA_ERR_EISDIR, FA_ERR_EACCES, FA_ERR_EPERM, FA_ERR_ENOEXEC, FA_ERR_ENOEXEC, + FA_ERR_ENOEXEC, FA_ERR_ENOEXEC, FA_ERR_ENOMEM, FA_ERR_EINVAL, FA_ERR_EINVAL, FA_ERR_ENOEXEC, FA_ERR_ENOENT, + FA_ERR_ENOEXEC, FA_ERR_ENOEXEC, FA_ERR_EFBIG, FA_ERR_EBADF, FA_ERR_ENOLCK}; + +s32 PFAPI_ParseOpenModeString(const char* mode_str) { + s32 open_mode = 0; + u32 i = 0; + + if (mode_str == NULL) { + open_mode = 10; + return open_mode; + } + + switch (mode_str[i++]) { + case 'r': { + open_mode = 2; + break; + } + case 'w': { + open_mode = 1; + break; + } + case 'a': { + open_mode = 4; + break; + } + default: { + return 0; + } + } + + if (mode_str[i] == 'b') { + i++; + } + switch (mode_str[i++]) { + case 0: { + return open_mode; + } + case 't': + default: { + return 0; + } + case '+': { + switch (mode_str[i]) { + case 0: { + return open_mode | 8; + } + default: { + return 0; + } + } + } + } + return 0; +} + +s32 PFAPI_convertError(s32 err) { + if (err == 0) { + return 0; + } + if (err == -1) { + return -1; + } + if (err > 0 && err < 0xA0) { + return pf_error_to_api_error[err]; + } + if (err == 0x1000) { + err = FA_ERR_EIO; + } + return err; +} + +s32 PFAPI_convertDriverError(s32 err) { + if (err == 0) { + return 0; + } + if (err <= 0) { + return err; + } + if ((u32)err < 0xA0) { + err = 1; + } + return err; +} + +s32 PFAPI_convertReturnValue(s32 err) { + if (err == 0) { + return 0; + } + return -1; +} + +s32 PFAPI_convertReturnValue4feof(s32 err) { + if (err == 1) { + return 1; + } + if (err == 0) { + return 0; + } + return -1; +} + +void* PFAPI_convertReturnValue2NULL(s32 err, void* p_stream) { + void* ret; + if (err) { + ret = NULL; + } else { + ret = p_stream; + } + return ret; +} + +s32 PFAPI_convertReturnValue4unmount(s32 err) { + if (err == 0) { + return 0; + } + if (err == 1) { + return 1; + } + return -1; +} diff --git a/libs/RVL_SDK/src/fa/pf_w_api_util.c b/libs/RVL_SDK/src/fa/pf_w_api_util.c new file mode 100644 index 00000000..cf7a7b2c --- /dev/null +++ b/libs/RVL_SDK/src/fa/pf_w_api_util.c @@ -0,0 +1,53 @@ +#include + +s32 PFWAPI_ParseOpenModeString(const unsigned short* mode_str) { + s32 open_mode = 0; + u32 i = 0; + + if (mode_str == NULL) { + open_mode = 10; + return open_mode; + } + + switch (mode_str[i++]) { + case 'r': { + open_mode = 2; + break; + } + case 'w': { + open_mode = 1; + break; + } + case 'a': { + open_mode = 4; + break; + } + default: { + return 0; + } + } + + if (mode_str[i] == 'b') { + i++; + } + switch (mode_str[i++]) { + case 0: { + return open_mode; + } + case 't': + default: { + return 0; + } + case '+': { + switch (mode_str[i]) { + case 0: { + return open_mode | 8; + } + default: { + return 0; + } + } + } + } + return 0; +} -- 2.49.1 From 358f5cc1b5b72088c9a72ea3e97d42ba8edbe5c4 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 01:49:39 +0000 Subject: [PATCH 12/61] decompile setting screen transitions --- include/scene/setting/iplSetting.h | 11 ++ src/scene/setting/iplSetting.cpp | 164 +++++++++++++++++++++++++++-- 2 files changed, 167 insertions(+), 8 deletions(-) diff --git a/include/scene/setting/iplSetting.h b/include/scene/setting/iplSetting.h index 85486dec..b8d9de75 100644 --- a/include/scene/setting/iplSetting.h +++ b/include/scene/setting/iplSetting.h @@ -13,6 +13,12 @@ #include "utility/iplThread.h" #endif +namespace ipl { + namespace controller { + class Interface; + } +} + namespace ipl { namespace scene { #ifdef IPL_SETTING_IMPLEMENTATION @@ -60,6 +66,11 @@ namespace ipl { void initMTU(); void initSecA(); void initVersion(); + void updateController_(); + void setSE(); + void changeVideoMode(); + bool isInitialSequenceExit(const ::ipl::controller::Interface* input); + bool updateScreenMode(); void start_point_event(const char* pageName); void start_trig_event(const char* pageName); void start_left_event(const char* pageName); diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 0c4d567d..b6b6fe28 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -5,6 +5,7 @@ #include "scene/setting/iplParental.h" #include "system/iplErrorHandler.h" #include "system/iplSystem.h" +#include "utility/iplWpad.h" #include "iplwww/www_wiisetting.h" #include "iplwww/www_surface.h" @@ -456,13 +457,13 @@ namespace ipl { } FaderSceneCommand Setting::calcFadein() { - if (System::hasCreatedAfter() && mBrowserCreated == 0) { - mBrowserCreated = 1; - createBrowser(); - OSReport("............browser created\n"); - } - - if (mBrowserCreated == 0) { + if (System::hasCreatedAfter()) { + if (mBrowserCreated == 0) { + mBrowserCreated = 1; + createBrowser(); + OSReport("............browser created\n"); + } + } else if (mBrowserCreated == 0) { OSReport("wait first init\n"); return FADER_SCN_CONTINUE; } @@ -477,10 +478,157 @@ namespace ipl { System::getFader()->fadeIn(); mCreatePageTime = OSGetTime(); OSReport("*** create page costs: %dms\n", - (OSGetTick() - mPrepareTick) / ((OS_TIMER_CLOCK / 4) / 1000)); + (OSGetTick() - mPrepareTick) / (OS_TIMER_CLOCK / 1000)); return FADER_SCN_NEXT; } + void Setting::updateController_() { + nw4r::ut::Rect projection; + System::getProjectionRect4x3(&projection); + + if (isAnimating()) { + return; + } + + controller::Interface* youngController = System::getYoungController(); + ext_ead::www::BrowserThread::CmdPacket packet; + + if (youngController == NULL) { + packet.type = 0; + packet.data.controller.irX = -1000.0f; + packet.data.controller.irY = -1000.0f; + packet.data.controller.btnHold = 0; + packet.data.controller.btnTrigger = 0; + packet.data.controller.btnRelease = 0; + ext_ead::www::SurfaceManager::GetInstance()->GetBrowserThread()->SendUIEvent(&packet); + return; + } + + if (unk_0xB9C >= 10 && *(reinterpret_cast(mpStringBuffer) + 0x60e) == 0) { + packet.data.controller.irX = youngController->getDpdProjectionPos().x - projection.left; + packet.data.controller.irY = youngController->getDpdProjectionPos().y - projection.top; + u32 classicHold = youngController->getClassicHoldFlag(); + u32 classicTrigger = youngController->getClassicTrigFlag(); + u32 classicRelease = youngController->getClassicReleaseFlag(); + packet.data.controller.btnHold = (classicHold << 16) | youngController->getHoldFlag(); + packet.data.controller.btnTrigger = (classicTrigger << 16) | youngController->getTrigFlag(); + packet.data.controller.btnRelease = (classicRelease << 16) | youngController->getReleaseFlag(); + } else { + packet.data.controller.irX = -1000.0f; + packet.data.controller.irY = -1000.0f; + packet.data.controller.btnHold = 0; + packet.data.controller.btnTrigger = 0; + packet.data.controller.btnRelease = 0; + } + + packet.type = 0; + if (mKeyboardState.type == textinput::MemoManager::ST_Hidden && unk_0x74 == 0) { + ext_ead::www::SurfaceManager::GetInstance()->GetBrowserThread()->SendUIEvent(&packet); + } + } + + void Setting::changeVideoMode() { + setSE(); + VISetBlack(TRUE); + VIFlush(); + VIWaitForRetrace(); + System::resetFrameworkRenderMode(); + + u32 startTick = OSGetTick(); + while ((OSGetTick() - startTick) / (OS_TIMER_CLOCK / 1000) < 0x67c) { + VIWaitForRetrace(); + } + + mAspectRatio = SCGetAspectRatio(); + mProgressiveMode = SCGetProgressiveMode(); + mEuRgb60Mode = SCGetEuRgb60Mode(); + unk_0xB94 = 0; + + VISetBlack(FALSE); + VIFlush(); + VIWaitForRetrace(); + + while (mpSecondAnimation->state == 1 || mpFirstAnimation->state == 1) { + mpChangeLayout->calc(); + } + + mState = 20; + unk_0xB9C = 10; + } + + bool Setting::isInitialSequenceExit(const controller::Interface* input) { + u32 connectedMask = utility::wpad::getWpadConnectedMask(); + if (input->downTrg(0x100800)) { + return true; + } + + OSTime elapsed = OSGetTime() - mCreatePageTime; + if (elapsed / (OS_TIMER_CLOCK / 1000) >= 500 && connectedMask != unk_0xBA8 && + utility::wpad::isIncreaseConnectedWpad(unk_0xBA8, connectedMask)) { + return true; + } + + if (connectedMask != unk_0xBA8) { + unk_0xBA8 = connectedMask; + } + return false; + } + + bool Setting::updateScreenMode() { + if (unk_0x91C[2] != 0) { + if (unk_0xB94 == 0) { + if (mEuRgb60Mode == SCGetEuRgb60Mode()) { + if (mProgressiveMode != SCGetProgressiveMode()) { + unk_0xB94 = 2; + } + } else { + unk_0xB94 = 3; + } + + if (unk_0xB94 != 0 && unk_0xB94 != 1) { + System::getFader()->fadeOut(); + mState = 0; + return true; + } + } + } else if (unk_0xB94 == 1 && unk_0x74 == 8) { + System::getFader()->fadeOut(); + mState = 0; + unk_0x92C = 0; + unk_0x74 = 0; + return true; + } + + if (unk_0xB94 == 1) { + if (System::getFader()->getStatus() != EGG::Fader::PREPARE_IN) { + mState = 0; + return true; + } + + System::getDialog()->terminate(); + SCSetAspectRatio(mAspectRatio & 0xff); + SCFlush(); + if (System::getDialog()->getLastResult() < 0) { + mState = 0; + return true; + } + + changeVideoMode(); + www::wiisetting::setStringBuf(mpStringBuffer); + System::getFader()->fadeIn(); + } else if (unk_0xB94 > 0 && unk_0xB94 < 4) { + if (System::getFader()->getStatus() != EGG::Fader::PREPARE_IN) { + mState = 0; + return true; + } + + changeVideoMode(); + System::getFader()->fadeIn(); + } + + return false; + } + u16 Setting::getProfileID() { u16 profileID; if (mProfileIDMode >= 3) { -- 2.49.1 From 9109e569ef53759e339733ccf241ffd1a0ce5138 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 01:52:47 +0000 Subject: [PATCH 13/61] match setting video mode transition --- src/scene/setting/iplSetting.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index b6b6fe28..1ebea248 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -548,6 +548,14 @@ namespace ipl { VIFlush(); VIWaitForRetrace(); + if (static_cast(System::getRegion()) == 2) { + if (mEuRgb60Mode == 0) { + *reinterpret_cast(0x800000cc) = 1; + } else { + *reinterpret_cast(0x800000cc) = 5; + } + } + while (mpSecondAnimation->state == 1 || mpFirstAnimation->state == 1) { mpChangeLayout->calc(); } -- 2.49.1 From c2e3917e0e5325f29f7949f6d4427f29287acf66 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 02:12:04 +0000 Subject: [PATCH 14/61] decompile setting normal update --- include/scene/setting/iplSetting.h | 26 +- src/scene/setting/iplSetting.cpp | 549 ++++++++++++++++++++++++++++- 2 files changed, 572 insertions(+), 3 deletions(-) diff --git a/include/scene/setting/iplSetting.h b/include/scene/setting/iplSetting.h index b8d9de75..7009b9c8 100644 --- a/include/scene/setting/iplSetting.h +++ b/include/scene/setting/iplSetting.h @@ -8,6 +8,7 @@ #include "layout/iplGuiManager.h" #include "layout/GUIManager.h" #include "iplwww/www_wiisetting.h" +#include "iplwww/www_browser.h" #include "system/iplKeyboard.h" #include "system/iplNand.h" #include "utility/iplThread.h" @@ -32,6 +33,7 @@ namespace ipl { virtual void onEvent(u32 componentID, u32 event, void* data); void setEventType(u8 eventType) { reinterpret_cast(mpManager) = eventType; } + u8 getEventType() const { return reinterpret_cast(mpManager); } private: Setting* mpSetting; @@ -71,6 +73,26 @@ namespace ipl { void changeVideoMode(); bool isInitialSequenceExit(const ::ipl::controller::Interface* input); bool updateScreenMode(); + void initHTMLText(); + void initMessage(); + void initKeyboard(const char* text); + void calcKeyboard(); + void calcSetting(); + bool calcSafeMode(); + void waitStart(); + void waitFinish(); + bool isWaitPlaying(); + void initAP(); + void resetAP(); + void redrawAP(); + void scanAP(); + void setNUP(); + void setUSBAP(); + void cancelUSBAP(); + void AOSSProcess(); + void RakuProcess(); + void setUpdate_(); + void setUseEULA_(); void start_point_event(const char* pageName); void start_trig_event(const char* pageName); void start_left_event(const char* pageName); @@ -144,8 +166,8 @@ namespace ipl { int unk_0x914; int unk_0x918; u8 unk_0x91C[4]; - void* mpBrowserData; - u32 unk_0x924; + ext_ead::www::ImeData* mpBrowserData; + www::wiisetting::WiiData* mpWiiSettingData; APEvent* mpAPEvent; u8 unk_0x92C; u8 unk_0x92D[3]; diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 1ebea248..64c4a306 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -3,9 +3,11 @@ #include "scene/setting/iplNCDSetting.h" #include "scene/setting/iplParental.h" +#include "scene/parentalDialog/iplParentalDialog.h" #include "system/iplErrorHandler.h" #include "system/iplSystem.h" #include "utility/iplWpad.h" +#include "sound/iplSound.h" #include "iplwww/www_wiisetting.h" #include "iplwww/www_surface.h" @@ -16,6 +18,7 @@ #include #include #include +#include namespace ipl { namespace keyboard { @@ -286,7 +289,7 @@ namespace ipl { mpWaitLayout->finishBinding(); mpWaitLayout->FindPaneByName("N_Wait")->SetVisible(false); - mpBrowserData = ::operator new(0x20); + mpBrowserData = static_cast(::operator new(0x20)); void* apScanThreadMemory = ::operator new(0x380); mpAPScanThread = apScanThreadMemory != NULL ? new (apScanThreadMemory) APScanThread() : NULL; void* usbThreadMemory = ::operator new(0x14); @@ -637,6 +640,550 @@ namespace ipl { return false; } + FaderSceneCommand Setting::calcNormal() { + if (unk_0x5C == 0) { + getFuncMsgQ(); + controller::Interface* input = System::getYoungController(); + + ++mState; + if (mState > 20) { + mState = 20; + } + if (unk_0xB9C > 0) { + ++unk_0xB9C; + } + if (unk_0xB9C > 10) { + unk_0xB9C = 10; + } + if (updateScreenMode()) { + return FADER_SCN_CONTINUE; + } + + if (input != NULL) { + if (input->downTrg(0x100800) && mpWiiSettingData->data[0x12] == 0x1e && + unk_0x92C > 0x1e && unk_0x92C < 0x78) { + unk_0x92C = 0x78; + www::wiisetting::setFuncResult(1); + mpWiiSettingData->data[0x37] = 1; + setSE(); + unk_0xB9C = 0; + } + if (isInitialSequenceExit(input) && mpWiiSettingData->data[0x12] == 0x1f) { + snd::getSystem()->startSE("WIPL_SE_DECIDE"); + www::wiisetting::setFuncResult(1); + mpWiiSettingData->data[0x12] = 0; + } + } + + if (unk_0xBAC == 0 && unk_0xB9C == 10 && mpStringBuffer->netSettingArg[0] != 0) { + www::wiisetting::setFuncResult(1); + unk_0xBAC = 1; + } + + if (System::getAspectRatio()) { + updateController_(); + } + + ext_ead::www::BrowserThread* browserThread = + ext_ead::www::SurfaceManager::GetInstance()->GetBrowserThread(); + if (browserThread->ReceiveWindowEvent(mpBrowserData)) { + if (mpBrowserData->unk_0x00 == 0) { + OSReport("IME Created "); + if (mpBrowserData->text != NULL) { + OSReport("initKeyboard %s\n"); + OSReport("initKeyboard %d\n", mpWiiSettingData->data[0x11]); + if (mpWiiSettingData->data[0x11] == 0) { + browserThread->CommitIme(mpBrowserData, mpBrowserData->text); + browserThread->DisposeImeData(mpBrowserData); + } else { + unk_0x74 = 1; + initKeyboard(mpBrowserData->text); + } + } else { + OSReport("NULL ptr\n"); + } + } else { + OSReport("Other Event\n"); + } + } + } + + switch (unk_0x74) { + case 1: + calcKeyboard(); + break; + case 2: + if (System::getDialog()->getLastResult() >= 0) { + unk_0xB9C = 1; + unk_0x74 = 0; + mIsResetAcceptable = 1; + } + break; + case 3: + if (System::getDialog()->getLastResult() == 1 || + System::getDialog()->getLastResult() == 2) { + if (unk_0xB9C == 0) { + www::wiisetting::setFuncResult(System::getDialog()->getLastResult()); + } else if (www::wiisetting::getFuncResult() == 0) { + unk_0x74 = 0; + } + unk_0xB9C = 1; + } + break; + case 4: + mpWiiSettingData->data[0x12] = 1; + if (System::getHomeButtonMenu()->disable() && + System::getDialog()->getLastResult() >= 0) { + unk_0x74 = 0; + } + break; + case 5: + if (System::getScene(0x1b) == NULL) { + if (unk_0x91C[3] == 1) { + unk_0x74 = 0; + unk_0x91C[3] = 0; + resetFuncMsgQ(); + if (mpAPEvent->getEventType() != 'O') { + unk_0xB9C = 1; + } + } + } else { + unk_0x91C[3] = 1; + scene::ParentalDialog* parentalDialog = + static_cast(System::getScene(0x1b)); + scene::ParentalDialog::Result result = parentalDialog->getResult(); + if (result == scene::ParentalDialog::RESULT_OVER_ATTEMPTS) { + www::wiisetting::setFuncResult(2); + } else if (result == scene::ParentalDialog::RESULT_SUCCESS) { + unk_0x74 = 6; + www::wiisetting::setFuncResult(1); + } else if (result > scene::ParentalDialog::RESULT_OVER_ATTEMPTS && + result <= scene::ParentalDialog::RESULT_CANCELLED) { + www::wiisetting::setFuncResult(2); + } + } + break; + case 6: + if (System::getScene(0x1b) == NULL) { + unk_0x91C[3] = 0; + if (mpAPEvent->getEventType() == 'O') { + if (!ncd::NCDSetting::getEnableFlag()) { + System::getDialog()->callBtn2(System::getRegion() == 2 ? 0x174 : 0x170, + 0x146, 0x25); + unk_0x74 = 9; + } else if (SCGetEULA() == 0) { + System::getDialog()->callBtn2(System::getRegion() == 2 ? 0x175 : 0x172, + 0x2e, 0x25); + unk_0x74 = 0xe; + } else { + www::wiisetting::setFuncResult(6); + unk_0x74 = 0; + resetFuncMsgQ(); + } + } else { + unk_0x74 = 0; + } + } + break; + case 7: + if (System::getDialog()->getLastResult() == 1) { + www::wiisetting::setFuncResult(1); + SCSetWCFlags(SCGetWCFlags() & 0xfffffffe); + SCIdleModeInfo idleMode = {0, 0}; + SCSetIdleMode(&idleMode); + if (System::getNwc24Manager() != NULL) { + System::getNwc24Manager()->enableLedNotification(TRUE); + } + SCSetEULA(0); + ncd::NCDSetting::adjustNWC24Flag(); + parental::Parental::setCountry(mpWiiSettingData->data[0x3c]); + parental::Parental::clear(); + System::reloadDownloadTask(); + unk_0x74 = 0; + } else if (System::getDialog()->getLastResult() == 2) { + www::wiisetting::setFuncResult(2); + unk_0x74 = 0; + unk_0xB9C = 1; + } + break; + case 8: + ++unk_0x92C; + if (unk_0x92C == 0xb4) { + unk_0xB94 = 1; + unk_0x92C = 0; + } + break; + case 9: + if (System::getDialog()->getLastResult() == 1) { + if (mpAPEvent->getEventType() == 'O') { + www::wiisetting::setFuncResult(5); + resetFuncMsgQ(); + } else { + www::wiisetting::setFuncResult(6); + } + unk_0x74 = 0; + } else if (System::getDialog()->getLastResult() == 2) { + if (mpAPEvent->getEventType() == 'O') { + if (unk_0xB9C == 0) { + www::wiisetting::setFuncResult(2); + } else if (www::wiisetting::getFuncResult() == 0) { + unk_0x74 = 0; + resetFuncMsgQ(); + } + unk_0xB9C = 1; + } else { + unk_0x74 = 0; + www::wiisetting::setFuncResult(2); + } + } + break; + case 10: + if (System::getDialog()->getLastResult() == 2) { + System::getDialog()->callBtn1(0x172, 1); + unk_0x74 = 0xb; + SCSetWCFlags(SCGetWCFlags() & 0xfffffffe); + SCIdleModeInfo idleMode = {0, 0}; + SCSetIdleMode(&idleMode); + if (System::getNwc24Manager() != NULL) { + System::getNwc24Manager()->enableLedNotification(TRUE); + } + SCSetEULA(0); + ncd::NCDSetting::adjustNWC24Flag(); + SCFlush(); + } else if (System::getDialog()->getLastResult() == 1) { + mProfileIDMode = 0; + unk_0xB9C = 1; + unk_0x74 = 0; + } + break; + case 0xb: + if (System::getDialog()->getLastResult() >= 0) { + mProfileIDMode = 10; + mpAPEvent->setEventType(0x54); + unk_0x74 = 0; + } + break; + case 0xc: + if (System::getDialog()->getLastResult() == 2) { + SCSetWCFlags(SCGetWCFlags() & 0xfffffffe); + SCIdleModeInfo idleMode = {0, 0}; + SCSetIdleMode(&idleMode); + if (System::getNwc24Manager() != NULL) { + System::getNwc24Manager()->enableLedNotification(TRUE); + } + SCSetEULA(0); + ncd::NCDSetting::adjustNWC24Flag(); + SCFlush(); + System::getDialog()->callBtn1(0x170, 0x2e); + unk_0x74 = 9; + } else if (System::getDialog()->getLastResult() == 1) { + unk_0xB9C = 1; + unk_0x74 = 0; + } + break; + case 0xd: + if (System::getDialog()->getLastResult() == 1) { + www::wiisetting::setFuncResult(8); + unk_0x74 = 0; + } else if (System::getDialog()->getLastResult() == 2) { + www::wiisetting::setFuncResult(7); + unk_0x74 = 0; + } + break; + case 0xe: + if (System::getDialog()->getLastResult() == 1) { + mpAPEvent->setEventType(0x55); + unk_0x74 = 0; + } else if (System::getDialog()->getLastResult() == 2) { + if (unk_0xB9C == 0) { + www::wiisetting::setFuncResult(2); + } else if (www::wiisetting::getFuncResult() == 0) { + resetFuncMsgQ(); + unk_0x74 = 0; + } + unk_0xB9C = 1; + } + break; + case 0x11: + calcSafeMode(); + break; + } + + u8 action = mpWiiSettingData->data[0x12]; + if (action != 0) { + if (action == 0x1e) { + ++unk_0x92C; + if (unk_0x92C == 1) { + System::getDialog()->callBtn1(0x1bf, 0x2e); + unk_0x74 = 4; + } else if (unk_0x92C == 3) { + TPLBind(NULL); + } else if (unk_0x92C == 0x55 || unk_0x92C == 0x5a) { + BOOL interruptLevel = OSDisableInterrupts(); + WPADSetSensorBarPower(unk_0x92C == 0x5a); + OSRestoreInterrupts(interruptLevel); + if (unk_0x92C == 0x5a) { + unk_0x92C = 0x1e; + } + } else if (unk_0x92C == 0x96) { + BOOL interruptLevel = OSDisableInterrupts(); + WPADSetSensorBarPower(TRUE); + OSRestoreInterrupts(interruptLevel); + System::getHomeButtonMenu()->enable(); + mpWiiSettingData->data[0x12] = 0; + TPLBind(reinterpret_cast( + static_cast(mpBackgroundTPLFile)->getBuffer())); + unk_0x92C = 0; + } + } else if (action < 0x1f) { + initHTMLText(); + initMessage(); + } + } + + if (mpWiiSettingData->data[0x36] != 0) { + calcSetting(); + } + + switch (mpAPEvent->getEventType()) { + case 1: + resetFuncMsgQ(); + waitStart(); + createChildScene(0x19, this, NULL, NULL); + break; + case 4: + resetAP(); + initAP(); + mpAPEvent->setEventType(2); + case 2: + case 3: + scanAP(); + break; + case 5: + resetAP(); + break; + case 6: + initAP(); + resetFuncMsgQ(); + break; + case 7: + redrawAP(); + break; + case 9: + setNUP(); + break; + case 0x17: + parental::Parental::clearMiss(); + case 'Z': + System::getHomeButtonMenu()->enable(); + resetFuncMsgQ(); + break; + case 0x18: + ncd::NCDSetting::write(); + case ']': + mIsResetAcceptable = 0; + resetFuncMsgQ(); + break; + case 0x1a: + System::getDialog()->callBtn2(System::getRegion() == 2 ? 0x160 : 0x15f, + 0x2e, 0x13b); + unk_0x74 = 3; + resetFuncMsgQ(); + break; + case 0x1c: + if (mAspectRatio != mpWiiSettingData->data[6]) { + mAspectRatio = mpWiiSettingData->data[6]; + if (mAspectRatio == 1) { + System::getDialog()->callBtn0(0x1bd, 0, false); + } else if (mAspectRatio == 0) { + System::getDialog()->callBtn0(0x1c9, 0, false); + } + unk_0x74 = 8; + } + resetFuncMsgQ(); + break; + case 0x1d: + case 'M': + case 'N': + if (action == 0x1d || calcSafeMode()) { + if (!parental::Parental::checkFlags()) { + www::wiisetting::setFuncResult(1); + if (mpAPEvent->getEventType() == 'N') { + unk_0x74 = 6; + } + } else { + createChildScene(0x1b, this, NULL, reinterpret_cast(1)); + unk_0x74 = 5; + } + if (mpAPEvent->getEventType() == 0x1d || mpAPEvent->getEventType() == 'M') { + resetFuncMsgQ(); + } else { + mpAPEvent->setEventType('O'); + } + } + break; + case 0x1e: + memset(mpMem2BrowserBuffer, 0, 0x800); + memset(mpBrowserStringBuffer, 0, 0x79); + mpAPEvent->setEventType(0x23); + case '#': + setUSBAP(); + break; + case 0x1f: + cancelUSBAP(); + break; + case ' ': + case '!': + case '"': + AOSSProcess(); + break; + case '(': + case ')': + case '*': + case '+': + case ',': + RakuProcess(); + break; + case '4': + if (System::getHomeButtonMenu()->disable() && unk_0x5C == 0) { + controller::Interface* youngController = System::getYoungController(); + if (youngController != NULL && youngController->downTrg(0x100800)) { + resetFuncMsgQ(); + System::getHomeButtonMenu()->enable(); + www::wiisetting::setFuncResult(5); + } + } + break; + case 'P': + SCSetLanguage(mpWiiSettingData->data[0x30]); + if (SCGetConfigDoneFlag() == 0 && SCGetConfigDoneFlag2() == 0 && + System::getRegion() == 2) { + if (mpWiiSettingData->data[0x30] == 3) { + mpWiiSettingData->data[0x3c] = 0x68; + parental::Parental::setCountry(0x68); + } else { + mpWiiSettingData->data[0x3c] = 0x40; + parental::Parental::setCountry(0x40); + } + } + SCFlush(); + System::getKeyboard()->setLanguage(SCGetLanguage()); + parental::Parental::init(); + System::reloadDownloadTask(); + resetFuncMsgQ(); + break; + case 'Q': + snd::getSystem()->muteOffBGM(0x5a); + resetFuncMsgQ(); + break; + case 'R': + snd::getSystem()->muteOnBGM(0x5a); + resetFuncMsgQ(); + break; + case 'S': + if (mInitialArgument == 2 || mInitialArgument == 5) { + parental::Parental::setCountry(mpWiiSettingData->data[0x3c]); + parental::Parental::clear(); + www::wiisetting::setFuncResult(1); + } else if (mpWiiSettingData->data[0x3c] == parental::Parental::getCountry()) { + www::wiisetting::setFuncResult(1); + } else { + System::getDialog()->callBtn2(0x1c4, 0x2e, 0x13b); + unk_0x74 = 7; + } + resetFuncMsgQ(); + break; + case 'T': + setUpdate_(); + break; + case 'U': + if (unk_0x7C == 0) { + unk_0x7C = 1; + } + setUseEULA_(); + break; + case 'V': + mProfileIDMode = 9; + setUpdate_(); + break; + case 'W': + setUseEULA_(); + break; + case 'X': + if (unk_0x7C == 0) { + unk_0x7C = 2; + } + setUseEULA_(); + break; + case 'Y': + mProfileIDMode = 2; + mpAPEvent->setEventType(0x54); + break; + case '[': + if (System::getHomeButtonMenu()->disable()) { + resetFuncMsgQ(); + } + break; + case '\\': + mIsResetAcceptable = 1; + resetFuncMsgQ(); + break; + case '^': + System::getHomeButtonMenu()->enable(); + mIsResetAcceptable = 1; + resetFuncMsgQ(); + break; + case '_': + if (System::getHomeButtonMenu()->disable()) { + mIsResetAcceptable = 0; + resetFuncMsgQ(); + } + break; + case 'd': + createChildScene(0x1d, this, NULL, reinterpret_cast(2)); + resetFuncMsgQ(); + waitStart(); + break; + case 'e': + unk_0x74 = 0xf; + ++unk_0x92C; + if (unk_0x92C >= 100) { + mIsResetAcceptable = 1; + System::getResetHandler()->reset(); + resetFuncMsgQ(); + } + break; + case 'f': + unk_0x74 = 0x10; + ++unk_0x92C; + if (unk_0x92C >= 100) { + mIsResetAcceptable = 1; + System::getResetHandler()->powerOff(); + resetFuncMsgQ(); + } + break; + case 'g': + if (calcSafeMode()) { + www::wiisetting::setFuncResult(1); + resetFuncMsgQ(); + } + break; + } + + if (mpWiiSettingData->data[0x37] != 0 || mpWiiSettingData->data[0x38] != 0) { + setSE(); + } + if (mpWiiSettingData->data[0x39] != 0) { + return FADER_SCN_NEXT; + } + + mpChangeLayout->calc(); + mpMainLayout->calc(); + mpWaitLayout->calc(); + unk_0x91C[2] = 0; + return FADER_SCN_CONTINUE; + } + u16 Setting::getProfileID() { u16 profileID; if (mProfileIDMode >= 3) { -- 2.49.1 From a7efd956cd00431e7a5049df100f34659971208f Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 02:17:55 +0000 Subject: [PATCH 15/61] decompile setting fadeout --- include/scene/setting/iplSetting.h | 2 +- src/scene/setting/iplSetting.cpp | 67 ++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/include/scene/setting/iplSetting.h b/include/scene/setting/iplSetting.h index 7009b9c8..2a7e8dff 100644 --- a/include/scene/setting/iplSetting.h +++ b/include/scene/setting/iplSetting.h @@ -142,7 +142,7 @@ namespace ipl { u8 unk_0x88[8]; int mFuncMsgPending; int unk_0x94; - u8 unk_0x98[8]; + ESTitleId mUpdateTitleId; u32 mPrepareTick; u8 mSettingData[0x16]; u8 unk_0xBA[2]; diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 64c4a306..eb9902dc 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -19,6 +19,8 @@ #include #include #include +#include +#include namespace ipl { namespace keyboard { @@ -1184,6 +1186,71 @@ namespace ipl { return FADER_SCN_CONTINUE; } + FaderSceneCommand Setting::calcFadeout() { + if (System::getFader()->getStatus() == EGG::Fader::PREPARE_IN) { + if (unk_0x5C == 0) { + unk_0x5C = 1; + ext_ead::www::SurfaceManager::GetInstance()->StopThreadAsync(); + OSReport("!!!!!!!!!!!!! SCFlush !!!!!!!!!!!!!!\n"); + SCFlush(); + } else if (unk_0x7C == 5) { + if (mInitialArgument == 2 || mInitialArgument == 5) { + SCSetConfigDoneFlag(TRUE); + SCSetConfigDoneFlag2(TRUE); + SCSetUpdateType(0); + SCFlush(); + } + + while (WPADGetStatus() != 0 || + System::getBS2Manager()->getIPLState() != bs2::IPL_STATE_8) { + snd::getSystem()->calc(); + System::getBS2Manager()->update(); + VIWaitForRetrace(); + if (WPADGetStatus() != 0) { + OSReport("wait for WPAD\n"); + } + if (System::getBS2Manager()->getIPLState() != bs2::IPL_STATE_8) { + OSReport("wait for BS2\n"); + } + } + + VISetBlack(TRUE); + VIFlush(); + VIWaitForRetrace(); + OSReport("VI Black\n"); + while (!__OSSyncSram()) { + OSReport("sync sram\n"); + } + while (!System::isReceiveScheduleStopped()) { + OSReport("Wait ScheduleStopped\n"); + OSSleepMilliseconds(5); + } + __OSLaunchTitlelForSystem(mUpdateTitleId, 0, NULL); + for (;;) { + OSReport(NULL); + } + } else if (ext_ead::www::SurfaceManager::GetInstance()->IsThreadStopped()) { + OSReport("reserve destroy\n"); + ext_ead::www::SurfaceManager::DisposeManager(); + OSReport("reserve destroy done\n"); + if (mInitialArgument == 2 || mInitialArgument == 5) { + SCSetConfigDoneFlag(TRUE); + SCSetConfigDoneFlag2(TRUE); + SCSetUpdateType(0); + SCFlush(); + reserveAllSceneDestruction(0x1a, NULL); + } else { + System::reloadDownloadTask(); + reserveAllSceneDestruction(0x15, NULL); + } + delete mpBrowserData; + return FADER_SCN_NEXT; + } + } + + return FADER_SCN_CONTINUE; + } + u16 Setting::getProfileID() { u16 profileID; if (mProfileIDMode >= 3) { -- 2.49.1 From 69fabd7f0cdde8c56973c4d12c8e90f0b88c6da1 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 02:20:52 +0000 Subject: [PATCH 16/61] match setting data initialization --- include/scene/setting/iplSetting.h | 5 +--- src/scene/setting/iplSetting.cpp | 43 +++++++++++++++++++----------- 2 files changed, 28 insertions(+), 20 deletions(-) diff --git a/include/scene/setting/iplSetting.h b/include/scene/setting/iplSetting.h index 2a7e8dff..72fdfe04 100644 --- a/include/scene/setting/iplSetting.h +++ b/include/scene/setting/iplSetting.h @@ -32,9 +32,6 @@ namespace ipl { virtual void onEvent(u32 componentID, u32 event, void* data); - void setEventType(u8 eventType) { reinterpret_cast(mpManager) = eventType; } - u8 getEventType() const { return reinterpret_cast(mpManager); } - private: Setting* mpSetting; }; @@ -168,7 +165,7 @@ namespace ipl { u8 unk_0x91C[4]; ext_ead::www::ImeData* mpBrowserData; www::wiisetting::WiiData* mpWiiSettingData; - APEvent* mpAPEvent; + www::wiisetting::WiiFlag* mpWiiSettingFlag; u8 unk_0x92C; u8 unk_0x92D[3]; int unk_0x930; diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index eb9902dc..cf1873d1 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -144,12 +144,12 @@ namespace ipl { OSMessage message = 0; if (mFuncMsgPending == 0 && OSReceiveMessage(&mFuncMessageQueue, &message, 0)) { mFuncMsgPending = 1; - mpAPEvent->setEventType((u8)message); + mpWiiSettingFlag->smthMsgData = (u8)message; } } void Setting::resetFuncMsgQ() { - mpAPEvent->setEventType(0); + mpWiiSettingFlag->smthMsgData = 0; mFuncMsgPending = 0; } @@ -323,7 +323,6 @@ namespace ipl { memset(mpBrowserStringBuffer, 0, 0x79); mpEventHandler = new APEvent(this); - mpAPEvent = mpEventHandler; mpPaneManager = new gui::PaneManager(mpEventHandler, mpMainLayout->getDrawInfo(), getSceneHeap(), NULL, false); mpPaneManager->setupScene(mpMainLayout); mpPaneManager->setAllBoundingBoxComponentTriggerTarget(false); @@ -745,7 +744,7 @@ namespace ipl { unk_0x74 = 0; unk_0x91C[3] = 0; resetFuncMsgQ(); - if (mpAPEvent->getEventType() != 'O') { + if (mpWiiSettingFlag->smthMsgData != 'O') { unk_0xB9C = 1; } } @@ -768,7 +767,7 @@ namespace ipl { case 6: if (System::getScene(0x1b) == NULL) { unk_0x91C[3] = 0; - if (mpAPEvent->getEventType() == 'O') { + if (mpWiiSettingFlag->smthMsgData == 'O') { if (!ncd::NCDSetting::getEnableFlag()) { System::getDialog()->callBtn2(System::getRegion() == 2 ? 0x174 : 0x170, 0x146, 0x25); @@ -817,7 +816,7 @@ namespace ipl { break; case 9: if (System::getDialog()->getLastResult() == 1) { - if (mpAPEvent->getEventType() == 'O') { + if (mpWiiSettingFlag->smthMsgData == 'O') { www::wiisetting::setFuncResult(5); resetFuncMsgQ(); } else { @@ -825,7 +824,7 @@ namespace ipl { } unk_0x74 = 0; } else if (System::getDialog()->getLastResult() == 2) { - if (mpAPEvent->getEventType() == 'O') { + if (mpWiiSettingFlag->smthMsgData == 'O') { if (unk_0xB9C == 0) { www::wiisetting::setFuncResult(2); } else if (www::wiisetting::getFuncResult() == 0) { @@ -861,7 +860,7 @@ namespace ipl { case 0xb: if (System::getDialog()->getLastResult() >= 0) { mProfileIDMode = 10; - mpAPEvent->setEventType(0x54); + mpWiiSettingFlag->smthMsgData = 0x54; unk_0x74 = 0; } break; @@ -894,7 +893,7 @@ namespace ipl { break; case 0xe: if (System::getDialog()->getLastResult() == 1) { - mpAPEvent->setEventType(0x55); + mpWiiSettingFlag->smthMsgData = 0x55; unk_0x74 = 0; } else if (System::getDialog()->getLastResult() == 2) { if (unk_0xB9C == 0) { @@ -947,7 +946,7 @@ namespace ipl { calcSetting(); } - switch (mpAPEvent->getEventType()) { + switch (mpWiiSettingFlag->smthMsgData) { case 1: resetFuncMsgQ(); waitStart(); @@ -956,7 +955,7 @@ namespace ipl { case 4: resetAP(); initAP(); - mpAPEvent->setEventType(2); + mpWiiSettingFlag->smthMsgData = 2; case 2: case 3: scanAP(); @@ -1010,24 +1009,25 @@ namespace ipl { if (action == 0x1d || calcSafeMode()) { if (!parental::Parental::checkFlags()) { www::wiisetting::setFuncResult(1); - if (mpAPEvent->getEventType() == 'N') { + if (mpWiiSettingFlag->smthMsgData == 'N') { unk_0x74 = 6; } } else { createChildScene(0x1b, this, NULL, reinterpret_cast(1)); unk_0x74 = 5; } - if (mpAPEvent->getEventType() == 0x1d || mpAPEvent->getEventType() == 'M') { + if (mpWiiSettingFlag->smthMsgData == 0x1d || + mpWiiSettingFlag->smthMsgData == 'M') { resetFuncMsgQ(); } else { - mpAPEvent->setEventType('O'); + mpWiiSettingFlag->smthMsgData = 'O'; } } break; case 0x1e: memset(mpMem2BrowserBuffer, 0, 0x800); memset(mpBrowserStringBuffer, 0, 0x79); - mpAPEvent->setEventType(0x23); + mpWiiSettingFlag->smthMsgData = 0x23; case '#': setUSBAP(); break; @@ -1119,7 +1119,7 @@ namespace ipl { break; case 'Y': mProfileIDMode = 2; - mpAPEvent->setEventType(0x54); + mpWiiSettingFlag->smthMsgData = 0x54; break; case '[': if (System::getHomeButtonMenu()->disable()) { @@ -1251,6 +1251,17 @@ namespace ipl { return FADER_SCN_CONTINUE; } + void Setting::initWiiSettingData() { + mpWiiSettingData = www::wiisetting::getWiiSettingData(); + mpWiiSettingFlag = www::wiisetting::getWiiSettingFlag(); + mpWiiSettingData->data[0x3c] = parental::Parental::getCountry(); + mpWiiSettingData->data[7] = 0x20 - (SCGetDisplayOffsetH() + 0x10); + mpWiiSettingData->data[0xb] = SCGetBtDpdSensibility(); + mpWiiSettingData->data[6] = SCGetAspectRatio(); + mpWiiSettingData->data[0x30] = SCGetLanguage(); + mpWiiSettingData->data[0x2d] = parental::Parental::checkRating(); + } + u16 Setting::getProfileID() { u16 profileID; if (mProfileIDMode >= 3) { -- 2.49.1 From 24591adedbe5431bb9232bbed88a11a082e8c62c Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 02:47:24 +0000 Subject: [PATCH 17/61] decompile setting input initialization --- include/scene/setting/iplSetting.h | 24 ++ src/scene/setting/iplSetting.cpp | 592 +++++++++++++++++++++++++++++ 2 files changed, 616 insertions(+) diff --git a/include/scene/setting/iplSetting.h b/include/scene/setting/iplSetting.h index 72fdfe04..fe3fd0d1 100644 --- a/include/scene/setting/iplSetting.h +++ b/include/scene/setting/iplSetting.h @@ -73,8 +73,32 @@ namespace ipl { void initHTMLText(); void initMessage(); void initKeyboard(const char* text); + int checkInputString(const wchar_t* text); + int checkIPString(const wchar_t* text); + void setDefaultBackString(); void calcKeyboard(); void calcSetting(); + void onTextInputOK(); + void setDisPos(); + void setNickName(); + void setSecurityKey(); + void setSSID(); + void setIP(); + void setDNS(); + void setProxy(); + void setBasic(); + void setMTU(); + void setParePass(); + void setPareRePass(); + void setPareJudgePass(); + void setSecA(); + void setReSecA(); + void setMasterKey(); + void adjustSecA(wchar_t* text); + char checkTextNum(const char* text); + bool checkSpace(); + void convertIP(char* destination, const u8* address); + void convertRevIP(u8* destination, const char* address); bool calcSafeMode(); void waitStart(); void waitFinish(); diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index cf1873d1..90b6fddf 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -7,10 +7,12 @@ #include "system/iplErrorHandler.h" #include "system/iplSystem.h" #include "utility/iplWpad.h" +#include "utility/iplCharacterCode.h" #include "sound/iplSound.h" #include "iplwww/www_wiisetting.h" #include "iplwww/www_surface.h" +#include "iplwww/www_trasition.h" #include #include @@ -22,6 +24,13 @@ #include #include +namespace ipl { + class SensitivityDrawing { + public: + static void draw(nand::File* file); + }; +} + namespace ipl { namespace keyboard { Manager::State& Manager::State::operator=(const Manager::State& other) { @@ -1251,6 +1260,82 @@ namespace ipl { return FADER_SCN_CONTINUE; } + void Setting::draw() { + if (!System::onDrawLayer(1)) { + return; + } + + if (!mBrowserCreated) { + utility::Graphics::setOrtho(0); + nw4r::ut::Rect background(-1000.0f, -1000.0f, 1000.0f, 1000.0f); + GXColor color = {0, 0, 0, 0xFF}; + utility::Graphics::drawPolygon(background, color); + return; + } + + ext_ead::www::SurfaceManager* surface = ext_ead::www::SurfaceManager::GetInstance(); + if (surface == NULL) { + return; + } + + ext_ead::www::BrowserThread* browser = surface->GetBrowserThread(); + if (browser == NULL || browser->GetTextureBuffer(0, NULL) == NULL) { + return; + } + + WWWRect* wideRect = NULL; + WWWRect* standardRect = NULL; + void* wideBuffer = browser->GetTextureBuffer(1, &wideRect); + void* standardBuffer = browser->GetTextureBuffer(0, &standardRect); + if (wideBuffer == NULL || standardBuffer == NULL) { + return; + } + + if (www::trasition::GetScrollState() != www::trasition::SCROLL_RESET) { + www::trasition::ResetScrollState(); + OSReport("changed %p %p\n", standardBuffer, wideBuffer); + ext_ead::www::Heap::reportLeaHeap(); + } + + nw4r::ut::Rect projection4x3; + nw4r::ut::Rect projection16x9; + System::getProjectionRect4x3(&projection4x3); + System::getProjectionRect16x9(&projection16x9); + + GXTexObj standardTexture; + GXTexObj wideTexture; + GXInitTexObj(&standardTexture, standardBuffer, standardRect->w, standardRect->h, GX_TF_RGBA8, GX_CLAMP, GX_CLAMP, GX_FALSE); + GXInitTexObj(&wideTexture, wideBuffer, wideRect->w, wideRect->h, GX_TF_RGBA8, GX_CLAMP, GX_CLAMP, GX_FALSE); + GXInitTexObjLOD(&standardTexture, GX_LINEAR, GX_LINEAR, 0.0f, 0.0f, 0.0f, GX_FALSE, GX_FALSE, GX_ANISO_1); + GXInitTexObjLOD(&wideTexture, GX_LINEAR, GX_LINEAR, 0.0f, 0.0f, 0.0f, GX_FALSE, GX_FALSE, GX_ANISO_1); + + utility::Graphics::setOrtho(0); + GXColor color = {0xFF, 0xFF, 0xFF, (u8)(mState * 0xFF / 20)}; + utility::Graphics::drawTexture(projection4x3, standardTexture, color, 1); + utility::Graphics::drawTexture(projection16x9, wideTexture, color, 1); + + if (mpWiiSettingData->data[0x12] == 0x1E && unk_0x92C > 3) { + SensitivityDrawing::draw(static_cast(mpBackgroundTPLFile)); + } + + mpChangeLayout->draw(); + mpWaitLayout->draw(); + if (mState == 0xC) { + unk_0xB9C = 1; + } + + if (mpWiiSettingFlag->smthMsgData >= 2 && mpWiiSettingFlag->smthMsgData <= 7) { + u32 left; + u32 top; + u32 width; + u32 height; + GXGetScissor(&left, &top, &width, &height); + GXSetScissor(0, System::getRenderModeObj()->efbHeight / 2 - 0xA4, System::getRenderModeObj()->fbWidth, 0x132); + mpWaitLayout->draw(); + GXSetScissor(left, top, width, height); + } + } + void Setting::initWiiSettingData() { mpWiiSettingData = www::wiisetting::getWiiSettingData(); mpWiiSettingFlag = www::wiisetting::getWiiSettingFlag(); @@ -1262,6 +1347,513 @@ namespace ipl { mpWiiSettingData->data[0x2d] = parental::Parental::checkRating(); } + void Setting::initHTMLText() { + OSReport("initHTMLText pageId:%d\n", mpWiiSettingData->data[0x12]); + memset(unk_0x938, 0, sizeof(unk_0x938)); + + switch (mpWiiSettingData->data[0x12]) { + case 2: + initNickName(); + break; + case 3: + initSecurityKey(); + break; + case 4: + initSSID(); + break; + case 5: + initIP(); + break; + case 6: + initDNS(); + break; + case 7: + initProxy(); + break; + case 8: + initBasic(); + break; + case 9: + initMTU(); + break; + case 10: + memset(&mpStringBuffer->parentalPass, 0, sizeof(mpStringBuffer->parentalPass)); + break; + case 11: + memset(&mpStringBuffer->parentalRePass, 0, sizeof(mpStringBuffer->parentalRePass)); + break; + case 12: + memset(&mpStringBuffer->parentalJudgePass, 0, sizeof(mpStringBuffer->parentalJudgePass)); + break; + case 13: + initSecA(); + break; + case 14: + memset(&mpStringBuffer->parentalReSecA, 0, sizeof(mpStringBuffer->parentalReSecA)); + break; + case 15: + memset(&mpStringBuffer->masterKey, 0, sizeof(mpStringBuffer->masterKey)); + break; + case 16: + memset(&mpStringBuffer->asterisks, 0, sizeof(mpStringBuffer->asterisks)); + break; + } + } + + void Setting::initMessage() { + OSReport("initMessage pageId:%d\n", mpWiiSettingData->data[0x12]); + mpWiiSettingData->data[0x12] = 0; + } + + void Setting::initKeyboard(const char* text) { + u8 formId = mpWiiSettingData->data[0x11]; + OSReport("initKeyboard formId:%d\n", formId); + memset(unk_0x938, 0, sizeof(unk_0x938)); + + int productArea = SCGetProductArea(); + int rowLimit = 0; + int stringLimit = 0; + keyboard::Manager::KeyboardType keyboardType = keyboard::Manager::LETTER; + + switch (formId) { + case 1: + stringLimit = 10; + rowLimit = 6; + break; + case 2: + if (ncd::NCDSetting::getPrivacyMode() == 1) { + stringLimit = 0x1A; + keyboardType = keyboard::Manager::NORMAL_WITHOUT_LINEFEED; + } else { + stringLimit = 0x40; + keyboardType = keyboard::Manager::NORMAL_WITHOUT_LINEFEED_WITH_SIGN; + } + rowLimit = 7; + break; + case 3: + case 12: + case 13: + stringLimit = 0x20; + keyboardType = keyboard::Manager::NORMAL_WITHOUT_LINEFEED; + rowLimit = 7; + break; + case 4: + case 5: + case 6: + case 7: + case 8: + stringLimit = 0xF; + rowLimit = 10; + break; + case 10: + stringLimit = 0xFF; + keyboardType = keyboard::Manager::NUMERIC_WITH_DOT; + rowLimit = 7; + break; + case 11: + case 20: + stringLimit = 5; + rowLimit = 3; + break; + case 14: + case 15: + case 16: + case 17: + stringLimit = 4; + rowLimit = 3; + break; + case 18: + case 19: + stringLimit = 0x20; + keyboardType = keyboard::Manager::NORMAL_WITHOUT_LINEFEED; + rowLimit = productArea == 11 || productArea == 6 ? 13 : 5; + break; + case 22: + stringLimit = 0x40; + keyboardType = keyboard::Manager::NORMAL_WITHOUT_LINEFEED_WITH_SIGN; + rowLimit = 7; + break; + } + + if (formId != 13 && formId != 2 && formId != 18 && formId != 19 && formId != 22) { + utility::CharacterCode::UTF8ToUTF16(reinterpret_cast(unk_0x938), text, 0x101); + } + + size_t textLength = wcslen(reinterpret_cast(unk_0x938)); + OSReport("キーボード: %d %d %d %d\n", rowLimit, stringLimit, keyboardType, textLength); + reinterpret_cast(unk_0x938)[stringLimit] = 0; + + int invalidInput = 0; + if (formId >= 4 && formId <= 8) { + invalidInput = checkIPString(reinterpret_cast(unk_0x938)); + } else if ((formId > 0 && formId < 4) || (formId >= 10 && formId <= 20) || formId == 22) { + invalidInput = checkInputString(reinterpret_cast(unk_0x938)); + } + + if (invalidInput != 0) { + memset(unk_0x938, 0, sizeof(unk_0x938)); + } + + keyboard::Manager* keyboardManager = System::getKeyboard(); + if (productArea == 11) { + keyboardManager->memoFrm()->setZiDictionary(keyboardManager->getZiSystemDic(), keyboardManager->getZiOemDic()); + } + + keyboard::Manager::KeyboardSetting setting; + setting.type = keyboardType; + setting.wcString = reinterpret_cast(unk_0x938); + setting.stringLimit = stringLimit; + setting.rowLimit = rowLimit; + keyboardManager->init(); + keyboardManager->start(0, setting); + + if (invalidInput != 0) { + setDefaultBackString(); + } else { + reinterpret_cast(keyboardManager->memoFrm())->setString(reinterpret_cast(unk_0x938)); + } + } + + void Setting::calcKeyboard() { + u8 formId = mpWiiSettingData->data[0x11]; + char* formText = NULL; + switch (formId) { + case 1: + formText = mpStringBuffer->nickname; + break; + case 2: + case 22: + formText = mpStringBuffer->asterisks; + break; + case 3: + formText = mpStringBuffer->securityKey; + break; + case 4: + formText = mpStringBuffer->ip.addr; + break; + case 5: + formText = mpStringBuffer->ip.netmask; + break; + case 6: + formText = mpStringBuffer->ip.gateway; + break; + case 7: + formText = mpStringBuffer->dns1; + break; + case 8: + formText = mpStringBuffer->dns2; + break; + case 10: + formText = mpStringBuffer->proxy.server; + break; + case 11: + formText = mpStringBuffer->proxy.port; + break; + case 12: + formText = mpStringBuffer->proxyBasic.uname; + break; + case 13: + formText = mpStringBuffer->proxyBasic.pass; + break; + case 14: + formText = mpStringBuffer->adjMtu; + break; + case 15: + formText = mpStringBuffer->parentalPass; + break; + case 16: + formText = mpStringBuffer->parentalRePass; + break; + case 17: + formText = mpStringBuffer->parentalJudgePass; + break; + case 18: + formText = mpStringBuffer->parentalSecA; + break; + case 19: + formText = mpStringBuffer->parentalReSecA; + break; + case 20: + formText = mpStringBuffer->masterKey; + break; + } + + ext_ead::www::BrowserThread* browser = ext_ead::www::SurfaceManager::GetInstance()->GetBrowserThread(); + if (mKeyboardState.iplType == keyboard::Manager::STATE_DISAPPEARING) { + if (!mKeyboardState.pressOK) { + browser->CommitIme(mpBrowserData, formText); + } else { + onTextInputOK(); + formId = mpWiiSettingData->data[0x11]; + OSReport("formID:%d %s\n", formId, formText); + if (strlen(formText) == 0) { + formText[0] = 0; + browser->CommitIme(mpBrowserData, formText); + memset(mpStringBuffer->asterisks, 0, sizeof(mpStringBuffer->asterisks)); + } else if (formId == 2 || formId == 22) { + memcpy(mpStringBuffer->asterisks, mpStringBuffer->securityKey, sizeof(mpStringBuffer->securityKey)); + mpStringBuffer->asterisks[0x41] = 0; + u32 index = 0; + while (mpStringBuffer->asterisks[index] != 0) { + mpStringBuffer->asterisks[index++] = '*'; + } + if (index > 0x20) { + mpStringBuffer->asterisks[0x20] = '\n'; + mpStringBuffer->asterisks[index] = '*'; + } + browser->CommitIme(mpBrowserData, mpStringBuffer->asterisks); + } else { + browser->CommitIme(mpBrowserData, formText); + } + } + + mpWiiSettingData->data[0x11] = 0; + browser->DisposeImeData(mpBrowserData); + } else if (mKeyboardState.iplType < keyboard::Manager::STATE_VISIBLE) { + if (mKeyboardState.iplType < keyboard::Manager::STATE_APPEARING && + formId != 0 && formId != 9 && formId != 21 && formId <= 22) { + if (System::getKeyboard()->memoMgr()->isVacancy()) { + reinterpret_cast(System::getKeyboard()->memoFrm())->setString(L""); + } else { + setDefaultBackString(); + } + } + } else if (mKeyboardState.iplType < keyboard::Manager::STATE_HIDDEN_AFTER_DISAPPEAR) { + reinterpret_cast(System::getKeyboard()->memoFrm())->setString(L""); + unk_0x74 = 0; + } + + mKeyboardState = *System::getKeyboard()->getState(); + } + + void Setting::calcSetting() { + u8 settingId = mpWiiSettingData->data[0x36]; + OSReport("setstring:%d\n", settingId); + switch (settingId) { + case 1: + setDisPos(); + break; + case 2: + setNickName(); + break; + case 3: + setSecurityKey(); + break; + case 4: + setSSID(); + break; + case 5: + setIP(); + break; + case 6: + setDNS(); + break; + case 7: + setProxy(); + break; + case 8: + setBasic(); + break; + case 9: + setMTU(); + break; + case 10: + setParePass(); + break; + case 11: + setPareRePass(); + break; + case 12: + setPareJudgePass(); + break; + case 13: + setSecA(); + break; + case 14: + setReSecA(); + break; + case 15: + setMasterKey(); + break; + } + mpWiiSettingData->data[0x36] = 0; + } + + void Setting::onTextInputOK() { + u8 formId = mpWiiSettingData->data[0x11]; + OSReport("Keyboard Confirm:%d\n", formId); + wcslen(mKeyboardState.wcString); + + memset(unk_0x938, 0, sizeof(unk_0x938)); + u8 convertedText[0x302]; + memset(convertedText, 0, sizeof(convertedText)); + memcpy(unk_0x938, mKeyboardState.wcString, sizeof(unk_0x938)); + + if (formId == 2 || formId == 22) { + utility::CharacterCode::UTF16ToANSI(convertedText, reinterpret_cast(unk_0x938), 0x100); + size_t textLength = wcslen(reinterpret_cast(unk_0x938)); + memset(convertedText + textLength, 0, 0x100 - textLength); + memcpy(mpStringBuffer->securityKey, convertedText, sizeof(mpStringBuffer->securityKey)); + return; + } + + if (formId == 18 || formId == 19) { + adjustSecA(reinterpret_cast(unk_0x938)); + } + utility::CharacterCode::UTF16ToUTF8(reinterpret_cast(convertedText), + reinterpret_cast(unk_0x938), 0x301); + + switch (formId) { + case 1: + memcpy(mpStringBuffer->nickname, convertedText, sizeof(mpStringBuffer->nickname)); + break; + case 3: + memcpy(mpStringBuffer->securityKey, convertedText, sizeof(mpStringBuffer->securityKey)); + break; + case 4: + memcpy(mpStringBuffer->ip.addr, convertedText, sizeof(mpStringBuffer->ip.addr)); + break; + case 5: + memcpy(mpStringBuffer->ip.netmask, convertedText, sizeof(mpStringBuffer->ip.netmask)); + break; + case 6: + memcpy(mpStringBuffer->ip.gateway, convertedText, sizeof(mpStringBuffer->ip.gateway)); + break; + case 7: + memcpy(mpStringBuffer->dns1, convertedText, sizeof(mpStringBuffer->dns1)); + break; + case 8: + memcpy(mpStringBuffer->dns2, convertedText, sizeof(mpStringBuffer->dns2)); + break; + case 10: + memcpy(mpStringBuffer->proxy.server, convertedText, sizeof(mpStringBuffer->proxy.server)); + break; + case 11: + memcpy(mpStringBuffer->proxy.port, convertedText, sizeof(mpStringBuffer->proxy.port)); + break; + case 12: + memcpy(mpStringBuffer->proxyBasic.uname, convertedText, sizeof(mpStringBuffer->proxyBasic.uname)); + break; + case 13: + memcpy(mpStringBuffer->proxyBasic.pass, convertedText, sizeof(mpStringBuffer->proxyBasic.pass)); + break; + case 14: + memcpy(mpStringBuffer->adjMtu, convertedText, sizeof(mpStringBuffer->adjMtu)); + break; + case 15: + memcpy(mpStringBuffer->parentalPass, convertedText, sizeof(mpStringBuffer->parentalPass)); + break; + case 16: + memcpy(mpStringBuffer->parentalRePass, convertedText, sizeof(mpStringBuffer->parentalRePass)); + break; + case 17: + memcpy(mpStringBuffer->parentalJudgePass, convertedText, sizeof(mpStringBuffer->parentalJudgePass)); + break; + case 18: + memcpy(mpStringBuffer->parentalSecA, convertedText, sizeof(mpStringBuffer->parentalSecA)); + break; + case 19: + memcpy(mpStringBuffer->parentalReSecA, convertedText, sizeof(mpStringBuffer->parentalReSecA)); + break; + case 20: + memcpy(mpStringBuffer->masterKey, convertedText, sizeof(mpStringBuffer->masterKey)); + break; + } + } + + void Setting::initNickName() { + BOOL hasNickname = SCGetOwnerNickName(reinterpret_cast(mSettingData)); + OSReport("SCGetOwnerNickName:%d\n", hasNickname); + if (hasNickname) { + SCOwnerNickname* ownerNickname = reinterpret_cast(mSettingData); + memcpy(unk_0x938, ownerNickname->name, ownerNickname->length * sizeof(wchar_t)); + } + memset(mpStringBuffer->nickname, 0, sizeof(mpStringBuffer->nickname)); + utility::CharacterCode::UTF16ToUTF8(mpStringBuffer->nickname, + reinterpret_cast(unk_0x938), + sizeof(mpStringBuffer->nickname)); + } + + void Setting::initSecurityKey() { + memset(mpStringBuffer->securityKey, 0, sizeof(mpStringBuffer->securityKey)); + u16 privacyMode = ncd::NCDSetting::getNCDPrivacyMode(); + size_t keyLength = 0; + if (privacyMode == 2) { + keyLength = 13; + } else if (privacyMode < 2) { + if (privacyMode == 1) { + keyLength = 5; + } + } else if (privacyMode > 3 && privacyMode < 7) { + keyLength = 64; + } + if (keyLength != 0) { + memcpy(mpStringBuffer->securityKey, ncd::NCDSetting::getPrivacy(), keyLength); + } + OSReport("privacy : %s\n", ncd::NCDSetting::getPrivacy()); + } + + void Setting::initSSID() { + memset(mpStringBuffer->ssid, 0, sizeof(mpStringBuffer->ssid)); + NCDApConfig* ssid = ncd::NCDSetting::getSSID(); + utility::CharacterCode::ANSIToUTF8(mpStringBuffer->ssid, ssid->ssid, ssid->ssidLength); + OSReport("initHTMLText initString:%s length:%d\n", ssid->ssid, ssid->ssidLength); + } + + void Setting::initIP() { + memset(mpStringBuffer->ip.addr, 0, sizeof(mpStringBuffer->ip.addr)); + memset(mpStringBuffer->ip.netmask, 0, sizeof(mpStringBuffer->ip.netmask)); + memset(mpStringBuffer->ip.gateway, 0, sizeof(mpStringBuffer->ip.gateway)); + NCDIpProfile* ip = ncd::NCDSetting::getIP(); + convertIP(mpStringBuffer->ip.addr, ip->addr); + convertIP(mpStringBuffer->ip.netmask, ip->netmask); + convertIP(mpStringBuffer->ip.gateway, ip->gateway); + } + + void Setting::initDNS() { + memset(mpStringBuffer->dns1, 0, sizeof(mpStringBuffer->dns1)); + memset(mpStringBuffer->dns2, 0, sizeof(mpStringBuffer->dns2)); + NCDIpProfile* ip = ncd::NCDSetting::getIP(); + convertIP(mpStringBuffer->dns1, ip->dns1); + convertIP(mpStringBuffer->dns2, ip->dns2); + } + + void Setting::initProxy() { + memset(mpStringBuffer->proxy.server, 0, sizeof(mpStringBuffer->proxy.server)); + memset(mpStringBuffer->proxy.port, 0, sizeof(mpStringBuffer->proxy.port)); + NCDProxyProfile* proxy = ncd::NCDSetting::getProxy(); + memcpy(mpStringBuffer->proxy.server, proxy->http.server, sizeof(proxy->http.server)); + sprintf(mpStringBuffer->proxy.port, "%d", proxy->http.port); + } + + void Setting::initBasic() { + memset(mpStringBuffer->proxyBasic.uname, 0, sizeof(mpStringBuffer->proxyBasic.uname)); + memset(mpStringBuffer->proxyBasic.pass, 0, sizeof(mpStringBuffer->proxyBasic.pass)); + NCDProxyProfile* proxy = ncd::NCDSetting::getProxy(); + memcpy(mpStringBuffer->proxyBasic.uname, proxy->http.username, sizeof(proxy->http.username)); + memcpy(mpStringBuffer->proxyBasic.pass, proxy->http.password, sizeof(proxy->http.password)); + } + + void Setting::initMTU() { + memset(mpStringBuffer->adjMtu, 0, sizeof(mpStringBuffer->adjMtu)); + char mtuText[20]; + sprintf(mtuText, "%d", ncd::NCDSetting::getMTU()); + utility::CharacterCode::ANSIToUTF8(mpStringBuffer->adjMtu, + reinterpret_cast(mtuText)); + } + + void Setting::initSecA() { + memset(mpStringBuffer->parentalSecA, 0, sizeof(mpStringBuffer->parentalSecA)); + wchar_t answer[42]; + memset(answer, 0, 0x44); + wcsncpy(answer, parental::Parental::getSecA(), 0x20); + memset(unk_0x938, 0, sizeof(unk_0x938)); + wcsncpy(reinterpret_cast(unk_0x938), answer, 0x20); + adjustSecA(answer); + utility::CharacterCode::UTF16ToUTF8(mpStringBuffer->parentalSecA, answer, + sizeof(mpStringBuffer->parentalSecA)); + } + u16 Setting::getProfileID() { u16 profileID; if (mProfileIDMode >= 3) { -- 2.49.1 From 157cfcb225ae9b7c80832ee1b06f66e3bc63f56d Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 03:08:10 +0000 Subject: [PATCH 18/61] decompile setting access point flow --- include/scene/setting/iplSetting.h | 36 +- src/scene/setting/iplSetting.cpp | 719 +++++++++++++++++++++++++++-- 2 files changed, 725 insertions(+), 30 deletions(-) diff --git a/include/scene/setting/iplSetting.h b/include/scene/setting/iplSetting.h index fe3fd0d1..ddc4d664 100644 --- a/include/scene/setting/iplSetting.h +++ b/include/scene/setting/iplSetting.h @@ -12,6 +12,9 @@ #include "system/iplKeyboard.h" #include "system/iplNand.h" #include "utility/iplThread.h" +extern "C" { +#include +} #endif namespace ipl { @@ -40,6 +43,12 @@ namespace ipl { u8 unknown[0x14]; int state; }; + + struct SettingAPScanList { + u8 unknown[0x14]; + u16 count; + u8 entries[0x802]; + }; #endif FADER_SCENE_CLASS(Setting) { @@ -73,7 +82,7 @@ namespace ipl { void initHTMLText(); void initMessage(); void initKeyboard(const char* text); - int checkInputString(const wchar_t* text); + bool checkInputString(const wchar_t* text); int checkIPString(const wchar_t* text); void setDefaultBackString(); void calcKeyboard(); @@ -95,10 +104,31 @@ namespace ipl { void setReSecA(); void setMasterKey(); void adjustSecA(wchar_t* text); - char checkTextNum(const char* text); + void reAdjustSecA(); + u8 checkTextNum(const char* text); bool checkSpace(); void convertIP(char* destination, const u8* address); void convertRevIP(u8* destination, const char* address); + void initScroll(); + void updateScroll(); + void setAPDraw(); + int getRadioLevel(const WDBssDesc_* descriptor); + void setUseEULA_Init_(); + void setUseEULA_Cancel_(); + void setUseEULA_Start_(); + void setUseEULA_WaitStopMotor_(); + bool validateEULA_(); + void setUpdate_Init_(); + void setUpdate_WaitAcceptDialog_(); + void setUpdate_ConnectTestStart_(); + void setUpdate_ConnectTestCreateWait_(); + void setUpdate_ConnectTestRun_(); + void setUpdate_ConnectTestFailed_(); + void setUpdate_SuccessDialog_(); + void setUpdate_NoUpdateDialog_(); + void setUpdate_EULAInit_(); + void setUpdate_Reboot_(); + void makeErrorMessage(); bool calcSafeMode(); void waitStart(); void waitFinish(); @@ -179,7 +209,7 @@ namespace ipl { utility::ut_thread* mpAOSSThread; utility::ut_thread* mpRakuRakuThread; APScanThread* mpAPScanThread; - u8 unk_0xEC[0x818]; + SettingAPScanList mAPScanList; void* mpMem1BrowserBuffer; u32 unk_0x908; void* mpMem2BrowserBuffer; diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 90b6fddf..3b25758b 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -15,6 +15,7 @@ #include "iplwww/www_trasition.h" #include +#include #include #include #include @@ -24,6 +25,8 @@ #include #include +extern "C" void __VISetAdjustingValues(s32 horizontal, s32 vertical); + namespace ipl { class SensitivityDrawing { public: @@ -49,6 +52,17 @@ namespace ipl { class APScanThread { public: APScanThread(); + void setResultData(unsigned short* buffer); + virtual ~APScanThread(); + virtual void* Run(); + virtual void Create(void* stack, u32 stackSize, int priority, bool startThread); + virtual void Resume(); + virtual void Suspend(); + virtual BOOL WaitForThreadExit(); + virtual bool IsThreadTerminated(); + virtual bool IsThreadSuspended(); + virtual bool SetThreadPriority(int priority); + virtual void unk_0x2C(); }; class USBAPThread { @@ -1762,9 +1776,9 @@ namespace ipl { } void Setting::initNickName() { - BOOL hasNickname = SCGetOwnerNickName(reinterpret_cast(mSettingData)); - OSReport("SCGetOwnerNickName:%d\n", hasNickname); - if (hasNickname) { + bool nicknameExists = SCGetOwnerNickName(reinterpret_cast(mSettingData)) != 0; + OSReport("SCGetOwnerNickName:%d\n", nicknameExists); + if (nicknameExists) { SCOwnerNickname* ownerNickname = reinterpret_cast(mSettingData); memcpy(unk_0x938, ownerNickname->name, ownerNickname->length * sizeof(wchar_t)); } @@ -1854,44 +1868,695 @@ namespace ipl { sizeof(mpStringBuffer->parentalSecA)); } - u16 Setting::getProfileID() { - u16 profileID; - if (mProfileIDMode >= 3) { - profileID = ncd::NCDSetting::getUseProfileID(); - ncd::NCDSetting::initSetID(profileID & 0xFF); - if ((u8)profileID == 3) { - profileID = 0; - } - } else { - profileID = ncd::NCDSetting::getID(); - } - return profileID; + void Setting::initVersion() { + const char* versionSuffix[12] = {"J", "U", "E", "", "", "J", "K", "", "", "", "", "C"}; + u32 versionData[24] = { + 0x00010008, 0x48414B4A, 0x00010008, 0x48414B45, 0x00010008, 0x48414B50, + 0, 0, 0, 0, 0, 0, 0x00010008, 0x48414B4A, 0x00010008, 0x48414B4B, + 0, 0, 0, 0, 0, 0, 0x00010008, 0x48414B43, + }; + u32 region = System::getRegion(); + sprintf(mpStringBuffer->version, "Ver. %d.%d%s", 4, 3, versionSuffix[region]); + mUpdateTitleId = *reinterpret_cast(&versionData[region * 2]); } - int Setting::getUpdateTiming() { - return mUpdateTiming; + void Setting::setDisPos() { + int displayPosition = 0x10 - mpWiiSettingData->data[7]; + __VISetAdjustingValues(static_cast(displayPosition), 0); + } + + void Setting::setNickName() { + SCOwnerNickname* nickname = reinterpret_cast(mSettingData); + nickname->length = wcslen(reinterpret_cast(unk_0x938)); + if (checkTextNum(mpStringBuffer->nickname) == 3) { + memset(nickname, 0, sizeof(*nickname)); + memcpy(nickname->name, unk_0x938, nickname->length * sizeof(wchar_t)); + BOOL written = SCSetOwnerNickName(nickname); + OSReport("nicknameFlag:1 %d %s\n", written, nickname->name); + } + } + + void Setting::setSecurityKey() { + int keyLength = ncd::NCDSetting::checkWEPKey(mpStringBuffer->securityKey); + if (keyLength < 0) { + System::getDialog()->callBtn0(0x1be, 0xb4, false); + unk_0x74 = 2; + www::wiisetting::setFuncResult(4); + } else { + www::wiisetting::setFuncResult(3); + ncd::NCDSetting::setPrivacy(reinterpret_cast(mpStringBuffer->securityKey), keyLength); + OSReport("securityFlag:1 %s\n", mpStringBuffer->securityKey); + } + } + + void Setting::setSSID() { + u8 ssid[0x61]; + memset(ssid, 0, sizeof(ssid)); + utility::CharacterCode::UTF8ToANSI(ssid, mpStringBuffer->ssid); + ncd::NCDSetting::setSSID(ssid); + } + + void Setting::setIP() { + NCDIpProfile ip; + memset(&ip, 0, sizeof(ip)); + convertRevIP(ip.addr, mpStringBuffer->ip.addr); + convertRevIP(ip.netmask, mpStringBuffer->ip.netmask); + convertRevIP(ip.gateway, mpStringBuffer->ip.gateway); + ncd::NCDSetting::setIP(&ip); + } + + void Setting::setDNS() { + NCDIpProfile ip; + memset(&ip, 0, sizeof(ip)); + convertRevIP(ip.dns1, mpStringBuffer->dns1); + convertRevIP(ip.dns2, mpStringBuffer->dns2); + ncd::NCDSetting::setDNS(&ip); + } + + void Setting::setProxy() { + NCDProxyServerProfile proxy; + memset(&proxy, 0, sizeof(proxy)); + wchar_t portText[6]; + u32 port; + memset(portText, 0, sizeof(portText)); + utility::CharacterCode::UTF8ToUTF16(portText, mpStringBuffer->proxy.port, 6); + utility::CharacterCode::UTF16ToU32(&port, portText); + proxy.port = port; + if (proxy.port == 0) { + www::wiisetting::setFuncResult(4); + System::getDialog()->callBtn0(0x1be, 0xb4, false); + unk_0x74 = 2; + } else { + int valid = ncd::NCDSetting::checkProxy(mpStringBuffer->proxy.server); + if (valid == 0) { + www::wiisetting::setFuncResult(4); + System::getDialog()->callBtn0(0x1be, 0xb4, false); + unk_0x74 = 2; + } else { + www::wiisetting::setFuncResult(3); + utility::CharacterCode::UTF8ToANSI(reinterpret_cast(proxy.server), + mpStringBuffer->proxy.server); + ncd::NCDSetting::setProxy(&proxy); + } + } + } + + void Setting::setBasic() { + int validUsername = ncd::NCDSetting::checkProxyBasic(mpStringBuffer->proxyBasic.uname); + int validPassword = validUsername == 0 + ? 0 + : ncd::NCDSetting::checkProxyBasic(mpStringBuffer->proxyBasic.pass); + if (validPassword == 0) { + www::wiisetting::setFuncResult(4); + System::getDialog()->callBtn0(0x1be, 0xb4, false); + unk_0x74 = 2; + } else { + NCDProxyServerProfile proxy; + memset(&proxy, 0, sizeof(proxy)); + www::wiisetting::setFuncResult(3); + utility::CharacterCode::UTF8ToANSI(reinterpret_cast(proxy.username), + mpStringBuffer->proxyBasic.uname); + utility::CharacterCode::UTF8ToANSI(reinterpret_cast(proxy.password), + mpStringBuffer->proxyBasic.pass); + ncd::NCDSetting::setBasic(&proxy); + } + } + + void Setting::setMTU() { + wchar_t mtuText[6]; + u32 mtu; + memset(mtuText, 0, sizeof(mtuText)); + utility::CharacterCode::UTF8ToUTF16(mtuText, mpStringBuffer->adjMtu, 6); + utility::CharacterCode::UTF16ToU32(&mtu, mtuText); + mtu &= 0xffff; + if (mtu < 0x240 || mtu > 0x5dc) { + mtu = 0; + } + ncd::NCDSetting::setMTU(mtu); + mpWiiSettingData->data[0x36] = 0; + } + + void Setting::setParePass() { + char password[5]; + memset(password, 0, 5); + utility::CharacterCode::UTF8ToANSI(reinterpret_cast(password), mpStringBuffer->parentalPass); + if (checkTextNum(password) == 3) { + parental::Parental::setPass(password); + } + memset(mpStringBuffer->parentalPass, 0, 5); + } + + void Setting::setPareRePass() { + char password[16]; + u8 result = 2; + memset(password, 0, 5); + utility::CharacterCode::UTF8ToANSI(reinterpret_cast(password), mpStringBuffer->parentalRePass); + if (checkTextNum(password) == 3 && parental::Parental::checkPass(password)) { + result = 1; + } + www::wiisetting::setFuncResult(result); + memset(mpStringBuffer->parentalRePass, 0, 5); + } + + void Setting::setPareJudgePass() { + char password[16]; + u8 result = 2; + memset(password, 0, 5); + utility::CharacterCode::UTF8ToANSI(reinterpret_cast(password), mpStringBuffer->parentalJudgePass); + if (checkTextNum(password) == 3 && parental::Parental::judgePass(password)) { + result = 1; + } + www::wiisetting::setFuncResult(result); + memset(mpStringBuffer->parentalJudgePass, 0, 5); + } + + void Setting::setSecA() { + memset(unk_0x938, 0, sizeof(unk_0x938)); + utility::CharacterCode::UTF8ToUTF16(reinterpret_cast(unk_0x938), + mpStringBuffer->parentalSecA, 0x44); + reAdjustSecA(); + if (checkTextNum(NULL) == 3) { + parental::Parental::setSecA(reinterpret_cast(unk_0x938)); + } + memset(unk_0x938, 0, sizeof(unk_0x938)); + } + + void Setting::setReSecA() { + u8 result = 2; + memset(unk_0x938, 0, sizeof(unk_0x938)); + utility::CharacterCode::UTF8ToUTF16(reinterpret_cast(unk_0x938), + mpStringBuffer->parentalReSecA, 0x44); + reAdjustSecA(); + if (checkTextNum(NULL) == 3 && parental::Parental::judgeSecA(reinterpret_cast(unk_0x938))) { + result = 1; + } + www::wiisetting::setFuncResult(result); + memset(unk_0x938, 0, sizeof(unk_0x938)); + } + + void Setting::setMasterKey() { + char masterKey[16]; + u8 result = 2; + memset(masterKey, 0, 6); + if (checkTextNum(mpStringBuffer->masterKey) == 3) { + utility::CharacterCode::UTF8ToANSI(reinterpret_cast(masterKey), mpStringBuffer->masterKey); + if (parental::Parental::judgeMaster(masterKey)) { + result = 1; + } + www::wiisetting::setFuncResult(result); + } + memset(mpStringBuffer->masterKey, 0, 6); + } + + u8 Setting::checkTextNum(const char* text) { + u8 formId = mpWiiSettingData->data[0x36]; + u32 message = 0; + u8 result = 4; + if (formId < 13) { + if (formId == 2) { + size_t length = wcslen(reinterpret_cast(unk_0x938)); + if (length == 0) { + message = 0x1c0; + } else if (checkSpace()) { + result = 3; + } else { + message = 0x1c1; + } + } else if (formId > 9) { + if (strlen(text) == 4) { + result = 3; + } + message = 0x1ba; + } + } else if (formId == 15) { + if (strlen(text) == 5) { + result = 3; + } + message = 0x1bc; + } else if (formId <= 14) { + u32 region = System::getRegion(); + u32 minimum = 6; + if (region == 6) { + minimum = 2; + } else if (region == 0 || region == 11) { + minimum = 3; + } + size_t length = wcslen(reinterpret_cast(unk_0x938)); + if (length < minimum) { + message = 0x1bb; + } else if (checkSpace()) { + result = 3; + } else { + message = 0x1c1; + } + } + www::wiisetting::setFuncResult(result); + if (result == 4) { + System::getDialog()->callBtn0(message, 0xb4, false); + unk_0x74 = 2; + } + return result; + } + + bool Setting::checkSpace() { + const wchar_t* text = reinterpret_cast(unk_0x938); + while (*text != 0) { + if (*text != L' ' && *text != 0x3000) { + return true; + } + ++text; + } + return false; + } + + void Setting::convertIP(char* destination, const u8* address) { + char ascii[20]; + sprintf(ascii, "%03d.%03d.%03d.%03d", address[0], address[1], address[2], address[3]); + utility::CharacterCode::ANSIToUTF8(destination, reinterpret_cast(ascii)); + } + + void Setting::convertRevIP(u8* destination, const char* address) { + char ascii[20]; + memset(ascii, 0, sizeof(ascii)); + utility::CharacterCode::UTF8ToANSI(reinterpret_cast(ascii), address); + char* component = ascii; + u32 count = 0; + for (char* current = ascii;; ++current) { + if (*current == '.' || *current == 0) { + bool finished = *current == 0; + *current = 0; + u32 value = atoi(component); + if (value > 0xff) { + value = 0xff; + } + destination[count++] = value; + if (finished || count == 4) { + break; + } + component = current + 1; + } + } + } + + void Setting::adjustSecA(wchar_t* text) { + bool containsWideCharacter = false; + for (u32 i = 0; text[i] != 0; ++i) { + if (text[i] > 0x7f) { + containsWideCharacter = true; + break; + } + } + if (containsWideCharacter && wcslen(reinterpret_cast(unk_0x938)) > 0x10) { + char secondLine[0x34]; + memcpy(secondLine, reinterpret_cast(text) + 0x20, 0x22); + memcpy(reinterpret_cast(text) + 0x22, secondLine, 0x22); + text[0x10] = L'\n'; + } + } + + void Setting::reAdjustSecA() { + wchar_t* text = reinterpret_cast(unk_0x938); + bool containsWideCharacter = false; + for (u32 i = 0; text[i] != 0; ++i) { + if (text[i] > 0x7f) { + containsWideCharacter = true; + break; + } + } + if (containsWideCharacter && wcslen(text) > 0x10) { + char secondLine[0x34]; + memcpy(secondLine, reinterpret_cast(text) + 0x22, 0x22); + memcpy(reinterpret_cast(text) + 0x20, secondLine, 0x22); + } + } + + void Setting::setDefaultBackString() { + switch (mpWiiSettingData->data[0x11]) { + case 1: + reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x15c)); + break; + case 2: + reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x153)); + break; + case 3: + reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x152)); + break; + case 4: + reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x14d)); + break; + case 5: + reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x150)); + break; + case 6: + reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x151)); + break; + case 7: + reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x14e)); + break; + case 8: + reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x14f)); + break; + case 10: + reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x154)); + break; + case 11: + reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x155)); + break; + case 12: + reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x156)); + break; + case 13: + reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x157)); + break; + case 14: + reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x158)); + break; + case 15: + case 16: + case 17: + reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x159)); + break; + case 18: + case 19: + reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x15a)); + break; + case 20: + reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x15b)); + break; + case 22: + reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x153)); + break; + } + } + + bool Setting::checkInputString(const wchar_t* text) { + return *text == 0; + } + + int Setting::checkIPString(const wchar_t* text) { + wchar_t zeroAddress[16] = L"000.000.000.000"; + return memcmp(text, zeroAddress, sizeof(zeroAddress)) == 0 || checkInputString(text); + } + + bool Setting::calcSafeMode() { + if (System::getNwc24Manager() != NULL) { + return true; + } + if (unk_0x94 == 1) { + if (System::getDialog()->getLastResult() >= 0) { + unk_0xB9C = 1; + unk_0x74 = 0; + unk_0x94 = 0; + } + } else if (unk_0x94 == 0) { + resetFuncMsgQ(); + System::getDialog()->callBtn1(0x21, 0x2e); + www::wiisetting::setFuncResult(2); + unk_0x74 = 0x11; + unk_0x94 = 1; + } + return false; + } + + void Setting::initAP() { + unk_0x78 = 1; + unk_0x914 = 0; + unk_0x918 = -1; + } + + void Setting::resetAP() { + mpChangeLayout->getAnim(0x15)->initFrame(); + mpChangeLayout->getAnim(0x15)->restart(); + if (unk_0x914 != 0) { + mpChangeLayout->getAnim(2)->initFrame(); + mpChangeLayout->getAnim(2)->restart(); + } + if (mAPScanList.count != unk_0x914 + 4) { + mpChangeLayout->getAnim(3)->initFrame(); + mpChangeLayout->getAnim(3)->restart(); + } + for (int animation = 0x10; animation < 0x14; ++animation) { + mpChangeLayout->getAnim(animation)->initFrame(); + mpChangeLayout->getAnim(animation)->restart(); + } + initAP(); + unk_0x918 = 0x15; + mpWiiSettingFlag->smthMsgData = 3; + unk_0x78 = 9; + } + + void Setting::redrawAP() { + unk_0x78 = 4; + unk_0x914 = 0; + unk_0x918 = -1; + mpWiiSettingFlag->smthMsgData = 3; + mpChangeLayout->getAnim(0x14)->initFrame(); + for (int animation = 0x10; animation < 0x14; ++animation) { + mpChangeLayout->getAnim(animation)->initFrame(); + mpChangeLayout->getAnim(animation)->restart(); + } + mpChangeLayout->calc(); + unk_0x91C[2] = 0; + } + + void Setting::scanAP() { + switch (unk_0x78) { + case 1: + memset(&mAPScanList.count, 0, 0x800); + mpAPScanThread->setResultData(reinterpret_cast(&mAPScanList.count)); + memset(mpMem1BrowserBuffer, 0, 0x1000); + mpAPScanThread->Create(mpMem1BrowserBuffer, 0x1000, 0x12, true); + unk_0x78 = 2; + unk_0x91C[2] = 0; + break; + case 2: + if (unk_0x91C[2] == 1) { + waitStart(); + } + if (mpAPScanThread->IsThreadTerminated()) { + mpAPScanThread->WaitForThreadExit(); + if (mAPScanList.count == 0) { + www::wiisetting::setFuncResult(2); + initAP(); + mpChangeLayout->getAnim(0x14)->initAnmFrame(); + mpChangeLayout->getAnim(0)->initAnmFrame(); + mpChangeLayout->getAnim(1)->initAnmFrame(); + } else { + www::wiisetting::setFuncResult(1); + setAPDraw(); + unk_0x78 = 3; + } + resetFuncMsgQ(); + unk_0xB9C = 0; + waitFinish(); + } + break; + case 3: + if (mpWiiSettingFlag->smthMsgData == 3) { + unk_0x78 = 4; + unk_0x91C[2] = 0; + } + break; + case 4: + initScroll(); + setAPDraw(); + mpPaneManager->update(); + break; + case 5: + mpPaneManager->update(); + break; + case 6: + unk_0xB9C = 1; + if (!mpChangeLayout->getAnim(unk_0x918)->isPlaying()) { + unk_0x78 = 5; + setAPDraw(); + mpChangeLayout->getAnim(unk_0x91C[0] == 0 ? 0xb : 0xa)->initAnmFrame(); + if (unk_0x914 == 0) { + mpChangeLayout->FindPaneByName(sSettingAPNumberNames[0])->SetVisible(false); + } else if (unk_0x914 == 1) { + mpChangeLayout->FindPaneByName(sSettingAPNumberNames[0])->SetVisible(true); + } + if (mAPScanList.count == unk_0x914 + 4) { + mpChangeLayout->FindPaneByName(sSettingAPNumberNames[1])->SetVisible(false); + } else if (mAPScanList.count == unk_0x914 + 5) { + mpChangeLayout->FindPaneByName(sSettingAPNumberNames[1])->SetVisible(true); + } + mpChangeLayout->FindPaneByName(sSettingAPTextNames[0])->SetVisible(true); + mpChangeLayout->FindPaneByName(sSettingAPTextNames[1])->SetVisible(true); + } + break; + case 7: + unk_0xB9C = 1; + if (!mpChangeLayout->getAnim(unk_0x918)->isPlaying()) { + updateScroll(); + unk_0x78 = 6; + } + break; + case 8: + resetAP(); + unk_0x91C[2] = 0; + break; + case 9: + if (!mpChangeLayout->getAnim(unk_0x918)->isPlaying()) { + resetFuncMsgQ(); + unk_0x78 = 1; + unk_0x918 = -1; + mpPaneManager->update(); + mpChangeLayout->getAnim(0x14)->initFrame(); + mpChangeLayout->calc(); + } + break; + } + } + + void Setting::initScroll() { + if (unk_0x91C[2] == 0) { + return; + } + for (int index = 1; index <= 4; ++index) { + mpChangeLayout->FindPaneByName(sSettingAPNumberNames[index])->SetVisible(true); + } + u16 count = mAPScanList.count; + if (count == 2) { + mpChangeLayout->FindPaneByName(sSettingAPNumberNames[3])->SetVisible(false); + } else if (count < 2) { + if (count == 0) { + mpChangeLayout->FindPaneByName(sSettingAPNumberNames[1])->SetVisible(false); + } + mpChangeLayout->FindPaneByName(sSettingAPNumberNames[2])->SetVisible(false); + mpChangeLayout->FindPaneByName(sSettingAPNumberNames[3])->SetVisible(false); + } + if (count < 4) { + for (int index = 4; index < 6; ++index) { + mpChangeLayout->FindPaneByName(sSettingAPNumberNames[index])->SetVisible(false); + } + mpChangeLayout->FindPaneByName("N_AP7")->SetVisible(false); + } + mpChangeLayout->getAnim(0x14)->initFrame(); + mpChangeLayout->getAnim(0x14)->restart(); + mpChangeLayout->getAnim(0)->initAnmFrame(); + mpChangeLayout->FindPaneByName(sSettingAPPaneNames[0])->SetVisible(false); + mpChangeLayout->FindPaneByName(sSettingAPPaneNames[1])->SetVisible(false); + if (count > unk_0x914 + 4) { + mpChangeLayout->FindPaneByName(sSettingAPPaneNames[3])->SetVisible(true); + mpChangeLayout->getAnim(1)->initFrame(); + mpChangeLayout->getAnim(1)->restart(); + for (int index = 1; index < 6; ++index) { + mpChangeLayout->FindPaneByName(sSettingAPNumberNames[index])->SetVisible(true); + } + } else { + mpChangeLayout->FindPaneByName(sSettingAPPaneNames[3])->SetVisible(false); + for (int index = count + 1; index < 6; ++index) { + mpChangeLayout->FindPaneByName(sSettingAPNumberNames[index])->SetVisible(false); + } + } + unk_0x78 = 6; + unk_0x918 = 0x14; + unk_0x91C[2] = 0; + } + + void Setting::updateScroll() { + if (unk_0x91C[0] == 0) { + --unk_0x914; + if (unk_0x914 == 0) { + mpChangeLayout->getAnim(2)->initFrame(); + mpChangeLayout->getAnim(2)->restart(); + mpChangeLayout->FindPaneByName(sSettingAPPaneNames[0])->SetVisible(false); + } + if (mAPScanList.count == unk_0x914 + 5) { + mpChangeLayout->getAnim(1)->initFrame(); + mpChangeLayout->getAnim(1)->restart(); + mpChangeLayout->FindPaneByName(sSettingAPPaneNames[1])->SetVisible(true); + } + } else { + int previous = unk_0x914++; + if (mAPScanList.count == previous + 5) { + mpChangeLayout->getAnim(3)->initFrame(); + mpChangeLayout->getAnim(3)->restart(); + mpChangeLayout->FindPaneByName(sSettingAPPaneNames[1])->SetVisible(false); + } + if (unk_0x914 == 1) { + mpChangeLayout->getAnim(0)->initFrame(); + mpChangeLayout->getAnim(0)->restart(); + mpChangeLayout->FindPaneByName(sSettingAPPaneNames[0])->SetVisible(true); + } + } + mpChangeLayout->getAnim(10)->stop(); + mpChangeLayout->getAnim(11)->stop(); + unk_0x918 = unk_0x91C[0] + 10; + mpChangeLayout->getAnim(unk_0x918)->initFrame(); + mpChangeLayout->getAnim(unk_0x918)->restart(); + } + + void Setting::setAPDraw() { + WDBssDesc_* descriptor = reinterpret_cast(mAPScanList.entries); + u32 recordOffset = 2; + for (u32 index = 0; index <= mAPScanList.count; ++index) { + if (recordOffset > 0x800) { + return; + } + descriptor = reinterpret_cast(mAPScanList.entries + recordOffset - 2); + mpChangeLayout->getAnim(10)->stop(); + mpChangeLayout->getAnim(11)->stop(); + int privacyMode = WDGetPrivacyMode(descriptor); + char ssid[0x21]; + wchar_t displayName[0x21]; + memcpy(ssid, descriptor->ssid, 0x20); + ssid[0x20] = 0; + memset(displayName, 0, sizeof(displayName)); + int row = index + 1 - unk_0x914; + if (row >= 0 && row < 6) { + utility::CharacterCode::UTF8ToUTF16(displayName, ssid, 0x21); + nw4r::lyt::TextBox* textBox = static_cast( + mpChangeLayout->FindPaneByName(sSettingAPTextNames[row])); + textBox->SetString(displayName); + if (privacyMode == 0) { + mpChangeLayout->getAnim(row + 0x2e)->initFrame(); + mpChangeLayout->getAnim(row + 0x2e)->restart(); + mpChangeLayout->getAnim(row + 0x34)->stop(); + } else { + mpChangeLayout->getAnim(row + 0x34)->initFrame(); + mpChangeLayout->getAnim(row + 0x34)->restart(); + mpChangeLayout->getAnim(row + 0x2e)->stop(); + } + for (int animation = row + 0x16; animation <= row + 0x28; animation += 6) { + mpChangeLayout->getAnim(animation)->stop(); + } + int signal = getRadioLevel(descriptor); + mpChangeLayout->getAnim(row + signal * 6 + 0x16)->initFrame(); + mpChangeLayout->getAnim(row + signal * 6 + 0x16)->restart(); + } + recordOffset += descriptor->length * 2; + } } int Setting::get_arw_no(const char* paneName) { - int result = -1; - for (int index = 0; index < 2; index++) { + for (int index = 0; index < 2; ++index) { if (strcmp(sSettingArrowNames[index], paneName) == 0) { - result = index; - break; + return index; } } - return result; + return -1; } int Setting::get_ap_no(const char* buttonName) { - int result = -1; - for (int index = 0; index < 4; index++) { + for (int index = 0; index < 4; ++index) { if (strcmp(sSettingAPButtonNames[index], buttonName) == 0) { - result = index; - break; + return index; } } - return result; + return -1; + } + + int Setting::getRadioLevel(const WDBssDesc_* descriptor) { + u16 signal = descriptor->rssi & 0xff; + if (signal > 0xc3) { + return 3; + } + if (signal > 0xb4) { + return 2; + } + return signal < 0xab ? 0 : 1; } BOOL Setting::isResetAcceptable() const { -- 2.49.1 From b21cac41f7cbbdf2eb71a7b81b06cf290d792ee5 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 03:22:57 +0000 Subject: [PATCH 19/61] decompile setting network workflows --- include/scene/setting/iplSetting.h | 5 +- src/scene/setting/iplSetting.cpp | 788 +++++++++++++++++++++++++++++ 2 files changed, 792 insertions(+), 1 deletion(-) diff --git a/include/scene/setting/iplSetting.h b/include/scene/setting/iplSetting.h index ddc4d664..bce7698b 100644 --- a/include/scene/setting/iplSetting.h +++ b/include/scene/setting/iplSetting.h @@ -149,6 +149,8 @@ namespace ipl { void start_left_event(const char* pageName); int get_arw_no(const char* paneName); int get_ap_no(const char* buttonName); + void makeSupportCode(); + int getErrorNum(); virtual void destroy(); virtual void prepare(); virtual void create(); @@ -190,7 +192,8 @@ namespace ipl { int unk_0x7C; int mProfileIDMode; int unk_0x84; - u8 unk_0x88[8]; + int mAOSSState; + int mRakuState; int mFuncMsgPending; int unk_0x94; ESTitleId mUpdateTitleId; diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 3b25758b..33f50ea5 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -3,12 +3,14 @@ #include "scene/setting/iplNCDSetting.h" #include "scene/setting/iplParental.h" +#include "scene/nakamuraTest/iplNakamuraTest.h" #include "scene/parentalDialog/iplParentalDialog.h" #include "system/iplErrorHandler.h" #include "system/iplSystem.h" #include "utility/iplWpad.h" #include "utility/iplCharacterCode.h" #include "sound/iplSound.h" +#include "utility/iplESMisc.h" #include "iplwww/www_wiisetting.h" #include "iplwww/www_surface.h" @@ -24,6 +26,7 @@ #include #include #include +#include extern "C" void __VISetAdjustingValues(s32 horizontal, s32 vertical); @@ -68,16 +71,27 @@ namespace ipl { class USBAPThread { public: USBAPThread(); + bool is(); + void setData(unsigned short* nickname, u8* result); + void Init(unsigned short* profile, u8* result); + void cancel(); }; class AOSSThread { public: AOSSThread(EGG::Heap* heap); + int start(); + int finish(NCDAossConfig* config, int* result); + void cancel(); }; class RakuRakuThread { public: RakuRakuThread(EGG::Heap* heap); + int getState(); + int start(); + int finish(NCDApConfig* config, int* result); + void cancel(); }; struct SettingAnimationBinding { @@ -2548,6 +2562,91 @@ namespace ipl { return -1; } + void Setting::start_point_event(const char* pageName) { + int accessPoint = get_ap_no(pageName); + mpChangeLayout->getAnim(10)->stop(); + mpChangeLayout->getAnim(11)->stop(); + int animation = accessPoint == -1 ? get_arw_no(pageName) + 4 : accessPoint + 0xc; + if (accessPoint == -1 && animation == 3) { + return; + } + mpChangeLayout->getAnim(animation)->initFrame(); + mpChangeLayout->getAnim(animation)->restart(); + mpWiiSettingData->data[0x37] = 2; + setSE(); + } + + void Setting::start_left_event(const char* pageName) { + int accessPoint = get_ap_no(pageName); + int animation; + if (accessPoint == -1) { + int arrow = get_arw_no(pageName); + if (arrow == -1) { + return; + } + animation = arrow + 6; + } else { + animation = accessPoint + 0x10; + } + mpChangeLayout->getAnim(animation)->initFrame(); + mpChangeLayout->getAnim(animation)->restart(); + } + + void Setting::start_trig_event(const char* pageName) { + int accessPoint = get_ap_no(pageName); + if (accessPoint != -1) { + u32 recordOffset = 2; + WDBssDesc_* descriptor = reinterpret_cast(mAPScanList.entries); + for (u32 index = 0; index <= mAPScanList.count; ++index) { + recordOffset += descriptor->length * 2; + if (recordOffset > 0x800) { + break; + } + if (index == accessPoint + unk_0x914 + 1) { + int privacyMode = WDGetPrivacyMode(descriptor); + char ssid[0x21]; + memcpy(ssid, descriptor->ssid, 0x20); + ssid[0x20] = 0; + memset(mpStringBuffer->securityKey, 0, sizeof(mpStringBuffer->securityKey)); + memset(mpStringBuffer->ssid, 0, sizeof(mpStringBuffer->ssid)); + utility::CharacterCode::ANSIToUTF8(mpStringBuffer->ssid, + reinterpret_cast(ssid), 0x20); + ncd::NCDSetting::setSSID(reinterpret_cast(ssid)); + ncd::NCDSetting::setWDPrivacyMode(privacyMode); + www::wiisetting::setFuncResult(privacyMode == 0 ? 2 : 1); + mpWiiSettingData->data[0x37] = 3; + setSE(); + OSReport("SET DATA : %d %s %d\n", index, ssid, privacyMode); + break; + } + descriptor = reinterpret_cast(mAPScanList.entries + recordOffset - 2); + } + unk_0x91C[2] = 0; + unk_0x78 = 8; + } else { + int arrow = get_arw_no(pageName); + if (arrow == -1) { + return; + } + unk_0x918 = arrow + 8; + mpChangeLayout->getAnim(unk_0x918)->initFrame(); + mpChangeLayout->getAnim(unk_0x918)->restart(); + if (arrow == 0) { + unk_0x91C[0] = 0; + if (unk_0x914 == 1) { + mpChangeLayout->FindPaneByName("N_AP0")->SetVisible(false); + } + } else { + unk_0x91C[0] = 1; + if (mAPScanList.count == unk_0x914 + 5) { + mpChangeLayout->FindPaneByName("N_AP7")->SetVisible(false); + } + } + unk_0x78 = 7; + snd::getSystem()->startSE("WIPL_SE_BT_PUSH"); + } + } + int Setting::getRadioLevel(const WDBssDesc_* descriptor) { u16 signal = descriptor->rssi & 0xff; if (signal > 0xc3) { @@ -2559,6 +2658,695 @@ namespace ipl { return signal < 0xab ? 0 : 1; } + void Setting::setUseEULA_() { + if (unk_0x7C == 2) { + setUseEULA_Cancel_(); + } else if (unk_0x7C == 0) { + setUseEULA_Init_(); + } else if (unk_0x7C == 1) { + setUseEULA_Start_(); + } else if (unk_0x7C == 4) { + setUseEULA_WaitStopMotor_(); + } else if (unk_0x7C < 4 && !snd::getSystem()->isSEActive("WIPL_SE_DECIDE")) { + unk_0x7C = 4; + } + } + + void Setting::setUseEULA_Init_() { + if (!ncd::NCDSetting::getEnableFlag()) { + System::getDialog()->callBtn2(System::getRegion() == 2 ? 0x174 : 0x170, 0x146, 0x25); + unk_0x74 = 9; + unk_0x7C = 0; + resetFuncMsgQ(); + } else { + unk_0x7C = 1; + } + } + + void Setting::setUseEULA_Cancel_() { + System::getDialog()->callBtn2(0x16f, 0x142, 0x141, true); + unk_0x74 = 0xc; + unk_0x7C = 0; + resetFuncMsgQ(); + } + + void Setting::setUseEULA_Start_() { + if (!validateEULA_()) { + return; + } + for (int channel = 0; channel < 4; ++channel) { + controller::Interface* input = System::getController(channel); + if (input != NULL) { + input->rumble(); + } + } + System::getBS2Manager()->abort(); + System::stopReceiveSchedule(); + unk_0x7C = 3; + } + + void Setting::setUseEULA_WaitStopMotor_() { + __WPADReconnect(1); + mSettingData[0x39] = 1; + snd::getSystem()->stopAllSound(0x14); + unk_0x7C = 5; + resetFuncMsgQ(); + } + + bool Setting::validateEULA_() { + ESTmdView* titleView = NULL; + s32 contentResult = 0; + s32 result = utility::ESMisc::GetTmdView(System::getMem1Root(), mUpdateTitleId, &titleView); + bool valid = false; + if (result == -0x401 || result == -0x6a) { + unk_0x7C = 0; + unk_0x74 = 0xd; + resetFuncMsgQ(); + System::getDialog()->callBtn2(0x180, 0x2e, 0x25); + } else if (result == 0) { + if (!utility::ESMisc::ContentExist(titleView, 1, &contentResult) && contentResult != 0) { + System::getErrorHandler()->log("error", contentResult, "iplSetting.cpp", 0x10fc); + System::getErrorHandler()->set(ErrorHandler::DEFAULT, 2); + } + valid = true; + } else { + System::getErrorHandler()->log("error", result, "iplSetting.cpp", 0x10f1); + System::getErrorHandler()->set(ErrorHandler::DEFAULT, 2); + } + if (titleView != NULL) { + System::getMem1Root()->free(titleView); + } + return valid; + } + + void Setting::setUpdate_() { + switch (mProfileIDMode) { + case 0: setUpdate_Init_(); break; + case 1: setUpdate_WaitAcceptDialog_(); break; + case 2: setUpdate_ConnectTestStart_(); break; + case 3: setUpdate_ConnectTestCreateWait_(); break; + case 4: setUpdate_ConnectTestRun_(); break; + case 5: setUpdate_ConnectTestFailed_(); break; + case 6: setUpdate_SuccessDialog_(); break; + case 7: setUpdate_NoUpdateDialog_(); break; + case 8: setUpdate_EULAInit_(); break; + case 9: + System::getDialog()->callBtn2(0x16f, 0x142, 0x141, true); + unk_0x74 = 10; + resetFuncMsgQ(); + break; + case 10: setUpdate_Reboot_(); break; + } + } + + void Setting::setUpdate_Init_() { + if (!ncd::NCDSetting::getEnableFlag()) { + System::getDialog()->callBtn2(0x17f, 0x146, 0x25); + unk_0x74 = 9; + resetFuncMsgQ(); + } else { + www::wiisetting::setFuncResult(1); + if (System::getRegion() == 2) { + System::getDialog()->callBtn1Sml(0x177, 0x179); + } else { + System::getDialog()->callBtn1Sml(0x176, 0x178); + } + mProfileIDMode = 1; + } + } + + void Setting::setUpdate_WaitAcceptDialog_() { + if (System::getDialog()->getLastResult() >= 0) { + mProfileIDMode = 2; + } + } + + void Setting::setUpdate_ConnectTestStart_() { + if (System::getSceneManager()->getScene(0x19) == NULL && www::wiisetting::getFuncResult() == 0) { + waitStart(); + createChildScene(0x19, this, NULL, NULL); + mProfileIDMode = 3; + } + } + + void Setting::setUpdate_ConnectTestCreateWait_() { + if (System::getSceneManager()->getScene(0x19) != NULL) { + mProfileIDMode = 4; + } + } + + void Setting::setUpdate_ConnectTestRun_() { + if (isWaitPlaying()) { + return; + } + if (mpWiiSettingFlag->err == 0) { + mpWiiSettingFlag->smthMsgData = 9; + mUpdateTiming = 3; + } else if (System::getDialog()->getLastResult() == 1) { + mProfileIDMode = 2; + } else if (System::getDialog()->getLastResult() == 2) { + www::wiisetting::setFuncResult(1); + mProfileIDMode = 5; + unk_0x92C = 0; + } + } + + void Setting::setUpdate_ConnectTestFailed_() { + if (unk_0x92C == 0) { + System::getDialog()->callBtn1(0x16c, 1); + ++unk_0x92C; + } else if (System::getDialog()->getLastResult() >= 0) { + mProfileIDMode = 10; + } + } + + void Setting::setUpdate_SuccessDialog_() { + if (System::getDialog()->getLastResult() >= 0) { + System::getDialog()->callBtn1(0x16a, 0x2e); + mProfileIDMode = 8; + } + } + + void Setting::setUpdate_NoUpdateDialog_() { + if (System::getDialog()->getLastResult() >= 0) { + if (unk_0x92C == 0) { + System::getDialog()->callBtn1(0x167, 1); + ++unk_0x92C; + } else { + mProfileIDMode = 10; + } + } + } + + void Setting::setUpdate_EULAInit_() { + if (System::getDialog()->getLastResult() >= 0) { + if (SCGetEULA() == 0) { + mProfileIDMode = 0; + www::wiisetting::setFuncResult(1); + resetFuncMsgQ(); + } else { + mProfileIDMode = 10; + } + } + } + + void Setting::setUpdate_Reboot_() { + if (unk_0x92C == 0xb4) { + if (mProgressiveMode == 2 || mProgressiveMode == 5) { + SCSetConfigDoneFlag(1); + SCSetConfigDoneFlag2(1); + SCFlush(); + } + mIsResetAcceptable = 1; + System::getResetHandler()->reset(); + } + ++unk_0x92C; + } + + u16 Setting::getProfileID() { + if (mProfileIDMode < 3) { + return ncd::NCDSetting::getID(); + } + u16 profileID = ncd::NCDSetting::getUseProfileID(); + ncd::NCDSetting::initSetID(profileID & 0xff); + return (profileID & 0xff) == 3 ? 0 : profileID; + } + + int Setting::getUpdateTiming() { + return mUpdateTiming; + } + + void Setting::setConnectTestResult(int result, int networkError, bool updateFound, int supportCode) { + unk_0x930 = supportCode; + if (!updateFound && result == 3) { + resetFuncMsgQ(); + mUpdateTiming = 0; + mIsResetAcceptable = 1; + } else if (mpWiiSettingFlag->smthMsgData == 9) { + if (result == 2) { + System::getDialog()->terminate(); + mUpdateTiming = 6; + mpWiiSettingFlag->err = networkError; + } else if (result == 1) { + System::getDialog()->setProgBarLength(100); + mProfileIDMode = 6; + mUpdateTiming = 0; + mpWiiSettingFlag->smthMsgData = 0x54; + SCSetUpdateType(2); + SCFlush(); + } else if (result == 3) { + System::getDialog()->terminate(); + if (SCGetConfigDoneFlag2() == 0) { + mProfileIDMode = 6; + } else { + mProfileIDMode = 7; + unk_0x92C = 0; + } + mUpdateTiming = 0; + mpWiiSettingFlag->smthMsgData = 0x54; + } + } else { + if (result == 1) { + mpWiiSettingFlag->err = 0; + ncd::NCDSetting::setConnectTestFlag(true); + System::reloadDownloadTask(); + } else { + if (mProfileIDMode == 0) { + unk_0x74 = 2; + } + mpWiiSettingFlag->err = networkError; + makeErrorMessage(); + ncd::NCDSetting::setConnectTestFlag(false); + } + waitFinish(); + www::wiisetting::setFuncResult(result); + } + } + + void Setting::setNUP() { + switch (mUpdateTiming) { + case 0: + makeSupportCode(); + mUpdateTiming = 1; + break; + case 1: + if (System::getDialog()->getLastResult() == 2) { + System::getDialog()->callBtn1Sml(System::getRegion() == 2 ? 0x177 : 0x176, + System::getRegion() == 2 ? 0x179 : 0x178); + mUpdateTiming = 2; + } else if (System::getDialog()->getLastResult() == 1) { + www::wiisetting::setFuncResult(2); + mUpdateTiming = 10; + } + break; + case 2: + if (System::getDialog()->getLastResult() >= 0) { + mUpdateTiming = 3; + } + break; + case 3: + System::getDialog()->callBtnPrg(0x162); + mUpdateTiming = 4; + break; + case 4: { + scene::NakamuraTest* test = static_cast(System::getSceneManager()->getScene(0x19)); + if (test != NULL && test->amtTotal() != 0) { + System::getDialog()->setProgBarLength(test->amtCompleted() * 100 / test->amtTotal()); + } + break; + } + case 5: + if (System::getDialog()->getLastResult() >= 0) { + System::getDialog()->callBtn0(0x163, 0xb4); + mUpdateTiming = 8; + } + break; + case 6: + if (System::getDialog()->getLastResult() >= 0) { + makeErrorMessage(); + mUpdateTiming = 0xb; + } + break; + case 7: + if (System::getDialog()->getLastResult() >= 0) { + System::getDialog()->callBtn1(0x167, 1); + mUpdateTiming = 8; + } + break; + case 8: + if (System::getDialog()->getLastResult() >= 0) { + mUpdateTiming = 9; + unk_0x92C = 0; + if (mProgressiveMode == 2 || mProgressiveMode == 5) { + SCSetConfigDoneFlag(1); + SCSetConfigDoneFlag2(1); + SCFlush(); + } + } + break; + case 9: + if (unk_0x92C == 0xb4) { + mIsResetAcceptable = 1; + System::getResetHandler()->reset(); + } + ++unk_0x92C; + break; + case 0xb: + if (System::getDialog()->getLastResult() >= 0) { + mProfileIDMode = 5; + mpWiiSettingFlag->smthMsgData = 0x54; + mUpdateTiming = 0; + unk_0x92C = 0; + } + break; + } + } + + void Setting::makeErrorMessage() { + const wchar_t* prefix = System::getMessage(400); + int messageId = getErrorNum(); + const wchar_t* detail = System::getMessage(messageId); + int error = mpWiiSettingFlag->err; + OSReport("error:%d\n", error); + wchar_t errorText[8]; + wchar_t message[0x140]; + swprintf(errorText, 8, L"\n%03d", error); + memset(message, 0, sizeof(message)); + size_t prefixLength = wcslen(prefix); + wcsncat(message, prefix, prefixLength); + size_t errorLength = wcslen(errorText); + wcsncat(message + prefixLength, errorText, errorLength); + size_t detailLength = wcslen(detail); + wcsncat(message + prefixLength + errorLength, detail, detailLength); + message[prefixLength + errorLength + detailLength] = 0; + bool connectTestError = mpWiiSettingFlag->smthMsgData == 9; + bool japaneseRegion = System::getRegion() == 2 && System::getLanguage() == 2 && getErrorNum() == 0x1b6; + if (connectTestError || mProfileIDMode == 0) { + if (japaneseRegion) { + System::getDialog()->callBtn1(message, 0x2e, 46.0f); + } else { + System::getDialog()->callBtn1(message, 0x2e); + } + } else { + System::getDialog()->callBtn2(message, 0x171, 0x25); + } + } + + int Setting::getErrorNum() { + int error = mpWiiSettingFlag->err; + if (error == 0x7d01) return System::getRegion() == 2 ? 0x1a5 : 0x191; + if (error == 0x7d02) return System::getRegion() == 2 ? 0x1a6 : 0x192; + if (error == 0x7d03) return System::getRegion() == 2 ? 0x1a7 : 0x193; + if (error < 33000) return System::getRegion() == 2 ? 0x1a8 : 0x194; + if (error < 0xc418) return System::getRegion() == 2 ? 0x1a9 : 0x195; + if (error < 0xc47c) return System::getRegion() == 2 ? 0x1aa : 0x196; + if (error < 0xc4e0) return System::getRegion() == 2 ? 0x1ab : 0x197; + if (error < 0xc544) return System::getRegion() == 2 ? 0x1ac : 0x198; + if (error < 0xc760) return System::getRegion() == 2 ? 0x1ad : 0x199; + if (error < 0xc76a) return System::getRegion() == 2 ? 0x1b8 : 0x1a4; + if (error < 0xc79c) return System::getRegion() == 2 ? 0x1ad : 0x199; + if (error < 0xc8c8) return System::getRegion() == 2 ? 0x1ae : 0x19a; + if (error < 0xc92c) return System::getRegion() == 2 ? 0x1af : 0x19b; + if (error < 0xcb84) return System::getRegion() == 2 ? 0x1b0 : 0x19c; + if (error < 0xcbe8) return System::getRegion() == 2 ? 0x1b1 : 0x19d; + if (error < 0xcc4c) return System::getRegion() == 2 ? 0x1b2 : 0x19e; + if (error < 0xcd14) return System::getRegion() == 2 ? 0x1b3 : 0x19f; + if (error < 0xcd78) return System::getRegion() == 2 ? 0x1b4 : 0x1a0; + if (error < 0xcddc) return System::getRegion() == 2 ? 0x1b5 : 0x1a1; + if (error < 0xce40) return System::getRegion() == 2 ? 0x1b6 : 0x1a2; + if (error < 55000) return System::getRegion() == 2 ? 0x1b7 : 0x1a3; + if (error > 100000) return 0x1c5; + return System::getRegion(); + } + + void Setting::makeSupportCode() { + const wchar_t* title = System::getMessage(0x16d); + const wchar_t* codeLabel = System::getMessage(0x1b9); + wchar_t supportCode[12]; + wchar_t message[0x110]; + swprintf(supportCode, 12, L"\n%03d", unk_0x930); + memset(message, 0, sizeof(message)); + size_t titleLength = wcslen(title); + wcsncat(message, title, titleLength); + message[titleLength] = L'\n'; + message[titleLength + 1] = 0; + size_t labelLength = wcslen(codeLabel); + wcsncat(message + titleLength + 1, codeLabel, labelLength); + size_t codeLength = wcslen(supportCode); + wcsncat(message + titleLength + 1 + labelLength, supportCode, codeLength); + message[titleLength + 1 + labelLength + codeLength] = 0; + System::getDialog()->callBtn2(message, 0x142, 0x141, true); + } + + void Setting::setInitializeResult(bool initialized, int error) { + waitFinish(); + if (!initialized) { + if (error == -2) { + System::getErrorHandler()->log("NandSDWorker", error, "iplSetting.cpp", 0x13a7); + System::getErrorHandler()->set(ErrorHandler::DEFAULT, 2); + } else if (error == -5) { + System::getErrorHandler()->set(ErrorHandler::DEFAULT, 1); + } + } else { + www::wiisetting::setFuncResult(1); + } + } + + void Setting::setUSBAP() { + if (unk_0x84 == 2) { + if (unk_0x91C[1] != 0) { + www::wiisetting::setFuncResult(unk_0x91C[1]); + unk_0x84 = 1; + unk_0x91C[1] = 0; + resetFuncMsgQ(); + } + } else if (unk_0x84 == 1 && static_cast(mpUSBAPThread)->is()) { + SCOwnerNickname nickname; + int result = SCGetOwnerNickName(&nickname); + if (!result) { + www::wiisetting::setFuncResult(2); + resetFuncMsgQ(); + } else { + OSReport("USB SCGetOwnerNickName:%d\n", result); + static_cast(mpUSBAPThread)->setData(nickname.name, &unk_0x91C[1]); + static_cast(mpUSBAPThread)->Init( + reinterpret_cast(mpMem1BrowserBuffer), + reinterpret_cast(mpMem2BrowserBuffer)); + unk_0x84 = 2; + } + } + } + + void Setting::cancelUSBAP() { + if (unk_0x84 == 3) { + if (unk_0x91C[1] != 0 || static_cast(mpUSBAPThread)->is()) { + www::wiisetting::setFuncResult(5); + unk_0x84 = 1; + unk_0x91C[1] = 0; + resetFuncMsgQ(); + } + } else if (unk_0x84 > 0 && unk_0x84 < 3) { + static_cast(mpUSBAPThread)->cancel(); + unk_0x84 = 3; + } + } + + void Setting::AOSSProcess() { + int error = mpWiiSettingFlag->err; + if (error == '"') { + if (mAOSSState == 3) { + if (System::getDialog()->getLastResult() >= 0) { + mAOSSState = 0; + www::wiisetting::setFuncResult(10); + resetFuncMsgQ(); + } + } else { + System::getDialog()->callBtn1(0x1c2, 0x2e); + mAOSSState = 3; + unk_0x74 = 2; + } + return; + } + AOSSThread* thread = reinterpret_cast(mpAOSSThread); + bool cancelled = error == '!'; + if (mAOSSState == 0) { + if (!snd::getSystem()->isSEActive("WIPL_SE_DECIDE")) { + if (cancelled || thread->start() == 0) { + www::wiisetting::setFuncResult(cancelled ? 5 : 2); + resetFuncMsgQ(); + } else { + mAOSSState = 1; + } + } + } else if (mAOSSState >= 0 && mAOSSState < 3) { + int result = 0; + if (thread->finish(&m_AOSSConfig, &result) != 0) { + mAOSSState = 0; + if (cancelled) { + www::wiisetting::setFuncResult(5); + } else if (result == 0) { + ncd::NCDSetting::getData(); + ncd::NCDSetting::getID(); + ncd::NCDSetting::setAOSSParams(m_AOSSConfig); + www::wiisetting::setFuncResult(1); + } else { + OSReport("m_AOSSThread : Terminated with Error(%d)\n", result); + www::wiisetting::setFuncResult(2); + } + resetFuncMsgQ(); + } else if (cancelled && mAOSSState != 2) { + thread->cancel(); + mAOSSState = 2; + } + } + } + + void Setting::RakuProcess() { + int command = mpWiiSettingFlag->smthMsgData; + int state = reinterpret_cast(mpRakuRakuThread)->getState(); + RakuRakuThread* thread = reinterpret_cast(mpRakuRakuThread); + int result = 0; + if (command == ',') { + if (mRakuState != 1) { + System::getDialog()->callBtn1(0x1c3, 0x2e); + mRakuState = 1; + unk_0x74 = 2; + } else if (System::getDialog()->getLastResult() >= 0) { + mRakuState = 0; + www::wiisetting::setFuncResult(10); + resetFuncMsgQ(); + } + return; + } + if (command == '+' && (state == 0 || state == 6 || state == 7 || state == 8)) { + if (thread->finish(NULL, NULL) != 0) { + www::wiisetting::setFuncResult(5); + resetFuncMsgQ(); + } else { + thread->cancel(); + } + return; + } + if (command != '+' && state == 0) { + if (!snd::getSystem()->isSEActive("WIPL_SE_DECIDE") && thread->start() == 0) { + www::wiisetting::setFuncResult(2); + resetFuncMsgQ(); + } + return; + } + if (command != '+' && state == 5) { + if (command == ')') { + www::wiisetting::setFuncResult(1); + resetFuncMsgQ(); + } + return; + } + if (state == 7) { + if (thread->finish(NULL, &result) != 0) { + www::wiisetting::setFuncResult(2); + resetFuncMsgQ(); + } + return; + } + if (state > 4 && state < 7) { + if (thread->finish(&m_RakuConfig.cfg, &result) != 0) { + if (result == 1) { + ncd::NCDSetting::getData(); + ncd::NCDSetting::getID(); + ncd::NCDSetting::setRakuParams(m_RakuConfig.cfg); + www::wiisetting::setFuncResult(1); + } else { + www::wiisetting::setFuncResult(2); + } + resetFuncMsgQ(); + } + return; + } + if (state > 0 && state < 4 && command == '(') { + www::wiisetting::setFuncResult(1); + resetFuncMsgQ(); + } + } + + void Setting::waitStart() { + mpMainLayout->getAnim(0)->initFrame(); + mpMainLayout->getAnim(0)->restart(); + mpMainLayout->FindPaneByName("G_Wait")->SetVisible(true); + snd::getSystem()->startSE("WIPL_SE_COPYING"); + } + + void Setting::waitFinish() { + mpMainLayout->getAnim(0)->stop(); + mpMainLayout->FindPaneByName("G_Wait")->SetVisible(false); + snd::getSystem()->startSE("WIPL_SE_COPY_FINISH"); + } + + bool Setting::isWaitPlaying() { + return mpMainLayout->getAnim(0)->isPlaying(); + } + + void Setting::setSE() { + u8& action = mpWiiSettingData->data[0x37]; + u8& pendingAction = mpWiiSettingData->data[0x38]; + if (unk_0xB9C < 10 && action == 2) { + action = 0; + } + if ((action == 0 || action == 2) && pendingAction != 0) { + action = pendingAction; + } + switch (action) { + case 1: + snd::getSystem()->startSE("WIPL_SE_BT_PUSH"); + break; + case 2: + snd::getSystem()->startSE("WIPL_SE_BT_TARGETTING"); + break; + case 3: + snd::getSystem()->startSE("WIPL_SE_DECIDE"); + break; + case 4: + snd::getSystem()->startSE("WIPL_SE_CANCEL"); + break; + case 5: + snd::getSystem()->startSE("WIPL_SE_CHOICE_CHG"); + break; + case 6: + snd::getSystem()->startSE("WIPL_SE_CHAR_DELETE_ERROR"); + break; + case 10: + snd::getSystem()->setOutputMode(snd::AUDIO_OUTPUT_MODE_MONO); + snd::getSystem()->startSE("WIPL_SE_OUTPUT_MODE_SELECT"); + break; + case 11: + snd::getSystem()->setOutputMode(snd::AUDIO_OUTPUT_MODE_STEREO); + snd::getSystem()->startSE("WIPL_SE_OUTPUT_MODE_SELECT"); + break; + case 12: + snd::getSystem()->setOutputMode(snd::AUDIO_OUTPUT_MODE_SURROUND); + snd::getSystem()->startSE("WIPL_SE_OUTPUT_MODE_SELECT"); + break; + case 30: + snd::getSystem()->setOutputMode(snd::AUDIO_OUTPUT_MODE_MONO); + snd::getSystem()->startSE("WIPL_SE_CANCEL"); + break; + case 31: + snd::getSystem()->setOutputMode(snd::AUDIO_OUTPUT_MODE_STEREO); + snd::getSystem()->startSE("WIPL_SE_CANCEL"); + break; + case 32: + snd::getSystem()->setOutputMode(snd::AUDIO_OUTPUT_MODE_SURROUND); + snd::getSystem()->startSE("WIPL_SE_CANCEL"); + break; + } + if (action == 2 || action == 0 || mpWiiSettingData->data[0x12] == 0x1e || pendingAction != 0) { + if (action == 2) { + controller::Interface* controller = System::getYoungController(); + if (controller != NULL) { + controller->rumble(0); + } + } + } else { + unk_0xB9C = 0; + } + action = 0; + pendingAction = 0; + } + + void APEvent::onEvent(u32 componentID, u32 event, void* data) { + gui::PaneComponent* component = static_cast(mpManager->getComponent(componentID)); + const char* paneName = component->getPane()->GetName(); + if (event == ::gui::EventHandler::ON_POINT) { + mpSetting->start_point_event(paneName); + } else if (event == ::gui::EventHandler::ON_TRIG) { + controller::Interface* input = static_cast(data); + if (input->downTrg(0x100800)) { + mpSetting->start_trig_event(paneName); + } + } else if (event == ::gui::EventHandler::ON_LEFT) { + mpSetting->start_left_event(paneName); + } + } + BOOL Setting::isResetAcceptable() const { return mIsResetAcceptable; } -- 2.49.1 From 1a5513f4cae2a7be8ce1a6be6615c34cdd02a3b3 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 03:26:38 +0000 Subject: [PATCH 20/61] match setting helper frames --- src/scene/setting/iplSetting.cpp | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 33f50ea5..a650d11b 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -1794,7 +1794,7 @@ namespace ipl { OSReport("SCGetOwnerNickName:%d\n", nicknameExists); if (nicknameExists) { SCOwnerNickname* ownerNickname = reinterpret_cast(mSettingData); - memcpy(unk_0x938, ownerNickname->name, ownerNickname->length * sizeof(wchar_t)); + memcpy(unk_0x938, mSettingData, ownerNickname->length * sizeof(wchar_t)); } memset(mpStringBuffer->nickname, 0, sizeof(mpStringBuffer->nickname)); utility::CharacterCode::UTF16ToUTF8(mpStringBuffer->nickname, @@ -1864,7 +1864,7 @@ namespace ipl { void Setting::initMTU() { memset(mpStringBuffer->adjMtu, 0, sizeof(mpStringBuffer->adjMtu)); - char mtuText[20]; + char mtuText[12]; sprintf(mtuText, "%d", ncd::NCDSetting::getMTU()); utility::CharacterCode::ANSIToUTF8(mpStringBuffer->adjMtu, reinterpret_cast(mtuText)); @@ -1872,7 +1872,7 @@ namespace ipl { void Setting::initSecA() { memset(mpStringBuffer->parentalSecA, 0, sizeof(mpStringBuffer->parentalSecA)); - wchar_t answer[42]; + wchar_t answer[34]; memset(answer, 0, 0x44); wcsncpy(answer, parental::Parental::getSecA(), 0x20); memset(unk_0x938, 0, sizeof(unk_0x938)); @@ -2173,15 +2173,16 @@ namespace ipl { } void Setting::adjustSecA(wchar_t* text) { + u32 index = 0; bool containsWideCharacter = false; - for (u32 i = 0; text[i] != 0; ++i) { - if (text[i] > 0x7f) { + for (; text[index] != 0; ++index) { + if (text[index] > 0x7f) { containsWideCharacter = true; break; } } if (containsWideCharacter && wcslen(reinterpret_cast(unk_0x938)) > 0x10) { - char secondLine[0x34]; + char secondLine[0x22]; memcpy(secondLine, reinterpret_cast(text) + 0x20, 0x22); memcpy(reinterpret_cast(text) + 0x22, secondLine, 0x22); text[0x10] = L'\n'; @@ -2198,7 +2199,7 @@ namespace ipl { } } if (containsWideCharacter && wcslen(text) > 0x10) { - char secondLine[0x34]; + char secondLine[0x22]; memcpy(secondLine, reinterpret_cast(text) + 0x22, 0x22); memcpy(reinterpret_cast(text) + 0x20, secondLine, 0x22); } @@ -2852,7 +2853,7 @@ namespace ipl { void Setting::setUpdate_Reboot_() { if (unk_0x92C == 0xb4) { - if (mProgressiveMode == 2 || mProgressiveMode == 5) { + if (mInitialArgument == 2 || mInitialArgument == 5) { SCSetConfigDoneFlag(1); SCSetConfigDoneFlag2(1); SCFlush(); @@ -3249,20 +3250,20 @@ namespace ipl { } void Setting::waitStart() { - mpMainLayout->getAnim(0)->initFrame(); - mpMainLayout->getAnim(0)->restart(); - mpMainLayout->FindPaneByName("G_Wait")->SetVisible(true); + mpWaitLayout->getAnim(0)->initFrame(); + mpWaitLayout->getAnim(0)->restart(); + mpWaitLayout->FindPaneByName("G_Wait")->SetVisible(true); snd::getSystem()->startSE("WIPL_SE_COPYING"); } void Setting::waitFinish() { - mpMainLayout->getAnim(0)->stop(); - mpMainLayout->FindPaneByName("G_Wait")->SetVisible(false); + mpWaitLayout->getAnim(0)->stop(); + mpWaitLayout->FindPaneByName("G_Wait")->SetVisible(false); snd::getSystem()->startSE("WIPL_SE_COPY_FINISH"); } bool Setting::isWaitPlaying() { - return mpMainLayout->getAnim(0)->isPlaying(); + return mpWaitLayout->getAnim(0)->isPlaying(); } void Setting::setSE() { -- 2.49.1 From edeeeb60f43a97bf113362d22d01fd01c458ca76 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 03:33:38 +0000 Subject: [PATCH 21/61] match setting update initialization --- src/scene/setting/iplSetting.cpp | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index a650d11b..c309904a 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -2675,7 +2675,11 @@ namespace ipl { void Setting::setUseEULA_Init_() { if (!ncd::NCDSetting::getEnableFlag()) { - System::getDialog()->callBtn2(System::getRegion() == 2 ? 0x174 : 0x170, 0x146, 0x25); + if (static_cast(System::getRegion()) == 2) { + System::getDialog()->callBtn2(0x174, 0x146, 0x25); + } else { + System::getDialog()->callBtn2(0x170, 0x146, 0x25); + } unk_0x74 = 9; unk_0x7C = 0; resetFuncMsgQ(); @@ -2761,18 +2765,18 @@ namespace ipl { } void Setting::setUpdate_Init_() { - if (!ncd::NCDSetting::getEnableFlag()) { - System::getDialog()->callBtn2(0x17f, 0x146, 0x25); - unk_0x74 = 9; - resetFuncMsgQ(); - } else { + if (ncd::NCDSetting::getEnableFlag()) { www::wiisetting::setFuncResult(1); - if (System::getRegion() == 2) { + if (static_cast(System::getRegion()) == 2) { System::getDialog()->callBtn1Sml(0x177, 0x179); } else { System::getDialog()->callBtn1Sml(0x176, 0x178); } mProfileIDMode = 1; + } else { + System::getDialog()->callBtn2(0x17f, 0x146, 0x25); + unk_0x74 = 9; + resetFuncMsgQ(); } } @@ -2841,12 +2845,12 @@ namespace ipl { void Setting::setUpdate_EULAInit_() { if (System::getDialog()->getLastResult() >= 0) { - if (SCGetEULA() == 0) { + if (SCGetEULA() != 0) { + mProfileIDMode = 10; + } else { mProfileIDMode = 0; www::wiisetting::setFuncResult(1); resetFuncMsgQ(); - } else { - mProfileIDMode = 10; } } } @@ -2870,7 +2874,10 @@ namespace ipl { } u16 profileID = ncd::NCDSetting::getUseProfileID(); ncd::NCDSetting::initSetID(profileID & 0xff); - return (profileID & 0xff) == 3 ? 0 : profileID; + if ((profileID & 0xff) == 3) { + profileID = 0; + } + return profileID; } int Setting::getUpdateTiming() { -- 2.49.1 From 9f1b9a2ddf116af4642f934d13b51208c0f04455 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 03:34:20 +0000 Subject: [PATCH 22/61] match setting eula initialization --- src/scene/setting/iplSetting.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index c309904a..44daf357 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -2674,17 +2674,17 @@ namespace ipl { } void Setting::setUseEULA_Init_() { - if (!ncd::NCDSetting::getEnableFlag()) { - if (static_cast(System::getRegion()) == 2) { - System::getDialog()->callBtn2(0x174, 0x146, 0x25); - } else { + if (ncd::NCDSetting::getEnableFlag()) { + unk_0x7C = 1; + } else { + if (static_cast(System::getRegion()) != 2) { System::getDialog()->callBtn2(0x170, 0x146, 0x25); + } else { + System::getDialog()->callBtn2(0x174, 0x146, 0x25); } unk_0x74 = 9; unk_0x7C = 0; resetFuncMsgQ(); - } else { - unk_0x7C = 1; } } -- 2.49.1 From a9eb08479d49e806893873258757c2617d1d29e1 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 03:45:54 +0000 Subject: [PATCH 23/61] match setting fadein readiness --- src/scene/setting/iplSetting.cpp | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 44daf357..e4424cf1 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -498,12 +498,10 @@ namespace ipl { } FaderSceneCommand Setting::calcFadein() { - if (System::hasCreatedAfter()) { - if (mBrowserCreated == 0) { - mBrowserCreated = 1; - createBrowser(); - OSReport("............browser created\n"); - } + if (System::hasCreatedAfter() && mBrowserCreated == 0) { + mBrowserCreated = 1; + createBrowser(); + OSReport("............browser created\n"); } else if (mBrowserCreated == 0) { OSReport("wait first init\n"); return FADER_SCN_CONTINUE; @@ -511,16 +509,15 @@ namespace ipl { ext_ead::www::SurfaceManager* surfaceManager = ext_ead::www::SurfaceManager::GetInstance(); ext_ead::www::BrowserThread* browserThread = surfaceManager->GetBrowserThread(); - if (browserThread == NULL || browserThread->GetTextureBuffer(0, NULL) == NULL || !System::hasCreatedAfter()) { - return FADER_SCN_CONTINUE; + if (browserThread != NULL && browserThread->GetTextureBuffer(0, NULL) != NULL && System::hasCreatedAfter()) { + mKeyboardState = *System::getKeyboard()->getState(); + System::getFader()->fadeIn(); + mCreatePageTime = OSGetTime(); + OSReport("*** create page costs: %dms\n", + (OSGetTick() - mPrepareTick) / (OS_TIMER_CLOCK / 1000)); + return FADER_SCN_NEXT; } - - mKeyboardState = *System::getKeyboard()->getState(); - System::getFader()->fadeIn(); - mCreatePageTime = OSGetTime(); - OSReport("*** create page costs: %dms\n", - (OSGetTick() - mPrepareTick) / (OS_TIMER_CLOCK / 1000)); - return FADER_SCN_NEXT; + return FADER_SCN_CONTINUE; } void Setting::updateController_() { -- 2.49.1 From a4e784149899a4d036c0229c3d6849efe3b0fbea Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Mon, 28 Sep 2026 22:49:34 -0500 Subject: [PATCH 24/61] Decompile RVL SDK wad to 16/40 functions (#246) * decompile wad import check * decompile wad stream helpers * match wad unpack routines * match wad termination scan * decompile backup WAD header * decompile WAD unpack formats * decompile wad export worker * refine content index scan * decompile WAD signature verification * decompile wad hash path * match savedata validation * match wad title metadata query * match BroadOn unpack offsets * tune WAD export chunk comparison * reuse WAD content index offsets * tune WAD hash chunk comparison * tune WAD content index lookup * match WAD transfer metadata helpers * refine WAD allocator dispatch * refine WAD stream dispatch * decompile WAD import dispatch * decompile WAD backup helpers * refine WAD savedata verification * decompile WAD DVD boot import * decompile WAD DVD title import * refine WAD DVD stream parsing * match WAD memory free * match WAD allocator and content checks --- libs/RVL_SDK/src/wad/wad.c | 3479 ++++++++++++++++++++++++++++++++++++ 1 file changed, 3479 insertions(+) create mode 100644 libs/RVL_SDK/src/wad/wad.c diff --git a/libs/RVL_SDK/src/wad/wad.c b/libs/RVL_SDK/src/wad/wad.c new file mode 100644 index 00000000..0f2c89e1 --- /dev/null +++ b/libs/RVL_SDK/src/wad/wad.c @@ -0,0 +1,3479 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +typedef union WADStreamHandle { + DVDFileInfo dvd; + NANDFileInfo nand; + CNTFileInfoDVD contentDvd; + CNTFileInfoNAND contentNand; + FAFILE* fa; + void* memoryBase; +} WADStreamHandle; + +typedef struct __attribute__((aligned(32))) WADStream { + WADLocation location; + WADStreamHandle handle; +} WADStream; + +typedef union WADTitleMetadata { + ESTitleMetaHeader tmd; + ESTitleId backupTitleId; + u8 bytes[0x80]; +} WADTitleMetadata; + +typedef struct WADBroadOnHeader { + u32 headerSize; + u32 contentOffset; + u32 certSize; + u32 crlSize; + u32 ticketSize; + u32 titleMetaSize; + u32 contentSize; + u32 fileListSize; +} WADBroadOnHeader; + +typedef struct WADUnpackInfo { + s32 type; + s32 headerInfo; + u16 cidxMode; + u8 reserved_0x0a[2]; + u32 size_0x0c; + u32 offset_0x10; + void* buffer_0x14; + u32 size_0x18; + u32 size_0x1c; + u32 offset_0x20; + void* buffer_0x24; + u32 size_0x28; + u32 size_0x2c; + u32 offset_0x30; + void* buffer_0x34; + u32 size_0x38; + u32 sectionSize; + u32 sectionOffset; + ESTitleMeta* titleMeta; + u32 titleMetaSize; + u32 contentSize; + u32 contentOffset; + u32 metaSize; + u32 metaOffset; + u32 fileListSize; + u32 fileOffset; + u32 fileCount; + void* contentIndex; + void* fileNames; +} WADUnpackInfo; + +typedef struct WADFileHeader { + u32 magic; + u32 fileSize; + u8 flags[3]; + char name[0x40]; + u8 reserved_0x4b[5]; + u8 iv[0x10]; + u8 reserved_0x60[0x20]; +} WADFileHeader; + +typedef struct WADBootImportParts { + s32 headerInfo[2]; + u32 certificateSize; + void* certificates; + u32 crlSize; + void* crls; + u32 ticketSize; + void* ticket; + u32 titleMetaSize; + void* titleMeta; +} WADBootImportParts; + +typedef struct WADBackupFileHeader { + u32 magic; + u32 fileSize; + u8 flags[3]; + char path[0x75]; +} WADBackupFileHeader; + +typedef struct WADSaveDataHeader { + u32 format; + u32 flags; + u32 reserved_0x08; + u32 saveType; + u8 reserved_0x10[0x50]; + u32 fileSize; + u32 magic; + u8 reserved_0x68[0x18]; +} WADSaveDataHeader; + +typedef struct WADThreadStack { + u8 bytes[0x1000]; +} WADThreadStack; + +typedef struct WADFileEntry { + u32 fileSize; + u8 flags[4]; + char name[0x40]; +} WADFileEntry; + +typedef union WADBackupHeaderBlock { + WADBackupHeader header; + u8 bytes[0x80]; +} WADBackupHeaderBlock; + +typedef union WADBackupTitleMetaBuffer { + ESTmdView view; + u8 data[0x4A00]; +} WADBackupTitleMetaBuffer; + +typedef struct WADBackupSignature { + u8 header[0x40]; + u8 firstCertificate[0x180]; + u8 secondCertificate[0x180]; +} WADBackupSignature; + +typedef struct WADVerificationCertificateBundle { + u8 caProduction[0x400]; + u8 msProduction[0x240]; + u8 caDevelopment[0x400]; + u8 msDevelopment[0x240]; + u8 firstCertificate[0x180]; + u8 secondCertificate[0x180]; +} WADVerificationCertificateBundle; + +typedef struct WADVerificationWorkspace { + void* readBuffer[16]; + u8 digest[0x40]; + u8 hashContext[0xC0]; +} WADVerificationWorkspace; + +#pragma pack(push, 4) +typedef struct WADFileMetadataView { + u8 reserved_0x00[0x18C]; + ESTitleId titleId; + u8 reserved_0x194[0x48]; + u16 titleVersion; +} WADFileMetadataView; +#pragma pack(pop) + +typedef struct __attribute__((aligned(32))) WADImportWorkspace { + u8 transferId[0x20]; + WADFileHeader fileHeader; + u8 wadHeader[0x80]; + WADUnpackInfo unpackInfo; + WADStream stream; +} WADImportWorkspace; + +typedef struct WADImportTransfer { + s32 error; + u32 chunkSize; + BOOL ready[2]; + void* buffers[2]; + OSMutex mutex[2]; + OSCond waitCond[2]; + OSCond signalCond[2]; +} WADImportTransfer; + +typedef struct WADImportLoopArgs { + s32 fd; + u32 size; + WADImportTransfer* transfer; +} WADImportLoopArgs; + +typedef WADImportLoopArgs WADExportLoopArgs; + +typedef struct WADHashThreadArgs { + void* context; + u32 size; + WADImportTransfer* transfer; +} WADHashThreadArgs; + +#define WAD_STREAM_ALIGNMENT 0x40 +#define WAD_READ_ALIGNMENT 0x20 +#define WAD_ALIGN32(value) (((value) + WAD_READ_ALIGNMENT - 1) & ~(WAD_READ_ALIGNMENT - 1)) + +s32 WADOpenStream(WADLocation location, const char* path, WADStream* stream, u32, u32); +size_t WADReadStream(WADStream* stream, void** buffer, size_t size, s32 offset); +void WADCloseStream(WADStream* stream); +s32 WADWriteStream(WADStream* stream, void* buffer, u32 size); +s32 WADSeekStream(WADStream* stream, u32 offset, s32 origin); +static s32 WAD_815C2F44(WADHeader* header, s32* headerInfo); +static s32 _WADGetTitleVer(WADHeader* header, ESTitleId* titleId, u16* titleVersion, s32 type, + s32 headerInfo); +static s32 _WADUnpackIRD(WADHeader* header, WADStream* stream, WADUnpackInfo* info, + MEMAllocator* allocator, u32 offset, u32 mode); +static s32 _WADUnpackBroadOn(WADBroadOnHeader* header, WADStream* stream, WADUnpackInfo* info, + MEMAllocator* allocator, u32 offset, u32 mode); +static s32 _WADUnpackBackup(WADHeader* header, WADStream* stream, WADUnpackInfo* info, + MEMAllocator* allocator, u32 offset, u32 flags); +static s32 _WADUnpack(void* header, WADStream* stream, WADUnpackInfo* info, MEMAllocator* allocator, + u32 offset, u32 flags, u32 mode); +static s32 _WADHash(WADStream* stream, u32 offset, u32 size, void* context, void* buffer, + u32 chunkSize, void* secondBuffer, void* threadStack, u32 threadStackSize); +void WAD_815C4A2C(WADImportTransfer* transfer, void* firstBuffer, void* secondBuffer, + u32 chunkSize); +s32 WADVerify(WADStream* stream, MEMAllocator* allocator, u32 offset, u32 size); +s32 _WADGetCidxCount(const ESContentMask* contentMask); +static s32 _WADGetCidx(const ESContentMask* contentMask, u32 contentNumber); +static s32 _WADGetTransferId(void* transferId); +static void* _WADMemAlloc(MEMAllocator* allocator, u32 size); +static void _WADMemFree(MEMAllocator* allocator, void* buffer); +static s32 _WADCanImportFile(const WADFileHeader* fileHeader, u32 transferId, const void* fileNames, + const void* transferIdBuffer); +static void _WADFreeMemory(WADUnpackInfo* info, MEMAllocator* allocator); +static s32 WAD_815BFFA8(WADImportLoopArgs* args); +static s32 _WADBackupGetFiles(const char* path, u32 flags, MEMAllocator* allocator, + u32* fileCount, WADBackupFileHeader* files); +static s32 _WADBackupGetSize(u32 flags, ESTmdView* titleMeta, ESContentMask* contentMask, + u32 fileCount, WADBackupFileHeader* files, u32* titleMetaSize, + u32* contentDataSize, u32* totalSize); +static s32 _WADCheckContents(ESTmdView* titleMeta, ESContentMask* contentMask); +static void _WADRandPad(void* buffer, u32 size); +static s32 _WADVerifySavedataZD(WADSaveDataHeader* header, WADStream* stream, + MEMAllocator* allocator, u32 offset); +static void _WADCleanTmpDir(MEMAllocator* allocator); +u32 _WADIsTerminated(const char* text, u32 maxLength); + +extern s32 ES_GetBoot2Version(u32* version); +extern s32 SHA1Reset(void* context); +extern s32 SHA1Input(void* context, const void* data, u32 size); +extern s32 SHA1Result(void* context, void* digest); +extern char* strrchr(const char* string, int character); + +s32 WADGetTitleVersionEx(char* path, ESTitleId* titleId, u16* titleVersion, WADLocation location, u32 offset) { + BOOL streamOpened; + WADStream stream ALIGN32; + u8 headerBytes[0x20] ALIGN32; + WADTitleMetadata metadata ALIGN32; + s32 headerInfo; + WADTitleMetadata* metadataBuffer = &metadata; + WADHeader* headerBuffer = (WADHeader*)headerBytes; + s32 result; + u32 titleDataOffset; + s32 type; + + streamOpened = FALSE; + titleDataOffset = 0; + if (path == 0) { + result = -3000; + } else if ((offset & 0x3F) != 0) { + result = -3007; + } else { + result = WADOpenStream(location, path, &stream, 0, 0); + streamOpened = TRUE; + if (result == 0) { + result = WADReadStream(&stream, (void**)&headerBuffer, 0x20, offset); + if (result != 0x20) { + result = -3005; + goto done; + } + type = WAD_815C2F44(headerBuffer, &headerInfo); + if (type == 0) { + result = -3001; + goto done; + } + if (((type == 2) && (headerBuffer->tmdSize == 0)) || + ((type == 1) && (headerBuffer->ticketSize == 0))) { + result = -3002; + if (headerInfo == 2) { + titleDataOffset = 0x60; + } else { + goto done; + } + } + + if (titleDataOffset == 0) { + result = _WADGetTitleVer(headerBuffer, 0, 0, type, headerInfo); + if (result == 0) { + result = -3002; + goto done; + } + titleDataOffset = result + 0x180; + result = WADReadStream(&stream, (void**)&metadataBuffer, 0x80, + offset + titleDataOffset); + if ((u32)result != 0x80) { + result = -3005; + goto done; + } + result = 0; + if (titleId != 0) { + titleId[0] = metadataBuffer->tmd.titleId; + } + if (titleVersion != 0) { + *titleVersion = metadataBuffer->tmd.titleVersion; + } + } else { + result = WADReadStream(&stream, (void**)&metadataBuffer, 0x20, + offset + titleDataOffset); + if (result != 0x20) { + result = -3005; + goto done; + } + result = 0; + if (titleId != 0) { + *titleId = metadataBuffer->backupTitleId; + } + } + } + } + +done: + if (streamOpened) { + WADCloseStream(&stream); + } + return result; +} + +s32 WADCheckImport(ESTitleId titleId, u32 titleVersion) { + u16 installedVersion; + s32 result; + + if (__OSInIPL && (titleId == 0x0001000248414141ULL) && (titleVersion == 0xFF00)) { + return 0; + } + + result = WADGetInstalledVersion(titleId, &installedVersion); + if (result == -3002) { + return 1; + } + if (result == 0) { + if (__OSInIPL) { + if (titleVersion > installedVersion) { + return 1; + } + } else if (titleVersion >= installedVersion) { + return 1; + } + } + return 0; +} + +s32 WADGetInstalledVersion(ESTitleId titleId, u16* version) { + u32 tmdSize; + u32 installedVersion; + ESTmdView tmdView __attribute__((aligned(32))); + ESTmdView* viewBuffer = &tmdView; + s32 result; + + if (version == 0) { + return -3000; + } + if (titleId == 0x0000000100000001ULL) { + result = ES_GetBoot2Version(&installedVersion); + if (result == 0) { + *version = installedVersion; + } + return result; + } + + result = ES_GetTmdView(titleId, 0, &tmdSize); + if (result == -106) { + return -3002; + } + if (result != 0) { + return result; + } + if (tmdSize > sizeof(ESTmdView)) { + return -3000; + } + result = ES_GetTmdView(titleId, viewBuffer, &tmdSize); + if (result == 0) { + *version = viewBuffer->head.titleVersion; + } + return result; +} + +s32 WADImportGetBlocks(char* path, MEMAllocator* allocator, WADLocation location, u32 offset, u32 flags, + WADBlocks* blocks, u32* fileListOut) { + WADImportWorkspace workspace ALIGN32; + void* wadHeader = workspace.wadHeader; + s32 result; + u32 fileOffset; + void* allocatedFiles; + BOOL streamOpened; + u32 transferId; + u32 contentCount; + ESTitleMeta* titleMeta; + ESContentMeta* contentMeta; + u32 index; + + streamOpened = FALSE; + fileOffset = 0; + allocatedFiles = 0; + memset(&workspace.unpackInfo, 0, sizeof(WADUnpackInfo)); + if (fileListOut != 0) { + *fileListOut = 0; + } + if ((allocator == 0) || (allocator->heap == 0) || (path == 0) || (blocks == 0)) { + result = -3000; + } else if ((offset & 0x3F) != 0) { + result = -3007; + } else { + result = WADOpenStream(location, path, &workspace.stream, 0, 0); + streamOpened = TRUE; + if (result == 0) { + result = WADReadStream(&workspace.stream, &wadHeader, 0x80, offset); + if (result != 0x80) { + result = -3005; + } else { + result = _WADUnpack(wadHeader, &workspace.stream, &workspace.unpackInfo, allocator, + offset, flags & ~4, 1); + if (result == 0) { + memset(blocks, 0, sizeof(WADBlocks)); + titleMeta = workspace.unpackInfo.titleMeta; + if (titleMeta != 0) { + if ((flags & 4) == 0) { + blocks->unkBlocks += (workspace.unpackInfo.sectionSize + 0x3FFF) >> 14; + blocks->unkInodes = 1; + } + if (workspace.unpackInfo.cidxMode < 1) { + contentCount = titleMeta->head.numContents; + } else { + contentCount = _WADGetCidxCount(workspace.unpackInfo.contentIndex); + if (contentCount > titleMeta->head.numContents) { + result = -3001; + goto cleanup; + } + } + contentMeta = titleMeta->contents; + for (index = 0; index < contentCount; index++) { + if (workspace.unpackInfo.cidxMode >= 1) { + s32 selectedIndex = _WADGetCidx(workspace.unpackInfo.contentIndex, index); + if ((selectedIndex < 0) || + (titleMeta->head.numContents <= selectedIndex)) { + result = -3001; + goto cleanup; + } + contentMeta = titleMeta->contents + selectedIndex; + result = 0; + } + if ((contentMeta->type & 0x8000) == 0) { + blocks->privateInodes++; + blocks->privateBlocks += ((u32)contentMeta->size + 0x3FFF) >> 14; + } else { + blocks->sharedInodes++; + blocks->sharedBlocks += ((u32)contentMeta->size + 0x3FFF) >> 14; + } + contentMeta++; + } + } + if ((workspace.unpackInfo.fileListSize != 0) && + (workspace.unpackInfo.fileCount != 0)) { + transferId = _WADGetTransferId(workspace.transferId); + if ((fileListOut == 0) || + ((allocatedFiles = _WADMemAlloc(allocator, + workspace.unpackInfo.fileCount * 0x48)) != 0)) { + fileOffset = workspace.unpackInfo.fileOffset; + for (index = 0; index < workspace.unpackInfo.fileCount; index++) { + WADFileHeader* fileHeader = &workspace.fileHeader; + result = WADReadStream(&workspace.stream, (void**)&fileHeader, 0x80, + offset + fileOffset); + if (result != 0x80) { + result = -3005; + goto cleanup; + } + result = 0; + if (_WADCanImportFile(fileHeader, transferId, + workspace.unpackInfo.fileNames, + workspace.transferId) != 0) { + blocks->fileBlocks += (fileHeader->fileSize + 0x3FFF) >> 14; + if (fileListOut != 0) { + WADFileEntry* fileEntries = allocatedFiles; + fileEntries += blocks->fileInodes; + fileEntries->fileSize = fileHeader->fileSize; + fileEntries->flags[0] = fileHeader->flags[0]; + fileEntries->flags[1] = fileHeader->flags[1]; + fileEntries->flags[2] = fileHeader->flags[2]; + fileEntries->flags[3] = 0; + strncpy(fileEntries->name, fileHeader->name, 0x40); + } + blocks->fileInodes++; + } + fileOffset = ((fileOffset + WAD_STREAM_ALIGNMENT - 1) & + ~(WAD_STREAM_ALIGNMENT - 1)) + fileHeader->fileSize; + fileOffset = (fileOffset + WAD_STREAM_ALIGNMENT - 1) & + ~(WAD_STREAM_ALIGNMENT - 1); + } + if (fileListOut != 0) { + *fileListOut = (u32)allocatedFiles; + } + } else { + result = -3003; + } + } + } + } + } + } + +cleanup: + _WADFreeMemory(&workspace.unpackInfo, allocator); + if ((fileListOut != 0) && (result != 0)) { + if (allocatedFiles != 0) { + _WADMemFree(allocator, allocatedFiles); + } + *fileListOut = 0; + } + if (streamOpened) { + WADCloseStream(&workspace.stream); + } + return result; +} + +static s32 WAD_815BFFA8(WADImportLoopArgs* args) { + s32 fd = args->fd; + s32 result = 0; + u32 remaining = args->size; + u32 bufferIndex = 0; + WADImportTransfer* transfer = args->transfer; + + while ((remaining != 0) && (result == 0)) { + u32 size = remaining; + OSMutex* mutex; + + if (remaining > transfer->chunkSize) { + size = transfer->chunkSize; + } + mutex = &transfer->mutex[bufferIndex]; + OSLockMutex(mutex); + while (transfer->ready[bufferIndex] == 0) { + OSWaitCond(&transfer->signalCond[bufferIndex], mutex); + } + result = ES_ImportContentData(fd, transfer->buffers[bufferIndex], size); + transfer->ready[bufferIndex] = 0; + if (result != 0) { + transfer->error = 1; + } + OSUnlockMutex(mutex); + OSSignalCond(&transfer->waitCond[bufferIndex]); + remaining -= size; + bufferIndex ^= 1; + } + return result; +} + +s32 WADImportEx(char* path, MEMAllocator* allocator, WADLocation location, u32 offset, u32 flags, + WADProcessCallback processCallback) { + WADImportWorkspace workspace ALIGN32; + WADSaveDataHeader wadHeader ALIGN32; + WADFileHeader backupHeader ALIGN32; + WADImportTransfer transfer; + WADImportLoopArgs threadArgs; + OSThread importThread; + NANDFileInfo backupFile; + NANDStatus fileStatus; + NANDStatus updatedFileStatus; + ESContentId* installedContentIds = 0; + ESTitleMeta* installedTitleMeta = 0; + ESContentMeta* matchingContents = 0; + ESHash* sharedContentHashes = 0; + void* firstBuffer = 0; + void* secondBuffer = 0; + WADThreadStack* threadStack = 0; + void* wadHeaderBuffer = &wadHeader; + void* fileHeaderBuffer = &backupHeader; + u8 transferId[0x20] ALIGN32; + u32 fileOffset = 0; + u32 importedBytes = 0; + u32 installedContentCount = 0; + u32 installedTmdSize = 0; + u32 sharedContentCount = 0; + u32 contentCount = 0; + u32 contentIndex; + u32 listIndex; + u32 sizeRemaining; + u32 transferIdValue; + s32 result = 0; + s32 streamOpened = FALSE; + s32 backupFileOpened = FALSE; + s32 titleImportStarted = FALSE; + s32 contentImportStarted = FALSE; + s32 threadCreated = FALSE; + s32 contentFd = 0; + s32 importExistingTitle = TRUE; + s32 existingTmdAvailable = FALSE; + s32 fileReadResult; + u32 importedContentCount = 0; + u32 bufferIndex = 0; + u32 callbackTotal = 0; + u32 installedContentIndex = 0; + u32 sharedContentIndex; + u32 contentFileOffset; + u32 pathFileIndex; + s32 matchFound; + s32 listResult; + s32 titleVersion; + u32 contentSize; + u32 chunkSize; + u32 readSize; + u32 bootSize; + u32 alignedSize; + u32 callbackDone; + u32 currentTitleId; + u32 currentTitleVersion; + u32 currentContentId; + u32 importedFileCount; + u32 savedataFileIndex; + s32 importResult; + u32 threadPriority; + const char* functionName = "WADImportEx"; + + memset(&workspace.unpackInfo, 0, sizeof(WADUnpackInfo)); + memset(&transfer, 0, sizeof(transfer)); + if ((path == 0) || (allocator == 0) || (allocator->heap == 0)) { + result = -3000; + goto cleanup; + } + if ((offset & 0x3F) != 0) { + result = -3007; + goto cleanup; + } + if (processCallback != 0) { + processCallback(0, 0, FALSE); + } + result = WADOpenStream(location, path, &workspace.stream, 0, 0); + streamOpened = TRUE; + if (result != 0) { + goto cleanup; + } + result = WADReadStream(&workspace.stream, &wadHeaderBuffer, sizeof(wadHeader), offset); + if (result != sizeof(wadHeader)) { + result = -3005; + goto cleanup; + } + result = _WADUnpack(&wadHeader, &workspace.stream, &workspace.unpackInfo, allocator, offset, + flags, 0); + if (result != 0) { + goto cleanup; + } + importedBytes = workspace.unpackInfo.contentOffset; + callbackTotal = workspace.unpackInfo.contentSize + workspace.unpackInfo.fileListSize; + if (((flags & 8) != 0) && (workspace.unpackInfo.titleMeta != 0)) { + if (workspace.unpackInfo.headerInfo != 2) { + result = -3001; + goto cleanup; + } + result = ES_GetTicketViews(workspace.unpackInfo.titleMeta->head.titleId, 0, + &installedContentCount); + if (result != 0) { + goto cleanup; + } + if (installedContentCount == 0) { + result = -1028; + goto cleanup; + } + } + if ((workspace.unpackInfo.titleMeta != 0) && + (((workspace.unpackInfo.size_0x18 == 1) && + (workspace.unpackInfo.size_0x0c == 1)) || + (workspace.unpackInfo.headerInfo == 3))) { + bootSize = (workspace.unpackInfo.titleMetaSize + 0x0F) & ~0x0F; + alignedSize = (bootSize + 0x1F) & ~0x1F; + firstBuffer = _WADMemAlloc(allocator, alignedSize); + if (firstBuffer == 0) { + result = -3003; + goto cleanup; + } + result = WADReadStream(&workspace.stream, &firstBuffer, alignedSize, + offset + importedBytes); + if ((u32)result != alignedSize) { + result = -3005; + goto cleanup; + } + result = ES_ImportBoot(workspace.unpackInfo.buffer_0x34, + workspace.unpackInfo.buffer_0x14, + workspace.unpackInfo.size_0x0c, + workspace.unpackInfo.titleMeta, + workspace.unpackInfo.sectionSize, + workspace.unpackInfo.buffer_0x14, + workspace.unpackInfo.size_0x0c, + workspace.unpackInfo.buffer_0x24, + workspace.unpackInfo.size_0x1c, firstBuffer, + workspace.unpackInfo.titleMetaSize); + goto cleanup; + } + if ((workspace.unpackInfo.titleMeta != 0) && + (workspace.unpackInfo.buffer_0x34 != 0)) { + result = ES_ImportTicket(workspace.unpackInfo.buffer_0x34, + workspace.unpackInfo.buffer_0x14, + workspace.unpackInfo.size_0x0c, + workspace.unpackInfo.buffer_0x24, + workspace.unpackInfo.size_0x1c, 0); + if (result != 0) { + goto cleanup; + } + } + if (processCallback != 0) { + processCallback(0, callbackTotal, FALSE); + } + if (workspace.unpackInfo.titleMeta != 0) { + if (workspace.unpackInfo.cidxMode == 0) { + contentCount = workspace.unpackInfo.titleMeta->head.numContents; + } else { + contentCount = _WADGetCidxCount(workspace.unpackInfo.contentIndex); + if (workspace.unpackInfo.titleMeta->head.numContents < contentCount) { + result = -3001; + goto cleanup; + } + } + result = ES_ListTmdContentsOnCard(workspace.unpackInfo.titleMeta, + workspace.unpackInfo.sectionSize, 0, + &installedContentCount); + if ((result == 0) && (installedContentCount != 0)) { + installedContentIds = _WADMemAlloc(allocator, installedContentCount * sizeof(ESContentId)); + if (installedContentIds == 0) { + result = -3003; + goto cleanup; + } + result = ES_ListTmdContentsOnCard(workspace.unpackInfo.titleMeta, + workspace.unpackInfo.sectionSize, + installedContentIds, &installedContentCount); + if ((result == 0) && + (ES_GetTmd(workspace.unpackInfo.titleMeta->head.titleId, 0, + &installedTmdSize) == 0)) { + alignedSize = (installedTmdSize + 0x1F) & ~0x1F; + installedTitleMeta = _WADMemAlloc(allocator, alignedSize); + if (installedTitleMeta == 0) { + result = -3003; + goto cleanup; + } + result = ES_GetTmd(workspace.unpackInfo.titleMeta->head.titleId, + installedTitleMeta, &installedTmdSize); + if (result == 0) { + importExistingTitle = FALSE; + } + } + } + if (!importExistingTitle && (installedContentCount != 0)) { + matchingContents = _WADMemAlloc(allocator, installedContentCount * sizeof(ESContentMeta)); + if (matchingContents == 0) { + result = -3003; + goto cleanup; + } + installedContentIndex = 0; + for (listIndex = 0; listIndex < installedContentCount; listIndex++) { + for (contentIndex = 0; + contentIndex < installedTitleMeta->head.numContents; contentIndex++) { + if (installedContentIds[listIndex] == + installedTitleMeta->contents[contentIndex].cid) { + memcpy(&matchingContents[installedContentIndex], + &installedTitleMeta->contents[contentIndex], sizeof(ESContentMeta)); + installedContentIndex++; + } + } + } + } + result = ES_ListSharedContents(&sharedContentCount, 0); + if (result == 0) { + alignedSize = (sharedContentCount * sizeof(ESHash) + 0x1F) & ~0x1F; + sharedContentHashes = _WADMemAlloc(allocator, alignedSize); + if ((sharedContentHashes == 0) && (sharedContentCount != 0)) { + result = -3003; + goto cleanup; + } + result = ES_ListSharedContents(&sharedContentCount, sharedContentHashes); + if ((result != 0) && (sharedContentHashes != 0)) { + _WADMemFree(allocator, sharedContentHashes); + sharedContentHashes = 0; + } + } + result = ES_ImportTitleInit(workspace.unpackInfo.titleMeta, + workspace.unpackInfo.sectionSize, + workspace.unpackInfo.buffer_0x14, + workspace.unpackInfo.size_0x0c, + workspace.unpackInfo.buffer_0x24, + workspace.unpackInfo.size_0x1c, + workspace.unpackInfo.headerInfo, 1); + if (result != 0) { + goto cleanup; + } + titleImportStarted = TRUE; + if ((flags & 2) == 0) { + for (contentIndex = 0; contentIndex < contentCount; contentIndex++) { + ESContentMeta* content; + s32 titleMetaIndex = contentIndex; + matchFound = FALSE; + if (workspace.unpackInfo.cidxMode != 0) { + titleMetaIndex = _WADGetCidx(workspace.unpackInfo.contentIndex, contentIndex); + if ((titleMetaIndex < 0) || + ((s32)workspace.unpackInfo.titleMeta->head.numContents <= titleMetaIndex)) { + result = -3001; + goto cleanup; + } + } + content = &workspace.unpackInfo.titleMeta->contents[titleMetaIndex]; + if (!importExistingTitle) { + for (listIndex = 0; listIndex < installedContentCount; listIndex++) { + ESContentMeta* installedContent = &matchingContents[listIndex]; + if ((content->cid == installedContent->cid) && + (memcmp(content->hash, installedContent->hash, sizeof(ESHash)) == 0) && + (content->type == installedContent->type)) { + matchFound = TRUE; + } + } + } + if (((content->type & 0x8000) != 0) && + (sharedContentHashes != 0) && !matchFound) { + for (sharedContentIndex = 0; sharedContentIndex < sharedContentCount; + sharedContentIndex++) { + if (memcmp(content->hash, sharedContentHashes[sharedContentIndex], + sizeof(ESHash)) == 0) { + matchFound = TRUE; + } + } + } + if (matchFound) { + importedBytes += (content->size + 0x0F) & ~0x0F; + if (processCallback != 0) { + processCallback(importedBytes - workspace.unpackInfo.contentOffset, + callbackTotal, FALSE); + } + } else { + if (firstBuffer == 0) { + firstBuffer = _WADMemAlloc(allocator, 0x10000); + if (firstBuffer == 0) { + result = -3003; + goto cleanup; + } + } + if (secondBuffer == 0) { + secondBuffer = _WADMemAlloc(allocator, 0x10000); + if (secondBuffer == 0) { + result = -3003; + goto cleanup; + } + } + if (threadStack == 0) { + threadStack = _WADMemAlloc(allocator, sizeof(WADThreadStack)); + if (threadStack == 0) { + result = -3003; + goto cleanup; + } + } + if ((firstBuffer == 0) || (secondBuffer == 0) || (threadStack == 0)) { + result = -3003; + goto cleanup; + } + contentFd = ES_ImportContentBegin( + workspace.unpackInfo.titleMeta->head.titleId, content->cid); + result = contentFd; + if (contentFd < 0) { + goto cleanup; + } + contentImportStarted = TRUE; + sizeRemaining = (content->size + 0x0F) & ~0x0F; + WAD_815C4A2C(&transfer, firstBuffer, secondBuffer, 0x10000); + threadArgs.fd = contentFd; + threadArgs.transfer = &transfer; + threadArgs.size = sizeRemaining; + threadPriority = OSGetThreadPriority(OSGetCurrentThread()); + threadCreated = OSCreateThread(&importThread, + (void* (*)(void*))WAD_815BFFA8, + &threadArgs, + &threadStack->bytes[sizeof(threadStack->bytes)], + sizeof(threadStack->bytes), + threadPriority, 0); + if (!threadCreated) { + result = -3009; + goto cleanup; + } + OSResumeThread(&importThread); + transfer.error = 0; + bufferIndex = 0; + while ((sizeRemaining != 0) && (transfer.error == 0)) { + chunkSize = sizeRemaining; + if (transfer.chunkSize < chunkSize) { + chunkSize = transfer.chunkSize; + } + OSLockMutex(&transfer.mutex[bufferIndex]); + while ((transfer.ready[bufferIndex] != 0) && + (transfer.error == 0)) { + OSWaitCond(&transfer.waitCond[bufferIndex], + &transfer.mutex[bufferIndex]); + } + if (transfer.error != 0) { + break; + } + readSize = (chunkSize + 0x1F) & ~0x1F; + result = WADReadStream(&workspace.stream, + &transfer.buffers[bufferIndex], readSize, + offset + importedBytes); + if ((u32)result != readSize) { + OSLockMutex(&transfer.mutex[bufferIndex ^ 1]); + OSCancelThread(&importThread); + OSJoinThread(&importThread, 0); + OSUnlockMutex(&transfer.mutex[bufferIndex ^ 1]); + OSUnlockMutex(&transfer.mutex[bufferIndex]); + result = -3005; + goto cleanup; + } + transfer.ready[bufferIndex] = chunkSize; + OSUnlockMutex(&transfer.mutex[bufferIndex]); + OSSignalCond(&transfer.signalCond[bufferIndex]); + importedBytes += chunkSize; + sizeRemaining -= chunkSize; + if (processCallback != 0) { + processCallback(importedBytes - workspace.unpackInfo.contentOffset, + callbackTotal, FALSE); + } + bufferIndex ^= 1; + } + if (threadCreated) { + importResult = OSJoinThread(&importThread, (void**)&result); + if (!importResult) { + result = -3009; + goto cleanup; + } + threadCreated = FALSE; + } + if ((result != 0) || (transfer.error != 0)) { + goto cleanup; + } + result = ES_ImportContentEnd(contentFd); + if (result != 0) { + goto cleanup; + } + contentImportStarted = FALSE; + } + if (workspace.unpackInfo.type == 2) { + importedBytes = (importedBytes + 0x3F) & ~0x3F; + } + } + } + result = ES_ImportTitleDone(); + if (result != 0) { + goto cleanup; + } + titleImportStarted = FALSE; + } + if (((flags & 2) != 0) || (workspace.unpackInfo.fileListSize == 0) || + (workspace.unpackInfo.fileCount == 0)) { + goto cleanup; + } + if (firstBuffer == 0) { + firstBuffer = _WADMemAlloc(allocator, 0x10000); + if (firstBuffer == 0) { + result = -3003; + goto cleanup; + } + } + if (secondBuffer == 0) { + secondBuffer = _WADMemAlloc(allocator, 0x10000); + if (secondBuffer == 0) { + result = -3003; + goto cleanup; + } + } + transferIdValue = _WADGetTransferId(transferId); + fileOffset = workspace.unpackInfo.fileOffset; + if (((wadHeader.magic & 0xFFFFFF00) == 0x525A4400) && + (wadHeader.fileSize == 0x10000)) { + result = _WADVerifySavedataZD(&wadHeader, &workspace.stream, allocator, + offset + workspace.unpackInfo.fileOffset); + goto cleanup; + } + for (pathFileIndex = 0; pathFileIndex < workspace.unpackInfo.fileCount; pathFileIndex++) { + result = WADReadStream(&workspace.stream, &fileHeaderBuffer, sizeof(backupHeader), + offset + fileOffset); + if (result != sizeof(backupHeader)) { + result = -3005; + goto cleanup; + } + fileOffset = (fileOffset + 0xBF) & ~0x3F; + if (backupHeader.magic != 0x3ADF17E) { + result = -3000; + goto cleanup; + } + result = 0; + if (_WADCanImportFile(&backupHeader, transferIdValue, + workspace.unpackInfo.fileNames, transferId) == 0) { + if ((backupHeader.flags[2] == 1) && (backupHeader.fileSize != 0)) { + fileOffset = (fileOffset + backupHeader.fileSize + 0x3F) & + ~0x3F; + } + continue; + } + if (backupHeader.flags[2] == 1) { + result = NANDPrivateCreate(backupHeader.name, backupHeader.flags[0] | 0x20, + backupHeader.flags[1]); + if (result != 0) { + goto cleanup; + } + if (backupHeader.fileSize != 0) { + result = NANDPrivateOpen(backupHeader.name, &backupFile, 2); + if (result != 0) { + goto cleanup; + } + backupFileOpened = TRUE; + sizeRemaining = backupHeader.fileSize; + while (sizeRemaining != 0) { + chunkSize = sizeRemaining; + if (chunkSize > 0x10000) { + chunkSize = 0x10000; + } + result = WADReadStream(&workspace.stream, &firstBuffer, + (chunkSize + 0x1F) & ~0x1F, + offset + fileOffset); + readSize = (chunkSize + 0x1F) & ~0x1F; + if ((u32)result != readSize) { + result = -3005; + goto cleanup; + } + result = ES_Decrypt(6, backupHeader.iv, + firstBuffer, readSize, secondBuffer); + if (result != 0) { + goto cleanup; + } + result = NANDWrite(&backupFile, secondBuffer, chunkSize); + if ((u32)result != chunkSize) { + result = -3006; + goto cleanup; + } + importedBytes += chunkSize; + sizeRemaining -= chunkSize; + if (processCallback != 0) { + processCallback(workspace.unpackInfo.fileListSize + + importedBytes - workspace.unpackInfo.fileOffset, + callbackTotal, FALSE); + } + fileOffset += chunkSize; + } + result = NANDClose(&backupFile); + if (result != 0) { + goto cleanup; + } + backupFileOpened = FALSE; + } + if ((backupHeader.flags[0] & 0x20) == 0) { + result = NANDPrivateGetStatus(backupHeader.name, &fileStatus); + if (result != 0) { + goto cleanup; + } + updatedFileStatus = fileStatus; + updatedFileStatus.permission = backupHeader.flags[0]; + updatedFileStatus.attribute = backupHeader.flags[1]; + result = NANDPrivateSetStatus(backupHeader.name, &updatedFileStatus); + if (result != 0) { + goto cleanup; + } + } + } else if (backupHeader.flags[2] == 2) { + result = NANDPrivateCreateDir(backupHeader.name, + backupHeader.flags[0] | 0x20, + backupHeader.flags[1]); + if (result != -6) { + if (result != 0) { + goto cleanup; + } + } else { + result = NANDPrivateGetStatus(backupHeader.name, &fileStatus); + if (result != 0) { + goto cleanup; + } + if ((fileStatus.permission & 0x20) == 0) { + fileStatus.permission = backupHeader.flags[0] | 0x20; + fileStatus.attribute = backupHeader.flags[1]; + result = NANDPrivateSetStatus(backupHeader.name, &fileStatus); + if (result != 0) { + goto cleanup; + } + } + } + } + fileOffset = (fileOffset + 0x3F) & ~0x3F; + if ((backupHeader.fileSize == 0) && (processCallback != 0)) { + processCallback(workspace.unpackInfo.fileListSize + + importedBytes - workspace.unpackInfo.fileOffset, + callbackTotal, FALSE); + } + fileOffset += backupHeader.fileSize; + fileOffset = (fileOffset + 0x3F) & ~0x3F; + } + fileOffset = workspace.unpackInfo.fileOffset; + for (savedataFileIndex = 0; savedataFileIndex < workspace.unpackInfo.fileCount; + savedataFileIndex++) { + fileReadResult = WADReadStream(&workspace.stream, &fileHeaderBuffer, + sizeof(backupHeader), + offset + fileOffset); + if (fileReadResult != sizeof(backupHeader)) { + result = -3005; + break; + } + result = 0; + fileOffset = (fileOffset + 0xBF) & ~0x3F; + if ((_WADCanImportFile(&backupHeader, transferIdValue, + workspace.unpackInfo.fileNames, transferId) != 0) && + (((result = NANDPrivateGetStatus(backupHeader.name, &fileStatus)) != + 0) || + ((backupHeader.flags[0] & 0x20) == 0 && + ((fileStatus.permission = backupHeader.flags[0]), + (result = NANDPrivateSetStatus(backupHeader.name, &fileStatus)) != + 0)))) { + break; + } + fileOffset = (fileOffset + backupHeader.fileSize + 0x3F) & ~0x3F; + } + +cleanup: + _WADFreeMemory(&workspace.unpackInfo, allocator); + if (firstBuffer != 0) { + _WADMemFree(allocator, firstBuffer); + } + if (secondBuffer != 0) { + _WADMemFree(allocator, secondBuffer); + } + if (installedTitleMeta != 0) { + _WADMemFree(allocator, installedTitleMeta); + } + if (installedContentIds != 0) { + _WADMemFree(allocator, installedContentIds); + } + if (matchingContents != 0) { + _WADMemFree(allocator, matchingContents); + } + if (sharedContentHashes != 0) { + _WADMemFree(allocator, sharedContentHashes); + } + if (threadStack != 0) { + _WADMemFree(allocator, threadStack); + } + if (backupFileOpened) { + NANDClose(&backupFile); + } + if (streamOpened) { + WADCloseStream(&workspace.stream); + } + if (contentImportStarted) { + ES_ImportContentEnd(contentFd); + OSReport("%s:%d Cancel importing the content.\n", functionName, 0x8DF); + } + if (titleImportStarted) { + ES_ImportTitleCancel(); + _WADCleanTmpDir(allocator); + OSReport("%s:%d Cancel importing the title.\n", functionName, 0x8E6); + } + if (processCallback != 0) { + if (importedBytes == 0) { + processCallback(0, 0, TRUE); + } else if ((callbackTotal == 0) || (workspace.unpackInfo.fileCount == 0)) { + processCallback(importedBytes - workspace.unpackInfo.contentOffset, callbackTotal, + TRUE); + } else { + processCallback(workspace.unpackInfo.fileListSize + + importedBytes - workspace.unpackInfo.fileOffset, + callbackTotal, TRUE); + } + } + return result; +} + +static s32 WAD_815C1288(WADExportLoopArgs* args) { + s32 result; + u32 remaining; + u32 bufferIndex; + ESFd fd; + WADImportTransfer* transfer; + u32 size; + OSMutex* mutex; + + fd = args->fd; + result = 0; + remaining = args->size; + bufferIndex = 0; + transfer = args->transfer; + + while ((remaining != 0) && (result == 0)) { + size = remaining; + + if (remaining > transfer->chunkSize) { + size = transfer->chunkSize; + } + mutex = &transfer->mutex[bufferIndex]; + OSLockMutex(mutex); + while (transfer->ready[bufferIndex] != 0) { + OSWaitCond(&transfer->waitCond[bufferIndex], mutex); + } + result = ES_ExportContentData(fd, transfer->buffers[bufferIndex], size); + transfer->ready[bufferIndex] = size; + if (result != 0) { + transfer->error = 1; + } + OSUnlockMutex(mutex); + OSSignalCond(&transfer->signalCond[bufferIndex]); + remaining -= size; + bufferIndex ^= 1; + } + return result; +} + +s32 WADBackupEx(u64 titleId, u32 ticketId, MEMAllocator* allocator, char* path, u32* sizeOut, + WADLocation location, u32 offset, WADProcessCallback processCallback) { + WADBackupTitleMetaBuffer* titleMetaBuffer = 0; + ESTmdView* titleMeta = 0; + WADBackupFileHeader* files = 0; + WADStream stream ALIGN32; + WADImportTransfer transfer; + WADExportLoopArgs threadArgs; + OSThread exportThread; + NANDFileInfo savedFile ALIGN32; + WADBackupHeaderBlock headerBlock ALIGN32; + ESContentMask existingContentMask ALIGN32; + ESContentId installedContentIds[520] ALIGN32; + u8 hashContext[0xC0] ALIGN32; + u8 digest[0x40] ALIGN32; + u8 signature[0x40] ALIGN32; + u8 deviceCertificate[0x180] ALIGN32; + ESCertSignature signerCertificate ALIGN32; + u8 encryptionIv[0x10] ALIGN32; + void* outputBuffer = 0; + void* encryptionBuffer = 0; + WADThreadStack* threadStack = 0; + u32 flags = ticketId; + u32 titleMetaSize = 0; + u32 contentDataSize = 0; + u32 fileDataSize = 0; + u32 fileCount = 0; + u32 installedContentCount = 0; + u32 currentContentCount = 0; + u32 fileIndex; + u32 contentIndex; + u32 importedSize = 0; + u32 paddedSize; + u32 transferId = 0; + u32 totalSize; + u32 priority; + u32 sizeRemaining; + u32 bufferIndex; + u32 chunkSize; + u32 readSize; + s32 result = 0; + s32 streamOpened = FALSE; + s32 titleExportStarted = FALSE; + s32 contentExportStarted = FALSE; + s32 threadCreated = FALSE; + s32 fileOpened = FALSE; + s32 fileFd; + u32 callbackDone = 0; + + if (flags == 0) { + flags = 0x0F; + } + memset(&transfer, 0, sizeof(transfer)); + memset(&headerBlock, 0, sizeof(headerBlock)); + memset(&existingContentMask, 0, sizeof(existingContentMask)); + memset(encryptionIv, 0, sizeof(encryptionIv)); + if (((flags & 3) == 0) || ((u32)(titleId >> 32) == 1) || + (allocator == 0) || (sizeOut == 0)) { + result = -3000; + goto cleanup; + } + if ((offset & 0x3F) != 0) { + result = -3007; + goto cleanup; + } + if (processCallback != 0) { + processCallback(0, 0, FALSE); + } + if (((flags & 1) != 0) || ((flags & 0x20) != 0)) { + result = ES_GetTmdView(titleId, 0, &titleMetaSize); + if (result != 0) { + goto cleanup; + } + titleMetaBuffer = _WADMemAlloc(allocator, sizeof(WADBackupTitleMetaBuffer)); + if (titleMetaBuffer == 0) { + result = -3003; + goto cleanup; + } + titleMeta = &titleMetaBuffer->view; + result = ES_GetTmdView(titleId, titleMeta, &titleMetaSize); + if (result != 0) { + goto cleanup; + } + } + if ((flags & 1) != 0) { + result = ES_ListTitleContentsOnCard(titleId, 0, &installedContentCount); + if (result == -106) { + result = -3002; + goto cleanup; + } + if ((result != 0) || (installedContentCount == 0)) { + result = -3002; + goto cleanup; + } + result = ES_ListTitleContentsOnCard(titleId, installedContentIds, + &installedContentCount); + if (result != 0) { + goto cleanup; + } + result = _WADCheckContents(titleMeta, &existingContentMask); + if (result != 0) { + goto cleanup; + } + } + if ((flags & 2) != 0) { + char currentDirectory[NAND_MAX_PATH] ALIGN32; + result = NANDGetCurrentDir(currentDirectory); + if (result != 0) { + goto cleanup; + } + result = _WADBackupGetFiles(0, flags, allocator, &fileCount, 0); + if (result != 0) { + goto cleanup; + } + if (fileCount != 0) { + files = _WADMemAlloc(allocator, fileCount * sizeof(WADBackupFileHeader)); + if (files == 0) { + result = -3003; + goto cleanup; + } + result = _WADBackupGetFiles(0, flags, allocator, &fileCount, files); + if (result != 0) { + goto cleanup; + } + } + } + result = _WADBackupGetSize(flags, titleMeta, &existingContentMask, fileCount, files, + &titleMetaSize, &contentDataSize, &fileDataSize); + if (result != 0) { + goto cleanup; + } + if ((contentDataSize == 0) && (fileDataSize == 0)) { + result = -3002; + goto cleanup; + } + totalSize = titleMetaSize + contentDataSize + fileDataSize + 0x340; + if (path == 0) { + *sizeOut = totalSize; + result = 0; + goto cleanup; + } + outputBuffer = _WADMemAlloc(allocator, 0x10000); + if (outputBuffer == 0) { + result = -3003; + goto cleanup; + } + if (processCallback != 0) { + processCallback(0, contentDataSize + fileDataSize, FALSE); + } + result = WADOpenStream(location, path, &stream, 1, offset); + streamOpened = TRUE; + if (result != 0) { + goto cleanup; + } + headerBlock.header.hdrSize = sizeof(WADBackupHeader); + headerBlock.header.wadType[0] = 'B'; + headerBlock.header.wadType[1] = 'k'; + headerBlock.header.wadVersion = 1; + headerBlock.header.numFiles = fileCount; + headerBlock.header.fileSize = fileDataSize; + headerBlock.header.tmdSize = titleMetaSize; + headerBlock.header.contentSize = contentDataSize; + headerBlock.header.backupAreaLen = titleMetaSize + contentDataSize + fileDataSize; + headerBlock.header.titleId = titleId; + result = ES_GetDeviceId(&headerBlock.header.deviceId); + if (result != 0) { + goto cleanup; + } + if ((flags & 1) != 0) { + headerBlock.header.cidx = existingContentMask; + } + result = WADWriteStream(&stream, &headerBlock, sizeof(headerBlock)); + if (result != sizeof(headerBlock)) { + result = -3006; + goto cleanup; + } + importedSize = sizeof(headerBlock); + result = SHA1Reset(hashContext); + if (result != 0) { + goto cleanup; + } + result = SHA1Input(hashContext, &headerBlock, sizeof(headerBlock)); + if (result != 0) { + goto cleanup; + } + srand(ticketId); + if (((flags & 1) != 0) || ((flags & 0x20) != 0)) { + result = ES_ExportTitleInit(titleId, headerBlock.header.deviceId, 0, (void*)2, 0, 0, 0, + 0, 0, 0, 0); + if (result != 0) { + goto cleanup; + } + titleExportStarted = TRUE; + paddedSize = (titleMetaSize + 0x3F) & ~0x3F; + _WADRandPad(&titleMetaBuffer->data[titleMetaSize], + paddedSize - titleMetaSize); + result = SHA1Input(hashContext, titleMeta, paddedSize); + if (result != 0) { + goto cleanup; + } + result = WADWriteStream(&stream, titleMeta, paddedSize); + if ((u32)result != paddedSize) { + result = -3006; + goto cleanup; + } + importedSize += paddedSize; + } + if ((flags & 1) != 0) { + encryptionBuffer = _WADMemAlloc(allocator, 0x10000); + if (encryptionBuffer == 0) { + result = -3003; + goto cleanup; + } + threadStack = _WADMemAlloc(allocator, sizeof(WADThreadStack)); + if (threadStack == 0) { + result = -3003; + goto cleanup; + } + currentContentCount = _WADGetCidxCount(&existingContentMask); + for (contentIndex = 0; contentIndex < currentContentCount; contentIndex++) { + s32 tmdIndex = _WADGetCidx(&existingContentMask, contentIndex); + ESContentMeta* content; + if ((tmdIndex < 0) || (titleMeta->head.numContents <= tmdIndex)) { + result = -3009; + goto cleanup; + } + content = (ESContentMeta*)&titleMeta->contents[tmdIndex]; + fileFd = ES_ExportContentBegin(titleId, content->cid); + result = fileFd; + if (fileFd < 0) { + goto cleanup; + } + contentExportStarted = TRUE; + sizeRemaining = (content->size + 0x0F) & ~0x0F; + WAD_815C4A2C(&transfer, outputBuffer, encryptionBuffer, 0x10000); + threadArgs.fd = fileFd; + threadArgs.size = sizeRemaining; + threadArgs.transfer = &transfer; + priority = OSGetThreadPriority(OSGetCurrentThread()); + threadCreated = OSCreateThread(&exportThread, (void* (*)(void*))WAD_815C1288, + &threadArgs, + &threadStack->bytes[sizeof(threadStack->bytes)], + sizeof(threadStack->bytes), + priority, 0); + if (!threadCreated) { + result = -3009; + goto cleanup; + } + OSResumeThread(&exportThread); + sizeRemaining = (sizeRemaining + 0x3F) & ~0x3F; + bufferIndex = 0; + while ((sizeRemaining != 0) && (transfer.error == 0)) { + chunkSize = sizeRemaining; + if (transfer.chunkSize < chunkSize) { + chunkSize = transfer.chunkSize; + } + OSLockMutex(&transfer.mutex[bufferIndex]); + while ((transfer.ready[bufferIndex] == 0) && (transfer.error == 0)) { + OSWaitCond(&transfer.waitCond[bufferIndex], &transfer.mutex[bufferIndex]); + } + if (transfer.error != 0) { + break; + } + readSize = (chunkSize + 0x3F) & ~0x3F; + if (readSize > chunkSize) { + _WADRandPad((u8*)transfer.buffers[bufferIndex] + chunkSize, + readSize - chunkSize); + } + result = SHA1Input(hashContext, transfer.buffers[bufferIndex], chunkSize); + if (result != 0) { + goto cleanup; + } + result = WADWriteStream(&stream, transfer.buffers[bufferIndex], chunkSize); + if ((u32)result != chunkSize) { + OSLockMutex(&transfer.mutex[bufferIndex ^ 1]); + OSCancelThread(&exportThread); + OSJoinThread(&exportThread, 0); + OSUnlockMutex(&transfer.mutex[bufferIndex ^ 1]); + OSUnlockMutex(&transfer.mutex[bufferIndex]); + result = -3006; + goto cleanup; + } + transfer.ready[bufferIndex] = 0; + OSUnlockMutex(&transfer.mutex[bufferIndex]); + OSSignalCond(&transfer.signalCond[bufferIndex]); + importedSize += chunkSize; + sizeRemaining -= chunkSize; + if (processCallback != 0) { + processCallback(importedSize, contentDataSize + fileDataSize, FALSE); + } + bufferIndex ^= 1; + } + if (threadCreated) { + result = OSJoinThread(&exportThread, (void**)&fileFd); + threadCreated = FALSE; + if (result == 0) { + result = -3009; + goto cleanup; + } + } + if (fileFd < 0) { + result = fileFd; + goto cleanup; + } + result = ES_ExportContentEnd(fileFd); + contentExportStarted = FALSE; + if (result != 0) { + goto cleanup; + } + } + } + if (titleExportStarted) { + result = ES_ExportTitleDone(); + titleExportStarted = FALSE; + if (result != 0) { + goto cleanup; + } + } + if ((flags & 2) != 0) { + for (fileIndex = 0; fileIndex < fileCount; fileIndex++) { + WADBackupFileHeader* file = &files[fileIndex]; + s32 filePosition = WADSeekStream(&stream, 0, 1); + size_t nameLength = strlen(file->path); + _WADRandPad(file->path + nameLength + 1, + 0x75 - (nameLength + 1)); + result = SHA1Input(hashContext, file, sizeof(WADBackupHeaderBlock)); + if (result != 0) { + goto cleanup; + } + result = WADWriteStream(&stream, file, sizeof(WADBackupHeaderBlock)); + if (result != sizeof(WADBackupHeaderBlock)) { + result = -3006; + goto cleanup; + } + importedSize += sizeof(WADBackupHeaderBlock); + if (processCallback != 0) { + processCallback(importedSize, contentDataSize + fileDataSize, FALSE); + } + if ((file->flags[2] == 1) && (file->fileSize != 0)) { + result = NANDPrivateOpen(file->path, &savedFile, 1); + if (result != 0) { + goto cleanup; + } + fileOpened = TRUE; + sizeRemaining = (file->fileSize + 0x1F) & ~0x1F; + while (sizeRemaining != 0) { + chunkSize = sizeRemaining; + if (chunkSize > 0x10000) { + chunkSize = 0x10000; + } + readSize = NANDRead(&savedFile, outputBuffer, chunkSize); + if (((readSize + 0x1F) & ~0x1F) != chunkSize) { + result = -3005; + goto cleanup; + } + result = ES_Encrypt(6, encryptionIv, outputBuffer, chunkSize, + encryptionBuffer); + if (result != 0) { + goto cleanup; + } + result = SHA1Input(hashContext, encryptionBuffer, chunkSize); + if (result != 0) { + goto cleanup; + } + result = WADWriteStream(&stream, encryptionBuffer, chunkSize); + if ((u32)result != chunkSize) { + result = -3006; + goto cleanup; + } + importedSize += chunkSize; + sizeRemaining -= chunkSize; + if (processCallback != 0) { + processCallback(importedSize, contentDataSize + fileDataSize, FALSE); + } + } + result = NANDClose(&savedFile); + fileOpened = FALSE; + if (result != 0) { + goto cleanup; + } + paddedSize = (file->fileSize + 0x3F) & ~0x3F; + if (paddedSize > file->fileSize) { + _WADRandPad(encryptionBuffer, paddedSize - file->fileSize); + result = SHA1Input(hashContext, encryptionBuffer, + paddedSize - file->fileSize); + if (result != 0) { + goto cleanup; + } + result = WADWriteStream(&stream, encryptionBuffer, + paddedSize - file->fileSize); + if ((u32)result != paddedSize - file->fileSize) { + result = -3006; + goto cleanup; + } + importedSize += paddedSize - file->fileSize; + } + } + if (filePosition < 0) { + result = filePosition; + goto cleanup; + } + } + } + result = WADSeekStream(&stream, 0, 1); + if (result < 0) { + goto cleanup; + } + if ((u32)result != offset + totalSize - 0x340) { + result = -3006; + goto cleanup; + } + result = SHA1Result(hashContext, digest); + if (result != 0) { + goto cleanup; + } + result = ES_Sign(digest, 0x14, signature, &signerCertificate); + if (result != 0) { + goto cleanup; + } + result = ES_GetDeviceCert(deviceCertificate); + if (result != 0) { + goto cleanup; + } + result = WADWriteStream(&stream, signature, sizeof(signature)); + if (result != sizeof(signature)) { + result = -3006; + goto cleanup; + } + result = WADWriteStream(&stream, deviceCertificate, sizeof(deviceCertificate)); + if (result != sizeof(deviceCertificate)) { + result = -3006; + goto cleanup; + } + result = WADWriteStream(&stream, &signerCertificate, sizeof(signerCertificate)); + if (result != sizeof(signerCertificate)) { + result = -3006; + goto cleanup; + } + if (WADSeekStream(&stream, offset, 0) != (s32)offset) { + result = -3006; + goto cleanup; + } + result = WADWriteStream(&stream, &headerBlock, sizeof(headerBlock)); + if (result != sizeof(headerBlock)) { + result = -3006; + goto cleanup; + } + *sizeOut = totalSize; + result = 0; + +cleanup: + if (titleMetaBuffer != 0) { + _WADMemFree(allocator, titleMetaBuffer); + } + if (outputBuffer != 0) { + _WADMemFree(allocator, outputBuffer); + } + if (encryptionBuffer != 0) { + _WADMemFree(allocator, encryptionBuffer); + } + if (threadStack != 0) { + _WADMemFree(allocator, threadStack); + } + if (files != 0) { + _WADMemFree(allocator, files); + } + if (fileOpened) { + NANDClose(&savedFile); + } + if (streamOpened) { + WADCloseStream(&stream); + } + if (contentExportStarted) { + ES_ExportContentEnd(fileFd); + } + if (titleExportStarted) { + ES_ExportTitleDone(); + } + if ((processCallback != 0) && (sizeOut != 0)) { + processCallback(importedSize, contentDataSize + fileDataSize, TRUE); + } + return result; +} + +static s32 _WADCheckContents(ESTmdView* titleMeta, ESContentMask* contentMask) { + ESContentId installedContentIds[512] ALIGN32; + u32 installedContentCount; + u32 contentIndex; + s32 result; + + if (ES_ListTitleContentsOnCard(titleMeta->head.titleId, 0, &installedContentCount) == -106) { + result = -3002; + } else { + result = ES_ListTitleContentsOnCard(titleMeta->head.titleId, installedContentIds, + &installedContentCount); + if (result == 0) { + memset(contentMask, 0, sizeof(*contentMask)); + for (contentIndex = 0; contentIndex < titleMeta->head.numContents; contentIndex++) { + u32 installedIndex; + + if ((titleMeta->contents[contentIndex].type & 0x8000) == 0) { + for (installedIndex = 0; installedIndex < installedContentCount; + installedIndex++) { + if (installedContentIds[installedIndex] == + titleMeta->contents[contentIndex].cid) { + contentMask->data[contentIndex >> 3] |= 1 << (contentIndex & 7); + break; + } + } + if ((installedIndex == installedContentCount) && + ((titleMeta->contents[contentIndex].type & 0x4000) == 0)) { + result = -3002; + goto done; + } + result = 0; + } + } + } + } +done: + return result; +} + +s32 _WADGetCidxCount(const ESContentMask* contentMask) { + s32 count = 0; + u32 bitIndex = 0; + u32 groupIndex; + + for (groupIndex = 0; groupIndex < 0x80; groupIndex++) { + if ((contentMask->data[bitIndex >> 3] & (1 << (bitIndex & 7))) != 0) { + count++; + } + if ((contentMask->data[(bitIndex + 1) >> 3] & (1 << ((bitIndex + 1) & 7))) != 0) { + count++; + } + if ((contentMask->data[(bitIndex + 2) >> 3] & (1 << ((bitIndex + 2) & 7))) != 0) { + count++; + } + if ((contentMask->data[(bitIndex + 3) >> 3] & (1 << ((bitIndex + 3) & 7))) != 0) { + count++; + } + bitIndex += 4; + } + return count; +} + +static s32 _WADGetCidx(const ESContentMask* contentMask, u32 contentNumber) { + u32 remaining = contentNumber + 1; + u32 bitIndex = 0; + u32 nextIndex; + + for (bitIndex = 0; bitIndex < 0x200; bitIndex += 4) { + if ((contentMask->data[(s32)bitIndex >> 3] & (1 << (bitIndex & 7))) != 0) { + remaining--; + } + if (remaining == 0) { + return bitIndex; + } + nextIndex = bitIndex + 1; + if ((contentMask->data[(s32)nextIndex >> 3] & (1 << (nextIndex & 7))) != 0) { + remaining--; + } + if (remaining == 0) { + return nextIndex; + } + nextIndex = bitIndex + 2; + if ((contentMask->data[(s32)nextIndex >> 3] & (1 << (nextIndex & 7))) != 0) { + remaining--; + } + if (remaining == 0) { + return nextIndex; + } + nextIndex = bitIndex + 3; + if ((contentMask->data[(s32)nextIndex >> 3] & (1 << (nextIndex & 7))) != 0) { + remaining--; + } + if (remaining == 0) { + return nextIndex; + } + } + return -1; +} + +#pragma dont_inline on +static s32 _WADGetTransferId(void* transferId) { + NANDFileInfo fileInfo; + BOOL valid; + s32 result; + + valid = FALSE; + result = NANDPrivateOpen("/shared2/succession/transfer.id", &fileInfo, 1); + if (result == 0) { + valid = TRUE; + result = NANDRead(&fileInfo, transferId, 0x20); + if (result != 0x20) { + valid = FALSE; + } + NANDClose(&fileInfo); + } + return valid; +} + +static s32 _WADCanImportFile(const WADFileHeader* fileHeader, u32 transferId, const void* fileNames, + const void* transferIdBuffer) { + s32 result; + + result = strncmp(fileHeader->name, "nocopy", 6); + if (result == 0) { + return FALSE; + } + result = strncmp(fileHeader->name, "notransfer", 10); + if (result == 0) { + if ((transferId == 0) || (fileNames == 0) || (transferIdBuffer == 0)) { + return FALSE; + } + result = memcmp(fileNames, transferIdBuffer, 6); + return result == 0; + } + return TRUE; +} + +static s32 _WADBackupGetFiles(const char* directoryPath, u32 flags, MEMAllocator* allocator, + u32* fileCount, WADBackupFileHeader* files) { + char currentDirectory[NAND_MAX_PATH] ALIGN32; + char fullDirectoryPath[NAND_MAX_PATH] ALIGN32; + char fullFilePath[NAND_MAX_PATH] ALIGN32; + char* names = 0; + char* nameList = 0; + u32 nameCount = 0; + u32 nameIndex; + u32 totalFiles = 0; + u32 childFileCount; + u8 fileType; + NANDFileInfo fileInfo; + NANDStatus status; + s32 result; + + if ((allocator == 0) || (fileCount == 0)) { + return -3000; + } + result = NANDGetCurrentDir(currentDirectory); + if (result != 0) { + return result; + } + if (directoryPath == 0) { + directoryPath = ""; + } + if (directoryPath[0] == '\0') { + strncpy(fullDirectoryPath, currentDirectory, sizeof(fullDirectoryPath)); + } else if (directoryPath[0] == '/') { + strncpy(fullDirectoryPath, directoryPath, sizeof(fullDirectoryPath)); + } else { + snprintf(fullDirectoryPath, sizeof(fullDirectoryPath), "%s/%s", currentDirectory, + directoryPath); + } + result = NANDPrivateReadDir(fullDirectoryPath, 0, &nameCount); + if (result == -1) { + *fileCount = 0; + return 0; + } + if (result != 0) { + return result; + } + if (nameCount != 0) { + nameList = _WADMemAlloc(allocator, nameCount * 0x40); + if (nameList == 0) { + return -3003; + } + names = nameList; + result = NANDPrivateReadDir(fullDirectoryPath, nameList, &nameCount); + if (result != 0) { + goto cleanup; + } + for (nameIndex = 0; nameIndex < nameCount; nameIndex++) { + char* name = names; + WADBackupFileHeader* file = 0; + u32 fileSize = 0; + BOOL closeFile = FALSE; + + if ((flags & 4) != 0) { + if (directoryPath[0] == '\0') { + snprintf(fullFilePath, sizeof(fullFilePath), "/%s", name); + } else { + snprintf(fullFilePath, sizeof(fullFilePath), "%s/%s", directoryPath, name); + } + } else if (directoryPath[0] == '\0') { + snprintf(fullFilePath, sizeof(fullFilePath), "%s/%s", currentDirectory, name); + } else if (directoryPath[0] == '/') { + snprintf(fullFilePath, sizeof(fullFilePath), "%s/%s", directoryPath, name); + } else { + snprintf(fullFilePath, sizeof(fullFilePath), "%s/%s/%s", currentDirectory, + directoryPath, name); + } + result = NANDPrivateGetType(fullFilePath, &fileType); + if (result != 0) { + break; + } + if ((fileType == 2) && ((flags & 8) == 0)) { + goto nextName; + } + if (fileType == 1) { + result = NANDPrivateOpen(fullFilePath, &fileInfo, 1); + if (result != 0) { + break; + } + closeFile = TRUE; + result = NANDGetLength(&fileInfo, &fileSize); + if (result != 0) { + NANDClose(&fileInfo); + break; + } + result = NANDClose(&fileInfo); + closeFile = FALSE; + if (result != 0) { + break; + } + } else if (fileType != 2) { + goto nextName; + } + result = NANDPrivateGetStatus(fullFilePath, &status); + if (result != 0) { + break; + } + if (files != 0) { + file = &files[totalFiles]; + file->magic = 0x3ADF17E; + file->fileSize = fileSize; + file->flags[0] = status.permission; + file->flags[1] = status.attribute; + file->flags[2] = fileType; + strncpy(file->path, fullFilePath, 0x40); + } + totalFiles++; + if (fileType == 2) { + childFileCount = 0; + result = _WADBackupGetFiles(fullFilePath, flags, allocator, &childFileCount, + files == 0 ? 0 : &files[totalFiles]); + if (result != 0) { + break; + } + totalFiles += childFileCount; + } + +nextName: + names += strlen(names) + 1; + if (closeFile) { + NANDClose(&fileInfo); + } + } + } + if (result == 0) { + *fileCount = totalFiles; + } + +cleanup: + if (nameList != 0) { + _WADMemFree(allocator, nameList); + } + return result; +} + +static s32 _WADBackupGetSize(u32 flags, ESTmdView* titleMeta, ESContentMask* contentMask, + u32 fileCount, WADBackupFileHeader* files, u32* titleMetaSize, + u32* contentDataSize, u32* fileDataSize) { + u32 titleSize = 0; + u32 contentSize = 0; + u32 filesSize = 0; + u32 selectedCount; + u32 contentIndex; + u32 fileIndex; + s32 result = 0; + + if (titleMeta == 0) { + if (titleMetaSize != 0) { + *titleMetaSize = 0; + } + } else if (((flags & 1) != 0) || ((flags & 0x20) != 0)) { + result = ES_GetTmdSizeFromView(titleMeta, &titleSize); + if (result != 0) { + return result; + } + titleSize = (titleSize + 0x3F) & ~0x3F; + } + if (((flags & 1) != 0) && (titleMeta != 0)) { + selectedCount = _WADGetCidxCount(contentMask); + for (contentIndex = 0; contentIndex < selectedCount; contentIndex++) { + s32 tmdIndex = _WADGetCidx(contentMask, contentIndex); + if ((tmdIndex < 0) || (titleMeta->head.numContents <= tmdIndex)) { + return -3009; + } + contentSize += (titleMeta->contents[tmdIndex].size + 0x3F) & ~0x3F; + } + } + if ((fileCount != 0) && (files != 0)) { + for (fileIndex = 0; fileIndex < fileCount; fileIndex++) { + filesSize += 0x80 + ((files[fileIndex].fileSize + 0x3F) & ~0x3F); + } + } + if (titleMetaSize != 0) { + *titleMetaSize = titleSize; + } + if (contentDataSize != 0) { + *contentDataSize = contentSize; + } + if (fileDataSize != 0) { + *fileDataSize = filesSize; + } + return result; +} +#pragma dont_inline reset + +#pragma dont_inline on +static void* _WADMemAlloc(MEMAllocator* allocator, u32 size) { + s32 allocationKind; + u32 heapType; + void* buffer = 0; + + if ((allocator != 0) && (allocator->heap != 0)) { + heapType = ((MEMiHeapHead*)allocator->heap)->magic; + switch (heapType) { + case 0x45585048: + allocationKind = 0; + break; + case 0x46524D48: + allocationKind = 1; + break; + case 0x554E5448: + allocationKind = 2; + break; + default: + allocationKind = 3; + break; + } + + switch (allocationKind) { + case 0: + buffer = MEMAllocFromExpHeapEx(allocator->heap, size, 0x40); + break; + case 1: + buffer = MEMAllocFromFrmHeapEx(allocator->heap, size, 0x40); + break; + case 2: + default: + buffer = MEMAllocFromAllocator(allocator, size); + if (((u32)buffer & 0x3F) != 0) { + OSReport("%s: Memory Allocator must return 64B aligned memBlocks\n", "_WADMemAlloc"); + MEMFreeToAllocator(allocator, buffer); + buffer = 0; + } + break; + } + } + return buffer; +} + +static void _WADMemFree(MEMAllocator* allocator, void* buffer) { + if ((allocator == 0) || (allocator->heap == 0) || (buffer == 0)) { + return; + } + MEMFreeToAllocator(allocator, buffer); +} +#pragma dont_inline reset + +static void _WADFreeMemory(WADUnpackInfo* info, MEMAllocator* allocator) { + if ((info->size_0x18 != 0) && (info->buffer_0x14 != 0)) { + _WADMemFree(allocator, info->buffer_0x14); + info->buffer_0x14 = 0; + } + if ((info->size_0x28 != 0) && (info->buffer_0x24 != 0)) { + _WADMemFree(allocator, info->buffer_0x24); + info->buffer_0x24 = 0; + } + if ((info->size_0x38 != 0) && (info->buffer_0x34 != 0)) { + _WADMemFree(allocator, info->buffer_0x34); + info->buffer_0x34 = 0; + } + if ((info->titleMetaSize != 0) && (info->titleMeta != 0)) { + _WADMemFree(allocator, info->titleMeta); + info->titleMeta = 0; + } +} + +static void _WADRandPad(void* buffer, u32 size) { + u32* words = buffer; + u32 wordCount = size >> 2; + u32 remainder = size & 3; + u32 wordIndex; + + for (wordIndex = 0; wordIndex < wordCount; wordIndex++) { + u32 first = rand(); + u32 second = rand(); + u32 third = rand(); + words[wordIndex] = (third & 3) | (second << 17) | (first << 2); + } + if (remainder != 0) { + u32 first = rand(); + u32 second = rand(); + u32 third = rand(); + u32 randomWord = (third & 3) | (second << 17) | (first << 2); + u8* tail = (u8*)&words[wordCount]; + u8* randomBytes = (u8*)&randomWord; + u32 byteIndex; + + for (byteIndex = 0; byteIndex < remainder; byteIndex++) { + tail[byteIndex] = randomBytes[byteIndex]; + } + } +} + +typedef struct WADContentPath { + const char* name; + void* handle; +} WADContentPath; + +typedef union WADFileInfoView { + FAFileInfo info; + struct { + u32 unknown; + u32 fileSize; + u8 reserved[0x18]; + } fields; +} WADFileInfoView; + +s32 WADOpenStream(WADLocation location, const char* path, WADStream* stream, u32 write, + u32 offset) { + s32 result; + + stream->location = location; + if (location == WAD_LOCATION_SD_CARD) { + if (write == 0) { + stream->handle.fa = FAFopen(path, "r"); + } else { + stream->handle.fa = FAFopen(path, "r+"); + if (stream->handle.fa == 0) { + stream->handle.fa = FACreate(path, 0); + } + if (stream->handle.fa == 0) { + return -3004; + } + if ((offset != 0) && (WADSeekStream(stream, offset, 0) != offset)) { + return -3004; + } + } + return stream->handle.fa == 0 ? -3004 : 0; + } + if (location < WAD_LOCATION_SD_CARD) { + if (location == WAD_LOCATION_DVD) { + if (write != 0) { + return -3004; + } + return DVDOpen(path, &stream->handle.dvd) ? 0 : -3004; + } + if (location == WAD_LOCATION_NAND) { + if (write == 0) { + return NANDPrivateOpen(path, &stream->handle.nand, 1) == 0 ? 0 : -3004; + } + result = NANDPrivateOpen(path, &stream->handle.nand, 3); + if (result == -12) { + result = NANDPrivateCreate(path, 0x3F, 0); + if (result != 0) { + return -3004; + } + result = NANDPrivateOpen(path, &stream->handle.nand, 3); + } + if (result != 0) { + return -3004; + } + result = NANDSeek(&stream->handle.nand, offset, 0); + if (result == -8) { + u8 zeroes[0x4000] ALIGN32; + u32 fileSize; + + fileSize = NANDSeek(&stream->handle.nand, 0, 2); + if (offset <= fileSize) { + return -3004; + } + memset(zeroes, 0, sizeof(zeroes)); + fileSize = offset - fileSize; + while (fileSize != 0) { + u32 writeSize = fileSize; + if (writeSize > sizeof(zeroes)) { + writeSize = sizeof(zeroes); + } + if (NANDWrite(&stream->handle.nand, zeroes, writeSize) != writeSize) { + return -3004; + } + fileSize -= writeSize; + } + result = NANDSeek(&stream->handle.nand, offset, 0); + } + return result == offset ? 0 : -3004; + } + if ((s32)location >= 0) { + if ((((u32)path + offset) & 0x3F) != 0) { + return -3007; + } + stream->handle.memoryBase = (void*)((u32)path + offset); + return 0; + } + } else if (location == WAD_LOCATION_CNT_NAND) { + WADContentPath* contentPath = (WADContentPath*)path; + if (write != 0) { + return -3004; + } + return contentOpenNAND(contentPath->handle, contentPath->name, + &stream->handle.contentNand) == 0 + ? 0 + : -3004; + } else if (location < WAD_LOCATION_CNT_NAND) { + WADContentPath* contentPath = (WADContentPath*)path; + if (write != 0) { + return -3004; + } + return contentOpenDVD(contentPath->handle, contentPath->name, + &stream->handle.contentDvd) == 0 + ? 0 + : -3004; + } + return -3000; +} + +size_t WADReadStream(WADStream* stream, void** buffer, size_t size, s32 offset) { + size_t result; + u32 alignedSize; + s32 location; + + if ((s32)size <= 0) { + result = 0; + } else if ((stream == 0) || (buffer == 0)) { + result = -3000; + } else { + alignedSize = (size + WAD_READ_ALIGNMENT - 1) & ~(WAD_READ_ALIGNMENT - 1); + if (size == alignedSize) { + location = stream->location; + if (location != WAD_LOCATION_SD_CARD) { + if (location < WAD_LOCATION_SD_CARD) { + if (location != WAD_LOCATION_DVD) { + if (location > 0) { + result = NANDSeek(&stream->handle.nand, offset, 0); + if ((s32)result < 0) { + return result; + } + return NANDRead(&stream->handle.nand, *buffer, alignedSize); + } + if (location >= 0) { + memcpy(*buffer, (u8*)stream->handle.memoryBase + offset, size); + return size; + } + } else { + return DVDReadPrio(&stream->handle.dvd, *buffer, alignedSize, offset, 2); + } + } else { + if (location != WAD_LOCATION_CNT_NAND) { + if (location < WAD_LOCATION_CNT_NAND) { + return contentReadDVD(&stream->handle.contentDvd, *buffer, alignedSize, + offset); + } + } else { + return contentReadNAND(&stream->handle.contentNand, *buffer, alignedSize, + offset); + } + } + result = -3000; + } else if (stream->handle.fa == 0) { + result = -3000; + } else { + result = FAFseek(stream->handle.fa, offset, 0); + if (result == 0) { + result = FAFread(*buffer, 1, size, stream->handle.fa); + } + } + } else { + result = -3000; + } + } + return result; +} + +void WADCloseStream(WADStream* stream) { + if (stream == 0) { + return; + } + if (stream->location != WAD_LOCATION_SD_CARD) { + if (stream->location < WAD_LOCATION_SD_CARD) { + if (stream->location != WAD_LOCATION_DVD) { + if (stream->location < WAD_LOCATION_DVD) { + return; + } + NANDClose(&stream->handle.nand); + return; + } + DVDClose(&stream->handle.dvd); + return; + } + if (stream->location != WAD_LOCATION_CNT_NAND) { + if (stream->location > WAD_LOCATION_CNT_NAND) { + return; + } + contentCloseDVD(&stream->handle.contentDvd); + return; + } + contentCloseNAND(&stream->handle.contentNand); + return; + } + if (stream->handle.fa != 0) { + FAFclose(stream->handle.fa); + } +} + +s32 WADWriteStream(WADStream* stream, void* buffer, u32 size) { + if ((stream == 0) || (buffer == 0)) { + return -3000; + } + if (stream->location == WAD_LOCATION_NAND) { + return NANDWrite(&stream->handle.nand, buffer, size); + } + if (stream->location == WAD_LOCATION_DVD - 1) { + memcpy(stream->handle.memoryBase, buffer, size); + return size; + } + if ((stream->location > WAD_LOCATION_NAND) && + (stream->location < WAD_LOCATION_CNT_DVD)) { + if (stream->handle.fa == 0) { + return -3000; + } + return FAFwrite(buffer, 1, size, stream->handle.fa); + } + return -3000; +} + +s32 WADSeekStream(WADStream* stream, u32 offset, s32 origin) { + s32 result; + + if ((stream == 0) || (origin < 0) || (origin > 2)) { + return -3000; + } + if (stream->location == WAD_LOCATION_SD_CARD) { + WADFileInfoView info; + if (stream->handle.fa == 0) { + return -3000; + } + result = FAFseek(stream->handle.fa, offset, origin); + if ((result == 0) && (FAFinfo(stream->handle.fa, &info.info) == 0)) { + result = info.fields.fileSize; + } + return result; + } + if (stream->location < WAD_LOCATION_SD_CARD) { + if (stream->location > WAD_LOCATION_DVD) { + return NANDSeek(&stream->handle.nand, offset, origin); + } + } else if (stream->location == WAD_LOCATION_CNT_NAND) { + return contentSeekNAND(&stream->handle.contentNand, offset, origin); + } else if (stream->location < WAD_LOCATION_CNT_NAND) { + return contentSeekDVD(&stream->handle.contentDvd, offset, origin); + } + return -3000; +} + +static s32 _WADGetTitleVer(WADHeader* header, ESTitleId* titleId, u16* titleVersion, s32 type, + s32 headerInfo) { + s32 titleDataOffset = 0; + + if (type == 2) { + if (header->tmdSize == 0) { + return 0; + } + if ((headerInfo == 0) || (headerInfo == 1) || (headerInfo == 3)) { + titleDataOffset = header->wadVersion == 1 ? 0x80 : 0x40; + titleDataOffset += (header->certSize + 0x3F) & ~0x3F; + titleDataOffset += (header->crlSize + 0x3F) & ~0x3F; + titleDataOffset += (header->ticketSize + 0x3F) & ~0x3F; + } else if (headerInfo == 2) { + titleDataOffset = 0x80; + } + } else if (type == 1) { + if (header->ticketSize == 0) { + return 0; + } + titleDataOffset = header->certSize + 0x20; + titleDataOffset += header->crlSize; + } + + { + WADFileMetadataView* metadata = (WADFileMetadataView*)((u8*)header + titleDataOffset); + if (titleId != 0) { + *titleId = metadata->titleId; + } + if (titleVersion != 0) { + *titleVersion = metadata->titleVersion; + } + } + return titleDataOffset; +} + +static s32 WAD_815C2F44(WADHeader* header, s32* headerInfo) { + u8 firstTypeByte; + u8 secondTypeByte; + + if (header == 0) { + return 0; + } + firstTypeByte = header->wadType[0]; + secondTypeByte = header->wadType[1]; + if ((firstTypeByte == 'I') && (secondTypeByte == 's')) { + if (headerInfo != 0) { + *headerInfo = 0; + } + return 2; + } + if ((firstTypeByte == 'X') && (secondTypeByte == 'p')) { + if (headerInfo != 0) { + *headerInfo = 1; + } + return 2; + } + if ((firstTypeByte == 'B') && (secondTypeByte == 'k')) { + if (headerInfo != 0) { + *headerInfo = 2; + } + return 2; + } + if ((firstTypeByte == 'i') && (secondTypeByte == 'b')) { + if (headerInfo != 0) { + *headerInfo = 3; + } + return 2; + } + if (header->hdrSize == 0x20) { + if (headerInfo != 0) { + *headerInfo = 0; + } + return 1; + } + return 0; +} + +#pragma dont_inline on +static s32 _WADUnpack(void* header, WADStream* stream, WADUnpackInfo* info, MEMAllocator* allocator, + u32 offset, u32 flags, u32 mode) { + s32 result; + s32 type; + + if ((header == 0) || (info == 0)) { + result = -3000; + } else { + memset(info, 0, 0x70); + type = WAD_815C2F44(header, &info->headerInfo); + info->type = type; + if (type == 2) { + if (info->headerInfo != 2) { + result = _WADUnpackIRD(header, stream, info, allocator, offset, mode); + } else { + result = _WADUnpackBackup(header, stream, info, allocator, offset, flags); + } + } else if (type == 1) { + result = _WADUnpackBroadOn((WADBroadOnHeader*)header, stream, info, allocator, offset, + mode); + } else { + result = -3001; + } + } + return result; +} +#pragma dont_inline reset + +static s32 _WADUnpackIRD(WADHeader* header, WADStream* stream, WADUnpackInfo* info, + MEMAllocator* allocator, u32 offset, u32 mode) { + u16 wadVersion = header->wadVersion; + s32 sectionSize; + u32 sectionOffset; + s32 alignedSize; + s32 bytesRead; + + if ((wadVersion != 0) && (wadVersion != 1)) { + return -3001; + } + if ((header->ticketSize == 0) && (header->tmdSize == 0)) { + return -3001; + } + if ((wadVersion == 0) && (header->hdrSize != 0x20)) { + return -3001; + } + if ((wadVersion == 1) && (header->hdrSize != 0x60)) { + return -3001; + } + + info->cidxMode = wadVersion; + if (wadVersion >= 1) { + info->contentIndex = &((WADBackupHeader*)header)->cidx; + } + sectionOffset = (header->hdrSize + 0x3F) & ~0x3F; + + sectionSize = header->certSize; + if (sectionSize != 0) { + info->size_0x0c = sectionSize; + info->offset_0x10 = sectionOffset; + if (mode == 0) { + alignedSize = WAD_ALIGN32(sectionSize); + info->buffer_0x14 = _WADMemAlloc(allocator, alignedSize); + if (info->buffer_0x14 == 0) { + return -3003; + } + info->size_0x18 = 1; + bytesRead = WADReadStream(stream, &info->buffer_0x14, alignedSize, + offset + info->offset_0x10); + if (bytesRead != alignedSize) { + return -3005; + } + } + sectionOffset += (header->certSize + 0x3F) & ~0x3F; + } + sectionSize = header->crlSize; + if (sectionSize != 0) { + info->size_0x1c = sectionSize; + info->offset_0x20 = sectionOffset; + if (mode == 0) { + alignedSize = WAD_ALIGN32(sectionSize); + info->buffer_0x24 = _WADMemAlloc(allocator, alignedSize); + if (info->buffer_0x24 == 0) { + return -3003; + } + info->size_0x28 = 1; + bytesRead = WADReadStream(stream, &info->buffer_0x24, alignedSize, + offset + info->offset_0x20); + if (bytesRead != alignedSize) { + return -3005; + } + } + sectionOffset += (header->crlSize + 0x3F) & ~0x3F; + } + sectionSize = header->ticketSize; + if (sectionSize != 0) { + info->size_0x2c = sectionSize; + info->offset_0x30 = sectionOffset; + if (mode == 0) { + alignedSize = WAD_ALIGN32(sectionSize); + info->buffer_0x34 = _WADMemAlloc(allocator, alignedSize); + if (info->buffer_0x34 == 0) { + return -3003; + } + info->size_0x38 = 1; + bytesRead = WADReadStream(stream, &info->buffer_0x34, alignedSize, + offset + info->offset_0x30); + if (bytesRead != alignedSize) { + return -3005; + } + } + sectionOffset += (header->ticketSize + 0x3F) & ~0x3F; + } + sectionSize = header->tmdSize; + if (sectionSize != 0) { + info->sectionSize = sectionSize; + info->sectionOffset = sectionOffset; + alignedSize = WAD_ALIGN32(sectionSize); + info->titleMeta = _WADMemAlloc(allocator, alignedSize); + if (info->titleMeta == 0) { + return -3003; + } + info->titleMetaSize = 1; + bytesRead = WADReadStream(stream, (void**)&info->titleMeta, alignedSize, + offset + info->sectionOffset); + if (bytesRead != alignedSize) { + return -3005; + } + sectionOffset += (header->tmdSize + 0x3F) & ~0x3F; + } + if (header->contentSize != 0) { + info->contentSize = header->contentSize; + info->contentOffset = sectionOffset; + sectionOffset += (header->contentSize + 0x3F) & ~0x3F; + } + if (header->metaSize != 0) { + info->metaSize = header->metaSize; + info->metaOffset = sectionOffset; + } + return 0; +} + +static s32 _WADUnpackBroadOn(WADBroadOnHeader* header, WADStream* stream, WADUnpackInfo* info, + MEMAllocator* allocator, u32 offset, u32 mode) { + u32 currentOffset; + s32 sectionSize; + s32 alignedSize; + s32 bytesRead; + + if ((header->crlSize == 0) && (header->ticketSize == 0)) { + return -3001; + } + + currentOffset = header->headerSize; + sectionSize = header->certSize; + if (sectionSize != 0) { + info->size_0x0c = sectionSize; + info->offset_0x10 = currentOffset; + if (mode == 0) { + alignedSize = WAD_ALIGN32(sectionSize); + info->buffer_0x14 = _WADMemAlloc(allocator, alignedSize); + if (info->buffer_0x14 == 0) { + return -3003; + } + info->size_0x18 = 1; + bytesRead = WADReadStream(stream, &info->buffer_0x14, alignedSize, + offset + info->offset_0x10); + if (bytesRead != alignedSize) { + return -3005; + } + } + currentOffset += header->certSize; + } + + sectionSize = header->crlSize; + if (sectionSize != 0) { + info->size_0x2c = sectionSize; + info->offset_0x30 = currentOffset; + if (mode == 0) { + alignedSize = WAD_ALIGN32(sectionSize); + info->buffer_0x34 = _WADMemAlloc(allocator, alignedSize); + if (info->buffer_0x34 == 0) { + return -3003; + } + info->size_0x38 = 1; + bytesRead = WADReadStream(stream, &info->buffer_0x34, alignedSize, + offset + info->offset_0x30); + if (bytesRead != alignedSize) { + return -3005; + } + } + currentOffset += header->crlSize; + } + + sectionSize = header->ticketSize; + if (sectionSize != 0) { + info->sectionSize = sectionSize; + info->sectionOffset = currentOffset; + alignedSize = WAD_ALIGN32(sectionSize); + info->titleMeta = _WADMemAlloc(allocator, alignedSize); + if (info->titleMeta == 0) { + return -3003; + } + info->titleMetaSize = 1; + bytesRead = WADReadStream(stream, (void**)&info->titleMeta, alignedSize, + offset + info->sectionOffset); + if (bytesRead != alignedSize) { + return -3005; + } + currentOffset += header->ticketSize; + } + + sectionSize = header->titleMetaSize; + if (sectionSize != 0) { + info->metaSize = sectionSize; + info->metaOffset = currentOffset; + currentOffset += header->titleMetaSize; + } + + sectionSize = header->fileListSize; + if (sectionSize != 0) { + info->size_0x1c = sectionSize; + info->offset_0x20 = currentOffset; + if (mode == 0) { + alignedSize = WAD_ALIGN32(sectionSize); + info->buffer_0x24 = _WADMemAlloc(allocator, alignedSize); + if (info->buffer_0x24 == 0) { + return -3003; + } + info->size_0x28 = 1; + bytesRead = WADReadStream(stream, &info->buffer_0x24, alignedSize, + offset + info->offset_0x20); + if (bytesRead != alignedSize) { + return -3005; + } + } + } + + info->contentOffset = header->contentOffset; + return 0; +} + +static s32 _WADUnpackBackup(WADHeader* header, WADStream* stream, WADUnpackInfo* info, + MEMAllocator* allocator, u32 offset, u32 flags) { + WADBackupHeader* backupHeader = (WADBackupHeader*)header; + ESDeviceId currentDeviceId; + s32 result; + u32 sectionOffset; + u32 alignedSize; + + if (backupHeader->wadVersion != 1) { + return -3001; + } + if (backupHeader->hdrSize != sizeof(WADBackupHeader)) { + return -3001; + } + if (backupHeader->contentSize != 0) { + result = ES_GetDeviceId(¤tDeviceId); + if (result != 0) { + return result; + } + if (currentDeviceId != backupHeader->deviceId) { + return -3008; + } + } + + info->cidxMode = backupHeader->wadVersion; + if (backupHeader->wadVersion >= 1) { + info->contentIndex = &backupHeader->cidx; + } + info->fileNames = backupHeader->deviceMac; + sectionOffset = (backupHeader->hdrSize + WAD_STREAM_ALIGNMENT - 1) & + ~(WAD_STREAM_ALIGNMENT - 1); + + if (backupHeader->tmdSize != 0) { + if ((flags & 4) == 0) { + info->sectionSize = backupHeader->tmdSize; + info->sectionOffset = sectionOffset; + alignedSize = WAD_ALIGN32(backupHeader->tmdSize); + info->titleMeta = _WADMemAlloc(allocator, alignedSize); + if (info->titleMeta == 0) { + return -3003; + } + info->titleMetaSize = 1; + result = WADReadStream(stream, (void**)&info->titleMeta, alignedSize, + offset + info->sectionOffset); + if (result != alignedSize) { + return -3005; + } + result = 0; + } + sectionOffset += (backupHeader->tmdSize + WAD_STREAM_ALIGNMENT - 1) & + ~(WAD_STREAM_ALIGNMENT - 1); + if ((flags & 2) != 0) { + return 0; + } + } + + if (backupHeader->contentSize != 0) { + info->contentSize = backupHeader->contentSize; + info->contentOffset = sectionOffset; + sectionOffset += (backupHeader->contentSize + WAD_STREAM_ALIGNMENT - 1) & + ~(WAD_STREAM_ALIGNMENT - 1); + } + if (backupHeader->fileSize != 0) { + info->fileListSize = backupHeader->fileSize; + info->fileOffset = sectionOffset; + info->fileCount = backupHeader->numFiles; + if ((flags & 1) == 0) { + result = WADVerify(stream, allocator, offset, backupHeader->backupAreaLen); + if (result != 0) { + return result; + } + } + } + return 0; +} + +typedef struct WADSaveDataRecord { + u8 reserved_0x00[0x4E]; + char fileName[8]; + u8 reserved_0x56[2]; + char bannerName[8]; + u8 reserved_0x60[0x12]; + char saveName[8]; + u8 reserved_0x7A[0x14]; + char titleName[8]; + u8 reserved_0x96[0x11E]; + char description[0x11]; + char subtitle[0x11]; + u8 reserved_0x1D6[0x8BE]; +} WADSaveDataRecord; + +typedef struct WADSaveDataFile { + u8 reserved_0x00[8]; + WADSaveDataRecord primary[3]; + u8 reserved_0x1FC4[0x44]; + WADSaveDataRecord secondary[3]; +} WADSaveDataFile; + +s32 WADCheckSavedataZD(const WADSaveDataFile* saveData) { + s32 result = FALSE; + u32 index; + const WADSaveDataRecord* record; + + record = saveData->primary; + index = 0; + do { + if (!_WADIsTerminated(record->fileName, 8)) { + goto done; + } + if (!_WADIsTerminated(record->bannerName, 8)) { + goto done; + } + if (!_WADIsTerminated(record->saveName, 8)) { + goto done; + } + if (!_WADIsTerminated(record->titleName, 8)) { + goto done; + } + if (!_WADIsTerminated(record->description, 0x11)) { + goto done; + } + if (!_WADIsTerminated(record->subtitle, 0x11)) { + goto done; + } + index++; + record++; + } while (index < 3); + record = saveData->secondary; + for (index = 0; index < 3; index++, record++) { + if (!_WADIsTerminated(record->fileName, 8)) { + goto done; + } + if (!_WADIsTerminated(record->bannerName, 8)) { + goto done; + } + if (!_WADIsTerminated(record->saveName, 8)) { + goto done; + } + if (!_WADIsTerminated(record->titleName, 8)) { + goto done; + } + if (!_WADIsTerminated(record->description, 0x11)) { + goto done; + } + if (!_WADIsTerminated(record->subtitle, 0x11)) { + goto done; + } + } + result = TRUE; +done: + return result; +} + +static s32 _WADVerifySavedataZD(WADSaveDataHeader* header, WADStream* stream, + MEMAllocator* allocator, u32 offset) { + WADFileHeader* fileHeader = 0; + void* encryptedData = 0; + void* decryptedData = 0; + NANDFileInfo fileInfo; + s32 fileOpened = FALSE; + s32 result; + + if (header->saveType != 1) { + return -3009; + } + fileHeader = MEMAllocFromAllocator(allocator, sizeof(WADFileHeader)); + if (fileHeader == 0) { + result = -3003; + goto cleanup; + } + result = WADReadStream(stream, (void**)&fileHeader, sizeof(WADFileHeader), offset); + if (result != sizeof(WADFileHeader)) { + result = -3005; + goto cleanup; + } + if (fileHeader->fileSize < 0x4000) { + result = -3009; + goto cleanup; + } + encryptedData = MEMAllocFromAllocator(allocator, 0x4000); + decryptedData = MEMAllocFromAllocator(allocator, 0x4000); + if ((encryptedData == 0) || (decryptedData == 0)) { + result = -3003; + goto cleanup; + } + memset(encryptedData, 0, 0x4000); + memset(decryptedData, 0, 0x4000); + if (strcmp(fileHeader->name, "zeldaTp.dat") != 0) { + result = -3009; + goto cleanup; + } + result = WADReadStream(stream, &encryptedData, 0x4000, offset + 0x80); + if (result != 0x4000) { + result = -3005; + goto cleanup; + } + result = ES_Decrypt(6, fileHeader->iv, encryptedData, 0x4000, decryptedData); + if (result != 0) { + result = -3005; + goto cleanup; + } + if (WADCheckSavedataZD(decryptedData) == 0) { + result = -3009; + goto cleanup; + } + result = NANDPrivateCreate(fileHeader->name, 0x34, 0); + if ((result == 0) && (NANDPrivateOpen(fileHeader->name, &fileInfo, 2) == 0)) { + fileOpened = TRUE; + result = NANDWrite(&fileInfo, decryptedData, 0x4000); + if (result != 0x4000) { + result = -3006; + } else { + result = NANDClose(&fileInfo); + if (result == 0) { + fileOpened = FALSE; + } + } + } + +cleanup: + if (fileHeader != 0) { + MEMFreeToAllocator(allocator, fileHeader); + } + if (encryptedData != 0) { + MEMFreeToAllocator(allocator, encryptedData); + } + if (decryptedData != 0) { + MEMFreeToAllocator(allocator, decryptedData); + } + if (fileOpened) { + NANDClose(&fileInfo); + } + return result; +} + +static void _WADCleanTmpDir(MEMAllocator* allocator) { + char* names = 0; + char* name; + char filePath[NAND_MAX_PATH] ALIGN32; + u32 fileCount = 0; + u32 fileIndex; + s32 result; + + result = NANDPrivateReadDir("/tmp", 0, &fileCount); + if ((result == 0) && (fileCount != 0)) { + names = MEMAllocFromAllocator(allocator, fileCount * 0x41); + if ((names != 0) && (NANDPrivateReadDir("/tmp", names, &fileCount) == 0)) { + name = names; + for (fileIndex = 0; fileIndex < fileCount; fileIndex++) { + char* extension = strrchr(name, '.'); + if ((extension != 0) && (strncmp(extension + 1, "tmp", 3) == 0)) { + snprintf(filePath, sizeof(filePath), "/tmp/%s", name); + NANDPrivateDelete(filePath); + OSReport("%s:%d remove %s", "WADImportEx", 0x1777, filePath); + } + name += strlen(name) + 1; + } + } + } + if (names != 0) { + MEMFreeToAllocator(allocator, names); + } +} + +s32 WADImportDVDForBS(const char* path, void* buffer, u32 bufferSize) { + DVDFileInfo fileInfo; + WADBootImportParts parts; + WADHeader* header; + ESTitleMeta* titleMeta; + u8* readBuffer = buffer; + void* applicationData; + u32 paddedFileSize; + u32 sectionOffset; + u32 applicationSize; + BOOL fileOpened = FALSE; + s32 result; + + if ((path == 0) || (buffer == 0)) { + result = -3000; + goto cleanup; + } + if (!DVDOpen(path, &fileInfo)) { + return -3004; + } + fileOpened = TRUE; + paddedFileSize = (fileInfo.length + 0x1F) & ~0x1F; + if (paddedFileSize > bufferSize) { + result = -3003; + goto cleanup; + } + if (((s32)readBuffer % 0x40) != 0) { + readBuffer += 0x20; + } + result = DVDReadPrio(&fileInfo, readBuffer, paddedFileSize, 0, 2); + if ((u32)result != paddedFileSize) { + result = -3005; + goto cleanup; + } + + memset(&parts, 0, sizeof(parts)); + header = (WADHeader*)readBuffer; + result = WAD_815C2F44(header, parts.headerInfo); + if (result != 2) { + OSReport("%s:%d Format should be iRD format: %s\n", "WADImportDVDForBS", 0x17D2, + path); + result = -3000; + goto cleanup; + } + if (parts.headerInfo[0] == 3) { + sectionOffset = (header->hdrSize + 0x3F) & ~0x3F; + if (header->certSize != 0) { + parts.certificateSize = header->certSize; + parts.certificates = readBuffer + sectionOffset; + sectionOffset += (header->certSize + 0x3F) & ~0x3F; + } + if (header->crlSize != 0) { + parts.crlSize = header->crlSize; + parts.crls = readBuffer + sectionOffset; + sectionOffset += (header->crlSize + 0x3F) & ~0x3F; + } + if (header->ticketSize != 0) { + parts.ticketSize = header->ticketSize; + parts.ticket = readBuffer + sectionOffset; + sectionOffset += (header->ticketSize + 0x3F) & ~0x3F; + } + if (header->tmdSize != 0) { + parts.titleMetaSize = header->tmdSize; + parts.titleMeta = readBuffer + sectionOffset; + sectionOffset += (header->tmdSize + 0x3F) & ~0x3F; + } + titleMeta = parts.titleMeta; + applicationSize = ((u32)titleMeta->contents[0].size + 0xF) & ~0xF; + applicationData = readBuffer + sectionOffset; + if ((titleMeta == 0) || (titleMeta->head.titleId != ES_TITLE_ID(1, 1))) { + OSReport("%s:%d This function only works for boot2 import.\n", "WADImportDVDForBS", + 0x180D); + result = -3000; + } else { + result = ES_ImportBoot(parts.ticket, parts.certificates, parts.certificateSize, + parts.titleMeta, parts.titleMetaSize, parts.certificates, + parts.certificateSize, parts.crls, parts.crlSize, applicationData, + applicationSize); + if (result != 0) { + OSReport("%s: Import Boot Failed: %d\n", "WADImportDVDForBS", result); + } else { + OSReport("%s: Import Boot Successful\n", "WADImportDVDForBS"); + } + } + } else { + OSReport("%s:%d This function only works for boot2 import.\n", "WADImportDVDForBS", + 0x1814); + result = -3000; + } + +cleanup: + if (fileOpened) { + DVDClose(&fileInfo); + } + return result; +} + +s32 WADImportDVDExForBS(const char* path, void* buffer, u32 bufferSize) { + WADHeader header ALIGN32; + WADBootImportParts parts; + DVDFileInfo fileInfo; + u8* readBuffer = buffer; + u8* contentBuffer; + ESTitleMeta* titleMeta; + ESContentMeta* contentMeta; + u32 sectionOffset; + u32 remainingBufferSize; + u32 contentCount; + u32 contentIndex; + s32 contentFd; + s32 result = 0; + s32 readResult; + BOOL fileOpened = FALSE; + + if ((path == 0) || (buffer == 0)) { + result = -3000; + goto cleanup; + } + if (!DVDOpen(path, &fileInfo)) { + return -3004; + } + fileOpened = TRUE; + if (buffer == 0) { + result = -3003; + goto cleanup; + } + if (((s32)readBuffer % 0x40) != 0) { + readBuffer += 0x20; + bufferSize -= 0x20; + } + readResult = DVDReadPrio(&fileInfo, &header, sizeof(header), 0, 2); + if (readResult != sizeof(header)) { + result = -3005; + goto cleanup; + } + + memset(&parts, 0, sizeof(parts)); + result = WAD_815C2F44(&header, parts.headerInfo); + if (result != 2) { + result = -3000; + goto cleanup; + } + + sectionOffset = (header.hdrSize + 0x3F) & ~0x3F; + if (header.certSize != 0) { + parts.certificateSize = header.certSize; + parts.certificates = readBuffer + sectionOffset; + sectionOffset += (header.certSize + 0x3F) & ~0x3F; + } + if (header.crlSize != 0) { + parts.crlSize = header.crlSize; + parts.crls = readBuffer + sectionOffset; + sectionOffset += (header.crlSize + 0x3F) & ~0x3F; + } + if (header.ticketSize != 0) { + parts.ticketSize = header.ticketSize; + parts.ticket = readBuffer + sectionOffset; + sectionOffset += (header.ticketSize + 0x3F) & ~0x3F; + } + if (header.tmdSize != 0) { + parts.titleMetaSize = header.tmdSize; + parts.titleMeta = readBuffer + sectionOffset; + sectionOffset += (header.tmdSize + 0x3F) & ~0x3F; + } + titleMeta = parts.titleMeta; + remainingBufferSize = bufferSize - sectionOffset; + contentBuffer = readBuffer + sectionOffset; + if (sectionOffset > bufferSize) { + result = -3003; + goto cleanup; + } + readResult = DVDReadPrio(&fileInfo, readBuffer, sectionOffset, 0, 2); + if (readResult != sectionOffset) { + result = -3005; + goto cleanup; + } + if (parts.headerInfo[0] == 3) { + result = -3001; + goto cleanup; + } + if (parts.ticket != 0) { + result = ES_ImportTicket(parts.ticket, parts.certificates, + parts.certificateSize, parts.crls, + parts.crlSize, 1); + if (result != 0) { + goto cleanup; + } + } + if (titleMeta == 0) { + goto cleanup; + } + if (parts.headerInfo[1] >= 1) { + contentCount = _WADGetCidxCount((ESContentMask*)parts.headerInfo); + if (contentCount > titleMeta->head.numContents) { + goto cleanup; + } + } else { + contentCount = titleMeta->head.numContents; + } + + result = ES_ImportTitleInit(parts.titleMeta, parts.titleMetaSize, + parts.certificates, parts.certificateSize, + parts.crls, parts.crlSize, + parts.headerInfo[0], 1); + if (result != 0) { + ES_ImportTitleCancel(); + goto cleanup; + } + + contentIndex = 0; + while (contentIndex < contentCount) { + s32 titleContentIndex; + u32 remainingContentSize; + + if (parts.headerInfo[1] >= 1) { + titleContentIndex = _WADGetCidx((ESContentMask*)parts.headerInfo, + contentIndex); + if ((titleContentIndex < 0) || + (titleContentIndex >= titleMeta->head.numContents)) { + ES_ImportTitleCancel(); + goto cleanup; + } + contentMeta = &titleMeta->contents[titleContentIndex]; + } else { + contentMeta = &titleMeta->contents[contentIndex]; + } + contentFd = ES_ImportContentBegin(titleMeta->head.titleId, contentMeta->cid); + if (contentFd < 0) { + result = contentFd; + ES_ImportContentEnd(contentFd); + ES_ImportTitleCancel(); + goto cleanup; + } + + remainingContentSize = ((u32)contentMeta->size + 0xF) & ~0xF; + while (remainingContentSize != 0) { + u32 chunkSize = remainingContentSize; + u32 readSize; + + if (chunkSize > remainingBufferSize) { + chunkSize = remainingBufferSize; + } + readSize = (chunkSize + 0x1F) & ~0x1F; + readResult = DVDReadPrio(&fileInfo, contentBuffer, readSize, sectionOffset, 2); + if ((u32)readResult != readSize) { + result = -3005; + ES_ImportContentEnd(contentFd); + ES_ImportTitleCancel(); + goto cleanup; + } + sectionOffset += readResult; + result = ES_ImportContentData(contentFd, contentBuffer, chunkSize); + if (result < 0) { + ES_ImportContentEnd(contentFd); + ES_ImportTitleCancel(); + goto cleanup; + } + remainingContentSize -= chunkSize; + } + sectionOffset = (sectionOffset + 0x3F) & ~0x3F; + result = ES_ImportContentEnd(contentFd); + if (result != 0) { + ES_ImportTitleCancel(); + goto cleanup; + } + contentIndex++; + } + + result = ES_ImportTitleDone(); + if (result != 0) { + ES_ImportTitleCancel(); + } + +cleanup: + if (fileOpened) { + DVDClose(&fileInfo); + } + return result; +} + +extern const u8 ca_ppki[]; +extern const u8 ms_ppki[]; +extern const u8 ca_dpki[]; +extern const u8 ms_dpki[]; +extern s32 SHA1Reset(void* context); +extern s32 SHA1Result(void* context, void* digest); + +static s32 WAD_815C43E0(WADHashThreadArgs* args) { + void* context; + s32 result; + u32 remaining; + u32 bufferIndex; + WADImportTransfer* transfer; + + context = args->context; + result = 0; + remaining = args->size; + bufferIndex = 0; + transfer = args->transfer; + + while ((remaining != 0) && (result == 0)) { + u32 size = remaining; + OSMutex* mutex; + + if (remaining > transfer->chunkSize) { + size = transfer->chunkSize; + } + mutex = &transfer->mutex[bufferIndex]; + OSLockMutex(mutex); + while (transfer->ready[bufferIndex] == 0) { + OSWaitCond(&transfer->signalCond[bufferIndex], mutex); + } + result = SHA1Input(context, transfer->buffers[bufferIndex], size); + transfer->ready[bufferIndex] = 0; + if (result != 0) { + transfer->error = 1; + } + OSUnlockMutex(mutex); + OSSignalCond(&transfer->waitCond[bufferIndex]); + remaining -= size; + bufferIndex ^= 1; + } + return result; +} + +static s32 _WADHash(WADStream* stream, u32 offset, u32 size, void* context, void* buffer, + u32 chunkSize, void* secondBuffer, void* threadStack, u32 threadStackSize) { + s32 result = 0; + + if ((stream == 0) || (context == 0) || (buffer == 0)) { + return -3000; + } + if (size != WAD_ALIGN32(size)) { + return -3000; + } + if (((u32)buffer & 0x1F) != 0) { + return -3007; + } + if (chunkSize != WAD_ALIGN32(chunkSize)) { + return -3000; + } + if ((secondBuffer == 0) || (threadStack == 0)) { + u32 completed = 0; + + while (size != 0) { + void* readBuffer = buffer; + u32 readSize = size; + + if (chunkSize < size) { + readSize = chunkSize; + } + result = WADReadStream(stream, &readBuffer, readSize, offset + completed); + if ((u32)result != readSize) { + result = -3005; + break; + } + result = SHA1Input(context, readBuffer, readSize); + if (result != 0) { + break; + } + completed += readSize; + size -= readSize; + } + } else { + WADImportTransfer transfer; + WADHashThreadArgs args; + OSThread thread; + s32 threadResult = 0; + u32 completed = 0; + u32 bufferIndex = 0; + BOOL readFailed = FALSE; + + WAD_815C4A2C(&transfer, buffer, secondBuffer, chunkSize); + args.context = context; + args.size = size; + args.transfer = &transfer; + if (!OSCreateThread(&thread, (void* (*)(void*))WAD_815C43E0, &args, + (u8*)threadStack + threadStackSize, threadStackSize, + OSGetThreadPriority(OSGetCurrentThread()), 0)) { + return -3009; + } + OSResumeThread(&thread); + while ((size != 0) && (transfer.error == 0)) { + void* readBuffer; + u32 readSize = size; + OSMutex* mutex = &transfer.mutex[bufferIndex]; + + if (chunkSize < size) { + readSize = chunkSize; + } + OSLockMutex(mutex); + while ((transfer.ready[bufferIndex] != 0) && (transfer.error == 0)) { + OSWaitCond(&transfer.waitCond[bufferIndex], mutex); + } + if (transfer.error != 0) { + OSUnlockMutex(mutex); + break; + } + readBuffer = transfer.buffers[bufferIndex]; + result = WADReadStream(stream, &readBuffer, readSize, offset + completed); + if ((u32)result != readSize) { + OSMutex* otherMutex = &transfer.mutex[bufferIndex ^ 1]; + + OSLockMutex(otherMutex); + OSCancelThread(&thread); + OSJoinThread(&thread, 0); + OSUnlockMutex(otherMutex); + OSUnlockMutex(mutex); + result = -3005; + readFailed = TRUE; + break; + } + transfer.ready[bufferIndex] = readSize; + OSUnlockMutex(mutex); + OSSignalCond(&transfer.signalCond[bufferIndex]); + completed += readSize; + size -= readSize; + bufferIndex ^= 1; + } + if (!readFailed) { + if (!OSJoinThread(&thread, &threadResult)) { + result = -3009; + } else { + result = threadResult; + } + } + } + return result; +} + +s32 WADVerify(WADStream* stream, MEMAllocator* allocator, u32 offset, u32 size) { + WADVerificationWorkspace workspace ALIGN64; + void* verificationBuffer = 0; + WADBackupSignature* backupSignature; + WADVerificationCertificateBundle* certificateBundle; + s32 result; + + workspace.readBuffer[0] = 0; + if (size != WAD_ALIGN32(size)) { + result = -3000; + } else if (size <= 0x340) { + result = -3000; + } else { + workspace.readBuffer[0] = _WADMemAlloc(allocator, 0x8000); + if (workspace.readBuffer[0] == 0) { + result = -3003; + } else if (((u32)workspace.readBuffer[0] & 0x3F) != 0) { + result = -3007; + } else { + u32 hashSize = size - 0x340; + + SHA1Reset(workspace.hashContext); + result = _WADHash(stream, offset, hashSize, workspace.hashContext, + workspace.readBuffer[0], 0x8000, 0, 0, 0x1000); + if (result == 0) { + result = SHA1Result(workspace.hashContext, workspace.digest); + if (result == 0) { + result = WADReadStream(stream, workspace.readBuffer, 0x340, + offset + hashSize); + if (result == 0x340) { + verificationBuffer = _WADMemAlloc(allocator, 0xF80); + if (verificationBuffer == 0) { + result = -3003; + } else { + backupSignature = workspace.readBuffer[0]; + certificateBundle = verificationBuffer; + memcpy(certificateBundle->caProduction, ca_ppki, 0x400); + memcpy(certificateBundle->msProduction, ms_ppki, 0x240); + memcpy(certificateBundle->caDevelopment, ca_dpki, 0x400); + memcpy(certificateBundle->msDevelopment, ms_dpki, 0x240); + memcpy(certificateBundle->firstCertificate, + backupSignature->firstCertificate, 0x180); + memcpy(certificateBundle->secondCertificate, + backupSignature->secondCertificate, 0x180); + result = ES_VerifySign(workspace.digest, 0x14, + workspace.readBuffer[0], verificationBuffer, + 0xF80); + } + } else { + result = -3005; + } + } + } + } + } + + if (workspace.readBuffer[0] != 0) { + _WADMemFree(allocator, workspace.readBuffer[0]); + } + if (verificationBuffer != 0) { + _WADMemFree(allocator, verificationBuffer); + } + return result; +} + +void WAD_815C4A2C(WADImportTransfer* transfer, void* firstBuffer, void* secondBuffer, + u32 chunkSize) { + transfer->chunkSize = chunkSize; + transfer->error = 0; + transfer->ready[1] = 0; + transfer->ready[0] = 0; + transfer->buffers[0] = firstBuffer; + transfer->buffers[1] = secondBuffer; + OSInitMutex(&transfer->mutex[0]); + OSInitMutex(&transfer->mutex[1]); + OSInitCond(&transfer->waitCond[0]); + OSInitCond(&transfer->waitCond[1]); + OSInitCond(&transfer->signalCond[0]); + OSInitCond(&transfer->signalCond[1]); +} + +#pragma dont_inline on +static u32 _WADIsTerminated(const char* text, u32 maxLength) { + u32 index; + + for (index = 0; index < maxLength; index++) { + if (text[index] == '\0') { + return TRUE; + } + } + return FALSE; +} +#pragma dont_inline reset -- 2.49.1 From 53be96c012c6d99075b1443962d909d1ae9fc57d Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Mon, 28 Sep 2026 22:51:32 -0500 Subject: [PATCH 25/61] Decompile PrFILE2 pf_dir to 20/38 functions (#247) * decompile pf_dir empty check * decompile pf_dir path handling * decompile pf_dir attribute and remove paths * decompile pf_dir fstat lookup * align pf dir metadata layouts * match pf dir wrappers * decompile pf dir fsexec paths * tune pf dir open scan * match pf dir slot scan * match pf dir handler close * match pf dir finalization loop * track free directory slot separately * align directory position error paths * align pf dir open path cases * match pf dir fsexec name helpers * match pf dir readdir loop --- libs/RVL_SDK/src/fa/pf_dir.c | 1526 ++++++++++++++++++++++++++++++++++ 1 file changed, 1526 insertions(+) create mode 100644 libs/RVL_SDK/src/fa/pf_dir.c diff --git a/libs/RVL_SDK/src/fa/pf_dir.c b/libs/RVL_SDK/src/fa/pf_dir.c new file mode 100644 index 00000000..734232f2 --- /dev/null +++ b/libs/RVL_SDK/src/fa/pf_dir.c @@ -0,0 +1,1526 @@ +#include + +#include +#include +#include +#include +#include +#include + +typedef struct PFDIR_FFD { + pf_u32 start_cluster; + pf_u32 flags; + pf_u32* p_start_cluster; + PF_LAST_CLUSTER last_cluster; + PF_FAT_LAST_ACCESS last_access_cluster; + PF_CLUSTER_LINK cluster_link; + struct PFDIR_FAT_HINT* p_hint; + PF_VOLUME* p_vol; +} PFDIR_FFD; + +typedef struct PFDIR_FAT_HINT { + pf_u32 chain_index; + pf_u32 cluster; + pf_u32 previous_cluster; +} PFDIR_FAT_HINT; + +typedef struct PFDIR_STR { + const pf_s8* p_head; + const pf_s8* p_tail; + const pf_s8* p_current; + pf_u32 code_mode; +} PFDIR_STR; + +struct PF_ENT_ITER { + pf_u32 index; + PF_VOLUME* p_vol; + PFDIR_FFD ffd; + pf_u32 file_sector_index; + pf_u32 sector; + pf_u16 offset; + pf_u16 offset_mask; + pf_u8 buf[32]; + pf_u8 log2_entries_per_sector; +}; + +typedef struct PFDIR_SDD { + pf_u32 stat; + pf_u16 num_handlers; + pf_u16 alignment; + PFDIR_FFD ffd; + PF_DIR_ENT dir_entry; +} PFDIR_SDD; + +typedef struct PFDIR_SFD { + pf_u32 stat; + pf_u16 num_handlers; + pf_u16 alignment; + PF_FFD ffd; + PF_DIR_ENT dir_entry; + pf_u8 lock_state[0x20]; +} PFDIR_SFD; + +typedef struct PFDIR_DIR { + pf_u32 stat; + PFDIR_SDD* p_sdd; + PFDIR_FAT_HINT hint; + pf_u32 current_position; + pf_u32 next_position; + pf_u32 end_position; +} PFDIR_DIR; + +typedef struct PFDIR_READ_RESULT { + pf_s8 name[0x200]; + pf_s8 short_name[0x200]; +} PFDIR_READ_RESULT; + +typedef struct PFDIR_FILE_STAT { + pf_u32 file_size; + pf_u16 access_date; + pf_u16 modify_time; + pf_u16 modify_date; + pf_u16 create_time; + pf_u16 create_date; + pf_u16 small_letter_flag; + pf_u8 attributes; +} PFDIR_FILE_STAT; + +typedef struct PFDIR_VOLUME_DIRS { + pf_u8 volume_prefix[0x40]; + PFDIR_SFD sfds[5]; + pf_u8 volume_state[0xF0]; + PFDIR_SDD sdds[3]; + PFDIR_DIR udds[3]; + pf_s32 num_opened_files; + pf_s32 num_opened_directories; + pf_u8 cache_state[0x20]; + void* cache_signature; + pf_u8 volume_tail[0x1F80 - 0x1648]; + pf_s32 last_error; +} PFDIR_VOLUME_DIRS; + +typedef struct PFDIR_GLOBAL_STATE { + pf_u8 state_prefix[0x40]; + pf_s32 last_error; +} PFDIR_GLOBAL_STATE; + +extern PFDIR_GLOBAL_STATE pf_vol_set; + +extern pf_s32 PFENT_ITER_MoveTo(PF_ENT_ITER* iter, pf_u32 index, pf_u32 may_allocate); +extern pf_s32 PFENT_ITER_Advance(PF_ENT_ITER* iter, pf_u32 may_allocate); +extern pf_s32 PFENT_ITER_IsAtLogicalEnd(PF_ENT_ITER* iter); +extern pf_s32 PFENT_ITER_GetEntryOfPath(PF_ENT_ITER* iter, PF_DIR_ENT* entry, PF_VOLUME* volume, PFDIR_STR* path, + pf_u32 no_look_last_token); +extern pf_s32 PFENT_GetRootDir(PF_VOLUME* volume, PF_DIR_ENT* entry); +extern pf_s32 PFVOL_GetCurrentDir(PF_VOLUME* volume, PF_DIR_ENT* entry); +extern pf_s32 PFVOL_SetCurrentDir(PF_VOLUME* volume, PF_DIR_ENT* entry); +extern pf_s32 PFFAT_InitFFD(void* ffd, void* hint, PF_VOLUME* volume, pf_u32* start_cluster); +extern void PFFAT_InitHint(PFDIR_FAT_HINT* hint); +extern pf_s32 PFSTR_StrNCmp(PFDIR_STR* path, const pf_s8* text, pf_u32 target, pf_s16 offset, pf_u16 count); +extern pf_u16 PFSTR_StrNumChar(PFDIR_STR* path, pf_u32 code_mode); +extern void PFSTR_MoveStrPos(PFDIR_STR* path, pf_s16 count); +extern pf_s32 PFSTR_InitStr(PFDIR_STR* path, const pf_s8* text, pf_u32 code_mode); +extern void PFSTR_SetLocalStr(PFDIR_STR* path, pf_u32 is_local); +extern pf_s32 PFENT_findEntryPos(PFDIR_FFD* ffd, PF_DIR_ENT* entry, pf_u32 start, PFDIR_STR* pattern, + pf_u8 attr_required, pf_u32 skip, pf_u32* logical_position, + pf_u32* entry_position); +extern pf_s8* pf_strcpy(pf_s8* destination, const pf_s8* source); +extern pf_s32 PFPATH_transformFromUnicodeToNormal(pf_s8* destination, const pf_u16* source); +extern pf_s32 PFPATH_SplitPath(PFDIR_STR* path, PFDIR_STR* directory, PFDIR_STR* filename); +extern pf_u8 PFENT_getcurrentDateTimeForEnt(pf_u16* date, pf_u16* time); +extern pf_s32 PFENT_updateEntry(PF_DIR_ENT* entry, pf_u32 clear_archive); +extern pf_s32 PFFILE_IsOpened(PF_DIR_ENT* entry); +extern pf_s32 PFVOL_CheckCurrentDir(PF_VOLUME* volume, pf_u32 start_cluster); +extern pf_s32 PFENT_RemoveEntry(PF_DIR_ENT* entry, PF_ENT_ITER* iter); +extern pf_s32 PFFAT_FreeChain(PFDIR_FFD* ffd, pf_u32 start_cluster, pf_u32 chain_index, pf_u32 size); + +pf_s32 PFDIR_CheckDirIsEmpty(PF_ENT_ITER* iter, pf_u32* is_empty) { + pf_u32 start_cluster = *iter->ffd.p_start_cluster; + pf_s32 error; + + if (start_cluster == 1 || + (iter->ffd.p_vol->bpb.fat_type == FAT_32 && + start_cluster == iter->ffd.p_vol->bpb.root_dir_cluster)) { + error = 0; + } else { + error = 2; + } + *is_empty = 1; + error = PFENT_ITER_MoveTo(iter, error, 0); + while (!PFENT_ITER_IsAtLogicalEnd(iter)) { + if (error != 0) { + if (error == 13) { + return 0; + } + return error; + } + if (iter->buf[0] != 0xE5) { + pf_u8 attributes = iter->buf[0xB]; + if ((attributes & 0xF) != 0xF && (attributes & 8) == 0) { + if (iter->buf[0] == 0) { + *is_empty = 1; + } else { + *is_empty = 0; + } + break; + } + } + error = PFENT_ITER_Advance(iter, 0); + } + return 0; +} + +PFDIR_SDD* PFDIR_GetSDD(PF_VOLUME* volume, PF_DIR_ENT* entry) { + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + PFDIR_SDD* first_free_sdd = 0; + PFDIR_SDD* free_candidate = volume_dirs->sdds; + pf_s32 i; + pf_s32 remaining = 3; + + for (i = 0; remaining != 0; i++, free_candidate++, remaining--) { + if ((volume_dirs->sdds[i].stat & 1) == 0) { + if (first_free_sdd == 0) { + first_free_sdd = free_candidate; + } + } else if (entry->p_vol == volume_dirs->sdds[i].dir_entry.p_vol && + entry->entry_sector == volume_dirs->sdds[i].dir_entry.entry_sector && + entry->entry_offset == volume_dirs->sdds[i].dir_entry.entry_offset) { + return &volume_dirs->sdds[i]; + } + } + if (first_free_sdd == 0) { + return 0; + } + first_free_sdd->stat = 3; + first_free_sdd->num_handlers = 0; + first_free_sdd->dir_entry = *entry; + PFFAT_InitFFD(&first_free_sdd->ffd, 0, entry->p_vol, &first_free_sdd->dir_entry.start_cluster); + return first_free_sdd; +} + +pf_s32 PFDIR_DoFsexecOpenDir(PF_DIR_ENT* entry, PF_ENT_ITER* iter, PFDIR_DIR** opened_dir) { + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)entry->p_vol; + PFDIR_SDD* sdd; + PFDIR_DIR* dir; + PFDIR_DIR* scan_dir; + pf_s32 i; + + *opened_dir = 0; + if ((entry->attr & 0x10) == 0) { + return 0x14; + } + sdd = PFDIR_GetSDD(entry->p_vol, entry); + if (sdd == 0) { + return 0x15; + } + dir = 0; + scan_dir = volume_dirs->udds; + for (i = 0; i < 3; i++, scan_dir++) { + if ((scan_dir->stat & 1) == 0) { + dir = &volume_dirs->udds[i]; + break; + } + } + if (dir == 0) { + return 0x16; + } + dir->p_sdd = sdd; + dir->stat = 1; + PFFAT_InitHint(&dir->hint); + dir->current_position = 0; + dir->next_position = 0; + dir->end_position = 0; + sdd->num_handlers++; + *opened_dir = dir; + return 0; +} + +pf_s32 PFDIR_p_opendir(PF_VOLUME* volume, PFDIR_STR* path, PFDIR_DIR** opened_dir) { + PF_ENT_ITER iter; + PF_DIR_ENT entry; + PFDIR_SDD* sdd; + PFDIR_DIR* dir; + pf_s32 error; + pf_s32 i; + + if ((PFSTR_StrNCmp(path, (const pf_s8*)"\\", 1, 0, 1) == 0 || + PFSTR_StrNCmp(path, (const pf_s8*)"/", 1, 0, 1) == 0) && + PFSTR_StrNCmp(path, (const pf_s8*)"", 1, 1, 1) == 0) { + error = PFENT_GetRootDir(volume, &entry); + if (error != 0) { + return error; + } + goto open_directory; + } else if (PFSTR_StrNumChar(path, 1) == 2 && + PFSTR_StrNCmp(path, (const pf_s8*)":", 1, 1, 1) == 0) { + error = PFVOL_GetCurrentDir(volume, &entry); + if (error != 0) { + return error; + } + goto open_directory; + } else if (PFSTR_StrNumChar(path, 1) == 3 && + PFSTR_StrNCmp(path, (const pf_s8*)":", 1, 1, 1) == 0 && + (PFSTR_StrNCmp(path, (const pf_s8*)"\\", 1, 2, 1) == 0 || + PFSTR_StrNCmp(path, (const pf_s8*)"/", 1, 2, 1) == 0)) { + error = PFENT_GetRootDir(volume, &entry); + if (error != 0) { + return error; + } + goto open_directory; + } else { + if (PFSTR_StrNCmp(path, (const pf_s8*)":", 1, 1, 1) == 0 && + (PFSTR_StrNCmp(path, (const pf_s8*)"\\", 1, 2, 1) == 0 || + PFSTR_StrNCmp(path, (const pf_s8*)"/", 1, 2, 1) == 0)) { + PFSTR_MoveStrPos(path, 2); + } + error = PFENT_ITER_GetEntryOfPath(&iter, &entry, volume, path, 0); + if (error != 0) { + return error; + } + if ((entry.attr & 0x10) == 0) { + return 1; + } + } + +open_directory: + sdd = PFDIR_GetSDD(volume, &entry); + if (sdd == 0) { + return 0x15; + } + dir = ((PFDIR_VOLUME_DIRS*)volume)->udds; + i = 0; + do { + if ((dir->stat & 1) == 0) { + break; + } + i++; + dir++; + } while (i < 3); + if (i == 3) { + return 0x16; + } + dir->p_sdd = sdd; + dir->stat = 1; + PFFAT_InitHint(&dir->hint); + dir->current_position = 0; + dir->next_position = 0; + dir->end_position = 0; + sdd->num_handlers++; + *opened_dir = dir; + return 0; +} + +pf_s32 PFDIR_p_readdir(PFDIR_DIR* dir, PFDIR_READ_RESULT* result) { + PFDIR_FFD ffd; + PFDIR_FAT_HINT hint; + PF_DIR_ENT entry; + PFDIR_STR pattern; + pf_u32 remaining; + pf_u32 logical_position; + pf_u32 entry_position; + pf_s32 error; + + PFFAT_InitFFD(&ffd, &hint, dir->p_sdd->ffd.p_vol, &dir->p_sdd->dir_entry.start_cluster); + remaining = dir->end_position; + if (dir->next_position <= remaining) { + remaining -= dir->next_position; + } else if (dir->next_position > remaining) { + dir->current_position = 0; + dir->next_position = 0; + } + do { + PFSTR_InitStr(&pattern, (const pf_s8*)"*", 1); + PFSTR_SetLocalStr(&pattern, 0); + error = PFENT_findEntryPos(&ffd, &entry, dir->current_position, &pattern, 0x7F, 0, + &logical_position, &entry_position); + if (error != 0) { + return error; + } + dir->current_position = entry_position + 1; + dir->next_position++; + } while (remaining-- != 0); + dir->end_position = dir->next_position; + pf_strcpy(result->short_name, entry.short_name); + if (entry.long_name[0] != 0) { + PFPATH_transformFromUnicodeToNormal(result->name, entry.long_name); + } else { + result->name[0] = 0; + } + return 0; +} + +pf_s32 PFDIR_p_mkdir(PF_VOLUME* p_vol, PF_STR* p_path, pf_u32 option, PF_DTA* p_dta) { + pf_s32 err; + PF_STR full_path; + PF_STR dirname; + pf_u16 dirname_len; + PF_DIR_ENT entry; + PF_DIR_ENT parent_entry; + PF_FFD ffd; + pf_u32 pos; + PF_FAT_HINT fat_hint; + pf_u32 prev_chain[2]; + pf_u32 new_sector; + + (void)option; + + err = 0; + new_sector = 0; + + err = VFiPFPATH_SplitPath(p_path, &full_path, &dirname); + if (err != 0) { + return err; + } + err = VFiPFENT_GetParentEntryOfPath(&parent_entry, p_vol, &full_path); + if (err != 0) { + return err; + } + if ((parent_entry.attr & 0x10) == 0) { + err = 0x14; + } + if (p_dta != PF_NULL) { + p_dta->parent_start_cluster = parent_entry.start_cluster; + } + VFiPFFAT_InitFFD(&ffd, &fat_hint, p_vol, &parent_entry.start_cluster); + err = VFiPFENT_findEntry(&ffd, &entry, 0U, &dirname, 0x77U, PF_NULL, PF_NULL); + if (err == 0) { + return 8; + } + if (err != 3) { + return err; + } + dirname_len = VFiPFSTR_StrNumChar(&dirname, 1U); + if ((dirname_len > 0xFFU) || ((dirname_len + parent_entry.path_len) > 0x103U)) { + return 2; + } + err = VFiPFENT_InitENT(&entry, &dirname, 0x10U, 1U, &parent_entry, p_vol); + if (err == 0) { + VFiPFFAT_InitFFD(&ffd, &fat_hint, p_vol, &parent_entry.start_cluster); + err = VFiPFENT_allocateEntry(&entry, (entry.num_entry_LFNs + 1), &ffd, prev_chain, PF_NULL, 0x77U, &pos); + if (err == 0) { + entry.start_cluster = 0; + VFiPFFAT_InitFFD(&ffd, &fat_hint, p_vol, &entry.start_cluster); + err = VFiPFFAT_GetSectorSpecified(&ffd, 0U, 1U, &new_sector); + if (new_sector == -1U) { + err = 6; + } + if (err == 0) { + err = VFiPFENT_FillVoidEntryToSectors(p_vol, new_sector, p_vol->bpb.sectors_per_cluster, 1U, &entry, &parent_entry); + if (err == 0) { + if ((entry.long_name[0] != 0) && ((VFipf_vol_set.setting & 2) == 2)) { + VFiPFPATH_AdjustExtShortName(&entry.short_name[0], pos); + entry.check_sum = VFiPFENT_CalcCheckSum(&entry); + } + err = VFiPFENT_UpdateEntry(&entry, prev_chain, 0U); + } + if (err != 0) { + VFiPFFAT_FreeChain(&ffd, entry.start_cluster, -1U, -1U); + } else if (p_dta != PF_NULL) { + p_dta->p_file = PF_NULL; + p_dta->p_dir = PF_NULL; + p_dta->p_vol = p_vol; + p_dta->parent_pos = pos + 1; + p_dta->num_entry_LFNs = entry.num_entry_LFNs; + p_dta->attr = entry.attr; + p_dta->Time = entry.modify_time; + p_dta->Date = entry.modify_date; + p_dta->FileSize = entry.file_size; + p_dta->Attribute = entry.attr; + if (VFiPFSTR_GetCodeMode(&dirname) == 1) { + VFiPFPATH_SetSearchPattern(p_dta->reg_exp, PF_NULL, &dirname); + p_dta->status |= 1; + } else { + VFiPFPATH_SetSearchPattern(p_dta->reg_exp, ((PF_DTAW*)p_dta)->reg_expW, &dirname); + p_dta->status |= 2; + } + VFipf_strcpy(p_dta->FileName, &entry.short_name[0]); + if ((p_dta->status & 2) == 2) { + VFiPFPATH_transformInUnicode(((PF_DTAW*)p_dta)->FileNameW, p_dta->FileName); + } + if (entry.long_name[0] == 0) { + p_dta->ordinal = 0; + p_dta->check_sum = 0; + p_dta->LongName[0] = 0; + if ((p_dta->status & 2) == 2) { + ((PF_DTAW*)p_dta)->LongNameW[0] = 0; + } + } else { + p_dta->ordinal = 1; + p_dta->check_sum = entry.check_sum; + if ((VFipf_vol_set.setting & 2) == 2) { + VFipf_vol_set.setting &= 0xFFFFFFFC; + VFipf_vol_set.setting |= 1; + VFiPFPATH_transformFromUnicodeToNormal(p_dta->LongName, entry.long_name); + VFipf_vol_set.setting &= 0xFFFFFFFC; + VFipf_vol_set.setting |= 2; + } else { + VFiPFPATH_transformFromUnicodeToNormal(p_dta->LongName, entry.long_name); + } + if ((p_dta->status & 2) == 2) { + VFipf_w_strcpy(((PF_DTAW*)p_dta)->LongNameW, entry.long_name); + } + } + } + } + } + } + +exit: + return err; +} + +pf_s32 PFDIR_p_chdir(PF_VOLUME* p_vol, PFDIR_STR* p_path_str) { + pf_s32 err; + PF_ENT_ITER iter; + PF_DIR_ENT entry_dir; + + if (((PFSTR_StrNCmp(p_path_str, (pf_s8*)"\\", 1U, 0, 1U) == 0) || (PFSTR_StrNCmp(p_path_str, (pf_s8*)"/", 1U, 0, 1U) == 0)) && + (PFSTR_StrNCmp(p_path_str, (pf_s8*)"\0", 1U, 1, 1U) == 0)) { + err = PFENT_GetRootDir(p_vol, &entry_dir); + if (err != 0) { + return err; + } + err = PFVOL_SetCurrentDir(p_vol, &entry_dir); + if (err != 0) { + return err; + } + + return 0; + } + if ((PFSTR_StrNumChar(p_path_str, 1U) == 2) && (PFSTR_StrNCmp(p_path_str, (pf_s8*)":", 1U, 1, 1U) == 0)) { + return 0; + } + if ((PFSTR_StrNumChar(p_path_str, 1U) == 3) && (PFSTR_StrNCmp(p_path_str, (pf_s8*)":", 1U, 1, 1U) == 0) && + ((PFSTR_StrNCmp(p_path_str, (pf_s8*)"\\", 1U, 2, 1U) == 0) || (PFSTR_StrNCmp(p_path_str, (pf_s8*)"/", 1U, 2, 1U) == 0))) { + err = PFENT_GetRootDir(p_vol, &entry_dir); + if (err != 0) { + return err; + } + err = PFVOL_SetCurrentDir(p_vol, &entry_dir); + if (err != 0) { + return err; + } + + return 0; + } + if ((PFSTR_StrNCmp(p_path_str, (pf_s8*)":", 1U, 1, 1U) == 0) && + ((PFSTR_StrNCmp(p_path_str, (pf_s8*)"\\", 1U, 2, 1U) == 0) || (PFSTR_StrNCmp(p_path_str, (pf_s8*)"/", 1U, 2, 1U) == 0))) { + PFSTR_MoveStrPos(p_path_str, 2); + } + err = PFENT_ITER_GetEntryOfPath(&iter, &entry_dir, p_vol, p_path_str, 0); + if (err != 0) { + return err; + } + if ((entry_dir.attr & 0x10) == 0) { + return 0x14; + } + err = PFVOL_SetCurrentDir(p_vol, &entry_dir); + if (err != 0) { + return err; + } + + return 0; +} + +pf_s32 PFDIR_p_chmod(PF_VOLUME* volume, PFDIR_STR* path, pf_u8 attributes) { + PFDIR_STR directory_path; + PFDIR_STR filename; + PF_ENT_ITER iter; + PF_DIR_ENT entry; + PFDIR_VOLUME_DIRS* volume_dirs; + pf_u16 date; + pf_u16 time; + pf_u8 create_time_ms; + pf_u32 i; + pf_s32 error; + + error = PFPATH_SplitPath(path, &directory_path, &filename); + if (error != 0) { + return error; + } + error = PFENT_ITER_GetEntryOfPath(&iter, &entry, volume, path, 0); + if (error != 0) { + return error; + } + if (((entry.attr & 0x10) == 0 && (attributes & 0x10) != 0) || + ((entry.attr & 0x10) != 0 && (attributes & 0x10) == 0)) { + return 10; + } + if ((attributes & 0x40) != 0) { + attributes &= (pf_u8)~0x40; + } + if ((entry.attr & 0x10) == 0) { + if (PFFILE_IsOpened(&entry) != 0) { + return 0x13; + } + } else { + volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + for (i = 0; i < 3; i++) { + PFDIR_SDD* sdd = &volume_dirs->sdds[i]; + if ((sdd->stat & 1) != 0 && (sdd->stat & 2) != 0 && + entry.p_vol == sdd->dir_entry.p_vol && + entry.entry_sector == sdd->dir_entry.entry_sector && + entry.entry_offset == sdd->dir_entry.entry_offset) { + return 0x13; + } + } + if ((attributes & 4) != 0 && (attributes & 0xF) != 0xF) { + return 10; + } + attributes |= 0x10; + } + create_time_ms = PFENT_getcurrentDateTimeForEnt(&date, &time); + entry.modify_date = date; + entry.modify_time = time; + entry.create_time_ms = create_time_ms; + entry.attr = attributes; + return PFENT_updateEntry(&entry, 0); +} + +pf_s32 PFDIR_p_rmdir(PF_VOLUME* volume, PFDIR_STR* path) { + PFDIR_VOLUME_DIRS* volume_dirs; + PFDIR_FAT_HINT hint; + PFDIR_FFD ffd; + PF_ENT_ITER iter; + PF_ENT_ITER directory_iter; + PF_DIR_ENT entry; + pf_u32 is_empty; + pf_u32 i; + pf_s32 error; + + error = PFENT_ITER_GetEntryOfPath(&iter, &entry, volume, path, 0); + if (error != 0) { + return error; + } + if ((entry.attr & 0x10) == 0 || (entry.attr & 1) != 0) { + return 0x14; + } + if (entry.start_cluster == 1 || + (volume->bpb.fat_type == FAT_32 && entry.start_cluster == volume->bpb.root_dir_cluster)) { + return 0x1C; + } + volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + for (i = 0; i < 3; i++) { + PFDIR_SDD* sdd = &volume_dirs->sdds[i]; + if ((sdd->stat & 3) == 3 && entry.p_vol == sdd->dir_entry.p_vol && + entry.entry_sector == sdd->dir_entry.entry_sector && + entry.entry_offset == sdd->dir_entry.entry_offset) { + return 0x13; + } + } + error = PFVOL_CheckCurrentDir(volume, entry.start_cluster); + if (error != 0) { + return 0x1C; + } + PFFAT_InitFFD(&ffd, &hint, volume, &entry.start_cluster); + directory_iter.ffd = ffd; + error = PFENT_ITER_IteratorInitialize(&directory_iter, 0); + if (error != 0) { + return error; + } + is_empty = 0; + error = PFDIR_CheckDirIsEmpty(&directory_iter, &is_empty); + if (error != 0) { + return error; + } + if (is_empty == 0) { + return 0x1D; + } + error = PFENT_RemoveEntry(&entry, &iter); + if (error != 0) { + return error; + } + return PFFAT_FreeChain(&iter.ffd, entry.start_cluster, -1U, -1U); +} + +pf_s32 PFDIR_p_fstat(PF_VOLUME* volume, PFDIR_STR* path, PFDIR_FILE_STAT* file_stat) { + PF_ENT_ITER iter; + PF_DIR_ENT entry; + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_u32 index; + pf_s32 error; + + error = PFENT_ITER_GetEntryOfPath(&iter, &entry, volume, path, 0); + if (error != 0) { + return error; + } + if (volume_dirs->num_opened_files != 0) { + for (index = 0; index < 5; index++) { + PFDIR_SFD* sfd = &volume_dirs->sfds[index]; + if ((sfd->stat & 1) != 0 && (sfd->stat & 2) != 0 && + entry.p_vol == sfd->dir_entry.p_vol && + entry.entry_sector == sfd->dir_entry.entry_sector && + entry.entry_offset == sfd->dir_entry.entry_offset) { + file_stat->file_size = sfd->dir_entry.file_size; + file_stat->access_date = sfd->dir_entry.access_date; + file_stat->modify_time = sfd->dir_entry.modify_time; + file_stat->modify_date = sfd->dir_entry.modify_date; + file_stat->create_time = sfd->dir_entry.create_time; + file_stat->create_date = sfd->dir_entry.create_date; + file_stat->small_letter_flag = sfd->dir_entry.small_letter_flag; + file_stat->attributes = sfd->dir_entry.attr; + break; + } + } + } + if (volume_dirs->num_opened_files == 0 || index == 5) { + file_stat->file_size = (entry.attr & 0x10) == 0 ? entry.file_size : 0; + file_stat->access_date = entry.access_date; + file_stat->modify_time = entry.modify_time; + file_stat->modify_date = entry.modify_date; + file_stat->create_time = entry.create_time; + file_stat->create_date = entry.create_date; + file_stat->small_letter_flag = entry.small_letter_flag; + file_stat->attributes = entry.attr; + } + return 0; +} + +extern PF_VOLUME* PFPATH_GetVolumeFromPath(PF_STR* path); +extern pf_s32 PFCACHE_FlushDataCacheSpecific(PF_VOLUME* volume, void* entry); +extern pf_s32 PFCACHE_FlushFATCache(PF_VOLUME* volume); +extern pf_s32 PFDIR_p_fsfirst(PF_VOLUME* volume, PF_STR* path, pf_u8 attributes, PF_DTA* data); +extern pf_s32 PFDIR_p_fsnext(PF_DTA* data); +extern pf_s32 PFDIR_p_fsexec(PF_DTA* data, pf_u32 flags, pf_u32 mode); +extern pf_s32 PFDIR_p_rename(PF_VOLUME* volume, PF_STR* old_path, PF_STR* new_path); +extern pf_s32 PFDIR_p_move(PF_VOLUME* volume, PF_STR* old_path, PF_STR* new_path); +extern pf_s32 PFDIR_p_fsexec_chmod(PF_DTA* data, PF_DIR_ENT* entry, pf_u32 attributes, pf_u32 mode); +extern pf_s32 PFDIR_p_fsexec_remove(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter); +extern pf_s32 PFDIR_p_fsexec_fopen(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter, pf_u32 flags, + pf_u32 mode); +extern pf_s32 PFDIR_p_fsexec_opendir(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter, pf_u32 flags); +extern void PFFAT_FinalizeFFD(PF_FFD* ffd); +extern pf_s32 PFENT_ITER_GetEntryOfPattern(PF_ENT_ITER* iter, PF_DIR_ENT* entry, PF_VOLUME* volume, + PFDIR_STR* directory); +extern pf_s32 PFENT_findEntry(PFDIR_FFD* ffd, PF_DIR_ENT* entry, pf_u32 start, PFDIR_STR* pattern, + pf_u8 attributes, pf_u32* logical_position, pf_u32* entry_position); +extern pf_u32 PFSTR_GetCodeMode(PFDIR_STR* path); +extern pf_s32 PFPATH_SplitPathPattern(PF_STR* path, PFDIR_STR* directory, PFDIR_STR* pattern); +extern void PFPATH_SetSearchPattern(pf_s8* ansi_pattern, pf_u16* unicode_pattern, PFDIR_STR* pattern); +extern pf_u16* pf_w_strcpy(pf_u16* destination, const pf_u16* source); +extern pf_s32 PFPATH_transformInUnicode(pf_u16* destination, const pf_s8* source); +extern pf_s32 PFPATH_parseShortName(PF_DIR_ENT* entry, const pf_s8* name); +extern pf_s32 PFENT_ITER_GetLFNEntryName(PF_ENT_ITER* iter); +extern void PFPATH_getLongNameformShortName(pf_s8* short_name, pf_s8* long_name, pf_u8 small_letter_flag); +extern pf_s32 PFFILE_FsexecOpenFile(PF_DIR_ENT* entry, PF_ENT_ITER* iter, pf_u32 mode, PF_DTA* data); +extern pf_s32 PFPATH_cmpName(const pf_s8* short_name, PFDIR_STR* pattern, pf_u32 short_search); +extern pf_s32 PFPATH_cmpNameUni(const pf_u16* name, PFDIR_STR* pattern); + +pf_s32 PFDIR_p_fsexec_remove(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter) { + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)entry->p_vol; + PFDIR_FAT_HINT hint; + PF_ENT_ITER directory_iter; + pf_u32 is_empty; + pf_u32 index; + pf_u32 start_cluster = entry->start_cluster; + pf_s32 error; + + if ((entry->attr & 1) != 0) { + return 0x18; + } + if ((entry->attr & 0x10) != 0) { + if (PFVOL_CheckCurrentDir(entry->p_vol, entry->start_cluster) != 0 || entry->start_cluster == 1 || + (entry->p_vol->bpb.fat_type == FAT_32 && + entry->start_cluster == entry->p_vol->bpb.root_dir_cluster)) { + return 0x1C; + } + for (index = 0; index < 3; index++) { + PFDIR_SDD* sdd = &volume_dirs->sdds[index]; + if ((sdd->stat & 1) != 0 && (sdd->stat & 2) != 0 && + sdd->dir_entry.p_vol == entry->p_vol && + sdd->dir_entry.entry_sector == entry->entry_sector && + sdd->dir_entry.entry_offset == entry->entry_offset) { + return 0x13; + } + } + directory_iter = *iter; + PFFAT_InitFFD(&directory_iter.ffd, &hint, entry->p_vol, &entry->start_cluster); + error = PFENT_ITER_IteratorInitialize(&directory_iter, 0); + if (error != 0) { + return error; + } + is_empty = 0; + error = PFDIR_CheckDirIsEmpty(&directory_iter, &is_empty); + if (error != 0) { + return error; + } + if (is_empty == 0) { + return 0x1D; + } + } else if (PFFILE_IsOpened(entry) != 0) { + return 0x13; + } + entry->num_entry_LFNs = data->num_entry_LFNs; + entry->ordinal = data->ordinal; + entry->check_sum = data->check_sum; + error = PFENT_RemoveEntry(entry, iter); + if (error != 0) { + return error; + } + return PFFAT_FreeChain(&iter->ffd, start_cluster, -1U, -1U); +} + +pf_s32 PFDIR_p_fsexec_chmod(PF_DTA* data, PF_DIR_ENT* entry, pf_u32 attributes, pf_u32 mode) { + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)entry->p_vol; + pf_u16 date; + pf_u16 time; + pf_u8 create_time_ms; + pf_u32 index; + pf_s32 error; + + if ((attributes & 0x40) != 0) { + attributes &= ~0x40; + } + if ((entry->attr & 0x10) == 0) { + if ((attributes & 0x10) != 0) { + return 10; + } + if (PFFILE_IsOpened(entry) != 0) { + return 0x13; + } + entry->attr = attributes; + } else { + if ((attributes & 4) != 0) { + return 10; + } + for (index = 0; index < 3; index++) { + PFDIR_SDD* sdd = &volume_dirs->sdds[index]; + if ((sdd->stat & 1) != 0 && (sdd->stat & 2) != 0 && + sdd->dir_entry.p_vol == entry->p_vol && + sdd->dir_entry.entry_sector == entry->entry_sector && + sdd->dir_entry.entry_offset == entry->entry_offset) { + return 0x13; + } + } + entry->attr = attributes | 0x10; + } + create_time_ms = PFENT_getcurrentDateTimeForEnt(&date, &time); + entry->modify_date = date; + entry->modify_time = time; + entry->create_time_ms = create_time_ms; + error = PFENT_updateEntry(entry, 0); + if (error != 0) { + return error; + } + if ((mode & 0x80000000) == 0) { + data->Attribute = entry->attr; + } + return PFCACHE_FlushDataCacheSpecific(entry->p_vol, 0); +} + +pf_s32 PFDIR_p_fsexec_fopen(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter, pf_u32 flags, + pf_u32 mode) { + pf_s8 long_name[13]; + pf_s32 error; + + if ((flags & 0x80000000) != 0) { + entry->num_entry_LFNs = data->num_entry_LFNs; + entry->ordinal = data->ordinal; + entry->check_sum = data->check_sum; + if ((iter->buf[0xC] & 0x18) != 0) { + PFPATH_getLongNameformShortName(entry->short_name, long_name, iter->buf[0xC]); + PFPATH_transformInUnicode(entry->long_name, long_name); + } else { + error = PFENT_ITER_GetLFNEntryName(iter); + if (error != 0) { + return error; + } + } + } + error = PFFILE_FsexecOpenFile(entry, iter, mode, data); + if (error != 0) { + return error; + } + error = 0; + ((PFDIR_VOLUME_DIRS*)data->p_vol)->num_opened_files++; + return error; +} + +pf_s32 PFDIR_p_fsexec_opendir(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter, pf_u32 flags) { + pf_s8 long_name[13]; + pf_s32 error; + + if ((flags & 0x80000000) != 0) { + entry->num_entry_LFNs = data->num_entry_LFNs; + entry->ordinal = data->ordinal; + entry->check_sum = data->check_sum; + if ((iter->buf[0xC] & 0x18) != 0) { + PFPATH_getLongNameformShortName(entry->short_name, long_name, iter->buf[0xC]); + PFPATH_transformInUnicode(entry->long_name, long_name); + } else { + error = PFENT_ITER_GetLFNEntryName(iter); + if (error != 0) { + return error; + } + } + } + error = PFDIR_DoFsexecOpenDir(entry, iter, (PFDIR_DIR**)&data->p_dir); + if (error != 0) { + return error; + } + error = 0; + ((PFDIR_VOLUME_DIRS*)data->p_vol)->num_opened_directories++; + return error; +} + +pf_s32 PFDIR_p_fsexec(PF_DTA* data, pf_u32 flags, pf_u32 mode) { + PFDIR_FFD ffd; + PFDIR_FAT_HINT hint; + PF_ENT_ITER iter; + PF_DIR_ENT entry; + PFDIR_STR pattern; + pf_u32 logical_position; + pf_u32 entry_position; + pf_u32 start_position; + pf_u32 code_mode; + const pf_s8* name; + pf_s32 error; + + if ((flags & 0x26) == 0 && (flags & 1) == 0) { + return 10; + } + if ((flags & 0x26) != 0 || (flags & 1) != 0 || ((flags & 0x10) != 0 && mode != 2)) { + error = PFVOL_CheckForWrite(data->p_vol); + if (error != 0) { + return error; + } + } + start_position = data->parent_pos - 1; + if ((flags & 0x80000000) == 0) { + start_position -= data->num_entry_LFNs; + } + PFFAT_InitFFD(&ffd, &hint, data->p_vol, &data->parent_start_cluster); + iter.p_vol = data->p_vol; + iter.ffd = ffd; + error = PFENT_ITER_IteratorInitialize(&iter, start_position); + if (error != 0) { + return error; + } + if ((data->status & 1) != 0) { + code_mode = 1; + name = data->FileName; + } else { + code_mode = 2; + if ((VFipf_vol_set.setting & 2) != 0) { + name = (const pf_s8*)((PF_DTAW*)data)->LongNameW; + } else { + name = (const pf_s8*)((PF_DTAW*)data)->FileNameW; + } + } + error = PFSTR_InitStr(&pattern, name, code_mode); + if (error != 0) { + return error; + } + if ((VFipf_vol_set.setting & 2) != 0) { + PFSTR_SetLocalStr(&pattern, (pf_u32)data->LongName); + } else { + PFSTR_SetLocalStr(&pattern, (pf_u32)data->FileName); + } + error = PFENT_findEntryPos(&ffd, &entry, start_position, &pattern, 0x7F, 0, + &logical_position, &entry_position); + if (error != 0) { + return error; + } + if ((flags & 0x80000000) == 0) { + if ((data->status & 2) != 0) { + if (PFPATH_cmpNameUni(entry.long_name, &pattern) != 0) { + return 3; + } + } else if (PFPATH_cmpName(entry.short_name, &pattern, 1) != 0) { + return 3; + } + } + if (entry.short_name[0] == '.' && + ((entry.short_name[1] == ' ' && entry.short_name[2] == ' ') || entry.short_name[1] == '.')) { + return 0x1C; + } + error = PFENT_ITER_MoveTo(&iter, entry_position, 0); + if (error != 0) { + return error; + } + if ((flags & 6) != 0) { + return PFDIR_p_fsexec_chmod(data, &entry, flags, mode); + } + if ((flags & 1) != 0) { + return PFDIR_p_fsexec_remove(data, &entry, &iter); + } + if ((flags & 0x10) != 0) { + return PFDIR_p_fsexec_fopen(data, &entry, &iter, flags, mode); + } + if ((flags & 0x20) != 0) { + return PFDIR_p_fsexec_opendir(data, &entry, &iter, flags); + } + return 10; +} + +void PFDIR_FinalizeAllDirs(PF_VOLUME* volume) { + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_u16 index; + + for (index = 0; index < 3; index++) { + volume_dirs->sdds[index].stat = 0; + PFFAT_FinalizeFFD((PF_FFD*)&volume_dirs->sdds[index].ffd); + } + volume_dirs->udds[0].stat &= ~1; + volume_dirs->udds[1].stat &= ~1; + volume_dirs->udds[2].stat &= ~1; + volume_dirs->num_opened_directories = 0; +} + +void PFDIR_fsfirst(PF_STR* path, pf_u8 attributes, PF_DTA* data) { + PF_VOLUME* volume = PFPATH_GetVolumeFromPath(path); + pf_s32 error = PFVOL_CheckForRead(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + error = PFDIR_p_fsfirst(volume, path, attributes, data); + if (error != 0) { + data->p_vol = 0; + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } +} + +void PFDIR_fsnext(PF_DTA* data) { + PF_VOLUME* volume = data->p_vol; + pf_s32 error = PFVOL_CheckForRead(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + error = PFDIR_p_fsnext(data); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } +} + +void PFDIR_fsexec(PF_DTA* data, pf_u32 flags, pf_u32 mode) { + PF_VOLUME* volume = data->p_vol; + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_s32 error = PFVOL_CheckForRead(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + volume_dirs->cache_signature = 0; + error = PFDIR_p_fsexec(data, flags, mode); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushFATCache(volume); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } + } + volume_dirs->cache_signature = 0; +} + +void PFDIR_fstat(PF_STR* path, PFDIR_FILE_STAT* file_stat) { + PF_VOLUME* volume = PFPATH_GetVolumeFromPath(path); + pf_s32 error = PFVOL_CheckForRead(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + error = PFDIR_p_fstat(volume, (PFDIR_STR*)path, file_stat); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } +} + +void PFDIR_rename(PF_STR* old_path, PF_STR* new_path) { + PF_VOLUME* volume = PFPATH_GetVolumeFromPath(old_path); + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_s32 error = PFVOL_CheckForWrite(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + volume_dirs->cache_signature = 0; + error = PFDIR_p_rename(volume, old_path, new_path); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushFATCache(volume); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushDataCacheSpecific(volume, 0); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } + } + } + volume_dirs->cache_signature = 0; +} + +void PFDIR_move(PF_STR* old_path, PF_STR* new_path) { + PF_VOLUME* volume = PFPATH_GetVolumeFromPath(old_path); + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_s32 error = PFVOL_CheckForWrite(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + volume_dirs->cache_signature = 0; + error = PFDIR_p_move(volume, old_path, new_path); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushFATCache(volume); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushDataCacheSpecific(volume, 0); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } + } + } + volume_dirs->cache_signature = 0; +} + +void PFDIR_opendir(PF_STR* path, PFDIR_DIR** dir) { + PF_VOLUME* volume = PFPATH_GetVolumeFromPath(path); + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_s32 error = PFVOL_CheckForRead(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + error = PFDIR_p_opendir(volume, (PFDIR_STR*)path, dir); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + volume_dirs->num_opened_directories++; + } +} + +pf_s32 PFDIR_closedir(PFDIR_DIR* dir) { + PF_VOLUME* volume = dir == 0 ? 0 : dir->p_sdd->dir_entry.p_vol; + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_s32 error = PFVOL_CheckForRead(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return error; + } + if ((dir->p_sdd->stat & 1) == 0 || (dir->p_sdd->stat & 2) == 0) { + error = 10; + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return error; + } + if (--dir->p_sdd->num_handlers == 0) { + dir->p_sdd->stat &= ~1; + } + dir->stat &= ~1; + volume_dirs->num_opened_directories--; + return 0; +} + +pf_s32 PFDIR_readdir(PFDIR_DIR* dir, PFDIR_READ_RESULT* result) { + PF_VOLUME* volume = dir == 0 ? 0 : dir->p_sdd->dir_entry.p_vol; + pf_s32 error = PFVOL_CheckForWrite(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return error; + } + if ((dir->p_sdd->stat & 1) == 0 || (dir->p_sdd->stat & 2) == 0) { + error = 10; + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return error; + } + error = PFDIR_p_readdir(dir, result); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } + return error; +} + +pf_s32 PFDIR_telldir(PFDIR_DIR* dir, pf_u32* position) { + PF_VOLUME* volume = dir == 0 ? 0 : dir->p_sdd->dir_entry.p_vol; + PFDIR_SDD* sdd; + pf_s32 error = PFVOL_CheckForWrite(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + sdd = dir->p_sdd; + if ((sdd->stat & 1) == 0 || (sdd->stat & 2) == 0) { + error = 10; + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + *position = dir->end_position != 0 ? dir->end_position : dir->next_position; + } + } + return error; +} + +pf_s32 PFDIR_seekdir(PFDIR_DIR* dir, pf_u32 position) { + PF_VOLUME* volume = dir == 0 ? 0 : dir->p_sdd->dir_entry.p_vol; + pf_s32 error = PFVOL_CheckForWrite(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else if ((dir->p_sdd->stat & 1) == 0 || (dir->p_sdd->stat & 2) == 0) { + error = 10; + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + dir->end_position = position; + } + return error; +} + +void PFDIR_rmdir(PF_STR* path) { + PF_VOLUME* volume = PFPATH_GetVolumeFromPath(path); + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_s32 error = PFVOL_CheckForWrite(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + volume_dirs->cache_signature = 0; + error = PFDIR_p_rmdir(volume, (PFDIR_STR*)path); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushFATCache(volume); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } + } + volume_dirs->cache_signature = 0; +} + +void PFDIR_mkdir(PF_STR* path) { + PF_VOLUME* volume = PFPATH_GetVolumeFromPath(path); + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_s32 error = PFVOL_CheckForWrite(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + volume_dirs->cache_signature = 0; + error = PFDIR_p_mkdir(volume, path, 0, 0); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushFATCache(volume); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushDataCacheSpecific(volume, 0); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } + } + } + volume_dirs->cache_signature = 0; +} + +void PFDIR_createdir(PF_STR* path, pf_u32 option, PF_DTA* data) { + PF_VOLUME* volume = PFPATH_GetVolumeFromPath(path); + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_s32 error = PFVOL_CheckForWrite(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + volume_dirs->cache_signature = 0; + error = PFDIR_p_mkdir(volume, path, option, data); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushFATCache(volume); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushDataCacheSpecific(volume, 0); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } + } + } + volume_dirs->cache_signature = 0; +} + +pf_s32 PFDIR_chdir(PF_STR* path) { + PF_VOLUME* volume = PFPATH_GetVolumeFromPath(path); + pf_s32 error = PFVOL_CheckForRead(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return error; + } + error = PFDIR_p_chdir(volume, (PFDIR_STR*)path); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return error; + } + PFVOL_SetCurrentVolume(volume); + return 0; +} + +pf_s32 PFDIR_fchdir(PFDIR_DIR* dir) { + PF_VOLUME* volume = dir == 0 ? 0 : dir->p_sdd->dir_entry.p_vol; + pf_s32 error = PFVOL_CheckForRead(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return error; + } + if ((dir->p_sdd->stat & 1) == 0 || (dir->p_sdd->stat & 2) == 0) { + error = 10; + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return error; + } + error = PFVOL_SetCurrentDir(volume, &dir->p_sdd->dir_entry); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return error; + } + PFVOL_SetCurrentVolume(volume); + return 0; +} + +void PFDIR_chmod(PF_STR* path, pf_u8 attributes) { + PF_VOLUME* volume = PFPATH_GetVolumeFromPath(path); + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_s32 error = PFVOL_CheckForWrite(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + volume_dirs->cache_signature = 0; + error = PFDIR_p_chmod(volume, (PFDIR_STR*)path, attributes); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushFATCache(volume); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushDataCacheSpecific(volume, 0); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } + } + } + volume_dirs->cache_signature = 0; +} + +void PFDIR_chdmod(PF_STR* path, pf_u8 attributes) { + PF_VOLUME* volume = PFPATH_GetVolumeFromPath(path); + PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + pf_s32 error = PFVOL_CheckForWrite(volume); + + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + return; + } + volume_dirs->cache_signature = 0; + error = PFDIR_p_chmod(volume, (PFDIR_STR*)path, attributes | 0x10); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushFATCache(volume); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else { + error = PFCACHE_FlushDataCacheSpecific(volume, 0); + if (error != 0) { + pf_vol_set.last_error = error; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } + } + } + volume_dirs->cache_signature = 0; +} + +pf_s32 PFDIR_p_fsnext(PF_DTA* data) { + PFDIR_FFD ffd; + PFDIR_FAT_HINT hint; + PF_DIR_ENT entry; + PFDIR_STR pattern; + pf_u32 logical_position = 0; + pf_u32 entry_position = 0; + pf_u32 code_mode; + pf_u32 index; + pf_s32 error; + + if ((data->status & 1) == 1) { + code_mode = 1; + error = PFSTR_InitStr(&pattern, data->reg_exp, code_mode); + } else { + code_mode = 2; + error = PFSTR_InitStr(&pattern, (const pf_s8*)((PF_DTAW*)data)->reg_expW, code_mode); + } + if (error != 0) { + return error; + } + PFSTR_SetLocalStr(&pattern, 0); + if (entry_position < 0xF423F) { + if (data->parent_pos > 0xF423E) { + return 10; + } + ffd.start_cluster = data->parent_start_cluster; + PFFAT_InitFFD(&ffd, &hint, data->p_vol, &ffd.start_cluster); + error = PFENT_findEntryPos(&ffd, &entry, data->parent_pos, &pattern, data->attr, 0, + &logical_position, &entry_position); + if (error != 0) { + return error; + } + data->parent_pos = entry_position + 1; + if (entry_position == 0xF423F) { + return 3; + } + } + pf_strcpy(data->FileName, entry.short_name); + if ((data->status & 2) == 2) { + PFPATH_transformInUnicode(((PF_DTAW*)data)->FileNameW, data->FileName); + } + if (entry.long_name[0] == 0) { + data->LongName[0] = 0; + if ((data->status & 2) == 2) { + ((PF_DTAW*)data)->LongNameW[0] = 0; + } + } else { + if ((VFipf_vol_set.setting & 2) == 2) { + VFipf_vol_set.setting &= 0xFFFFFFFC; + VFipf_vol_set.setting |= 1; + PFPATH_transformFromUnicodeToNormal(data->LongName, entry.long_name); + VFipf_vol_set.setting &= 0xFFFFFFFC; + VFipf_vol_set.setting |= 2; + } else { + PFPATH_transformFromUnicodeToNormal(data->LongName, entry.long_name); + } + if ((data->status & 2) == 2) { + pf_w_strcpy(((PF_DTAW*)data)->LongNameW, entry.long_name); + } + } + if (((PFDIR_VOLUME_DIRS*)data->p_vol)->num_opened_files != 0) { + PFDIR_SFD* sfd = ((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds; + for (index = 0; index < 5; index++) { + if ((sfd->stat & 1) != 0 && (sfd->stat & 2) != 0 && + sfd->dir_entry.p_vol == entry.p_vol && + sfd->dir_entry.entry_sector == entry.entry_sector && + sfd->dir_entry.entry_offset == entry.entry_offset) { + data->FileSize = sfd->dir_entry.file_size; + data->Time = sfd->dir_entry.modify_time; + data->Date = sfd->dir_entry.modify_date; + data->Attribute = sfd->dir_entry.attr; + data->num_entry_LFNs = sfd->dir_entry.num_entry_LFNs; + data->ordinal = sfd->dir_entry.ordinal; + data->check_sum = sfd->dir_entry.check_sum; + break; + } + sfd++; + } + } + if (((PFDIR_VOLUME_DIRS*)data->p_vol)->num_opened_files == 0 || index == 5) { + data->FileSize = entry.file_size; + data->Time = entry.modify_time; + data->Date = entry.modify_date; + data->Attribute = entry.attr; + data->num_entry_LFNs = entry.num_entry_LFNs; + data->ordinal = entry.ordinal; + data->check_sum = entry.check_sum; + } + return 0; +} + +pf_s32 PFDIR_p_fsfirst(PF_VOLUME* volume, PF_STR* path, pf_u8 attributes, PF_DTA* data) { + PFDIR_STR directory; + PFDIR_STR pattern; + PF_DIR_ENT entry; + PF_ENT_ITER iter; + pf_s32 error; + + error = PFPATH_SplitPathPattern(path, &directory, &pattern); + if (error != 0) { + return error; + } + error = PFENT_ITER_GetEntryOfPattern(&iter, &entry, volume, &directory); + if (error != 0) { + return error; + } + if ((entry.attr & 0x10) == 0) { + return 0x14; + } + data->parent_start_cluster = entry.start_cluster; + data->parent_pos = 0; + data->p_vol = entry.p_vol; + data->attr = attributes; + data->status = 0; + if (PFSTR_GetCodeMode(&pattern) == 1) { + PFPATH_SetSearchPattern(data->reg_exp, 0, &pattern); + data->status |= 1; + } else { + PFPATH_SetSearchPattern(data->reg_exp, ((PF_DTAW*)data)->reg_expW, &pattern); + data->status |= 2; + } + return PFDIR_p_fsnext(data); +} -- 2.49.1 From 341ce036f5320b8699ce75513a1a01c563fe8dee Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Mon, 28 Sep 2026 22:53:07 -0500 Subject: [PATCH 26/61] Decompile iplSDChannelSelect to 42/129 functions (#248) * start sd channel select decompilation * add sd channel layouts and drawing * match sd worker state helpers * match nand title count handling * name sd channel scene helpers * match sd worker completion handlers * match channel visibility lookup * match channel queue helpers * fix sd command notice payloads * align sd worker state dispatch * match sd channel object destruction * match visible channel drawing passes * match sd channel layout updates * match sd channel pane helpers * match page animation calculation --- config/43U/symbols.txt | 104 +- include/math/iplMathTypes.h | 2 +- .../sdChannelSelect/iplSDChannelSelect.h | 255 ++- include/system/iplSaveDataManager.h | 6 + .../sdChannelSelect/iplSDChannelSelect.cpp | 1409 +++++++++++++++++ 5 files changed, 1716 insertions(+), 60 deletions(-) create mode 100644 src/scene/sdChannelSelect/iplSDChannelSelect.cpp diff --git a/config/43U/symbols.txt b/config/43U/symbols.txt index 2ab7fbb1..625ff77d 100644 --- a/config/43U/symbols.txt +++ b/config/43U/symbols.txt @@ -4558,44 +4558,44 @@ __ct__Q33ipl5scene15SDChannelSelectFPQ23EGG4Heap = .text:0x813DAB08; // type:fun __dt__Q33ipl5scene15SDChannelSelectFv = .text:0x813DAE7C; // type:function size:0x5C prepare__Q33ipl5scene15SDChannelSelectFv = .text:0x813DAED8; // type:function size:0xA8 create__Q33ipl5scene15SDChannelSelectFv = .text:0x813DAF80; // type:function size:0x248 -iplSDChannelSelect_813DB1C8 = .text:0x813DB1C8; // type:function size:0x44 -iplSDChannelSelect_813DB20C = .text:0x813DB20C; // type:function size:0x48 -iplSDChannelSelect_813DB254 = .text:0x813DB254; // type:function size:0xB4 -iplSDChannelSelect_813DB308 = .text:0x813DB308; // type:function size:0x5C -iplSDChannelSelect_813DB364 = .text:0x813DB364; // type:function size:0x5C -iplSDChannelSelect_813DB3C0 = .text:0x813DB3C0; // type:function size:0x5C -iplSDChannelSelect_813DB41C = .text:0x813DB41C; // type:function size:0x5C -iplSDChannelSelect_813DB478 = .text:0x813DB478; // type:function size:0x5C -iplSDChannelSelect_813DB4D4 = .text:0x813DB4D4; // type:function size:0x5C -iplSDChannelSelect_813DB530 = .text:0x813DB530; // type:function size:0x5C -iplSDChannelSelect_813DB58C = .text:0x813DB58C; // type:function size:0x60 -iplSDChannelSelect_813DB5EC = .text:0x813DB5EC; // type:function size:0x60 -iplSDChannelSelect_813DB64C = .text:0x813DB64C; // type:function size:0x40 -iplSDChannelSelect_813DB68C = .text:0x813DB68C; // type:function size:0x40 -iplSDChannelSelect_813DB6CC = .text:0x813DB6CC; // type:function size:0x518 -iplSDChannelSelect_813DBBE4 = .text:0x813DBBE4; // type:function size:0xB0 -iplSDChannelSelect_813DBC94 = .text:0x813DBC94; // type:function size:0xB8 -iplSDChannelSelect_813DBD4C = .text:0x813DBD4C; // type:function size:0x48 -iplSDChannelSelect_813DBD94 = .text:0x813DBD94; // type:function size:0xD8 -iplSDChannelSelect_813DBE6C = .text:0x813DBE6C; // type:function size:0x28 -iplSDChannelSelect_813DBE94 = .text:0x813DBE94; // type:function size:0x124 -iplSDChannelSelect_813DBFB8 = .text:0x813DBFB8; // type:function size:0x28 +enqueueStartNotice__Q33ipl5scene15SDChannelSelectFv = .text:0x813DB1C8; // type:function size:0x44 +enqueueFinishNotice__Q33ipl5scene15SDChannelSelectFv = .text:0x813DB20C; // type:function size:0x48 +enqueueNotice__Q33ipl5scene15SDChannelSelectFUlUlUl = .text:0x813DB254; // type:function size:0xB4 +enqueueLoadNotice__Q33ipl5scene15SDChannelSelectFv = .text:0x813DB308; // type:function size:0x5C +enqueuePageNotice__Q33ipl5scene15SDChannelSelectFv = .text:0x813DB364; // type:function size:0x5C +enqueueResultNotice__Q33ipl5scene15SDChannelSelectFUl = .text:0x813DB3C0; // type:function size:0x5C +enqueueChannelNotice__Q33ipl5scene15SDChannelSelectFUlUlUlUl = .text:0x813DB41C; // type:function size:0x5C +enqueueMoveNotice__Q33ipl5scene15SDChannelSelectFUlUlUl = .text:0x813DB478; // type:function size:0x5C +enqueueStateNotice__Q33ipl5scene15SDChannelSelectFUlUlUlUl = .text:0x813DB4D4; // type:function size:0x5C +enqueueErrorNotice__Q33ipl5scene15SDChannelSelectFUlUl = .text:0x813DB530; // type:function size:0x5C +enqueueCommandNotice__Q33ipl5scene15SDChannelSelectFUlUlUl = .text:0x813DB58C; // type:function size:0x60 +enqueueDeleteNotice__Q33ipl5scene15SDChannelSelectFUlUlUl = .text:0x813DB5EC; // type:function size:0x60 +clearCommandQueue__Q33ipl5scene15SDChannelSelectFv = .text:0x813DB64C; // type:function size:0x40 +clearNoticeQueue__Q33ipl5scene15SDChannelSelectFv = .text:0x813DB68C; // type:function size:0x40 +processWorkerCommands__Q33ipl5scene15SDChannelSelectFv = .text:0x813DB6CC; // type:function size:0x518 +handleWorkerStartup__Q33ipl5scene15SDChannelSelectFv = .text:0x813DBBE4; // type:function size:0xB0 +handleNandTitleCount__Q33ipl5scene15SDChannelSelectFv = .text:0x813DBC94; // type:function size:0xB8 +handleNandTitleUsageComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DBD4C; // type:function size:0x48 +handleNandTitleUsage__Q33ipl5scene15SDChannelSelectFv = .text:0x813DBD94; // type:function size:0xD8 +compareTitleUsage__Q33ipl5scene15SDChannelSelectFPCvPCv = .text:0x813DBE6C; // type:function size:0x28 +handleSDTitleList__Q33ipl5scene15SDChannelSelectFv = .text:0x813DBE94; // type:function size:0x124 +compareTitleInfo__Q33ipl5scene15SDChannelSelectFPCvPCv = .text:0x813DBFB8; // type:function size:0x28 iplSDChannelSelect_813DBFE0 = .text:0x813DBFE0; // type:function size:0x2AC -iplSDChannelSelect_813DC28C = .text:0x813DC28C; // type:function size:0x64 +handleSDMountComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC28C; // type:function size:0x64 iplSDChannelSelect_813DC2F0 = .text:0x813DC2F0; // type:function size:0x1B0 -iplSDChannelSelect_813DC4A0 = .text:0x813DC4A0; // type:function size:0x5C -iplSDChannelSelect_813DC4FC = .text:0x813DC4FC; // type:function size:0x78 -iplSDChannelSelect_813DC574 = .text:0x813DC574; // type:function size:0x80 -iplSDChannelSelect_813DC5F4 = .text:0x813DC5F4; // type:function size:0x48 -iplSDChannelSelect_813DC63C = .text:0x813DC63C; // type:function size:0x48 -iplSDChannelSelect_813DC684 = .text:0x813DC684; // type:function size:0x90 -iplSDChannelSelect_813DC714 = .text:0x813DC714; // type:function size:0x48 -iplSDChannelSelect_813DC75C = .text:0x813DC75C; // type:function size:0x48 -iplSDChannelSelect_813DC7A4 = .text:0x813DC7A4; // type:function size:0x48 +handleSDCardReady__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC4A0; // type:function size:0x5C +handleCardCommand__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC4FC; // type:function size:0x78 +handleCopyComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC574; // type:function size:0x80 +handleSDLocationUpdateComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC5F4; // type:function size:0x48 +handleSDLocationReadComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC63C; // type:function size:0x48 +handleMoveComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC684; // type:function size:0x90 +handleBackupFitComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC714; // type:function size:0x48 +handleNandSDCleanupComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC75C; // type:function size:0x48 +handleSDDeleteComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC7A4; // type:function size:0x48 iplSDChannelSelect_813DC7EC = .text:0x813DC7EC; // type:function size:0x14C -iplSDChannelSelect_813DC938 = .text:0x813DC938; // type:function size:0x18C -iplSDChannelSelect_813DCAC4 = .text:0x813DCAC4; // type:function size:0x42C -iplSDChannelSelect_813DCEF0 = .text:0x813DCEF0; // type:function size:0x24 +processWorkerState__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC938; // type:function size:0x18C +updateDialogAnimation__Q33ipl5scene15SDChannelSelectFv = .text:0x813DCAC4; // type:function size:0x42C +setDialogMessage__Q33ipl5scene15SDChannelSelectFUlUl = .text:0x813DCEF0; // type:function size:0x24 iplSDChannelSelect_813DCF14 = .text:0x813DCF14; // type:function size:0xCC iplSDChannelSelect_813DCFE0 = .text:0x813DCFE0; // type:function size:0xCC iplSDChannelSelect_813DD0AC = .text:0x813DD0AC; // type:function size:0x194 @@ -4619,13 +4619,13 @@ initCalcFadeout__Q33ipl5scene15SDChannelSelectFv = .text:0x813DE24C; // type:fun calcFadeout__Q33ipl5scene15SDChannelSelectFv = .text:0x813DE2EC; // type:function size:0x50 draw__Q33ipl5scene15SDChannelSelectFv = .text:0x813DE33C; // type:function size:0x38C destroy__Q33ipl5scene15SDChannelSelectFv = .text:0x813DE6C8; // type:function size:0x334 -iplSDChannelSelect_813DE9FC = .text:0x813DE9FC; // type:function size:0x440 -iplSDChannelSelect_813DEE3C = .text:0x813DEE3C; // type:function size:0x5C -iplSDChannelSelect_813DEE98 = .text:0x813DEE98; // type:function size:0x78 -iplSDChannelSelect_813DEF10 = .text:0x813DEF10; // type:function size:0x58 +createBaseLayout__Q33ipl5scene15SDChannelSelectFv = .text:0x813DE9FC; // type:function size:0x440 +updateChannelObjects__Q33ipl5scene15SDChannelSelectFv = .text:0x813DEE3C; // type:function size:0x5C +updateChannelObject__Q33ipl5scene15SDChannelSelectFPQ33ipl5scene12SDChannelObj = .text:0x813DEE98; // type:function size:0x78 +calcChannelObjects__Q33ipl5scene15SDChannelSelectFv = .text:0x813DEF10; // type:function size:0x58 iplSDChannelSelect_813DEF68 = .text:0x813DEF68; // type:function size:0x27C iplSDChannelSelect_813DF1E4 = .text:0x813DF1E4; // type:function size:0x14 -iplSDChannelSelect_813DF1F8 = .text:0x813DF1F8; // type:function size:0xB0 +drawChannelObjects__Q33ipl5scene15SDChannelSelectFv = .text:0x813DF1F8; // type:function size:0xB0 iplSDChannelSelect_813DF2A8 = .text:0x813DF2A8; // type:function size:0x138 iplSDChannelSelect_813DF3E0 = .text:0x813DF3E0; // type:function size:0x1C iplSDChannelSelect_813DF3FC = .text:0x813DF3FC; // type:function size:0x110 @@ -4637,13 +4637,13 @@ iplSDChannelSelect_813DF944 = .text:0x813DF944; // type:function size:0x84 iplSDChannelSelect_813DF9C8 = .text:0x813DF9C8; // type:function size:0xF8 iplSDChannelSelect_813DFAC0 = .text:0x813DFAC0; // type:function size:0xFC iplSDChannelSelect_813DFBBC = .text:0x813DFBBC; // type:function size:0xE4 -iplSDChannelSelect_813DFCA0 = .text:0x813DFCA0; // type:function size:0x50 +destroyChannelObject__Q33ipl5scene15SDChannelSelectFPQ33ipl5scene12SDChannelObj = .text:0x813DFCA0; // type:function size:0x50 iplSDChannelSelect_813DFCF0 = .text:0x813DFCF0; // type:function size:0x74 iplSDChannelSelect_813DFD64 = .text:0x813DFD64; // type:function size:0x154 iplSDChannelSelect_813DFEB8 = .text:0x813DFEB8; // type:function size:0x74 iplSDChannelSelect_813DFF2C = .text:0x813DFF2C; // type:function size:0x1C0 -iplSDChannelSelect_813E00EC = .text:0x813E00EC; // type:function size:0x140 -iplSDChannelSelect_813E022C = .text:0x813E022C; // type:function size:0x68 +hasChannelObject__Q33ipl5scene15SDChannelSelectCFii = .text:0x813E00EC; // type:function size:0x140 +isChannelInCalc__Q33ipl5scene15SDChannelSelectCFiii = .text:0x813E022C; // type:function size:0x68 iplSDChannelSelect_813E0294 = .text:0x813E0294; // type:function size:0x104 iplSDChannelSelect_813E0398 = .text:0x813E0398; // type:function size:0x18 iplSDChannelSelect_813E03B0 = .text:0x813E03B0; // type:function size:0xA0 @@ -4651,13 +4651,13 @@ iplSDChannelSelect_813E0450 = .text:0x813E0450; // type:function size:0xEC iplSDChannelSelect_813E053C = .text:0x813E053C; // type:function size:0x84 iplSDChannelSelect_813E05C0 = .text:0x813E05C0; // type:function size:0x64 iplSDChannelSelect_813E0624 = .text:0x813E0624; // type:function size:0xB4 -iplSDChannelSelect_813E06D8 = .text:0x813E06D8; // type:function size:0xAC -iplSDChannelSelect_813E0784 = .text:0x813E0784; // type:function size:0x30 -iplSDChannelSelect_813E07B4 = .text:0x813E07B4; // type:function size:0x30 -iplSDChannelSelect_813E07E4 = .text:0x813E07E4; // type:function size:0x64 +getChannelBasePane__Q33ipl5scene15SDChannelSelectCFiii = .text:0x813E06D8; // type:function size:0xAC +getCenterChannelPane__Q33ipl5scene15SDChannelSelectCFi = .text:0x813E0784; // type:function size:0x30 +getChannelPane__Q33ipl5scene15SDChannelSelectCFi = .text:0x813E07B4; // type:function size:0x30 +getChannelPanePosition__Q33ipl5scene15SDChannelSelectFPQ33ipl5scene15SDChannelSelecti = .text:0x813E07E4; // type:function size:0x64 iplSDChannelSelect_813E0848 = .text:0x813E0848; // type:function size:0x3A4 iplSDChannelSelect_813E0BEC = .text:0x813E0BEC; // type:function size:0x294 -iplSDChannelSelect_813E0E80 = .text:0x813E0E80; // type:function size:0x60 +calcPageAnimations__Q33ipl5scene15SDChannelSelectFv = .text:0x813E0E80; // type:function size:0x60 iplSDChannelSelect_813E0EE0 = .text:0x813E0EE0; // type:function size:0x26C iplSDChannelSelect_813E114C = .text:0x813E114C; // type:function size:0x78 iplSDChannelSelect_813E11C4 = .text:0x813E11C4; // type:function size:0x3A4 @@ -4678,10 +4678,10 @@ iplSDChannelSelect_813E2750 = .text:0x813E2750; // type:function size:0x164 iplSDChannelSelect_813E28B4 = .text:0x813E28B4; // type:function size:0x2A0 iplSDChannelSelect_813E2B54 = .text:0x813E2B54; // type:function size:0x240 startResetting__Q33ipl5scene15SDChannelSelectFv = .text:0x813E2D94; // type:function size:0x44 -iplSDChannelSelect_813E2DD8 = .text:0x813E2DD8; // type:function size:0x4C -iplSDChannelSelect_813E2E24 = .text:0x813E2E24; // type:function size:0x80 -iplSDChannelSelect_813E2EA4 = .text:0x813E2EA4; // type:function size:0x4C -iplSDChannelSelect_813E2EF0 = .text:0x813E2EF0; // type:function size:0x34 +pop__Q33ipl5scene26SDChannelSelectNoticeQueueFv = .text:0x813E2DD8; // type:function size:0x4C +push__Q33ipl5scene27SDChannelSelectCommandQueueFRCQ33ipl5scene22SDChannelSelectCommand = .text:0x813E2E24; // type:function size:0x80 +pop__Q33ipl5scene27SDChannelSelectCommandQueueFv = .text:0x813E2EA4; // type:function size:0x4C +copyFrom__Q33ipl5scene22SDChannelSelectCommandFRCQ33ipl5scene22SDChannelSelectCommand = .text:0x813E2EF0; // type:function size:0x34 @20@__dt__Q33ipl5scene15SDChannelSelectFv = .text:0x813E2F24; // type:function size:0x8 __ct__Q33ipl5scene12SDChannelObjFPQ23EGG4Heapii = .text:0x813E2F2C; // type:function size:0x130 __dt__Q33ipl5scene12SDChannelObjFv = .text:0x813E305C; // type:function size:0xA8 diff --git a/include/math/iplMathTypes.h b/include/math/iplMathTypes.h index 45a21ff4..8e7b0ef8 100644 --- a/include/math/iplMathTypes.h +++ b/include/math/iplMathTypes.h @@ -103,7 +103,7 @@ namespace ipl { y = r.y; z = 0.0f; } -#ifdef IPL_ADDRESS_EDIT_CPP +#if defined(IPL_ADDRESS_EDIT_CPP) || defined(IPL_SD_CHANNEL_SELECT_CPP) VEC3(f32 fx, f32 fy, f32 fz); #else VEC3(f32 fx, f32 fy, f32 fz) { diff --git a/include/scene/sdChannelSelect/iplSDChannelSelect.h b/include/scene/sdChannelSelect/iplSDChannelSelect.h index a98697da..d650b64d 100644 --- a/include/scene/sdChannelSelect/iplSDChannelSelect.h +++ b/include/scene/sdChannelSelect/iplSDChannelSelect.h @@ -1,18 +1,259 @@ #ifndef IPL_SCENE_SD_CHANNEL_SELECT_H #define IPL_SCENE_SD_CHANNEL_SELECT_H -#include "iplSceneHeader.h" +#include "iplSceneUIHeader.h" + +#include "math/iplInterporation.h" +#include "scene/sdButton/iplSDButton.h" +#include "system/iplChannelRsoThread.h" +#include "system/iplNandSDWorker.h" namespace ipl { namespace scene { - FADER_SCENE_CLASS(SDChannelSelect) { + class SDChannelObj { public: - SDChannelSelect(EGG::Heap * heap); + ~SDChannelObj(); + + EGG::Heap* getHeap() const { return mpHeap; } + int getPage() const { return mPage; } + int getIndex() const { return mIndex; } private: - u8 unk_0x58[0x728]; + nw4r::ut::Link mListLink; + f32 mOffsetX; + f32 mOffsetY; + EGG::Heap* mpHeap; + u32 mState; + int mPage; + int mIndex; }; - } // namespace scene -} // namespace ipl + extern "C" void iplSDChannelObj_813E3104(SDChannelObj* channel); + extern "C" void iplSDChannelObj_813E311C(SDChannelObj* channel, EGG::ExpHeap* firstHeap, + EGG::ExpHeap* secondHeap); + extern "C" void iplSDChannelObj_813E322C(SDChannelObj* channel); + extern "C" void iplSDChannelObj_813E3178(SDChannelObj* channel, nw4r::lyt::Pane* pane); + extern "C" void iplSDChannelObj_813E3180(SDChannelObj* channel, nand::LayoutFile* layoutFile); + extern "C" void iplSDChannelObj_813E3304(SDChannelObj* channel); + extern "C" void iplSDChannelObj_813E330C(SDChannelObj* channel); -#endif // IPL_SCENE_SD_CHANNEL_SELECT_H + union SDChannelSelectCommandArguments { + u32 values[3]; + NandSDWorker::AppBlocksInfo* appBlocks[3]; + NandSDWorker::TitleIdList* titleLists[3]; + void* pointers[3]; + }; + + struct SDChannelSelectCommand { + u32 type; + u64 titleId; + SDChannelSelectCommandArguments arguments; + + void copyFrom(const SDChannelSelectCommand& other); + }; + + struct SDChannelSelectCommandQueue { + SDChannelSelectCommand commands[4]; + int capacity; + int count; + int readIndex; + int writeIndex; + + SDChannelSelectCommandQueue(u32 capacity, u32 count, u32 readIndex, u32 writeIndex) + : capacity(capacity), count(count), readIndex(readIndex), writeIndex(writeIndex) { + } + + bool push(const SDChannelSelectCommand& command); + bool pop(); + }; + + struct SDChannelSelectTitleInfo { + ESTitleId32 titleId; + u32 state; + }; + + struct SDChannelSelectNoticeQueue { + SDChannelSelectCommand notices[42]; + int capacity; + int count; + int readIndex; + int writeIndex; + + SDChannelSelectNoticeQueue(u32 capacity, u32 count, u32 readIndex, u32 writeIndex) + : capacity(capacity), count(count), readIndex(readIndex), writeIndex(writeIndex) { + } + + bool pop(); + }; + + FADER_SCENE_CLASS(SDChannelSelect) { + public: + enum { + PAGE_COUNT = 5, + }; + + SDChannelSelect(EGG::Heap* heap); + virtual ~SDChannelSelect(); + + virtual BOOL isResetProcessDone(); + virtual void startResetting(); + virtual void prepare(); + virtual void create(); + virtual void draw(); + virtual void destroy(); + virtual void initCalcFadeout(); + virtual void calcCommon(); + virtual FaderSceneCommand calcFadein(); + virtual FaderSceneCommand calcNormal(); + virtual FaderSceneCommand calcFadeout(); + + static const char* mscChannelPaneNames[PAGE_COUNT][MAX_CHANNEL_INDEX]; + static const char* mscBasePaneNames[PAGE_COUNT]; + static const char* mscPicturePaneNames[PAGE_COUNT]; + static const char* mscEdgePaneNames[PAGE_COUNT]; + static const char* mscClockPaneNames[3]; + static const char* mscMaskPaneName; + + private: + void enqueueStartNotice(); + bool enqueueFinishNotice(); + bool enqueueNotice(u32 highTitleId, u32 lowTitleId, u32 result); + bool enqueueLoadNotice(); + bool enqueuePageNotice(); + bool enqueueResultNotice(u32 result); + bool enqueueChannelNotice(u32 controller, u32 page, u32 index, u32 value); + bool enqueueMoveNotice(u32 controller, u32 page, u32 index); + bool enqueueStateNotice(u32 controller, u32 page, u32 index, u32 state); + bool enqueueErrorNotice(u32 page, u32 index); + bool enqueueCommandNotice(u32 page, u32 index, u32 command); + bool enqueueDeleteNotice(u32 controller, u32 page, u32 index); + void clearCommandQueue(); + void clearNoticeQueue(); + void calcChannelObjects(); + void updateChannelObjects(); + void updateChannelObject(SDChannelObj* channel); + void drawChannelObjects(); + bool isChannelInCalc(int page, int index, int currentPage) const; + nw4r::lyt::Pane* getChannelBasePane(int page, int index, int currentPage) const; + nw4r::lyt::Pane* getCenterChannelPane(int index) const; + nw4r::lyt::Pane* getChannelPane(int index) const; + static math::VEC3 getChannelPanePosition(SDChannelSelect* scene, int index); + void calcPageAnimations(); + void updateArrowVisibility(); + void processWorkerState(); + void updateDialogAnimation(); + void processWorkerCommands(); + void handleWorkerStartup(); + void handleNandTitleCount(); + void handleNandTitleUsage(); + void handleNandTitleUsageComplete(); + void handleSDTitleList(); + void handleSDMountComplete(); + void handleCopyComplete(); + void handleDeleteComplete(); + void handleMoveComplete(); + void handleStorageCheckComplete(); + void handleCardCommand(); + void handleSDCardReady(); + void handleSDLocationUpdateComplete(); + void handleSDLocationReadComplete(); + void handleBackupFitComplete(); + void handleNandSDCleanupComplete(); + void handleSDDeleteComplete(); + bool setDialogMessage(u32 state, u32 message); + static int compareTitleUsage(const void* lhs, const void* rhs); + static int compareTitleInfo(const void* lhs, const void* rhs); + void createChannelList(int page, bool force); + void destroyChannelObject(SDChannelObj* channel); + bool hasChannelObject(int page, int index) const; + void createChannelObject(int page, int index); + void createBaseLayout(); + void updateNoCardLayouts(); + void createChannelThumbnails(); + + nw4r::ut::List mChannelObjects; + nand::LayoutFile* mpLayoutFile; + layout::Object* mpLayout; + math::HermiteIntp* mpPageAnimations[4]; + gui::PaneManager* mpPaneManager; + layout::Object* mpNoCardLayout; + layout::Object* mpPageLayouts[3]; + layout::Object* mpDialogLayout; + SDButtonEventHandlerBase* mpButtonEventHandler; + int mState; + int mCurrentPage; + int mPageCount; + int mCurrentChannelIndex; + f32 mThumbOffsetX; + f32 mThumbOffsetY; + nw4r::math::VEC3 mPosition; + math::VEC2 mScale; + f32 mAspectRatioScale; + bool mbLeftArrowVisible; + bool mbRightArrowVisible; + u8 mArrowState; + u8 mNoCardState; + EGG::UnitHeap* mpLayoutHeap; + EGG::ExpHeap* mpDialogHeap; + EGG::ExpHeap* mpChannelHeap; + EGG::ExpHeap* mpThumbnailHeap; + nw4r::math::VEC2 mPointerPosition; + int mControllerChannel; + int mSourcePage; + int mSourceIndex; + int mDestinationPage; + int mDestinationIndex; + int mPendingPage; + int mPendingIndex; + int mMoveState; + bool mbButtonEnabled; + bool mbDialogActive; + u16 mInputFlags; + SDChannelObj* mpCurrentChannel; + layout::Object* mpStateLayout; + layout::Object* mpHelpLayout; + EGG::ExpHeap* mpRsoHeap; + channel::RsoThread* mpRsoThread; + u32 mCommandQueueState; + SDChannelSelectCommandQueue mCommandQueue; + SDChannelSelectNoticeQueue mNoticeQueue; + int mCurrentSDState; + int mPreviousSDState; + int mWorkerState; + int mWorkerCommand; + EGG::Heap* mpWorkerHeap; + EGG::Heap* mpThumbnailWorkHeap; + NandSDWorker* mpSDWorker; + ESTitleId32* mpSDTitleIds; + SDChannelSelectTitleInfo* mpSDTitleInfo; + NandSDWorker::TitleUsage* mpNandTitleInfo; + u32 mFirstTitleCount; + u32 mSecondTitleCount; + SDChannelObj* mpCurrentLoadedChannel; + u32 mSDTitleCount; + u32 mNandTitleCount; + u32* mpChannelTitleIds; + u32 mPendingOperation; + int mLastOperation; + layout::Object* mpErrorLayout; + layout::Object* mpPointerLayout; + layout::Object* mpHelpButtonLayout; + int mOperationResult; + u8 mbShowNoCardMessage; + u8 mbOperationActive; + u8 mbSDCardBroken; + u32 mOperationState; + u32 mDialogState; + nand::File* mpSaveDataFile; + u32 mAnimationState; + u32 mAnimationTarget; + OSTime mOperationStartTime; + nand::File* mpCorruptIconFile; + u8 mbHazardTitleFound; + u8 mbChannelLimitReached; + u8 mbInitialLoadComplete; + u8 mbNeedsRefresh; + }; + } +} + +#endif diff --git a/include/system/iplSaveDataManager.h b/include/system/iplSaveDataManager.h index 0af3e212..4ede525a 100644 --- a/include/system/iplSaveDataManager.h +++ b/include/system/iplSaveDataManager.h @@ -50,6 +50,12 @@ namespace ipl { int getPrevPage() { return mLastPrevPage; } +#ifdef IPL_SD_CHANNEL_SELECT_ACCESS + int getLastSDPrevPage() { return mLastSDPrevPage; } + void setLastSDPrevPage(int page) { mLastSDPrevPage = page; } + BOOL didntGotoSDMenu() const { return mData.didntGotoSDMenu; } +#endif + bool hasPhotoMP3Dummy() { return mbPhotoMP3; } bool hasPhoto2Title() { return mbPhoto2; } bool hasPhoto2DummyCheck() { return mbPhoto2Check; } diff --git a/src/scene/sdChannelSelect/iplSDChannelSelect.cpp b/src/scene/sdChannelSelect/iplSDChannelSelect.cpp new file mode 100644 index 00000000..793ccfb9 --- /dev/null +++ b/src/scene/sdChannelSelect/iplSDChannelSelect.cpp @@ -0,0 +1,1409 @@ +#define IPL_SD_CHANNEL_SELECT_ACCESS +#define IPL_SD_CHANNEL_SELECT_CPP + +#include + +#include "iplSceneUI.h" +#include "system/iplSystem.h" +#include "system/iplSaveDataManager.h" +#include "utility/iplCSFlags.h" +#include "sound/iplSound.h" + +#include "scene/sdChannelSelect/iplSDChannelSelect.h" + +#include +#include + +namespace ipl { + namespace scene { + namespace { + class SDChannelSelectButtonEventHandler : public SDButtonEventHandlerBase { + public: + explicit SDChannelSelectButtonEventHandler(SDChannelSelect* scene) + : mpScene(scene) { + } + + void onEventDerived(u32 compId, u32 event, const controller::Interface* con) override { + } + + private: + SDChannelSelect* mpScene; + }; + + } + + const char* SDChannelSelect::mscChannelPaneNames[PAGE_COUNT][MAX_CHANNEL_INDEX] = { + { + "", "", "", "N_Ch_a04", "", "", "", "N_Ch_a08", "", "", "", "N_Ch_a12", + }, + { + "N_Ch_b01", "N_Ch_b02", "N_Ch_b03", "N_Ch_b04", "N_Ch_b05", "N_Ch_b06", + "N_Ch_b07", "N_Ch_b08", "N_Ch_b09", "N_Ch_b10", "N_Ch_b11", "N_Ch_b12", + }, + { + "N_Ch_c01", "N_Ch_c02", "N_Ch_c03", "N_Ch_c04", "N_Ch_c05", "N_Ch_c06", + "N_Ch_c07", "N_Ch_c08", "N_Ch_c09", "N_Ch_c10", "N_Ch_c11", "N_Ch_c12", + }, + { + "N_Ch_d01", "N_Ch_d02", "N_Ch_d03", "N_Ch_d04", "N_Ch_d05", "N_Ch_d06", + "N_Ch_d07", "N_Ch_d08", "N_Ch_d09", "N_Ch_d10", "N_Ch_d11", "N_Ch_d12", + }, + { + "N_Ch_e01", "", "", "", "N_Ch_e05", "", "", "", "N_Ch_e09", "", "", "", + }, + }; + + const char* SDChannelSelect::mscBasePaneNames[PAGE_COUNT] = { + "BaseMask0", "BaseMask1", "BaseMask2", "BaseMask3", "BaseMask4", + }; + + const char* SDChannelSelect::mscPicturePaneNames[PAGE_COUNT] = { + "Picture_00", "Picture_01", "Picture_02", "Picture_03", "Picture_04", + }; + + const char* SDChannelSelect::mscEdgePaneNames[PAGE_COUNT] = { + "Edge0", "Edge1", "Edge2", "Edge3", "Edge4", + }; + + const char* SDChannelSelect::mscClockPaneNames[3] = { + "N_Clock0", "N_Clock1", "N_Clock2", + }; + + const char* SDChannelSelect::mscMaskPaneName = "ChMask"; + + static const f32 sThumbnailOffsets[2][2] = { + {64.0f, 48.0f}, + {85.0f, 48.0f}, + }; + + static const u32 sChannelLayoutOrder[12] = { + 11, 7, 3, 10, 6, 2, 9, 5, 1, 8, 4, 0, + }; + + SDChannelSelect::SDChannelSelect(EGG::Heap* heap) + : FaderSceneBase(heap), + mpButtonEventHandler(new SDChannelSelectButtonEventHandler(this)), + mState(0), + mThumbOffsetX(sThumbnailOffsets[SCGetAspectRatio()][0]), + mThumbOffsetY(sThumbnailOffsets[SCGetAspectRatio()][1]), + mCommandQueue(4, 0, 0, 0), + mNoticeQueue(42, 0, 0, 0), + mCurrentSDState(0), + mPreviousSDState(0), + mWorkerState(0), + mWorkerCommand(1), + mpWorkerHeap(NULL), + mpThumbnailWorkHeap(NULL), + mpSDWorker(NULL), + mpSDTitleIds(NULL), + mpSDTitleInfo(NULL), + mpNandTitleInfo(NULL), + mpCurrentLoadedChannel(NULL), + mpChannelTitleIds(NULL), + mLastOperation(14), + mOperationResult(0), + mbShowNoCardMessage(false), + mbOperationActive(false), + mbSDCardBroken(false), + mOperationState(0), + mDialogState(0), + mpSaveDataFile(NULL), + mAnimationState(0), + mAnimationTarget(0), + mbHazardTitleFound(false), + mbChannelLimitReached(false), + mbInitialLoadComplete(false), + mbNeedsRefresh(false) { + mCurrentPage = System::getSaveData()->getLastSDPrevPage(); + mPageCount = 20; + mCurrentChannelIndex = 0; + mbLeftArrowVisible = mCurrentPage != 0; + mbRightArrowVisible = mCurrentPage != mPageCount - 1; + setSceneParentFlags(SCN_PARENTFLAG_DRAW | SCN_PARENTFLAG_CALC); + math::VEC3 position(0.0f, 0.0f, 0.0f); + mPosition = position; + math::VEC2 scale(1.0f, 1.0f); + mScale = scale; + + nw4r::ut::Rect projection4x3; + System::getProjectionRect4x3(&projection4x3); + nw4r::ut::Rect projection16x9; + System::getProjectionRect16x9(&projection16x9); + f32 aspectScale = projection16x9.GetWidth() / projection4x3.GetWidth(); + if (SCGetAspectRatio() != SC_ASPECT_RATIO_16x9) { + aspectScale = 1.0f; + } + mAspectRatioScale = aspectScale; + + memset(&mPointerPosition, 0, 0x30); + mpThumbnailHeap = EGG::ExpHeap::create( + 0x13610, heap, MEM_HEAP_OPT_DEBUG_FILL | MEM_HEAP_OPT_THREAD_SAFE); + mpLayoutHeap = EGG::UnitHeap::create( + EGG::UnitHeap::calcHeapSize(0x212B8, 0x2D, 32), 0x212B8, + System::getMem2App(), 32, 2); + nw4r::ut::List_Init(&mChannelObjects, 0); + createChannelList(mCurrentPage, true); + TVRCManager::getHandle()->setEnable(TRUE); + + mpChannelTitleIds = (u32*)new (System::getMem2App(), 32) u8[mPageCount * 0x30]; + memset(mpChannelTitleIds, 0, mPageCount * 0x30); + mpSDTitleInfo = new (System::getMem2App(), 32) + SDChannelSelectTitleInfo[0x4B00 / sizeof(SDChannelSelectTitleInfo)]; + memset(mpSDTitleInfo, 0, 0x4B00); + mpSDTitleIds = new (System::getMem2App(), 32) ESTitleId32[0x2580 / sizeof(ESTitleId32)]; + memset(mpSDTitleIds, 0, 0x2580); + mpNandTitleInfo = new (System::getMem2App(), 32) + NandSDWorker::TitleUsage[0x600 / sizeof(NandSDWorker::TitleUsage)]; + memset(mpNandTitleInfo, 0, 0x600); + mFirstTitleCount = 0; + mSecondTitleCount = 0; + mSourcePage = -1; + mSourceIndex = -1; + } + + SDChannelSelect::~SDChannelSelect() { + } + + BOOL SDChannelSelect::isResetProcessDone() { + switch (mLastOperation) { + case 5: + case 6: + case 7: + case 8: + return FALSE; + default: + return TRUE; + } + } + + void SDChannelSelect::prepare() { + System::getBS2Manager()->abort(); + mpLayoutFile = System::getNandManager()->readLayoutAsync(getSceneHeap(), "sdChanSel.ash"); + mpCorruptIconFile = System::getNandManager()->readAsync( + getSceneHeap(), "corrupt_icon.ash", 0, 0, 0); + + SDChannelObj* channel = NULL; + while (channel = static_cast(nw4r::ut::List_GetNext(&mChannelObjects, channel)), + channel != NULL) { + iplSDChannelObj_813E3104(channel); + } + } + + void SDChannelSelect::create() { + mpSDWorker = new (System::getMem2App(), 4) NandSDWorker(); + mpWorkerHeap = (EGG::Heap*)System::getMem2App()->alloc(0x3EA60, 0x40); + u32 thumbnailHeapSize = MEMCalcHeapSizeForUnitHeap(0x19620, 0x60, 0x20); + mpThumbnailWorkHeap = (EGG::Heap*)System::getMem2App()->alloc( + thumbnailHeapSize + 0x40000, 0x40); + mpSDWorker->create(mpWorkerHeap, NULL, mpThumbnailWorkHeap, 0x12); + + if (System::getSaveData()->didntGotoSDMenu() == FALSE) { + mpSDWorker->mount_sd_async(); + mWorkerState = 1; + } + + mpDialogHeap = EGG::ExpHeap::create(0x21100, getSceneHeap(), 6); + mpChannelHeap = EGG::ExpHeap::create(0x2C100, getSceneHeap(), 6); + mpRsoHeap = EGG::ExpHeap::create(TVRCManager::getHandle(), 0x200000, 0); + mpRsoThread = new (System::getMem2App(), 32) channel::RsoThread(mpRsoHeap); + + createBaseLayout(); + if (mCurrentPage < mPageCount - 1) { + createChannelList(mCurrentPage + 1, false); + } + if (mCurrentPage > 0) { + createChannelList(mCurrentPage - 1, false); + } + updateNoCardLayouts(); + createChannelThumbnails(); + + u32 startTick = OSGetTick(); + while (System::getBS2Manager()->getIPLState() != 8) { + System::getBS2Manager()->update(); + OSReport(" ... wait for bs2 abord\n"); + VIWaitForRetrace(); + } + u32 elapsedTicks = OSGetTick() - startTick; + OSReport("*** BS2 abort costs: %dms\n", OSTicksToMilliseconds(elapsedTicks)); + + System::getFader()->fadeIn(); + mState = 2; + utility::CSFlags::UpdateFlagsFile(); + } + + void SDChannelSelect::enqueueStartNotice() { + SDChannelSelectCommand command; + command.type = 1; + command.titleId = 0; + command.arguments.values[0] = 0; + command.arguments.values[1] = 0; + command.arguments.values[2] = 0; + mCommandQueue.push(command); + } + + bool SDChannelSelect::enqueueFinishNotice() { + SDChannelSelectCommand command; + command.type = 2; + command.titleId = 0; + command.arguments.values[0] = 0; + command.arguments.values[1] = 0; + command.arguments.values[2] = 0; + mCommandQueue.push(command); + return true; + } + + bool SDChannelSelect::enqueueNotice(u32 titleId, u32 argument0, u32 argument1) { + if (mCurrentSDState != 6) { + return false; + } + + if (mNoticeQueue.capacity != mNoticeQueue.count) { + SDChannelSelectCommand notice; + notice.type = 4; + notice.titleId = titleId; + notice.arguments.values[0] = argument0; + notice.arguments.values[1] = argument1; + notice.arguments.values[2] = 0; + mNoticeQueue.notices[mNoticeQueue.writeIndex].copyFrom(notice); + ++mNoticeQueue.writeIndex; + if (mNoticeQueue.writeIndex >= mNoticeQueue.capacity) { + mNoticeQueue.writeIndex = 0; + } + ++mNoticeQueue.count; + } + return true; + } + + bool SDChannelSelect::enqueueLoadNotice() { + if (mCurrentSDState != 6) { + return false; + } + + SDChannelSelectCommand command; + command.type = 8; + command.titleId = 0; + command.arguments.values[0] = 0; + command.arguments.values[1] = 0; + command.arguments.values[2] = 0; + mCommandQueue.push(command); + return true; + } + + bool SDChannelSelect::enqueuePageNotice() { + if (mCurrentSDState != 6) { + return false; + } + + SDChannelSelectCommand command; + command.type = 9; + command.titleId = 0; + command.arguments.values[0] = 0; + command.arguments.values[1] = 0; + command.arguments.values[2] = 0; + mCommandQueue.push(command); + return true; + } + + bool SDChannelSelect::enqueueResultNotice(u32 result) { + if (mCurrentSDState != 6) { + return false; + } + + SDChannelSelectCommand command; + command.type = 5; + command.titleId = result; + command.arguments.values[0] = 0; + command.arguments.values[1] = 0; + command.arguments.values[2] = 0; + mCommandQueue.push(command); + return true; + } + + bool SDChannelSelect::enqueueChannelNotice(u32 controller, u32 page, u32 index, u32 value) { + if (mCurrentSDState != 6) { + return false; + } + + SDChannelSelectCommand command; + command.type = 10; + command.titleId = ((u64)page << 32) | index; + command.arguments.values[0] = value; + command.arguments.values[1] = (u32)&mFirstTitleCount; + command.arguments.values[2] = 0; + mCommandQueue.push(command); + return true; + } + + bool SDChannelSelect::enqueueMoveNotice(u32 controller, u32 page, u32 index) { + if (mCurrentSDState != 6) { + return false; + } + + SDChannelSelectCommand command; + command.type = 6; + command.titleId = ((u64)page << 32) | index; + command.arguments.values[0] = 0; + command.arguments.values[1] = 0; + command.arguments.values[2] = 0; + mCommandQueue.push(command); + return true; + } + + bool SDChannelSelect::enqueueStateNotice(u32 controller, u32 page, u32 index, u32 state) { + if (mCurrentSDState != 6) { + return false; + } + + SDChannelSelectCommand command; + command.type = 7; + command.titleId = ((u64)page << 32) | index; + command.arguments.values[0] = state; + command.arguments.values[1] = 0; + command.arguments.values[2] = 0; + mCommandQueue.push(command); + return true; + } + + bool SDChannelSelect::enqueueErrorNotice(u32 page, u32 index) { + if (mCurrentSDState != 6) { + return false; + } + + SDChannelSelectCommand command; + command.type = 11; + command.titleId = 0; + command.arguments.values[0] = page; + command.arguments.values[1] = index; + command.arguments.values[2] = 0; + mCommandQueue.push(command); + return true; + } + + bool SDChannelSelect::enqueueCommandNotice(u32 page, u32 index, u32 commandType) { + if (mCurrentSDState != 6) { + return false; + } + + SDChannelSelectCommand command; + command.type = 12; + command.titleId = 0; + command.arguments.values[0] = page; + command.arguments.values[1] = index; + command.arguments.values[2] = commandType; + mCommandQueue.push(command); + return true; + } + + bool SDChannelSelect::enqueueDeleteNotice(u32 controller, u32 page, u32 index) { + if (mCurrentSDState != 6) { + return false; + } + + SDChannelSelectCommand command; + command.type = 13; + command.titleId = ((u64)page << 32) | index; + command.arguments.values[0] = 0; + command.arguments.values[1] = 0; + command.arguments.values[2] = 0; + mCommandQueue.push(command); + return true; + } + + void SDChannelSelect::clearCommandQueue() { + while (mCommandQueue.count > 0) { + mCommandQueue.pop(); + } + } + + void SDChannelSelect::clearNoticeQueue() { + while (mNoticeQueue.count > 0) { + mNoticeQueue.pop(); + } + } + + void SDChannelSelect::handleWorkerStartup() { + if (!mpSDWorker->is_working()) { + if (mpSDWorker->get_async_result() == NandSDWorker::RESULT_OK) { + if (mOperationState == 0) { + setDialogMessage(8, 0xaa); + } + enqueueFinishNotice(); + mWorkerCommand = 1; + } + mpSDWorker->startup_async(); + mWorkerState = 2; + } else if (mPreviousSDState != mCurrentSDState && mCurrentSDState == 7) { + System::getErrorHandler()->set(ErrorHandler::DEFAULT, 1); + } + } + + void SDChannelSelect::handleNandTitleCount() { + if (!mpSDWorker->is_working()) { + int result = mpSDWorker->get_async_result(); + if (result == NandSDWorker::RESULT_NAND_CORRUPT) { + System::getErrorHandler()->set(ErrorHandler::DEFAULT, 1); + return; + } + + mNandTitleCount = mpSDWorker->get_nand_app_num(); + if (mNandTitleCount > 0x60) { + mNandTitleCount = 0x60; + } + if (mNandTitleCount != 0) { + mpSDWorker->list_nand_apps_usage_async( + mpNandTitleInfo, reinterpret_cast(mNandTitleCount)); + mWorkerState = 3; + } else { + mWorkerState = 4; + } + } + } + + void SDChannelSelect::handleNandTitleUsage() { + if (!mpSDWorker->is_working()) { + if (mpSDWorker->get_async_result() == NandSDWorker::RESULT_OK) { + qsort(mpNandTitleInfo, mNandTitleCount, sizeof(NandSDWorker::TitleUsage), + compareTitleUsage); + for (u32 index = 0; index < mNandTitleCount; ++index) { + mpNandTitleInfo[index].size -= 0x4000; + --mpNandTitleInfo[index].inode; + } + mWorkerState = 4; + } else { + System::getErrorHandler()->set(ErrorHandler::DEFAULT, 2); + } + } + } + + void SDChannelSelect::handleNandTitleUsageComplete() { + if (!mpSDWorker->is_working()) { + mLastOperation = 14; + mWorkerCommand = 1; + } + } + + void SDChannelSelect::handleSDTitleList() { + if (mpSDWorker->is_working()) { + return; + } + + mLastOperation = 14; + if (mSDTitleCount == 0) { + if (mDialogState == 0) { + setDialogMessage(1, 0); + mWorkerCommand = 15; + } + return; + } + + if (mpSDWorker->get_async_result() == NandSDWorker::RESULT_OK) { + for (u32 index = 0; index < mSDTitleCount; ++index) { + mpSDTitleInfo[index].titleId = mpSDTitleIds[index]; + if (mpSDTitleIds[index] == 0x48415A41) { + mbHazardTitleFound = true; + } + } + qsort(mpSDTitleInfo, mSDTitleCount, sizeof(SDChannelSelectTitleInfo), + compareTitleInfo); + enqueuePageNotice(); + mWorkerCommand = 1; + } else if (mDialogState == 0) { + setDialogMessage(2, 0xc3); + mWorkerCommand = 15; + } + } + + bool SDChannelSelect::setDialogMessage(u32 state, u32 message) { + if (mDialogState == 0) { + mDialogState = state; + mAnimationTarget = message; + return true; + } + return false; + } + + int SDChannelSelect::compareTitleUsage(const void* lhs, const void* rhs) { + const NandSDWorker::TitleUsage* left = + static_cast(lhs); + const NandSDWorker::TitleUsage* right = + static_cast(rhs); + if ((s32)left->size < (s32)right->size) { + return -1; + } + return left->size != right->size; + } + + int SDChannelSelect::compareTitleInfo(const void* lhs, const void* rhs) { + const SDChannelSelectTitleInfo* left = + static_cast(lhs); + const SDChannelSelectTitleInfo* right = + static_cast(rhs); + if (left->titleId < right->titleId) { + return -1; + } + return left->titleId != right->titleId; + } + + void SDChannelSelect::processWorkerCommands() { + if (mpSDWorker->is_working() || mWorkerState != 4) { + return; + } + + if (mCommandQueue.count == 0) { + if (mNoticeQueue.count > 0) { + mNoticeQueue.pop(); + } + return; + } + + SDChannelSelectCommand command = {0, 0, {{0, 0, 0}}}; + command.copyFrom(mCommandQueue.commands[mCommandQueue.readIndex]); + mLastOperation = command.type; + + switch (command.type) { + case 1: + mpSDWorker->mount_sd_async(); + mWorkerCommand = 0; + mbInitialLoadComplete = false; + break; + case 2: + mSDTitleCount = mpSDWorker->get_sd_app_num(); + mpSDWorker->list_sd_app_async(mpSDTitleIds); + mWorkerCommand = 2; + break; + case 5: + mpSDWorker->copy_sd_app_to_nand_async((ESTitleId32)command.titleId, true); + mWorkerCommand = 7; + break; + case 6: + mpSDWorker->copy_nand_app_to_sd_async((ESTitleId)command.titleId); + mWorkerCommand = 9; + break; + case 7: { + mpSDWorker->delete_nand_app_async((ESTitleId)command.titleId, + command.arguments.values[2] != 0); + mWorkerCommand = 10; + u32 index = 0; + while (index < mNandTitleCount && + mpNandTitleInfo[index].curTitleId != command.titleId) { + ++index; + } + if (index < mNandTitleCount) { + for (; index + 1 < mNandTitleCount; ++index) { + mpNandTitleInfo[index] = mpNandTitleInfo[index + 1]; + } + --mNandTitleCount; + } + break; + } + case 8: + mpSDWorker->update_sd_app_location_async(mpChannelTitleIds); + mWorkerCommand = 4; + break; + case 9: + mpSDWorker->read_sd_app_location_async(mpChannelTitleIds); + mWorkerCommand = 5; + break; + case 10: + mpSDWorker->check_for_sd_app_to_nand_async( + (ESTitleId)command.titleId, + command.arguments.appBlocks[0], command.arguments.appBlocks[1]); + mWorkerCommand = 8; + break; + case 11: + mpSDWorker->check_backup_fits_async( + command.arguments.titleLists[0], command.arguments.titleLists[1]); + mWorkerCommand = 11; + break; + case 12: + mpSDWorker->iplNandSD_81348EA8( + command.arguments.pointers[0], command.arguments.pointers[1], + command.arguments.pointers[2]); + mWorkerCommand = 12; + break; + case 13: + mpSDWorker->delete_sd_app_async((ESTitleId32)command.titleId); + mWorkerCommand = 13; + break; + default: + break; + } + + mCommandQueue.pop(); + } + + void SDChannelSelect::handleSDMountComplete() { + if (!mpSDWorker->is_working()) { + mLastOperation = 14; + if (mpSDWorker->get_async_result() == NandSDWorker::RESULT_OUT_OF_SPACE) { + mbSDCardBroken = true; + } + mbShowNoCardMessage = true; + mWorkerCommand = 1; + } + } + + void SDChannelSelect::handleCopyComplete() { + if (!mpSDWorker->is_working()) { + mLastOperation = 14; + if (mpSDWorker->get_async_result() == NandSDWorker::RESULT_NAND_CORRUPT) { + System::getErrorHandler()->set(ErrorHandler::DEFAULT, 1); + } else { + mWorkerCommand = 1; + } + } + } + + void SDChannelSelect::handleDeleteComplete() { + if (!mpSDWorker->is_working()) { + mLastOperation = 14; + mWorkerCommand = 1; + } + } + + void SDChannelSelect::handleMoveComplete() { + if (!mpSDWorker->is_working()) { + mLastOperation = 14; + if (mpSDWorker->get_async_result() == NandSDWorker::RESULT_NAND_CORRUPT) { + System::getErrorHandler()->set(ErrorHandler::DEFAULT, 1); + } else { + System::getChannelManager()->reserveRefresh(); + mWorkerCommand = 1; + } + } + } + + void SDChannelSelect::handleStorageCheckComplete() { + if (!mpSDWorker->is_working()) { + mLastOperation = 14; + mWorkerCommand = 1; + } + } + + void SDChannelSelect::handleCardCommand() { + if (mDialogState != 0) { + return; + } + + if (mpSDWorker->get_sd_state() == NandSDWorker::SD_STATE_EJECTED) { + setDialogMessage(2, 0xa9); + mWorkerCommand = 6; + } else if (mpSDWorker->get_sd_state() == NandSDWorker::SD_STATE_INSERTED) { + mWorkerCommand = 1; + } + } + + void SDChannelSelect::handleSDCardReady() { + if (mpSDWorker->get_sd_state() == NandSDWorker::SD_STATE_INSERTED && + mDialogState == 0) { + setDialogMessage(1, 0); + mWorkerCommand = 1; + } + } + + void SDChannelSelect::handleSDLocationUpdateComplete() { + if (!mpSDWorker->is_working()) { + mLastOperation = 14; + mWorkerCommand = 1; + } + } + + void SDChannelSelect::handleSDLocationReadComplete() { + if (!mpSDWorker->is_working()) { + mLastOperation = 14; + mWorkerCommand = 1; + } + } + + void SDChannelSelect::handleBackupFitComplete() { + if (!mpSDWorker->is_working()) { + mLastOperation = 14; + mWorkerCommand = 1; + } + } + + void SDChannelSelect::handleNandSDCleanupComplete() { + if (!mpSDWorker->is_working()) { + mLastOperation = 14; + mWorkerCommand = 1; + } + } + + void SDChannelSelect::handleSDDeleteComplete() { + if (!mpSDWorker->is_working()) { + mLastOperation = 14; + mWorkerCommand = 1; + } + } + + void SDChannelSelect::processWorkerState() { + mPreviousSDState = mCurrentSDState; + mCurrentSDState = mpSDWorker->get_sd_state(); + + if (mWorkerState == 2) { + handleNandTitleCount(); + } else if (mWorkerState < 2) { + if (mWorkerState > 0) { + handleWorkerStartup(); + } + } else if (mWorkerState < 4) { + handleNandTitleUsage(); + } + + switch (mWorkerCommand) { + case 0: + handleNandTitleUsageComplete(); + break; + case 1: + processWorkerCommands(); + break; + case 2: + handleSDTitleList(); + break; + case 3: + handleCopyComplete(); + break; + case 4: + handleSDMountComplete(); + break; + case 5: + handleDeleteComplete(); + break; + case 6: + handleSDCardReady(); + break; + case 7: + handleCopyComplete(); + break; + case 8: + handleSDLocationUpdateComplete(); + break; + case 9: + handleSDLocationReadComplete(); + break; + case 10: + handleMoveComplete(); + break; + case 11: + handleBackupFitComplete(); + break; + case 12: + handleNandSDCleanupComplete(); + break; + case 13: + handleSDDeleteComplete(); + break; + case 15: + handleCardCommand(); + break; + } + + if (mCurrentSDState != 6 && mState > 14 && mState < 24) { + mbDialogActive = true; + } + + updateDialogAnimation(); + } + + void SDChannelSelect::updateDialogAnimation() { + u32 animationIndex = 0xffffffff; + if (mpNoCardLayout->isPlaying()) { + animationIndex = 4; + if (!mpNoCardLayout->isPlaying(animationIndex)) { + return; + } + } + + switch (mOperationState) { + case 3: + mOperationState = 4; + mOperationStartTime = OSGetTime(); + break; + case 6: + mOperationState = 7; + break; + case 9: + mOperationState = 10; + mOperationStartTime = OSGetTime(); + break; + case 12: + mOperationState = 13; + break; + } + + if (mDialogState == 0) { + if (mOperationState == 10) { + mOperationState = 14; + } else if (mOperationState < 10 && mOperationState == 7) { + mOperationState = 8; + } + } else if (mDialogState == 2) { + switch (mOperationState) { + case 0: + case 1: + case 7: + case 13: + mOperationState = 2; + mAnimationState = mAnimationTarget; + break; + case 2: + if (mAnimationState != mAnimationTarget) { + mAnimationState = mAnimationTarget; + } + mDialogState = 0; + break; + case 4: + if (mAnimationState == mAnimationTarget) { + mDialogState = 0; + } else { + mOperationState = 5; + } + break; + case 10: + case 14: + case 15: + mOperationState = 11; + break; + } + } else if (mDialogState < 2) { + if (mDialogState > 0) { + switch (mOperationState) { + case 0: + case 1: + case 2: + case 7: + case 8: + case 13: + mOperationState = 1; + mDialogState = 0; + mAnimationState = mAnimationTarget; + break; + case 4: + mOperationState = 5; + break; + case 10: + case 14: + case 15: + mOperationState = 11; + break; + } + } + } else if (mDialogState == 8) { + switch (mOperationState) { + case 0: + case 1: + case 7: + case 13: + mOperationState = 8; + mAnimationState = mAnimationTarget; + break; + case 4: + mOperationState = 5; + break; + case 8: + if (mAnimationState != mAnimationTarget) { + mAnimationState = mAnimationTarget; + } + mDialogState = 0; + break; + case 10: + case 14: + case 15: + if (mAnimationState == mAnimationTarget) { + mDialogState = 0; + } else { + mOperationState = 11; + } + break; + } + } + + layout::Animator* animator = NULL; + switch (mOperationState) { + case 2: + static_cast(mpNoCardLayout->FindPaneByName("T_TimerMes")) + ->SetString(System::getMessage(mAnimationState), 0); + animator = mpNoCardLayout->getAnim(0); + break; + case 5: + animator = mpNoCardLayout->getAnim(1); + break; + case 8: + static_cast(mpNoCardLayout->FindPaneByName("T_TimerMes_01")) + ->SetString(System::getMessage(mAnimationState), 0); + animator = mpNoCardLayout->getAnim(2); + break; + case 11: + mpNoCardLayout->getAnim(4)->stop(); + animator = mpNoCardLayout->getAnim(3); + break; + case 14: + animator = mpNoCardLayout->getAnim(4); + break; + } + + if (animator != NULL) { + animator->initAnmFrame(); + animator->initFrame(); + animator->restart(); + ++mOperationState; + } + } + + void SDChannelSelect::updateChannelObjects() { + SDChannelObj* channel = NULL; + while (channel = static_cast(nw4r::ut::List_GetNext(&mChannelObjects, channel)), + channel != NULL) { + updateChannelObject(channel); + } + } + + void SDChannelSelect::updateChannelObject(SDChannelObj* channel) { + iplSDChannelObj_813E3104(channel); + iplSDChannelObj_813E311C(channel, mpDialogHeap, mpChannelHeap); + iplSDChannelObj_813E3178(channel, + getChannelBasePane(channel->getPage(), channel->getIndex(), + mCurrentPage)); + iplSDChannelObj_813E3180(channel, mpLayoutFile); + } + + void SDChannelSelect::calcChannelObjects() { + SDChannelObj* channel = NULL; + while (channel = static_cast(nw4r::ut::List_GetNext(&mChannelObjects, channel)), + channel != NULL) { + iplSDChannelObj_813E322C(channel); + } + } + + void SDChannelSelect::drawChannelObjects() { + SDChannelObj* channel = NULL; + while (channel = static_cast(nw4r::ut::List_GetNext(&mChannelObjects, channel)), + channel != NULL) { + if (hasChannelObject(channel->getPage(), channel->getIndex())) { + iplSDChannelObj_813E3304(channel); + } + } + + channel = NULL; + while (channel = static_cast(nw4r::ut::List_GetNext(&mChannelObjects, channel)), + channel != NULL) { + if (hasChannelObject(channel->getPage(), channel->getIndex())) { + iplSDChannelObj_813E330C(channel); + } + } + } + + void SDChannelSelect::updateArrowVisibility() { + int leftPageOffset = (mState == 10 || mState == 22) ? 1 : 0; + int rightPageOffset = (mState == 11 || mState == 23) ? 1 : 0; + layout::Object* layout = mpLayout; + + if (mCurrentPage <= leftPageOffset) { + layout->hide(mscEdgePaneNames[0]); + layout->hide(mscEdgePaneNames[1]); + } else { + layout->show(mscEdgePaneNames[0]); + layout->show(mscEdgePaneNames[1]); + } + + if (mCurrentPage + rightPageOffset + 1 >= mPageCount) { + layout->hide(mscEdgePaneNames[3]); + layout->hide(mscEdgePaneNames[4]); + } else { + layout->show(mscEdgePaneNames[3]); + layout->show(mscEdgePaneNames[4]); + } + } + + FaderSceneCommand SDChannelSelect::calcFadein() { + return mpLayout->isPlaying(0) ? FADER_SCN_CONTINUE : FADER_SCN_NEXT; + } + + void SDChannelSelect::calcCommon() { + if (mState == 2 && !mpLayout->isPlaying(0)) { + SDButton* button = static_cast(System::getSceneManager()->getScene(0x24)); + if (button != NULL) { + button->setEventHandler(mpButtonEventHandler, NULL); + mState = 3; + if (mCurrentPage < 1) { + button->initArrowAppearance(1, false); + } else { + button->initArrowAppearance(1, true); + } + + if (mPageCount < 2 || mPageCount - 1 <= mCurrentPage) { + button->initArrowAppearance(0, false); + } else { + button->initArrowAppearance(0, true); + } + } + } + + if (mState == 3 && System::getFader()->getStatus() == EGG::Fader::PREPARE_OUT) { + if (System::getSaveData()->didntGotoSDMenu()) { + mOperationResult = 0; + mState = 24; + } else { + mState = 1; + } + } + + mpLayout->calc(); + mpPaneManager->calc(); + calcChannelObjects(); + mpPageLayouts[0]->calc(); + mpPageLayouts[1]->calc(); + mpPageLayouts[2]->calc(); + mpHelpButtonLayout->calc(); + mpErrorLayout->calc(); + mpStateLayout->calc(); + mpNoCardLayout->calc(); + processWorkerState(); + } + + void SDChannelSelect::initCalcFadeout() { + if (mState == 4) { + clearCommandQueue(); + clearNoticeQueue(); + System::getFader()->fadeOut(); + TVRCManager::getHandle()->setEnable(FALSE); + System::getChannelManager()->refreshAsync(); + reserveAllSceneDestruction(4, NULL); + } + } + + FaderSceneCommand SDChannelSelect::calcFadeout() { + FaderSceneCommand command = FADER_SCN_CONTINUE; + if (mState == 4) { + command = (FaderSceneCommand)!System::getFader()->getStatus(); + } + return command; + } + + void SDChannelSelect::draw() { + bool onDrawLayer = System::onDrawLayer(DRAW_LAYER_DEFAULT); + if (mState == 13) { + if (onDrawLayer) { + utility::Graphics::setOrtho(); + GXColor color = {0, 0, 0, 255}; + nw4r::ut::Rect projection; + System::getProjectionRect(&projection); + utility::Graphics::drawPolygon(projection, color); + } + return; + } + + if (!onDrawLayer) { + return; + } + + if (mState == 7 || mState == 12 || mState == 14) { + utility::Graphics::setOrthoTransAndScale(mPosition, mScale); + } + utility::Graphics::setOrtho(); + + for (int edge = 0; edge < PAGE_COUNT; ++edge) { + nw4r::lyt::Pane* pane = mpLayout->FindPaneByName(mscEdgePaneNames[edge]); + pane->SetVisible(true); + mpLayout->draw(pane); + pane->SetVisible(false); + } + + drawChannelObjects(); + updateArrowVisibility(); + + GXSetScissor(0, 0, System::getRenderModeObj()->fbWidth, + System::getRenderModeObj()->efbHeight); + + nw4r::lyt::Pane* mask = mpLayout->FindPaneByName(mscMaskPaneName); + mask->SetVisible(false); + mpLayout->draw(); + + nw4r::lyt::TextBox* pageText = static_cast( + mpDialogLayout->FindPaneByName("TextBox_00")); + for (int page = 0; page < 3; ++page) { + wchar_t pageNumber[20]; + swprintf(pageNumber, 19, L"%d", mCurrentPage + page); + pageText->SetString(pageNumber, 0); + mpDialogLayout->draw(); + } + + drawChannelObjects(); + mask->SetVisible(true); + mpLayout->draw(mask); + mpPageLayouts[1]->draw(); + mpNoCardLayout->draw(); + } + + void SDChannelSelect::destroyChannelObject(SDChannelObj* channel) { + EGG::Heap* heap = channel->getHeap(); + delete channel; + if (heap != NULL) { + heap->destroy(); + } + } + + bool SDChannelSelect::hasChannelObject(int page, int index) const { + if (page == mCurrentPage) { + return true; + } + + if (page == mCurrentPage - 1) { + if (mState == 10 || mState == 22) { + return true; + } + for (int current = 3; current < MAX_CHANNEL_INDEX; current += 4) { + if (current == index) { + return true; + } + } + } else if (page == mCurrentPage - 2) { + if (mState == 10 || mState == 22) { + for (int current = 3; current < MAX_CHANNEL_INDEX; current += 4) { + if (current == index) { + return true; + } + } + } + } else if (page == mCurrentPage + 1) { + if (mState == 11 || mState == 23) { + return true; + } + for (int current = 0; current < MAX_CHANNEL_INDEX; current += 4) { + if (current == index) { + return true; + } + } + } else if (page == mCurrentPage + 2 && (mState == 11 || mState == 23)) { + for (int current = 0; current < MAX_CHANNEL_INDEX; current += 4) { + if (current == index) { + return true; + } + } + } + + return false; + } + + void SDChannelSelect::destroy() { + System::getBS2Manager()->restart(); + System::getSaveData()->setLastSDPrevPage(mCurrentPage); + + SDChannelObj* channel = NULL; + while (channel = static_cast(nw4r::ut::List_GetNext(&mChannelObjects, channel)), + channel != NULL) { + nw4r::ut::List_Remove(&mChannelObjects, channel); + destroyChannelObject(channel); + } + + if (mpRsoThread != NULL) { + delete mpRsoThread; + mpRsoThread = NULL; + } + + if (mpThumbnailHeap != NULL) { + mpThumbnailHeap->destroy(); + } + if (mpLayoutHeap != NULL) { + mpLayoutHeap->destroy(); + } + if (mpDialogHeap != NULL) { + mpDialogHeap->destroy(); + } + if (mpChannelHeap != NULL) { + mpChannelHeap->destroy(); + } + + if (mpSaveDataFile != NULL) { + while (!System::getSaveData()->isFinished(mpSaveDataFile)) { + OSYieldThread(); + } + delete mpSaveDataFile; + mpSaveDataFile = NULL; + } + + if (mpSDWorker != NULL) { + if (!mpSDWorker->is_terminated()) { + mpSDWorker->terminate_async(); + while (mpSDWorker->is_working()) { + OSYieldThread(); + } + while (!mpSDWorker->is_terminated()) { + OSYieldThread(); + } + } + + if (mpWorkerHeap != NULL) { + mpWorkerHeap->destroy(); + } + if (mpThumbnailWorkHeap != NULL) { + mpThumbnailWorkHeap->destroy(); + } + + delete[] mpSDTitleIds; + delete[] mpSDTitleInfo; + delete[] mpChannelTitleIds; + delete[] mpNandTitleInfo; + delete mpSDWorker; + mpSDWorker = NULL; + } + } + + void SDChannelSelect::createBaseLayout() { + GXTexObj widescreenTexture; + GXTexObj standardTexture; + + mpLayout = new layout::Object(getSceneHeap(), mpLayoutFile, "arc", + "mn_SdcardMenu_a.brlyt"); + + if (SCGetAspectRatio() == SC_ASPECT_RATIO_16x9) { + mpLayout->FindPaneByName("ChangeTex16x9") + ->GetMaterial() + ->GetTexture(&widescreenTexture, GX_TEXMAP0); + mpLayout->FindPaneByName("Picture_16") + ->GetMaterial() + ->GetTexture(&standardTexture, GX_TEXMAP0); + + for (int page = 0; page < PAGE_COUNT; ++page) { + mpLayout->FindPaneByName(mscPicturePaneNames[page]) + ->GetMaterial() + ->SetTexture(GX_TEXMAP0, widescreenTexture); + mpLayout->FindPaneByName(mscEdgePaneNames[page]) + ->GetMaterial() + ->SetTexture(GX_TEXMAP0, standardTexture); + } + } + + mpLayout->bind("mn_SdcardMenu_a.brlan"); + mpLayout->finishBinding(); + + mpDialogLayout = new layout::Object(getSceneHeap(), mpLayoutFile, "arc", + "mn_SdcardMenu_Page.brlyt"); + mpNoCardLayout = new layout::Object(getSceneHeap(), mpLayoutFile, "arc", + "mn_Nocard.brlyt"); + mpNoCardLayout->bindToGroup("mn_Nocard_IN.brlan", "Group_00", false, true); + mpNoCardLayout->bindToGroup("mn_Nocard_Out.brlan", "Group_00", false, true); + mpNoCardLayout->bindToGroup("mn_Nocard_IN_02.brlan", "Group_01", false, true); + mpNoCardLayout->bindToGroup("mn_Nocard_Out_02.brlan", "Group_01", false, true); + mpNoCardLayout->bindToGroup("mn_Nocard_Wait.brlan", "G_Wait", false, true); + mpNoCardLayout->getAnim(0)->initAnmFrame(); + mpNoCardLayout->getAnim(2)->initAnmFrame(); + mpNoCardLayout->finishBinding(); + + mpHelpButtonLayout = new layout::Object(getSceneHeap(), mpLayoutFile, "arc", + "help_Btn.brlyt"); + + mpButtonEventHandler = new SDChannelSelectButtonEventHandler(this); + mpPaneManager = new gui::PaneManager(mpButtonEventHandler, mpLayout->getDrawInfo(), + NULL, NULL); + mpPaneManager->createLayoutScene(*mpLayout->getNW4RLyt()); + mpPaneManager->setAllComponentTriggerTarget(false); + + for (int index = 0; index < MAX_CHANNEL_INDEX; ++index) { + const char* paneName = mscChannelPaneNames[mCurrentPage % PAGE_COUNT][index]; + if (paneName[0] != '\0') { + mpPaneManager->getPaneComponentByPane(mpLayout->FindPaneByName(paneName)) + ->setTriggerTarget(true); + } + } + + for (int index = 0; index < 4; ++index) { + mpPageAnimations[index] = new math::HermiteIntp(); + } + } + + bool SDChannelSelect::isChannelInCalc(int page, int index, int currentPage) const { + int relativePage = page - currentPage; + if (relativePage <= -3 || relativePage >= 3 || + strcmp(mscChannelPaneNames[relativePage + 2][index], "") == 0) { + return false; + } + return true; + } + + nw4r::lyt::Pane* SDChannelSelect::getChannelBasePane(int page, int index, + int currentPage) const { + if (isChannelInCalc(page, index, currentPage)) { + return mpLayout->FindPaneByName(mscChannelPaneNames[page - currentPage + 2][index]); + } + return mpLayout->FindPaneByName("Picture_16"); + } + + nw4r::lyt::Pane* SDChannelSelect::getCenterChannelPane(int index) const { + return mpLayout->FindPaneByName(mscChannelPaneNames[2][index]); + } + + nw4r::lyt::Pane* SDChannelSelect::getChannelPane(int index) const { + return mpLayout->FindPaneByName(mscChannelPaneNames[2][index]); + } + + math::VEC3 SDChannelSelect::getChannelPanePosition(SDChannelSelect* scene, int index) { + math::VEC3 position(0.0f, 0.0f, 0.0f); + MTXMultVec(scene->getCenterChannelPane(index)->GetGlobalMtx(), position, position); + return position; + } + + void SDChannelSelect::calcPageAnimations() { + for (int index = 0; index < 4; ++index) { + math::HermiteIntp* animation = mpPageAnimations[index]; + animation->calc(); + } + } + + void SDChannelSelect::startResetting() { + snd::getSystem()->resetAllSound(); + clearCommandQueue(); + clearNoticeQueue(); + } + + void SDChannelSelectCommand::copyFrom(const SDChannelSelectCommand& other) { + type = other.type; + titleId = other.titleId; + arguments.values[0] = other.arguments.values[0]; + arguments.values[1] = other.arguments.values[1]; + arguments.values[2] = other.arguments.values[2]; + } + + bool SDChannelSelectCommandQueue::push(const SDChannelSelectCommand& command) { + if (capacity == count) { + return false; + } + + commands[writeIndex].copyFrom(command); + ++writeIndex; + if (writeIndex >= capacity) { + writeIndex = 0; + } + ++count; + return true; + } + + bool SDChannelSelectCommandQueue::pop() { + bool result = true; + if (count == 0) { + result = false; + } else { + ++readIndex; + if (readIndex >= capacity) { + readIndex = 0; + } + --count; + } + return result; + } + + bool SDChannelSelectNoticeQueue::pop() { + bool result = true; + if (count == 0) { + result = false; + } else { + ++readIndex; + if (readIndex >= capacity) { + readIndex = 0; + } + --count; + } + return result; + } + } +} -- 2.49.1 From 9347e0b1c3969c464ca44b8534b7085cdeecec2b Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Mon, 28 Sep 2026 22:53:23 -0500 Subject: [PATCH 27/61] Decompile iplSDMemory to 22/66 functions (#249) * decompile SD memory setup helpers * match SD memory arrow helpers * match sd memory setup helpers * decompile sd memory dialog reset * order sd memory text pane updates * match sd memory calculation * decompile sd memory dialog states --- config/43U/symbols.txt | 82 +-- include/scene/sdChannelMemory/iplSDMemory.h | 115 ++++ include/system/iplDialogWindow.h | 4 + include/utility/iplScroller.h | 4 + libs/NW4R/include/nw4r/lyt/pane.h | 4 + src/scene/sdChannelMemory/iplSDMemory.cpp | 681 ++++++++++++++++++++ 6 files changed, 849 insertions(+), 41 deletions(-) create mode 100644 include/scene/sdChannelMemory/iplSDMemory.h create mode 100644 src/scene/sdChannelMemory/iplSDMemory.cpp diff --git a/config/43U/symbols.txt b/config/43U/symbols.txt index 625ff77d..1aa0bdf3 100644 --- a/config/43U/symbols.txt +++ b/config/43U/symbols.txt @@ -4837,48 +4837,48 @@ onEvent__Q33ipl5scene22SDMenuEventHandlerBaseFUlUlPv = .text:0x813EB51C; // type onEventDerived__Q33ipl5scene22SDMenuEventHandlerBaseFUlUlPCQ33ipl10controller9Interface = .text:0x813EB5E8; // type:function size:0x4 __ct__Q33ipl5scene8SDMemoryFv = .text:0x813EB5EC; // type:function size:0x48 __dt__Q33ipl5scene8SDMemoryFv = .text:0x813EB634; // type:function size:0x5C -iplSDMemory_813EB690 = .text:0x813EB690; // type:function size:0x10A0 -iplSDMemory_813EC730 = .text:0x813EC730; // type:function size:0xD4 -iplSDMemory_813EC804 = .text:0x813EC804; // type:function size:0x144 -iplSDMemory_813EC948 = .text:0x813EC948; // type:function size:0x20 -iplSDMemory_813EC968 = .text:0x813EC968; // type:function size:0x84 -iplSDMemory_813EC9EC = .text:0x813EC9EC; // type:function size:0x9C -iplSDMemory_813ECA88 = .text:0x813ECA88; // type:function size:0x74 -iplSDMemory_813ECAFC = .text:0x813ECAFC; // type:function size:0x74 -iplSDMemory_813ECB70 = .text:0x813ECB70; // type:function size:0x78 -iplSDMemory_813ECBE8 = .text:0x813ECBE8; // type:function size:0x78 -iplSDMemory_813ECC60 = .text:0x813ECC60; // type:function size:0x160 -iplSDMemory_813ECDC0 = .text:0x813ECDC0; // type:function size:0x60 -iplSDMemory_813ECE20 = .text:0x813ECE20; // type:function size:0x60 -iplSDMemory_813ECE80 = .text:0x813ECE80; // type:function size:0x64 -iplSDMemory_813ECEE4 = .text:0x813ECEE4; // type:function size:0x64 -iplSDMemory_813ECF48 = .text:0x813ECF48; // type:function size:0x13C -iplSDMemory_813ED084 = .text:0x813ED084; // type:function size:0x268 -iplSDMemory_813ED2EC = .text:0x813ED2EC; // type:function size:0x4CC -iplSDMemory_813ED7B8 = .text:0x813ED7B8; // type:function size:0xA4 -iplSDMemory_813ED85C = .text:0x813ED85C; // type:function size:0xC4 -iplSDMemory_813ED920 = .text:0x813ED920; // type:function size:0x124 -iplSDMemory_813EDA44 = .text:0x813EDA44; // type:function size:0x110 -iplSDMemory_813EDB54 = .text:0x813EDB54; // type:function size:0x78 -iplSDMemory_813EDBCC = .text:0x813EDBCC; // type:function size:0xC0 -iplSDMemory_813EDC8C = .text:0x813EDC8C; // type:function size:0x278 -iplSDMemory_813EDF04 = .text:0x813EDF04; // type:function size:0xA4 -iplSDMemory_813EDFA8 = .text:0x813EDFA8; // type:function size:0x130 -iplSDMemory_813EE0D8 = .text:0x813EE0D8; // type:function size:0xE0 -iplSDMemory_813EE1B8 = .text:0x813EE1B8; // type:function size:0x1A0 +create__Q33ipl5scene8SDMemoryFPQ23EGG4HeapPQ33ipl4nand10LayoutFilePQ33ipl5scene17NandSDCardManager = .text:0x813EB690; // type:function size:0x10A0 +setTitleLists__Q33ipl5scene8SDMemoryFRCQ43ipl5scene8SDMemory10TitleRangeRCQ43ipl5scene8SDMemory10TitleRange = .text:0x813EC730; // type:function size:0xD4 +setScrollLimit__Q33ipl5scene8SDMemoryFv = .text:0x813EC804; // type:function size:0x144 +init__Q33ipl7utility8ScrollerFv = .text:0x813EC948; // type:function size:0x20 +resetScrollArrows__Q33ipl5scene8SDMemoryFv = .text:0x813EC968; // type:function size:0x84 +updateScrollArrows__Q33ipl5scene8SDMemoryFUlUlUlUl = .text:0x813EC9EC; // type:function size:0x9C +showDownArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECA88; // type:function size:0x74 +showUpArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECAFC; // type:function size:0x74 +hideDownArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECB70; // type:function size:0x78 +hideUpArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECBE8; // type:function size:0x78 +updateSideArrows__Q33ipl5scene8SDMemoryFv = .text:0x813ECC60; // type:function size:0x160 +showLeftArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECDC0; // type:function size:0x60 +showRightArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECE20; // type:function size:0x60 +hideLeftArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECE80; // type:function size:0x64 +hideRightArrow__Q33ipl5scene8SDMemoryFv = .text:0x813ECEE4; // type:function size:0x64 +resetDialogPaneAnimations__Q33ipl5scene8SDMemoryFv = .text:0x813ECF48; // type:function size:0x13C +calc__Q33ipl5scene8SDMemoryFv = .text:0x813ED084; // type:function size:0x268 +updateState__Q33ipl5scene8SDMemoryFv = .text:0x813ED2EC; // type:function size:0x4CC +onDialogState0__Q33ipl5scene8SDMemoryFv = .text:0x813ED7B8; // type:function size:0xA4 +onDialogState2__Q33ipl5scene8SDMemoryFv = .text:0x813ED85C; // type:function size:0xC4 +onDialogState3__Q33ipl5scene8SDMemoryFv = .text:0x813ED920; // type:function size:0x124 +onDialogState4__Q33ipl5scene8SDMemoryFv = .text:0x813EDA44; // type:function size:0x110 +onDialogState6__Q33ipl5scene8SDMemoryFv = .text:0x813EDB54; // type:function size:0x78 +onDialogState7__Q33ipl5scene8SDMemoryFv = .text:0x813EDBCC; // type:function size:0xC0 +onDialogState8__Q33ipl5scene8SDMemoryFv = .text:0x813EDC8C; // type:function size:0x278 +onDialogState9__Q33ipl5scene8SDMemoryFv = .text:0x813EDF04; // type:function size:0xA4 +onDialogState10__Q33ipl5scene8SDMemoryFv = .text:0x813EDFA8; // type:function size:0x130 +onDialogState11__Q33ipl5scene8SDMemoryFv = .text:0x813EE0D8; // type:function size:0xE0 +onDialogState12__Q33ipl5scene8SDMemoryFv = .text:0x813EE1B8; // type:function size:0x1A0 iplSDMemory_813EE358 = .text:0x813EE358; // type:function size:0x44 -iplSDMemory_813EE39C = .text:0x813EE39C; // type:function size:0xEC -iplSDMemory_813EE488 = .text:0x813EE488; // type:function size:0x1C4 -iplSDMemory_813EE64C = .text:0x813EE64C; // type:function size:0x12C -iplSDMemory_813EE778 = .text:0x813EE778; // type:function size:0xA0 -iplSDMemory_813EE818 = .text:0x813EE818; // type:function size:0x128 -iplSDMemory_813EE940 = .text:0x813EE940; // type:function size:0xE8 -iplSDMemory_813EEA28 = .text:0x813EEA28; // type:function size:0x84 -iplSDMemory_813EEAAC = .text:0x813EEAAC; // type:function size:0xE8 -iplSDMemory_813EEB94 = .text:0x813EEB94; // type:function size:0x148 -iplSDMemory_813EECDC = .text:0x813EECDC; // type:function size:0x11C -iplSDMemory_813EEDF8 = .text:0x813EEDF8; // type:function size:0x78 -iplSDMemory_813EEE70 = .text:0x813EEE70; // type:function size:0xC0 +onDialogState13__Q33ipl5scene8SDMemoryFv = .text:0x813EE39C; // type:function size:0xEC +onDialogState14__Q33ipl5scene8SDMemoryFv = .text:0x813EE488; // type:function size:0x1C4 +onDialogState15__Q33ipl5scene8SDMemoryFv = .text:0x813EE64C; // type:function size:0x12C +onDialogState16__Q33ipl5scene8SDMemoryFv = .text:0x813EE778; // type:function size:0xA0 +onDialogState17__Q33ipl5scene8SDMemoryFv = .text:0x813EE818; // type:function size:0x128 +onDialogState18__Q33ipl5scene8SDMemoryFv = .text:0x813EE940; // type:function size:0xE8 +onDialogState19__Q33ipl5scene8SDMemoryFv = .text:0x813EEA28; // type:function size:0x84 +onDialogState20__Q33ipl5scene8SDMemoryFv = .text:0x813EEAAC; // type:function size:0xE8 +onDialogState21__Q33ipl5scene8SDMemoryFv = .text:0x813EEB94; // type:function size:0x148 +onDialogState22__Q33ipl5scene8SDMemoryFv = .text:0x813EECDC; // type:function size:0x11C +onDialogState23__Q33ipl5scene8SDMemoryFv = .text:0x813EEDF8; // type:function size:0x78 +onDialogState24__Q33ipl5scene8SDMemoryFv = .text:0x813EEE70; // type:function size:0xC0 iplSDMemory_813EEF30 = .text:0x813EEF30; // type:function size:0x88 iplSDMemory_813EEFB8 = .text:0x813EEFB8; // type:function size:0x70C iplSDMemory_813EF6C4 = .text:0x813EF6C4; // type:function size:0x14 diff --git a/include/scene/sdChannelMemory/iplSDMemory.h b/include/scene/sdChannelMemory/iplSDMemory.h new file mode 100644 index 00000000..6352f88c --- /dev/null +++ b/include/scene/sdChannelMemory/iplSDMemory.h @@ -0,0 +1,115 @@ +#ifndef IPL_SCENE_SD_MEMORY_H +#define IPL_SCENE_SD_MEMORY_H + +#include + +#include "layout/iplLayout.h" +#include "layout/iplGuiManager.h" +#include "scene/board/iplFocusObject.h" +#include "scene/channelEdit/iplNandSDCardManager.h" + +namespace ipl { + namespace scene { + class SDMemory { + public: + struct TitleRange { + ESTitleId* mpTitles; + u32 mCount; + }; + + SDMemory(); + ~SDMemory(); + + void create(EGG::Heap* heap, nand::LayoutFile* layoutFile, NandSDCardManager* manager); + void setTitleLists(const TitleRange& nandTitles, const TitleRange& sdTitles); + bool calc(); + void setScrollLimit(); + void updateSideArrows(); + void resetScrollArrows(); + void updateScrollArrows(u32 previousDownEnd, u32 previousUpEnd, u32 downEnd, u32 upEnd); + void showDownArrow(); + void showUpArrow(); + void hideDownArrow(); + void hideUpArrow(); + void showLeftArrow(); + void showRightArrow(); + void hideLeftArrow(); + void hideRightArrow(); + + private: + s32 updateState(); + void onDialogState0(); + void onDialogState2(); + bool onDialogState3(); + void onDialogState4(); + void onDialogState6(); + void onDialogState7(); + void onDialogState8(); + void onDialogState9(); + void onDialogState10(); + void onDialogState11(); + void onDialogState12(); + void onDialogState13(); + void onDialogState14(); + void onDialogState15(); + void onDialogState16(); + void onDialogState17(); + void onDialogState18(); + void onDialogState19(); + bool onDialogState20(); + void onDialogState21(); + bool onDialogState22(); + void onDialogState23(); + bool onDialogState24(); + void resetDialogPaneAnimations(); + + layout::Object* mpMainLayout; + layout::Object* mpTitleLayout; + layout::Object* mpDialogLayout; + layout::Object* mpProgressLayout; + gui::PaneManager* mpPaneManagers[3]; + s32 mDialogState; + s32 mProcessState; + s32 mDisplayMode; + s32 mMessageId; + u32 mErrorCode; + u32 mPanelStates[3]; + u32 mTitlePanelStates[5]; + u32 mPanelAnimationStates[4]; + NandSDCardManager* mpNandSDCardManager; + TitleRange mNandTitleRange; + TitleRange mSDTitleRange; + u32 mTitleCount; + u32 mCurrentTitle; + u32 mTitleFlags; + ESTitleId mTitleIds[96]; + wchar_t mTitleNames[96][21]; + u32 mTitleNameCount; + u32 mNandTitleNameCount; + ESTitleId mNandTitleIds[96]; + u32 mNandTitleCount; + u32 mSDTitleCount; + ESTitleId mSDTitleIds[96]; + wchar_t mCurrentTitleName[0x840]; + u8 mTransferFlags[4]; + u32 mTransferStatus; + u64 mTransferStartTime; + s32 mTransferFrame; + struct TitleListState { + ESTitleId* mpTitles; + u32 mCount; + ESTitleId* mpSecondaryTitles; + u32 mSecondaryCount; + ESTitleId* mpNames; + u32 mNameCount; + } mTitleListState; + scroller mScroller; + s32 mButtonState; + u8 mControllerFlags[4]; + u32 mFinalState[3]; + u8 mFinalFlags[4]; + }; + } // namespace scene +} // namespace ipl + +#endif diff --git a/include/system/iplDialogWindow.h b/include/system/iplDialogWindow.h index 4a2498df..5fe75217 100644 --- a/include/system/iplDialogWindow.h +++ b/include/system/iplDialogWindow.h @@ -118,6 +118,10 @@ namespace ipl { int getLastResult() { return mLastResult; } /** @return If the dialog is moving onto the next state. */ bool doingNextState() { return mbNextState; } +#ifdef IPL_SDMEMORY_DIALOG_STATE_ACCESSOR + int getStateForSDMemory() const { return mState; } + int getResultForSDMemory() const { return mResult; } +#endif /*=================*/ /* DIALOG BUTTON 0 */ diff --git a/include/utility/iplScroller.h b/include/utility/iplScroller.h index bbcd685e..fe39e065 100644 --- a/include/utility/iplScroller.h +++ b/include/utility/iplScroller.h @@ -49,6 +49,9 @@ namespace ipl { public: Scroller(); +#ifdef IPL_SDMEMORY_SCROLLER_INIT_OUT_OF_LINE + void init(); +#else void init() { mState = 0; mScroll = 0.0f; @@ -56,6 +59,7 @@ namespace ipl { mUpLimit = 0.0f; mDownLimit = 0.0f; } +#endif void calc(); f32 get() const; diff --git a/libs/NW4R/include/nw4r/lyt/pane.h b/libs/NW4R/include/nw4r/lyt/pane.h index 4f0519af..3bff5dc5 100644 --- a/libs/NW4R/include/nw4r/lyt/pane.h +++ b/libs/NW4R/include/nw4r/lyt/pane.h @@ -88,7 +88,11 @@ namespace nw4r { PaneList& GetChildList() { return mChildList; } const math::VEC3& GetTranslate() { return mTranslate; } +#ifdef IPL_SDMEMORY_SET_TRANSLATE_OUT_OF_LINE + void SetTranslate(const math::VEC3& translate); +#else void SetTranslate(const math::VEC3& translate) { mTranslate = translate; } +#endif void SetTranslate(const math::VEC2& translate) { SetTranslate(math::VEC3(translate.x, translate.y, 0.0f)); } const math::VEC3& GetRotate() const { return mRotate; } diff --git a/src/scene/sdChannelMemory/iplSDMemory.cpp b/src/scene/sdChannelMemory/iplSDMemory.cpp new file mode 100644 index 00000000..eb7cd7d3 --- /dev/null +++ b/src/scene/sdChannelMemory/iplSDMemory.cpp @@ -0,0 +1,681 @@ +#define IPL_SDMEMORY_SCROLLER_INIT_OUT_OF_LINE +#define IPL_SDMEMORY_SET_TRANSLATE_OUT_OF_LINE +#define IPL_SDMEMORY_DIALOG_STATE_ACCESSOR +#include "scene/sdChannelMemory/iplSDMemory.h" +#undef IPL_SDMEMORY_DIALOG_STATE_ACCESSOR +#undef IPL_SDMEMORY_SET_TRANSLATE_OUT_OF_LINE +#undef IPL_SDMEMORY_SCROLLER_INIT_OUT_OF_LINE + +#include "system/iplSystem.h" +#include "sound/iplSound.h" + +namespace ipl { + namespace utility { + void Scroller::init() { + mState = 0; + mScroll = 0.0f; + unk_0x3C = 0.0f; + mUpLimit = 0.0f; + mDownLimit = 0.0f; + } + } + + namespace scene { + static const char* const sControlPaneNames[] = { + "A", "B", "B_BtnA", "A", "B", "C", "D", "B_BtnA", "B_00", "C_00", "D_00", "B_BtnA", + }; + + static const char* const sDialogPaneNames[] = {"B_ArwR", "B_ArwL", "B_CalExit", "B_CalExit_00"}; + + SDMemory::SDMemory() : mScroller() {} + + SDMemory::~SDMemory() {} + + void SDMemory::create(EGG::Heap* heap, nand::LayoutFile* layoutFile, NandSDCardManager* manager) { + mpNandSDCardManager = manager; + + mpMainLayout = new (heap) layout::Object(heap, layoutFile, "arc", "mn_DialogWindow_ChChange_a.brlyt"); + mpMainLayout->bindToGroup("mn_DialogWindow_ChChange_a_DialogIn.brlan", "G_InOut", false, true); + mpMainLayout->bindToGroup("mn_DialogWindow_ChChange_a_DialogOut.brlan", "G_InOut", false, true); + mpMainLayout->bindToGroup("mn_DialogWindow_ChChange_a_FocusBtn_on.brlan", "G_FocusBtnA", false, true); + mpMainLayout->bindToGroup("mn_DialogWindow_ChChange_a_FocusBtn_off.brlan", "G_FocusBtnA", false, true); + mpMainLayout->bindToGroup("mn_DialogWindow_ChChange_a_SelectBtn_Ac.brlan", "G_SelectBtnA", false, true); + mpMainLayout->bindToGroup("mn_DialogWindow_ChChange_a_BtnA_Rollover.brlan", "G_BtnA", false, true); + mpMainLayout->bindToGroup("mn_DialogWindow_ChChange_a_BtnA_Rollout.brlan", "G_BtnA", false, true); + mpMainLayout->bindToGroup("mn_DialogWindow_ChChange_a_BtnA_On.brlan", "G_BtnA", false, true); + mpMainLayout->bindToGroup("mn_DialogWindow_ChChange_a_BtnB_Rollover.brlan", "G_BtnB", false, true); + mpMainLayout->bindToGroup("mn_DialogWindow_ChChange_a_BtnB_Rollout.brlan", "G_BtnB", false, true); + mpMainLayout->bindToGroup("mn_DialogWindow_ChChange_a_BtnB_On.brlan", "G_BtnB", false, true); + mpMainLayout->finishBinding(); + mpMainLayout->getAnim(0)->initAnmFrame(); + mpMainLayout->getAnim(2)->initAnmFrame(); + mpMainLayout->getAnim(5)->initAnmFrame(); + mpMainLayout->getAnim(8)->initAnmFrame(); + + nw4r::lyt::TextBox* textBox = nw4r::ut::DynamicCast(mpMainLayout->FindPaneByName("T_Dialog_00")); + textBox->SetString(System::getMessage(0xB0)); + textBox = nw4r::ut::DynamicCast(mpMainLayout->FindPaneByName("TextBox_05")); + textBox->SetString(System::getMessage(0xBB)); + textBox = nw4r::ut::DynamicCast(mpMainLayout->FindPaneByName("TextBox_06")); + textBox->SetString(System::getMessage(0xBC)); + textBox = nw4r::ut::DynamicCast(mpMainLayout->FindPaneByName("T_BtnA")); + textBox->SetString(System::getMessage(0x25)); + + mpTitleLayout = new (heap) layout::Object(heap, layoutFile, "arc", "mn_DialogWindow_ChChange_b.brlyt"); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_DialogIn.brlan", "G_InOut", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_DialogOut.brlan", "G_InOut", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_FocusBtn_on.brlan", "G_FocusBtnA", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_FocusBtn_off.brlan", "G_FocusBtnA", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_SelectBtn_Ac.brlan", "G_SelectBtnA", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnA_Rollover.brlan", "G_BtnA", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnA_Rollout.brlan", "G_BtnA", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnA_On.brlan", "G_BtnA", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnB_Rollover.brlan", "G_BtnB", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnB_Rollout.brlan", "G_BtnB", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnB_On.brlan", "G_BtnB", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnC_Rollover.brlan", "G_BtnC", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnC_Rollout.brlan", "G_BtnC", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnC_On.brlan", "G_BtnC", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnD_Rollover.brlan", "G_BtnD", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnD_Rollout.brlan", "G_BtnD", false, true); + mpTitleLayout->bindToGroup("mn_DialogWindow_ChChange_b_BtnD_On.brlan", "G_BtnD", false, true); + mpTitleLayout->finishBinding(); + mpTitleLayout->getAnim(0)->initAnmFrame(); + mpTitleLayout->getAnim(2)->initAnmFrame(); + mpTitleLayout->getAnim(5)->initAnmFrame(); + mpTitleLayout->getAnim(8)->initAnmFrame(); + mpTitleLayout->getAnim(11)->initAnmFrame(); + mpTitleLayout->getAnim(14)->initAnmFrame(); + + textBox = nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("T_Dialog")); + textBox->SetString(System::getMessage(0xB6)); + textBox = nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_00")); + textBox->SetString(System::getMessage(0xB7)); + textBox = nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_01")); + textBox->SetString(System::getMessage(0xB8)); + textBox = nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_02")); + textBox->SetString(System::getMessage(0xB9)); + textBox = nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_03")); + textBox->SetString(System::getMessage(0xBA)); + textBox = nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("T_Dialog_00")); + textBox->SetString(System::getMessage(0xB6)); + textBox = nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_05")); + textBox->SetString(System::getMessage(0xB8)); + textBox = nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_06")); + textBox->SetString(System::getMessage(0xB9)); + textBox = nw4r::ut::DynamicCast(mpTitleLayout->FindPaneByName("TextBox_07")); + textBox->SetString(System::getMessage(0xBA)); + + mpDialogLayout = new (heap) layout::Object(heap, layoutFile, "arc", "mn_DialogWindow_ChChange_c.brlyt"); + static_cast(mpDialogLayout->FindPaneByName("T_Letter"))->AllocStringBuffer(0x840); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Dialog_FadeIn.brlan", "G_Fede", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Dialog_FadeOut.brlan", "G_Fede", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Back_RollOver.brlan", "G_Back_Focus", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Back_Rollout.brlan", "G_Back_Focus", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Back_On.brlan", "G_Back_Ac", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Move_RollOver.brlan", "G_Move_Focus", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Move_Rollout.brlan", "G_Move_Focus", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Move_On.brlan", "G_Move_Ac", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_FocusOn.brlan", "G_ArwL_Focus", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_FocusOff.brlan", "G_ArwL_Focus", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Select.brlan", "G_ArwL_Ac", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_FocusOn.brlan", "G_ArwR_Focus", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_FocusOff.brlan", "G_ArwR_Focus", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Select.brlan", "G_ArwR_Ac", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Appear.brlan", "G_ArwL_End", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Lost.brlan", "G_ArwL_End", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Appear.brlan", "G_ArwR_End", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Lost.brlan", "G_ArwR_End", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_Loop.brlan", "G_ArwRoop", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_HDActionStart.brlan", "G_ArwL_HDAc", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_HDActionEnd.brlan", "G_ArwL_HDAc", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_HDActionStart.brlan", "G_ArwR_HDAc", false, true); + mpDialogLayout->bindToGroup("mn_DialogWindow_ChChange_c_HDActionEnd.brlan", "G_ArwR_HDAc", false, true); + mpDialogLayout->finishBinding(); + mpDialogLayout->getAnim(0)->initAnmFrame(); + mpDialogLayout->getAnim(2)->initAnmFrame(); + mpDialogLayout->getAnim(5)->initAnmFrame(); + mpDialogLayout->getAnim(11)->initAnmFrame(); + mpDialogLayout->getAnim(8)->initAnmFrame(); + mpDialogLayout->getAnim(18)->initAnmFrame(); + mpDialogLayout->getAnim(18)->initFrame(); + mpDialogLayout->getAnim(18)->restart(); + + textBox = nw4r::ut::DynamicCast(mpDialogLayout->FindPaneByName("T_CalExit")); + textBox->SetString(System::getMessage(0xA5)); + textBox = nw4r::ut::DynamicCast(mpDialogLayout->FindPaneByName("T_CalExit_00")); + textBox->SetString(System::getMessage(0xC4)); + + mpProgressLayout = new (heap) layout::Object(heap, layoutFile, "arc", "mn_DialogWindow_Background.brlyt"); + mpProgressLayout->bindToGroup("mn_DialogWindow_Background_DialogIn.brlan", "G_InOut", false, true); + mpProgressLayout->bindToGroup("mn_DialogWindow_Background_DialogOut.brlan", "G_InOut", false, true); + mpProgressLayout->finishBinding(); + mpProgressLayout->getAnim(0)->initAnmFrame(); + + } + + void SDMemory::setTitleLists(const TitleRange& nandTitles, const TitleRange& sdTitles) { + mNandTitleRange = nandTitles; + mSDTitleRange = sdTitles; + mTransferFlags[0] = 1; + mDialogState = 0; + mpMainLayout->getAnim(0)->initAnmFrame(); + mpMainLayout->getAnim(0)->play(); + mpProgressLayout->getAnim(0)->initAnmFrame(); + mpProgressLayout->getAnim(0)->play(); + snd::getSystem()->startSE("WIPL_SE_INFO_WINDOW"); + mTransferFlags[1] = 1; + mErrorCode = 0; + } + + void SDMemory::setScrollLimit() { + nw4r::lyt::Pane* headerPane = mpDialogLayout->FindPaneByName("N_Header"); + nw4r::lyt::Pane* buttonPane = mpDialogLayout->FindPaneByName("T_BtnA"); + nw4r::lyt::Pane* footerPane = mpDialogLayout->FindPaneByName("N_Footer"); + + nw4r::ut::Rect projection; + System::getProjectionRect(&projection); + + f32 itemCount = static_cast(mButtonState); + f32 buttonHeight = buttonPane->GetSize().height; + f32 headerHeight = headerPane->GetSize().height; + f32 footerHeight = footerPane->GetSize().height; + f32 contentHeight = headerHeight + footerHeight; + f32 itemHeight = itemCount * buttonHeight; + f32 contentHeightWithItems = itemHeight + contentHeight; + f32 downLimit = contentHeightWithItems - projection.GetHeight() + 1.0f; + if (downLimit < 0.0f) { + downLimit = 0.0f; + } + + mScroller.init(); + mScroller.setDownLimit(downLimit); + } + + void SDMemory::updateSideArrows() { + controller::Interface* masterController = System::getMasterController(); + + if (mScroller.getBInst().isActive() ? false : true) { + if (masterController->down(controller::BTN_UP)) { + showLeftArrow(); + } + if (!masterController->down(controller::BTN_UP)) { + hideLeftArrow(); + } + if (masterController->down(controller::BTN_DOWN)) { + showRightArrow(); + } + if (!masterController->down(controller::BTN_DOWN)) { + hideRightArrow(); + } + } else { + if (mScroller.getBInst().isUp()) { + showLeftArrow(); + } + if (!mScroller.getBInst().isUp()) { + hideLeftArrow(); + } + if (mScroller.getBInst().isDown()) { + showRightArrow(); + } + if (!mScroller.getBInst().isDown()) { + hideRightArrow(); + } + } + } + + void SDMemory::resetScrollArrows() { + mControllerFlags[0] = 0; + mControllerFlags[1] = 0; + mControllerFlags[2] = 0; + mControllerFlags[3] = 0; + mpDialogLayout->getAnim(16)->initAnmFrame(); + mpDialogLayout->getAnim(14)->initAnmFrame(); + if (!mScroller.isDownEnd()) { + showUpArrow(); + } + } + + void SDMemory::updateScrollArrows(u32 previousDownEnd, u32 previousUpEnd, u32 downEnd, u32 upEnd) { + if (previousDownEnd != 1 && downEnd == 1) { + hideDownArrow(); + } + if (previousDownEnd == 1 && downEnd != 1) { + showDownArrow(); + } + if (previousUpEnd != 1 && upEnd == 1) { + hideUpArrow(); + } + if (previousUpEnd == 1 && upEnd != 1) { + showUpArrow(); + } + } + + void SDMemory::showDownArrow() { + if (mControllerFlags[0] == 0) { + layout::Animator* initAnimation = mpDialogLayout->getAnim(16); + initAnimation->initAnmFrame(); + layout::Animator* playAnimation = mpDialogLayout->getAnim(16); + playAnimation->initFrame(); + playAnimation->restart(); + mControllerFlags[0] = 1; + } + } + + void SDMemory::showUpArrow() { + if (mControllerFlags[1] == 0) { + layout::Animator* initAnimation = mpDialogLayout->getAnim(14); + initAnimation->initAnmFrame(); + layout::Animator* playAnimation = mpDialogLayout->getAnim(14); + playAnimation->initFrame(); + playAnimation->restart(); + mControllerFlags[1] = 1; + } + } + + void SDMemory::hideDownArrow() { + if (mControllerFlags[0] != 0) { + layout::Animator* initAnimation = mpDialogLayout->getAnim(17); + initAnimation->initAnmFrame(); + layout::Animator* playAnimation = mpDialogLayout->getAnim(17); + playAnimation->initFrame(); + playAnimation->restart(); + mControllerFlags[0] = 0; + } + } + + void SDMemory::hideUpArrow() { + if (mControllerFlags[1] != 0) { + layout::Animator* initAnimation = mpDialogLayout->getAnim(15); + initAnimation->initAnmFrame(); + layout::Animator* playAnimation = mpDialogLayout->getAnim(15); + playAnimation->initFrame(); + playAnimation->restart(); + mControllerFlags[1] = 0; + } + } + + void SDMemory::showLeftArrow() { + if (mControllerFlags[2] == 0) { + layout::Animator* animation = mpDialogLayout->getAnim(19); + animation->initFrame(); + animation->restart(); + mControllerFlags[2] = 1; + } + } + + void SDMemory::showRightArrow() { + if (mControllerFlags[3] == 0) { + layout::Animator* animation = mpDialogLayout->getAnim(21); + animation->initFrame(); + animation->restart(); + mControllerFlags[3] = 1; + } + } + + void SDMemory::hideLeftArrow() { + if (mControllerFlags[2] != 0) { + layout::Animator* animation = mpDialogLayout->getAnim(20); + animation->initFrame(); + animation->restart(); + mControllerFlags[2] = 0; + } + } + + void SDMemory::hideRightArrow() { + if (mControllerFlags[3] != 0) { + layout::Animator* animation = mpDialogLayout->getAnim(22); + animation->initFrame(); + animation->restart(); + mControllerFlags[3] = 0; + } + } + + void SDMemory::resetDialogPaneAnimations() { + for (int i = 0; i < 4; i++) { + if (mPanelAnimationStates[i] != 0) { + mPanelAnimationStates[i] = 0; + nw4r::lyt::Pane* pane = mpDialogLayout->FindPaneByName(sDialogPaneNames[i]); + mpPaneManagers[2]->initPane(pane); + + layout::Animator* animation = NULL; + switch (i) { + case 2: + animation = mpDialogLayout->getAnim(3); + break; + case 3: + animation = mpDialogLayout->getAnim(6); + break; + case 0: + animation = mpDialogLayout->getAnim(12); + break; + case 1: + animation = mpDialogLayout->getAnim(9); + break; + } + + if (animation != NULL) { + animation->initAnmFrame(); + animation->initFrame(); + animation->restart(); + } + } + } + } + + bool SDMemory::calc() { + bool result = false; + s32 stateResult = updateState(); + if (stateResult == 0) { + if (mScroller.calc(mDialogState == 10) == TRUE) { + resetDialogPaneAnimations(); + } + + nw4r::math::VEC3 translation(0.0f, mScroller.get(), 0.0f); + mpDialogLayout->FindPaneByName("N_Memo")->SetTranslate(translation); + + switch (mDialogState) { + case 0: + onDialogState0(); + break; + case 1: + mpPaneManagers[0]->update(); + mpPaneManagers[0]->calc(); + break; + case 2: + onDialogState2(); + break; + case 3: + result = onDialogState3(); + break; + case 4: + onDialogState4(); + break; + case 5: + mpPaneManagers[1]->update(); + mpPaneManagers[1]->calc(); + break; + case 6: + onDialogState6(); + break; + case 7: + onDialogState7(); + break; + case 8: + onDialogState8(); + break; + case 9: + onDialogState9(); + break; + case 10: + onDialogState10(); + break; + case 11: + onDialogState11(); + break; + case 12: + onDialogState12(); + break; + case 13: + onDialogState13(); + break; + case 14: + onDialogState14(); + break; + case 15: + onDialogState15(); + break; + case 16: + onDialogState16(); + break; + case 17: + onDialogState17(); + break; + case 18: + onDialogState18(); + break; + case 19: + onDialogState19(); + break; + case 20: + result = onDialogState20(); + break; + case 21: + onDialogState21(); + break; + case 22: + result = onDialogState22(); + break; + case 23: + onDialogState23(); + break; + case 24: + result = onDialogState24(); + break; + case 25: + result = true; + break; + } + } + + mpMainLayout->calc(); + mpTitleLayout->calc(); + mpDialogLayout->calc(); + mpProgressLayout->calc(); + + return stateResult == 2 ? true : result; + } + + void SDMemory::onDialogState0() { + if (!mpMainLayout->isPlaying(-1)) { + for (int i = 0; i < 3; i++) { + mPanelStates[i] = 0; + mpPaneManagers[0]->initPane(mpMainLayout->getNW4RLyt()->GetRootPane()->FindPaneByName(sControlPaneNames[i], true)); + } + + mDialogState = 1; + } + } + + void SDMemory::onDialogState2() { + if (!mpMainLayout->isPlaying(-1)) { + mpMainLayout->getAnim(1)->initAnmFrame(); + mpMainLayout->getAnim(1)->play(); + + if (mProcessState == 2) { + mpProgressLayout->getAnim(1)->initAnmFrame(); + mpProgressLayout->getAnim(1)->play(); + mTransferFlags[1] = 0; + } + + mDialogState = 3; + } + } + + void SDMemory::onDialogState4() { + if (!mpTitleLayout->isPlaying(-1)) { + if (mDisplayMode == 4) { + for (int i = 0; i < 5; i++) { + mTitlePanelStates[i] = 0; + mpPaneManagers[1]->initPane(mpTitleLayout->FindPaneByName(sControlPaneNames[i + 3])); + } + } else { + for (int i = 1; i < 5; i++) { + mTitlePanelStates[i] = 0; + mpPaneManagers[1]->initPane(mpTitleLayout->FindPaneByName(sControlPaneNames[i + 7])); + } + } + + mDialogState = 5; + } + } + + void SDMemory::onDialogState6() { + if (!mpTitleLayout->isPlaying(-1)) { + mDialogState = 7; + mpTitleLayout->getAnim(1)->initAnmFrame(); + mpTitleLayout->getAnim(1)->play(); + } + } + + void SDMemory::onDialogState7() { + if (!mpTitleLayout->isPlaying(-1)) { + switch (mProcessState) { + case 4: + mDialogState = 0; + mpMainLayout->getAnim(0)->play(); + snd::getSystem()->startSE("WIPL_SE_BT_TARGETTING"); + break; + default: + mTransferStartTime = 0; + mTransferFrame = 0; + System::getDialog()->callBtn0NoShade(0xCC, 0, true); + mDialogState = 8; + break; + } + } + } + + void SDMemory::onDialogState9() { + if (!mpDialogLayout->isPlaying(0)) { + for (int i = 0; i < 4; i++) { + mPanelAnimationStates[i] = 0; + mpPaneManagers[2]->initPane(mpDialogLayout->getNW4RLyt()->GetRootPane()->FindPaneByName(sDialogPaneNames[i], true)); + } + + mDialogState = 10; + } + } + + void SDMemory::onDialogState10() { + controller::Interface* masterController = System::getMasterController(); + if (mScroller.isActive()) { + updateSideArrows(); + if (mScroller.getBInst().isActive() ? false : true) { + if (masterController->down(controller::BTN_UP)) { + mScroller.scrollUpByCon(); + } else if (masterController->down(controller::BTN_DOWN)) { + mScroller.scrollDownByCon(); + } + } + } + + bool previousDownEnd = !!mControllerFlags[0]; + bool previousUpEnd = !!mControllerFlags[1]; + updateScrollArrows(previousDownEnd, previousUpEnd, mScroller.isUpEnd(), mScroller.isDownEnd()); + + if (mScroller.getBInst().isActive() ? false : true) { + mpPaneManagers[2]->update(); + } + mpPaneManagers[2]->calc(); + } + + void SDMemory::onDialogState11() { + if (!mpDialogLayout->isPlaying(4) && !mpDialogLayout->isPlaying(7)) { + if (mProcessState < 4 && mProcessState >= 2) { + mDialogState = 12; + mpDialogLayout->getAnim(1)->initAnmFrame(); + mpDialogLayout->getAnim(1)->play(); + + if (mControllerFlags[0] != 0) { + hideDownArrow(); + } + if (mControllerFlags[1] != 0) { + hideUpArrow(); + } + } else { + mDialogState = 10; + } + } + } + + void SDMemory::onDialogState19() { + if (!mpNandSDCardManager->getWorker()->is_working()) { + if (mpNandSDCardManager->getWorker()->get_async_result() == 0) { + mDialogState = 13; + } else { + System::getDialog()->terminate(); + mDialogState = 20; + mErrorCode = 1; + mMessageId = 0xAE; + } + } + } + + bool SDMemory::onDialogState20() { + DialogWindow* dialog = System::getDialog(); + if (dialog->getStateForSDMemory() == 4 && mTransferFlags[1] && mErrorCode == 0) { + mTransferFlags[1] = 0; + mpProgressLayout->getAnim(1)->initAnmFrame(); + mpProgressLayout->getAnim(1)->play(); + } + + if (System::getDialog()->getLastResult() != -1) { + if (mErrorCode == 0) { + mTransferFlags[0] = 1; + mDialogState = 25; + return true; + } + + mDialogState = 23; + } + + return false; + } + + bool SDMemory::onDialogState22() { + DialogWindow* dialog = System::getDialog(); + if (dialog->getStateForSDMemory() == 3 && dialog->getResultForSDMemory() == 1) { + mpProgressLayout->getAnim(1)->initAnmFrame(); + mpProgressLayout->getAnim(1)->play(); + mTransferFlags[1] = 0; + } + + if (System::getDialog()->getLastResult() != -1) { + if (System::getDialog()->getLastResult() == 1) { + mErrorCode = 4; + mDialogState = 25; + return true; + } + + mpMainLayout->getAnim(0)->initAnmFrame(); + mpMainLayout->getAnim(0)->play(); + snd::getSystem()->startSE("WIPL_SE_CANCEL"); + mDialogState = 0; + } + + return false; + } + + void SDMemory::onDialogState23() { + switch (mMessageId) { + case 0xBF: + case 0xB5: + System::getDialog()->callBtn1NoShade(mMessageId, 0xA5); + break; + default: + System::getDialog()->callBtn1NoShade(mMessageId, 0x2E); + break; + } + + mDialogState = 24; + } + + bool SDMemory::onDialogState24() { + if (System::getDialog()->getStateForSDMemory() == 3) { + mpProgressLayout->getAnim(1)->initAnmFrame(); + mpProgressLayout->getAnim(1)->play(); + mTransferFlags[1] = 0; + } + + if (System::getDialog()->getLastResult() != -1) { + mTransferFlags[0] = 1; + System::getHomeButtonMenu()->enable(); + mDialogState = 25; + return true; + } + + return false; + } + } +} -- 2.49.1 From c819231092915e6ed4d821b8b387b6daa7bcc944 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 04:01:48 +0000 Subject: [PATCH 28/61] type setting helper allocations --- include/scene/setting/iplAPScanThread.h | 6 +- src/scene/setting/iplSetting.cpp | 96 +++++++++++++------------ 2 files changed, 57 insertions(+), 45 deletions(-) diff --git a/include/scene/setting/iplAPScanThread.h b/include/scene/setting/iplAPScanThread.h index 2b8f5aa5..5a3f93c7 100644 --- a/include/scene/setting/iplAPScanThread.h +++ b/include/scene/setting/iplAPScanThread.h @@ -17,7 +17,11 @@ namespace ipl { virtual ~APScanThread(); // 0x08 virtual void* Run(); // 0x0C - virtual void unk_0x2C() = 0; // 0x2C +#ifdef IPL_SETTING_IMPLEMENTATION + virtual void unk_0x2C(); +#else + virtual void unk_0x2C() = 0; +#endif void setResultData(unsigned short* buffer); void setParam(); diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index e4424cf1..01192418 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -1,5 +1,6 @@ #define IPL_SETTING_IMPLEMENTATION #include "scene/setting/iplSetting.h" +#include "scene/setting/iplAPScanThread.h" #include "scene/setting/iplNCDSetting.h" #include "scene/setting/iplParental.h" @@ -52,46 +53,54 @@ namespace ipl { namespace ipl { namespace scene { - class APScanThread { - public: - APScanThread(); - void setResultData(unsigned short* buffer); - virtual ~APScanThread(); - virtual void* Run(); - virtual void Create(void* stack, u32 stackSize, int priority, bool startThread); - virtual void Resume(); - virtual void Suspend(); - virtual BOOL WaitForThreadExit(); - virtual bool IsThreadTerminated(); - virtual bool IsThreadSuspended(); - virtual bool SetThreadPriority(int priority); - virtual void unk_0x2C(); - }; - class USBAPThread { public: USBAPThread(); bool is(); - void setData(unsigned short* nickname, u8* result); + void setData(const wchar_t* nickname, u8* result); void Init(unsigned short* profile, u8* result); void cancel(); + + private: + wchar_t mNickname[10]; }; - class AOSSThread { + class AOSSThread : public utility::ut_thread { public: AOSSThread(EGG::Heap* heap); + virtual ~AOSSThread(); + virtual void* Run(); int start(); int finish(NCDAossConfig* config, int* result); void cancel(); + + private: + int mResult; + int mPriority; + void* mpThreadStack; + void* mpHeapArea; + void* mpExpandedHeap; + u8 mStartParameters[0x26c]; }; - class RakuRakuThread { + class RakuRakuThread : public utility::ut_thread { public: RakuRakuThread(EGG::Heap* heap); + virtual ~RakuRakuThread(); + virtual void* Run(); int getState(); int start(); int finish(NCDApConfig* config, int* result); void cancel(); + + private: + int mResult; + int mState; + void* mpMessageQueue; + u32 mFlags; + void* mpHeapArea; + void* mpThreadStack; + int mMessage; }; struct SettingAnimationBinding { @@ -99,6 +108,11 @@ namespace ipl { u16 pane; }; + struct SettingSecAText { + wchar_t firstLine[16]; + wchar_t wrappedLine[17]; + }; + static const SettingAnimationBinding sSettingAnimationBindings[] = { {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 2}, {2, 3}, {3, 2}, {3, 3}, {4, 2}, {4, 3}, {5, 0}, {6, 0}, {7, 8}, {7, 9}, {7, 10}, {7, 11}, {8, 8}, {8, 9}, {8, 10}, {8, 11}, @@ -306,7 +320,7 @@ namespace ipl { System::getErrorHandler()->set(ErrorHandler::DEFAULT, 2, NULL, 0, -1); } if (writtenArchive != NULL) { - writtenArchive->write(); + delete writtenArchive; } mpChangeLayout = new layout::Object(getSceneHeap(), mpSettingLayoutFile, "arc", "SceenChange_b.brlyt"); @@ -317,9 +331,8 @@ namespace ipl { mpMainLayout = new layout::Object(getSceneHeap(), mpSettingLayoutFile, "arc", "my_AP_a.brlyt"); for (int index = 0; index < 58; index++) { const SettingAnimationBinding& binding = sSettingAnimationBindings[index]; - bool isSpecialAnimation = index == 10 || index == 20; mpMainLayout->bindToGroup(sSettingAPAnimations[binding.animation], sSettingAPPaneNames[binding.pane], false, - isSpecialAnimation); + index == 20 || index == 10); } mpMainLayout->finishBinding(); @@ -328,22 +341,14 @@ namespace ipl { mpWaitLayout->finishBinding(); mpWaitLayout->FindPaneByName("N_Wait")->SetVisible(false); - mpBrowserData = static_cast(::operator new(0x20)); - void* apScanThreadMemory = ::operator new(0x380); - mpAPScanThread = apScanThreadMemory != NULL ? new (apScanThreadMemory) APScanThread() : NULL; - void* usbThreadMemory = ::operator new(0x14); - mpUSBAPThread = usbThreadMemory != NULL ? new (usbThreadMemory) USBAPThread() : NULL; + mpBrowserData = new ext_ead::www::ImeData; + mpAPScanThread = new APScanThread(); + mpUSBAPThread = new USBAPThread(); ncd::NCDSetting::init(); parental::Parental::init(); - void* aossThreadMemory = ::operator new(0x5b0); - mpAOSSThread = aossThreadMemory != NULL - ? reinterpret_cast(new (aossThreadMemory) AOSSThread(getSceneHeap())) - : NULL; - void* rakuThreadMemory = ::operator new(0x348); - mpRakuRakuThread = rakuThreadMemory != NULL - ? reinterpret_cast(new (rakuThreadMemory) RakuRakuThread(getSceneHeap())) - : NULL; + mpAOSSThread = new AOSSThread(getSceneHeap()); + mpRakuRakuThread = new RakuRakuThread(getSceneHeap()); www::wiisetting::initWiiSetting(); initWiiSettingData(); @@ -432,7 +437,7 @@ namespace ipl { } else if (mInitialArgument == ARG_UNK_6) { int directPage = 0; for (int index = 0; index < 4; index++) { - if (strstr(reinterpret_cast(mpStringBuffer) + 0x60e, pageNames[index]) != NULL) { + if (strstr(mpStringBuffer->netSettingArg, pageNames[index]) != NULL) { directPage = index; break; } @@ -475,7 +480,7 @@ namespace ipl { } const char* settingArgument = System::getNetSettingArg(); if (settingArgument != NULL) { - memcpy(reinterpret_cast(mpStringBuffer) + 0x60e, settingArgument, 0x80); + memcpy(mpStringBuffer->netSettingArg, settingArgument, 0x80); } } @@ -542,7 +547,7 @@ namespace ipl { return; } - if (unk_0xB9C >= 10 && *(reinterpret_cast(mpStringBuffer) + 0x60e) == 0) { + if (unk_0xB9C >= 10 && mpStringBuffer->netSettingArg[0] == 0) { packet.data.controller.irX = youngController->getDpdProjectionPos().x - projection.left; packet.data.controller.irY = youngController->getDpdProjectionPos().y - projection.top; u32 classicHold = youngController->getClassicHoldFlag(); @@ -2180,9 +2185,10 @@ namespace ipl { } if (containsWideCharacter && wcslen(reinterpret_cast(unk_0x938)) > 0x10) { char secondLine[0x22]; - memcpy(secondLine, reinterpret_cast(text) + 0x20, 0x22); - memcpy(reinterpret_cast(text) + 0x22, secondLine, 0x22); - text[0x10] = L'\n'; + SettingSecAText* lines = reinterpret_cast(text); + memcpy(secondLine, lines->wrappedLine, 0x22); + memcpy(&lines->wrappedLine[1], secondLine, 0x22); + lines->wrappedLine[0] = L'\n'; } } @@ -2197,8 +2203,9 @@ namespace ipl { } if (containsWideCharacter && wcslen(text) > 0x10) { char secondLine[0x22]; - memcpy(secondLine, reinterpret_cast(text) + 0x22, 0x22); - memcpy(reinterpret_cast(text) + 0x20, secondLine, 0x22); + SettingSecAText* lines = reinterpret_cast(text); + memcpy(secondLine, &lines->wrappedLine[1], 0x22); + memcpy(lines->wrappedLine, secondLine, 0x22); } } @@ -3113,7 +3120,8 @@ namespace ipl { resetFuncMsgQ(); } else { OSReport("USB SCGetOwnerNickName:%d\n", result); - static_cast(mpUSBAPThread)->setData(nickname.name, &unk_0x91C[1]); + static_cast(mpUSBAPThread)->setData( + reinterpret_cast(nickname.name), &unk_0x91C[1]); static_cast(mpUSBAPThread)->Init( reinterpret_cast(mpMem1BrowserBuffer), reinterpret_cast(mpMem2BrowserBuffer)); -- 2.49.1 From f0f1462ff40cc65f36fd019cb53ee29683ff468a Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Mon, 28 Sep 2026 23:05:09 -0500 Subject: [PATCH 29/61] match pf dir handle checks (#250) --- libs/RVL_SDK/src/fa/pf_dir.c | 248 +++++++++++++++++++++++++++++++---- 1 file changed, 224 insertions(+), 24 deletions(-) diff --git a/libs/RVL_SDK/src/fa/pf_dir.c b/libs/RVL_SDK/src/fa/pf_dir.c index 734232f2..36003880 100644 --- a/libs/RVL_SDK/src/fa/pf_dir.c +++ b/libs/RVL_SDK/src/fa/pf_dir.c @@ -178,7 +178,7 @@ PFDIR_SDD* PFDIR_GetSDD(PF_VOLUME* volume, PF_DIR_ENT* entry) { pf_s32 remaining = 3; for (i = 0; remaining != 0; i++, free_candidate++, remaining--) { - if ((volume_dirs->sdds[i].stat & 1) == 0) { + if ((volume_dirs->sdds[i].stat & 1) == 0 || (volume_dirs->sdds[i].stat & 2) == 0) { if (first_free_sdd == 0) { first_free_sdd = free_candidate; } @@ -209,18 +209,19 @@ pf_s32 PFDIR_DoFsexecOpenDir(PF_DIR_ENT* entry, PF_ENT_ITER* iter, PFDIR_DIR** o if ((entry->attr & 0x10) == 0) { return 0x14; } - sdd = PFDIR_GetSDD(entry->p_vol, entry); + sdd = PFDIR_GetSDD((PF_VOLUME*)volume_dirs, entry); if (sdd == 0) { return 0x15; } - dir = 0; scan_dir = volume_dirs->udds; for (i = 0; i < 3; i++, scan_dir++) { if ((scan_dir->stat & 1) == 0) { dir = &volume_dirs->udds[i]; - break; + goto directory_available; } } + dir = 0; +directory_available: if (dir == 0) { return 0x16; } @@ -240,8 +241,8 @@ pf_s32 PFDIR_p_opendir(PF_VOLUME* volume, PFDIR_STR* path, PFDIR_DIR** opened_di PF_DIR_ENT entry; PFDIR_SDD* sdd; PFDIR_DIR* dir; - pf_s32 error; pf_s32 i; + pf_s32 error; if ((PFSTR_StrNCmp(path, (const pf_s8*)"\\", 1, 0, 1) == 0 || PFSTR_StrNCmp(path, (const pf_s8*)"/", 1, 0, 1) == 0) && @@ -287,16 +288,15 @@ open_directory: if (sdd == 0) { return 0x15; } - dir = ((PFDIR_VOLUME_DIRS*)volume)->udds; - i = 0; - do { - if ((dir->stat & 1) == 0) { - break; + for (i = 0; i < 3; i++) { + if ((((PFDIR_VOLUME_DIRS*)volume)->udds[i].stat & 1) == 0) { + dir = &((PFDIR_VOLUME_DIRS*)volume)->udds[i]; + goto directory_available; } - i++; - dir++; - } while (i < 3); - if (i == 3) { + } + dir = 0; +directory_available: + if (dir == 0) { return 0x16; } dir->p_sdd = sdd; @@ -356,6 +356,7 @@ pf_s32 PFDIR_p_mkdir(PF_VOLUME* p_vol, PF_STR* p_path, pf_u32 option, PF_DTA* p_ pf_u16 dirname_len; PF_DIR_ENT entry; PF_DIR_ENT parent_entry; + PF_ENT_ITER parent_iter; PF_FFD ffd; pf_u32 pos; PF_FAT_HINT fat_hint; @@ -371,12 +372,13 @@ pf_s32 PFDIR_p_mkdir(PF_VOLUME* p_vol, PF_STR* p_path, pf_u32 option, PF_DTA* p_ if (err != 0) { return err; } - err = VFiPFENT_GetParentEntryOfPath(&parent_entry, p_vol, &full_path); + err = PFENT_ITER_GetEntryOfPath(&parent_iter, &parent_entry, p_vol, + (PFDIR_STR*)&full_path, 1); if (err != 0) { return err; } if ((parent_entry.attr & 0x10) == 0) { - err = 0x14; + return 0x14; } if (p_dta != PF_NULL) { p_dta->parent_start_cluster = parent_entry.start_cluster; @@ -682,8 +684,6 @@ extern pf_s32 PFCACHE_FlushFATCache(PF_VOLUME* volume); extern pf_s32 PFDIR_p_fsfirst(PF_VOLUME* volume, PF_STR* path, pf_u8 attributes, PF_DTA* data); extern pf_s32 PFDIR_p_fsnext(PF_DTA* data); extern pf_s32 PFDIR_p_fsexec(PF_DTA* data, pf_u32 flags, pf_u32 mode); -extern pf_s32 PFDIR_p_rename(PF_VOLUME* volume, PF_STR* old_path, PF_STR* new_path); -extern pf_s32 PFDIR_p_move(PF_VOLUME* volume, PF_STR* old_path, PF_STR* new_path); extern pf_s32 PFDIR_p_fsexec_chmod(PF_DTA* data, PF_DIR_ENT* entry, pf_u32 attributes, pf_u32 mode); extern pf_s32 PFDIR_p_fsexec_remove(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter); extern pf_s32 PFDIR_p_fsexec_fopen(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter, pf_u32 flags, @@ -692,9 +692,12 @@ extern pf_s32 PFDIR_p_fsexec_opendir(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITE extern void PFFAT_FinalizeFFD(PF_FFD* ffd); extern pf_s32 PFENT_ITER_GetEntryOfPattern(PF_ENT_ITER* iter, PF_DIR_ENT* entry, PF_VOLUME* volume, PFDIR_STR* directory); +extern pf_s32 PFENT_ITER_FindEntry(PF_ENT_ITER* iter, PF_DIR_ENT* entry, PFDIR_STR* pattern, + pf_u8 attributes, pf_u32 start, pf_u32* found); extern pf_s32 PFENT_findEntry(PFDIR_FFD* ffd, PF_DIR_ENT* entry, pf_u32 start, PFDIR_STR* pattern, pf_u8 attributes, pf_u32* logical_position, pf_u32* entry_position); extern pf_u32 PFSTR_GetCodeMode(PFDIR_STR* path); +extern const pf_s8* PFSTR_GetStrPos(PFDIR_STR* path, pf_u32 target); extern pf_s32 PFPATH_SplitPathPattern(PF_STR* path, PFDIR_STR* directory, PFDIR_STR* pattern); extern void PFPATH_SetSearchPattern(pf_s8* ansi_pattern, pf_u16* unicode_pattern, PFDIR_STR* pattern); extern pf_u16* pf_w_strcpy(pf_u16* destination, const pf_u16* source); @@ -706,6 +709,201 @@ extern pf_s32 PFFILE_FsexecOpenFile(PF_DIR_ENT* entry, PF_ENT_ITER* iter, pf_u32 extern pf_s32 PFPATH_cmpName(const pf_s8* short_name, PFDIR_STR* pattern, pf_u32 short_search); extern pf_s32 PFPATH_cmpNameUni(const pf_u16* name, PFDIR_STR* pattern); +pf_s32 PFDIR_p_rename(PF_VOLUME* volume, PF_STR* old_path, PF_STR* new_path) { + PF_ENT_ITER source_iter; + PF_ENT_ITER destination_iter; + PF_DIR_ENT source_entry; + PF_DIR_ENT source_parent; + PF_DIR_ENT destination_parent; + PF_DIR_ENT existing_entry; + PFDIR_STR source_directory; + PFDIR_STR source_name; + PFDIR_STR destination_directory; + PFDIR_STR destination_name; + pf_s8 normalized_name[512]; + const pf_s8* name; + pf_u32 entry_position; + pf_s32 error; + + error = PFPATH_SplitPath((PFDIR_STR*)old_path, &source_directory, &source_name); + if (error != 0) { + return error; + } + if (PFSTR_GetCodeMode(&source_name) == 2) { + if (PFSTR_StrNumChar(&source_name, 1) > 0xFF) { + return 1; + } + error = PFPATH_transformFromUnicodeToNormal( + normalized_name, (const pf_u16*)PFSTR_GetStrPos(&source_name, 1)); + if (error != 0) { + return error; + } + PFSTR_SetLocalStr(&source_name, (pf_u32)normalized_name); + } + error = PFENT_ITER_GetEntryOfPath(&source_iter, &source_parent, volume, + &source_directory, 1); + if (error != 0) { + return error; + } + PFFAT_InitFFD(&source_iter.ffd, 0, volume, &source_parent.start_cluster); + error = PFENT_ITER_IteratorInitialize(&source_iter, 0); + if (error != 0) { + return error; + } + error = PFENT_ITER_FindEntry(&source_iter, &source_entry, &source_name, 0x7F, 0, + &entry_position); + if (error != 0) { + return error; + } + if (entry_position == 0) { + return 3; + } + if ((source_entry.attr & 0x10) != 0) { + return 3; + } + if ((source_entry.attr & 1) != 0) { + return 0x18; + } + if (PFSTR_StrNCmp((PFDIR_STR*)new_path, (const pf_s8*)":", 1, 1, 1) == 0 && + PFPATH_GetVolumeFromPath(new_path) != volume) { + return 0x1F; + } + error = PFPATH_SplitPath((PFDIR_STR*)new_path, &destination_directory, + &destination_name); + if (error != 0) { + return error; + } + error = PFENT_ITER_GetEntryOfPath(&destination_iter, &destination_parent, volume, + &destination_directory, 1); + if (error != 0) { + return error; + } + if ((destination_parent.attr & 0x10) == 0) { + return 0x14; + } + if (source_iter.ffd.start_cluster != destination_parent.start_cluster) { + return 0x1F; + } + if (PFSTR_GetCodeMode(&destination_name) == 2) { + if (PFSTR_StrNumChar(&destination_name, 1) > 0xFF) { + return 1; + } + error = PFPATH_transformFromUnicodeToNormal( + normalized_name, (const pf_u16*)PFSTR_GetStrPos(&destination_name, 1)); + if (error != 0) { + return error; + } + PFSTR_SetLocalStr(&destination_name, (pf_u32)normalized_name); + } + name = PFSTR_GetStrPos(&destination_name, 1); + error = PFENT_ITER_FindEntry(&destination_iter, &existing_entry, &destination_name, + 0x7F, 0, &entry_position); + if (error == 0) { + return 8; + } + if (error != 3) { + return error; + } + error = PFPATH_parseShortName(&source_entry, name); + if (error != 0) { + return error; + } + source_entry.long_name[0] = 0; + return PFENT_updateEntry(&source_entry, 1); +} + +pf_s32 PFDIR_p_move(PF_VOLUME* volume, PF_STR* old_path, PF_STR* new_path) { + PF_ENT_ITER source_iter; + PF_ENT_ITER destination_iter; + PF_DIR_ENT source_entry; + PF_DIR_ENT destination_entry; + PF_DIR_ENT existing_entry; + PFDIR_STR destination_directory; + PFDIR_STR destination_name; + PFDIR_VOLUME_DIRS* volume_dirs; + pf_s8 normalized_name[512]; + pf_u32 entry_position; + pf_u32 index; + pf_s32 error; + + error = PFENT_ITER_GetEntryOfPath(&source_iter, &source_entry, volume, + (PFDIR_STR*)old_path, 0); + if (error != 0) { + return error; + } + if (PFPATH_GetVolumeFromPath(new_path) != volume) { + return 0x1F; + } + error = PFPATH_SplitPath((PFDIR_STR*)new_path, &destination_directory, + &destination_name); + if (error != 0) { + return error; + } + if (PFSTR_GetCodeMode(&destination_name) == 2) { + if (PFSTR_StrNumChar(&destination_name, 1) > 0xFF) { + return 1; + } + error = PFPATH_transformFromUnicodeToNormal( + normalized_name, (const pf_u16*)PFSTR_GetStrPos(&destination_name, 1)); + if (error != 0) { + return error; + } + PFSTR_SetLocalStr(&destination_name, (pf_u32)normalized_name); + } + error = PFENT_ITER_GetEntryOfPath(&destination_iter, &destination_entry, volume, + &destination_directory, 1); + if (error != 0) { + return error; + } + if ((destination_entry.attr & 0x10) == 0) { + return 0x14; + } + if ((source_entry.attr & 1) != 0) { + return 0x18; + } + volume_dirs = (PFDIR_VOLUME_DIRS*)volume; + if ((source_entry.attr & 0x10) != 0) { + if (PFVOL_CheckCurrentDir(volume, source_entry.start_cluster) != 0 || + source_entry.start_cluster == 1 || + (volume->bpb.fat_type == FAT_32 && + source_entry.start_cluster == volume->bpb.root_dir_cluster)) { + return 0x1C; + } + for (index = 0; index < 3; index++) { + PFDIR_SDD* sdd = &volume_dirs->sdds[index]; + if ((sdd->stat & 1) != 0 && (sdd->stat & 2) != 0 && + sdd->dir_entry.p_vol == source_entry.p_vol && + sdd->dir_entry.entry_sector == source_entry.entry_sector && + sdd->dir_entry.entry_offset == source_entry.entry_offset) { + return 0x13; + } + } + } else if (PFFILE_IsOpened(&source_entry) != 0) { + return 0x13; + } + PFFAT_InitFFD(&destination_iter.ffd, 0, volume, &destination_entry.start_cluster); + error = PFENT_ITER_IteratorInitialize(&destination_iter, 0); + if (error != 0) { + return error; + } + error = PFENT_ITER_FindEntry(&destination_iter, &existing_entry, &destination_name, + 0x7F, 0, &entry_position); + if (error == 0) { + if (source_entry.entry_sector == existing_entry.entry_sector && + source_entry.entry_offset == existing_entry.entry_offset) { + return 0; + } + return 8; + } + if (error != 3) { + return error; + } + if (source_iter.ffd.start_cluster != destination_entry.start_cluster) { + return 0x1F; + } + return PFDIR_p_rename(volume, old_path, new_path); +} + pf_s32 PFDIR_p_fsexec_remove(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter) { PFDIR_VOLUME_DIRS* volume_dirs = (PFDIR_VOLUME_DIRS*)entry->p_vol; PFDIR_FAT_HINT hint; @@ -1118,7 +1316,7 @@ void PFDIR_opendir(PF_STR* path, PFDIR_DIR** dir) { pf_vol_set.last_error = error; ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; } else { - volume_dirs->num_opened_directories++; + ((PFDIR_VOLUME_DIRS*)volume)->num_opened_directories++; } } @@ -1180,11 +1378,13 @@ pf_s32 PFDIR_telldir(PFDIR_DIR* dir, pf_u32* position) { } else { sdd = dir->p_sdd; if ((sdd->stat & 1) == 0 || (sdd->stat & 2) == 0) { + pf_vol_set.last_error = 10; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = 10; error = 10; - pf_vol_set.last_error = error; - ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; + } else if (dir->end_position != 0) { + *position = dir->end_position; } else { - *position = dir->end_position != 0 ? dir->end_position : dir->next_position; + *position = dir->next_position; } } return error; @@ -1198,9 +1398,9 @@ pf_s32 PFDIR_seekdir(PFDIR_DIR* dir, pf_u32 position) { pf_vol_set.last_error = error; ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; } else if ((dir->p_sdd->stat & 1) == 0 || (dir->p_sdd->stat & 2) == 0) { + pf_vol_set.last_error = 10; + ((PFDIR_VOLUME_DIRS*)volume)->last_error = 10; error = 10; - pf_vol_set.last_error = error; - ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; } else { dir->end_position = position; } -- 2.49.1 From 67ed1533869eceac82c73dab28b3d1f8a878ddcf Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 04:09:27 +0000 Subject: [PATCH 30/61] localize browser setting tables --- src/scene/setting/iplSetting.cpp | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 01192418..834c68b5 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -383,16 +383,6 @@ namespace ipl { } void Setting::createBrowser() { - static const char* urlFormats[] = {"marc:%s/%s/", "file:dvd/html/IPLSetting/%s/%s/"}; - static const char* pagePaths[] = { - "index01.html", "Internet/Internet_index.html", "Setup/startup_index1.html", - "Update/Update_index.html", "index02.html", "Setup/ScreenSave.html", - "Country/US_Country_flame.html", - }; - static const char* pageNames[] = {"Calendar", "Parental_Control", "Internet", "Wiiconnect24"}; - static const char* regionCodes[] = {"JP/JP", "FIX/US", "EU/EU", "TW/TW", "KR/KR", "CN/CN"}; - static const char* languageCodes[] = {"JPN", "ENG", "GER", "FRA", "SPA", "ITA", "DUT", "CHN", "KOR"}; - EGG::Heap* mem1Heap = System::createMem1AppHeap(); u32 mem1Size = mem1Heap->getAllocatableSize(4); EGG::Heap* mem2Heap = System::getMem2App(); @@ -408,6 +398,16 @@ namespace ipl { int width = projection16x9.right - projection16x9.left; int height = projection16x9.bottom - projection16x9.top; + const char* urlFormats[] = {"marc:%s/%s/", "file:dvd/html/IPLSetting/%s/%s/"}; + const char* pagePaths[] = { + "index01.html", "Internet/Internet_index.html", "Setup/startup_index1.html", + "Update/Update_index.html", "index02.html", "Setup/ScreenSave.html", + "Country/US_Country_flame.html", + }; + const char* pageNames[] = {"Calendar", "Parental_Control", "Internet", "Wiiconnect24"}; + const char* regionCodes[] = {"JP/JP", "FIX/US", "EU/EU", "TW/TW", "KR/KR", "CN/CN"}; + const char* languageCodes[] = {"JPN", "ENG", "GER", "FRA", "SPA", "ITA", "DUT", "CHN", "KOR"}; + char basePath[100]; char browserPath[100]; memset(basePath, 0, sizeof(basePath)); -- 2.49.1 From 65dbdfa404d794200e97d1d25a032e2f0b8469b7 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 04:12:41 +0000 Subject: [PATCH 31/61] match setting controller flow --- src/scene/setting/iplSetting.cpp | 45 ++++++++++++++++---------------- 1 file changed, 22 insertions(+), 23 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 834c68b5..72ad68cc 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -536,36 +536,35 @@ namespace ipl { controller::Interface* youngController = System::getYoungController(); ext_ead::www::BrowserThread::CmdPacket packet; - if (youngController == NULL) { - packet.type = 0; - packet.data.controller.irX = -1000.0f; - packet.data.controller.irY = -1000.0f; - packet.data.controller.btnHold = 0; - packet.data.controller.btnTrigger = 0; - packet.data.controller.btnRelease = 0; - ext_ead::www::SurfaceManager::GetInstance()->GetBrowserThread()->SendUIEvent(&packet); - return; - } + if (youngController != NULL) { + if (unk_0xB9C < 10 || mpStringBuffer->netSettingArg[0] != 0) { + packet.data.controller.irX = -1000.0f; + packet.data.controller.irY = -1000.0f; + packet.data.controller.btnHold = 0; + packet.data.controller.btnTrigger = 0; + packet.data.controller.btnRelease = 0; + } else { + packet.data.controller.irX = youngController->getDpdProjectionPos().x - projection.left; + packet.data.controller.irY = youngController->getDpdProjectionPos().y - projection.top; + u32 classicHold = youngController->getClassicHoldFlag(); + u32 classicTrigger = youngController->getClassicTrigFlag(); + u32 classicRelease = youngController->getClassicReleaseFlag(); + packet.data.controller.btnHold = (classicHold << 16) | youngController->getHoldFlag(); + packet.data.controller.btnTrigger = (classicTrigger << 16) | youngController->getTrigFlag(); + packet.data.controller.btnRelease = (classicRelease << 16) | youngController->getReleaseFlag(); + } - if (unk_0xB9C >= 10 && mpStringBuffer->netSettingArg[0] == 0) { - packet.data.controller.irX = youngController->getDpdProjectionPos().x - projection.left; - packet.data.controller.irY = youngController->getDpdProjectionPos().y - projection.top; - u32 classicHold = youngController->getClassicHoldFlag(); - u32 classicTrigger = youngController->getClassicTrigFlag(); - u32 classicRelease = youngController->getClassicReleaseFlag(); - packet.data.controller.btnHold = (classicHold << 16) | youngController->getHoldFlag(); - packet.data.controller.btnTrigger = (classicTrigger << 16) | youngController->getTrigFlag(); - packet.data.controller.btnRelease = (classicRelease << 16) | youngController->getReleaseFlag(); + packet.type = 0; + if (mKeyboardState.type == textinput::MemoManager::ST_Hidden && unk_0x74 == 0) { + ext_ead::www::SurfaceManager::GetInstance()->GetBrowserThread()->SendUIEvent(&packet); + } } else { packet.data.controller.irX = -1000.0f; packet.data.controller.irY = -1000.0f; packet.data.controller.btnHold = 0; packet.data.controller.btnTrigger = 0; packet.data.controller.btnRelease = 0; - } - - packet.type = 0; - if (mKeyboardState.type == textinput::MemoManager::ST_Hidden && unk_0x74 == 0) { + packet.type = 0; ext_ead::www::SurfaceManager::GetInstance()->GetBrowserThread()->SendUIEvent(&packet); } } -- 2.49.1 From 490fa0ea76cf5a8c853bf3c59787c10c3b80e18f Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 04:13:45 +0000 Subject: [PATCH 32/61] match setting exit condition --- src/scene/setting/iplSetting.cpp | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 72ad68cc..09458073 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -608,13 +608,10 @@ namespace ipl { bool Setting::isInitialSequenceExit(const controller::Interface* input) { u32 connectedMask = utility::wpad::getWpadConnectedMask(); - if (input->downTrg(0x100800)) { - return true; - } - - OSTime elapsed = OSGetTime() - mCreatePageTime; - if (elapsed / (OS_TIMER_CLOCK / 1000) >= 500 && connectedMask != unk_0xBA8 && - utility::wpad::isIncreaseConnectedWpad(unk_0xBA8, connectedMask)) { + if (input->downTrg(0x100800) || + ((OSGetTime() - mCreatePageTime) / (OS_TIMER_CLOCK / 1000) >= 500 && + connectedMask != unk_0xBA8 && + utility::wpad::isIncreaseConnectedWpad(unk_0xBA8, connectedMask))) { return true; } -- 2.49.1 From 76f56d4270d64f8a71c90eb71d9d3e82b2031313 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 04:17:37 +0000 Subject: [PATCH 33/61] improve setting screen mode flow --- src/scene/setting/iplSetting.cpp | 34 ++++++++++++++++---------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 09458073..689f5156 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -647,30 +647,30 @@ namespace ipl { } if (unk_0xB94 == 1) { - if (System::getFader()->getStatus() != EGG::Fader::PREPARE_IN) { + if (System::getFader()->getStatus() == EGG::Fader::PREPARE_IN) { + System::getDialog()->terminate(); + SCSetAspectRatio(mAspectRatio & 0xff); + SCFlush(); + if (System::getDialog()->getLastResult() < 0) { + mState = 0; + return true; + } + + changeVideoMode(); + www::wiisetting::setStringBuf(mpStringBuffer); + System::getFader()->fadeIn(); + } else { mState = 0; return true; } - - System::getDialog()->terminate(); - SCSetAspectRatio(mAspectRatio & 0xff); - SCFlush(); - if (System::getDialog()->getLastResult() < 0) { - mState = 0; - return true; - } - - changeVideoMode(); - www::wiisetting::setStringBuf(mpStringBuffer); - System::getFader()->fadeIn(); } else if (unk_0xB94 > 0 && unk_0xB94 < 4) { - if (System::getFader()->getStatus() != EGG::Fader::PREPARE_IN) { + if (System::getFader()->getStatus() == EGG::Fader::PREPARE_IN) { + changeVideoMode(); + System::getFader()->fadeIn(); + } else { mState = 0; return true; } - - changeVideoMode(); - System::getFader()->fadeIn(); } return false; -- 2.49.1 From 35724c1cf084330e5defe54cfcbfac8d19487e9d Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 04:30:59 +0000 Subject: [PATCH 34/61] match setting normal state cases --- src/scene/setting/iplSetting.cpp | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 689f5156..1355e9b4 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -756,10 +756,16 @@ namespace ipl { } break; case 3: - if (System::getDialog()->getLastResult() == 1 || - System::getDialog()->getLastResult() == 2) { + if (System::getDialog()->getLastResult() == 1) { if (unk_0xB9C == 0) { - www::wiisetting::setFuncResult(System::getDialog()->getLastResult()); + www::wiisetting::setFuncResult(1); + } else if (www::wiisetting::getFuncResult() == 0) { + unk_0x74 = 0; + } + unk_0xB9C = 1; + } else if (System::getDialog()->getLastResult() == 2) { + if (unk_0xB9C == 0) { + www::wiisetting::setFuncResult(2); } else if (www::wiisetting::getFuncResult() == 0) { unk_0x74 = 0; } @@ -827,9 +833,7 @@ namespace ipl { SCSetWCFlags(SCGetWCFlags() & 0xfffffffe); SCIdleModeInfo idleMode = {0, 0}; SCSetIdleMode(&idleMode); - if (System::getNwc24Manager() != NULL) { - System::getNwc24Manager()->enableLedNotification(TRUE); - } + System::getNwc24Manager()->enableLedNotification(TRUE); SCSetEULA(0); ncd::NCDSetting::adjustNWC24Flag(); parental::Parental::setCountry(mpWiiSettingData->data[0x3c]); @@ -880,9 +884,7 @@ namespace ipl { SCSetWCFlags(SCGetWCFlags() & 0xfffffffe); SCIdleModeInfo idleMode = {0, 0}; SCSetIdleMode(&idleMode); - if (System::getNwc24Manager() != NULL) { - System::getNwc24Manager()->enableLedNotification(TRUE); - } + System::getNwc24Manager()->enableLedNotification(TRUE); SCSetEULA(0); ncd::NCDSetting::adjustNWC24Flag(); SCFlush(); @@ -904,9 +906,7 @@ namespace ipl { SCSetWCFlags(SCGetWCFlags() & 0xfffffffe); SCIdleModeInfo idleMode = {0, 0}; SCSetIdleMode(&idleMode); - if (System::getNwc24Manager() != NULL) { - System::getNwc24Manager()->enableLedNotification(TRUE); - } + System::getNwc24Manager()->enableLedNotification(TRUE); SCSetEULA(0); ncd::NCDSetting::adjustNWC24Flag(); SCFlush(); -- 2.49.1 From 359e2ce7a46590d7008a5160436c87fb5301be70 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 04:38:45 +0000 Subject: [PATCH 35/61] improve setting keyboard initialization --- src/scene/setting/iplSetting.cpp | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 1355e9b4..545791e2 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -1432,16 +1432,16 @@ namespace ipl { } void Setting::initKeyboard(const char* text) { - u8 formId = mpWiiSettingData->data[0x11]; - OSReport("initKeyboard formId:%d\n", formId); + OSReport("initKeyboard formId:%d\n", mpWiiSettingData->data[0x11]); memset(unk_0x938, 0, sizeof(unk_0x938)); - int productArea = SCGetProductArea(); + int invalidInput = 0; + keyboard::Manager::KeyboardType keyboardType = keyboard::Manager::LETTER; int rowLimit = 0; int stringLimit = 0; - keyboard::Manager::KeyboardType keyboardType = keyboard::Manager::LETTER; + int productArea = SCGetProductArea(); - switch (formId) { + switch (mpWiiSettingData->data[0x11]) { case 1: stringLimit = 10; rowLimit = 6; @@ -1457,7 +1457,15 @@ namespace ipl { rowLimit = 7; break; case 3: + stringLimit = 0x20; + keyboardType = keyboard::Manager::NORMAL_WITHOUT_LINEFEED; + rowLimit = 7; + break; case 12: + stringLimit = 0x20; + keyboardType = keyboard::Manager::NORMAL_WITHOUT_LINEFEED; + rowLimit = 7; + break; case 13: stringLimit = 0x20; keyboardType = keyboard::Manager::NORMAL_WITHOUT_LINEFEED; @@ -1501,7 +1509,9 @@ namespace ipl { break; } - if (formId != 13 && formId != 2 && formId != 18 && formId != 19 && formId != 22) { + if (mpWiiSettingData->data[0x11] != 13 && mpWiiSettingData->data[0x11] != 2 && + mpWiiSettingData->data[0x11] != 18 && mpWiiSettingData->data[0x11] != 19 && + mpWiiSettingData->data[0x11] != 22) { utility::CharacterCode::UTF8ToUTF16(reinterpret_cast(unk_0x938), text, 0x101); } @@ -1509,10 +1519,11 @@ namespace ipl { OSReport("キーボード: %d %d %d %d\n", rowLimit, stringLimit, keyboardType, textLength); reinterpret_cast(unk_0x938)[stringLimit] = 0; - int invalidInput = 0; - if (formId >= 4 && formId <= 8) { + if (mpWiiSettingData->data[0x11] >= 4 && mpWiiSettingData->data[0x11] <= 8) { invalidInput = checkIPString(reinterpret_cast(unk_0x938)); - } else if ((formId > 0 && formId < 4) || (formId >= 10 && formId <= 20) || formId == 22) { + } else if ((mpWiiSettingData->data[0x11] > 0 && mpWiiSettingData->data[0x11] < 4) || + (mpWiiSettingData->data[0x11] >= 10 && mpWiiSettingData->data[0x11] <= 20) || + mpWiiSettingData->data[0x11] == 22) { invalidInput = checkInputString(reinterpret_cast(unk_0x938)); } @@ -1522,7 +1533,7 @@ namespace ipl { keyboard::Manager* keyboardManager = System::getKeyboard(); if (productArea == 11) { - keyboardManager->memoFrm()->setZiDictionary(keyboardManager->getZiSystemDic(), keyboardManager->getZiOemDic()); + keyboardManager->memoFrm()->setZiDictionary(keyboardManager->getZiOemDic(), keyboardManager->getZiSystemDic()); } keyboard::Manager::KeyboardSetting setting; -- 2.49.1 From 6806dc192659d25f720f0154986cd276051be1c7 Mon Sep 17 00:00:00 2001 From: "devin-ai-integration[bot]" <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Tue, 29 Sep 2026 04:39:06 +0000 Subject: [PATCH 36/61] net: link nettime (genuine implementation, objdiff 100%) (#251) Co-authored-by: devin Co-authored-by: wch --- configure.py | 2 +- libs/RevoEX/src/net/nettime.c | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 libs/RevoEX/src/net/nettime.c diff --git a/configure.py b/configure.py index 52f48215..bb86da5b 100644 --- a/configure.py +++ b/configure.py @@ -1041,7 +1041,7 @@ config.libs = [ ] ), RevoEXLib("net", [ - Object(NonMatching, "net/nettime.c"), + Object(Matching, "net/nettime.c"), Object(Matching, "net/crc.c"), Object(NonMatching, "net/md5.c"), Object(NonMatching, "net/sha1.c"), diff --git a/libs/RevoEX/src/net/nettime.c b/libs/RevoEX/src/net/nettime.c new file mode 100644 index 00000000..7c7ef06f --- /dev/null +++ b/libs/RevoEX/src/net/nettime.c @@ -0,0 +1,33 @@ +#include + +#include +#include + +#include +#include + +NWC24Err NWC24iEpochSecondsToDate(NWC24Date* date, OSTime time); +NWC24Err NWC24iDateToOSCalendarTime(OSCalendarTime* cal, const NWC24Date* date); + +BOOL NETGetUniversalCalendar(OSCalendarTime* pTime) { + static s64 whenCached = 0; + NWC24Date date; + s64 universalTime; + + if (whenCached == 0 || + whenCached + OSSecondsToTicks(60) < __OSGetSystemTime()) { + + NWC24iSynchronizeRtcCounter(FALSE); + whenCached = __OSGetSystemTime(); + } + + if (NWC24iGetUniversalTime(&universalTime) >= 0 && + NWC24iEpochSecondsToDate(&date, universalTime) >= 0 && + NWC24iDateToOSCalendarTime(pTime, &date) >= 0) { + + return TRUE; + } + + OSTicksToCalendarTime(OSGetTime(), pTime); + return FALSE; +} -- 2.49.1 From dacd3edf4e4db7a7cffb625bbd0a9fe62931901f Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 04:53:00 +0000 Subject: [PATCH 37/61] match setting text input handling --- src/scene/setting/iplSetting.cpp | 225 ++++++++++++++++++++----------- 1 file changed, 143 insertions(+), 82 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 545791e2..9b510f56 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -1552,80 +1552,76 @@ namespace ipl { } void Setting::calcKeyboard() { - u8 formId = mpWiiSettingData->data[0x11]; - char* formText = NULL; - switch (formId) { - case 1: - formText = mpStringBuffer->nickname; - break; - case 2: - case 22: - formText = mpStringBuffer->asterisks; - break; - case 3: - formText = mpStringBuffer->securityKey; - break; - case 4: - formText = mpStringBuffer->ip.addr; - break; - case 5: - formText = mpStringBuffer->ip.netmask; - break; - case 6: - formText = mpStringBuffer->ip.gateway; - break; - case 7: - formText = mpStringBuffer->dns1; - break; - case 8: - formText = mpStringBuffer->dns2; - break; - case 10: - formText = mpStringBuffer->proxy.server; - break; - case 11: - formText = mpStringBuffer->proxy.port; - break; - case 12: - formText = mpStringBuffer->proxyBasic.uname; - break; - case 13: - formText = mpStringBuffer->proxyBasic.pass; - break; - case 14: - formText = mpStringBuffer->adjMtu; - break; - case 15: - formText = mpStringBuffer->parentalPass; - break; - case 16: - formText = mpStringBuffer->parentalRePass; - break; - case 17: - formText = mpStringBuffer->parentalJudgePass; - break; - case 18: - formText = mpStringBuffer->parentalSecA; - break; - case 19: - formText = mpStringBuffer->parentalReSecA; - break; - case 20: - formText = mpStringBuffer->masterKey; - break; - } - - ext_ead::www::BrowserThread* browser = ext_ead::www::SurfaceManager::GetInstance()->GetBrowserThread(); + char* formText; if (mKeyboardState.iplType == keyboard::Manager::STATE_DISAPPEARING) { - if (!mKeyboardState.pressOK) { - browser->CommitIme(mpBrowserData, formText); - } else { + if (mKeyboardState.pressOK) { onTextInputOK(); - formId = mpWiiSettingData->data[0x11]; + u8 formId = mpWiiSettingData->data[0x11]; + formText = NULL; + switch (formId) { + case 1: + formText = mpStringBuffer->nickname; + break; + case 2: + case 22: + formText = mpStringBuffer->securityKey; + break; + case 3: + formText = mpStringBuffer->securityKey; + break; + case 4: + formText = mpStringBuffer->ip.addr; + break; + case 5: + formText = mpStringBuffer->ip.netmask; + break; + case 6: + formText = mpStringBuffer->ip.gateway; + break; + case 7: + formText = mpStringBuffer->dns1; + break; + case 8: + formText = mpStringBuffer->dns2; + break; + case 10: + formText = mpStringBuffer->proxy.server; + break; + case 11: + formText = mpStringBuffer->proxy.port; + break; + case 12: + formText = mpStringBuffer->proxyBasic.uname; + break; + case 13: + formText = mpStringBuffer->proxyBasic.pass; + break; + case 14: + formText = mpStringBuffer->adjMtu; + break; + case 15: + formText = mpStringBuffer->parentalPass; + break; + case 16: + formText = mpStringBuffer->parentalRePass; + break; + case 17: + formText = mpStringBuffer->parentalJudgePass; + break; + case 18: + formText = mpStringBuffer->parentalSecA; + break; + case 19: + formText = mpStringBuffer->parentalReSecA; + break; + case 20: + formText = mpStringBuffer->masterKey; + break; + } OSReport("formID:%d %s\n", formId, formText); if (strlen(formText) == 0) { formText[0] = 0; - browser->CommitIme(mpBrowserData, formText); + ext_ead::www::SurfaceManager::GetInstance()->GetBrowserThread()->CommitIme(mpBrowserData, formText); memset(mpStringBuffer->asterisks, 0, sizeof(mpStringBuffer->asterisks)); } else if (formId == 2 || formId == 22) { memcpy(mpStringBuffer->asterisks, mpStringBuffer->securityKey, sizeof(mpStringBuffer->securityKey)); @@ -1638,15 +1634,80 @@ namespace ipl { mpStringBuffer->asterisks[0x20] = '\n'; mpStringBuffer->asterisks[index] = '*'; } - browser->CommitIme(mpBrowserData, mpStringBuffer->asterisks); + ext_ead::www::SurfaceManager::GetInstance()->GetBrowserThread()->CommitIme(mpBrowserData, mpStringBuffer->asterisks); } else { - browser->CommitIme(mpBrowserData, formText); + ext_ead::www::SurfaceManager::GetInstance()->GetBrowserThread()->CommitIme(mpBrowserData, formText); } + } else { + u8 formId = mpWiiSettingData->data[0x11]; + formText = NULL; + switch (formId) { + case 1: + formText = mpStringBuffer->nickname; + break; + case 2: + case 22: + formText = mpStringBuffer->asterisks; + break; + case 3: + formText = mpStringBuffer->securityKey; + break; + case 4: + formText = mpStringBuffer->ip.addr; + break; + case 5: + formText = mpStringBuffer->ip.netmask; + break; + case 6: + formText = mpStringBuffer->ip.gateway; + break; + case 7: + formText = mpStringBuffer->dns1; + break; + case 8: + formText = mpStringBuffer->dns2; + break; + case 10: + formText = mpStringBuffer->proxy.server; + break; + case 11: + formText = mpStringBuffer->proxy.port; + break; + case 12: + formText = mpStringBuffer->proxyBasic.uname; + break; + case 13: + formText = mpStringBuffer->proxyBasic.pass; + break; + case 14: + formText = mpStringBuffer->adjMtu; + break; + case 15: + formText = mpStringBuffer->parentalPass; + break; + case 16: + formText = mpStringBuffer->parentalRePass; + break; + case 17: + formText = mpStringBuffer->parentalJudgePass; + break; + case 18: + formText = mpStringBuffer->parentalSecA; + break; + case 19: + formText = mpStringBuffer->parentalReSecA; + break; + case 20: + formText = mpStringBuffer->masterKey; + break; + } + ext_ead::www::SurfaceManager::GetInstance()->GetBrowserThread()->CommitIme(mpBrowserData, formText); } mpWiiSettingData->data[0x11] = 0; - browser->DisposeImeData(mpBrowserData); + ext_ead::www::SurfaceManager::GetInstance()->GetBrowserThread()->DisposeImeData(mpBrowserData); } else if (mKeyboardState.iplType < keyboard::Manager::STATE_VISIBLE) { + u8 formId = mpWiiSettingData->data[0x11]; if (mKeyboardState.iplType < keyboard::Manager::STATE_APPEARING && formId != 0 && formId != 9 && formId != 21 && formId <= 22) { if (System::getKeyboard()->memoMgr()->isVacancy()) { @@ -1664,8 +1725,8 @@ namespace ipl { } void Setting::calcSetting() { + OSReport("setstring:%d\n", mpWiiSettingData->data[0x36]); u8 settingId = mpWiiSettingData->data[0x36]; - OSReport("setstring:%d\n", settingId); switch (settingId) { case 1: setDisPos(); @@ -1717,19 +1778,19 @@ namespace ipl { } void Setting::onTextInputOK() { - u8 formId = mpWiiSettingData->data[0x11]; - OSReport("Keyboard Confirm:%d\n", formId); + OSReport("Keyboard Confirm:%d\n", mpWiiSettingData->data[0x11]); wcslen(mKeyboardState.wcString); memset(unk_0x938, 0, sizeof(unk_0x938)); u8 convertedText[0x302]; memset(convertedText, 0, sizeof(convertedText)); memcpy(unk_0x938, mKeyboardState.wcString, sizeof(unk_0x938)); + u8 formId = mpWiiSettingData->data[0x11]; if (formId == 2 || formId == 22) { utility::CharacterCode::UTF16ToANSI(convertedText, reinterpret_cast(unk_0x938), 0x100); - size_t textLength = wcslen(reinterpret_cast(unk_0x938)); - memset(convertedText + textLength, 0, 0x100 - textLength); + memset(convertedText + wcslen(reinterpret_cast(unk_0x938)), 0, + 0x100 - wcslen(reinterpret_cast(unk_0x938))); memcpy(mpStringBuffer->securityKey, convertedText, sizeof(mpStringBuffer->securityKey)); return; } @@ -1740,12 +1801,12 @@ namespace ipl { utility::CharacterCode::UTF16ToUTF8(reinterpret_cast(convertedText), reinterpret_cast(unk_0x938), 0x301); - switch (formId) { + switch (mpWiiSettingData->data[0x11]) { case 1: memcpy(mpStringBuffer->nickname, convertedText, sizeof(mpStringBuffer->nickname)); break; case 3: - memcpy(mpStringBuffer->securityKey, convertedText, sizeof(mpStringBuffer->securityKey)); + memcpy(mpStringBuffer->ssid, convertedText, sizeof(mpStringBuffer->ssid)); break; case 4: memcpy(mpStringBuffer->ip.addr, convertedText, sizeof(mpStringBuffer->ip.addr)); @@ -1774,9 +1835,6 @@ namespace ipl { case 13: memcpy(mpStringBuffer->proxyBasic.pass, convertedText, sizeof(mpStringBuffer->proxyBasic.pass)); break; - case 14: - memcpy(mpStringBuffer->adjMtu, convertedText, sizeof(mpStringBuffer->adjMtu)); - break; case 15: memcpy(mpStringBuffer->parentalPass, convertedText, sizeof(mpStringBuffer->parentalPass)); break; @@ -1795,6 +1853,9 @@ namespace ipl { case 20: memcpy(mpStringBuffer->masterKey, convertedText, sizeof(mpStringBuffer->masterKey)); break; + case 14: + memcpy(mpStringBuffer->adjMtu, convertedText, sizeof(mpStringBuffer->adjMtu)); + break; } } -- 2.49.1 From 7f8b4c8a4fb817911b19f536312bfb7ed546a019 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Mon, 28 Sep 2026 23:57:01 -0500 Subject: [PATCH 38/61] wad: continue decompilation (worker snapshot f33bf397) (#252) --- libs/RVL_SDK/src/wad/wad.c | 582 ++++++++++++++++++++----------------- 1 file changed, 308 insertions(+), 274 deletions(-) diff --git a/libs/RVL_SDK/src/wad/wad.c b/libs/RVL_SDK/src/wad/wad.c index 0f2c89e1..43373a86 100644 --- a/libs/RVL_SDK/src/wad/wad.c +++ b/libs/RVL_SDK/src/wad/wad.c @@ -1,3 +1,4 @@ +#include #include #include #include @@ -236,7 +237,7 @@ static s32 _WADCheckContents(ESTmdView* titleMeta, ESContentMask* contentMask); static void _WADRandPad(void* buffer, u32 size); static s32 _WADVerifySavedataZD(WADSaveDataHeader* header, WADStream* stream, MEMAllocator* allocator, u32 offset); -static void _WADCleanTmpDir(MEMAllocator* allocator); +static s32 _WADCleanTmpDir(MEMAllocator* allocator); u32 _WADIsTerminated(const char* text, u32 maxLength); extern s32 ES_GetBoot2Version(u32* version); @@ -1173,22 +1174,15 @@ cleanup: } static s32 WAD_815C1288(WADExportLoopArgs* args) { - s32 result; - u32 remaining; - u32 bufferIndex; - ESFd fd; - WADImportTransfer* transfer; - u32 size; - OSMutex* mutex; - - fd = args->fd; - result = 0; - remaining = args->size; - bufferIndex = 0; - transfer = args->transfer; + ESFd fd = args->fd; + s32 result = 0; + u32 remaining = args->size; + u32 bufferIndex = 0; + WADImportTransfer* transfer = args->transfer; while ((remaining != 0) && (result == 0)) { - size = remaining; + u32 size = remaining; + OSMutex* mutex; if (remaining > transfer->chunkSize) { size = transfer->chunkSize; @@ -1317,10 +1311,16 @@ s32 WADBackupEx(u64 titleId, u32 ticketId, MEMAllocator* allocator, char* path, } if ((flags & 2) != 0) { char currentDirectory[NAND_MAX_PATH] ALIGN32; + u32 currentTitleHigh = 0; + u32 currentTitleLow = 0; result = NANDGetCurrentDir(currentDirectory); if (result != 0) { goto cleanup; } + if (strncmp(currentDirectory, "/title/", 7) == 0) { + sscanf(currentDirectory, "/title/%x/%x", ¤tTitleHigh, ¤tTitleLow); + headerBlock.header.titleId = ((u64)currentTitleHigh << 32) | currentTitleLow; + } result = _WADBackupGetFiles(0, flags, allocator, &fileCount, 0); if (result != 0) { goto cleanup; @@ -1374,7 +1374,6 @@ s32 WADBackupEx(u64 titleId, u32 ticketId, MEMAllocator* allocator, char* path, headerBlock.header.tmdSize = titleMetaSize; headerBlock.header.contentSize = contentDataSize; headerBlock.header.backupAreaLen = titleMetaSize + contentDataSize + fileDataSize; - headerBlock.header.titleId = titleId; result = ES_GetDeviceId(&headerBlock.header.deviceId); if (result != 0) { goto cleanup; @@ -1734,6 +1733,58 @@ done: return result; } +#pragma dont_inline on +static void* _WADMemAlloc(MEMAllocator* allocator, u32 size) { + s32 allocationKind; + u32 heapType; + void* buffer = 0; + + if ((allocator != 0) && (allocator->heap != 0)) { + heapType = ((MEMiHeapHead*)allocator->heap)->magic; + switch (heapType) { + case 0x45585048: + allocationKind = 0; + break; + case 0x46524D48: + allocationKind = 1; + break; + case 0x554E5448: + allocationKind = 2; + break; + default: + allocationKind = 3; + break; + } + + switch (allocationKind) { + case 0: + buffer = MEMAllocFromExpHeapEx(allocator->heap, size, 0x40); + break; + case 1: + buffer = MEMAllocFromFrmHeapEx(allocator->heap, size, 0x40); + break; + case 2: + default: + buffer = MEMAllocFromAllocator(allocator, size); + if (((u32)buffer & 0x3F) != 0) { + OSReport("%s: Memory Allocator must return 64B aligned memBlocks\n", __func__); + MEMFreeToAllocator(allocator, buffer); + buffer = 0; + } + break; + } + } + return buffer; +} + +static void _WADMemFree(MEMAllocator* allocator, void* buffer) { + if ((allocator == 0) || (allocator->heap == 0) || (buffer == 0)) { + return; + } + MEMFreeToAllocator(allocator, buffer); +} +#pragma dont_inline reset + s32 _WADGetCidxCount(const ESContentMask* contentMask) { s32 count = 0; u32 bitIndex = 0; @@ -1835,8 +1886,9 @@ static s32 _WADCanImportFile(const WADFileHeader* fileHeader, u32 transferId, co static s32 _WADBackupGetFiles(const char* directoryPath, u32 flags, MEMAllocator* allocator, u32* fileCount, WADBackupFileHeader* files) { char currentDirectory[NAND_MAX_PATH] ALIGN32; - char fullDirectoryPath[NAND_MAX_PATH] ALIGN32; char fullFilePath[NAND_MAX_PATH] ALIGN32; + char noCopyPath[NAND_MAX_PATH] ALIGN32; + char bannerPath[NAND_MAX_PATH] ALIGN32; char* names = 0; char* nameList = 0; u32 nameCount = 0; @@ -1856,17 +1908,9 @@ static s32 _WADBackupGetFiles(const char* directoryPath, u32 flags, MEMAllocator return result; } if (directoryPath == 0) { - directoryPath = ""; + directoryPath = "."; } - if (directoryPath[0] == '\0') { - strncpy(fullDirectoryPath, currentDirectory, sizeof(fullDirectoryPath)); - } else if (directoryPath[0] == '/') { - strncpy(fullDirectoryPath, directoryPath, sizeof(fullDirectoryPath)); - } else { - snprintf(fullDirectoryPath, sizeof(fullDirectoryPath), "%s/%s", currentDirectory, - directoryPath); - } - result = NANDPrivateReadDir(fullDirectoryPath, 0, &nameCount); + result = NANDPrivateReadDir(directoryPath, 0, &nameCount); if (result == -1) { *fileCount = 0; return 0; @@ -1880,7 +1924,7 @@ static s32 _WADBackupGetFiles(const char* directoryPath, u32 flags, MEMAllocator return -3003; } names = nameList; - result = NANDPrivateReadDir(fullDirectoryPath, nameList, &nameCount); + result = NANDPrivateReadDir(directoryPath, nameList, &nameCount); if (result != 0) { goto cleanup; } @@ -1934,6 +1978,29 @@ static s32 _WADBackupGetFiles(const char* directoryPath, u32 flags, MEMAllocator if (result != 0) { break; } + if ((flags & 0x10) == 0) { + if ((flags & 4) == 0) { + if (strcmp(directoryPath, ".") == 0) { + snprintf(noCopyPath, sizeof(noCopyPath), "%s/%s", currentDirectory, + "nocopy"); + snprintf(bannerPath, sizeof(bannerPath), "%s/%s", currentDirectory, + "banner.bin"); + if ((strcmp(fullFilePath, noCopyPath) == 0) && (fileType == 2)) { + goto nextName; + } + if ((strcmp(fullFilePath, bannerPath) == 0) && (fileType == 1)) { + goto nextName; + } + } + } else { + if ((strcmp(fullFilePath, "nocopy") == 0) && (fileType == 2)) { + goto nextName; + } + if ((strcmp(fullFilePath, "banner.bin") == 0) && (fileType == 1)) { + goto nextName; + } + } + } if (files != 0) { file = &files[totalFiles]; file->magic = 0x3ADF17E; @@ -2022,57 +2089,6 @@ static s32 _WADBackupGetSize(u32 flags, ESTmdView* titleMeta, ESContentMask* con } #pragma dont_inline reset -#pragma dont_inline on -static void* _WADMemAlloc(MEMAllocator* allocator, u32 size) { - s32 allocationKind; - u32 heapType; - void* buffer = 0; - - if ((allocator != 0) && (allocator->heap != 0)) { - heapType = ((MEMiHeapHead*)allocator->heap)->magic; - switch (heapType) { - case 0x45585048: - allocationKind = 0; - break; - case 0x46524D48: - allocationKind = 1; - break; - case 0x554E5448: - allocationKind = 2; - break; - default: - allocationKind = 3; - break; - } - - switch (allocationKind) { - case 0: - buffer = MEMAllocFromExpHeapEx(allocator->heap, size, 0x40); - break; - case 1: - buffer = MEMAllocFromFrmHeapEx(allocator->heap, size, 0x40); - break; - case 2: - default: - buffer = MEMAllocFromAllocator(allocator, size); - if (((u32)buffer & 0x3F) != 0) { - OSReport("%s: Memory Allocator must return 64B aligned memBlocks\n", "_WADMemAlloc"); - MEMFreeToAllocator(allocator, buffer); - buffer = 0; - } - break; - } - } - return buffer; -} - -static void _WADMemFree(MEMAllocator* allocator, void* buffer) { - if ((allocator == 0) || (allocator->heap == 0) || (buffer == 0)) { - return; - } - MEMFreeToAllocator(allocator, buffer); -} -#pragma dont_inline reset static void _WADFreeMemory(WADUnpackInfo* info, MEMAllocator* allocator) { if ((info->size_0x18 != 0) && (info->buffer_0x14 != 0)) { @@ -2099,17 +2115,14 @@ static void _WADRandPad(void* buffer, u32 size) { u32 remainder = size & 3; u32 wordIndex; + if (size == 0) { + return; + } for (wordIndex = 0; wordIndex < wordCount; wordIndex++) { - u32 first = rand(); - u32 second = rand(); - u32 third = rand(); - words[wordIndex] = (third & 3) | (second << 17) | (first << 2); + words[wordIndex] = ((u32)rand() << 2) | ((u32)rand() << 17) | (rand() & 3); } if (remainder != 0) { - u32 first = rand(); - u32 second = rand(); - u32 third = rand(); - u32 randomWord = (third & 3) | (second << 17) | (first << 2); + u32 randomWord = ((u32)rand() << 2) | ((u32)rand() << 17) | (rand() & 3); u8* tail = (u8*)&words[wordCount]; u8* randomBytes = (u8*)&randomWord; u32 byteIndex; @@ -2136,34 +2149,62 @@ typedef union WADFileInfoView { s32 WADOpenStream(WADLocation location, const char* path, WADStream* stream, u32 write, u32 offset) { - s32 result; - stream->location = location; - if (location == WAD_LOCATION_SD_CARD) { - if (write == 0) { - stream->handle.fa = FAFopen(path, "r"); + + switch (location) { + case WAD_LOCATION_CNT_DVD: { + WADContentPath* contentPath = (WADContentPath*)path; + s32 result; + if (write != 0) { + result = -3004; } else { - stream->handle.fa = FAFopen(path, "r+"); - if (stream->handle.fa == 0) { - stream->handle.fa = FACreate(path, 0); - } - if (stream->handle.fa == 0) { - return -3004; - } - if ((offset != 0) && (WADSeekStream(stream, offset, 0) != offset)) { - return -3004; + result = contentOpenDVD(contentPath->handle, contentPath->name, + &stream->handle.contentDvd); + if (result != 0) { + result = -3004; } } - return stream->handle.fa == 0 ? -3004 : 0; + return result; } - if (location < WAD_LOCATION_SD_CARD) { - if (location == WAD_LOCATION_DVD) { - if (write != 0) { - return -3004; + + case WAD_LOCATION_CNT_NAND: { + WADContentPath* contentPath = (WADContentPath*)path; + s32 result; + if (write != 0) { + result = -3004; + } else { + result = contentOpenNAND(contentPath->handle, contentPath->name, + &stream->handle.contentNand); + if (result != 0) { + result = -3004; } - return DVDOpen(path, &stream->handle.dvd) ? 0 : -3004; } - if (location == WAD_LOCATION_NAND) { + return result; + } + + case (WADLocation)0: + if ((((u32)path + offset) & 0x3F) != 0) { + return -3007; + } + stream->handle.memoryBase = (void*)((u32)path + offset); + return 0; + + case WAD_LOCATION_DVD: + { + s32 result; + if (write != 0) { + result = -3004; + } else if (DVDOpen(path, &stream->handle.dvd)) { + result = 0; + } else { + result = -3004; + } + return result; + } + + case WAD_LOCATION_NAND: + { + s32 result; if (write == 0) { return NANDPrivateOpen(path, &stream->handle.nand, 1) == 0 ? 0 : -3004; } @@ -2184,7 +2225,7 @@ s32 WADOpenStream(WADLocation location, const char* path, WADStream* stream, u32 u32 fileSize; fileSize = NANDSeek(&stream->handle.nand, 0, 2); - if (offset <= fileSize) { + if (fileSize < offset) { return -3004; } memset(zeroes, 0, sizeof(zeroes)); @@ -2203,142 +2244,130 @@ s32 WADOpenStream(WADLocation location, const char* path, WADStream* stream, u32 } return result == offset ? 0 : -3004; } - if ((s32)location >= 0) { - if ((((u32)path + offset) & 0x3F) != 0) { - return -3007; + + case WAD_LOCATION_SD_CARD: { + if (write == 0) { + stream->handle.fa = FAFopen(path, "r"); + } else { + stream->handle.fa = FAFopen(path, "r+"); + if (stream->handle.fa == 0) { + stream->handle.fa = FACreate(path, 0); + } + if (stream->handle.fa == 0) { + return -3004; + } + if ((offset != 0) && (WADSeekStream(stream, offset, 0) != offset)) { + return -3004; } - stream->handle.memoryBase = (void*)((u32)path + offset); - return 0; } - } else if (location == WAD_LOCATION_CNT_NAND) { - WADContentPath* contentPath = (WADContentPath*)path; - if (write != 0) { - return -3004; - } - return contentOpenNAND(contentPath->handle, contentPath->name, - &stream->handle.contentNand) == 0 - ? 0 - : -3004; - } else if (location < WAD_LOCATION_CNT_NAND) { - WADContentPath* contentPath = (WADContentPath*)path; - if (write != 0) { - return -3004; - } - return contentOpenDVD(contentPath->handle, contentPath->name, - &stream->handle.contentDvd) == 0 - ? 0 - : -3004; + return stream->handle.fa == 0 ? -3004 : 0; + } + + default: + return -3000; } - return -3000; } size_t WADReadStream(WADStream* stream, void** buffer, size_t size, s32 offset) { size_t result; u32 alignedSize; - s32 location; if ((s32)size <= 0) { - result = 0; - } else if ((stream == 0) || (buffer == 0)) { - result = -3000; - } else { - alignedSize = (size + WAD_READ_ALIGNMENT - 1) & ~(WAD_READ_ALIGNMENT - 1); - if (size == alignedSize) { - location = stream->location; - if (location != WAD_LOCATION_SD_CARD) { - if (location < WAD_LOCATION_SD_CARD) { - if (location != WAD_LOCATION_DVD) { - if (location > 0) { - result = NANDSeek(&stream->handle.nand, offset, 0); - if ((s32)result < 0) { - return result; - } - return NANDRead(&stream->handle.nand, *buffer, alignedSize); - } - if (location >= 0) { - memcpy(*buffer, (u8*)stream->handle.memoryBase + offset, size); - return size; - } - } else { - return DVDReadPrio(&stream->handle.dvd, *buffer, alignedSize, offset, 2); - } - } else { - if (location != WAD_LOCATION_CNT_NAND) { - if (location < WAD_LOCATION_CNT_NAND) { - return contentReadDVD(&stream->handle.contentDvd, *buffer, alignedSize, - offset); - } - } else { - return contentReadNAND(&stream->handle.contentNand, *buffer, alignedSize, - offset); - } - } - result = -3000; - } else if (stream->handle.fa == 0) { - result = -3000; - } else { - result = FAFseek(stream->handle.fa, offset, 0); - if (result == 0) { - result = FAFread(*buffer, 1, size, stream->handle.fa); - } - } - } else { - result = -3000; - } + return 0; + } + if ((stream == 0) || (buffer == 0)) { + return -3000; + } + alignedSize = (size + WAD_READ_ALIGNMENT - 1) & ~(WAD_READ_ALIGNMENT - 1); + if (size != alignedSize) { + return -3000; + } + + switch (stream->location) { + case WAD_LOCATION_CNT_DVD: + return contentReadDVD(&stream->handle.contentDvd, *buffer, alignedSize, offset); + + case WAD_LOCATION_CNT_NAND: + return contentReadNAND(&stream->handle.contentNand, *buffer, alignedSize, offset); + + case (WADLocation)0: + memcpy(*buffer, (u8*)stream->handle.memoryBase + offset, size); + return size; + + case WAD_LOCATION_DVD: + return DVDReadPrio(&stream->handle.dvd, *buffer, alignedSize, offset, 2); + + case WAD_LOCATION_NAND: + result = NANDSeek(&stream->handle.nand, offset, 0); + if ((s32)result >= 0) { + result = NANDRead(&stream->handle.nand, *buffer, alignedSize); + } + return result; + + case WAD_LOCATION_SD_CARD: + if (stream->handle.fa == 0) { + return -3000; + } + result = FAFseek(stream->handle.fa, offset, 0); + if (result == 0) { + return FAFread(*buffer, 1, size, stream->handle.fa); + } + return result; + + default: + return -3000; } - return result; } void WADCloseStream(WADStream* stream) { if (stream == 0) { return; } - if (stream->location != WAD_LOCATION_SD_CARD) { - if (stream->location < WAD_LOCATION_SD_CARD) { - if (stream->location != WAD_LOCATION_DVD) { - if (stream->location < WAD_LOCATION_DVD) { - return; - } - NANDClose(&stream->handle.nand); - return; - } - DVDClose(&stream->handle.dvd); - return; - } - if (stream->location != WAD_LOCATION_CNT_NAND) { - if (stream->location > WAD_LOCATION_CNT_NAND) { - return; - } - contentCloseDVD(&stream->handle.contentDvd); - return; - } + switch (stream->location) { + case WAD_LOCATION_CNT_DVD: + contentCloseDVD(&stream->handle.contentDvd); + return; + case WAD_LOCATION_CNT_NAND: contentCloseNAND(&stream->handle.contentNand); return; - } - if (stream->handle.fa != 0) { - FAFclose(stream->handle.fa); + case WAD_LOCATION_DVD: + DVDClose(&stream->handle.dvd); + return; + case WAD_LOCATION_NAND: + NANDClose(&stream->handle.nand); + return; + case WAD_LOCATION_SD_CARD: + if (stream->handle.fa != 0) { + FAFclose(stream->handle.fa); + } + return; + default: + return; } } s32 WADWriteStream(WADStream* stream, void* buffer, u32 size) { + s32 result = size; + if ((stream == 0) || (buffer == 0)) { - return -3000; - } - if (stream->location == WAD_LOCATION_NAND) { - return NANDWrite(&stream->handle.nand, buffer, size); - } - if (stream->location == WAD_LOCATION_DVD - 1) { - memcpy(stream->handle.memoryBase, buffer, size); - return size; - } - if ((stream->location > WAD_LOCATION_NAND) && - (stream->location < WAD_LOCATION_CNT_DVD)) { - if (stream->handle.fa == 0) { - return -3000; + result = -3000; + } else if (stream->location != WAD_LOCATION_NAND) { + if (stream->location == (WADLocation)0) { + memcpy(stream->handle.memoryBase, buffer, size); + } else if ((stream->location > WAD_LOCATION_NAND) && + (stream->location < WAD_LOCATION_CNT_DVD)) { + if (stream->handle.fa == 0) { + result = -3000; + } else { + result = FAFwrite(buffer, 1, size, stream->handle.fa); + } + } else { + result = -3000; } - return FAFwrite(buffer, 1, size, stream->handle.fa); + } else { + result = NANDWrite(&stream->handle.nand, buffer, size); } - return -3000; + return result; } s32 WADSeekStream(WADStream* stream, u32 offset, s32 origin) { @@ -2734,7 +2763,7 @@ static s32 _WADUnpackBackup(WADHeader* header, WADStream* stream, WADUnpackInfo* info->titleMetaSize = 1; result = WADReadStream(stream, (void**)&info->titleMeta, alignedSize, offset + info->sectionOffset); - if (result != alignedSize) { + if ((s32)result != (s32)alignedSize) { return -3005; } result = 0; @@ -2853,7 +2882,8 @@ static s32 _WADVerifySavedataZD(WADSaveDataHeader* header, WADStream* stream, s32 result; if (header->saveType != 1) { - return -3009; + result = -3009; + goto cleanup; } fileHeader = MEMAllocFromAllocator(allocator, sizeof(WADFileHeader)); if (fileHeader == 0) { @@ -2877,26 +2907,29 @@ static s32 _WADVerifySavedataZD(WADSaveDataHeader* header, WADStream* stream, } memset(encryptedData, 0, 0x4000); memset(decryptedData, 0, 0x4000); - if (strcmp(fileHeader->name, "zeldaTp.dat") != 0) { - result = -3009; - goto cleanup; - } - result = WADReadStream(stream, &encryptedData, 0x4000, offset + 0x80); - if (result != 0x4000) { - result = -3005; - goto cleanup; - } - result = ES_Decrypt(6, fileHeader->iv, encryptedData, 0x4000, decryptedData); - if (result != 0) { - result = -3005; - goto cleanup; - } - if (WADCheckSavedataZD(decryptedData) == 0) { - result = -3009; - goto cleanup; - } - result = NANDPrivateCreate(fileHeader->name, 0x34, 0); - if ((result == 0) && (NANDPrivateOpen(fileHeader->name, &fileInfo, 2) == 0)) { + if (strcmp(fileHeader->name, "zeldaTp.dat") == 0) { + result = WADReadStream(stream, &encryptedData, 0x4000, offset + 0x80); + if (result != 0x4000) { + result = -3005; + goto cleanup; + } + result = ES_Decrypt(6, fileHeader->iv, encryptedData, 0x4000, decryptedData); + if (result != 0) { + result = -3005; + goto cleanup; + } + if (WADCheckSavedataZD(decryptedData) == 0) { + result = -3009; + goto cleanup; + } + result = NANDPrivateCreate(fileHeader->name, 0x34, 0); + if (result != 0) { + goto cleanup; + } + result = NANDPrivateOpen(fileHeader->name, &fileInfo, 2); + if (result != 0) { + goto cleanup; + } fileOpened = TRUE; result = NANDWrite(&fileInfo, decryptedData, 0x4000); if (result != 0x4000) { @@ -2907,6 +2940,8 @@ static s32 _WADVerifySavedataZD(WADSaveDataHeader* header, WADStream* stream, fileOpened = FALSE; } } + } else { + result = -3009; } cleanup: @@ -2925,33 +2960,38 @@ cleanup: return result; } -static void _WADCleanTmpDir(MEMAllocator* allocator) { +static s32 _WADCleanTmpDir(MEMAllocator* allocator) { + s32 result; + u32 fileCount = 0; char* names = 0; char* name; - char filePath[NAND_MAX_PATH] ALIGN32; - u32 fileCount = 0; + char filePath[NAND_MAX_PATH + 1] = {0}; u32 fileIndex; - s32 result; result = NANDPrivateReadDir("/tmp", 0, &fileCount); if ((result == 0) && (fileCount != 0)) { names = MEMAllocFromAllocator(allocator, fileCount * 0x41); - if ((names != 0) && (NANDPrivateReadDir("/tmp", names, &fileCount) == 0)) { - name = names; - for (fileIndex = 0; fileIndex < fileCount; fileIndex++) { - char* extension = strrchr(name, '.'); - if ((extension != 0) && (strncmp(extension + 1, "tmp", 3) == 0)) { - snprintf(filePath, sizeof(filePath), "/tmp/%s", name); - NANDPrivateDelete(filePath); - OSReport("%s:%d remove %s", "WADImportEx", 0x1777, filePath); + if (names != 0) { + result = NANDPrivateReadDir("/tmp", names, &fileCount); + if (result == 0) { + name = names; + for (fileIndex = 0; fileIndex < fileCount;) { + char* extension = strrchr(name, '.'); + if ((extension != 0) && (strncmp(extension + 1, "tmp", 3) == 0)) { + sprintf(filePath, "/tmp/%s", name); + NANDPrivateDelete(filePath); + OSReport("%s:%d remove %s\n", __func__, 0x1777, filePath); + } + fileIndex++; + name += strlen(name) + 1; } - name += strlen(name) + 1; } } } if (names != 0) { MEMFreeToAllocator(allocator, names); } + return result; } s32 WADImportDVDForBS(const char* path, void* buffer, u32 bufferSize) { @@ -2993,7 +3033,7 @@ s32 WADImportDVDForBS(const char* path, void* buffer, u32 bufferSize) { header = (WADHeader*)readBuffer; result = WAD_815C2F44(header, parts.headerInfo); if (result != 2) { - OSReport("%s:%d Format should be iRD format: %s\n", "WADImportDVDForBS", 0x17D2, + OSReport("%s:%d Format should be iRD format: %s\n", __func__, 0x17D2, path); result = -3000; goto cleanup; @@ -3023,23 +3063,23 @@ s32 WADImportDVDForBS(const char* path, void* buffer, u32 bufferSize) { titleMeta = parts.titleMeta; applicationSize = ((u32)titleMeta->contents[0].size + 0xF) & ~0xF; applicationData = readBuffer + sectionOffset; - if ((titleMeta == 0) || (titleMeta->head.titleId != ES_TITLE_ID(1, 1))) { - OSReport("%s:%d This function only works for boot2 import.\n", "WADImportDVDForBS", - 0x180D); - result = -3000; - } else { + if ((titleMeta != 0) && (titleMeta->head.titleId == ES_TITLE_ID(1, 1))) { result = ES_ImportBoot(parts.ticket, parts.certificates, parts.certificateSize, parts.titleMeta, parts.titleMetaSize, parts.certificates, parts.certificateSize, parts.crls, parts.crlSize, applicationData, applicationSize); if (result != 0) { - OSReport("%s: Import Boot Failed: %d\n", "WADImportDVDForBS", result); + OSReport("%s: Import Boot Failed: %d\n", __func__, result); } else { - OSReport("%s: Import Boot Successful\n", "WADImportDVDForBS"); + OSReport("%s: Import Boot Successful\n", __func__); } + } else { + OSReport("%s:%d This function only works for boot2 import.\n", __func__, + 0x180D); + result = -3000; } } else { - OSReport("%s:%d This function only works for boot2 import.\n", "WADImportDVDForBS", + OSReport("%s:%d This function only works for boot2 import.\n", __func__, 0x1814); result = -3000; } @@ -3242,17 +3282,11 @@ extern s32 SHA1Reset(void* context); extern s32 SHA1Result(void* context, void* digest); static s32 WAD_815C43E0(WADHashThreadArgs* args) { - void* context; - s32 result; - u32 remaining; - u32 bufferIndex; - WADImportTransfer* transfer; - - context = args->context; - result = 0; - remaining = args->size; - bufferIndex = 0; - transfer = args->transfer; + void* context = args->context; + s32 result = 0; + u32 remaining = args->size; + u32 bufferIndex = 0; + WADImportTransfer* transfer = args->transfer; while ((remaining != 0) && (result == 0)) { u32 size = remaining; -- 2.49.1 From f98e550b24e7752f1674ee1d1cfa92afe418ed5a Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Mon, 28 Sep 2026 23:57:07 -0500 Subject: [PATCH 39/61] sdchansel: continue decompilation (worker snapshot b063d97f) (#253) --- config/43U/symbols.txt | 18 +- .../sdChannelSelect/iplSDChannelSelect.h | 44 ++- .../sdChannelSelect/iplSDChannelSelect.cpp | 303 +++++++++++++++++- 3 files changed, 351 insertions(+), 14 deletions(-) diff --git a/config/43U/symbols.txt b/config/43U/symbols.txt index 1aa0bdf3..2679503c 100644 --- a/config/43U/symbols.txt +++ b/config/43U/symbols.txt @@ -4580,9 +4580,9 @@ handleNandTitleUsage__Q33ipl5scene15SDChannelSelectFv = .text:0x813DBD94; // typ compareTitleUsage__Q33ipl5scene15SDChannelSelectFPCvPCv = .text:0x813DBE6C; // type:function size:0x28 handleSDTitleList__Q33ipl5scene15SDChannelSelectFv = .text:0x813DBE94; // type:function size:0x124 compareTitleInfo__Q33ipl5scene15SDChannelSelectFPCvPCv = .text:0x813DBFB8; // type:function size:0x28 -iplSDChannelSelect_813DBFE0 = .text:0x813DBFE0; // type:function size:0x2AC +handleSDTitleListResult__Q33ipl5scene15SDChannelSelectFv = .text:0x813DBFE0; // type:function size:0x2AC handleSDMountComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC28C; // type:function size:0x64 -iplSDChannelSelect_813DC2F0 = .text:0x813DC2F0; // type:function size:0x1B0 +handleSDChannelUpdateComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC2F0; // type:function size:0x1B0 handleSDCardReady__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC4A0; // type:function size:0x5C handleCardCommand__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC4FC; // type:function size:0x78 handleCopyComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC574; // type:function size:0x80 @@ -4592,7 +4592,7 @@ handleMoveComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC684; // type: handleBackupFitComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC714; // type:function size:0x48 handleNandSDCleanupComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC75C; // type:function size:0x48 handleSDDeleteComplete__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC7A4; // type:function size:0x48 -iplSDChannelSelect_813DC7EC = .text:0x813DC7EC; // type:function size:0x14C +updateChannelNotices__Q33ipl5scene15SDChannelSelectFii = .text:0x813DC7EC; // type:function size:0x14C processWorkerState__Q33ipl5scene15SDChannelSelectFv = .text:0x813DC938; // type:function size:0x18C updateDialogAnimation__Q33ipl5scene15SDChannelSelectFv = .text:0x813DCAC4; // type:function size:0x42C setDialogMessage__Q33ipl5scene15SDChannelSelectFUlUl = .text:0x813DCEF0; // type:function size:0x24 @@ -4632,15 +4632,15 @@ iplSDChannelSelect_813DF3FC = .text:0x813DF3FC; // type:function size:0x110 iplSDChannelSelect_813DF50C = .text:0x813DF50C; // type:function size:0x4C iplSDChannelSelect_813DF558 = .text:0x813DF558; // type:function size:0x178 iplSDChannelSelect_813DF6D0 = .text:0x813DF6D0; // type:function size:0x164 -iplSDChannelSelect_813DF834 = .text:0x813DF834; // type:function size:0x110 -iplSDChannelSelect_813DF944 = .text:0x813DF944; // type:function size:0x84 -iplSDChannelSelect_813DF9C8 = .text:0x813DF9C8; // type:function size:0xF8 -iplSDChannelSelect_813DFAC0 = .text:0x813DFAC0; // type:function size:0xFC -iplSDChannelSelect_813DFBBC = .text:0x813DFBBC; // type:function size:0xE4 +createChannelList__Q33ipl5scene15SDChannelSelectFib = .text:0x813DF834; // type:function size:0x110 +createChannelObject__Q33ipl5scene15SDChannelSelectFii = .text:0x813DF944; // type:function size:0x84 +destroyUnusedChannelObjects__Q33ipl5scene15SDChannelSelectFiPQ33ipl5scene12SDChannelObj = .text:0x813DF9C8; // type:function size:0xF8 +refreshChannelList__Q33ipl5scene15SDChannelSelectFv = .text:0x813DFAC0; // type:function size:0xFC +refreshAfterSDTitleList__Q33ipl5scene15SDChannelSelectFv = .text:0x813DFBBC; // type:function size:0xE4 destroyChannelObject__Q33ipl5scene15SDChannelSelectFPQ33ipl5scene12SDChannelObj = .text:0x813DFCA0; // type:function size:0x50 iplSDChannelSelect_813DFCF0 = .text:0x813DFCF0; // type:function size:0x74 iplSDChannelSelect_813DFD64 = .text:0x813DFD64; // type:function size:0x154 -iplSDChannelSelect_813DFEB8 = .text:0x813DFEB8; // type:function size:0x74 +findChannelObject__Q33ipl5scene15SDChannelSelectCFii = .text:0x813DFEB8; // type:function size:0x74 iplSDChannelSelect_813DFF2C = .text:0x813DFF2C; // type:function size:0x1C0 hasChannelObject__Q33ipl5scene15SDChannelSelectCFii = .text:0x813E00EC; // type:function size:0x140 isChannelInCalc__Q33ipl5scene15SDChannelSelectCFiii = .text:0x813E022C; // type:function size:0x68 diff --git a/include/scene/sdChannelSelect/iplSDChannelSelect.h b/include/scene/sdChannelSelect/iplSDChannelSelect.h index d650b64d..ea16e604 100644 --- a/include/scene/sdChannelSelect/iplSDChannelSelect.h +++ b/include/scene/sdChannelSelect/iplSDChannelSelect.h @@ -12,6 +12,7 @@ namespace ipl { namespace scene { class SDChannelObj { public: + SDChannelObj(EGG::Heap* heap, int page, int index); ~SDChannelObj(); EGG::Heap* getHeap() const { return mpHeap; } @@ -19,13 +20,41 @@ namespace ipl { int getIndex() const { return mIndex; } private: + friend class SDChannelSelect; + nw4r::ut::Link mListLink; - f32 mOffsetX; - f32 mOffsetY; + EGG::ExpHeap* mpDialogHeap; + EGG::ExpHeap* mpChannelHeap; EGG::Heap* mpHeap; u32 mState; int mPage; int mIndex; + nand::LayoutFile* mpLayoutFile; + nw4r::lyt::Pane* mpPane; + layout::Animator* mpPaneAnimator; + layout::Object* mpBaseLayout; + layout::Animator* mpBaseAnimator; + layout::Object* mpPageLayout; + layout::Animator* mpPageAnimators[3]; + int mPageAnimation; + int mPageAnimationFrame; + layout::Object* mpDialogLayout; + layout::Animator* mpDialogAnimator; + int mDialogState; + int mDialogFrame; + int mDialogTimer; + int mAnimationState; + nw4r::lyt::Group* mpNewMessageGroup; + int mNewMessageCount; + u8 mbNewMessageGroupActive; + int mNewMessageState; + int mNewMessageFrame; + f32 mOffsetX; + f32 mOffsetY; + f32 mAspectRatioScale; + int mStateFlags; + void* mpThumbnailData; + NandSDWorker::SDAppMetaEntry mAppMeta; }; extern "C" void iplSDChannelObj_813E3104(SDChannelObj* channel); extern "C" void iplSDChannelObj_813E311C(SDChannelObj* channel, EGG::ExpHeap* firstHeap, @@ -35,6 +64,8 @@ namespace ipl { extern "C" void iplSDChannelObj_813E3180(SDChannelObj* channel, nand::LayoutFile* layoutFile); extern "C" void iplSDChannelObj_813E3304(SDChannelObj* channel); extern "C" void iplSDChannelObj_813E330C(SDChannelObj* channel); + extern "C" void* iplSDChannelObj_813E3128(SDChannelObj* channel); + extern "C" bool iplSDChannelObj_813E3330(SDChannelObj* channel); union SDChannelSelectCommandArguments { u32 values[3]; @@ -68,7 +99,7 @@ namespace ipl { struct SDChannelSelectTitleInfo { ESTitleId32 titleId; - u32 state; + bool used; }; struct SDChannelSelectNoticeQueue { @@ -147,6 +178,10 @@ namespace ipl { void handleNandTitleUsage(); void handleNandTitleUsageComplete(); void handleSDTitleList(); + void handleSDTitleListResult(); + void refreshAfterSDTitleList(); + void handleSDChannelUpdateComplete(); + void updateChannelNotices(int pageOffset, int index); void handleSDMountComplete(); void handleCopyComplete(); void handleDeleteComplete(); @@ -164,7 +199,10 @@ namespace ipl { static int compareTitleInfo(const void* lhs, const void* rhs); void createChannelList(int page, bool force); void destroyChannelObject(SDChannelObj* channel); + void destroyUnusedChannelObjects(int currentPage, SDChannelObj* keepChannel); + void refreshChannelList(); bool hasChannelObject(int page, int index) const; + SDChannelObj* findChannelObject(int page, int index) const; void createChannelObject(int page, int index); void createBaseLayout(); void updateNoCardLayouts(); diff --git a/src/scene/sdChannelSelect/iplSDChannelSelect.cpp b/src/scene/sdChannelSelect/iplSDChannelSelect.cpp index 793ccfb9..678f43af 100644 --- a/src/scene/sdChannelSelect/iplSDChannelSelect.cpp +++ b/src/scene/sdChannelSelect/iplSDChannelSelect.cpp @@ -433,7 +433,7 @@ namespace ipl { mpSDWorker->startup_async(); mWorkerState = 2; } else if (mPreviousSDState != mCurrentSDState && mCurrentSDState == 7) { - System::getErrorHandler()->set(ErrorHandler::DEFAULT, 1); + setDialogMessage(8, 0xaa); } } @@ -544,6 +544,91 @@ namespace ipl { return left->titleId != right->titleId; } + void SDChannelSelect::handleSDTitleListResult() { + if (mpSDWorker->is_working()) { + return; + } + + mLastOperation = 14; + if (mDialogState != 0) { + return; + } + + if (OSGetTime() - mOperationStartTime >= OS_TIMER_CLOCK) { + setDialogMessage(1, 0); + int result = mpSDWorker->get_async_result(); + if (result == NandSDWorker::RESULT_OK || + result == NandSDWorker::RESULT_SD_APP_LOC_NOT_FOUND) { + for (int channelIndex = 0; channelIndex < mPageCount * 12; + ++channelIndex) { + if (mpChannelTitleIds[channelIndex] != 0) { + SDChannelSelectTitleInfo* info = + static_cast( + bsearch(mpChannelTitleIds + channelIndex, mpSDTitleInfo, + mSDTitleCount, sizeof(SDChannelSelectTitleInfo), + compareTitleInfo)); + if (info != NULL) { + info->used = true; + } else { + mpChannelTitleIds[channelIndex] = 0; + } + } + } + + int channelIndex = 0; + u32 titleIndex = 0; + bool addedTitle = false; + for (; channelIndex < mPageCount * 12; ++channelIndex) { + if (mpChannelTitleIds[channelIndex] == 0) { + if (titleIndex == mSDTitleCount) { + break; + } + + for (; titleIndex < mSDTitleCount; ++titleIndex) { + SDChannelSelectTitleInfo* info = &mpSDTitleInfo[titleIndex]; + if (!info->used && info->titleId != 0x48415A41) { + mpChannelTitleIds[channelIndex] = info->titleId; + addedTitle = true; + ++titleIndex; + break; + } + } + } + } + + if (addedTitle || result == NandSDWorker::RESULT_SD_APP_LOC_NOT_FOUND) { + enqueueLoadNotice(); + } + } else { + int channelCount = 0; + int channelIndex = 0; + u32 titleIndex = 0; + for (; titleIndex < mSDTitleCount; ++titleIndex) { + u32 titleId = mpSDTitleInfo[titleIndex].titleId; + if (titleId != 0x48415A41) { + ++channelCount; + mpChannelTitleIds[channelIndex++] = titleId; + if (channelCount == mPageCount * 12) { + break; + } + } + } + enqueueLoadNotice(); + } + + mWorkerCommand = 1; + mbNeedsRefresh = true; + u32 titleCount = mbHazardTitleFound ? mSDTitleCount - 1 : mSDTitleCount; + if (titleCount > static_cast(mPageCount * 12)) { + mbOperationActive = true; + } + if (titleCount >= static_cast(mPageCount * 12)) { + mbSDCardBroken = true; + } + refreshAfterSDTitleList(); + } + } + void SDChannelSelect::processWorkerCommands() { if (mpSDWorker->is_working() || mWorkerState != 4) { return; @@ -643,6 +728,53 @@ namespace ipl { } } + void SDChannelSelect::handleSDChannelUpdateComplete() { + if (mpSDWorker->is_working()) { + return; + } + + mLastOperation = 14; + SDChannelObj* channel = mpCurrentLoadedChannel; + int page = channel->mPage; + int index = channel->mIndex; + if (!isChannelInCalc(page, index, mCurrentPage) || + static_cast(mCurrentSDState) - 1 <= 1) { + destroyChannelObject(channel); + mWorkerCommand = 1; + mpCurrentLoadedChannel = NULL; + return; + } + + if (mpSDWorker->get_async_result() >= 0) { + channel->mStateFlags = 0; + channel->mState = 2; + DCFlushRange(iplSDChannelObj_813E3128(channel), 0x19000); + } else { + memcpy(iplSDChannelObj_813E3128(channel), + mpCorruptIconFile->getBuffer(), mpCorruptIconFile->getLength()); + memset(&channel->mAppMeta, 0, sizeof(channel->mAppMeta)); + channel->mStateFlags = 3; + channel->mState = 2; + } + + SDChannelObj* previous = findChannelObject(page, index); + if (previous != NULL) { + nw4r::ut::List_Insert(&mChannelObjects, previous, channel); + nw4r::ut::List_Remove(&mChannelObjects, previous); + destroyChannelObject(previous); + } else { + nw4r::ut::List_Append(&mChannelObjects, channel); + } + + updateChannelObject(channel); + if (mCurrentPage == page) { + mpPaneManager->initPane(getChannelPane(index)); + } + + mWorkerCommand = 1; + mpCurrentLoadedChannel = NULL; + } + void SDChannelSelect::handleCopyComplete() { if (!mpSDWorker->is_working()) { mLastOperation = 14; @@ -736,6 +868,50 @@ namespace ipl { } } + void SDChannelSelect::updateChannelNotices(int pageOffset, int index) { + int page = mCurrentPage + pageOffset; + if (page < 0 || mpChannelTitleIds == NULL) { + return; + } + + int firstIndex; + int indexStep; + if (pageOffset == 2) { + firstIndex = 0; + indexStep = 4; + } else if (pageOffset < 2) { + if (pageOffset == -2) { + firstIndex = 3; + indexStep = 4; + } else { + firstIndex = 0; + indexStep = 1; + } + } else { + firstIndex = 0; + indexStep = 1; + } + + int pageTitleIndex = page * 12; + SDChannelObj* channel; + if (index >= 0 && index < 12 && + (channel = findChannelObject(page, index)) != NULL && channel->mState == 2 && + mpChannelTitleIds[pageTitleIndex + index] != 0) { + enqueueNotice(mpChannelTitleIds[pageTitleIndex + index], page, index); + } + + for (int channelIndex = firstIndex; channelIndex < 12; + channelIndex += indexStep) { + if (channelIndex != index && + (channel = findChannelObject(page, channelIndex)) != NULL && + channel->mState == 2 && + mpChannelTitleIds[pageTitleIndex + channelIndex] != 0) { + enqueueNotice(mpChannelTitleIds[pageTitleIndex + channelIndex], page, + channelIndex); + } + } + } + void SDChannelSelect::processWorkerState() { mPreviousSDState = mCurrentSDState; mCurrentSDState = mpSDWorker->get_sd_state(); @@ -761,7 +937,7 @@ namespace ipl { handleSDTitleList(); break; case 3: - handleCopyComplete(); + handleSDChannelUpdateComplete(); break; case 4: handleSDMountComplete(); @@ -1337,6 +1513,129 @@ namespace ipl { return mpLayout->FindPaneByName(mscChannelPaneNames[2][index]); } + void SDChannelSelect::createChannelList(int page, bool force) { + for (int index = 0; index < MAX_CHANNEL_INDEX; ++index) { + if (force || findChannelObject(page, index) == NULL) { + createChannelObject(page, index); + } + } + + if (page < mPageCount - 1) { + for (int index = 0; index < MAX_CHANNEL_INDEX; index += 4) { + if (force || findChannelObject(page + 1, index) == NULL) { + createChannelObject(page + 1, index); + } + } + } + + if (page > 0) { + for (int index = 3; index < MAX_CHANNEL_INDEX; index += 4) { + if (force || findChannelObject(page - 1, index) == NULL) { + createChannelObject(page - 1, index); + } + } + } + } + + void SDChannelSelect::destroyUnusedChannelObjects(int currentPage, + SDChannelObj* keepChannel) { + int keepPage; + int keepIndex; + if (keepChannel != NULL) { + keepPage = keepChannel->getPage(); + keepIndex = keepChannel->getIndex(); + } + + SDChannelObj* channel = NULL; + while (channel = static_cast( + nw4r::ut::List_GetNext(&mChannelObjects, channel)), + channel != NULL) { + int page = channel->getPage(); + int index = channel->getIndex(); + if (keepChannel != NULL && page == keepPage && index == keepIndex) { + continue; + } + if (mState < 0x18) { + if (mState >= 0xF && page == mSourcePage && index == mSourceIndex) { + continue; + } + } + if (!isChannelInCalc(page, index, currentPage)) { + SDChannelObj* previous = static_cast( + nw4r::ut::List_GetPrev(&mChannelObjects, channel)); + nw4r::ut::List_Remove(&mChannelObjects, channel); + destroyChannelObject(channel); + channel = previous; + } + } + } + + void SDChannelSelect::createChannelObject(int page, int index) { + EGG::FrmHeap* objectHeap = EGG::FrmHeap::create(0x212B8, mpLayoutHeap, 2); + SDChannelObj* channel = new (mpThumbnailHeap, 4) SDChannelObj(objectHeap, page, index); + nw4r::ut::List_Append(&mChannelObjects, channel); + } + + void SDChannelSelect::refreshChannelList() { + SDChannelObj* channel = NULL; + while (channel = static_cast( + nw4r::ut::List_GetNext(&mChannelObjects, channel)), + channel != NULL) { + if (iplSDChannelObj_813E3330(channel)) { + SDChannelObj* previous = static_cast( + nw4r::ut::List_GetPrev(&mChannelObjects, channel)); + nw4r::ut::List_Remove(&mChannelObjects, channel); + destroyChannelObject(channel); + channel = previous; + } else if (channel->mStateFlags == 2) { + channel->mStateFlags = 1; + } + } + + createChannelList(mCurrentPage, false); + if (mCurrentPage < mPageCount - 1) { + createChannelList(mCurrentPage + 1, false); + } + if (mCurrentPage > 0) { + createChannelList(mCurrentPage - 1, false); + } + updateChannelObjects(); + } + + void SDChannelSelect::refreshAfterSDTitleList() { + SDChannelObj* channel = NULL; + while (channel = static_cast( + nw4r::ut::List_GetNext(&mChannelObjects, channel)), + channel != NULL) { + int channelIndex = channel->mPage * 12 + channel->mIndex; + if (!iplSDChannelObj_813E3330(channel) && + mpChannelTitleIds[channelIndex] != 0) { + channel->mStateFlags = 2; + } + } + + clearNoticeQueue(); + updateChannelNotices(0, -1); + updateChannelNotices(-1, -1); + updateChannelNotices(1, -1); + updateChannelNotices(-2, -1); + updateChannelNotices(2, -1); + } + + SDChannelObj* SDChannelSelect::findChannelObject(int page, int index) const { + SDChannelObj* channel = NULL; + while (channel = static_cast( + nw4r::ut::List_GetNext(&mChannelObjects, channel)), + channel != NULL) { + if (page == channel->getPage()) { + if (index == channel->getIndex()) { + return channel; + } + } + } + return NULL; + } + math::VEC3 SDChannelSelect::getChannelPanePosition(SDChannelSelect* scene, int index) { math::VEC3 position(0.0f, 0.0f, 0.0f); MTXMultVec(scene->getCenterChannelPane(index)->GetGlobalMtx(), position, position); -- 2.49.1 From 313e396989c1bc8d4f0719633133bb4f4574fd2f Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Mon, 28 Sep 2026 23:57:13 -0500 Subject: [PATCH 40/61] sdmemory: continue decompilation (worker snapshot d94f5e95) (#254) --- config/43U/symbols.txt | 4 +- include/layout/iplLayout.h | 4 + include/scene/sdChannelMemory/iplSDMemory.h | 3 +- include/system/iplDialogWindow.h | 1 + src/scene/sdChannelMemory/iplSDMemory.cpp | 186 +++++++++++++++++++- 5 files changed, 190 insertions(+), 8 deletions(-) diff --git a/config/43U/symbols.txt b/config/43U/symbols.txt index 2679503c..db234d49 100644 --- a/config/43U/symbols.txt +++ b/config/43U/symbols.txt @@ -4881,12 +4881,12 @@ onDialogState23__Q33ipl5scene8SDMemoryFv = .text:0x813EEDF8; // type:function si onDialogState24__Q33ipl5scene8SDMemoryFv = .text:0x813EEE70; // type:function size:0xC0 iplSDMemory_813EEF30 = .text:0x813EEF30; // type:function size:0x88 iplSDMemory_813EEFB8 = .text:0x813EEFB8; // type:function size:0x70C -iplSDMemory_813EF6C4 = .text:0x813EF6C4; // type:function size:0x14 +writeFourFlagBytes__Q23ipl5sceneFPUcUcUcUcUc = .text:0x813EF6C4; // type:function size:0x14 iplSDMemory_813EF6D8 = .text:0x813EF6D8; // type:function size:0x48 GetBeginIter__Q34nw4r2ut28LinkListFv = .text:0x813EF720; // type:function size:0x8 iplSDMemory_813EF728 = .text:0x813EF728; // type:function size:0x8 __ne__Q24nw4r2utFQ44nw4r2ut28LinkList8IteratorQ44nw4r2ut28LinkList8Iterator = .text:0x813EF730; // type:function size:0x18 -iplSDMemory_813EF748 = .text:0x813EF748; // type:function size:0x74 +getControlPaneIndex__Q33ipl5scene8SDMemoryFPCc = .text:0x813EF748; // type:function size:0x74 iplSDMemory_813EF7BC = .text:0x813EF7BC; // type:function size:0x128 iplSDMemory_813EF8E4 = .text:0x813EF8E4; // type:function size:0xF0 iplSDMemory_813EF9D4 = .text:0x813EF9D4; // type:function size:0x120 diff --git a/include/layout/iplLayout.h b/include/layout/iplLayout.h index 46ab9cd3..cc14ecd0 100644 --- a/include/layout/iplLayout.h +++ b/include/layout/iplLayout.h @@ -180,7 +180,11 @@ namespace ipl { /*** TODO: These always generate a weak. Try and make them not do that. ***/ const nw4r::ut::Rect getTextDrawRect(const nw4r::lyt::TextBox* textBox) const { return textBox->GetTextDrawRect(mDrawInfo); } +#ifdef IPL_SDMEMORY_GET_TEXT_DRAW_RECT_OUT_OF_LINE + const nw4r::ut::Rect getTextDrawRect(const char* paneName) const; +#else const nw4r::ut::Rect getTextDrawRect(const char* paneName) const { return getTextDrawRect(nw4r::ut::DynamicCast(mLayout.GetRootPane()->FindPaneByName(paneName))); } +#endif const nw4r::ut::Rect getPaneRect(nw4r::lyt::Pane* pane) const { return pane->GetPaneRect(mDrawInfo); } const nw4r::ut::Rect getPaneRect(const char* paneName) const { return getPaneRect(mLayout.GetRootPane()->FindPaneByName(paneName)); } diff --git a/include/scene/sdChannelMemory/iplSDMemory.h b/include/scene/sdChannelMemory/iplSDMemory.h index 6352f88c..e4d3826d 100644 --- a/include/scene/sdChannelMemory/iplSDMemory.h +++ b/include/scene/sdChannelMemory/iplSDMemory.h @@ -13,7 +13,7 @@ namespace ipl { class SDMemory { public: struct TitleRange { - ESTitleId* mpTitles; + s32 mByteSize; u32 mCount; }; @@ -62,6 +62,7 @@ namespace ipl { void onDialogState23(); bool onDialogState24(); void resetDialogPaneAnimations(); + s32 getControlPaneIndex(const char* paneName); layout::Object* mpMainLayout; layout::Object* mpTitleLayout; diff --git a/include/system/iplDialogWindow.h b/include/system/iplDialogWindow.h index 5fe75217..59c707ca 100644 --- a/include/system/iplDialogWindow.h +++ b/include/system/iplDialogWindow.h @@ -121,6 +121,7 @@ namespace ipl { #ifdef IPL_SDMEMORY_DIALOG_STATE_ACCESSOR int getStateForSDMemory() const { return mState; } int getResultForSDMemory() const { return mResult; } + void setTitleForSDMemory(const wchar_t* text) { set_title(text); } #endif /*=================*/ diff --git a/src/scene/sdChannelMemory/iplSDMemory.cpp b/src/scene/sdChannelMemory/iplSDMemory.cpp index eb7cd7d3..ec77a71a 100644 --- a/src/scene/sdChannelMemory/iplSDMemory.cpp +++ b/src/scene/sdChannelMemory/iplSDMemory.cpp @@ -1,13 +1,27 @@ #define IPL_SDMEMORY_SCROLLER_INIT_OUT_OF_LINE #define IPL_SDMEMORY_SET_TRANSLATE_OUT_OF_LINE #define IPL_SDMEMORY_DIALOG_STATE_ACCESSOR +#define IPL_SDMEMORY_GET_TEXT_DRAW_RECT_OUT_OF_LINE #include "scene/sdChannelMemory/iplSDMemory.h" #undef IPL_SDMEMORY_DIALOG_STATE_ACCESSOR #undef IPL_SDMEMORY_SET_TRANSLATE_OUT_OF_LINE #undef IPL_SDMEMORY_SCROLLER_INIT_OUT_OF_LINE +#undef IPL_SDMEMORY_GET_TEXT_DRAW_RECT_OUT_OF_LINE #include "system/iplSystem.h" #include "sound/iplSound.h" +#include "utility/iplLayout.h" +#include + +extern "C" bool iplSDChannelSelect_813DDB74(ipl::scene::NandSDCardManager* manager, + ipl::scene::SDMemory::TitleRange* nandTitles, + ipl::scene::SDMemory::TitleRange* sdTitles, + ESTitleId* titleIds, wchar_t* titleNames, u32* titleCount, + s32 state); +extern "C" bool iplSDChannelSelect_813DB5EC(ipl::scene::NandSDCardManager* manager, + const ESTitleId* titleEntry, ESTitleId titleId); +extern "C" bool iplSDChannelSelect_813DB4D4(ipl::scene::NandSDCardManager* manager, + const ESTitleId* titleEntry, ESTitleId titleId, u32 flags); namespace ipl { namespace utility { @@ -22,9 +36,11 @@ namespace ipl { namespace scene { static const char* const sControlPaneNames[] = { - "A", "B", "B_BtnA", "A", "B", "C", "D", "B_BtnA", "B_00", "C_00", "D_00", "B_BtnA", + "A", "B", "B_BtnA", }; + static const char* const sTitlePaneNames[] = {"A", "B", "B_BtnA", "C", "D"}; + static const char* const sAdditionalTitlePaneNames[] = {"B_00", "C_00", "D_00", "B_BtnA"}; static const char* const sDialogPaneNames[] = {"B_ArwR", "B_ArwL", "B_CalExit", "B_CalExit_00"}; SDMemory::SDMemory() : mScroller() {} @@ -470,7 +486,8 @@ namespace ipl { if (!mpMainLayout->isPlaying(-1)) { for (int i = 0; i < 3; i++) { mPanelStates[i] = 0; - mpPaneManagers[0]->initPane(mpMainLayout->getNW4RLyt()->GetRootPane()->FindPaneByName(sControlPaneNames[i], true)); + nw4r::lyt::Pane* pane = mpMainLayout->FindPaneByName(sControlPaneNames[i]); + mpPaneManagers[0]->initPane(pane); } mDialogState = 1; @@ -492,17 +509,46 @@ namespace ipl { } } + bool SDMemory::onDialogState3() { + if (!mpMainLayout->isPlaying(-1)) { + switch (mProcessState) { + case 0: + if (iplSDChannelSelect_813DDB74(mpNandSDCardManager, &mNandTitleRange, &mSDTitleRange, + mTitleIds, &mTitleNames[0][0], &mTitleCount, 2)) { + mDialogState = 4; + mpTitleLayout->getAnim(0)->initAnmFrame(); + mpTitleLayout->getAnim(0)->play(); + snd::getSystem()->startSE("WIPL_SE_INFO_WINDOW"); + } else { + mDialogState = 21; + mMessageId = 0xB4; + } + break; + case 1: + mDialogState = 21; + mMessageId = 0xB3; + break; + case 2: + mDialogState = 25; + mErrorCode = 3; + return true; + } + } + + return false; + } + void SDMemory::onDialogState4() { if (!mpTitleLayout->isPlaying(-1)) { if (mDisplayMode == 4) { for (int i = 0; i < 5; i++) { mTitlePanelStates[i] = 0; - mpPaneManagers[1]->initPane(mpTitleLayout->FindPaneByName(sControlPaneNames[i + 3])); + mpPaneManagers[1]->initPane(mpTitleLayout->GetRootPane()->FindPaneByName(sTitlePaneNames[i], true)); } } else { for (int i = 1; i < 5; i++) { mTitlePanelStates[i] = 0; - mpPaneManagers[1]->initPane(mpTitleLayout->FindPaneByName(sControlPaneNames[i + 7])); + mpPaneManagers[1]->initPane(mpTitleLayout->GetRootPane()->FindPaneByName(sAdditionalTitlePaneNames[i - 1], true)); } } @@ -518,6 +564,52 @@ namespace ipl { } } + void SDMemory::onDialogState8() { + if (System::getDialog()->getStateForSDMemory() == 2) { + if (mTransferStartTime == 0) { + mTransferStartTime = OSGetTime(); + } + + if (!mpNandSDCardManager->getWorker()->is_working() && + OSGetTime() - mTransferStartTime > OS_TIMER_CLOCK) { + System::getDialog()->terminate(); + } + } + + if (System::getDialog()->getLastResult() != -1) { + if (mpNandSDCardManager->getWorker()->get_async_result() == 0) { + mNandTitleCount = mTitleListState.mSecondaryCount; + mTitleNameCount = mTitleListState.mNameCount; + } else { + mNandTitleCount = 0; + mTitleNameCount = 0; + } + + mDialogState = 9; + layout::Animator* animation = mpMainLayout->getAnim(0); + animation->initFrame(); + animation->restart(); + + nw4r::lyt::Pane* headerPane = mpMainLayout->FindPaneByName("T_Header"); + static_cast(headerPane)->SetString(System::getMessage(0xBE), 0); + + mButtonState = 0; + nw4r::lyt::Pane* titlePane = mpMainLayout->FindPaneByName("N_Body"); + nw4r::lyt::Pane* bodyPane = mpMainLayout->FindPaneByName("T_Letter"); + bodyPane->SetAlpha(0xFF); + + for (u32 i = 0; i < mTitleCount; i++) { + utility::layout::set_string(bodyPane, mTitleNames[i]); + nw4r::ut::Rect textRect = mpMainLayout->getTextDrawRect("T_Letter"); + f32 lineCount = -(textRect.bottom - textRect.top) / titlePane->GetSize().height; + mButtonState += static_cast(ceil(lineCount)); + } + + setScrollLimit(); + resetScrollArrows(); + } + } + void SDMemory::onDialogState7() { if (!mpTitleLayout->isPlaying(-1)) { switch (mProcessState) { @@ -536,11 +628,14 @@ namespace ipl { } } + + void SDMemory::onDialogState9() { if (!mpDialogLayout->isPlaying(0)) { for (int i = 0; i < 4; i++) { mPanelAnimationStates[i] = 0; - mpPaneManagers[2]->initPane(mpDialogLayout->getNW4RLyt()->GetRootPane()->FindPaneByName(sDialogPaneNames[i], true)); + nw4r::lyt::Pane* pane = mpDialogLayout->FindPaneByName(sDialogPaneNames[i]); + mpPaneManagers[2]->initPane(pane); } mDialogState = 10; @@ -589,6 +684,41 @@ namespace ipl { } } + void SDMemory::onDialogState16() { + if (mTitleCount > mCurrentTitle && System::isReceiveScheduleStopped()) { + const ESTitleId* titleEntry = &mTitleIds[mCurrentTitle]; + if (iplSDChannelSelect_813DB4D4(mpNandSDCardManager, titleEntry, *titleEntry, 0)) { + mDialogState = 16; + } else { + System::getDialog()->terminate(); + mDialogState = 20; + mErrorCode = 1; + mMessageId = 0xAE; + } + } + } + + void SDMemory::onDialogState18() { + if (System::getDialog()->getStateForSDMemory() == 2) { + mCurrentTitleName[0] = L'\0'; + const wchar_t* message = System::getMessage(0xB1); + const wchar_t* titleName = mTitleNames[mCurrentTitle]; + swprintf(mCurrentTitleName, 0x107f, L"%ls\n%ls", titleName, message); + System::getDialog()->setTitleForSDMemory(mCurrentTitleName); + + const ESTitleId* titleEntry = &mTitleIds[mCurrentTitle]; + const ESTitleId titleId = *titleEntry; + if (iplSDChannelSelect_813DB5EC(mpNandSDCardManager, titleEntry, titleId)) { + mDialogState = 18; + } else { + System::getDialog()->terminate(); + mDialogState = 20; + mErrorCode = 1; + mMessageId = 0xAE; + } + } + } + void SDMemory::onDialogState19() { if (!mpNandSDCardManager->getWorker()->is_working()) { if (mpNandSDCardManager->getWorker()->get_async_result() == 0) { @@ -623,6 +753,33 @@ namespace ipl { return false; } + void SDMemory::onDialogState21() { + const wchar_t* message = System::getMessage(mMessageId); + const wchar_t* blockCountMarker = wcsstr(message, L"***\n"); + wchar_t* format = new (System::getMem2App(), -32) wchar_t[0x400]; + wchar_t* dialogMessage = new (System::getMem2App(), -32) wchar_t[0x400]; + + if (blockCountMarker != NULL && message != NULL) { + format[0] = L'\0'; + wcsncat(format, message, static_cast(blockCountMarker - message) >> 1); + wcscat(format, L"%d"); + wcscat(format, blockCountMarker + 4); + + s32 blocks = mNandTitleRange.mByteSize / 0x20000; + if (mNandTitleRange.mByteSize % 0x20000 != 0) { + blocks++; + } + + swprintf(dialogMessage, 0x3ff, format, blocks); + } + + System::getDialog()->callBtn2NoShade(dialogMessage, 0xC8, 0xA5, false); + mDialogState = 22; + + delete[] format; + delete[] dialogMessage; + } + bool SDMemory::onDialogState22() { DialogWindow* dialog = System::getDialog(); if (dialog->getStateForSDMemory() == 3 && dialog->getResultForSDMemory() == 1) { @@ -677,5 +834,24 @@ namespace ipl { return false; } + + s32 SDMemory::getControlPaneIndex(const char* paneName) { + s32 paneIndex = -1; + for (s32 i = 0; i < 3; i++) { + if (strcmp(paneName, sControlPaneNames[i]) == 0) { + paneIndex = i; + break; + } + } + + return paneIndex; + } + + void writeFourFlagBytes(u8* flags, u8 first, u8 second, u8 third, u8 fourth) { + flags[0] = first; + flags[1] = second; + flags[2] = third; + flags[3] = fourth; + } } } -- 2.49.1 From dfea0005386b2aad18c4f7b325a383259f1234af Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 04:58:55 +0000 Subject: [PATCH 41/61] match setting ssid initialization --- src/scene/setting/iplSetting.cpp | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 9b510f56..c50982e8 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -1874,16 +1874,22 @@ namespace ipl { void Setting::initSecurityKey() { memset(mpStringBuffer->securityKey, 0, sizeof(mpStringBuffer->securityKey)); - u16 privacyMode = ncd::NCDSetting::getNCDPrivacyMode(); - size_t keyLength = 0; - if (privacyMode == 2) { - keyLength = 13; - } else if (privacyMode < 2) { - if (privacyMode == 1) { - keyLength = 5; + s32 privacyMode = ncd::NCDSetting::getNCDPrivacyMode(); + size_t keyLength; + if (privacyMode != 2) { + if (privacyMode < 2) { + if (privacyMode == 0) { + keyLength = 0; + } else { + keyLength = 5; + } + } else if (privacyMode < 7 && privacyMode > 3) { + keyLength = 64; + } else { + keyLength = 0; } - } else if (privacyMode > 3 && privacyMode < 7) { - keyLength = 64; + } else { + keyLength = 13; } if (keyLength != 0) { memcpy(mpStringBuffer->securityKey, ncd::NCDSetting::getPrivacy(), keyLength); @@ -1893,9 +1899,10 @@ namespace ipl { void Setting::initSSID() { memset(mpStringBuffer->ssid, 0, sizeof(mpStringBuffer->ssid)); - NCDApConfig* ssid = ncd::NCDSetting::getSSID(); - utility::CharacterCode::ANSIToUTF8(mpStringBuffer->ssid, ssid->ssid, ssid->ssidLength); - OSReport("initHTMLText initString:%s length:%d\n", ssid->ssid, ssid->ssidLength); + u16 stringLength = ncd::NCDSetting::getSSID()->ssidLength; + utility::CharacterCode::ANSIToUTF8(mpStringBuffer->ssid, ncd::NCDSetting::getSSID()->ssid, stringLength); + u16 reportLength = ncd::NCDSetting::getSSID()->ssidLength; + OSReport("initHTMLText initString:%s length:%d\n", ncd::NCDSetting::getSSID()->ssid, reportLength); } void Setting::initIP() { -- 2.49.1 From 35215ab46a7db809fb988dfd5ee3519d2c7a2561 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 05:00:12 +0000 Subject: [PATCH 42/61] match setting address initialization --- src/scene/setting/iplSetting.cpp | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index c50982e8..097f23a0 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -1909,18 +1909,16 @@ namespace ipl { memset(mpStringBuffer->ip.addr, 0, sizeof(mpStringBuffer->ip.addr)); memset(mpStringBuffer->ip.netmask, 0, sizeof(mpStringBuffer->ip.netmask)); memset(mpStringBuffer->ip.gateway, 0, sizeof(mpStringBuffer->ip.gateway)); - NCDIpProfile* ip = ncd::NCDSetting::getIP(); - convertIP(mpStringBuffer->ip.addr, ip->addr); - convertIP(mpStringBuffer->ip.netmask, ip->netmask); - convertIP(mpStringBuffer->ip.gateway, ip->gateway); + convertIP(mpStringBuffer->ip.addr, ncd::NCDSetting::getIP()->addr); + convertIP(mpStringBuffer->ip.netmask, ncd::NCDSetting::getIP()->netmask); + convertIP(mpStringBuffer->ip.gateway, ncd::NCDSetting::getIP()->gateway); } void Setting::initDNS() { memset(mpStringBuffer->dns1, 0, sizeof(mpStringBuffer->dns1)); memset(mpStringBuffer->dns2, 0, sizeof(mpStringBuffer->dns2)); - NCDIpProfile* ip = ncd::NCDSetting::getIP(); - convertIP(mpStringBuffer->dns1, ip->dns1); - convertIP(mpStringBuffer->dns2, ip->dns2); + convertIP(mpStringBuffer->dns1, ncd::NCDSetting::getIP()->dns1); + convertIP(mpStringBuffer->dns2, ncd::NCDSetting::getIP()->dns2); } void Setting::initProxy() { -- 2.49.1 From cccd77df26b4c25b3cd8281c1994285e335d4dd0 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 05:01:16 +0000 Subject: [PATCH 43/61] match setting proxy initialization --- src/scene/setting/iplSetting.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 097f23a0..ee611212 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -1924,17 +1924,18 @@ namespace ipl { void Setting::initProxy() { memset(mpStringBuffer->proxy.server, 0, sizeof(mpStringBuffer->proxy.server)); memset(mpStringBuffer->proxy.port, 0, sizeof(mpStringBuffer->proxy.port)); - NCDProxyProfile* proxy = ncd::NCDSetting::getProxy(); - memcpy(mpStringBuffer->proxy.server, proxy->http.server, sizeof(proxy->http.server)); - sprintf(mpStringBuffer->proxy.port, "%d", proxy->http.port); + memcpy(mpStringBuffer->proxy.server, ncd::NCDSetting::getProxy()->http.server, + sizeof(ncd::NCDSetting::getProxy()->http.server)); + sprintf(mpStringBuffer->proxy.port, "%d", ncd::NCDSetting::getProxy()->http.port); } void Setting::initBasic() { memset(mpStringBuffer->proxyBasic.uname, 0, sizeof(mpStringBuffer->proxyBasic.uname)); memset(mpStringBuffer->proxyBasic.pass, 0, sizeof(mpStringBuffer->proxyBasic.pass)); - NCDProxyProfile* proxy = ncd::NCDSetting::getProxy(); - memcpy(mpStringBuffer->proxyBasic.uname, proxy->http.username, sizeof(proxy->http.username)); - memcpy(mpStringBuffer->proxyBasic.pass, proxy->http.password, sizeof(proxy->http.password)); + memcpy(mpStringBuffer->proxyBasic.uname, ncd::NCDSetting::getProxy()->http.username, + sizeof(ncd::NCDSetting::getProxy()->http.username)); + memcpy(mpStringBuffer->proxyBasic.pass, ncd::NCDSetting::getProxy()->http.password, + sizeof(ncd::NCDSetting::getProxy()->http.password)); } void Setting::initMTU() { -- 2.49.1 From e261346445ef9e40ce264f7c934023bd54119849 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 05:02:45 +0000 Subject: [PATCH 44/61] match setting nickname save --- src/scene/setting/iplSetting.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index ee611212..56810d1c 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -1976,13 +1976,14 @@ namespace ipl { } void Setting::setNickName() { - SCOwnerNickname* nickname = reinterpret_cast(mSettingData); - nickname->length = wcslen(reinterpret_cast(unk_0x938)); + reinterpret_cast(mSettingData)->length = wcslen(reinterpret_cast(unk_0x938)); if (checkTextNum(mpStringBuffer->nickname) == 3) { - memset(nickname, 0, sizeof(*nickname)); - memcpy(nickname->name, unk_0x938, nickname->length * sizeof(wchar_t)); - BOOL written = SCSetOwnerNickName(nickname); - OSReport("nicknameFlag:1 %d %s\n", written, nickname->name); + memset(mSettingData, 0, sizeof(reinterpret_cast(mSettingData)->name)); + memcpy(mSettingData, unk_0x938, + reinterpret_cast(mSettingData)->length * sizeof(wchar_t)); + bool written = SCSetOwnerNickName(reinterpret_cast(mSettingData)) != 0; + OSReport("nicknameFlag:1 %d %s\n", written, + reinterpret_cast(mSettingData)->name); } } -- 2.49.1 From b7f4bc5900c7bb93f444f228ce384da39b48938d Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 05:04:32 +0000 Subject: [PATCH 45/61] match setting security and ssid writes --- src/scene/setting/iplSetting.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 56810d1c..7c7e6203 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -1989,14 +1989,14 @@ namespace ipl { void Setting::setSecurityKey() { int keyLength = ncd::NCDSetting::checkWEPKey(mpStringBuffer->securityKey); - if (keyLength < 0) { - System::getDialog()->callBtn0(0x1be, 0xb4, false); - unk_0x74 = 2; - www::wiisetting::setFuncResult(4); - } else { + if (keyLength >= 0) { www::wiisetting::setFuncResult(3); ncd::NCDSetting::setPrivacy(reinterpret_cast(mpStringBuffer->securityKey), keyLength); OSReport("securityFlag:1 %s\n", mpStringBuffer->securityKey); + } else { + System::getDialog()->callBtn0(0x1be, 0xb4, false); + unk_0x74 = 2; + www::wiisetting::setFuncResult(4); } } @@ -2004,6 +2004,7 @@ namespace ipl { u8 ssid[0x61]; memset(ssid, 0, sizeof(ssid)); utility::CharacterCode::UTF8ToANSI(ssid, mpStringBuffer->ssid); + memset(ssid + 0x20, 0, 0x41); ncd::NCDSetting::setSSID(ssid); } -- 2.49.1 From 5583b7b98e156b5568ca35cf860850425fece7cb Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 05:07:39 +0000 Subject: [PATCH 46/61] match setting proxy profile updates --- src/scene/setting/iplSetting.cpp | 33 +++++++++++++++----------------- 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 7c7e6203..692ee3cd 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -2027,11 +2027,11 @@ namespace ipl { void Setting::setProxy() { NCDProxyServerProfile proxy; - memset(&proxy, 0, sizeof(proxy)); + const char* portString = mpStringBuffer->proxy.port; wchar_t portText[6]; u32 port; memset(portText, 0, sizeof(portText)); - utility::CharacterCode::UTF8ToUTF16(portText, mpStringBuffer->proxy.port, 6); + utility::CharacterCode::UTF8ToUTF16(portText, portString, 6); utility::CharacterCode::UTF16ToU32(&port, portText); proxy.port = port; if (proxy.port == 0) { @@ -2039,38 +2039,35 @@ namespace ipl { System::getDialog()->callBtn0(0x1be, 0xb4, false); unk_0x74 = 2; } else { - int valid = ncd::NCDSetting::checkProxy(mpStringBuffer->proxy.server); - if (valid == 0) { - www::wiisetting::setFuncResult(4); - System::getDialog()->callBtn0(0x1be, 0xb4, false); - unk_0x74 = 2; - } else { + if (ncd::NCDSetting::checkProxy(mpStringBuffer->proxy.server) != 0) { www::wiisetting::setFuncResult(3); + memset(proxy.server, 0, sizeof(proxy.server)); utility::CharacterCode::UTF8ToANSI(reinterpret_cast(proxy.server), mpStringBuffer->proxy.server); ncd::NCDSetting::setProxy(&proxy); + } else { + www::wiisetting::setFuncResult(4); + System::getDialog()->callBtn0(0x1be, 0xb4, false); + unk_0x74 = 2; } } } void Setting::setBasic() { - int validUsername = ncd::NCDSetting::checkProxyBasic(mpStringBuffer->proxyBasic.uname); - int validPassword = validUsername == 0 - ? 0 - : ncd::NCDSetting::checkProxyBasic(mpStringBuffer->proxyBasic.pass); - if (validPassword == 0) { - www::wiisetting::setFuncResult(4); - System::getDialog()->callBtn0(0x1be, 0xb4, false); - unk_0x74 = 2; - } else { + if (ncd::NCDSetting::checkProxyBasic(mpStringBuffer->proxyBasic.uname) != 0 && + ncd::NCDSetting::checkProxyBasic(mpStringBuffer->proxyBasic.pass) != 0) { NCDProxyServerProfile proxy; - memset(&proxy, 0, sizeof(proxy)); www::wiisetting::setFuncResult(3); + memset(&proxy, 0, sizeof(proxy)); utility::CharacterCode::UTF8ToANSI(reinterpret_cast(proxy.username), mpStringBuffer->proxyBasic.uname); utility::CharacterCode::UTF8ToANSI(reinterpret_cast(proxy.password), mpStringBuffer->proxyBasic.pass); ncd::NCDSetting::setBasic(&proxy); + } else { + www::wiisetting::setFuncResult(4); + System::getDialog()->callBtn0(0x1be, 0xb4, false); + unk_0x74 = 2; } } -- 2.49.1 From 6d43e53bf643dc03a85f72bf913e55bd76750893 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 05:08:52 +0000 Subject: [PATCH 47/61] match setting mtu parsing --- src/scene/setting/iplSetting.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 692ee3cd..7a4ed202 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -2072,12 +2072,13 @@ namespace ipl { } void Setting::setMTU() { + const char* mtuString = mpStringBuffer->adjMtu; wchar_t mtuText[6]; - u32 mtu; + u32 parsedMtu; memset(mtuText, 0, sizeof(mtuText)); - utility::CharacterCode::UTF8ToUTF16(mtuText, mpStringBuffer->adjMtu, 6); - utility::CharacterCode::UTF16ToU32(&mtu, mtuText); - mtu &= 0xffff; + utility::CharacterCode::UTF8ToUTF16(mtuText, mtuString, 6); + utility::CharacterCode::UTF16ToU32(&parsedMtu, mtuText); + s32 mtu = parsedMtu & 0xffff; if (mtu < 0x240 || mtu > 0x5dc) { mtu = 0; } -- 2.49.1 From a78c46348358a711433cc69cd587f30236e27878 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 05:10:21 +0000 Subject: [PATCH 48/61] match parental password results --- src/scene/setting/iplSetting.cpp | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 7a4ed202..e8e01b50 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -2098,25 +2098,29 @@ namespace ipl { void Setting::setPareRePass() { char password[16]; - u8 result = 2; memset(password, 0, 5); + u8 result = 2; utility::CharacterCode::UTF8ToANSI(reinterpret_cast(password), mpStringBuffer->parentalRePass); - if (checkTextNum(password) == 3 && parental::Parental::checkPass(password)) { - result = 1; + if (checkTextNum(password) == 3) { + if (parental::Parental::checkPass(password)) { + result = 1; + } + www::wiisetting::setFuncResult(result); } - www::wiisetting::setFuncResult(result); memset(mpStringBuffer->parentalRePass, 0, 5); } void Setting::setPareJudgePass() { char password[16]; - u8 result = 2; memset(password, 0, 5); + u8 result = 2; utility::CharacterCode::UTF8ToANSI(reinterpret_cast(password), mpStringBuffer->parentalJudgePass); - if (checkTextNum(password) == 3 && parental::Parental::judgePass(password)) { - result = 1; + if (checkTextNum(password) == 3) { + if (parental::Parental::judgePass(password)) { + result = 1; + } + www::wiisetting::setFuncResult(result); } - www::wiisetting::setFuncResult(result); memset(mpStringBuffer->parentalJudgePass, 0, 5); } -- 2.49.1 From 686c9df4992241cea939b0719553fa5dc8dafddd Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 05:11:17 +0000 Subject: [PATCH 49/61] match parental security answer result --- src/scene/setting/iplSetting.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index e8e01b50..c86a6406 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -2141,10 +2141,12 @@ namespace ipl { utility::CharacterCode::UTF8ToUTF16(reinterpret_cast(unk_0x938), mpStringBuffer->parentalReSecA, 0x44); reAdjustSecA(); - if (checkTextNum(NULL) == 3 && parental::Parental::judgeSecA(reinterpret_cast(unk_0x938))) { - result = 1; + if (checkTextNum(NULL) == 3) { + if (parental::Parental::judgeSecA(reinterpret_cast(unk_0x938))) { + result = 1; + } + www::wiisetting::setFuncResult(result); } - www::wiisetting::setFuncResult(result); memset(unk_0x938, 0, sizeof(unk_0x938)); } -- 2.49.1 From e6ae2bda435e8a8ec242fa895dc56aff1dda9ad6 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 05:12:12 +0000 Subject: [PATCH 50/61] match master key result order --- src/scene/setting/iplSetting.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index c86a6406..0b5b878f 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -2152,8 +2152,8 @@ namespace ipl { void Setting::setMasterKey() { char masterKey[16]; - u8 result = 2; memset(masterKey, 0, 6); + u8 result = 2; if (checkTextNum(mpStringBuffer->masterKey) == 3) { utility::CharacterCode::UTF8ToANSI(reinterpret_cast(masterKey), mpStringBuffer->masterKey); if (parental::Parental::judgeMaster(masterKey)) { -- 2.49.1 From a4ad9c3234440bed7ae9f4f64a528a5774297820 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 05:21:28 +0000 Subject: [PATCH 51/61] improve setting text validation --- src/scene/setting/iplSetting.cpp | 66 ++++++++++++++++++++------------ 1 file changed, 41 insertions(+), 25 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 0b5b878f..b2ca7491 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -2165,11 +2165,20 @@ namespace ipl { } u8 Setting::checkTextNum(const char* text) { - u8 formId = mpWiiSettingData->data[0x36]; - u32 message = 0; + int formId = mpWiiSettingData->data[0x36]; u8 result = 4; + u32 message = 0; if (formId < 13) { - if (formId == 2) { + if (formId != 2) { + if (formId < 2) { + } else if (formId < 10) { + } else { + if (strlen(text) == 4) { + result = 3; + } + message = 0x1ba; + } + } else { size_t length = wcslen(reinterpret_cast(unk_0x938)); if (length == 0) { message = 0x1c0; @@ -2178,33 +2187,40 @@ namespace ipl { } else { message = 0x1c1; } - } else if (formId > 9) { - if (strlen(text) == 4) { - result = 3; - } - message = 0x1ba; } - } else if (formId == 15) { + } else if (formId != 15) { + if (formId <= 14) { + int region = System::getRegion(); + u32 minimum; + if (region == 6) { + minimum = 2; + } else if (region < 6) { + if (region == 0) { + minimum = 3; + } else { + minimum = 6; + } + } else { + if (region == 11) { + minimum = 3; + } else { + minimum = 6; + } + } + size_t length = wcslen(reinterpret_cast(unk_0x938)); + if (length < minimum) { + message = 0x1bb; + } else if (checkSpace()) { + result = 3; + } else { + message = 0x1c1; + } + } + } else { if (strlen(text) == 5) { result = 3; } message = 0x1bc; - } else if (formId <= 14) { - u32 region = System::getRegion(); - u32 minimum = 6; - if (region == 6) { - minimum = 2; - } else if (region == 0 || region == 11) { - minimum = 3; - } - size_t length = wcslen(reinterpret_cast(unk_0x938)); - if (length < minimum) { - message = 0x1bb; - } else if (checkSpace()) { - result = 3; - } else { - message = 0x1c1; - } } www::wiisetting::setFuncResult(result); if (result == 4) { -- 2.49.1 From 1bba091c6196913c816ddb54587e4362ac25946f Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 05:28:11 +0000 Subject: [PATCH 52/61] implement setting reverse ip conversion --- src/scene/setting/iplSetting.cpp | 42 +++++++++++++++++++++++--------- 1 file changed, 31 insertions(+), 11 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index b2ca7491..db1e6641 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -2249,23 +2249,43 @@ namespace ipl { void Setting::convertRevIP(u8* destination, const char* address) { char ascii[20]; + int count = 0; memset(ascii, 0, sizeof(ascii)); utility::CharacterCode::UTF8ToANSI(reinterpret_cast(ascii), address); - char* component = ascii; - u32 count = 0; - for (char* current = ascii;; ++current) { - if (*current == '.' || *current == 0) { - bool finished = *current == 0; - *current = 0; - u32 value = atoi(component); + char* converted = ascii; + int componentStart = 0; + u8* output = destination; + for (int index = 0; index < 0x10; ++index) { + u8 character = static_cast(converted[index]); + if (character == '.' || character == 0) { + if (character == 0) { + index = 0x10; + } + converted[index] = 0; + u32 value = atoi(converted + componentStart); if (value > 0xff) { value = 0xff; } - destination[count++] = value; - if (finished || count == 4) { - break; + if (count == 0) { + *output = value; + } else { + destination[1] = destination[2]; + destination[2] = destination[3]; + destination[3] = value; + } + componentStart = index + 1; + ++count; + ++output; + if (count == 3 && index != 0x10) { + value = atoi(converted + componentStart); + if (value > 0xff) { + value = 0xff; + } + destination[1] = destination[2]; + destination[2] = destination[3]; + destination[3] = value; + return; } - component = current + 1; } } } -- 2.49.1 From 35210c3a463325a47e65569eb4ef13b8039a5779 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 05:30:58 +0000 Subject: [PATCH 53/61] type setting text buffer as wide characters --- include/scene/setting/iplSetting.h | 4 ++++ src/scene/setting/iplSetting.cpp | 16 +++++++--------- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/include/scene/setting/iplSetting.h b/include/scene/setting/iplSetting.h index bce7698b..3351d64d 100644 --- a/include/scene/setting/iplSetting.h +++ b/include/scene/setting/iplSetting.h @@ -227,7 +227,11 @@ namespace ipl { u8 unk_0x92D[3]; int unk_0x930; www::wiisetting::SetStringBuf* mpStringBuffer; +#ifdef IPL_SETTING_IMPLEMENTATION + wchar_t unk_0x938[0x101]; +#else u8 unk_0x938[0x202]; +#endif u8 unk_0xB3A; u8 mBrowserCreated; keyboard::Manager::State mKeyboardState; diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index db1e6641..74fe65f3 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -2231,12 +2231,10 @@ namespace ipl { } bool Setting::checkSpace() { - const wchar_t* text = reinterpret_cast(unk_0x938); - while (*text != 0) { - if (*text != L' ' && *text != 0x3000) { + for (u32 i = 0; unk_0x938[i] != 0; ++i) { + if (unk_0x938[i] != L' ' && unk_0x938[i] != 0x3000) { return true; } - ++text; } return false; } @@ -2309,17 +2307,17 @@ namespace ipl { } void Setting::reAdjustSecA() { - wchar_t* text = reinterpret_cast(unk_0x938); + u32 i = 0; bool containsWideCharacter = false; - for (u32 i = 0; text[i] != 0; ++i) { - if (text[i] > 0x7f) { + for (; unk_0x938[i] != 0; ++i) { + if (unk_0x938[i] > 0x7f) { containsWideCharacter = true; break; } } - if (containsWideCharacter && wcslen(text) > 0x10) { + if (containsWideCharacter && wcslen(unk_0x938) > 0x10) { char secondLine[0x22]; - SettingSecAText* lines = reinterpret_cast(text); + SettingSecAText* lines = reinterpret_cast(unk_0x938); memcpy(secondLine, &lines->wrappedLine[1], 0x22); memcpy(lines->wrappedLine, secondLine, 0x22); } -- 2.49.1 From 3a8a5abca998b4215797e5045e5c572186d77c8a Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 05:36:52 +0000 Subject: [PATCH 54/61] match setting default back string --- src/scene/setting/iplSetting.cpp | 40 ++++++++++++++++++-------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 74fe65f3..b7c0e7e1 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -2326,58 +2326,64 @@ namespace ipl { void Setting::setDefaultBackString() { switch (mpWiiSettingData->data[0x11]) { case 1: - reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x15c)); + System::getKeyboard()->memoMgr()->setTitleText(System::getMessage(0x15c)); break; case 2: - reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x153)); + System::getKeyboard()->memoMgr()->setTitleText(System::getMessage(0x153)); break; case 3: - reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x152)); + System::getKeyboard()->memoMgr()->setTitleText(System::getMessage(0x152)); break; case 4: - reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x14d)); + System::getKeyboard()->memoMgr()->setTitleText(System::getMessage(0x14d)); break; case 5: - reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x150)); + System::getKeyboard()->memoMgr()->setTitleText(System::getMessage(0x150)); break; case 6: - reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x151)); + System::getKeyboard()->memoMgr()->setTitleText(System::getMessage(0x151)); break; case 7: - reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x14e)); + System::getKeyboard()->memoMgr()->setTitleText(System::getMessage(0x14e)); break; case 8: - reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x14f)); + System::getKeyboard()->memoMgr()->setTitleText(System::getMessage(0x14f)); break; case 10: - reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x154)); + System::getKeyboard()->memoMgr()->setTitleText(System::getMessage(0x154)); break; case 11: - reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x155)); + System::getKeyboard()->memoMgr()->setTitleText(System::getMessage(0x155)); break; case 12: - reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x156)); + System::getKeyboard()->memoMgr()->setTitleText(System::getMessage(0x156)); break; case 13: - reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x157)); + System::getKeyboard()->memoMgr()->setTitleText(System::getMessage(0x157)); break; case 14: - reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x158)); + System::getKeyboard()->memoMgr()->setTitleText(System::getMessage(0x158)); break; case 15: + System::getKeyboard()->memoMgr()->setTitleText(System::getMessage(0x159)); + break; case 16: + System::getKeyboard()->memoMgr()->setTitleText(System::getMessage(0x159)); + break; case 17: - reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x159)); + System::getKeyboard()->memoMgr()->setTitleText(System::getMessage(0x159)); break; case 18: + System::getKeyboard()->memoMgr()->setTitleText(System::getMessage(0x15a)); + break; case 19: - reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x15a)); + System::getKeyboard()->memoMgr()->setTitleText(System::getMessage(0x15a)); break; case 20: - reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x15b)); + System::getKeyboard()->memoMgr()->setTitleText(System::getMessage(0x15b)); break; case 22: - reinterpret_cast(System::getKeyboard()->memoFrm())->setString(System::getMessage(0x153)); + System::getKeyboard()->memoMgr()->setTitleText(System::getMessage(0x153)); break; } } -- 2.49.1 From 8e254f1c883d7e75d5fa33d19455fff87625464b Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 00:39:13 -0500 Subject: [PATCH 55/61] wad: refine import/backup paths (21/40) (#255) --- libs/RVL_SDK/src/wad/wad.c | 100 ++++++++++++++++++++----------------- 1 file changed, 53 insertions(+), 47 deletions(-) diff --git a/libs/RVL_SDK/src/wad/wad.c b/libs/RVL_SDK/src/wad/wad.c index 43373a86..33835973 100644 --- a/libs/RVL_SDK/src/wad/wad.c +++ b/libs/RVL_SDK/src/wad/wad.c @@ -232,7 +232,7 @@ static s32 _WADBackupGetFiles(const char* path, u32 flags, MEMAllocator* allocat u32* fileCount, WADBackupFileHeader* files); static s32 _WADBackupGetSize(u32 flags, ESTmdView* titleMeta, ESContentMask* contentMask, u32 fileCount, WADBackupFileHeader* files, u32* titleMetaSize, - u32* contentDataSize, u32* totalSize); + u32* contentDataSize, u32* fileDataSize, u32* totalSize); static s32 _WADCheckContents(ESTmdView* titleMeta, ESContentMask* contentMask); static void _WADRandPad(void* buffer, u32 size); static s32 _WADVerifySavedataZD(WADSaveDataHeader* header, WADStream* stream, @@ -432,14 +432,14 @@ s32 WADImportGetBlocks(char* path, MEMAllocator* allocator, WADLocation location blocks->unkBlocks += (workspace.unpackInfo.sectionSize + 0x3FFF) >> 14; blocks->unkInodes = 1; } - if (workspace.unpackInfo.cidxMode < 1) { - contentCount = titleMeta->head.numContents; - } else { + if (workspace.unpackInfo.cidxMode >= 1) { contentCount = _WADGetCidxCount(workspace.unpackInfo.contentIndex); if (contentCount > titleMeta->head.numContents) { result = -3001; goto cleanup; } + } else { + contentCount = titleMeta->head.numContents; } contentMeta = titleMeta->contents; for (index = 0; index < contentCount; index++) { @@ -453,12 +453,12 @@ s32 WADImportGetBlocks(char* path, MEMAllocator* allocator, WADLocation location contentMeta = titleMeta->contents + selectedIndex; result = 0; } - if ((contentMeta->type & 0x8000) == 0) { - blocks->privateInodes++; - blocks->privateBlocks += ((u32)contentMeta->size + 0x3FFF) >> 14; - } else { + if ((contentMeta->type & 0x8000) != 0) { blocks->sharedInodes++; blocks->sharedBlocks += ((u32)contentMeta->size + 0x3FFF) >> 14; + } else { + blocks->privateInodes++; + blocks->privateBlocks += ((u32)contentMeta->size + 0x3FFF) >> 14; } contentMeta++; } @@ -1338,7 +1338,7 @@ s32 WADBackupEx(u64 titleId, u32 ticketId, MEMAllocator* allocator, char* path, } } result = _WADBackupGetSize(flags, titleMeta, &existingContentMask, fileCount, files, - &titleMetaSize, &contentDataSize, &fileDataSize); + &titleMetaSize, &contentDataSize, &fileDataSize, &totalSize); if (result != 0) { goto cleanup; } @@ -1346,9 +1346,8 @@ s32 WADBackupEx(u64 titleId, u32 ticketId, MEMAllocator* allocator, char* path, result = -3002; goto cleanup; } - totalSize = titleMetaSize + contentDataSize + fileDataSize + 0x340; if (path == 0) { - *sizeOut = totalSize; + *sizeOut = totalSize + 0x340; result = 0; goto cleanup; } @@ -1794,48 +1793,51 @@ s32 _WADGetCidxCount(const ESContentMask* contentMask) { if ((contentMask->data[bitIndex >> 3] & (1 << (bitIndex & 7))) != 0) { count++; } - if ((contentMask->data[(bitIndex + 1) >> 3] & (1 << ((bitIndex + 1) & 7))) != 0) { + bitIndex++; + if ((contentMask->data[bitIndex >> 3] & (1 << (bitIndex & 7))) != 0) { count++; } - if ((contentMask->data[(bitIndex + 2) >> 3] & (1 << ((bitIndex + 2) & 7))) != 0) { + bitIndex++; + if ((contentMask->data[bitIndex >> 3] & (1 << (bitIndex & 7))) != 0) { count++; } - if ((contentMask->data[(bitIndex + 3) >> 3] & (1 << ((bitIndex + 3) & 7))) != 0) { + bitIndex++; + if ((contentMask->data[bitIndex >> 3] & (1 << (bitIndex & 7))) != 0) { count++; } - bitIndex += 4; + bitIndex++; } return count; } static s32 _WADGetCidx(const ESContentMask* contentMask, u32 contentNumber) { u32 remaining = contentNumber + 1; - u32 bitIndex = 0; - u32 nextIndex; + s32 bitIndex = 0; + s32 nextIndex; for (bitIndex = 0; bitIndex < 0x200; bitIndex += 4) { - if ((contentMask->data[(s32)bitIndex >> 3] & (1 << (bitIndex & 7))) != 0) { + if ((contentMask->data[bitIndex >> 3] & (1 << (bitIndex & 7))) != 0) { remaining--; } if (remaining == 0) { return bitIndex; } nextIndex = bitIndex + 1; - if ((contentMask->data[(s32)nextIndex >> 3] & (1 << (nextIndex & 7))) != 0) { + if ((contentMask->data[nextIndex >> 3] & (1 << (nextIndex & 7))) != 0) { remaining--; } if (remaining == 0) { return nextIndex; } nextIndex = bitIndex + 2; - if ((contentMask->data[(s32)nextIndex >> 3] & (1 << (nextIndex & 7))) != 0) { + if ((contentMask->data[nextIndex >> 3] & (1 << (nextIndex & 7))) != 0) { remaining--; } if (remaining == 0) { return nextIndex; } nextIndex = bitIndex + 3; - if ((contentMask->data[(s32)nextIndex >> 3] & (1 << (nextIndex & 7))) != 0) { + if ((contentMask->data[nextIndex >> 3] & (1 << (nextIndex & 7))) != 0) { remaining--; } if (remaining == 0) { @@ -2041,8 +2043,8 @@ cleanup: static s32 _WADBackupGetSize(u32 flags, ESTmdView* titleMeta, ESContentMask* contentMask, u32 fileCount, WADBackupFileHeader* files, u32* titleMetaSize, - u32* contentDataSize, u32* fileDataSize) { - u32 titleSize = 0; + u32* contentDataSize, u32* fileDataSize, u32* totalSize) { + u32 titleSize = 0x80; u32 contentSize = 0; u32 filesSize = 0; u32 selectedCount; @@ -2050,26 +2052,26 @@ static s32 _WADBackupGetSize(u32 flags, ESTmdView* titleMeta, ESContentMask* con u32 fileIndex; s32 result = 0; - if (titleMeta == 0) { - if (titleMetaSize != 0) { - *titleMetaSize = 0; - } - } else if (((flags & 1) != 0) || ((flags & 0x20) != 0)) { - result = ES_GetTmdSizeFromView(titleMeta, &titleSize); - if (result != 0) { - return result; - } - titleSize = (titleSize + 0x3F) & ~0x3F; - } - if (((flags & 1) != 0) && (titleMeta != 0)) { - selectedCount = _WADGetCidxCount(contentMask); - for (contentIndex = 0; contentIndex < selectedCount; contentIndex++) { - s32 tmdIndex = _WADGetCidx(contentMask, contentIndex); - if ((tmdIndex < 0) || (titleMeta->head.numContents <= tmdIndex)) { - return -3009; + if ((titleMeta != 0) && (titleMetaSize != 0)) { + if (((flags & 1) != 0) || ((flags & 0x20) != 0)) { + result = ES_GetTmdSizeFromView(titleMeta, titleMetaSize); + if (result != 0) { + return result; } - contentSize += (titleMeta->contents[tmdIndex].size + 0x3F) & ~0x3F; + titleSize += (*titleMetaSize + 0x3F) & ~0x3F; } + if ((flags & 1) != 0) { + selectedCount = _WADGetCidxCount(contentMask); + for (contentIndex = 0; contentIndex < selectedCount; contentIndex++) { + s32 tmdIndex = _WADGetCidx(contentMask, contentIndex); + if ((tmdIndex < 0) || (titleMeta->head.numContents <= tmdIndex)) { + return -3009; + } + contentSize += (titleMeta->contents[tmdIndex].size + 0x3F) & ~0x3F; + } + } + } else if ((titleMeta == 0) && (titleMetaSize != 0)) { + *titleMetaSize = 0; } if ((fileCount != 0) && (files != 0)) { for (fileIndex = 0; fileIndex < fileCount; fileIndex++) { @@ -2085,6 +2087,9 @@ static s32 _WADBackupGetSize(u32 flags, ESTmdView* titleMeta, ESContentMask* con if (fileDataSize != 0) { *fileDataSize = filesSize; } + if (totalSize != 0) { + *totalSize = titleSize + contentSize + filesSize; + } return result; } #pragma dont_inline reset @@ -2998,13 +3003,13 @@ s32 WADImportDVDForBS(const char* path, void* buffer, u32 bufferSize) { DVDFileInfo fileInfo; WADBootImportParts parts; WADHeader* header; - ESTitleMeta* titleMeta; - u8* readBuffer = buffer; + u8* readBuffer; + BOOL fileOpened = FALSE; + ESTitleMeta* titleMeta = 0; void* applicationData; u32 paddedFileSize; u32 sectionOffset; u32 applicationSize; - BOOL fileOpened = FALSE; s32 result; if ((path == 0) || (buffer == 0)) { @@ -3015,6 +3020,7 @@ s32 WADImportDVDForBS(const char* path, void* buffer, u32 bufferSize) { return -3004; } fileOpened = TRUE; + readBuffer = buffer; paddedFileSize = (fileInfo.length + 0x1F) & ~0x1F; if (paddedFileSize > bufferSize) { result = -3003; @@ -3057,10 +3063,10 @@ s32 WADImportDVDForBS(const char* path, void* buffer, u32 bufferSize) { } if (header->tmdSize != 0) { parts.titleMetaSize = header->tmdSize; - parts.titleMeta = readBuffer + sectionOffset; + titleMeta = (ESTitleMeta*)(readBuffer + sectionOffset); + parts.titleMeta = titleMeta; sectionOffset += (header->tmdSize + 0x3F) & ~0x3F; } - titleMeta = parts.titleMeta; applicationSize = ((u32)titleMeta->contents[0].size + 0xF) & ~0xF; applicationData = readBuffer + sectionOffset; if ((titleMeta != 0) && (titleMeta->head.titleId == ES_TITLE_ID(1, 1))) { @@ -3093,8 +3099,8 @@ cleanup: s32 WADImportDVDExForBS(const char* path, void* buffer, u32 bufferSize) { WADHeader header ALIGN32; - WADBootImportParts parts; DVDFileInfo fileInfo; + WADBootImportParts parts; u8* readBuffer = buffer; u8* contentBuffer; ESTitleMeta* titleMeta; -- 2.49.1 From 8aeb23f37a75d5889fd1ea6ecdf0003964f40fa2 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 05:46:42 +0000 Subject: [PATCH 56/61] improve setting safe mode match --- src/scene/setting/iplSetting.cpp | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index b7c0e7e1..7eef40e4 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -2401,18 +2401,18 @@ namespace ipl { if (System::getNwc24Manager() != NULL) { return true; } - if (unk_0x94 == 1) { - if (System::getDialog()->getLastResult() >= 0) { - unk_0xB9C = 1; - unk_0x74 = 0; - unk_0x94 = 0; + if (unk_0x94 != 1) { + if (unk_0x94 < 1 && unk_0x94 >= 0) { + resetFuncMsgQ(); + System::getDialog()->callBtn1(0x21, 0x2e); + www::wiisetting::setFuncResult(2); + unk_0x74 = 0x11; + unk_0x94 = 1; } - } else if (unk_0x94 == 0) { - resetFuncMsgQ(); - System::getDialog()->callBtn1(0x21, 0x2e); - www::wiisetting::setFuncResult(2); - unk_0x74 = 0x11; - unk_0x94 = 1; + } else if (System::getDialog()->getLastResult() >= 0) { + unk_0xB9C = 1; + unk_0x74 = 0; + unk_0x94 = 0; } return false; } -- 2.49.1 From 020cfa2f8e577118e596b299d492d65afac76816 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 05:49:43 +0000 Subject: [PATCH 57/61] match setting access point reset --- src/scene/setting/iplSetting.cpp | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 7eef40e4..dd9cf588 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -2424,19 +2424,23 @@ namespace ipl { } void Setting::resetAP() { - mpChangeLayout->getAnim(0x15)->initFrame(); - mpChangeLayout->getAnim(0x15)->restart(); + layout::Animator* animation = mpMainLayout->getAnim(0x15); + animation->initFrame(); + animation->restart(); if (unk_0x914 != 0) { - mpChangeLayout->getAnim(2)->initFrame(); - mpChangeLayout->getAnim(2)->restart(); + animation = mpMainLayout->getAnim(2); + animation->initFrame(); + animation->restart(); } if (mAPScanList.count != unk_0x914 + 4) { - mpChangeLayout->getAnim(3)->initFrame(); - mpChangeLayout->getAnim(3)->restart(); + animation = mpMainLayout->getAnim(3); + animation->initFrame(); + animation->restart(); } - for (int animation = 0x10; animation < 0x14; ++animation) { - mpChangeLayout->getAnim(animation)->initFrame(); - mpChangeLayout->getAnim(animation)->restart(); + for (int index = 0x10; index <= 0x13; ++index) { + animation = mpMainLayout->getAnim(index); + animation->initFrame(); + animation->restart(); } initAP(); unk_0x918 = 0x15; -- 2.49.1 From acd26ecda512988df50593206c1495e669c07476 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 05:50:35 +0000 Subject: [PATCH 58/61] match setting access point redraw --- src/scene/setting/iplSetting.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index dd9cf588..2df27e7a 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -2453,12 +2453,13 @@ namespace ipl { unk_0x914 = 0; unk_0x918 = -1; mpWiiSettingFlag->smthMsgData = 3; - mpChangeLayout->getAnim(0x14)->initFrame(); - for (int animation = 0x10; animation < 0x14; ++animation) { - mpChangeLayout->getAnim(animation)->initFrame(); - mpChangeLayout->getAnim(animation)->restart(); + mpMainLayout->getAnim(0x14)->initFrame(); + for (int index = 0x10; index <= 0x13; ++index) { + layout::Animator* animation = mpMainLayout->getAnim(index); + animation->initFrame(); + animation->restart(); } - mpChangeLayout->calc(); + mpMainLayout->calc(); unk_0x91C[2] = 0; } -- 2.49.1 From caf667565d2e7fe9cc4759658029fb20c6892de1 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 06:03:33 +0000 Subject: [PATCH 59/61] match setting access point events --- src/scene/setting/iplSetting.cpp | 173 +++++++++++++++++-------------- 1 file changed, 98 insertions(+), 75 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 2df27e7a..023d10c0 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -2482,9 +2482,9 @@ namespace ipl { if (mAPScanList.count == 0) { www::wiisetting::setFuncResult(2); initAP(); - mpChangeLayout->getAnim(0x14)->initAnmFrame(); - mpChangeLayout->getAnim(0)->initAnmFrame(); - mpChangeLayout->getAnim(1)->initAnmFrame(); + mpMainLayout->getAnim(0x14)->initAnmFrame(); + mpMainLayout->getAnim(0)->initAnmFrame(); + mpMainLayout->getAnim(1)->initAnmFrame(); } else { www::wiisetting::setFuncResult(1); setAPDraw(); @@ -2511,27 +2511,27 @@ namespace ipl { break; case 6: unk_0xB9C = 1; - if (!mpChangeLayout->getAnim(unk_0x918)->isPlaying()) { + if (!mpMainLayout->getAnim(unk_0x918)->isPlaying()) { unk_0x78 = 5; setAPDraw(); - mpChangeLayout->getAnim(unk_0x91C[0] == 0 ? 0xb : 0xa)->initAnmFrame(); + mpMainLayout->getAnim(unk_0x91C[0] == 0 ? 0xb : 0xa)->initAnmFrame(); if (unk_0x914 == 0) { - mpChangeLayout->FindPaneByName(sSettingAPNumberNames[0])->SetVisible(false); + mpMainLayout->FindPaneByName(sSettingAPNumberNames[0])->SetVisible(false); } else if (unk_0x914 == 1) { - mpChangeLayout->FindPaneByName(sSettingAPNumberNames[0])->SetVisible(true); + mpMainLayout->FindPaneByName(sSettingAPNumberNames[0])->SetVisible(true); } if (mAPScanList.count == unk_0x914 + 4) { - mpChangeLayout->FindPaneByName(sSettingAPNumberNames[1])->SetVisible(false); + mpMainLayout->FindPaneByName(sSettingAPNumberNames[1])->SetVisible(false); } else if (mAPScanList.count == unk_0x914 + 5) { - mpChangeLayout->FindPaneByName(sSettingAPNumberNames[1])->SetVisible(true); + mpMainLayout->FindPaneByName(sSettingAPNumberNames[1])->SetVisible(true); } - mpChangeLayout->FindPaneByName(sSettingAPTextNames[0])->SetVisible(true); - mpChangeLayout->FindPaneByName(sSettingAPTextNames[1])->SetVisible(true); + mpMainLayout->FindPaneByName(sSettingAPTextNames[0])->SetVisible(true); + mpMainLayout->FindPaneByName(sSettingAPTextNames[1])->SetVisible(true); } break; case 7: unk_0xB9C = 1; - if (!mpChangeLayout->getAnim(unk_0x918)->isPlaying()) { + if (!mpMainLayout->getAnim(unk_0x918)->isPlaying()) { updateScroll(); unk_0x78 = 6; } @@ -2541,13 +2541,13 @@ namespace ipl { unk_0x91C[2] = 0; break; case 9: - if (!mpChangeLayout->getAnim(unk_0x918)->isPlaying()) { + if (!mpMainLayout->getAnim(unk_0x918)->isPlaying()) { resetFuncMsgQ(); unk_0x78 = 1; unk_0x918 = -1; mpPaneManager->update(); - mpChangeLayout->getAnim(0x14)->initFrame(); - mpChangeLayout->calc(); + mpMainLayout->getAnim(0x14)->initFrame(); + mpMainLayout->calc(); } break; } @@ -2558,40 +2558,40 @@ namespace ipl { return; } for (int index = 1; index <= 4; ++index) { - mpChangeLayout->FindPaneByName(sSettingAPNumberNames[index])->SetVisible(true); + mpMainLayout->FindPaneByName(sSettingAPNumberNames[index])->SetVisible(true); } u16 count = mAPScanList.count; if (count == 2) { - mpChangeLayout->FindPaneByName(sSettingAPNumberNames[3])->SetVisible(false); + mpMainLayout->FindPaneByName(sSettingAPNumberNames[3])->SetVisible(false); } else if (count < 2) { if (count == 0) { - mpChangeLayout->FindPaneByName(sSettingAPNumberNames[1])->SetVisible(false); + mpMainLayout->FindPaneByName(sSettingAPNumberNames[1])->SetVisible(false); } - mpChangeLayout->FindPaneByName(sSettingAPNumberNames[2])->SetVisible(false); - mpChangeLayout->FindPaneByName(sSettingAPNumberNames[3])->SetVisible(false); + mpMainLayout->FindPaneByName(sSettingAPNumberNames[2])->SetVisible(false); + mpMainLayout->FindPaneByName(sSettingAPNumberNames[3])->SetVisible(false); } if (count < 4) { for (int index = 4; index < 6; ++index) { - mpChangeLayout->FindPaneByName(sSettingAPNumberNames[index])->SetVisible(false); + mpMainLayout->FindPaneByName(sSettingAPNumberNames[index])->SetVisible(false); } - mpChangeLayout->FindPaneByName("N_AP7")->SetVisible(false); + mpMainLayout->FindPaneByName("N_AP7")->SetVisible(false); } - mpChangeLayout->getAnim(0x14)->initFrame(); - mpChangeLayout->getAnim(0x14)->restart(); - mpChangeLayout->getAnim(0)->initAnmFrame(); - mpChangeLayout->FindPaneByName(sSettingAPPaneNames[0])->SetVisible(false); - mpChangeLayout->FindPaneByName(sSettingAPPaneNames[1])->SetVisible(false); + mpMainLayout->getAnim(0x14)->initFrame(); + mpMainLayout->getAnim(0x14)->restart(); + mpMainLayout->getAnim(0)->initAnmFrame(); + mpMainLayout->FindPaneByName(sSettingAPPaneNames[0])->SetVisible(false); + mpMainLayout->FindPaneByName(sSettingAPPaneNames[1])->SetVisible(false); if (count > unk_0x914 + 4) { - mpChangeLayout->FindPaneByName(sSettingAPPaneNames[3])->SetVisible(true); - mpChangeLayout->getAnim(1)->initFrame(); - mpChangeLayout->getAnim(1)->restart(); + mpMainLayout->FindPaneByName(sSettingAPPaneNames[3])->SetVisible(true); + mpMainLayout->getAnim(1)->initFrame(); + mpMainLayout->getAnim(1)->restart(); for (int index = 1; index < 6; ++index) { - mpChangeLayout->FindPaneByName(sSettingAPNumberNames[index])->SetVisible(true); + mpMainLayout->FindPaneByName(sSettingAPNumberNames[index])->SetVisible(true); } } else { - mpChangeLayout->FindPaneByName(sSettingAPPaneNames[3])->SetVisible(false); + mpMainLayout->FindPaneByName(sSettingAPPaneNames[3])->SetVisible(false); for (int index = count + 1; index < 6; ++index) { - mpChangeLayout->FindPaneByName(sSettingAPNumberNames[index])->SetVisible(false); + mpMainLayout->FindPaneByName(sSettingAPNumberNames[index])->SetVisible(false); } } unk_0x78 = 6; @@ -2603,33 +2603,46 @@ namespace ipl { if (unk_0x91C[0] == 0) { --unk_0x914; if (unk_0x914 == 0) { - mpChangeLayout->getAnim(2)->initFrame(); - mpChangeLayout->getAnim(2)->restart(); - mpChangeLayout->FindPaneByName(sSettingAPPaneNames[0])->SetVisible(false); + layout::Animator* animation = mpMainLayout->getAnim(2); + animation->initFrame(); + animation->restart(); + mpMainLayout->FindPaneByName(sSettingAPPaneNames[0])->SetVisible(false); + for (int point = 0; point < 8; ++point) { + mpPaneManager->getPaneComponentByPane( + mpMainLayout->FindPaneByName(sSettingAPPaneNames[0]))->setPointed(point, false); + } } if (mAPScanList.count == unk_0x914 + 5) { - mpChangeLayout->getAnim(1)->initFrame(); - mpChangeLayout->getAnim(1)->restart(); - mpChangeLayout->FindPaneByName(sSettingAPPaneNames[1])->SetVisible(true); + layout::Animator* animation = mpMainLayout->getAnim(1); + animation->initFrame(); + animation->restart(); + mpMainLayout->FindPaneByName(sSettingAPPaneNames[1])->SetVisible(true); } } else { - int previous = unk_0x914++; - if (mAPScanList.count == previous + 5) { - mpChangeLayout->getAnim(3)->initFrame(); - mpChangeLayout->getAnim(3)->restart(); - mpChangeLayout->FindPaneByName(sSettingAPPaneNames[1])->SetVisible(false); + ++unk_0x914; + if (mAPScanList.count == unk_0x914 + 4) { + layout::Animator* animation = mpMainLayout->getAnim(3); + animation->initFrame(); + animation->restart(); + mpMainLayout->FindPaneByName(sSettingAPPaneNames[1])->SetVisible(false); + for (int point = 0; point < 8; ++point) { + mpPaneManager->getPaneComponentByPane( + mpMainLayout->FindPaneByName(sSettingAPPaneNames[1]))->setPointed(point, false); + } } if (unk_0x914 == 1) { - mpChangeLayout->getAnim(0)->initFrame(); - mpChangeLayout->getAnim(0)->restart(); - mpChangeLayout->FindPaneByName(sSettingAPPaneNames[0])->SetVisible(true); + layout::Animator* animation = mpMainLayout->getAnim(0); + animation->initFrame(); + animation->restart(); + mpMainLayout->FindPaneByName(sSettingAPPaneNames[0])->SetVisible(true); } } - mpChangeLayout->getAnim(10)->stop(); - mpChangeLayout->getAnim(11)->stop(); + mpMainLayout->getAnim(10)->stop(); + mpMainLayout->getAnim(11)->stop(); unk_0x918 = unk_0x91C[0] + 10; - mpChangeLayout->getAnim(unk_0x918)->initFrame(); - mpChangeLayout->getAnim(unk_0x918)->restart(); + layout::Animator* animation = mpMainLayout->getAnim(unk_0x918); + animation->initFrame(); + animation->restart(); } void Setting::setAPDraw() { @@ -2640,8 +2653,8 @@ namespace ipl { return; } descriptor = reinterpret_cast(mAPScanList.entries + recordOffset - 2); - mpChangeLayout->getAnim(10)->stop(); - mpChangeLayout->getAnim(11)->stop(); + mpMainLayout->getAnim(10)->stop(); + mpMainLayout->getAnim(11)->stop(); int privacyMode = WDGetPrivacyMode(descriptor); char ssid[0x21]; wchar_t displayName[0x21]; @@ -2652,23 +2665,23 @@ namespace ipl { if (row >= 0 && row < 6) { utility::CharacterCode::UTF8ToUTF16(displayName, ssid, 0x21); nw4r::lyt::TextBox* textBox = static_cast( - mpChangeLayout->FindPaneByName(sSettingAPTextNames[row])); + mpMainLayout->FindPaneByName(sSettingAPTextNames[row])); textBox->SetString(displayName); if (privacyMode == 0) { - mpChangeLayout->getAnim(row + 0x2e)->initFrame(); - mpChangeLayout->getAnim(row + 0x2e)->restart(); - mpChangeLayout->getAnim(row + 0x34)->stop(); + mpMainLayout->getAnim(row + 0x2e)->initFrame(); + mpMainLayout->getAnim(row + 0x2e)->restart(); + mpMainLayout->getAnim(row + 0x34)->stop(); } else { - mpChangeLayout->getAnim(row + 0x34)->initFrame(); - mpChangeLayout->getAnim(row + 0x34)->restart(); - mpChangeLayout->getAnim(row + 0x2e)->stop(); + mpMainLayout->getAnim(row + 0x34)->initFrame(); + mpMainLayout->getAnim(row + 0x34)->restart(); + mpMainLayout->getAnim(row + 0x2e)->stop(); } for (int animation = row + 0x16; animation <= row + 0x28; animation += 6) { - mpChangeLayout->getAnim(animation)->stop(); + mpMainLayout->getAnim(animation)->stop(); } int signal = getRadioLevel(descriptor); - mpChangeLayout->getAnim(row + signal * 6 + 0x16)->initFrame(); - mpChangeLayout->getAnim(row + signal * 6 + 0x16)->restart(); + mpMainLayout->getAnim(row + signal * 6 + 0x16)->initFrame(); + mpMainLayout->getAnim(row + signal * 6 + 0x16)->restart(); } recordOffset += descriptor->length * 2; } @@ -2694,14 +2707,24 @@ namespace ipl { void Setting::start_point_event(const char* pageName) { int accessPoint = get_ap_no(pageName); - mpChangeLayout->getAnim(10)->stop(); - mpChangeLayout->getAnim(11)->stop(); - int animation = accessPoint == -1 ? get_arw_no(pageName) + 4 : accessPoint + 0xc; - if (accessPoint == -1 && animation == 3) { + mpMainLayout->getAnim(10)->stop(); + mpMainLayout->getAnim(11)->stop(); + if (accessPoint != -1) { + layout::Animator* animator = mpMainLayout->getAnim(accessPoint + 0xc); + animator->initFrame(); + animator->restart(); + mpWiiSettingData->data[0x37] = 2; + setSE(); return; } - mpChangeLayout->getAnim(animation)->initFrame(); - mpChangeLayout->getAnim(animation)->restart(); + int arrow = get_arw_no(pageName); + if (arrow == -1) { + return; + } + int animation = arrow + 4; + layout::Animator* animator = mpMainLayout->getAnim(animation); + animator->initFrame(); + animator->restart(); mpWiiSettingData->data[0x37] = 2; setSE(); } @@ -2718,8 +2741,8 @@ namespace ipl { } else { animation = accessPoint + 0x10; } - mpChangeLayout->getAnim(animation)->initFrame(); - mpChangeLayout->getAnim(animation)->restart(); + mpMainLayout->getAnim(animation)->initFrame(); + mpMainLayout->getAnim(animation)->restart(); } void Setting::start_trig_event(const char* pageName) { @@ -2759,17 +2782,17 @@ namespace ipl { return; } unk_0x918 = arrow + 8; - mpChangeLayout->getAnim(unk_0x918)->initFrame(); - mpChangeLayout->getAnim(unk_0x918)->restart(); + mpMainLayout->getAnim(unk_0x918)->initFrame(); + mpMainLayout->getAnim(unk_0x918)->restart(); if (arrow == 0) { unk_0x91C[0] = 0; if (unk_0x914 == 1) { - mpChangeLayout->FindPaneByName("N_AP0")->SetVisible(false); + mpMainLayout->FindPaneByName("N_AP0")->SetVisible(false); } } else { unk_0x91C[0] = 1; if (mAPScanList.count == unk_0x914 + 5) { - mpChangeLayout->FindPaneByName("N_AP7")->SetVisible(false); + mpMainLayout->FindPaneByName("N_AP7")->SetVisible(false); } } unk_0x78 = 7; -- 2.49.1 From 01da1730e3365efcf765f8842d45a37b8dddfddd Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 06:04:26 +0000 Subject: [PATCH 60/61] match setting left event --- src/scene/setting/iplSetting.cpp | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 023d10c0..33877882 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -2731,18 +2731,19 @@ namespace ipl { void Setting::start_left_event(const char* pageName) { int accessPoint = get_ap_no(pageName); - int animation; - if (accessPoint == -1) { - int arrow = get_arw_no(pageName); - if (arrow == -1) { - return; - } - animation = arrow + 6; - } else { - animation = accessPoint + 0x10; + if (accessPoint != -1) { + layout::Animator* animator = mpMainLayout->getAnim(accessPoint + 0x10); + animator->initFrame(); + animator->restart(); + return; } - mpMainLayout->getAnim(animation)->initFrame(); - mpMainLayout->getAnim(animation)->restart(); + int arrow = get_arw_no(pageName); + if (arrow == -1) { + return; + } + layout::Animator* animator = mpMainLayout->getAnim(arrow + 6); + animator->initFrame(); + animator->restart(); } void Setting::start_trig_event(const char* pageName) { -- 2.49.1 From fa3ebbc53a3323692e1bfc2abb1c49e3820c6a12 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Tue, 29 Sep 2026 06:25:19 +0000 Subject: [PATCH 61/61] improve setting creation and AP traversal --- include/scene/setting/iplSetting.h | 3 +- src/scene/setting/iplSetting.cpp | 70 ++++++++++++++++++------------ 2 files changed, 44 insertions(+), 29 deletions(-) diff --git a/include/scene/setting/iplSetting.h b/include/scene/setting/iplSetting.h index 3351d64d..6743299c 100644 --- a/include/scene/setting/iplSetting.h +++ b/include/scene/setting/iplSetting.h @@ -47,7 +47,8 @@ namespace ipl { struct SettingAPScanList { u8 unknown[0x14]; u16 count; - u8 entries[0x802]; + u8 entries[0x7fe]; + WDBssDesc_* currentDescriptor; }; #endif diff --git a/src/scene/setting/iplSetting.cpp b/src/scene/setting/iplSetting.cpp index 33877882..5b46c3e8 100644 --- a/src/scene/setting/iplSetting.cpp +++ b/src/scene/setting/iplSetting.cpp @@ -258,19 +258,21 @@ namespace ipl { goto koreanFont; } if (productArea < 6) { - if (productArea != 4) { - if (productArea > 3) { - goto europeFont; - } else if (productArea >= 0) { - snprintf(fontName, sizeof(fontName), "WiiNTLG-Regular.ttc"); - snprintf(htmlPath, sizeof(htmlPath), "/html/%s/iplsetting.ash", "US2"); - goto loadFiles; - } + if (productArea == 4) { + goto defaultFont; + } + if (productArea >= 4) { + goto europeFont; + } + if (productArea >= 0) { + goto standardFont; } } else if (productArea == 11) { goto chineseFont; } + goto defaultFont; + standardFont: snprintf(fontName, sizeof(fontName), "WiiNTLG-Regular.ttc"); snprintf(htmlPath, sizeof(htmlPath), "/html/%s/iplsetting.ash", "US2"); goto loadFiles; @@ -288,6 +290,11 @@ namespace ipl { europeFont: snprintf(fontName, sizeof(fontName), "WiiNTLG-Regular.ttc"); snprintf(htmlPath, sizeof(htmlPath), "/html/%s/iplsetting.ash", "TW2"); + goto loadFiles; + + defaultFont: + snprintf(fontName, sizeof(fontName), "WiiNTLG-Regular.ttc"); + snprintf(htmlPath, sizeof(htmlPath), "/html/%s/iplsetting.ash", "US2"); loadFiles: mpSettingHTMLFile = System::getNandManager()->readAsync( @@ -315,13 +322,11 @@ namespace ipl { nand::File* archiveFile = static_cast(mpWWWArchiveFile); nand::File* writtenArchive = System::getNandManager()->write( getSceneHeap(), "/tmp/www.arc", archiveFile->getBuffer(), archiveFile->getLength(), 0x30); - if (writtenArchive->isFatalError()) { - System::getErrorHandler()->log("NAND", writtenArchive->checkData(), "iplSetting.cpp", 0x178); + if (writtenArchive->isFullForTask()) { + System::getErrorHandler()->log("NAND", 0, "iplSetting.cpp", 0x178); System::getErrorHandler()->set(ErrorHandler::DEFAULT, 2, NULL, 0, -1); } - if (writtenArchive != NULL) { - delete writtenArchive; - } + delete writtenArchive; mpChangeLayout = new layout::Object(getSceneHeap(), mpSettingLayoutFile, "arc", "SceenChange_b.brlyt"); mpFirstAnimation = reinterpret_cast(mpChangeLayout->bind("SceenChange_b_Right.brlan")); @@ -330,9 +335,11 @@ namespace ipl { mpMainLayout = new layout::Object(getSceneHeap(), mpSettingLayoutFile, "arc", "my_AP_a.brlyt"); for (int index = 0; index < 58; index++) { + bool initialAnimation = index == 20 || index == 10; const SettingAnimationBinding& binding = sSettingAnimationBindings[index]; - mpMainLayout->bindToGroup(sSettingAPAnimations[binding.animation], sSettingAPPaneNames[binding.pane], false, - index == 20 || index == 10); + const char* animation = sSettingAPAnimations[binding.animation]; + const char* pane = sSettingAPPaneNames[binding.pane]; + mpMainLayout->bindToGroup(animation, pane, false, initialAnimation); } mpMainLayout->finishBinding(); @@ -348,7 +355,9 @@ namespace ipl { parental::Parental::init(); mpAOSSThread = new AOSSThread(getSceneHeap()); + mAOSSState = 0; mpRakuRakuThread = new RakuRakuThread(getSceneHeap()); + mRakuState = 0; www::wiisetting::initWiiSetting(); initWiiSettingData(); @@ -358,16 +367,15 @@ namespace ipl { www::wiisetting::setMsgQueue(&mFuncMessageQueue); mpMem1BrowserBuffer = getSceneHeap()->alloc(0x1000, 0x20); - unk_0x908 = 0; mpMem2BrowserBuffer = getSceneHeap()->alloc(0x800, 4); memset(mpMem2BrowserBuffer, 0, 0x800); mpBrowserStringBuffer = getSceneHeap()->alloc(0x79, 4); memset(mpBrowserStringBuffer, 0, 0x79); mpEventHandler = new APEvent(this); - mpPaneManager = new gui::PaneManager(mpEventHandler, mpMainLayout->getDrawInfo(), getSceneHeap(), NULL, false); + mpPaneManager = new gui::PaneManager(mpEventHandler, mpMainLayout->getDrawInfo(), NULL, NULL, true); mpPaneManager->setupScene(mpMainLayout); - mpPaneManager->setAllBoundingBoxComponentTriggerTarget(false); + mpPaneManager->setAllComponentTriggerTarget(false); for (int index = 0; index < 4; index++) { mpPaneManager->setTriggerTarget(mpMainLayout->FindPaneByName(sSettingAPButtonNames[index]), true); @@ -377,8 +385,8 @@ namespace ipl { } TPLBind(reinterpret_cast(static_cast(mpBackgroundTPLFile)->getBuffer())); - int tick = OSGetTick(); - OSReport("*** prepare costs: %dms\n", (tick - mPrepareTick) / (OS_TIMER_CLOCK / 4000)); + u32 elapsed = OSGetTick() - mPrepareTick; + OSReport("*** prepare costs: %dms\n", elapsed / (OS_TIMER_CLOCK / 1000)); mPrepareTick = OSGetTick(); } @@ -2646,13 +2654,14 @@ namespace ipl { } void Setting::setAPDraw() { - WDBssDesc_* descriptor = reinterpret_cast(mAPScanList.entries); + mAPScanList.currentDescriptor = reinterpret_cast(mAPScanList.entries); u32 recordOffset = 2; for (u32 index = 0; index <= mAPScanList.count; ++index) { + WDBssDesc_* descriptor = mAPScanList.currentDescriptor; + recordOffset += descriptor->length * 2; if (recordOffset > 0x800) { return; } - descriptor = reinterpret_cast(mAPScanList.entries + recordOffset - 2); mpMainLayout->getAnim(10)->stop(); mpMainLayout->getAnim(11)->stop(); int privacyMode = WDGetPrivacyMode(descriptor); @@ -2683,7 +2692,8 @@ namespace ipl { mpMainLayout->getAnim(row + signal * 6 + 0x16)->initFrame(); mpMainLayout->getAnim(row + signal * 6 + 0x16)->restart(); } - recordOffset += descriptor->length * 2; + mAPScanList.currentDescriptor = + reinterpret_cast(mAPScanList.entries + recordOffset - 2); } } @@ -2750,8 +2760,9 @@ namespace ipl { int accessPoint = get_ap_no(pageName); if (accessPoint != -1) { u32 recordOffset = 2; - WDBssDesc_* descriptor = reinterpret_cast(mAPScanList.entries); - for (u32 index = 0; index <= mAPScanList.count; ++index) { + u32 index = 0; + while (index <= mAPScanList.count) { + WDBssDesc_* descriptor = mAPScanList.currentDescriptor; recordOffset += descriptor->length * 2; if (recordOffset > 0x800) { break; @@ -2773,7 +2784,9 @@ namespace ipl { OSReport("SET DATA : %d %s %d\n", index, ssid, privacyMode); break; } - descriptor = reinterpret_cast(mAPScanList.entries + recordOffset - 2); + mAPScanList.currentDescriptor = + reinterpret_cast(mAPScanList.entries + recordOffset - 2); + ++index; } unk_0x91C[2] = 0; unk_0x78 = 8; @@ -2783,8 +2796,9 @@ namespace ipl { return; } unk_0x918 = arrow + 8; - mpMainLayout->getAnim(unk_0x918)->initFrame(); - mpMainLayout->getAnim(unk_0x918)->restart(); + layout::Animator* animator = mpMainLayout->getAnim(unk_0x918); + animator->initFrame(); + animator->restart(); if (arrow == 0) { unk_0x91C[0] = 0; if (unk_0x914 == 1) { -- 2.49.1