From 9ad0863dbf4da4f32d67d7843da355cb65788e6a Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Wed, 30 Sep 2026 00:14:18 -0500 Subject: [PATCH 1/5] tiHwKeyboard 10/10, tiCandidateBox 105/112, MyTiManager 91/91 (worker 913d06d4) (#333) --- README.md | 4 +- include/keyboard/MyTiBg.h | 4 +- include/keyboard/MyTiManager.h | 20 + include/keyboard/tiCellPhone.h | 20 +- include/keyboard/tiHKBManager.h | 15 +- include/keyboard/tiHwKeyboard.h | 12 +- include/keyboard/tiKeyboard.h | 8 +- include/keyboard/tiManager.h | 3 + include/keyboard/tiPcKeyboard.h | 2 +- include/keyboard/tiPcKeyboardImpl.h | 6 + include/keyboard/tiTextInputBase.h | 4 +- include/keyboard/tiToolBar.h | 5 + src/keyboard/MyTiManager.cpp | 988 ++++++++++-------- src/keyboard/tiCandidateBox.cpp | 42 +- src/keyboard/tiHwKeyboard.cpp | 345 ++++++ tools/decomp-assist/MyTiManager.attempts.md | 89 ++ .../decomp-assist/tiCandidateBox.attempts.md | 41 + tools/decomp-assist/tiHwKeyboard.attempts.md | 19 + 18 files changed, 1149 insertions(+), 478 deletions(-) create mode 100644 tools/decomp-assist/MyTiManager.attempts.md create mode 100644 tools/decomp-assist/tiCandidateBox.attempts.md create mode 100644 tools/decomp-assist/tiHwKeyboard.attempts.md diff --git a/README.md b/README.md index 93cae5b2..3f88af20 100644 --- a/README.md +++ b/README.md @@ -53,9 +53,9 @@ Progress | Decompiled | Matched | Linked | Data | |:---:|:---:|:---:|:---:| -| 87.60% | 77.28% | 56.92% | 88.22% | +| 87.88% | 77.62% | 56.92% | 88.23% | -units 752/1027 complete, functions 11313/12563 matched. +units 752/1027 complete, functions 11324/12563 matched. decompiled = code with a C/C++ implementation (objdiff fuzzy), matched = byte-exact code, linked = code actually linked into the DOL, data = byte-exact data diff --git a/include/keyboard/MyTiBg.h b/include/keyboard/MyTiBg.h index aad892fe..dd3805ba 100644 --- a/include/keyboard/MyTiBg.h +++ b/include/keyboard/MyTiBg.h @@ -18,7 +18,9 @@ namespace textinput { LayoutByNW4R(nw4r::lyt::MultiArcResourceAccessor* multiArc, const char* layoutName, EventObserver* event) : nw4rmanager::Layout(multiArc, layoutName, event) {} #endif -#ifdef MYTIMANAGER_IMPLEMENTATION +#if defined(MYTIMANAGER_MATCHING) + virtual ~LayoutByNW4R() {} +#elif defined(MYTIMANAGER_IMPLEMENTATION) virtual ~LayoutByNW4R(); #else virtual ~LayoutByNW4R() {} diff --git a/include/keyboard/MyTiManager.h b/include/keyboard/MyTiManager.h index 584767c5..feebe6e8 100644 --- a/include/keyboard/MyTiManager.h +++ b/include/keyboard/MyTiManager.h @@ -167,6 +167,25 @@ namespace textinput { void setManager(Manager* manager) { mpManager = manager; } #endif virtual ~State(); +#ifdef MYTIMANAGER_MATCHING + virtual Manager::StateType getStateType() = 0; + + virtual void create() = 0; + + virtual void init() = 0; + + virtual void draw() = 0; + virtual void memoDraw() = 0; + + virtual void calc() = 0; + + virtual bool updateInput(int chan, f32 x, f32 y, u32 trig, u32 hold, u32 release) = 0; + virtual bool updateInput(input::HKBManager& hkbManager) = 0; + + virtual void start() = 0; + virtual void end() = 0; + +#else virtual Manager::StateType getStateType(); virtual void create(); @@ -184,6 +203,7 @@ namespace textinput { virtual void start(); virtual void end(); +#endif #ifdef MYTIMANAGER_IMPLEMENTATION virtual InputForm* InputForm(); virtual keyboard::hwkey::HWKeyboard* HWKeyboard(); diff --git a/include/keyboard/tiCellPhone.h b/include/keyboard/tiCellPhone.h index b1bc2349..09e782f9 100644 --- a/include/keyboard/tiCellPhone.h +++ b/include/keyboard/tiCellPhone.h @@ -2,20 +2,20 @@ #define TEXTINPUT_CELL_PHONE_H #include "tiNw4rManager.h" -#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) +#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) #include "tiKeyboard.h" #endif namespace textinput { namespace keyboard { namespace cellphonetype { -#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) +#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) class Base : public textinput::keyboard::KeyboardBase { #else class Base { #endif public: -#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) +#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) enum InputMode { IM_00, IM_01, @@ -32,6 +32,8 @@ namespace textinput { #ifdef TIMANAGER_IMPLEMENTATION Base(Manager* manager) : mpManager(manager) {} virtual int getType() override; +#elif defined(TIHWKEYBOARD_IMPLEMENTATION) + virtual int getType() override; #else virtual void getType() override; #endif @@ -79,7 +81,7 @@ namespace textinput { virtual void vt_0x4C(); virtual void vt_0x50(); -#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) +#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) virtual void doNumericMode(bool); #else virtual void vt_0x54(); @@ -95,11 +97,11 @@ namespace textinput { // TODO enum? int getInputType() const; -#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) +#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) void resetHoldingButton(); #endif -#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) +#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) private: u32 mPreviousInputMode; u32 mCurrentInputMode; @@ -123,7 +125,7 @@ namespace textinput { class LayoutByNW4R : public Base, public nw4rmanager::Layout { public: -#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) +#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) #ifdef TIMANAGER_IMPLEMENTATION LayoutByNW4R(Manager* manager, nw4r::lyt::MultiArcResourceAccessor* accessor, EventObserver* observer, const char* layoutName) : Base(manager), nw4rmanager::Layout(accessor, layoutName, observer), mpEventHandler(NULL) {} @@ -162,7 +164,7 @@ namespace textinput { void onPressedShift(bool shift); void onReleasedShift(); -#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) +#if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) bool hasLineFeedButton() const { return mbLineFeedButton; } private: bool mbLineFeedButton; @@ -176,7 +178,7 @@ namespace textinput { #endif public: #endif -#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) +#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) virtual bool updateInput(int chan, f32 x, f32 y, u32 trig, u32 hold, u32 release, void* data) override; virtual bool updateInput(input::HKBManager& hkbManager) override; #endif diff --git a/include/keyboard/tiHKBManager.h b/include/keyboard/tiHKBManager.h index 1f5504a1..f2a43939 100644 --- a/include/keyboard/tiHKBManager.h +++ b/include/keyboard/tiHKBManager.h @@ -119,6 +119,9 @@ namespace textinput { KeySet GetTriggeredKeySet() const; KeySet GetReleasedKeySet() const; KeySet GetRepeatedKeySet() const; +#ifdef TIHWKEYBOARD_IMPLEMENTATION + KeySet GetReleasedKeySet() const; +#endif static void SetLedCB(_KBDEc result, void* userData); static void AttachCB(KBDDevEvent* event); static void DetachCB(KBDDevEvent* event); @@ -148,15 +151,22 @@ namespace textinput { u32 GetModifierState() const; void SetModifierState(u32, u32); -#if defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION) +#if defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION) class KeySet { public: u8 GetKey() const; +#ifdef TIHWKEYBOARD_IMPLEMENTATION + u32 GetWChar() const; +#else wchar_t GetWChar() const; +#endif bool IsValid() const; KeySet GetNext() const; KeySet(const KeySet& other) : mpManager(other.mpManager), mKind(other.mKind), mIndex(other.mIndex), mDevice(other.mDevice), mCharacter(other.mCharacter) {} +#ifdef TIHWKEYBOARD_IMPLEMENTATION + KeySet() : mpManager(NULL), mKind(0), mIndex(-1), mDevice(0), mCharacter(0) {} +#endif private: const HKBManager* mpManager; u8 mKind; @@ -166,6 +176,9 @@ namespace textinput { }; KeySet GetTriggeredKeySet() const; KeySet GetRepeatedKeySet() const; +#ifdef TIHWKEYBOARD_IMPLEMENTATION + KeySet GetReleasedKeySet() const; +#endif void SetForceModifierState(u32 mask, u32 state); #else class KeySet { diff --git a/include/keyboard/tiHwKeyboard.h b/include/keyboard/tiHwKeyboard.h index 5a8d7bec..1bda5121 100644 --- a/include/keyboard/tiHwKeyboard.h +++ b/include/keyboard/tiHwKeyboard.h @@ -25,7 +25,7 @@ namespace textinput { #endif virtual void init(); -#ifdef TI_PC_KEYBOARD_IMPLEMENTATION +#if defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION) wchar_t convertWCCode(wchar_t code) const; #endif @@ -40,6 +40,11 @@ namespace textinput { void resetQuoteState() { mbSingleQuoteClosing = 0; mbDoubleQuoteClosing = 0; } #endif private: +#ifdef TIHWKEYBOARD_IMPLEMENTATION + bool updateRepeatKey_(input::HKBManager&); + bool updateTriggerKey_(input::HKBManager&); + bool updateTappingShift_(input::HKBManager&); +#endif void updateShift(input::HKBManager& hkbManager); void controlKeyTriggeredHandler(input::HKBManager); @@ -50,9 +55,14 @@ namespace textinput { #ifdef TIINPUTFORM_IMPLEMENTATION u8 mbSingleQuoteClosing; u8 mbDoubleQuoteClosing; +#else +#ifdef TIHWKEYBOARD_IMPLEMENTATION + bool field_0x15; + bool field_0x16; #else u8 field_0x15; // 0x15 u8 field_0x16; // 0x16 +#endif #endif }; diff --git a/include/keyboard/tiKeyboard.h b/include/keyboard/tiKeyboard.h index 5b7b10f4..e641e7e4 100644 --- a/include/keyboard/tiKeyboard.h +++ b/include/keyboard/tiKeyboard.h @@ -12,7 +12,7 @@ namespace textinput { KeyboardBase() : meLanguage(JP) {} #endif virtual ~KeyboardBase() {} -#if !defined(TI_PC_KEYBOARD_IMPLEMENTATION) && !defined(TIMANAGER_IMPLEMENTATION) && !defined(TISIGNWINDOW_IMPLEMENTATION) +#if !(defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION)) && !defined(TIMANAGER_IMPLEMENTATION) && !defined(TISIGNWINDOW_IMPLEMENTATION) virtual void create(MEMAllocator* alloc) override; virtual void init() override; virtual void setCommandReceiver(CommandReceiver* receiver) override; @@ -21,18 +21,18 @@ namespace textinput { #if !defined(TIMANAGER_IMPLEMENTATION) && !defined(TISIGNWINDOW_IMPLEMENTATION) virtual void updateFromReceiver(u32, void*) override; #endif -#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION) +#if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || (defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION)) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION) virtual void onKey(u32, void*); #else virtual void onKey(u32); #endif -#if defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION) +#if (defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION)) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION) virtual int getType(); #else virtual void getType(); #endif virtual void setLanguage(Language language); - #if defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION) + #if (defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION)) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION) #ifdef TISIGNWINDOW_IMPLEMENTATION virtual Language getLanguage() const; #else diff --git a/include/keyboard/tiManager.h b/include/keyboard/tiManager.h index d954067b..5a7bec30 100644 --- a/include/keyboard/tiManager.h +++ b/include/keyboard/tiManager.h @@ -120,6 +120,9 @@ namespace textinput { virtual void start() {} virtual void end() {} +#ifdef TIHWKEYBOARD_IMPLEMENTATION + EventObserver* getEventObserverForHardware() const { return mpEventObserver; } +#endif virtual InputForm* getInputForm() { return mpInputForm; } virtual const InputForm* getInputForm() const { return mpInputForm; } diff --git a/include/keyboard/tiPcKeyboard.h b/include/keyboard/tiPcKeyboard.h index afd6cc68..916d79f3 100644 --- a/include/keyboard/tiPcKeyboard.h +++ b/include/keyboard/tiPcKeyboard.h @@ -1,7 +1,7 @@ #ifndef TEXTINPUT_PC_KEYBOARD_H #define TEXTINPUT_PC_KEYBOARD_H -#if defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION) +#if (defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION)) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION) #include "tiPcKeyboardImpl.h" #else diff --git a/include/keyboard/tiPcKeyboardImpl.h b/include/keyboard/tiPcKeyboardImpl.h index a4824790..cc8715a6 100644 --- a/include/keyboard/tiPcKeyboardImpl.h +++ b/include/keyboard/tiPcKeyboardImpl.h @@ -226,6 +226,12 @@ namespace textinput { State mState; const LanguageData* mpInitialLanguageData; KeyState mKeyState; +#ifdef TIHWKEYBOARD_IMPLEMENTATION + public: + KeyState& hardwareKeyState() { return mKeyState; } + bool hardwareLanguageKeyActive() const { return mbLanguageKeyActive; } + protected: +#endif MEMAllocator* mpAllocator; bool mbOnlyQwerty; bool mbLanguageKeyActive; diff --git a/include/keyboard/tiTextInputBase.h b/include/keyboard/tiTextInputBase.h index a7bd8b22..3e21198d 100644 --- a/include/keyboard/tiTextInputBase.h +++ b/include/keyboard/tiTextInputBase.h @@ -70,7 +70,7 @@ namespace textinput { INPUT_COMMAND_37 = 37, } INPUT_COMMAND; -#if defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION) +#if (defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION)) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION) struct ChangePredictMode { u32 mode; bool enabled; }; #endif virtual void clearSender(); @@ -86,7 +86,7 @@ namespace textinput { CommandSender() : mpCommandReceiver(NULL) {} virtual void setCommandReceiver(CommandReceiver* cmdRecv); - #if defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) + #if (defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION)) || defined(TIMANAGER_IMPLEMENTATION) virtual void sendCommand(u32 command, void* data) { if (mpCommandReceiver != NULL) mpCommandReceiver->onCommand(static_cast(command), data); } diff --git a/include/keyboard/tiToolBar.h b/include/keyboard/tiToolBar.h index b29f4668..142704a9 100644 --- a/include/keyboard/tiToolBar.h +++ b/include/keyboard/tiToolBar.h @@ -58,8 +58,13 @@ namespace textinput { virtual void setQwertyWithSE(bool qwerty); virtual bool isEnableKeytopChange() const; virtual void enableKeytopChange(bool enable); +#ifdef MYTIMANAGER_MATCHING + virtual nw4r::lyt::Pane* getDownArea(); + virtual nw4r::lyt::Pane* getUpArea(); +#else virtual nw4r::lyt::Pane* getUpArea(); virtual nw4r::lyt::Pane* getDownArea(); +#endif virtual void setOKButtonVisible(bool visible); virtual void setCancelButtonVisible(bool visible); virtual void setOKButtonCaption(const wchar_t* caption); diff --git a/src/keyboard/MyTiManager.cpp b/src/keyboard/MyTiManager.cpp index 2bb03a87..966007ca 100644 --- a/src/keyboard/MyTiManager.cpp +++ b/src/keyboard/MyTiManager.cpp @@ -1,6 +1,6 @@ #define MYTIMANAGER_IMPLEMENTATION +#define MYTIMANAGER_MATCHING #include "keyboard/MyTiManager.h" -#include "keyboard/MyTiBg.h" #include "keyboard/tiLanguageIndependentData.h" #include "keyboard/tiPredictLang.h" #include "keyboard/tiUtil.h" @@ -75,7 +75,7 @@ public: void start(); void end(); -private: +protected: f32 mTime; }; @@ -93,17 +93,25 @@ public: void end(); }; -class DisappearMemoState : public State { +class DisappearMemoState : public AppearMemoState { public: - DisappearMemoState() : mTime(0.0f) {} + DisappearMemoState() {} Manager::StateType getStateType(); void start(); void calc(); -private: - f32 mTime; }; +} +} +} + +#include "keyboard/MyTiBg.h" + +namespace textinput { +namespace extend { +namespace memo { + static DispMemoState sDispMemoState; static EditMemoState sEditMemoState; static AppearMemoState sAppearMemoState; @@ -173,271 +181,8 @@ Manager::~Manager() { setSignWindowForMemo(NULL); } -State::~State() {} - -void DispMemoState::create() {} - -void DispMemoState::init() { - getManager()->getConfigType(); -} - -void DispMemoState::start() { - switch (getManager()->getConfigType()) { - case Manager::CT_Letter: - case Manager::CT_PhotoLetter: - InputForm()->setEditMode(InputForm::EM_Disp); - InputForm()->getLayout()->GetRootPane()->SetTranslate( - nw4r::math::VEC3(sLetterMemoPosition.x, sLetterMemoPosition.y, 0.0f)); - break; - default: - break; - } -} - -void DispMemoState::calc() { - Manager::ConfigType configType = getManager()->getConfigType(); - switch (configType) { - case Manager::CT_Letter: - case Manager::CT_PhotoLetter: - InputForm()->calc(); - break; - default: - break; - } -} - -bool DispMemoState::updateInput(input::HKBManager& hkbManager) { - Manager::ConfigType configType = getManager()->getConfigType(); - switch (configType) { - case Manager::CT_Letter: - case Manager::CT_PhotoLetter: - InputForm(); - return InputForm()->updateInput(hkbManager); - default: - return false; - } -} - -bool DispMemoState::updateInput(int chan, f32 x, f32 y, u32 trig, u32 hold, u32 release) { - Manager::ConfigType configType = getManager()->getConfigType(); - switch (configType) { - case Manager::CT_Letter: - case Manager::CT_PhotoLetter: { - InputForm(); - struct InputParameters { - int chan; - f32 x; - f32 y; - u32 trig; - u32 hold; - u32 release; - } inputParameters = {chan, x, y, trig, hold, release}; - return InputForm()->updateInput(chan, x, y, trig, hold, release, &inputParameters); - } - default: - return false; - } -} - -void AppearMemoState::init() {} - -void AppearMemoState::calc() { - InputForm()->calc(); - if (ToolBar()->isQwerty()) { - PCKeyboard()->calc(); - } else { - static_cast(CellPhoneKeyboard())->calc(); - } - if (CandidateBox()->isActive()) { - CandidateBox()->calc(); - } - ToolBar()->calc(); - static_cast(BG())->calc(); - if (mTime >= 30.0f) { - getManager()->setState(Manager::ST_Appearing); - } - mTime += 1.0f; -} - -void AppearMemoState::draw() { - if (getManager()->getConfigType() != Manager::CT_Letter && - getManager()->getConfigType() != Manager::CT_PhotoLetter) { - static_cast(BG())->draw(); - } - ToolBar()->draw(); - if (getManager()->getConfigType() != Manager::CT_Letter && - getManager()->getConfigType() != Manager::CT_PhotoLetter) { - InputForm()->draw(); - } - if (CandidateBox()->isActive()) { - CandidateBox()->draw(); - } - if (ToolBar()->isQwerty()) { - PCKeyboard()->draw(); - } else { - static_cast(CellPhoneKeyboard())->draw(); - } -} - -void AppearMemoState::start() { - mTime = 0.0f; - Manager::ConfigType configType = getManager()->getConfigType(); - switch (configType) { - case Manager::CT_Letter: - case Manager::CT_PhotoLetter: - InputForm()->setEditMode(InputForm::EM_Appear); - break; - default: - break; - } -} - -bool AppearMemoState::updateInput(int, f32, f32, u32, u32, u32) { - return false; -} - -bool AppearMemoState::updateInput(input::HKBManager&) { - return false; -} - -void EditMemoState::create() {} - -void EditMemoState::init() {} - -void EditMemoState::calc() { - if (ToolBar()->isQwerty()) { - PCKeyboard()->calc(); - } else { - static_cast(CellPhoneKeyboard())->calc(); - } - ToolBar()->calc(); - if (CandidateBox()->isActive()) { - CandidateBox()->calc(); - } - InputForm()->calc(); - if (static_cast(PredictLanguageSelectDialog())->isActive()) { - static_cast(PredictLanguageSelectDialog())->calc(); - } - if (static_cast(SignKeyboard())->isActive()) { - SignWindowLayout& signWindow = *static_cast(SignKeyboard()); - static_cast(signWindow).calc(); - } - if (getManager()->getConfigType() != Manager::CT_Letter && - getManager()->getConfigType() != Manager::CT_PhotoLetter) { - static_cast(BG())->calc(); - } -} - -void EditMemoState::draw() { - GXSetZMode(GX_TRUE, GX_LEQUAL, GX_TRUE); - if (getManager()->getConfigType() != Manager::CT_Letter && - getManager()->getConfigType() != Manager::CT_PhotoLetter) { - static_cast(BG())->draw(); - } - ToolBar()->draw(); - if (getManager()->getConfigType() != Manager::CT_Letter && - getManager()->getConfigType() != Manager::CT_PhotoLetter) { - InputForm()->draw(); - } - if (CandidateBox()->isActive()) { - CandidateBox()->draw(); - } - if (ToolBar()->isQwerty()) { - PCKeyboard()->draw(); - } else { - static_cast(CellPhoneKeyboard())->draw(); - } - if (static_cast(PredictLanguageSelectDialog())->isActive()) { - static_cast(PredictLanguageSelectDialog())->draw(); - } - if (static_cast(SignKeyboard())->isActive()) { - static_cast(SignKeyboard())->draw(); - } -} - -bool EditMemoState::updateInput(input::HKBManager& hkbManager) { - bool wasQwerty = ToolBar()->isQwerty(); - if (static_cast(PredictLanguageSelectDialog())->isActive()) { - return false; - } - HWKeyboard()->updateInput(hkbManager); - if (static_cast(SignKeyboard())->isActive()) { - return static_cast(SignKeyboard())->updateInput(hkbManager); - } - bool handled; - if (wasQwerty) { - handled = PCKeyboard()->updateInput(hkbManager); - } else { - handled = CellPhoneKeyboard()->updateInput(hkbManager); - } - if (wasQwerty != ToolBar()->isQwerty()) { - InputForm()->onCommand(static_cast(6), NULL); - CandidateBox()->checkValidation(); - if (ToolBar()->isQwerty()) { - PCKeyboard()->onActive(); - } else { - CellPhoneKeyboard()->onActive(); - } - } - return handled; -} - -void EditMemoState::start() { - switch (getManager()->getConfigType()) { - case Manager::CT_Letter: - case Manager::CT_PhotoLetter: - InputForm()->setEditMode(InputForm::EM_Edit); - InputForm()->getLayout()->GetRootPane()->SetTranslate( - nw4r::math::VEC3(sLetterMemoPosition.x, sLetterMemoPosition.y, 0.0f)); - break; - default: - break; - } -} - -bool EditMemoState::updateInput(int chan, f32 x, f32 y, u32 trig, u32 hold, u32 release) { - bool wasQwerty = ToolBar()->isQwerty(); - struct InputParameters { - int chan; - f32 x; - f32 y; - u32 trig; - u32 hold; - u32 release; - } inputParameters = {chan, x, y, trig, hold, release}; - HWKeyboard()->updateInput(chan, x, y, trig, hold, release, &inputParameters); - predictlang::LayoutByNW4R* predictDialog = - static_cast(PredictLanguageSelectDialog()); - if (predictDialog->isActive()) { - return predictDialog->updateInput(chan, x, y, trig, hold, release, &inputParameters); - } - bool inputHandled = InputForm()->updateInput(chan, x, y, trig, hold, release, &inputParameters); - if (static_cast(SignKeyboard())->isActive()) { - return static_cast(SignKeyboard())->updateInput( - chan, x, y, trig, hold, release, &inputParameters); - } - bool handled; - if (wasQwerty) { - handled = PCKeyboard()->updateInput(chan, x, y, trig, hold, release, &inputParameters); - } else { - handled = CellPhoneKeyboard()->updateInput(chan, x, y, trig, hold, release, &inputParameters); - } - bool toolbarHandled = ToolBar()->updateInput(chan, x, y, trig, hold, release, &inputParameters); - bool candidateHandled = false; - if (CandidateBox()->isActive()) { - candidateHandled = CandidateBox()->updateInput(chan, x, y, trig, hold, release, &inputParameters); - } - inputHandled = InputForm()->updateInput(chan, x, y, trig, hold, release, &inputParameters) || inputHandled; - if (wasQwerty != ToolBar()->isQwerty()) { - InputForm()->onCommand(static_cast(6), NULL); - CandidateBox()->checkValidation(); - if (ToolBar()->isQwerty()) { - PCKeyboard()->onActive(); - } else { - CellPhoneKeyboard()->onActive(); - } - } - return handled | candidateHandled | inputHandled | toolbarHandled; +inline void setPaneAlpha(nw4r::lyt::Pane* pane, s32 alpha) { + pane->SetAlpha(alpha); } void Manager::create(MEMAllocator*) { @@ -606,153 +351,6 @@ void* Manager::createBG() { "fs_VK_bg_a.brlyt", eventObserver); } -void Manager::start() { - if (meConfigType >= CT_Numeric) return; - if (meConfigType < CT_Letter) return; - static_cast(getInputFormForMemo())->open(); -} - -void Manager::end() { - if (meConfigType >= CT_Numeric) return; - if (meConfigType < CT_Letter) return; - static_cast(getInputFormForMemo())->close(); -} - -InputForm* State::InputForm() { - return static_cast(getManager()->getInputForm()); -} - -f32 InputForm::getScrollFrom() { - return mfScrollFrom; -} - -f32 InputForm::getScrollTo() { - return mfScrollTo; -} - -keyboard::hwkey::HWKeyboard* State::HWKeyboard() { - return getManager()->getHWKeyboard(); -} - -keyboard::pctype::LayoutByNW4R* State::PCKeyboard() { - return getManager()->getPCKeyboard(); -} - -keyboard::cellphonetype::LayoutByNW4R* State::CellPhoneKeyboard() { - return getManager()->getCellPhoneKeyboard(); -} - -void* State::SignKeyboard() { - return getManager()->getSignKeyboard(); -} - -candidatebox::LayoutByNW4R* State::CandidateBox() { - return getManager()->getCandidateBox(); -} - -toolbar::LayoutByNW4R* State::ToolBar() { - return getManager()->getToolBar(); -} - -void* State::PredictLanguageSelectDialog() { - return getManager()->getPredictLanguageSelectDialog(); -} - -void* State::BG() { - return getManager()->getBackGround(); -} - -Manager::StateType DispMemoState::getStateType() { - return Manager::ST_Hidden; -} - -void DispMemoState::draw() {} - -void DispMemoState::memoDraw() { - if (getManager()->getConfigType() == Manager::CT_Letter || - getManager()->getConfigType() == Manager::CT_PhotoLetter) { - InputForm()->draw(); - } -} - -void DispMemoState::end() {} - -Manager::StateType AppearMemoState::getStateType() { - return Manager::ST_Appearing; -} - -void AppearMemoState::memoDraw() { - if (getManager()->getConfigType() == Manager::CT_Letter || - getManager()->getConfigType() == Manager::CT_PhotoLetter) { - InputForm()->draw(); - } -} - -void AppearMemoState::create() {} - -void AppearMemoState::end() {} - -Manager::StateType EditMemoState::getStateType() { - return Manager::ST_Visible; -} - -void EditMemoState::memoDraw() { - if (getManager()->getConfigType() == Manager::CT_Letter || - getManager()->getConfigType() == Manager::CT_PhotoLetter) { - InputForm()->draw(); - } -} - -void EditMemoState::end() {} - -Manager::StateType DisappearMemoState::getStateType() { - return Manager::ST_Disappearing; -} - -void DisappearMemoState::calc() { - if (mTime >= 30.0f) { - getManager()->setState(Manager::ST_Disappearing); - } - InputForm()->calc(); - if (ToolBar()->isQwerty()) { - PCKeyboard()->calc(); - } else { - static_cast(CellPhoneKeyboard())->calc(); - } - ToolBar()->calc(); - if (CandidateBox()->isActive()) { - CandidateBox()->calc(); - } - static_cast(BG())->calc(); - f32 slideX = util::hermiteInterporation( - mTime, 0.0f, 0.0f, 0.0f, 30.0f, sHiddenMemoPosition.x, 0.0f); - nw4r::lyt::Pane* keyboardPane = PCKeyboard()->getLayout()->GetRootPane(); - nw4r::math::VEC3 keyboardPosition = keyboardPane->GetTranslate(); - keyboardPosition.x = slideX; - keyboardPane->SetTranslate(keyboardPosition); - mTime += 1.0f; -} - -void DisappearMemoState::start() { - mTime = 0.0f; - Manager::ConfigType configType = getManager()->getConfigType(); - switch (configType) { - case Manager::CT_Letter: - case Manager::CT_PhotoLetter: - InputForm()->setEditMode(InputForm::EM_Disappear); - getManager()->setSaveData(); - break; - default: - InputForm()->onClose(); - break; - } -} - -void Manager::configNumericBigTextWithDot() { - configNumericWithDot(); - meConfigType = CT_NumericBigTextWithDot; -} - void Manager::configDefault() { meConfigType = CT_Default; setPCKeyboardForMemo(static_cast(mpDefaultPCKeyboard)); @@ -829,7 +427,7 @@ void Manager::configLetter() { reflectSaveData(); limitStringLength(0x100); limitRowNum(0x10); - sLetterMemoPosition.y = 0.0f; + sLetterMemoPosition.y = 145.0f; getInputFormForMemo()->dirtyCacheAll(); } @@ -861,7 +459,7 @@ void Manager::configPhotoLetter() { reflectSaveData(); limitStringLength(0x100); limitRowNum(0x10); - sLetterMemoPosition.y = 0.0f; + sLetterMemoPosition.y = 151.0f; getInputFormForMemo()->dirtyCacheAll(); } @@ -950,6 +548,17 @@ void Manager::configOnlyQwertyBigTextWithoutLineFeedAndSign() { getInputFormForMemo()->dirtyCacheAll(); } +void Manager::configNumericWithDot() { + configNumeric(); + meConfigType = CT_NumericWithDot; + getCellPhoneKeyboardForMemo()->doNumericWithDotMode(true); +} + +void Manager::configNumericBigTextWithDot() { + configNumericWithDot(); + meConfigType = CT_NumericBigTextWithDot; +} + void Manager::configNormalBigTextWithoutLineFeedWithSign() { configDefault(); setInputFormForMemo(mpBigTextInputForm); @@ -987,12 +596,6 @@ void Manager::configNormalWithoutLineFeedWithSign() { getInputFormForMemo()->dirtyCacheAll(); } -void Manager::configNumericWithDot() { - configNumeric(); - meConfigType = CT_NumericWithDot; - getCellPhoneKeyboardForMemo()->doNumericWithDotMode(true); -} - void Manager::configPredictWithoutLineFeed() { configDefault(); meConfigType = CT_PredictWithoutLineFeed; @@ -1007,6 +610,18 @@ void Manager::configPredictBigText() { textinput::Manager::init(); } +void Manager::start() { + if (meConfigType >= CT_Numeric) return; + if (meConfigType < CT_Letter) return; + static_cast(getInputFormForMemo())->open(); +} + +void Manager::end() { + if (meConfigType >= CT_Numeric) return; + if (meConfigType < CT_Letter) return; + static_cast(getInputFormForMemo())->close(); +} + void Manager::setSaveData() { mMemoSetting.uRevisionAndType = getToolBarForMemo()->isQwerty() | 0x10; mMemoSetting.uDictionary = getInputFormForMemo()->getPredictMode(); @@ -1027,15 +642,14 @@ void Manager::setSaveData() { void Manager::reflectSaveData() { s32 revision = (mMemoSetting.uRevisionAndType >> 4) & 0xF; - if (revision >= 1) { - if (revision <= 1) { - reflectSaveDataRev1(); - } else { - reflectSaveDataDefault(); - } - } else { - reflectSaveDataDefault(); + switch (revision) { + case 0: + break; + case 1: + reflectSaveDataRev1(); + return; } + reflectSaveDataDefault(); } void Manager::reflectSaveDataRev1() { @@ -1115,16 +729,516 @@ void Manager::SetFont(nw4r::lyt::FontRefLink* fontLink) { } } -void bg::Base::init() {} +void DispMemoState::create() {} -void bg::Base::create(MEMAllocator*) {} +void DispMemoState::init() { + getManager()->getConfigType(); +} -bg::LayoutByNW4R::~LayoutByNW4R() {} +void DispMemoState::calc() { + Manager::ConfigType configType = getManager()->getConfigType(); + switch (configType) { + case Manager::CT_Letter: + case Manager::CT_PhotoLetter: + InputForm()->calc(); + break; + default: + break; + } +} + +InputForm* State::InputForm() { + return static_cast(getManager()->getInputForm()); +} + +void DispMemoState::draw() {} + +void DispMemoState::memoDraw() { + if (getManager()->getConfigType() == Manager::CT_Letter || + getManager()->getConfigType() == Manager::CT_PhotoLetter) { + InputForm()->draw(); + } +} + +bool DispMemoState::updateInput(int chan, f32 x, f32 y, u32 trig, u32 hold, u32 release) { + Manager::ConfigType configType = getManager()->getConfigType(); + switch (configType) { + case Manager::CT_Letter: + case Manager::CT_PhotoLetter: { + InputForm(); + struct InputParameters { + int chan; + f32 x; + f32 y; + u32 trig; + u32 hold; + u32 release; + } inputParameters = {chan, x, y, trig, hold, release}; + return InputForm()->updateInput(chan, x, y, trig, hold, release, &inputParameters); + } + default: + return false; + } +} + +bool DispMemoState::updateInput(input::HKBManager& hkbManager) { + Manager::ConfigType configType = getManager()->getConfigType(); + switch (configType) { + case Manager::CT_Letter: + case Manager::CT_PhotoLetter: + InputForm(); + return InputForm()->updateInput(hkbManager); + default: + return false; + } +} + +void DispMemoState::start() { + Manager::ConfigType configType = getManager()->getConfigType(); + switch (configType) { + case Manager::CT_Letter: + case Manager::CT_PhotoLetter: + InputForm()->setEditMode(InputForm::EM_Disp); + InputForm()->getLayout()->GetRootPane()->SetTranslate(nw4r::math::VEC2(0.0f, sLetterMemoPosition.x)); + InputForm()->getLayout()->GetRootPane()->SetAlpha(255); + break; + default: + InputForm()->getLayout()->GetRootPane()->SetTranslate(nw4r::math::VEC2(0.0f, sHiddenMemoPosition.x)); + setPaneAlpha(InputForm()->getLayout()->GetRootPane(), static_cast(sAppearingMemoPosition.x)); + break; + } + PCKeyboard()->getLayout()->GetRootPane()->SetTranslate(nw4r::math::VEC2(0.0f, sHiddenMemoPosition.x)); + CellPhoneKeyboard()->getLayout()->GetRootPane()->SetTranslate(nw4r::math::VEC2(0.0f, sHiddenMemoPosition.x)); + CandidateBox()->getLayout()->GetRootPane()->SetTranslate(nw4r::math::VEC2(0.0f, sHiddenMemoPosition.x)); + ToolBar()->getUpArea()->SetTranslate(nw4r::math::VEC2(0.0f, sHiddenMemoPosition.x / 3.0f)); + ToolBar()->getDownArea()->SetTranslate(nw4r::math::VEC2(0.0f, -sHiddenMemoPosition.x / 3.0f)); + static_cast(BG())->getLayout()->GetRootPane()->SetTranslate(nw4r::math::VEC2(0.0f, 0.0f)); + setPaneAlpha(PCKeyboard()->getLayout()->GetRootPane(), static_cast(sAppearingMemoPosition.x)); + setPaneAlpha(CellPhoneKeyboard()->getLayout()->GetRootPane(), static_cast(sAppearingMemoPosition.x)); + setPaneAlpha(CandidateBox()->getLayout()->GetRootPane(), static_cast(sAppearingMemoPosition.x)); + setPaneAlpha(ToolBar()->getUpArea(), static_cast(sAppearingMemoPosition.x)); + setPaneAlpha(ToolBar()->getDownArea(), static_cast(sAppearingMemoPosition.x)); + setPaneAlpha(static_cast(BG())->getLayout()->GetRootPane(), static_cast(sAppearingMemoPosition.x)); +} + +keyboard::pctype::LayoutByNW4R* State::PCKeyboard() { + return getManager()->getPCKeyboard(); +} + +keyboard::cellphonetype::LayoutByNW4R* State::CellPhoneKeyboard() { + return getManager()->getCellPhoneKeyboard(); +} + +candidatebox::LayoutByNW4R* State::CandidateBox() { + return getManager()->getCandidateBox(); +} + +toolbar::LayoutByNW4R* State::ToolBar() { + return getManager()->getToolBar(); +} + +void* State::BG() { + return getManager()->getBackGround(); +} + +void AppearMemoState::create() {} + +void AppearMemoState::init() {} + +void AppearMemoState::calc() { + InputForm()->calc(); + if (ToolBar()->isQwerty()) { + PCKeyboard()->calc(); + } else { + static_cast(CellPhoneKeyboard())->calc(); + } + if (CandidateBox()->isActive()) { + CandidateBox()->calc(); + } + ToolBar()->calc(); + static_cast(BG())->calc(); + if (30.0f <= mTime) { + getManager()->changeState(Manager::STL_Transition); + } + + f32 offset = textinput::util::hermiteInterporation( + mTime, 0.0f, sHiddenMemoPosition.x, 0.0f, + 30.0f, sHiddenMemoPosition.y, 0.0f); + PCKeyboard()->getLayout()->GetRootPane()->SetTranslate(nw4r::math::VEC2(0.0f, offset)); + CellPhoneKeyboard()->getLayout()->GetRootPane()->SetTranslate(nw4r::math::VEC2(0.0f, offset)); + CandidateBox()->getLayout()->GetRootPane()->SetTranslate(nw4r::math::VEC2(0.0f, offset)); + ToolBar()->getUpArea()->SetTranslate( + nw4r::math::VEC2(0.0f, offset / 3.0f)); + ToolBar()->getDownArea()->SetTranslate( + nw4r::math::VEC2(0.0f, -offset / 3.0f)); + static_cast(BG())->getLayout()->GetRootPane()->SetTranslate(nw4r::math::VEC2(0.0f, 0.0f)); + + f32 alpha = textinput::util::hermiteInterporation( + mTime, 0.0f, sAppearingMemoPosition.x, 0.0f, + 30.0f, sAppearingMemoPosition.y, 0.0f); + s32 alphaByte = static_cast(alpha); + setPaneAlpha(PCKeyboard()->getLayout()->GetRootPane(), alphaByte); + setPaneAlpha(CellPhoneKeyboard()->getLayout()->GetRootPane(), alphaByte); + setPaneAlpha(CandidateBox()->getLayout()->GetRootPane(), alphaByte); + setPaneAlpha(ToolBar()->getUpArea(), alphaByte); + setPaneAlpha(static_cast(BG())->getLayout()->GetRootPane(), alphaByte); + + Manager::ConfigType configType = getManager()->getConfigType(); + switch (configType) { + case Manager::CT_Letter: + case Manager::CT_PhotoLetter: { + f32 letterOffset = textinput::util::hermiteInterporation( + mTime, 0.0f, sLetterMemoPosition.x, 0.0f, + 30.0f, sLetterMemoPosition.y, 0.0f); + InputForm()->getLayout()->GetRootPane()->SetTranslate( + nw4r::math::VEC2(0.0f, letterOffset)); + setPaneAlpha(InputForm()->getLayout()->GetRootPane(), 0xff); + MemoInputForm* inputForm = InputForm(); + inputForm->setScroll(textinput::util::hermiteInterporation( + mTime, 0.0f, inputForm->getScrollFrom(), 0.0f, + 30.0f, inputForm->getScrollTo(), 0.0f)); + break; + } + default: { + InputForm()->getLayout()->GetRootPane()->SetTranslate( + nw4r::math::VEC2(0.0f, offset)); + setPaneAlpha(InputForm()->getLayout()->GetRootPane(), alphaByte); + } + } + mTime += 1.0f; +} + +f32 InputForm::getScrollFrom() { + return mfScrollFrom; +} + +f32 InputForm::getScrollTo() { + return mfScrollTo; +} + +void AppearMemoState::draw() { + if (getManager()->getConfigType() != Manager::CT_Letter && + getManager()->getConfigType() != Manager::CT_PhotoLetter) { + static_cast(BG())->draw(); + } + ToolBar()->draw(); + if (getManager()->getConfigType() != Manager::CT_Letter && + getManager()->getConfigType() != Manager::CT_PhotoLetter) { + InputForm()->draw(); + } + if (CandidateBox()->isActive()) { + CandidateBox()->draw(); + } + if (ToolBar()->isQwerty()) { + PCKeyboard()->draw(); + } else { + static_cast(CellPhoneKeyboard())->draw(); + } +} void bg::LayoutByNW4R::draw() { nw4rmanager::Layout::draw(); } +void AppearMemoState::memoDraw() { + if (getManager()->getConfigType() == Manager::CT_Letter || + getManager()->getConfigType() == Manager::CT_PhotoLetter) { + InputForm()->draw(); + } +} + +bool AppearMemoState::updateInput(int, f32, f32, u32, u32, u32) { + return false; +} + +bool AppearMemoState::updateInput(input::HKBManager&) { + return false; +} + +void AppearMemoState::start() { + mTime = 0.0f; + Manager::ConfigType configType = getManager()->getConfigType(); + switch (configType) { + case Manager::CT_Letter: + case Manager::CT_PhotoLetter: + InputForm()->setEditMode(InputForm::EM_Appear); + break; + default: + break; + } +} + +void EditMemoState::create() {} + +void EditMemoState::init() {} + +void EditMemoState::calc() { + if (ToolBar()->isQwerty()) { + PCKeyboard()->calc(); + } else { + static_cast(CellPhoneKeyboard())->calc(); + } + ToolBar()->calc(); + if (CandidateBox()->isActive()) { + CandidateBox()->calc(); + } + InputForm()->calc(); + if (static_cast(PredictLanguageSelectDialog())->isActive()) { + static_cast(PredictLanguageSelectDialog())->calc(); + } + if (static_cast(SignKeyboard())->isActive()) { + SignWindowLayout& signWindow = *static_cast(SignKeyboard()); + static_cast(signWindow).calc(); + } + if (getManager()->getConfigType() != Manager::CT_Letter && + getManager()->getConfigType() != Manager::CT_PhotoLetter) { + static_cast(BG())->calc(); + } +} + +void* State::PredictLanguageSelectDialog() { + return getManager()->getPredictLanguageSelectDialog(); +} + +void* State::SignKeyboard() { + return getManager()->getSignKeyboard(); +} + +void EditMemoState::draw() { + GXSetZMode(GX_TRUE, GX_LEQUAL, GX_TRUE); + if (getManager()->getConfigType() != Manager::CT_Letter && + getManager()->getConfigType() != Manager::CT_PhotoLetter) { + static_cast(BG())->draw(); + } + ToolBar()->draw(); + if (getManager()->getConfigType() != Manager::CT_Letter && + getManager()->getConfigType() != Manager::CT_PhotoLetter) { + InputForm()->draw(); + } + if (CandidateBox()->isActive()) { + CandidateBox()->draw(); + } + if (ToolBar()->isQwerty()) { + PCKeyboard()->draw(); + } else { + static_cast(CellPhoneKeyboard())->draw(); + } + if (static_cast(PredictLanguageSelectDialog())->isActive()) { + static_cast(PredictLanguageSelectDialog())->draw(); + } + if (static_cast(SignKeyboard())->isActive()) { + static_cast(SignKeyboard())->draw(); + } +} + +void EditMemoState::memoDraw() { + if (getManager()->getConfigType() == Manager::CT_Letter || + getManager()->getConfigType() == Manager::CT_PhotoLetter) { + InputForm()->draw(); + } +} + +bool EditMemoState::updateInput(int chan, f32 x, f32 y, u32 trig, u32 hold, u32 release) { + bool wasQwerty = ToolBar()->isQwerty(); + struct InputParameters { + int chan; + f32 x; + f32 y; + u32 trig; + u32 hold; + u32 release; + } inputParameters = {chan, x, y, trig, hold, release}; + HWKeyboard()->updateInput(chan, x, y, trig, hold, release, &inputParameters); + if (static_cast(PredictLanguageSelectDialog())->isActive()) { + return static_cast(PredictLanguageSelectDialog())->updateInput(chan, x, y, trig, hold, release, &inputParameters); + } + InputForm()->updateInputCommon(chan, trig, hold, release, &inputParameters); + if (static_cast(SignKeyboard())->isActive()) { + return static_cast(SignKeyboard())->updateInput( + chan, x, y, trig, hold, release, &inputParameters); + } + bool handled; + if (wasQwerty) { + handled = PCKeyboard()->updateInput(chan, x, y, trig, hold, release, &inputParameters); + } else { + handled = CellPhoneKeyboard()->updateInput(chan, x, y, trig, hold, release, &inputParameters); + } + bool toolbarHandled = ToolBar()->updateInput(chan, x, y, trig, hold, release, &inputParameters); + bool candidateHandled = false; + if (CandidateBox()->isActive()) { + candidateHandled = CandidateBox()->updateInput(chan, x, y, trig, hold, release, &inputParameters); + } + u32 inputHandled = 0; + if (!candidateHandled) { + inputHandled = InputForm()->updateInput(chan, x, y, trig, hold, release, &inputParameters); + } else { + InputForm()->updateInput(chan, (1.0f / 0.0f), (1.0f / 0.0f), trig, hold, release, &inputParameters); + } + handled = (handled | candidateHandled) | (inputHandled | toolbarHandled); + if (wasQwerty != ToolBar()->isQwerty()) { + InputForm()->onCommand(static_cast(6), NULL); + CandidateBox()->checkValidation(); + if (ToolBar()->isQwerty()) { + PCKeyboard()->onActive(); + } else { + CellPhoneKeyboard()->onActive(); + } + } + return handled; +} + +keyboard::hwkey::HWKeyboard* State::HWKeyboard() { + return getManager()->getHWKeyboard(); +} + +bool EditMemoState::updateInput(input::HKBManager& hkbManager) { + bool wasQwerty = ToolBar()->isQwerty(); + if (static_cast(PredictLanguageSelectDialog())->isActive()) { + return false; + } + HWKeyboard()->updateInput(hkbManager); + if (static_cast(SignKeyboard())->isActive()) { + return static_cast(SignKeyboard())->updateInput(hkbManager); + } + bool handled; + if (wasQwerty) { + handled = PCKeyboard()->updateInput(hkbManager); + } else { + handled = CellPhoneKeyboard()->updateInput(hkbManager); + } + if (wasQwerty != ToolBar()->isQwerty()) { + InputForm()->onCommand(static_cast(6), NULL); + CandidateBox()->checkValidation(); + if (ToolBar()->isQwerty()) { + PCKeyboard()->onActive(); + } else { + CellPhoneKeyboard()->onActive(); + } + } + return handled; +} + +void EditMemoState::start() { + if (getManager()->getConfigType() == Manager::CT_Letter || + getManager()->getConfigType() == Manager::CT_PhotoLetter) { + InputForm()->setEditMode(InputForm::EM_Edit); + InputForm()->getLayout()->GetRootPane()->SetTranslate(nw4r::math::VEC2(0.0f, sLetterMemoPosition.y)); + InputForm()->getLayout()->GetRootPane()->SetAlpha(255); + } else { + InputForm()->getLayout()->GetRootPane()->SetTranslate(nw4r::math::VEC2(0.0f, sHiddenMemoPosition.y)); + setPaneAlpha(InputForm()->getLayout()->GetRootPane(), static_cast(sAppearingMemoPosition.y)); + } + PCKeyboard()->getLayout()->GetRootPane()->SetTranslate(nw4r::math::VEC2(0.0f, sHiddenMemoPosition.y)); + CellPhoneKeyboard()->getLayout()->GetRootPane()->SetTranslate(nw4r::math::VEC2(0.0f, sHiddenMemoPosition.y)); + CandidateBox()->getLayout()->GetRootPane()->SetTranslate(nw4r::math::VEC2(0.0f, sHiddenMemoPosition.y)); + ToolBar()->getUpArea()->SetTranslate(nw4r::math::VEC2(0.0f, sHiddenMemoPosition.y / 3.0f)); + ToolBar()->getDownArea()->SetTranslate(nw4r::math::VEC2(0.0f, -sHiddenMemoPosition.y / 3.0f)); + static_cast(BG())->getLayout()->GetRootPane()->SetTranslate(nw4r::math::VEC2(0.0f, 0.0f)); + setPaneAlpha(PCKeyboard()->getLayout()->GetRootPane(), static_cast(sAppearingMemoPosition.y)); + setPaneAlpha(CellPhoneKeyboard()->getLayout()->GetRootPane(), static_cast(sAppearingMemoPosition.y)); + setPaneAlpha(CandidateBox()->getLayout()->GetRootPane(), static_cast(sAppearingMemoPosition.y)); + setPaneAlpha(ToolBar()->getUpArea(), static_cast(sAppearingMemoPosition.y)); + setPaneAlpha(ToolBar()->getDownArea(), static_cast(sAppearingMemoPosition.y)); + setPaneAlpha(static_cast(BG())->getLayout()->GetRootPane(), static_cast(sAppearingMemoPosition.y)); + PCKeyboard()->onActive(); + CellPhoneKeyboard()->onActive(); + if (ToolBar()->isQwerty()) PCKeyboard()->onActive(); + else CellPhoneKeyboard()->onActive(); +} + +void DisappearMemoState::calc() { + if (30.0f <= mTime) { + getManager()->changeState(Manager::STL_Transition); + } + InputForm()->calc(); + + f32 offset = textinput::util::hermiteInterporation( + mTime, 0.0f, sHiddenMemoPosition.y, 0.0f, + 30.0f, sHiddenMemoPosition.x, 0.0f); + PCKeyboard()->getLayout()->GetRootPane()->SetTranslate(nw4r::math::VEC2(0.0f, offset)); + CellPhoneKeyboard()->getLayout()->GetRootPane()->SetTranslate(nw4r::math::VEC2(0.0f, offset)); + CandidateBox()->getLayout()->GetRootPane()->SetTranslate(nw4r::math::VEC2(0.0f, offset)); + ToolBar()->getUpArea()->SetTranslate( + nw4r::math::VEC2(0.0f, offset / 3.0f)); + ToolBar()->getDownArea()->SetTranslate( + nw4r::math::VEC2(0.0f, -offset / 3.0f)); + static_cast(BG())->getLayout()->GetRootPane()->SetTranslate(nw4r::math::VEC2(0.0f, 0.0f)); + + f32 alpha = textinput::util::hermiteInterporation( + mTime, 0.0f, sAppearingMemoPosition.y, 0.0f, + 30.0f, sAppearingMemoPosition.x, 0.0f); + s32 alphaByte = static_cast(alpha); + setPaneAlpha(PCKeyboard()->getLayout()->GetRootPane(), alphaByte); + setPaneAlpha(CellPhoneKeyboard()->getLayout()->GetRootPane(), alphaByte); + setPaneAlpha(CandidateBox()->getLayout()->GetRootPane(), alphaByte); + setPaneAlpha(ToolBar()->getUpArea(), alphaByte); + setPaneAlpha(ToolBar()->getDownArea(), alphaByte); + setPaneAlpha(static_cast(BG())->getLayout()->GetRootPane(), alphaByte); + + Manager::ConfigType configType = getManager()->getConfigType(); + switch (configType) { + case Manager::CT_Letter: + case Manager::CT_PhotoLetter: { + f32 letterOffset = textinput::util::hermiteInterporation( + mTime, 0.0f, sLetterMemoPosition.y, 0.0f, + 30.0f, sLetterMemoPosition.x, 0.0f); + InputForm()->getLayout()->GetRootPane()->SetTranslate( + nw4r::math::VEC2(0.0f, letterOffset)); + setPaneAlpha(InputForm()->getLayout()->GetRootPane(), 0xff); + break; + } + default: { + InputForm()->getLayout()->GetRootPane()->SetTranslate( + nw4r::math::VEC2(0.0f, offset)); + setPaneAlpha(InputForm()->getLayout()->GetRootPane(), alphaByte); + } + } + mTime += 1.0f; +} + +void DisappearMemoState::start() { + mTime = 0.0f; + Manager::ConfigType configType = getManager()->getConfigType(); + switch (configType) { + case Manager::CT_Letter: + case Manager::CT_PhotoLetter: + InputForm()->setEditMode(InputForm::EM_Disappear); + getManager()->setSaveData(); + break; + default: + InputForm()->onClose(); + break; + } +} + +void bg::Base::init() {} + +void bg::Base::create(MEMAllocator*) {} + +void AppearMemoState::end() {} + +Manager::StateType DisappearMemoState::getStateType() { + return Manager::ST_Disappearing; +} + +void EditMemoState::end() {} + +Manager::StateType EditMemoState::getStateType() { + return Manager::ST_Visible; +} + +inline State::~State() {} + +Manager::StateType AppearMemoState::getStateType() { + return Manager::ST_Appearing; +} + +void DispMemoState::end() {} + +Manager::StateType DispMemoState::getStateType() { + return Manager::ST_Hidden; +} + } } } diff --git a/src/keyboard/tiCandidateBox.cpp b/src/keyboard/tiCandidateBox.cpp index 6b9e17b3..623f8cd8 100644 --- a/src/keyboard/tiCandidateBox.cpp +++ b/src/keyboard/tiCandidateBox.cpp @@ -44,6 +44,8 @@ namespace textinput { }; // name made up, no dwarf (?) + inline const char* commonScrollAnimationName() { return COMMON_SCROLL_ANIM; } + inline const char* commonTextAnimationName() { return COMMON_TEXT_ANIM; } struct PaneToAnimation { s32 type; char paneName[20]; @@ -85,7 +87,7 @@ namespace textinput { {KT_ScrollButton, "P_prdc_scrl_Rght", 7, - COMMON_SCROLL_ANIM, + commonScrollAnimationName(), {&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[4], &csAninationFile[5], &csAninationFile[6]}}, {KT_CandidateText, @@ -96,97 +98,97 @@ namespace textinput { {KT_CandidateText, "T_prdc_Text_01", 5, - COMMON_TEXT_ANIM, + commonTextAnimationName(), {&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}}, {KT_CandidateText, "T_prdc_Text_02", 5, - COMMON_TEXT_ANIM, + commonTextAnimationName(), {&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}}, {KT_CandidateText, "T_prdc_Text_03", 5, - COMMON_TEXT_ANIM, + commonTextAnimationName(), {&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}}, {KT_CandidateText, "T_prdc_Text_04", 5, - COMMON_TEXT_ANIM, + commonTextAnimationName(), {&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}}, {KT_CandidateText, "T_prdc_Text_05", 5, - COMMON_TEXT_ANIM, + commonTextAnimationName(), {&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}}, {KT_CandidateText, "T_prdc_Text_06", 5, - COMMON_TEXT_ANIM, + commonTextAnimationName(), {&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}}, {KT_CandidateText, "T_prdc_Text_07", 5, - COMMON_TEXT_ANIM, + commonTextAnimationName(), {&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}}, {KT_CandidateText, "T_prdc_Text_08", 5, - COMMON_TEXT_ANIM, + commonTextAnimationName(), {&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}}, {KT_CandidateText, "T_prdc_Text_09", 5, - COMMON_TEXT_ANIM, + commonTextAnimationName(), {&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}}, {KT_CandidateText, "T_prdc_Text_10", 5, - COMMON_TEXT_ANIM, + commonTextAnimationName(), {&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}}, {KT_CandidateText, "T_prdc_Text_11", 5, - COMMON_TEXT_ANIM, + commonTextAnimationName(), {&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}}, {KT_CandidateText, "T_prdc_Text_12", 5, - COMMON_TEXT_ANIM, + commonTextAnimationName(), {&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}}, {KT_CandidateText, "T_prdc_Text_13", 5, - COMMON_TEXT_ANIM, + commonTextAnimationName(), {&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}}, {KT_CandidateText, "T_prdc_Text_14", 5, - COMMON_TEXT_ANIM, + commonTextAnimationName(), {&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}}, {KT_CandidateText, "T_prdc_Text_15", 5, - COMMON_TEXT_ANIM, + commonTextAnimationName(), {&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}}, {KT_CandidateText, "T_prdc_Text_16", 5, - COMMON_TEXT_ANIM, + commonTextAnimationName(), {&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}}, {KT_CandidateText, "T_prdc_Text_17", 5, - COMMON_TEXT_ANIM, + commonTextAnimationName(), {&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}}, {KT_CandidateText, "T_prdc_Text_18", 5, - COMMON_TEXT_ANIM, + commonTextAnimationName(), {&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}}, {KT_CandidateText, "T_prdc_Text_19", 5, - COMMON_TEXT_ANIM, + commonTextAnimationName(), {&csAninationFile[0], &csAninationFile[1], &csAninationFile[2], &csAninationFile[3], &csAninationFile[6]}}, {KT_OnOffButton, "P_OnBtn", diff --git a/src/keyboard/tiHwKeyboard.cpp b/src/keyboard/tiHwKeyboard.cpp index 6fa8860c..0cac3b1a 100644 --- a/src/keyboard/tiHwKeyboard.cpp +++ b/src/keyboard/tiHwKeyboard.cpp @@ -1,3 +1,4 @@ +#define TIHWKEYBOARD_IMPLEMENTATION #include "keyboard/tiHwKeyboard.h" #include "keyboard/tiManager.h" @@ -247,6 +248,349 @@ namespace textinput { blr } +struct NavigationCommand { u32 command; u32 modifiers; }; +struct KeyInputData { + wchar_t character; + u16 flags; + u32 modifier; + u8 direct; + u8 repeated; + u16 reserved; + u32 data; +}; +extern const u8 controlKeys[]; + bool HWKeyboard::updateRepeatKey_(input::HKBManager& hkbManager) { + u32 modifierState = hkbManager.GetModifierState(); + input::HKBManager::KeySet currentKeySet; + currentKeySet = hkbManager.GetRepeatedKeySet(); + + if (!currentKeySet.IsValid()) { + return false; + } + + if (!mgr()->getToolBar()->isQwerty()) { + if (mgr()->getToolBar()->isEnableKeytopChange()) { + return true; + } + } + + u32 modifierFlag = modifierState & 0x8; + + while (currentKeySet.IsValid()) { + int key = currentKeySet.GetKey(); + u32 command; + + if (key == 0x4c) { + goto sendCommand2; + } + + if (key < 0x4c) { + if (key != 0x2b) { + if (key < 0x2b) { + if (key >= 0x2a) { + goto sendCommand1; + } + } else { + if (key >= 0x2d) { + goto nextRepeatedKey; + } + goto checkSpecialCommand; + } + } + goto nextRepeatedKey; + } + + if (key == 0x51) { + goto setNavigationCommand1e; + } + + if (key < 0x51) { + if (key == 0x4f) { + goto setNavigationCommand20; + } else if (key >= 0x4f) { + goto setNavigationCommand1f; + } + } else { + if (key >= 0x53) { + goto nextRepeatedKey; + } + goto setNavigationCommand1d; + } + + goto nextRepeatedKey; + + sendCommand2: + sendCommand(2, NULL); + goto nextRepeatedKey; + + sendCommand1: + sendCommand(1, NULL); + goto nextRepeatedKey; + + setNavigationCommand20: + command = 0x20; + goto sendNavigationCommand; + + setNavigationCommand1f: + command = 0x1f; + goto sendNavigationCommand; + + setNavigationCommand1e: + command = 0x1e; + goto sendNavigationCommand; + + setNavigationCommand1d: + command = 0x1d; + + sendNavigationCommand: + { + u32 commandData[2]; + commandData[0] = command; + commandData[1] = modifierState; + sendCommand(0x26, commandData); + } + goto nextRepeatedKey; + + checkSpecialCommand: + if (mgr()->getToolBar()->isQwerty() || + !mgr()->getCellPhoneKeyboard()->isNumeric()) { + if (modifierFlag == 0) { + goto sendSpecialCommand; + } + } + goto nextRepeatedKey; + + sendSpecialCommand: + { + NavigationCommand commandData = {8, modifierState}; + sendCommand(0x26, &commandData); + } + + nextRepeatedKey: + + currentKeySet = currentKeySet.GetNext(); + } + + return false; + } + + bool HWKeyboard::updateTriggerKey_(input::HKBManager& hkbManager) { + u32 modifierState = hkbManager.GetModifierState(); + input::HKBManager::KeySet currentKeySet; + currentKeySet = hkbManager.GetTriggeredKeySet(); + + if (!currentKeySet.IsValid()) { + return false; + } + + if (!mgr()->getToolBar()->isQwerty() && + mgr()->getToolBar()->isEnableKeytopChange()) { + return true; + } + + if (!mgr()->getPCKeyboard()->isABC()) { + if (mgr()->getToolBar()->isQwerty()) { + EventObserver* eventObserver = mgr()->getEventObserverForHardware(); + if (eventObserver != NULL) { + eventObserver->onSE(sound::SE_KETAI_MODE_SWITCHING); + } + } + mgr()->getPCKeyboard()->setABC(true); + } + + while (currentKeySet.IsValid()) { + u32 character = currentKeySet.GetWChar(); + u8 key = currentKeySet.GetKey(); + + if (static_cast(character) == 0x20) { + if ((modifierState & 0x8) != 0) { + NavigationCommand commandData = {8, modifierState}; + sendCommand(0x26, &commandData); + } + } else if (static_cast(character) != 0) { + bool sendCharacter = true; + if (!mgr()->getToolBar()->isQwerty() && + mgr()->getCellPhoneKeyboard()->isNumeric()) { + if (static_cast(character) == '/') { + goto suppressCharacter; + } + if (static_cast(character) < '/') { + if (static_cast(character) >= '.') { + goto checkNumericDot; + } + goto suppressCharacter; + } + if (static_cast(character) >= ':') { + goto suppressCharacter; + } + goto sendCharacterCheck; + checkNumericDot: + if (mgr()->getCellPhoneKeyboard()->isNumericWithDot()) { + goto sendCharacterCheck; + } + suppressCharacter: + sendCharacter = false; + } + + goto sendCharacterCheck; + sendCharacterCheck: + if (sendCharacter) { + modifierState = 0; + if ((hkbManager.GetModifierState() & 0x2) != 0) { + modifierState |= 1; + } + if ((hkbManager.GetModifierState() & 0x200) != 0) { + modifierState |= 2; + } + if ((modifierState & 1) == 0) { + keyboard::pctype::Base::KeyState& keyState = mgr()->getPCKeyboard()->hardwareKeyState(); + keyState.setABCFlag(keyState.abcFlags & 0xffffff70); + } + + character = convertWCCode(character); + KeyInputData keyInputData = {0, 0, 0, 1, 0, 0, 0}; + keyInputData.character = character; + keyInputData.modifier = modifierState; + sendCommand(0, &keyInputData); + + if (mgr()->getLanguage() == CN) { + if (static_cast(character + (0x10000 - 0x201c)) <= 1) { + field_0x16 = !field_0x16; + } else if (static_cast(character + (0x10000 - 0x2018)) <= 1) { + field_0x15 = !field_0x15; + } + + } + } + } else { + bool sendKey = true; + int translatedKey; + if (key < 0x20) { + translatedKey = 0; + } else if (key < 0x98) { + translatedKey = controlKeys[key - 0x20]; + } else if (key < 0xe0) { + translatedKey = 0; + } else if (key < 0xf0) { + translatedKey = controlKeys[key - 0x68]; + } else { + translatedKey = 0; + } + + if (translatedKey == 0x1c) { + bool capsLock = !(hkbManager.GetModifierState() & 0x100); + if (!mgr()->getToolBar()->isQwerty() && + mgr()->getCellPhoneKeyboard()->isNumeric()) { + capsLock = true; + } + hkbManager.SetModifierState(capsLock ? 0x100 : 0, 0x100); + } + + if (mgr()->getToolBar()->isQwerty() || + !mgr()->getCellPhoneKeyboard()->isNumeric()) { + goto sendKeyCheck; + } + + switch (translatedKey) { + case 0x15: + case 0x16: + case 0x1d: + case 0x1e: + case 0x1f: + case 0x20: + break; + default: + sendKey = false; + break; + } + sendKeyCheck: + if (sendKey) { + u32 commandData[2] = {translatedKey, modifierState}; + sendCommand(0x26, commandData); + } + } + + int capsKey = currentKeySet.GetKey(); + switch (capsKey) { + case 0x39: + if (mgr()->getToolBar()->isQwerty() || + mgr()->getToolBar()->isEnableKeytopChange()) { + mgr()->getPCKeyboard()->onPressedCaps(); + } + break; + default: + break; + } + + currentKeySet = currentKeySet.GetNext(); + } + + return false; + } + +const u8 controlKeys[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x01, 0x0a, 0x03, + 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, + 0x00, 0x04, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, + 0x2b, 0x2c, 0x19, 0x1a, 0x1b, 0x13, 0x15, 0x17, 0x14, 0x16, 0x18, 0x00, + 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x0f, 0x0e, + 0x00, 0x00, 0x00, 0x00, + 0x11, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x05, 0x07, 0x0b, + 0x06, 0x05, 0x07, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +}; + bool HWKeyboard::updateTappingShift_(input::HKBManager& hkbManager) { + hkbManager.GetModifierState(); + input::HKBManager::KeySet currentKeySet; + input::HKBManager::KeySet triggeredKeySet; + input::HKBManager::KeySet releasedKeySet; + input::HKBManager::KeySet releasedNextKeySet; + triggeredKeySet = hkbManager.GetTriggeredKeySet(); + currentKeySet = triggeredKeySet; + + while (currentKeySet.IsValid()) { + int key = currentKeySet.GetKey(); + switch (key) { + case 0xe5: + case 0xe1: + field_0x14 = 1; + return false; + default: + field_0x14 = 0; + currentKeySet = currentKeySet.GetNext(); + break; + } + } + + if (field_0x14 == 0) { + return false; + } + + releasedKeySet = hkbManager.GetReleasedKeySet(); + currentKeySet = releasedKeySet; + while (currentKeySet.IsValid()) { + int key = currentKeySet.GetKey(); + switch (key) { + case 0xe5: + case 0xe1: + field_0x14 = 0; + if (mgr()->getToolBar()->isQwerty() && + mgr()->getPCKeyboard()->hardwareLanguageKeyActive()) { + sendCommand(0x2e, NULL); + } + return false; + default: + currentKeySet = currentKeySet.GetNext(); + break; + } + } + + return false; + } + HWKeyboard::HWKeyboard(Manager* manager) : mpManager(manager), field_0x14(0), field_0x15(0), field_0x16(0) { } @@ -474,3 +818,4 @@ namespace textinput { } // namespace keyboard } // namespace textinput + diff --git a/tools/decomp-assist/MyTiManager.attempts.md b/tools/decomp-assist/MyTiManager.attempts.md new file mode 100644 index 00000000..0b7e5177 --- /dev/null +++ b/tools/decomp-assist/MyTiManager.attempts.md @@ -0,0 +1,89 @@ +# MyTiManager matching attempts + +Baseline: 84/91 instruction-exact functions, 12748/20196 code bytes, +20/1132 reported data bytes. Existing pool was identical. + +## reflectSaveData + +1. Branch directly on revision one: six instructions versus eight. +2. Switch with revision one and a default call: seven versus eight. +3. Separate revision-zero/default calls: eleven versus eight. +4. Revision-zero break followed by the shared default call: eight/eight, + zero instruction differences. + +## DispMemoState::start + +1. Reconstructed pane translations and alpha assignments using VEC3 and + byte conversion: 321/326 instructions. +2. VEC2 translations and an integer alpha helper: 325/326. +3. Corrected toolbar pane accessor order under the private header guard, + and used the configuration switch: 326/326, zero differences. + +## EditMemoState::start + +1. Full initialization with VEC3 and direct byte conversion: 381/385. +2. VEC2 and integer alpha helper: 385/385, four accessor-slot differences. +3. Corrected the toolbar accessor declarations in the private guard: + 385/385, zero differences. + +## AppearMemoState::calc + +1. Reconstructed interpolation, pane movement, alpha and scrolling: + 437/428. Background movement, toolbar alpha and configuration branches + differed from the target. +2. Kept the background stationary, used the configuration switch and removed + the extra toolbar alpha assignment: 428/428, one accessor-slot difference. +3. Applied alpha to the upper toolbar pane: 428/428, zero differences. + +## EditMemoState::updateInput + +1. Restored common input processing and candidate-dependent pointer handling. + Infinity is computed with ordinary floating arithmetic. 306/309; + caching the prediction dialog removed the repeated virtual getter. +2. Repeated the prediction getter as the target does: 309/309, two register + differences in the combined return value. +3. Reused the keyboard-handled local for the combined result: + 309/309, zero differences. + +## DisappearMemoState::calc + +1. Restored animation interpolation and pane assignments: 370/342. +2. Kept the background stationary, used the configuration switch and removed + the scrolling operation absent from the target: 342/342, zero differences. + +## Static initialization and data + +1. Corrected DisappearMemoState to inherit AppearMemoState and its timer, + and made State's abstract operations pure under the private guard: + 63/64 initializer instructions; the derived table now inherits the correct + appearance operations. +2. Explicit background base construction and moving base function definitions + earlier did not change the initializer differences. Discarded. +3. Inline definitions for the base destructor and background operations: + 64/64, four remaining state-table offsets. Retained the inline State + destructor; discarded the ineffective background edits. +4. Background constructor moved out of the class with an inline definition: + same four offsets; createBG stayed exact. Discarded. +5. Restored function definitions to target object order and fixed the real + letter/photo-letter translation values to 145 and 151. This made the + floating constant pool identical, rather than relying on relocation-only + function scoring. Restored the background destructor omitted by the + ordering experiment before accepting the result. +6. External state globals: no code change, worse .bss score (40% versus 60%). + Reverted to the existing static definitions. +7. Included the background class declarations after the memo state classes: + moved its tables ahead of the state tables, but the strong background + destructor also emitted its derived table there. +8. Made the background destructor inline only for this unit, preserving the + existing header branches: its deduplicated derived table remains external, + background Base is first, and all four state offsets match. Initializer: + 64/64, zero differences. All 91 functions are instruction-exact. + +Pool remains identical. .sdata, .sdata2, .sbss and .ctors report 100%. +Reported .data remains 61.94834% and .bss 60.000004%. The original splits the +Manager vtable at 0x33c into a separately named 156-byte symbol; the compiler +emits one ordinary 320-byte vtable. Its entries and relocations through 0x3ac +agree. The extracted original additionally ends in 40 zero bytes after the +vtable; no source padding was added. The .bss registry buffers and state +objects have identical offsets and 72 zero bytes, but different buffer symbol +boundaries. No symbol configuration or hand-placed data was introduced. diff --git a/tools/decomp-assist/tiCandidateBox.attempts.md b/tools/decomp-assist/tiCandidateBox.attempts.md new file mode 100644 index 00000000..f87c7813 --- /dev/null +++ b/tools/decomp-assist/tiCandidateBox.attempts.md @@ -0,0 +1,41 @@ +# tiCandidateBox continuation + +Baseline: 104/112 objdiff, 102/112 instruction exact; code 17112/24000, data 1132/4652. + +Closest functions first: CalcPaneLocate_, StartScrollToIdx, StartScroll, GetPrevPageIdx_. Attempts 1 reorder margin/scale evaluation, 2 reverse multiplication and use an unsigned fixed pane-loop index, 3 reorder evaluation and addition. None improved the baseline. + +Draw: attempt 1 sequential vector initialization, 2 full scissor rectangle (12 differences), 3 direct corner initialization. Discarded attempt 2 because two unused fields add no readability; original retained. + +createAnmPane_: attempt 1 widened counters, 2 animation reference, 3 direct ID retrieval. All discarded. + +create: attempt 1 combined string allocation/construction, 2 combined candidate allocation/construction, 3 passed the saved allocator. All discarded. + +Static initializer: attempt 1 inline name access by value (exact), 2 const record member (22 differences), 3 inline name access by reference (exact). Retained meaningful shared-name accessors; 25/25 instructions, zero differences. + +Data: pool identical; .rodata and .sdata2 100%. Changing the existing empty-text array's final 1 to the target zero moved its storage and reduced .sdata to 75%; reverted. Existing pinned data and assembly not expanded. No shared-header changes. + +Measured trials: +- CalcPaneLocate_ attempt 1: src 0x6d0 base 0x6cc insns 436/435; --- insert mine 29:29 base 29:31 +- StartScrollToIdx attempt 1: src 0x2e4 base 0x2e0 insns 185/184; --- insert mine 21:21 base 21:23 +- StartScroll attempt 1: src 0x2e8 base 0x2e4 insns 186/185; --- insert mine 21:21 base 21:23 +- GetPrevPageIdx_ attempt 1: src 0x208 base 0x204 insns 130/129; --- replace mine 23:24 base 23:24 +- CalcPaneLocate_ attempt 2: src 0x6cc base 0x6cc insns 435/435; diffs 50: [34, 39, 41, 69, 168, 170, 247, 248, 249, 250, 254, 255, 258, 259, 260, 264, 266, 267, 269, 271] +- StartScrollToIdx attempt 2: src 0x2e0 base 0x2e0 insns 184/184; diffs 21: [27, 33, 35, 47, 54, 58, 60, 65, 70, 73, 74, 85, 88, 97, 102, 103, 121, 126, 141, 142] +- StartScroll attempt 2: src 0x2e4 base 0x2e4 insns 185/185; diffs 27: [27, 33, 35, 41, 50, 54, 56, 57, 58, 61, 63, 68, 73, 76, 77, 88, 90, 98, 106, 110] +- GetPrevPageIdx_ attempt 2: src 0x204 base 0x204 insns 129/129; diffs 23: [28, 36, 38, 39, 42, 51, 52, 58, 59, 61, 63, 64, 65, 71, 75, 76, 79, 80, 89, 90] +- CalcPaneLocate_ attempt 3: src 0x6d0 base 0x6cc insns 436/435; --- insert mine 29:29 base 29:31 +- StartScrollToIdx attempt 3: src 0x2e4 base 0x2e0 insns 185/184; --- insert mine 21:21 base 21:23 +- StartScroll attempt 3: src 0x2e8 base 0x2e4 insns 186/185; --- insert mine 21:21 base 21:23 +- GetPrevPageIdx_ attempt 3: src 0x208 base 0x204 insns 130/129; --- replace mine 23:24 base 23:24 +- Draw attempt 1: src 0x310 base 0x310 insns 196/196; diffs 33: [0, 2, 3, 68, 72, 73, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 93] +- createAnmPane_ attempt 1: src 0x36c base 0x360 insns 219/216; --- replace mine 0:1 base 0:1 +- create attempt 1: src 0x57c base 0x580 insns 351/352; --- replace mine 5:6 base 5:6 +- Draw attempt 2: src 0x310 base 0x310 insns 196/196; diffs 12: [0, 2, 3, 83, 84, 85, 143, 145, 148, 190, 192, 194] +- createAnmPane_ attempt 2: src 0x358 base 0x360 insns 214/216; --- insert mine 5:5 base 5:8 +- create attempt 2: src 0x57c base 0x580 insns 351/352; --- replace mine 5:6 base 5:6 +- Draw attempt 3: src 0x310 base 0x310 insns 196/196; diffs 33: [0, 2, 3, 68, 72, 73, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 93] +- createAnmPane_ attempt 3: src 0x370 base 0x360 insns 220/216; --- delete mine 5:6 base 5:5 +- create attempt 3: src 0x57c base 0x580 insns 351/352; --- replace mine 5:6 base 5:6 +- static initializer attempt 1: src 0x64 base 0x64 insns 25/25; diffs 0: [] +- static initializer attempt 2: src 0x64 base 0x64 insns 25/25; diffs 22: [1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21] +- static initializer attempt 3: src 0x64 base 0x64 insns 25/25; diffs 0: [] diff --git a/tools/decomp-assist/tiHwKeyboard.attempts.md b/tools/decomp-assist/tiHwKeyboard.attempts.md new file mode 100644 index 00000000..d7ddc26e --- /dev/null +++ b/tools/decomp-assist/tiHwKeyboard.attempts.md @@ -0,0 +1,19 @@ +# tiHwKeyboard + +Baseline: 7/10 exact, 1676/4596 code bytes, 296/568 data bytes. Three functions were absent. Existing assembly bodies and pinned data were not expanded. + +- updateTappingShift_: typed KeySet iteration and inherited keyboard fields reproduce 145/145 instructions exactly on the first implementation. +- updateRepeatKey_ attempt 1: scalar space command produced 182/180 instructions and an extra saved register. +- attempt 2: copying a static NavigationCommand aggregate produced 184/180 and a larger frame. +- attempt 3: initialize the local NavigationCommand with {8, modifierState}; 180/180, one mask difference when using a boolean modifier. +- attempt 4: preserve the masked u32 modifier; 180/180, zero differences. +- updateTriggerKey_ attempt 1: copying the static character-input template was hoisted; 407/405, extra frame space. +- attempt 2: separate aggregate assignment and wider character temporary: 403/405, register and stack differences. +- attempt 3: local navigation aggregate and numeric range simplification: 405/405, 284 differences, mostly allocation/frame offsets. +- attempt 4: initialize the character aggregate locally; 400/405, template copy now occurs inside the loop. +- attempt 5: accurate u32 GetWChar declaration and explicit wchar_t narrowing; restored numeric filter switch. 404/405, quote handling remained. +- attempt 6: quote switch: 405/405, 14 branch differences. +- attempt 7: wchar_t quote-pair ranges: 404/405, missing high-half addition. +- attempt 8: express modular quote distances as character + (0x10000 - quote); 405/405, zero differences. + +Data: the first 64 extracted .rodata bytes belong to the preceding letter animation table (documented in MyTiLetterForm.attempts.md). They were not recreated as hardware dummy data. The real hardware key map and character-input template use ordinary typed C++ objects. Moving the key map after its consumer preserves all exact functions; moving country definitions after their assembly consumer failed compilation and was reverted. Target .bss is unreferenced extracted space; .sdata2 includes trailing zeros. No padding or force-active objects were added. Pools remain identical. Shared changes are isolated behind TIHWKEYBOARD_IMPLEMENTATION. -- 2.49.1 From 6b6215ad3ea99ba27fbab1a1ae45f8d030550a60 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Wed, 30 Sep 2026 00:15:46 -0500 Subject: [PATCH 2/5] CDBRecord 26/29, CDBIntArray 13/13, NWC24Download (worker 231065dc) (#334) --- README.md | 4 +- libs/RevoEX/include/private/cdb/CDBRecord.h | 13 + .../RevoEX/include/revolution/cdb/CDBRecord.h | 16 + libs/RevoEX/src/cdb/CDBIntArray.c | 211 ++++ libs/RevoEX/src/cdb/CDBRecord.c | 953 ++++++++++++++++++ libs/RevoEX/src/nwc24/NWC24Download.c | 766 ++++---------- tools/decomp-assist/CDBIntArray.attempts.md | 29 + tools/decomp-assist/CDBRecord.attempts.md | 31 + tools/decomp-assist/NWC24Download.attempts.md | 131 +++ 9 files changed, 1607 insertions(+), 547 deletions(-) create mode 100644 libs/RevoEX/src/cdb/CDBIntArray.c create mode 100644 libs/RevoEX/src/cdb/CDBRecord.c create mode 100644 tools/decomp-assist/CDBIntArray.attempts.md create mode 100644 tools/decomp-assist/CDBRecord.attempts.md create mode 100644 tools/decomp-assist/NWC24Download.attempts.md diff --git a/README.md b/README.md index 3f88af20..b51194be 100644 --- a/README.md +++ b/README.md @@ -53,9 +53,9 @@ Progress | Decompiled | Matched | Linked | Data | |:---:|:---:|:---:|:---:| -| 87.88% | 77.62% | 56.92% | 88.23% | +| 88.20% | 77.88% | 56.92% | 88.24% | -units 752/1027 complete, functions 11324/12563 matched. +units 752/1027 complete, functions 11369/12563 matched. decompiled = code with a C/C++ implementation (objdiff fuzzy), matched = byte-exact code, linked = code actually linked into the DOL, data = byte-exact data diff --git a/libs/RevoEX/include/private/cdb/CDBRecord.h b/libs/RevoEX/include/private/cdb/CDBRecord.h index b0701d90..98f146c0 100644 --- a/libs/RevoEX/include/private/cdb/CDBRecord.h +++ b/libs/RevoEX/include/private/cdb/CDBRecord.h @@ -4,19 +4,32 @@ #include #include #include +#ifdef CDB_RECORD_IMPLEMENTATION +#include +#endif #ifdef __cplusplus extern "C" { #endif // __cplusplus typedef struct _CDBRecordFile { +#ifdef CDB_RECORD_IMPLEMENTATION + OSMutex mutex; + BOOL used; +#else u8 unk_0x00[0x1C - 0x00]; +#endif int unk_0x1C; CDBAttr attr; // 0x20 CDBBridgeFile bridgeFile; // 0x42C u8 unk_0x434[0x438 - 0x434]; CDBRecordKey key; // 0x438 +#ifdef CDB_RECORD_IMPLEMENTATION + u32 database; + u8 reserved[0x480 - 0x46C]; +#else u8 unk_0x468[0x480 - 0x468]; +#endif } CDBRecordFile; enum { diff --git a/libs/RevoEX/include/revolution/cdb/CDBRecord.h b/libs/RevoEX/include/revolution/cdb/CDBRecord.h index c6d28406..4be8dfc6 100644 --- a/libs/RevoEX/include/revolution/cdb/CDBRecord.h +++ b/libs/RevoEX/include/revolution/cdb/CDBRecord.h @@ -86,10 +86,26 @@ CDBErr CDBRecordClose(CDBRecord* record); CDBErr CDBRecordGetDataSize(CDBRecord* record, u32* recordSize); CDBErr CDBRecordGetId(CDBRecord* record, CDBId* id); +#ifdef CDB_RECORD_IMPLEMENTATION +void CDBRecordGetCalendarTimeForce(CDBRecord* record, int* year, int* month, int* day, int* hour, int* min, int* sec); +#else CDBErr CDBRecordGetCalendarTimeForce(CDBRecord* record, int* year, int* month, int* day, int* hour, int* min, int* sec); +#endif +#ifdef CDB_RECORD_IMPLEMENTATION +void CDBRecordGetKeyForce(CDBRecord* record, CDBRecordKey* recordKey); +#else CDBErr CDBRecordGetKeyForce(CDBRecord* record, CDBRecordKey* recordKey); +#endif +#ifdef CDB_RECORD_IMPLEMENTATION +void CDBRecordGetTypeForce(CDBRecord* record, char* type); +#else CDBErr CDBRecordGetTypeForce(CDBRecord* record, char* type); +#endif +#ifdef CDB_RECORD_IMPLEMENTATION +void CDBRecordGetGameCodeForce(CDBRecord* record, char* gcStr); +#else CDBErr CDBRecordGetGameCodeForce(CDBRecord* record, char* gcStr); +#endif CDBErr CDBRecordRemove(CDBRecord* record); diff --git a/libs/RevoEX/src/cdb/CDBIntArray.c b/libs/RevoEX/src/cdb/CDBIntArray.c new file mode 100644 index 00000000..e71fa95f --- /dev/null +++ b/libs/RevoEX/src/cdb/CDBIntArray.c @@ -0,0 +1,211 @@ +#include +#include + +typedef struct { + int* values; + int capacity; + int size; + int direction; +} CDBIntArray; + +void CDBIntCopy(int* destination, const int* value) { + *destination = *value; +} + +int CDBIntCompare(const int* left, const int* right) { + if (*left < *right) { + return -1; + } + return *left != *right; +} + +void CDBIntArrayInit(CDBIntArray* array, int* values, int capacity) { + array->size = 0; + array->direction = 1; + array->capacity = capacity; + array->values = values; +} + +void CDBIntArraySetReverse(CDBIntArray* array) { + array->direction = -1; +} + +int CDBIntArraySize(CDBIntArray* array) { + return array->size; +} + +int* CDBIntArrayAt(CDBIntArray* array, int index) { + return array->values + index; +} + +BOOL CDBIntArrayEmpty(CDBIntArray* array) { + return array->size == 0; +} + +BOOL CDBIntArrayFull(CDBIntArray* array) { + return array->capacity <= array->size; +} + +int* CDBIntArrayEnd(CDBIntArray* array) { + return array->values + array->size; +} + +#pragma dont_inline on +int CDBIntArrayDicInsertR(CDBIntArray* array, int* value, int first, int last) { + int index; + int result; + + if (first == last || first == last - 1) { + result = ((*(value) < *(array->values + first)) ? -1 : (*(value) != *(array->values + first))); + if (result < 0) { + return first; + } + + result = ((*(value) < *(array->values + last)) ? -1 : (*(value) != *(array->values + last))); + index = last; + if (result >= 0) { + index = last + 1; + } + return index; + } + + index = first + (last - first) / 2; + result = ((*(value) < *(array->values + index)) ? -1 : (*(value) != *(array->values + index))); + if (result < 0) { + return CDBIntArrayDicInsertR(array, value, first, index); + } + if (result > 0) { + return CDBIntArrayDicInsertR(array, value, index, last); + } + + return index; +} + +int* CDBIntArrayDicInsert(CDBIntArray* array, int* value) { + int size = array->size; + int index; + int moveCount; + int* record; + int number; + int stored; + + if (size == 0) { + if (size < array->capacity) { + record = array->values + size; + *record = *value; + array->size++; + } + return value; + } + + if (array->capacity <= size) { + if (array->direction == 1) { + if (size != 0) { + record = array->values + (size - 1); + } else { + record = array->values; + } + number = *value; + stored = *record; + if ((stored < number ? -1 : stored != number) < 0) { + return record; + } + + array->size--; + index = CDBIntArrayDicInsertR(array, value, 0, array->size - 1); + moveCount = (array->size - index) * sizeof(int); + if (array->capacity <= array->size) { + moveCount -= sizeof(int); + } + if (moveCount > 0) { + memmove((array->values + (index + 1)), (array->values + index), moveCount); + } + *(array->values + index) = *value; + if (array->size < array->capacity) { + array->size++; + } + return (array->values + index); + } + + record = array->values; + number = *value; + if ((number < *record ? -1 : number != *record) < 0) { + return record; + } + + array->size--; + if (array->size >= 0 && array->capacity - 1 >= 0) { + memmove(array->values, array->values + 1, array->size * sizeof(int)); + } + index = CDBIntArrayDicInsertR(array, value, 0, array->size - 1); + moveCount = (array->size - index) * sizeof(int); + if (array->capacity <= array->size) { + moveCount -= sizeof(int); + } + if (moveCount > 0) { + memmove((array->values + (index + 1)), (array->values + index), moveCount); + } + *(array->values + index) = *value; + if (array->size < array->capacity) { + array->size++; + } + return (array->values + index); + } + + index = CDBIntArrayDicInsertR(array, value, 0, size - 1); + moveCount = (array->size - index) * sizeof(int); + if (array->capacity <= array->size) { + moveCount -= sizeof(int); + } + if (moveCount > 0) { + memmove((array->values + (index + 1)), (array->values + index), moveCount); + } + *(array->values + index) = *value; + if (array->size < array->capacity) { + array->size++; + } + return (array->values + index); +} + +int CDBIntArrayDicFindR(CDBIntArray* array, int* value, int first, int last) { + int index; + int result; + + if (first == last || first == last - 1) { + result = ((*(value) < *(array->values + first)) ? -1 : (*(value) != *(array->values + first))); + if (result == 0) { + return first; + } + + result = ((*(value) < *(array->values + last)) ? -1 : (*(value) != *(array->values + last))); + return result != 0 ? -1 : last; + } + + index = first + (last - first) / 2; + result = ((*(value) < *(array->values + index)) ? -1 : (*(value) != *(array->values + index))); + if (result < 0) { + return CDBIntArrayDicFindR(array, value, first, index); + } + if (result > 0) { + return CDBIntArrayDicFindR(array, value, index, last); + } + + return index; +} + +#pragma dont_inline reset +int* CDBIntArrayDicFind(CDBIntArray* array, int* value) { + int size = array->size; + int index; + + if (size == 0) { + return array->values + size; + } + + index = CDBIntArrayDicFindR(array, value, 0, size - 1); + if (index != -1) { + return array->values + index; + } + + return array->values + array->size; +} diff --git a/libs/RevoEX/src/cdb/CDBRecord.c b/libs/RevoEX/src/cdb/CDBRecord.c new file mode 100644 index 00000000..43ac6224 --- /dev/null +++ b/libs/RevoEX/src/cdb/CDBRecord.c @@ -0,0 +1,953 @@ +#define CDB_RECORD_IMPLEMENTATION +#include +#include + +#include +#include + +#include +#include + +typedef struct { + u8 state[0xC010]; + u32 openFlags; +} CDBRecordDatabaseState; + +typedef struct { + u8 buf[0xD0]; +} NETHMACContext; + +typedef struct { + u8 buf[0x120]; +} NETAESContext; + +extern CDBErr CDBCryptBufAllocate(CDBCryptBuf** cryptBuf); +extern CDBErr CDBCryptBufFree(CDBCryptBuf** cryptBuf); +extern void CDBLock(void); +extern void CDBUnlock(void); +extern BOOL CDBRecordBelongedDBOpenedAsRW(CDBRecord* record); +extern void CDBGetWiiIdKey(char* wiiIdKey); +extern void CDBCopyWiiIdKey(char* wiiIdKey1, char* wiiIdKey2); +extern void CDBGetDeviceKey(char* devKey); +extern BOOL CDBFSIsExistFile(const char* fileName, CDBLocation location); +extern const void* NETGetSHA1Interface(void); +extern void NETHMACInit(NETHMACContext* context, const void* interface, const void* key, u32 keyLength); +extern void NETHMACUpdate(NETHMACContext* context, const void* data, u32 length); +extern void NETHMACGetDigest(NETHMACContext* context, void* digest); +extern BOOL NETAESCreate(NETAESContext* context, const void* key, u32 keyLength, const void* iv); +extern void NETAESDelete(NETAESContext* context); +extern BOOL NETAESEncrypt(NETAESContext* context, void* dst, const void* src, u32 length); +extern BOOL NETAESDecrypt(NETAESContext* context, void* dst, const void* src, u32 length); + +static u8 s_cdbCryptBuffer[0x40] ALIGN32; +static u8 s_cdbCryptBufferResult[0x40] ALIGN32; +static const u8 s_cdbCryptKey[0x10] = {0}; + +CDBErr CDBRecordOpen_(CDBRecord* record); +CDBErr CDBRecordOpenReadOnly_(CDBRecord* record); +CDBErr CDBRecordClose_(CDBRecord* record); +CDBErr CDBRecordWrite_(CDBRecord* record, void* buffer, u32 size); +CDBErr CDBRecordRemove_(CDBRecord* record); +CDBErr CDBRecordBackupToSD_(CDBRecord* record); +CDBErr CDBRecordUpdateModifiedDate(CDBRecord* record); +CDBErr CDBRecordEncrypt(CDBRecord* record, void* buffer, CDBRecordKey* key, u32 size, u32* encryptedSize); +CDBErr CDBRecordDecrypt(CDBRecord* record, void* buffer, u32 size, u32* dataSize, CDBRecordKey* key); + +void CDBRecordInstanceInit(CDBRecordFile* recordFile, CDBRecord* record, int type) { + OSLockMutex((OSMutex*)recordFile); + recordFile->used = 1; + OSUnlockMutex((OSMutex*)recordFile); + recordFile->unk_0x1C = type; + recordFile->database = record->unk_0x00; + CDBAttrInit(&recordFile->attr); + CDBRecordKeyCopy(&recordFile->key, &record->key); +} + +BOOL CDBRecordInstanceIsUsed(CDBRecordFile* recordFile) { + BOOL used; + OSLockMutex((OSMutex*)recordFile); + used = recordFile->used; + OSUnlockMutex((OSMutex*)recordFile); + return used; +} + +void CDBRecordInitDescriptor(CDBRecord* record, CDBDatabase* database, CDBRecordKey* key) { + CDBLock(); + record->unk_0x00 = (u32)database; + CDBRecordKeyCopy(&record->key, key); + record->cryptBuf = NULL; + record->file = NULL; + CDBUnlock(); +} + +CDBErr CDBRecordCreateAtOnce(CDBRecord* record, CDBDatabase* database, const char* desc, char* fileType, CDBDate epoch, int gameCode, u16 makerCode, + void* buffer, u32 size) { + CDBRecordKey key; + CDBAttr attr; + CDBErr err; + + if (strlen(fileType) >= 6) { + return CDB_ERROR_19; + } + if (size < CDB_RECORD_BUFFER_SIZE) { + return CDB_ERROR_20; + } + + CDBRecordKeyInit(&key, epoch, gameCode, makerCode, 0, fileType, CDB_FS_LOCATION_NAND); + CDBLock(); + record->unk_0x00 = (u32)database; + CDBRecordKeyCopy(&record->key, &key); + record->cryptBuf = NULL; + record->file = NULL; + CDBUnlock(); + + err = CDBAttrCreateOnNAND(&attr, desc, epoch); + if (err != CDB_ERROR_OK) { + return err; + } + err = CDBAttrSetModifiedCount(&attr, 1); + if (err != CDB_ERROR_OK) { + return err; + } + memcpy(buffer, &attr, CDB_RECORD_BUFFER_SIZE); + return CDBRecordFileCreateAtOnce(record, buffer, size); +} + +CDBErr CDBRecordOpen(CDBRecord* record) { + CDBErr err; + CDBLock(); + err = CDBRecordOpen_(record); + CDBUnlock(); + return err; +} + +CDBErr CDBRecordOpen_(CDBRecord* record) { + char fullPath[256]; + CDBCryptBuf* cryptBuf; + CDBErr err; + CDBDatabase* database; + CDBRecordDatabaseState* instance; + + database = (CDBDatabase*)record->unk_0x00; + instance = database->instance; + record->cryptBuf = NULL; + if (instance == NULL) { + CDBReportError("(CDB) error : can't open the record; the database is closed\n"); + return CDB_ERROR_27; + } + if ((instance->openFlags & 2) == 0) { + CDBReportError("can't open the record; the database is READONLY\n"); + return CDB_ERROR_26; + } + CDBConvKeyToFullPath(&record->key, fullPath); + err = CDBRecordFileOpen(record, fullPath, CDB_RECORD_ALLOC_RW); + if (err != CDB_ERROR_OK) { + return err; + } + err = CDBRecordFileReadAttrBuf(record); + if (err != CDB_ERROR_OK) { + return err; + } + if (record->key.location == CDB_FS_LOCATION_SD) { + err = CDBCryptBufAllocate((CDBCryptBuf**)&record->cryptBuf); + if (err != CDB_ERROR_OK) { + return err; + } + cryptBuf = (CDBCryptBuf*)record->cryptBuf; + if (record == NULL || !CDBRecordKeyIsValid(&record->key)) { + err = CDB_ERROR_1; + } else { + if (record->key.location == CDB_FS_LOCATION_SD) { + goto open_location_ok; + } + err = CDB_ERROR_2; + goto open_result_ready; + open_location_ok: + if (CDBFSSDIsMounted()) { + err = CDBRecordDecrypt(record, cryptBuf, 0x3EC00, &cryptBuf->unk_0x3EC00, NULL); + } else { + err = CDB_ERROR_SD_IS_NOT_MOUNTED; + } + } + open_result_ready: + if (err != CDB_ERROR_OK) { + CDBCryptBufFree((CDBCryptBuf**)&record->cryptBuf); + return err; + } + cryptBuf->unk_0x3EC04 = sizeof(CDBAttrBuf); + } + return CDB_ERROR_OK; +} + +CDBErr CDBRecordOpenReadOnly(CDBRecord* record) { + CDBErr err; + CDBLock(); + err = CDBRecordOpenReadOnly_(record); + CDBUnlock(); + return err; +} + +CDBErr CDBRecordOpenReadOnly_(CDBRecord* record) { + char fullPath[260]; + CDBErr err; + CDBErr result; + CDBCryptBuf* cryptBuf; + + record->cryptBuf = NULL; + if (!CDBRecordKeyIsValid(&record->key)) { + CDBReportError("invalid key\n"); + return CDB_ERROR_5; + } + CDBConvKeyToFullPath(&record->key, fullPath); + err = CDBRecordFileOpen(record, fullPath, CDB_RECORD_ALLOC_READ); + if (err != CDB_ERROR_OK) { + return err; + } + err = CDBRecordFileReadAttrBuf(record); + if (err != CDB_ERROR_OK) { + return err; + } + if (record->key.location == CDB_FS_LOCATION_SD) { + err = CDBCryptBufAllocate((CDBCryptBuf**)&record->cryptBuf); + if (err != CDB_ERROR_OK) { + return err; + } + cryptBuf = (CDBCryptBuf*)record->cryptBuf; + if (record == NULL || !CDBRecordKeyIsValid(&record->key)) { + result = CDB_ERROR_1; + } else { + if (record->key.location == CDB_FS_LOCATION_SD) { + goto location_ok; + } + result = CDB_ERROR_2; + goto result_ready; + location_ok: + if (CDBFSSDIsMounted()) { + result = CDBRecordDecrypt(record, cryptBuf, 0x3EC00, &cryptBuf->unk_0x3EC00, NULL); + } else { + result = CDB_ERROR_SD_IS_NOT_MOUNTED; + } + } + result_ready: + if (result != CDB_ERROR_OK) { + CDBCryptBufFree((CDBCryptBuf**)&record->cryptBuf); + return result; + } + cryptBuf->unk_0x3EC04 = sizeof(CDBAttrBuf); + } + return CDB_ERROR_OK; +} + +CDBErr CDBRecordClose(CDBRecord* record) { + CDBErr err; + CDBLock(); + err = CDBRecordClose_(record); + CDBUnlock(); + return err; +} + +CDBErr CDBRecordClose_(CDBRecord* record) { + CDBRecordFile* recordFile; + CDBErr err; + + recordFile = record->file; + if (record->cryptBuf != NULL) { + err = CDBCryptBufFree((CDBCryptBuf**)&record->cryptBuf); + if (err != CDB_ERROR_OK) { + return err; + } + } + if (recordFile == NULL) { + return CDB_ERROR_27; + } + err = CDBRecordFileWriteAttrBuf(record); + if (err != CDB_ERROR_OK && err != CDB_ERROR_SD_EJECTED && err != CDB_ERROR_VF_ERROR) { + return err; + } + err = CDBRecordFileClose(record); + if (err != CDB_ERROR_OK) { + return err; + } + if (record->key.location == CDB_FS_LOCATION_NAND) { + err = CDBVFSync(); + if (err != CDB_ERROR_OK) { + return err; + } + } + return CDB_ERROR_OK; +} + +CDBErr CDBRecordWrite(CDBRecord* record, void* buffer, u32 size) { + CDBErr err; + CDBLock(); + err = CDBRecordWrite_(record, buffer, size); + CDBUnlock(); + return err; +} + +CDBErr CDBRecordWrite_(CDBRecord* record, void* buffer, u32 size) { + CDBRecordFile* recordFile; + CDBDatabase* database; + CDBErr err; + CDBErr result; + CDBRecordDatabaseState* instance; + + database = (CDBDatabase*)record->unk_0x00; + instance = database->instance; + recordFile = record->file; + if (record->key.location == CDB_FS_LOCATION_SD) { + return CDB_ERROR_ACCESS_DENIED; + } + if ((instance->openFlags & 2) == 0) { + CDBReportError("can't write data in the record; the database is opened as READONLY\n"); + return CDB_ERROR_26; + } + if (!CDBRecordBelongedDBOpenedAsRW(record)) { + CDBReportError("can't write data in the record; permission denied\n"); + return CDB_ERROR_ACCESS_DENIED; + } + if (recordFile == NULL) { + CDBReportError("can't write data in the record; the record is closed\n"); + return CDB_ERROR_27; + } + if ((recordFile->unk_0x1C & 2) == 0) { + CDBReportError("can't write data in the record; the record is opened as READONLY\n"); + return CDB_ERROR_27; + } + err = CDBRecordFileWriteData(record, buffer, size); + if (err != CDB_ERROR_OK) { + return err; + } + err = CDBRecordUpdateModifiedDate(record); + result = CDB_ERROR_OK; + if (err != CDB_ERROR_OK) { + result = err; + } + return result; +} + +CDBErr CDBRecordRead(CDBRecord* record, void* buffer, u32 size, u32* readSize) { + CDBErr err; + CDBLock(); + if (record->file == NULL) { + CDBReportError("can't read data in the record; the record is closed\n"); + err = CDB_ERROR_27; + } else { + err = CDBRecordFileReadData(record, buffer, size, readSize); + } + CDBUnlock(); + return err; +} + +CDBErr CDBRecordSeek(CDBRecord* record, s32 offset, CDBSeek seek) { + CDBErr err; + CDBLock(); + if (record->file == NULL) { + err = CDB_ERROR_27; + } else { + switch (seek) { + case CDB_SEEK_CUR: { + err = CDBRecordFileSeekData(record, offset, CDB_SEEK_CUR); + break; + } + case CDB_SEEK_BEGIN: { + err = CDBRecordFileSeekData(record, offset, CDB_SEEK_BEGIN); + break; + } + case CDB_SEEK_END: { + err = CDBRecordFileSeekData(record, offset, CDB_SEEK_END); + break; + } + default: + err = CDB_ERROR_1; + break; + } + } + CDBUnlock(); + return err; +} + +CDBErr CDBRecordGetDataSize(CDBRecord* record, u32* size) { + CDBErr err; + CDBLock(); + if (record->file == NULL) { + CDBReportError("can't get data size of the record ; the record is closed\n"); + err = CDB_ERROR_27; + } else { + err = CDBRecordFileGetDataSize(record, size); + } + CDBUnlock(); + return err; +} + +CDBErr CDBRecordRemove(CDBRecord* record) { + CDBErr err; + CDBLock(); + err = CDBRecordRemove_(record); + CDBUnlock(); + return err; +} + +CDBErr CDBRecordRemove_(CDBRecord* record) { + CDBErr err; + CDBErr result; + if (record->file != NULL) { + CDBReportError("can't remove the record ; the record is opened\n"); + return CDB_ERROR_28; + } + if (!CDBRecordBelongedDBOpenedAsRW(record)) { + CDBReportError("can't remove the record ; permission denied\n"); + return CDB_ERROR_ACCESS_DENIED; + } + err = CDBRecordFileDelete(record); + if (err != CDB_ERROR_OK) { + return err; + } + err = CDBVFSync(); + result = CDB_ERROR_OK; + if (err != CDB_ERROR_OK) { + result = err; + } + return result; +} + +void CDBRecordGetTypeForce(CDBRecord* record, char* type) { + CDBLock(); + CDBConvKeyStrToType(record->key.keyString, type); + CDBUnlock(); +} + +void CDBRecordGetGameCodeForce(CDBRecord* record, char* gameCode) { + u32 value; + CDBLock(); + CDBConvKeyStrToGameCode(record->key.keyString, &value); + CDBConvGCValueToGCStr(value, gameCode); + CDBUnlock(); +} + +void CDBRecordGetKeyForce(CDBRecord* record, CDBRecordKey* key) { + CDBLock(); + CDBRecordKeyCopy(key, &record->key); + CDBUnlock(); +} + +void CDBRecordGetCalendarTimeForce(CDBRecord* record, int* year, int* month, int* day, int* hour, int* min, int* sec) { + char epochString[64]; + CDBDate epoch; + CDBLock(); + CDBConvKeyStrToEpochStr(record->key.keyString, epochString); + CDBConvEpochStrToEpochValue(epochString, &epoch); + CDBConvEpochValueToDate(epoch, year, month, day, hour, min, sec); + CDBUnlock(); +} + +CDBErr CDBRecordGetId(CDBRecord* record, CDBId* id) { + CDBErr err = CDB_ERROR_OK; + CDBRecordFile* recordFile; + char epochString[64]; + + CDBLock(); + recordFile = record->file; + if (recordFile == NULL) { + CDBReportError("can't get CDBId of the record ; the record is closed\n"); + err = CDB_ERROR_27; + goto get_id_done; + } else { + CDBLock(); + if (record->file == NULL) { + CDBReportError("can't get CDBId of the record ; the record is closed\n"); + err = CDB_ERROR_27; + } else { + CDBLock(); + CDBConvKeyStrToEpochStr(record->key.keyString, epochString); + CDBConvEpochStrToEpochValue(epochString, &id->num); + CDBUnlock(); + err = CDB_ERROR_OK; + } + CDBUnlock(); + } + switch (err) { + case CDB_ERROR_OK: + err = CDBAttrGetIDNumber(&recordFile->attr, (CDBId*)&id->modifiedCount); + err = CDB_ERROR_OK; + break; + default: + goto get_id_done; + } +get_id_done: + CDBUnlock(); + return err; +} + +BOOL CDBRecordIsExistFile(CDBRecord* record) { + char fullPath[256]; + CDBConvKeyToFullPath(&record->key, fullPath); + return CDBFSIsExistFile(fullPath, record->key.location); +} + +CDBErr CDBRecordUpdateModifiedDate(CDBRecord* record) { + s64 ticks; + u32 modifiedDate; + u32 modifiedCount; + CDBRecordFile* recordFile; + CDBErr err; + + ticks = OSGetTime(); + modifiedDate = ticks / (OS_BUS_CLOCK / 4); + recordFile = record->file; + if ((((CDBRecordDatabaseState*)((CDBDatabase*)record->unk_0x00)->instance)->openFlags & 2) == 0) { + CDBReportError("can't set modified time of the record; the database is opened as READONLY\n"); + return CDB_ERROR_26; + } + if (recordFile == NULL) { + CDBReportError("can't set modified time of the record ; the record is closed\n"); + return CDB_ERROR_27; + } + err = CDBAttrSetModifiedDate(&recordFile->attr, modifiedDate); + if (err != CDB_ERROR_OK) { + return err; + } + err = CDBAttrGetModifiedCount(&recordFile->attr, &modifiedCount); + if (err != CDB_ERROR_OK) { + return err; + } + modifiedCount++; + err = CDBAttrSetModifiedCount(&recordFile->attr, modifiedCount); + if (err != CDB_ERROR_OK) { + return err; + } + return CDB_ERROR_OK; +} + +CDBErr CDBRecordBackupToSD(CDBRecord* record) { + CDBErr err; + CDBLock(); + err = CDBRecordBackupToSD_(record); + CDBUnlock(); + return err; +} + +CDBErr CDBRecordBackupToSD_(CDBRecord* record) { + CDBRecordFile* recordFile; + CDBCryptBuf* cryptBuf; + CDBRecord localRecord; + CDBErr err; + u32 encryptedSize; + + localRecord.cryptBuf = NULL; + recordFile = NULL; + + if (record == NULL || !CDBRecordKeyIsValid(&record->key)) { + return CDB_ERROR_1; + } + if (record->key.location != CDB_FS_LOCATION_NAND) { + return CDB_ERROR_2; + } + if (!CDBFSSDIsMounted()) { + return CDB_ERROR_SD_IS_NOT_MOUNTED; + } + err = CDBCryptBufAllocate((CDBCryptBuf**)&localRecord.cryptBuf); + if (err != CDB_ERROR_OK) { + CDBLock(); + CDBRecordClose_(&localRecord); + CDBUnlock(); + return err; + } + cryptBuf = localRecord.cryptBuf; + CDBRecordKeyCopy(&localRecord.key, &record->key); + localRecord.file = NULL; + localRecord.key.location = CDB_FS_LOCATION_SD; + localRecord.unk_0x00 = record->unk_0x00; + err = CDBRecordFileCreateBlank(&localRecord); + if (err != CDB_ERROR_OK) { + CDBLock(); + CDBRecordClose_(&localRecord); + CDBUnlock(); + return err; + } + err = CDBRecordEncrypt(record, cryptBuf, &localRecord.key, 0x3EC00, &encryptedSize); + if (err != CDB_ERROR_OK) { + CDBLock(); + CDBRecordClose_(&localRecord); + CDBUnlock(); + CDBRecordFileDelete(&localRecord); + return err; + } + err = CDBRecordFileDump(&localRecord, cryptBuf, encryptedSize); + if (err != CDB_ERROR_OK) { + CDBLock(); + CDBRecordClose_(&localRecord); + CDBUnlock(); + return err; + } + CDBLock(); + err = CDBRecordClose_(record); + CDBUnlock(); + if (err != CDB_ERROR_OK) { + CDBLock(); + CDBRecordClose_(&localRecord); + CDBUnlock(); + return err; + } + CDBLock(); + err = CDBRecordRemove_(record); + CDBUnlock(); + if (err != CDB_ERROR_OK) { + CDBLock(); + CDBRecordClose_(&localRecord); + CDBUnlock(); + return err; + } + CDBLock(); + recordFile = localRecord.file; + CDBRecordKeyCopy(&record->key, &localRecord.key); + record->unk_0x00 = localRecord.unk_0x00; + record->file = localRecord.file; + record->cryptBuf = localRecord.cryptBuf; + CDBRecordKeyCopy(&recordFile->key, &localRecord.key); + CDBUnlock(); + return CDB_ERROR_OK; +} + +CDBErr CDBCryptBuffer(void* buffer, u32 size, void* iv, u32* processedSize, BOOL encrypt) { + NETAESContext context ATTRIBUTE_ALIGN(64); + u32 offset; + u32 length; + + if (processedSize) { + *processedSize = 0; + } + if (!NETAESCreate(&context, s_cdbCryptKey, 16, iv)) { + CDBReportError("NETAESCreate\n"); + return CDB_ERROR_14; + } + offset = 0; + while (offset < size) { + if (processedSize) { + *processedSize += 64; + } + if (offset + 64 < size) { + length = 64; + } else { + length = size - offset; + memset(s_cdbCryptBuffer, 0, 64); + } + memcpy(s_cdbCryptBuffer, (u8*)buffer + offset, length); + if (encrypt) { + if (!NETAESEncrypt(&context, s_cdbCryptBufferResult, s_cdbCryptBuffer, 64)) { + CDBReportError("NETAESEncrypt\n"); + NETAESDelete(&context); + return CDB_ERROR_14; + } + } else { + if (!NETAESDecrypt(&context, s_cdbCryptBufferResult, s_cdbCryptBuffer, 64)) { + CDBReportError("NETAESDecrypt\n"); + NETAESDelete(&context); + return CDB_ERROR_14; + } + } + memcpy((u8*)buffer + offset, s_cdbCryptBufferResult, 64); + offset += 64; + } + NETAESDelete(&context); + return CDB_ERROR_OK; +} + +CDBErr CDBRecordEncrypt(CDBRecord* record, void* buffer, CDBRecordKey* key, u32 size, u32* encryptedSize) { + CDBRecordFile* recordFile; + CDBErr err; + u32 fileSize; + u32 dataSize; + u32 cryptSize; + int fileOffset; + u8 iv[0x10]; + u8 wiiIdKey[0x40] ATTRIBUTE_ALIGN(64); + u8 digest[0x14] ATTRIBUTE_ALIGN(64); + CDBAttrSignature signature ATTRIBUTE_ALIGN(64); + NETHMACContext hmac ATTRIBUTE_ALIGN(64); + + recordFile = record->file; + memset(wiiIdKey, 0, sizeof(wiiIdKey)); + memset(&signature, 0, sizeof(signature)); + memset(buffer, 0, size); + if ((s32)recordFile == 0) { + return CDB_ERROR_27; + } + if (recordFile->unk_0x1C == 1) { + return CDB_ERROR_26; + } + if ((s32)buffer == 0) { + return CDB_ERROR_1; + } + { + CDBErr result; + CDBRecordFile* tempFile; + tempFile = record->file; + if ((s32)tempFile == 0) { + result = CDB_ERROR_27; + } else if (tempFile->unk_0x1C == 1) { + result = CDB_ERROR_26; + } else { + CDBAttrSetWiiId(&tempFile->attr, CDBGetWiiId()); + result = CDB_ERROR_OK; + } + if (result != CDB_ERROR_OK) { + return CDB_ERROR_OK; + } + } + { + CDBErr result; + if ((s32)record->file == 0) { + result = CDB_ERROR_27; + } else if (((CDBRecordFile*)record->file)->unk_0x1C == 1) { + result = CDB_ERROR_26; + } else { + CDBAttrInitIV(&((CDBRecordFile*)record->file)->attr); + result = CDB_ERROR_OK; + } + if (result != CDB_ERROR_OK) { + return CDB_ERROR_OK; + } + } + { + CDBErr result; + if ((s32)record->file == 0) { + result = CDB_ERROR_27; + } else if (((CDBRecordFile*)record->file)->unk_0x1C == 1) { + result = CDB_ERROR_26; + } else { + CDBAttrSetKeyStr(&((CDBRecordFile*)record->file)->attr, key); + result = CDB_ERROR_OK; + } + if (result != CDB_ERROR_OK) { + return CDB_ERROR_OK; + } + } + CDBLock(); + if ((s32)record->file == 0) { + CDBReportError("can't get file size of the record ; the record is closed\n"); + err = CDB_ERROR_27; + } else { + err = CDBRecordFileGetFileSize(record, &fileSize); + } + CDBUnlock(); + CDBAttrSetFileSize(&recordFile->attr, fileSize); + if (err != CDB_ERROR_OK) { + return CDB_ERROR_OK; + } + CDBLock(); + if ((s32)record->file == 0) { + CDBReportError("can't get data size of the record ; the record is closed\n"); + err = CDB_ERROR_27; + } else { + err = CDBRecordFileGetDataSize(record, &dataSize); + } + CDBUnlock(); + if (err != CDB_ERROR_OK) { + return CDB_ERROR_OK; + } + if (size < dataSize + CDB_RECORD_BUFFER_SIZE) { + return CDB_ERROR_20; + } + memcpy(buffer, &recordFile->attr, CDB_RECORD_BUFFER_SIZE); + CDBLock(); + if ((s32)record->file == 0) { + err = CDB_ERROR_27; + } else { + fileOffset = CDBRecordFileTellData(record); + if (fileOffset < 0) { + err = CDB_ERROR_CANNOT_OPEN_FILE; + } else { + err = CDB_ERROR_OK; + } + } + CDBUnlock(); + if (err != CDB_ERROR_OK) { + return CDB_ERROR_OK; + } + CDBLock(); + if ((s32)record->file == 0) { + err = CDB_ERROR_27; + } else { + err = CDBRecordFileSeekData(record, 0, CDB_SEEK_BEGIN); + } + CDBUnlock(); + if (err != CDB_ERROR_OK) { + return CDB_ERROR_OK; + } + CDBLock(); + if ((s32)record->file == 0) { + CDBReportError("can't read data in the record; the record is closed\n"); + err = CDB_ERROR_27; + } else { + err = CDBRecordFileReadData(record, (u8*)buffer + CDB_RECORD_BUFFER_SIZE, size - CDB_RECORD_BUFFER_SIZE, &dataSize); + } + CDBUnlock(); + if (err != CDB_ERROR_OK) { + return CDB_ERROR_OK; + } + CDBLock(); + if ((s32)record->file == 0) { + err = CDB_ERROR_27; + } else { + err = CDBRecordFileSeekData(record, fileOffset, CDB_SEEK_BEGIN); + } + CDBUnlock(); + if (err != CDB_ERROR_OK) { + return CDB_ERROR_OK; + } + CDBAttrGetIV(&recordFile->attr, iv); + err = CDBCryptBuffer((u8*)buffer + CDB_RECORD_BUFFER_SIZE, dataSize, iv, &cryptSize, TRUE); + if (err != CDB_ERROR_OK) { + return err; + } + CDBGetWiiIdKey((char*)wiiIdKey); + CDBGetDeviceKey((char*)&wiiIdKey[12]); + CDBAttrClearSignature((CDBAttr*)buffer); + NETHMACInit(&hmac, NETGetSHA1Interface(), wiiIdKey, 0x40); + NETHMACUpdate(&hmac, buffer, cryptSize + CDB_RECORD_BUFFER_SIZE); + NETHMACGetDigest(&hmac, digest); + memcpy(((CDBAttrBuf*)buffer)->signature.sha1Hmac, digest, sizeof(digest)); + if (encryptedSize != 0) { + *encryptedSize = cryptSize + CDB_RECORD_BUFFER_SIZE; + } + return CDB_ERROR_OK; +} + +CDBErr CDBRecordDecrypt(CDBRecord* record, void* buffer, u32 size, u32* dataSize, CDBRecordKey* key) { + CDBErr status; + int fileOffset; + CDBRecordFile* recordFile; + u32 fileDataSize; + u32 fileSize; + u8 iv[16]; + CDBRecordKey comparisonKey; + u8 digest[20] ATTRIBUTE_ALIGN(64); + u8 wiiIdKey[64] ATTRIBUTE_ALIGN(16); + NETHMACContext hmac; + CDBAttrSignature signature; + + recordFile = record->file; + memset(wiiIdKey, 0, sizeof(wiiIdKey)); + memset(&signature, 0, sizeof(signature)); + memset(buffer, 0, size); + if ((s32)recordFile == 0) { + return CDB_ERROR_27; + } + if ((s32)buffer == 0) { + return CDB_ERROR_1; + } + { + CDBLock(); + if ((s32)record->file == 0) { + CDBReportError("can't get data size of the record ; the record is closed\n"); + status = CDB_ERROR_27; + } else { + status = CDBRecordFileGetDataSize(record, &fileDataSize); + } + CDBUnlock(); + if (status != CDB_ERROR_OK) { + return CDB_ERROR_OK; + } + } + if (size < fileDataSize + CDB_RECORD_BUFFER_SIZE) { + if (fileDataSize > 0x3E800) { + return CDB_ERROR_32; + } + return CDB_ERROR_20; + } + if ((fileDataSize & 0x3F) != 0) { + return CDB_ERROR_32; + } + { + CDBErr err; + err = CDBRecordFileReadAttrBuf(record); + if (err != CDB_ERROR_OK) { + return CDB_ERROR_32; + } + } + memcpy(buffer, &recordFile->attr, CDB_RECORD_BUFFER_SIZE); + { + CDBErr err; + int offset; + if ((s32)record->file == 0) { + err = CDB_ERROR_27; + } else { + offset = CDBRecordFileTellDataFile(record); + if (offset < 0) { + err = CDB_ERROR_CANNOT_OPEN_FILE; + } else { + fileOffset = offset; + err = CDB_ERROR_OK; + } + } + if (err != CDB_ERROR_OK) { + return err; + } + } + { + CDBErr err; + if ((s32)record->file == 0) { + err = CDB_ERROR_27; + } else { + err = CDBRecordFileSeekDataFile(record, 0, CDB_SEEK_BEGIN); + } + if (err != CDB_ERROR_OK) { + return err; + } + } + { + CDBErr err; + err = CDBRecordFileReadDataFile(record, (u8*)buffer + CDB_RECORD_BUFFER_SIZE, size - CDB_RECORD_BUFFER_SIZE, &fileDataSize); + if (err != CDB_ERROR_OK) { + return err; + } + } + { + CDBErr err; + if ((s32)record->file == 0) { + err = CDB_ERROR_27; + } else { + err = CDBRecordFileSeekDataFile(record, fileOffset, CDB_SEEK_BEGIN); + } + if (err != CDB_ERROR_OK) { + return err; + } + } + CDBAttrGetSignature((CDBAttr*)buffer, &signature); + CDBAttrClearSignature((CDBAttr*)buffer); + if ((s32)key == 0) { + CDBGetWiiIdKey((char*)wiiIdKey); + } else { + CDBCopyWiiIdKey((char*)wiiIdKey, (char*)key); + } + CDBGetDeviceKey((char*)&wiiIdKey[12]); + status = fileDataSize + CDB_RECORD_BUFFER_SIZE; + NETHMACInit(&hmac, NETGetSHA1Interface(), wiiIdKey, 0x40); + NETHMACUpdate(&hmac, buffer, status); + NETHMACGetDigest(&hmac, digest); + if (memcmp(digest, signature.sha1Hmac, 0x14) != 0) { + return CDB_ERROR_32; + } + CDBAttrGetKeyStr((CDBAttr*)buffer, comparisonKey.keyString); + if (CDBRecordKeyCompareByDate(&comparisonKey, &record->key) != 0) { + if (CDBIsPrintDebugMessage(3)) { + CDBReport_(3); + OSReport("CDBRecordPrivateChangeOwner\n"); + } + return CDB_ERROR_32; + } + CDBAttrGetIV(&recordFile->attr, iv); + { + CDBErr err; + err = CDBCryptBuffer((u8*)buffer + CDB_RECORD_BUFFER_SIZE, fileDataSize, iv, NULL, FALSE); + if (err != CDB_ERROR_OK) { + return err; + } + } + if (dataSize != 0) { + CDBAttrGetFileSize((CDBAttr*)buffer, &fileSize); + *dataSize = fileSize; + } + return CDB_ERROR_OK; +} diff --git a/libs/RevoEX/src/nwc24/NWC24Download.c b/libs/RevoEX/src/nwc24/NWC24Download.c index 7f023401..e06f710e 100644 --- a/libs/RevoEX/src/nwc24/NWC24Download.c +++ b/libs/RevoEX/src/nwc24/NWC24Download.c @@ -32,6 +32,14 @@ typedef struct { u8 unknown_0x1fd[3]; } DlTaskData; +typedef struct { + u32 appId; + u32 nextTime; + u32 lastAccess; + u8 priority; + u8 reserved[3]; +} DlTaskEntry; + typedef struct { u32 magic; u32 version; @@ -42,13 +50,7 @@ typedef struct { u16 taskCount; u16 maxTaskCount; u8 unknown_0x16[0x6a]; - struct { - u32 flags; - u32 nextTime; - u32 lastAccess; - u8 priority; - u8 unknown_0x0d[3]; - } entries[NWC24_DL_TASK_MAX]; + DlTaskEntry entries[NWC24_DL_TASK_MAX]; } DlTaskListHeader; typedef struct { @@ -67,15 +69,106 @@ NWC24Err NWC24iLoadDlHeader(); NWC24Err NWC24iCheckDlHeaderConsistency(DlTaskListHeader* header, BOOL repair); NWC24Err NWC24iCreateDlTaskList(); NWC24Err NWC24iOpenDlTaskList(); -NWC24Err StoreDlTask(NWC24DlTask* dlTask); +NWC24Err StoreDlTask(NWC24DlTask* dlTask) NO_INLINE; NWC24Err AddTaskInternal(NWC24DlTask* dlTask, u16 taskCount, u16 maxTaskCount); -NWC24Err DeleteDlTask(NWC24DlTask* dlTask); +NWC24Err DeleteDlTask(NWC24DlTask* dlTask) NO_INLINE; static s32 IterationPredicatorLastAccess(NWC24DlId taskId); static s32 IterationPredicatorNextTime(NWC24DlId taskId); static s32 IterationPredicatorPriority(NWC24DlId taskId); +static inline DlTaskListHeader* GetCachedDlHeader(void) { + if (NWC24WorkP != NULL) { + return (DlTaskListHeader*)NWC24WorkP->dlHead; + } + return NULL; +} + +static inline BOOL IsDlTaskOwner(u32 appId) { + return (appId & 0xffffff00) == (NWC24GetAppId() & 0xffffff00); +} + +static inline BOOL IsDlTaskGroupWritable(u16 groupId, u32 flags) { + return (flags & 0x40) && groupId == NWC24GetGroupId(); +} + +static inline NWC24Err ValidateDlTask(const NWC24DlTask* dlTask, BOOL write) { + const DlTaskData* task = (const DlTaskData*)dlTask; + DlTaskListHeader* header = GetCachedDlHeader(); + if (task == NULL) { + return NWC24_ERR_INVALID_VALUE; + } + if (header == NULL) { + return NWC24_ERR_LIB_NOT_OPENED; + } + if (write && !NWC24IsMsgLibOpenedByTool() && !IsDlTaskOwner(task->appId)) { + if (!IsDlTaskGroupWritable(task->groupId, task->flags)) { + return NWC24_ERR_PROTECTED; + } + } + if (task->id != 0xffff && task->id >= header->maxTaskCount) { + return NWC24_ERR_INVALID_VALUE; + } + return NWC24_OK; +} + +static inline NWC24Err SeekDlTaskEntry(u16 taskId, NWC24File* file) { + DlTaskListHeader* header = GetCachedDlHeader(); + if (header->maxTaskCount > NWC24_DL_TASK_MAX || taskId >= header->maxTaskCount) { + return NWC24_ERR_INVALID_VALUE; + } + return NWC24FSeek(file, 0x800 + taskId * 0x200, NWC24_SEEK_BEG); +} + +static inline NWC24Err WriteDlTaskEntry(DlTaskData* task, NWC24File* file) { + NWC24Err result = SeekDlTaskEntry(task->id, file); + if (result < NWC24_OK) { + return result; + } + memcpy(NWC24WorkP->dlTask, task, sizeof(*task)); + result = NWC24FWrite(NWC24WorkP->dlTask, sizeof(*task), file); + if (result < NWC24_OK) { + return result; + } + return NWC24_OK; +} + +static inline NWC24Err WriteDlHeader(NWC24File* file) { + NWC24Err result = NWC24FSeek(file, 0, NWC24_SEEK_BEG); + if (result < NWC24_OK) { + return result; + } + result = NWC24FWrite(GetCachedDlHeader(), 0x800, file); + if (result < NWC24_OK) { + return result; + } + return NWC24_OK; +} + +static inline NWC24Err UpdateDlEntryHeader(DlTaskData* task) { + u16 taskId = task->id; + DlTaskListHeader* header = GetCachedDlHeader(); + DlTaskEntry* entry = &header->entries[taskId]; + entry->appId = task->appId; + entry->priority = task->priority; + return NWC24_OK; +} + +static inline void InitDlEntryHeader(u16 taskId) { + DlTaskListHeader* header = (DlTaskListHeader*)NWC24WorkP->dlHead; + memset(&header->entries[taskId], 0, sizeof(header->entries[taskId])); +} + +static inline NWC24Err ClearDlTaskEntry(u16 taskId, NWC24File* file) { + DlTaskData* task = (DlTaskData*)NWC24WorkP->dlTask; + memset(task, 0, sizeof(*task)); + task->type = 0xff; + task->id = taskId; + InitDlEntryHeader(taskId); + return WriteDlTaskEntry(task, file); +} + NWC24Err NWC24InitDlTask(NWC24DlTask* dlTask, NWC24DLType dlType) { - char homePath[64] = { 0 }; + char homePath[64] = {0}; u32 nwc24IdHigh; u32 nwc24IdLow; DlTaskData* task; @@ -167,34 +260,16 @@ NWC24Err NWC24InitDlTask(NWC24DlTask* dlTask, NWC24DLType dlType) { NWC24Err NWC24SetDlId(NWC24DlTask* dlTask, NWC24DlId dlId) { NWC24Err result; - u16 taskId; DlTaskData* task; DlTaskListHeader* header; NWC24Work* work = NWC24WorkP; - if (work != NULL) { - header = (DlTaskListHeader*)work->dlHead; - } else { - header = NULL; - } - - if (dlTask == NULL) { - result = NWC24_ERR_INVALID_VALUE; - } else if (header == NULL) { - result = NWC24_ERR_LIB_NOT_OPENED; - } else { - task = (DlTaskData*)dlTask; - taskId = task->id; - if (taskId != 0xffff && taskId >= header->maxTaskCount) { - result = NWC24_ERR_INVALID_VALUE; - } else { - result = NWC24_OK; - } - } - + result = ValidateDlTask(dlTask, FALSE); if (result != NWC24_OK) { return result; } + task = (DlTaskData*)dlTask; + if (NWC24WorkP != NULL) { header = (DlTaskListHeader*)NWC24WorkP->dlHead; } else { @@ -209,46 +284,9 @@ NWC24Err NWC24SetDlId(NWC24DlTask* dlTask, NWC24DlId dlId) { } NWC24Err NWC24SetDlPriority(NWC24DlTask* dlTask, u8 dlPriority) { - DlTaskListHeader* header; NWC24Err result; - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; - } - - if (dlTask == NULL) { - result = NWC24_ERR_INVALID_VALUE; - } else if (header == NULL) { - result = NWC24_ERR_LIB_NOT_OPENED; - } else { - result = NWC24_OK; - if (!NWC24IsMsgLibOpenedByTool()) { - u32 taskAppId = ((DlTaskData*)dlTask)->appId; - u32 appId = NWC24GetAppId(); - BOOL sameAppId = (taskAppId & 0xffffff00) == (appId & 0xffffff00); - if (!sameAppId) { - BOOL allowed = FALSE; - if (((DlTaskData*)dlTask)->flags & 0x40) { - u16 groupId = ((DlTaskData*)dlTask)->groupId; - if (groupId == NWC24GetGroupId()) { - allowed = TRUE; - } - } - if (!allowed) { - result = NWC24_ERR_PROTECTED; - } - } - } - if (result == NWC24_OK) { - u16 taskId = ((DlTaskData*)dlTask)->id; - if (taskId != 0xffff && taskId >= header->maxTaskCount) { - result = NWC24_ERR_INVALID_VALUE; - } - } - } - + result = ValidateDlTask(dlTask, TRUE); if (result != NWC24_OK) { return result; } @@ -267,38 +305,11 @@ NWC24Err NWC24SetDlInterval(NWC24DlTask* dlTask, u16 dlInterval) { NWC24Err result; OSTime universalTime; - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; - } - - if (dlTask == NULL) { - result = NWC24_ERR_INVALID_VALUE; - } else if (header == NULL) { - result = NWC24_ERR_LIB_NOT_OPENED; - } else { - task = (DlTaskData*)dlTask; - result = NWC24_OK; - if (!NWC24IsMsgLibOpenedByTool()) { - u32 taskAppId = task->appId; - u32 appId = NWC24GetAppId(); - if ((taskAppId & 0xffffff00) != (appId & 0xffffff00) && - (!(task->flags & 0x40) || task->groupId != NWC24GetGroupId())) { - result = NWC24_ERR_PROTECTED; - } - } - if (result == NWC24_OK) { - taskId = task->id; - if (taskId != 0xffff && taskId >= header->maxTaskCount) { - result = NWC24_ERR_INVALID_VALUE; - } - } - } - + result = ValidateDlTask(dlTask, TRUE); if (result != NWC24_OK) { return result; } + task = (DlTaskData*)dlTask; task = (DlTaskData*)dlTask; if (!NWC24iLaxParameterCheck) { @@ -308,8 +319,7 @@ NWC24Err NWC24SetDlInterval(NWC24DlTask* dlTask, u16 dlInterval) { header = NULL; } taskId = task->id; - if (taskId >= header->taskCount && !(task->flags & 0x40000000) && - (dlInterval < 0x00b4 || dlInterval > 0x2760)) { + if (taskId >= header->taskCount && !(task->flags & 0x40000000) && (dlInterval < 0x00b4 || dlInterval > 0x2760)) { return NWC24_ERR_INVALID_VALUE; } } @@ -358,47 +368,14 @@ NWC24Err NWC24SetDlInterval(NWC24DlTask* dlTask, u16 dlInterval) { } NWC24Err NWC24SetDlUrl(NWC24DlTask* dlTask, const char* dlUrl) { - DlTaskListHeader* header; DlTaskData* task; - u16 taskId; NWC24Err result; - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; + result = ValidateDlTask(dlTask, TRUE); + if (result != NWC24_OK) { + return result; } - - if (dlTask == NULL) { - return NWC24_ERR_INVALID_VALUE; - } - if (header == NULL) { - return NWC24_ERR_LIB_NOT_OPENED; - } - task = (DlTaskData*)dlTask; - if (!NWC24IsMsgLibOpenedByTool()) { - u32 taskAppId = task->appId; - u32 appId = NWC24GetAppId(); - BOOL allowed = (taskAppId & 0xffffff00) == (appId & 0xffffff00); - if (!allowed) { - allowed = FALSE; - if (task->flags & 0x40) { - if (task->groupId == NWC24GetGroupId()) { - allowed = TRUE; - } - } - if (!allowed) { - return NWC24_ERR_PROTECTED; - } - } - } - - taskId = task->id; - if (taskId != 0xffff && taskId >= header->maxTaskCount) { - return NWC24_ERR_INVALID_VALUE; - } - result = NWC24iCheckStringLength(dlUrl, 7, 0x100); if (result < NWC24_OK) { return result; @@ -422,67 +399,27 @@ NWC24Err NWC24SetDlUrl(NWC24DlTask* dlTask, const char* dlUrl) { } NWC24Err NWC24SetDlFlags(NWC24DlTask* dlTask, u32 dlFlags) { - DlTaskListHeader* header; DlTaskData* task; - u16 taskId; NWC24Err result; - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; - } - - if (dlTask == NULL) { - return NWC24_ERR_INVALID_VALUE; - } - if (header == NULL) { - return NWC24_ERR_LIB_NOT_OPENED; - } - - task = (DlTaskData*)dlTask; - result = NWC24_OK; - if (!NWC24IsMsgLibOpenedByTool()) { - u32 taskAppId = task->appId; - u32 appId = NWC24GetAppId(); - if ((taskAppId & 0xffffff00) != (appId & 0xffffff00)) { - BOOL allowed = FALSE; - if (task->flags & 0x40) { - u16 groupId = task->groupId; - if (groupId == NWC24GetGroupId()) { - allowed = TRUE; - } - } - if (!allowed) { - result = NWC24_ERR_PROTECTED; - } - } - } - - if (result == NWC24_OK) { - taskId = task->id; - if (taskId != 0xffff && taskId >= header->maxTaskCount) { - result = NWC24_ERR_INVALID_VALUE; - } - } + result = ValidateDlTask(dlTask, TRUE); if (result != NWC24_OK) { return result; } - task = (DlTaskData*)dlTask; if (!NWC24iLaxParameterCheck && (dlFlags & 0x4) && strncmp(task->url, "http://", 7) == 0) { return NWC24_ERR_INVALID_VALUE; } switch (task->type) { - case NWC24_DLTYPE_MULTIPART_V1: - case NWC24_DLTYPE_OCTETSTREAM_V1: { - if (dlFlags & 0x80000038) { - return NWC24_ERR_INVALID_OPERATION; + case NWC24_DLTYPE_MULTIPART_V1: + case NWC24_DLTYPE_OCTETSTREAM_V1: { + if (dlFlags & 0x80000038) { + return NWC24_ERR_INVALID_OPERATION; + } + break; } - break; - } - default: - break; + default: + break; } task->flags = dlFlags; return NWC24_OK; @@ -490,30 +427,12 @@ NWC24Err NWC24SetDlFlags(NWC24DlTask* dlTask, u32 dlFlags) { NWC24Err NWC24GetDlAppId(const NWC24DlTask* dlTask, u32* dlAppId) { NWC24Err result; - const DlTaskData* task; - DlTaskListHeader* header; - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; - } - - if (dlTask == NULL) { - result = NWC24_ERR_INVALID_VALUE; - } else if (header == NULL) { - result = NWC24_ERR_LIB_NOT_OPENED; - } else { - task = (const DlTaskData*)dlTask; - if (task->id != 0xffff && task->id >= header->maxTaskCount) { - result = NWC24_ERR_INVALID_VALUE; - } else { - result = NWC24_OK; - } - } + result = ValidateDlTask(dlTask, FALSE); if (result != NWC24_OK) { return result; } + if (dlAppId == NULL) { return NWC24_ERR_INVALID_VALUE; } @@ -553,11 +472,11 @@ NWC24Err NWC24DumpDlTask(NWC24DlTask* dlTask) { } NWC24Err NWC24IterateDlTask(NWC24DlId* dlIterateId, BOOL begin) { - DlTaskListHeader* header; + NWC24Err result; NWC24Work* work; u16 taskId; u16 maxTaskCount; - NWC24Err result; + DlTaskListHeader* header; if (NWC24WorkP != NULL) { header = (DlTaskListHeader*)NWC24WorkP->dlHead; @@ -606,7 +525,7 @@ NWC24Err NWC24IterateDlTask(NWC24DlId* dlIterateId, BOOL begin) { header = NULL; } result = NWC24_ERR_NOT_FOUND; - if (header->entries[taskId].flags == 0) { + if (header->entries[taskId].appId == 0) { result = NWC24_OK; } if (result >= NWC24_OK) { @@ -635,17 +554,17 @@ NWC24Err NWC24IterateDlTaskEx(NWC24DlIterateWork* dlIterateWork, NWC24DlId* dlIt descending = (state->sortMode >> 31) != 0; switch (state->sortMode & 0xffff) { - case 0: - getValue = IterationPredicatorLastAccess; - break; - case 1: - getValue = IterationPredicatorNextTime; - break; - case 2: - getValue = IterationPredicatorPriority; - break; - default: - return NWC24_ERR_INVALID_VALUE; + case 0: + getValue = IterationPredicatorLastAccess; + break; + case 1: + getValue = IterationPredicatorNextTime; + break; + case 2: + getValue = IterationPredicatorPriority; + break; + default: + return NWC24_ERR_INVALID_VALUE; } if (state->initialized == 0) { @@ -700,41 +619,17 @@ NWC24Err NWC24IterateDlTaskEx(NWC24DlIterateWork* dlIterateWork, NWC24DlId* dlIt NWC24Err NWC24UpdateDlTask(NWC24DlTask* dlTask) { DlTaskData* task = (DlTaskData*)dlTask; - DlTaskListHeader* header; + NWC24DlId taskId; NWC24Err result; OSTime universalTime; - NWC24DlId taskId; + DlTaskListHeader* header; - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; + result = ValidateDlTask(dlTask, TRUE); + if (result != NWC24_OK) { + return result; } - - if (dlTask == NULL) { - return NWC24_ERR_INVALID_VALUE; - } - if (header == NULL) { - return NWC24_ERR_LIB_NOT_OPENED; - } - - if (!NWC24IsMsgLibOpenedByTool()) { - u32 taskAppId = task->appId; - u32 appId = NWC24GetAppId(); - BOOL allowed = (taskAppId & 0xffffff00) == (appId & 0xffffff00); - if (!allowed && (task->flags & 0x40)) { - allowed = task->groupId == NWC24GetGroupId(); - } - if (!allowed) { - return NWC24_ERR_PROTECTED; - } - } - + task = (DlTaskData*)dlTask; taskId = task->id; - if (taskId != 0xffff && taskId >= header->maxTaskCount) { - return NWC24_ERR_INVALID_VALUE; - } - if (taskId != 0xffff) { if (NWC24WorkP != NULL) { header = (DlTaskListHeader*)NWC24WorkP->dlHead; @@ -874,11 +769,7 @@ NWC24Err NWC24DeleteDlTask(NWC24DlTask* dlTask) { if (NWC24GetAppId() == 0x48414541) { result = NWC24_OK; } else { - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; - } + header = GetCachedDlHeader(); if (dlTask == NULL) { return NWC24_ERR_INVALID_VALUE; @@ -910,11 +801,7 @@ NWC24Err NWC24DeleteDlTask(NWC24DlTask* dlTask) { return result; } - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; - } + header = GetCachedDlHeader(); if (dlTask == NULL) { return NWC24_ERR_INVALID_VALUE; } @@ -966,8 +853,7 @@ NWC24Err NWC24AddDlTask(NWC24DlTask* dlTask) { } } - if (header->maxTaskCount < 1 || header->taskCount < 1 || - header->maxTaskCount < header->taskCount) { + if (header->maxTaskCount < 1 || header->taskCount < 1 || header->maxTaskCount < header->taskCount) { return NWC24_ERR_BROKEN; } @@ -1040,7 +926,7 @@ NWC24Err NWC24GetDlTask(NWC24DlTask* dlTask, NWC24DlId dlId) { } else { header = NULL; } - if (header->entries[dlId].flags == 0) { + if (header->entries[dlId].appId == 0) { result = NWC24_ERR_NOT_FOUND; } else { result = NWC24_OK; @@ -1101,11 +987,7 @@ NWC24Err NWC24PurgeOldestDlTask() { state.valid = 1; taskId = 0; - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; - } + header = GetCachedDlHeader(); result = NWC24_OK; do { @@ -1113,11 +995,7 @@ NWC24Err NWC24PurgeOldestDlTask() { if (result != NWC24_OK) { break; } - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; - } + header = GetCachedDlHeader(); } while (taskId < header->taskCount); if (result == NWC24_ERR_DONE) { @@ -1129,23 +1007,15 @@ NWC24Err NWC24PurgeOldestDlTask() { taskPointer = &task; selectedId = taskId; - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; - } + header = GetCachedDlHeader(); if (header == NULL) { return NWC24_ERR_LIB_NOT_OPENED; } if (selectedId >= header->maxTaskCount || selectedId == 0xffff) { return NWC24_ERR_INVALID_VALUE; } - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; - } - if (header->entries[selectedId].flags == 0) { + header = GetCachedDlHeader(); + if (header->entries[selectedId].appId == 0) { return NWC24_ERR_NOT_FOUND; } @@ -1154,11 +1024,7 @@ NWC24Err NWC24PurgeOldestDlTask() { return result; } - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; - } + header = GetCachedDlHeader(); if (header->maxTaskCount > NWC24_DL_TASK_MAX || selectedId >= header->maxTaskCount) { result = NWC24_ERR_INVALID_VALUE; } else { @@ -1176,15 +1042,10 @@ NWC24Err NWC24PurgeOldestDlTask() { return result; } - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; - } + header = GetCachedDlHeader(); if (header == NULL) { result = NWC24_ERR_LIB_NOT_OPENED; - } else if (((DlTaskData*)taskPointer)->id == 0xffff || - ((DlTaskData*)taskPointer)->id >= header->maxTaskCount) { + } else if (((DlTaskData*)taskPointer)->id == 0xffff || ((DlTaskData*)taskPointer)->id >= header->maxTaskCount) { result = NWC24_ERR_INVALID_VALUE; } else { result = NWC24_OK; @@ -1235,7 +1096,7 @@ NWC24Err NWC24ManageDlTaskListForMenu() { result = NWC24_ERR_LIB_NOT_OPENED; } else if (header->maxTaskCount <= 2) { result = NWC24_ERR_INVALID_VALUE; - } else if (header->entries[2].flags == 0) { + } else if (header->entries[2].appId == 0) { result = NWC24_ERR_NOT_FOUND; } if (result < NWC24_OK) { @@ -1280,8 +1141,7 @@ NWC24Err NWC24ManageDlTaskListForMenu() { } if (header == NULL) { result = NWC24_ERR_LIB_NOT_OPENED; - } else if (((DlTaskData*)&task)->id == 0xffff || - ((DlTaskData*)&task)->id >= header->maxTaskCount) { + } else if (((DlTaskData*)&task)->id == 0xffff || ((DlTaskData*)&task)->id >= header->maxTaskCount) { result = NWC24_ERR_INVALID_VALUE; } else { result = NWC24_OK; @@ -1358,7 +1218,6 @@ NWC24Err NWC24iCloseDlTaskList() { NWC24Err NWC24ExtendDlTaskList(u32 num) { DlTaskListHeader* header; NWC24File file; - DlTaskData* task; NWC24Err result; NWC24Err closeResult; u16 taskId; @@ -1387,43 +1246,13 @@ NWC24Err NWC24ExtendDlTaskList(u32 num) { } for (; taskId < num; taskId++) { - if (NWC24WorkP != NULL) { - task = (DlTaskData*)NWC24WorkP->dlTask; - } else { - task = NULL; - } - memset(task, 0, sizeof(*task)); - task->type = 0xff; - task->id = taskId; - memset(&((DlTaskListHeader*)NWC24WorkP->dlHead)->entries[taskId], 0, - sizeof(header->entries[taskId])); - - if (((DlTaskListHeader*)NWC24WorkP->dlHead)->maxTaskCount > NWC24_DL_TASK_MAX || - taskId >= ((DlTaskListHeader*)NWC24WorkP->dlHead)->maxTaskCount) { - result = NWC24_ERR_INVALID_VALUE; - break; - } - result = NWC24FSeek(&file, 0x800 + taskId * 0x200, NWC24_SEEK_BEG); - if (result >= NWC24_OK) { - result = NWC24FWrite(task, sizeof(*task), &file); - if (result >= NWC24_OK) { - result = NWC24_OK; - } - } + result = ClearDlTaskEntry(taskId, &file); if (result < NWC24_OK) { - break; - } - } - - if (result >= NWC24_OK) { - result = NWC24FSeek(&file, 0, NWC24_SEEK_BEG); - if (result >= NWC24_OK) { - result = NWC24FWrite((DlTaskListHeader*)NWC24WorkP->dlHead, 0x800, &file); - if (result >= NWC24_OK) { - result = NWC24_OK; - } + goto closeList; } } + result = WriteDlHeader(&file); +closeList: closeResult = NWC24FClose(&file); if (result != NWC24_OK) { closeResult = result; @@ -1444,17 +1273,13 @@ NWC24Err NWC24iCheckDlHeaderConsistency(DlTaskListHeader* header, BOOL repair) { NWC24Err closeResult; for (taskId = 0; taskId < header->maxTaskCount; taskId++) { - if (NWC24WorkP != NULL) { - currentHeader = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - currentHeader = NULL; - } + currentHeader = GetCachedDlHeader(); result = NWC24_OK; if (currentHeader == NULL) { result = NWC24_ERR_LIB_NOT_OPENED; } else if (taskId >= currentHeader->maxTaskCount || taskId == 0xffff) { result = NWC24_ERR_INVALID_VALUE; - } else if (currentHeader->entries[taskId].flags == 0) { + } else if (currentHeader->entries[taskId].appId == 0) { result = NWC24_ERR_NOT_FOUND; } if (result < NWC24_OK) { @@ -1462,17 +1287,13 @@ NWC24Err NWC24iCheckDlHeaderConsistency(DlTaskListHeader* header, BOOL repair) { } if (repair) { - if (NWC24WorkP != NULL) { - currentHeader = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - currentHeader = NULL; - } + currentHeader = GetCachedDlHeader(); result = NWC24_OK; if (currentHeader == NULL) { result = NWC24_ERR_LIB_NOT_OPENED; } else if (taskId >= currentHeader->maxTaskCount || taskId == 0xffff) { result = NWC24_ERR_INVALID_VALUE; - } else if (currentHeader->entries[taskId].flags == 0) { + } else if (currentHeader->entries[taskId].appId == 0) { result = NWC24_ERR_NOT_FOUND; } if (result < NWC24_OK) { @@ -1483,15 +1304,10 @@ NWC24Err NWC24iCheckDlHeaderConsistency(DlTaskListHeader* header, BOOL repair) { if (result < NWC24_OK) { return result; } - if (NWC24WorkP != NULL) { - currentHeader = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - currentHeader = NULL; - } + currentHeader = GetCachedDlHeader(); if (currentHeader == NULL) { result = NWC24_ERR_LIB_NOT_OPENED; - } else if (currentHeader->maxTaskCount > NWC24_DL_TASK_MAX || - taskId >= currentHeader->maxTaskCount) { + } else if (currentHeader->maxTaskCount > NWC24_DL_TASK_MAX || taskId >= currentHeader->maxTaskCount) { result = NWC24_ERR_INVALID_VALUE; } else { result = NWC24FSeek(&file, 0x800 + taskId * 0x200, NWC24_SEEK_BEG); @@ -1509,15 +1325,9 @@ NWC24Err NWC24iCheckDlHeaderConsistency(DlTaskListHeader* header, BOOL repair) { if (result < NWC24_OK) { return result; } - if (NWC24WorkP != NULL) { - currentHeader = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - currentHeader = NULL; - } - if (currentHeader != NULL && taskId >= currentHeader->taskCount && - ((DlTaskData*)&task)->subTaskCount == 0) { - if (((DlTaskData*)&task)->id == 0xffff || - ((DlTaskData*)&task)->id >= currentHeader->maxTaskCount) { + currentHeader = GetCachedDlHeader(); + if (currentHeader != NULL && taskId >= currentHeader->taskCount && ((DlTaskData*)&task)->subTaskCount == 0) { + if (((DlTaskData*)&task)->id == 0xffff || ((DlTaskData*)&task)->id >= currentHeader->maxTaskCount) { result = NWC24_ERR_INVALID_VALUE; } else { result = DeleteDlTask(&task); @@ -1534,11 +1344,10 @@ NWC24Err NWC24iCheckDlHeaderConsistency(DlTaskListHeader* header, BOOL repair) { } NWC24Err NWC24iCreateDlTaskList() { - NWC24File file; - DlTaskListHeader* header; - DlTaskData* task; - NWC24Err result; u16 taskId; + DlTaskListHeader* header; + NWC24Err result; + NWC24File file; if (NWC24WorkP != NULL) { header = (DlTaskListHeader*)NWC24WorkP->dlHead; @@ -1560,64 +1369,34 @@ NWC24Err NWC24iCreateDlTaskList() { return result; } - result = NWC24FSeek(&file, 0, NWC24_SEEK_BEG); - if (result >= NWC24_OK) { - result = NWC24FWrite(header, 0x800, &file); - if (result >= NWC24_OK) { - result = NWC24_OK; - } - } - + result = WriteDlHeader(&file); if (result >= NWC24_OK) { for (taskId = 0; taskId < NWC24_DL_TASK_MAX; taskId++) { - if (NWC24WorkP != NULL) { - task = (DlTaskData*)NWC24WorkP->dlTask; - } else { - task = NULL; - } - - memset(task, 0, sizeof(*task)); - task->type = 0xff; - task->id = taskId; - memset(&header->entries[taskId], 0, sizeof(header->entries[taskId])); - - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; - } - if (header->maxTaskCount > NWC24_DL_TASK_MAX || taskId >= header->maxTaskCount) { - result = NWC24_ERR_INVALID_VALUE; - break; - } - - result = NWC24FSeek(&file, 0x800 + taskId * 0x200, NWC24_SEEK_BEG); - if (result < NWC24_OK) { - break; - } - - memcpy((DlTaskData*)NWC24WorkP->dlTask, task, sizeof(*task)); - result = NWC24FWrite((DlTaskData*)NWC24WorkP->dlTask, 0x200, &file); + result = ClearDlTaskEntry(taskId, &file); if (result < NWC24_OK) { break; } } } - - NWC24FClose(&file); - return result; + { + NWC24Err closeResult = NWC24FClose(&file); + if (result != NWC24_OK) { + return result; + } + return closeResult; + } } +#pragma dont_inline on NWC24Err NWC24iInitDlTaskList(BOOL force) { NWC24Err result; DlTaskListHeader* header; result = NWC24iOpenDlTaskList(); - if (result == NWC24_OK) { - if (!force) { - return result; - } - } else if (result == NWC24_ERR_VER_MISMATCH) { + if (result == NWC24_OK && !force) { + return result; + } + if (result == NWC24_ERR_VER_MISMATCH) { if (NWC24WorkP != NULL) { header = (DlTaskListHeader*)NWC24WorkP->dlHead; } else { @@ -1629,6 +1408,7 @@ NWC24Err NWC24iInitDlTaskList(BOOL force) { } return NWC24iCreateDlTaskList(); } +#pragma dont_inline reset NWC24Err NWC24iLoadDlHeader() { NWC24File file; @@ -1669,19 +1449,19 @@ NWC24Err NWC24iLoadDlHeader() { } if (NWC24FOpen(&updateFile, DLFilePath, NWC24_OPEN_RW) >= NWC24_OK) { if (NWC24FSeek(&updateFile, 0, NWC24_SEEK_BEG) >= NWC24_OK) { + DlTaskListHeader* writeHeader; if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; + writeHeader = (DlTaskListHeader*)NWC24WorkP->dlHead; } else { - header = NULL; + writeHeader = NULL; } - NWC24FWrite(header, 0x800, &updateFile); + NWC24FWrite(writeHeader, 0x800, &updateFile); } NWC24FClose(&updateFile); } } - if (header->maxTaskCount < 1 || header->taskCount < 1 || - header->maxTaskCount < header->taskCount) { + if (header->maxTaskCount < 1 || header->taskCount < 1 || header->maxTaskCount < header->taskCount) { result = NWC24_ERR_BROKEN; } else { result = NWC24_OK; @@ -1697,50 +1477,24 @@ NWC24Err NWC24iLoadDlHeader() { NWC24Err StoreDlTask(NWC24DlTask* dlTask) { NWC24File file; - DlTaskData* task; - DlTaskListHeader* header; NWC24Err result; - NWC24DlId taskId; - - task = (DlTaskData*)dlTask; - result = NWC24FOpen(&file, DLFilePath, 4); + NWC24Err closeResult; + result = NWC24FOpen(&file, DLFilePath, NWC24_OPEN_RW); if (result < NWC24_OK) { return result; } - - taskId = task->id; - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; - } - if (header->maxTaskCount > NWC24_DL_TASK_MAX || taskId >= header->maxTaskCount) { - result = NWC24_ERR_INVALID_VALUE; - } else { - result = NWC24FSeek(&file, 0x800 + taskId * 0x200, NWC24_SEEK_BEG); - } - + result = WriteDlTaskEntry((DlTaskData*)dlTask, &file); if (result >= NWC24_OK) { - memcpy(NWC24WorkP->dlTask, task, sizeof(*task)); - result = NWC24FWrite(NWC24WorkP->dlTask, sizeof(*task), &file); - } - - if (result >= NWC24_OK) { - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; - } - header->entries[taskId].flags = task->flags; - header->entries[taskId].priority = task->priority; - result = NWC24FSeek(&file, 0, NWC24_SEEK_BEG); + result = UpdateDlEntryHeader((DlTaskData*)dlTask); if (result >= NWC24_OK) { - result = NWC24FWrite(header, 0x800, &file); + result = WriteDlHeader(&file); } } - - NWC24FClose(&file); - return result; + closeResult = NWC24FClose(&file); + if (result != NWC24_OK) { + return result; + } + return closeResult; } NWC24Err AddTaskInternal(NWC24DlTask* dlTask, u16 taskCount, u16 maxTaskCount) { @@ -1751,41 +1505,15 @@ NWC24Err AddTaskInternal(NWC24DlTask* dlTask, u16 taskCount, u16 maxTaskCount) { char* url; OSTime universalTime; - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; + result = ValidateDlTask(dlTask, TRUE); + if (result != NWC24_OK) { + return result; } - - if (dlTask == NULL) { - return NWC24_ERR_INVALID_VALUE; - } - if (header == NULL) { - return NWC24_ERR_LIB_NOT_OPENED; - } - task = (DlTaskData*)dlTask; - if (!NWC24IsMsgLibOpenedByTool()) { - u32 taskAppId = task->appId; - u32 appId = NWC24GetAppId(); - BOOL allowed = (taskAppId & 0xffffff00) == (appId & 0xffffff00); - if (!allowed && (task->flags & 0x40)) { - allowed = task->groupId == NWC24GetGroupId(); - } - if (!allowed) { - return NWC24_ERR_PROTECTED; - } - } - taskId = task->id; - if (taskId != 0xffff && taskId >= header->maxTaskCount) { - return NWC24_ERR_INVALID_VALUE; - } - url = task->url; result = NWC24iCheckStringLength(url, 7, 0x100); - if (result >= NWC24_OK && strncmp(url, "http://", 7) != 0 && - strncmp(url, "https://", 8) != 0) { + if (result >= NWC24_OK && strncmp(url, "http://", 7) != 0 && strncmp(url, "https://", 8) != 0) { result = NWC24_ERR_FORMAT; } if (result < NWC24_OK) { @@ -1795,11 +1523,7 @@ NWC24Err AddTaskInternal(NWC24DlTask* dlTask, u16 taskCount, u16 maxTaskCount) { retryExistingTask: taskId = task->id; if (taskId != 0xffff) { - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; - } + header = GetCachedDlHeader(); result = NWC24_OK; if (dlTask == NULL) { @@ -1827,22 +1551,14 @@ retryExistingTask: return result; } - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; - } + header = GetCachedDlHeader(); if (taskId >= header->maxTaskCount) { return NWC24_ERR_INVALID_VALUE; } result = NWC24iGetUniversalTime(&universalTime); if (result >= NWC24_OK) { - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; - } + header = GetCachedDlHeader(); result = NWC24_OK; if (dlTask == NULL) { result = NWC24_ERR_INVALID_VALUE; @@ -1864,11 +1580,7 @@ retryExistingTask: return result; } - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; - } + header = GetCachedDlHeader(); result = NWC24_OK; if (dlTask == NULL) { result = NWC24_ERR_INVALID_VALUE; @@ -1903,11 +1615,7 @@ retryExistingTask: u32 retryMask; task->retryCount = (task->retryCount + 1) & 0x1f; - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; - } + header = GetCachedDlHeader(); if (dlTask == NULL) { return NWC24_ERR_INVALID_VALUE; } @@ -1955,24 +1663,16 @@ retryExistingTask: for (;;) { u16 currentTaskId; - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; - } - if (dlTask == NULL || header == NULL || taskCount > maxTaskCount || - taskCount >= header->maxTaskCount || maxTaskCount > header->maxTaskCount) { + header = GetCachedDlHeader(); + if (dlTask == NULL || header == NULL || taskCount > maxTaskCount || taskCount >= header->maxTaskCount || + maxTaskCount > header->maxTaskCount) { return NWC24_ERR_INVALID_VALUE; } currentTaskId = taskCount; while (currentTaskId < maxTaskCount) { - if (NWC24WorkP != NULL) { - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - } else { - header = NULL; - } - if (header->entries[currentTaskId].flags == 0) { + header = GetCachedDlHeader(); + if (header->entries[currentTaskId].appId == 0) { task->id = currentTaskId; goto retryExistingTask; } @@ -1989,42 +1689,18 @@ retryExistingTask: NWC24Err DeleteDlTask(NWC24DlTask* dlTask) { NWC24File file; - DlTaskData* task; - DlTaskListHeader* header; NWC24Err result; NWC24Err closeResult; - NWC24DlId taskId; result = NWC24FOpen(&file, DLFilePath, 4); if (result < NWC24_OK) { return result; } - taskId = ((DlTaskData*)dlTask)->id; - task = (DlTaskData*)NWC24WorkP->dlTask; - memset(task, 0, sizeof(*task)); - task->id = taskId; - task->type = 0xff; - memset(&((DlTaskListHeader*)NWC24WorkP->dlHead)->entries[taskId], 0, - sizeof(((DlTaskListHeader*)NWC24WorkP->dlHead)->entries[taskId])); - - header = (DlTaskListHeader*)NWC24WorkP->dlHead; - if (header->maxTaskCount > NWC24_DL_TASK_MAX || taskId >= header->maxTaskCount) { - result = NWC24_ERR_INVALID_VALUE; - } else { - result = NWC24FSeek(&file, 0x800 + taskId * 0x200, NWC24_SEEK_BEG); - } + result = ClearDlTaskEntry(((DlTaskData*)dlTask)->id, &file); if (result >= NWC24_OK) { - memcpy(NWC24WorkP->dlTask, task, sizeof(*task)); - result = NWC24FWrite(NWC24WorkP->dlTask, sizeof(*task), &file); - } - if (result >= NWC24_OK) { - memset(&((DlTaskListHeader*)NWC24WorkP->dlHead)->entries[taskId], 0, - sizeof(((DlTaskListHeader*)NWC24WorkP->dlHead)->entries[taskId])); - result = NWC24FSeek(&file, 0, NWC24_SEEK_BEG); - if (result >= NWC24_OK) { - result = NWC24FWrite((DlTaskListHeader*)NWC24WorkP->dlHead, 0x800, &file); - } + InitDlEntryHeader(((DlTaskData*)dlTask)->id); + result = WriteDlHeader(&file); } closeResult = NWC24FClose(&file); diff --git a/tools/decomp-assist/CDBIntArray.attempts.md b/tools/decomp-assist/CDBIntArray.attempts.md new file mode 100644 index 00000000..695def4c --- /dev/null +++ b/tools/decomp-assist/CDBIntArray.attempts.md @@ -0,0 +1,29 @@ +# CDBIntArray attempts + +Baseline 0/13, 0/1556 code. No data sections. + +Started with scalar copies, ordered comparison, array descriptors and recursive dictionary operations. Explicit full test operand order and unequal return match the nine basic methods. Initial recursive auto-inlining expanded searches to 412 instructions; disabling recursive inlining and using direct scalar comparisons restores tail calls. Adapted the existing sibling record-key array implementation, using the same capacity and reverse-direction behavior. The same ordinary dont_inline pragma as that sibling preserves the recursive searches. No helper retained solely for emission. + +CDBIntArrayDicInsertR | return right index plus comparison | (93.548386, -5) | src 0xf8 base 0xf8 insns 62/62 +CDBIntArrayDicInsertR | explicit values in comparisons | (98.30645, -9999) | src 0xfc base 0xf8 insns 63/62 +CDBIntArrayDicInsertR | middle first local declaration | (98.30645, -9999) | src 0xfc base 0xf8 insns 63/62 +CDBIntArrayDicFindR | direct array indexing | (94.19355, -9999) | src 0xfc base 0xf8 insns 63/62 +CDBIntArrayDicFindR | inverted leaf comparison | (100.0, -2) | src 0xf8 base 0xf8 insns 62/62 +CDBIntArrayDicFindR | comparison first declaration | (94.19355, -9999) | src 0xfc base 0xf8 insns 63/62 +CDBIntArrayDicInsertR | leaf early return | (98.30645, -9999) | src 0xfc base 0xf8 insns 63/62 +CDBIntArrayDicInsertR | leaf result conditional expression | (93.548386, -3) | src 0xf8 base 0xf8 insns 62/62 +CDBIntArrayDicInsertR | comparison variable before index | (93.548386, -3) | src 0xf8 base 0xf8 insns 62/62 +CDBIntArrayDicFindR | leaf positive branch first | (94.19355, -9999) | src 0xfc base 0xf8 insns 63/62 +CDBIntArrayDicFindR | leaf conditional expression | (100.0, 0) | src 0xf8 base 0xf8 insns 62/62 +CDBIntArrayDicInsert | direct scalar copies | (99.60317, -16) | src 0x2f4 base 0x2f4 insns 189/189 +CDBIntArrayDicInsert | record pointer before scalar temporaries | (94.89418, -9999) | src 0x300 base 0x2f4 insns 192/189 +CDBIntArrayDicInsert | signed move byte counts | (94.89418, -9999) | src 0x300 base 0x2f4 insns 192/189 +CDBIntArrayDicInsertR | separate result index | (100.0, 0) | src 0xf8 base 0xf8 insns 62/62 +CDBIntArrayDicInsert | local value loaded before ordered comparisons | (99.78836, -5) | src 0x2f4 base 0x2f4 insns 189/189 +CDBIntArrayDicInsert | record local first declaration | (99.60317, -14) | src 0x2f4 base 0x2f4 insns 189/189 +CDBIntArrayDicInsert | comparison expression evaluates stored value first | (99.49735, -16) | src 0x2f4 base 0x2f4 insns 189/189 +CDBIntArrayDicInsert | stored element captured after incoming value | (100.0, 0) | src 0x2f4 base 0x2f4 insns 189/189 + +Recursion trials additionally included recursive calls, goto iteration, source-level ordered comparisons and separate leaf return index. Find tried empty end return, found-first branch and shared result before adopting the sibling method; it now matches. + +Final: all 13 functions instruction-exact, 1556/1556 code bytes, no data sections. Full gate and pool pass. diff --git a/tools/decomp-assist/CDBRecord.attempts.md b/tools/decomp-assist/CDBRecord.attempts.md new file mode 100644 index 00000000..a3127316 --- /dev/null +++ b/tools/decomp-assist/CDBRecord.attempts.md @@ -0,0 +1,31 @@ +# CDBRecord attempts + +Baseline: 0/29 exact, 0/7076 code bytes. + +Reconstructed descriptor, instance, cryptographic, and file operations using the target instructions and existing declarations. Named mutex, used flag, database and open flags replace opaque offsets; the header layout is gated by CDB_RECORD_IMPLEMENTATION. + +The pool first diverges at string 8: the original contains diagnostics for file-size, reduction, setters, duplication and owner-change functions absent from this extracted object. No unused string objects or artificial padding were retained. BSS buffers and zero AES key match (144 bytes); the 2496-byte data section remains partial. + +CDBCryptBuffer | for loop offset progression | (99.97479, -3) | src 0x1dc base 0x1dc insns 119/119 +CDBCryptBuffer | remaining-length comparison | (92.411766, -9999) | src 0x1d8 base 0x1dc insns 118/119 +CDBCryptBuffer | named input chunk pointer | (96.40336, -9999) | src 0x1e0 base 0x1dc insns 120/119 +CDBRecordEncrypt | integer null tests | (96.20422, -68) | src 0x470 base 0x470 insns 284/284 +CDBRecordEncrypt | signature and hmac declaration order | (90.60564, -9999) | src 0x494 base 0x470 insns 293/284 +CDBRecordEncrypt | single file temporary for setters | (90.60564, -9999) | src 0x494 base 0x470 insns 293/284 +CDBRecordDecrypt | 64-byte hash key alignment | (86.073395, -9999) | src 0x384 base 0x368 insns 225/218 +CDBRecordDecrypt | integer null tests | (90.348625, -9999) | src 0x370 base 0x368 insns 220/218 +CDBRecordDecrypt | signature before digest declaration | (86.0367, -9999) | src 0x384 base 0x368 insns 225/218 +CDBRecordDecrypt | signature and hmac alignment | (99.89449, -23) | src 0x368 base 0x368 insns 218/218 +CDBRecordDecrypt | 64-byte key alignment with signature | (99.89449, -23) | src 0x368 base 0x368 insns 218/218 +CDBRecordDecrypt | reverse file and status declaration lifetime | (99.68807, -32) | src 0x368 base 0x368 insns 218/218 +CDBRecordDecrypt | swap digest and key-string lifetimes | (99.944954, -12) | src 0x368 base 0x368 insns 218/218 +CDBRecordDecrypt | 16-byte key string alignment | (99.94954, -11) | src 0x368 base 0x368 insns 218/218 +CDBRecordDecrypt | unaligned key string | (99.94954, -11) | src 0x368 base 0x368 insns 218/218 +CDBRecordDecrypt | complete record key | (99.96789, -7) | src 0x368 base 0x368 insns 218/218 + +Additional Encrypt attempt: moved error status to the outer scope, 97.19014%, 283/284 instructions. +Additional Decrypt correction: restored 0x3E800 size limit, actual seek/read error returns, level-3 owner warning, output-size local; 218/218 instructions. Natural buffer alignment and declaration order reach 99.96789%, seven stack-address differences. + +Remaining: CDBCryptBuffer 99.97479%, 119/119 instructions, three pool offsets; CDBRecordEncrypt 97.19014%, register allocation and one instruction; CDBRecordDecrypt 99.96789%, stack placement. + +The four forced field accessors end with CDBUnlock and do not produce a CDBErr result. Their void declarations are gated by CDB_RECORD_IMPLEMENTATION, preserving all other translation units and avoiding fall-through non-void definitions. diff --git a/tools/decomp-assist/NWC24Download.attempts.md b/tools/decomp-assist/NWC24Download.attempts.md new file mode 100644 index 00000000..e58d7538 --- /dev/null +++ b/tools/decomp-assist/NWC24Download.attempts.md @@ -0,0 +1,131 @@ +# NWC24Download attempts + +Baseline 7/30 instruction-exact, 472/12496 code bytes, 80/80 data bytes. + +Pool checked before code tuning: identical (3 strings). Header, title ownership and group permission checks were reconstructed as readable inline helpers; SetDlId, SetDlPriority and GetDlAppId now match. The initializer retains its observed task-list calls. Seek/write/clear helpers restore task and header normalization, close-result propagation, and entry ownership metadata (application ID, not task flags). StoreDlTask and DeleteDlTask now match, with original explicit call boundaries preserved by the repository NO_INLINE macro. + +Closest functions were tried first. Each remaining function has at least three distinct compiled source attempts below. Header-helper extraction, declaration lifetime and keeping call boundaries were measured independently, with only improvements retained. Register-only survivors were left after additional scoped-local and branch-form attempts. + +NWC24GetDlTask | named destination alias | (99.728264, -5) | src 0x170 base 0x170 insns 92/92 +NWC24GetDlTask | task identifier alias before destination | (99.728264, -5) | src 0x170 base 0x170 insns 92/92 +NWC24GetDlTask | operation status before read status | (99.728264, -5) | src 0x170 base 0x170 insns 92/92 +NWC24GetDlAppId | taskId local declared after header | (99.0, -7) | src 0x8c base 0x8c insns 35/35 +NWC24GetDlAppId | task pointer declared after header | (99.0, -7) | src 0x8c base 0x8c insns 35/35 +NWC24GetDlAppId | common exit after output | (99.0, -7) | src 0x8c base 0x8c insns 35/35 +NWC24SetDlId | work declaration before header | (98.875, -8) | src 0xa0 base 0xa0 insns 40/40 +NWC24SetDlId | reuse initial work in refreshed header | (98.875, -8) | src 0xa0 base 0xa0 insns 40/40 +NWC24SetDlId | header declared before task identifier | (98.5, -11) | src 0xa0 base 0xa0 insns 40/40 +NWC24iLoadDlHeader | scoped write header pointer | (97.9, -4) | src 0x190 base 0x190 insns 100/100 +NWC24iLoadDlHeader | seek and read shared operation result | (96.15, -9999) | src 0x194 base 0x190 insns 101/100 +NWC24iLoadDlHeader | read status conditional branch | (95.05, -9999) | src 0x198 base 0x190 insns 102/100 +NWC24iInitDlTaskList | separate success and version checks | (51.29032, -9999) | src 0xb8 base 0x7c insns 46/31 +NWC24iInitDlTaskList | success test nested before version | (51.29032, -9999) | src 0xb8 base 0x7c insns 46/31 +NWC24iInitDlTaskList | common final result | (51.129032, -9999) | src 0xb8 base 0x7c insns 46/31 +NWC24iInitDlTaskList | preserve task list calls | (100.0, 0) | src 0x7c base 0x7c insns 31/31 +NWC24iLoadDlHeader | shared seek-read status with scoped write pointer | (97.25, -16) | src 0x190 base 0x190 insns 100/100 +NWC24iLoadDlHeader | seek-read operation local | (97.25, -16) | src 0x190 base 0x190 insns 100/100 +NWC24iLoadDlHeader | inline seek-read operation | (96.25, -9999) | src 0x194 base 0x190 insns 101/100 +NWC24SetDlPriority | shared inline validation with owner and group predicates | (100.0, 0) | src 0x108 base 0x108 insns 66/66 +NWC24SetDlInterval | shared inline validation with owner and group predicates | (99.89796, -3) | src 0x24c base 0x24c insns 147/147 +NWC24SetDlUrl | shared inline validation with owner and group predicates | (99.95413, -1) | src 0x1b4 base 0x1b4 insns 109/109 +NWC24SetDlFlags | shared inline validation with owner and group predicates | (98.9011, -9999) | src 0x168 base 0x16c insns 90/91 +NWC24GetDlAppId | shared inline validation with owner and group predicates | (100.0, 0) | src 0x8c base 0x8c insns 35/35 +NWC24SetDlId | shared inline validation with owner and group predicates | (100.0, 0) | src 0xa0 base 0xa0 insns 40/40 +NWC24SetDlInterval | separate final identifier lifetime | (99.89796, -3) | src 0x24c base 0x24c insns 147/147 +NWC24SetDlInterval | refresh validation helper | (99.89796, -3) | src 0x24c base 0x24c insns 147/147 +NWC24SetDlInterval | timestamp temporary declaration first | (99.89796, -3) | src 0x24c base 0x24c insns 147/147 +NWC24SetDlFlags | separate reserved flag categories | (95.43956, -4) | src 0x16c base 0x16c insns 91/91 +NWC24SetDlFlags | type checks with two cases | (94.83517, -9999) | src 0x15c base 0x16c insns 87/91 +NWC24SetDlFlags | write flags from common exit | (93.95605, -9999) | src 0x178 base 0x16c insns 94/91 +NWC24SetDlUrl | length error to common URL check | (98.99083, -9999) | src 0x1b0 base 0x1b4 insns 108/109 +NWC24SetDlUrl | length guard around schemes | (98.99083, -9999) | src 0x1b0 base 0x1b4 insns 108/109 +NWC24SetDlUrl | ownership pointer after result variable | (99.95413, -1) | src 0x1b4 base 0x1b4 insns 109/109 +NWC24InitDlTask | cached-header inline helper lifetime | (89.36806, -9999) | src 0x234 base 0x240 insns 141/144 +NWC24InitDlTask | scalar and pointer declaration order | (89.36806, -9999) | src 0x234 base 0x240 insns 141/144 +NWC24InitDlTask | preserve calls to earlier functions | (89.36806, -9999) | src 0x234 base 0x240 insns 141/144 +NWC24DeleteDlTask | cached-header inline helper lifetime | (85.75238, -9999) | src 0x18c base 0x1a4 insns 99/105 +NWC24DeleteDlTask | scalar and pointer declaration order | (85.419044, -9999) | src 0x18c base 0x1a4 insns 99/105 +NWC24DeleteDlTask | preserve calls to earlier functions | (85.419044, -9999) | src 0x18c base 0x1a4 insns 99/105 +NWC24IterateDlTaskEx | scalar and pointer declaration order | (85.06896, -9999) | src 0x234 base 0x244 insns 141/145 +NWC24IterateDlTaskEx | preserve calls to earlier functions | (85.06896, -9999) | src 0x234 base 0x244 insns 141/145 +NWC24IterateDlTask | cached-header inline helper lifetime | (80.79747, -9999) | src 0x128 base 0x13c insns 74/79 +NWC24IterateDlTask | scalar and pointer declaration order | (81.177216, -9999) | src 0x128 base 0x13c insns 74/79 +NWC24IterateDlTask | preserve calls to earlier functions | (80.79747, -9999) | src 0x128 base 0x13c insns 74/79 +NWC24ManageDlTaskListForMenu | cached-header inline helper lifetime | (73.45395, -9999) | src 0x20c base 0x260 insns 131/152 +NWC24ManageDlTaskListForMenu | scalar and pointer declaration order | (73.585526, -9999) | src 0x20c base 0x260 insns 131/152 +NWC24ManageDlTaskListForMenu | preserve calls to earlier functions | (73.585526, -9999) | src 0x20c base 0x260 insns 131/152 +NWC24PurgeOldestDlTask | cached-header inline helper lifetime | (72.3125, -9999) | src 0x25c base 0x2c0 insns 151/176 +NWC24PurgeOldestDlTask | scalar and pointer declaration order | (72.22727, -9999) | src 0x25c base 0x2c0 insns 151/176 +NWC24PurgeOldestDlTask | preserve calls to earlier functions | (72.22727, -9999) | src 0x25c base 0x2c0 insns 151/176 +DeleteDlTask | scalar and pointer declaration order | (69.92921, -9999) | src 0x16c base 0x1c4 insns 91/113 +DeleteDlTask | preserve calls to earlier functions | (69.92921, -9999) | src 0x16c base 0x1c4 insns 91/113 +NWC24iCreateDlTaskList | cached-header inline helper lifetime | (69.01504, -9999) | src 0x1e0 base 0x214 insns 120/133 +NWC24iCreateDlTaskList | scalar and pointer declaration order | (69.2406, -9999) | src 0x1e0 base 0x214 insns 120/133 +NWC24iCreateDlTaskList | preserve calls to earlier functions | (69.01504, -9999) | src 0x1e0 base 0x214 insns 120/133 +StoreDlTask | cached-header inline helper lifetime | (68.196075, -9999) | src 0x154 base 0x198 insns 85/102 +StoreDlTask | scalar and pointer declaration order | (68.245094, -9999) | src 0x154 base 0x198 insns 85/102 +StoreDlTask | preserve calls to earlier functions | (68.245094, -9999) | src 0x154 base 0x198 insns 85/102 +NWC24AddDlTask | cached-header inline helper lifetime | (67.14685, -9999) | src 0x1c4 base 0x23c insns 113/143 +NWC24AddDlTask | scalar and pointer declaration order | (65.44056, -9999) | src 0x1cc base 0x23c insns 115/143 +NWC24AddDlTask | preserve calls to earlier functions | (67.46154, -9999) | src 0x1c4 base 0x23c insns 113/143 +AddTaskInternal | cached-header inline helper lifetime | (63.670822, -9999) | src 0x5d0 base 0x644 insns 372/401 +AddTaskInternal | scalar and pointer declaration order | (63.658356, -9999) | src 0x5d0 base 0x644 insns 372/401 +AddTaskInternal | preserve calls to earlier functions | (63.658356, -9999) | src 0x5d0 base 0x644 insns 372/401 +NWC24UpdateDlTask | cached-header inline helper lifetime | (62.225296, -9999) | src 0x408 base 0x3f4 insns 258/253 +NWC24UpdateDlTask | scalar and pointer declaration order | (62.343872, -9999) | src 0x408 base 0x3f4 insns 258/253 +NWC24UpdateDlTask | preserve calls to earlier functions | (62.225296, -9999) | src 0x408 base 0x3f4 insns 258/253 +NWC24ExtendDlTaskList | cached-header inline helper lifetime | (61.992702, -9999) | src 0x1e4 base 0x224 insns 121/137 +NWC24ExtendDlTaskList | scalar and pointer declaration order | (61.91971, -9999) | src 0x1e4 base 0x224 insns 121/137 +NWC24ExtendDlTaskList | preserve calls to earlier functions | (61.992702, -9999) | src 0x1e4 base 0x224 insns 121/137 +NWC24iCheckDlHeaderConsistency | cached-header inline helper lifetime | (53.9717, -9999) | src 0x270 base 0x350 insns 156/212 +NWC24iCheckDlHeaderConsistency | scalar and pointer declaration order | (53.853775, -9999) | src 0x270 base 0x350 insns 156/212 +NWC24iCheckDlHeaderConsistency | preserve calls to earlier functions | (53.853775, -9999) | src 0x270 base 0x350 insns 156/212 +StoreDlTask | full-width cached count in seek helper | (99.70588, -5) | src 0x198 base 0x198 insns 102/102 +StoreDlTask | direct count fields in seek helper | (100.0, 0) | src 0x198 base 0x198 insns 102/102 +StoreDlTask | id comparison first in seek helper | (95.78432, -7) | src 0x198 base 0x198 insns 102/102 +DeleteDlTask | identifier before cached task declaration | (99.823006, -4) | src 0x1c4 base 0x1c4 insns 113/113 +DeleteDlTask | result before cached task declaration | (99.42478, -12) | src 0x1c4 base 0x1c4 insns 113/113 +DeleteDlTask | separate header reset identifier | (99.42478, -12) | src 0x1c4 base 0x1c4 insns 113/113 +NWC24IterateDlTaskEx | descending expression signed sort mode | (85.06896, -9999) | src 0x234 base 0x244 insns 141/145 +NWC24IterateDlTaskEx | iteration result next step in for clause | (85.06896, -9999) | src 0x234 base 0x244 insns 141/145 +NWC24IterateDlTaskEx | callback value before candidate booleans | (85.06896, -9999) | src 0x234 base 0x244 insns 141/145 +DeleteDlTask | clear helper scopes for task and identifier | (100.0, 0) | src 0x1c4 base 0x1c4 insns 113/113 +NWC24iCreateDlTaskList | shared clear/write helpers and original close-result propagation | (99.62406, -10) | src 0x214 base 0x214 insns 133/133 +NWC24ExtendDlTaskList | shared clear/write helpers and original close-result propagation | (97.62774, -9999) | src 0x230 base 0x224 insns 140/137 +NWC24iCreateDlTaskList | header lifetime scoped to initialization | (99.62406, -10) | src 0x214 base 0x214 insns 133/133 +NWC24iCreateDlTaskList | header declaration after task id | (99.62406, -10) | src 0x214 base 0x214 insns 133/133 +NWC24iCreateDlTaskList | header after error result | (99.62406, -10) | src 0x214 base 0x214 insns 133/133 +NWC24ExtendDlTaskList | iteration failure to close block | (99.85401, -4) | src 0x224 base 0x224 insns 137/137 +NWC24ExtendDlTaskList | close status declaration before open status | (91.30657, -9999) | src 0x220 base 0x224 insns 136/137 +NWC24ExtendDlTaskList | open result scoped away from iteration | (96.86131, -9999) | src 0x234 base 0x224 insns 141/137 +NWC24iCreateDlTaskList | header-format initializer helper | (99.62406, -10) | src 0x214 base 0x214 insns 133/133 +NWC24ExtendDlTaskList | separate final return status | (91.277374, -9999) | src 0x1f8 base 0x224 insns 126/137 +NWC24ExtendDlTaskList | loop identifier separate scope | (99.85401, -4) | src 0x224 base 0x224 insns 137/137 +NWC24ExtendDlTaskList | header pointer declaration after close status | (99.85401, -4) | src 0x224 base 0x224 insns 137/137 +NWC24UpdateDlTask | shared ownership and validation helpers | (68.19763, -9999) | src 0x420 base 0x3f4 insns 264/253 +NWC24DeleteDlTask | shared ownership and validation helpers | (0, -9999) | [1/1] MWCC build/43U/src/libs/RevoEX/src/nwc24/NWC24Download.o +AddTaskInternal | shared ownership and validation helpers | (66.2394, -9999) | src 0x5e4 base 0x644 insns 377/401 + +Additional Store/Delete trials: reconstructed file helpers (91.27451%, 105/102; 91.28319%,109/113), captured entry pointer and reloaded original identifier (99.70588%,102/102;99.159294%,113/113), widened seek count (Store100%), scoped clear helper (Delete100%). Explicit NO_INLINE declarations prevent these functions from being auto-inlined into Update/AddTaskInternal; all 30 functions were remeasured after these changes. + +Remaining: + +NWC24InitDlTask 89.36806%: validation, branch shape and instruction count; src 0x234 base 0x240 insns 141/144. +NWC24SetDlInterval 99.89796%: register allocation; src 0x24c base 0x24c insns 147/147. +NWC24SetDlUrl 99.95413%: one error branch destination; src 0x1b4 base 0x1b4 insns 109/109. +NWC24SetDlFlags 98.9011%: validation, branch shape and instruction count; src 0x168 base 0x16c insns 90/91. +NWC24IterateDlTask 81.177216%: validation, branch shape and instruction count; src 0x128 base 0x13c insns 74/79. +NWC24IterateDlTaskEx 85.06896%: validation, branch shape and instruction count; src 0x234 base 0x244 insns 141/145. +NWC24UpdateDlTask 68.19763%: validation, branch shape and instruction count; src 0x420 base 0x3f4 insns 264/253. +NWC24DeleteDlTask 85.75238%: validation, branch shape and instruction count; src 0x18c base 0x1a4 insns 99/105. +NWC24AddDlTask 67.46154%: validation, branch shape and instruction count; src 0x1c4 base 0x23c insns 113/143. +NWC24GetDlTask 99.728264%: register allocation; src 0x170 base 0x170 insns 92/92. +NWC24PurgeOldestDlTask 72.3125%: validation, branch shape and instruction count; src 0x25c base 0x2c0 insns 151/176. +NWC24ManageDlTaskListForMenu 73.585526%: validation, branch shape and instruction count; src 0x20c base 0x260 insns 131/152. +NWC24ExtendDlTaskList 99.85401%: register allocation; src 0x224 base 0x224 insns 137/137. +NWC24iCheckDlHeaderConsistency 53.9717%: validation, branch shape and instruction count; src 0x270 base 0x350 insns 156/212. +NWC24iCreateDlTaskList 99.62406%: register allocation; src 0x214 base 0x214 insns 133/133. +NWC24iLoadDlHeader 97.9%: seek/read error join (four instructions differ); src 0x190 base 0x190 insns 100/100. +AddTaskInternal 66.2394%: validation, branch shape and instruction count; src 0x5e4 base 0x644 insns 377/401. + +Final object: {'fuzzy_match_percent': 83.35883, 'total_code': '12496', 'matched_code': '2020', 'matched_code_percent': 16.165173, 'total_data': '80', 'matched_data': '80', 'matched_data_percent': 100.0, 'total_functions': 30, 'matched_functions': 13, 'matched_functions_percent': 43.333332, 'total_units': 1} -- 2.49.1 From 033b33a4865c4d86ec55c15fb9884fc0d19cec49 Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Wed, 30 Sep 2026 00:18:48 -0500 Subject: [PATCH 3/5] tiCellPhone: 72/86 functions (worker 1ccf7e1f) (#335) --- README.md | 4 +- include/keyboard/tiCellPhone.h | 174 ++- include/keyboard/tiHKBManager.h | 13 + include/keyboard/tiKeyboard.h | 10 +- include/keyboard/tiPcKeyboard.h | 4 + include/keyboard/tiTextInputBase.h | 3 + include/keyboard/tiToolBar.h | 4 + src/keyboard/tiCellPhone.cpp | 1606 ++++++++++++++++++++++++++++ 8 files changed, 1811 insertions(+), 7 deletions(-) create mode 100644 src/keyboard/tiCellPhone.cpp diff --git a/README.md b/README.md index b51194be..7fca1c39 100644 --- a/README.md +++ b/README.md @@ -53,9 +53,9 @@ Progress | Decompiled | Matched | Linked | Data | |:---:|:---:|:---:|:---:| -| 88.20% | 77.88% | 56.92% | 88.24% | +| 88.75% | 78.13% | 56.92% | 88.24% | -units 752/1027 complete, functions 11369/12563 matched. +units 752/1027 complete, functions 11441/12563 matched. decompiled = code with a C/C++ implementation (objdiff fuzzy), matched = byte-exact code, linked = code actually linked into the DOL, data = byte-exact data diff --git a/include/keyboard/tiCellPhone.h b/include/keyboard/tiCellPhone.h index 09e782f9..b93479b4 100644 --- a/include/keyboard/tiCellPhone.h +++ b/include/keyboard/tiCellPhone.h @@ -6,9 +6,44 @@ #include "tiKeyboard.h" #endif +#ifdef TI_CELLPHONE_IMPLEMENTATION +#include +#endif + namespace textinput { + class Manager; +#ifdef TI_CELLPHONE_SAMPLE_CLASS + class EventObserver; +#endif + namespace predictlang { + class LayoutByNW4R; + } + namespace keyboard { +#ifdef TI_CELLPHONE_IMPLEMENTATION + enum VKeyCode { + VK_LINE_FEED = 0, + VK_DELETE = 1, + VK_SIGN_INPUT = 9, + VK_PREDICT_LANGUAGE = 10, + VK_INPUT_MODE_02 = 11, + VK_INPUT_MODE_03 = 13, + VK_INPUT_MODE_00 = 18, + VK_INPUT_MODE_01 = 19, + VK_TOGGLE_ABC_MODE = 23, + }; +#endif + namespace signwindow { + class LayoutByNW4R; + } + } + namespace keyboard { namespace cellphonetype { + class EventHandler; +#ifdef TI_CELLPHONE_IMPLEMENTATION + class CellPhoneAnmPane; + struct PaneNameToCharCode; +#endif #if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) class Base : public textinput::keyboard::KeyboardBase { #else @@ -16,6 +51,9 @@ namespace textinput { #endif public: #if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) +#if defined(MYTIMANAGER_IMPLEMENTATION) && defined(TI_CELLPHONE_SAMPLE_CLASS) + Base(Manager* manager) : mPreviousInputMode(0), mCurrentInputMode(0), mpManager(manager) {} +#endif enum InputMode { IM_00, IM_01, @@ -31,6 +69,10 @@ namespace textinput { virtual void onKey(u32, void*) override; #ifdef TIMANAGER_IMPLEMENTATION Base(Manager* manager) : mpManager(manager) {} +#endif +#if defined(TI_CELLPHONE_IMPLEMENTATION) + virtual u32 getType() override; +#elif defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION) virtual int getType() override; #elif defined(TIHWKEYBOARD_IMPLEMENTATION) virtual int getType() override; @@ -59,6 +101,9 @@ namespace textinput { virtual bool isAtokActive(); virtual void doInput(); virtual void updateFixMode(); +#ifdef TI_CELLPHONE_IMPLEMENTATION + wchar_t convertToZiCellphoneInput_(wchar_t value); +#endif #else virtual void vt_0x08(); virtual void vt_0x0C(); @@ -102,7 +147,11 @@ namespace textinput { #endif #if defined(MYTIMANAGER_IMPLEMENTATION) || defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) +#if defined(MYTIMANAGER_IMPLEMENTATION) && defined(TI_CELLPHONE_IMPLEMENTATION) + protected: +#else private: +#endif u32 mPreviousInputMode; u32 mCurrentInputMode; bool mbInputModeLocked; @@ -111,15 +160,26 @@ namespace textinput { bool mbUpperCaseMode; bool mbAbcMode; bool mbLanguageKeyMode; +#ifdef TI_CELLPHONE_IMPLEMENTATION + const PaneNameToCharCode* mHoldingButton; +#else u32 mHoldingButton; +#endif void* mpInputModeTable; MEMAllocator* mpAllocator; -#ifdef TIMANAGER_IMPLEMENTATION +#ifdef TI_CELLPHONE_IMPLEMENTATION Manager* mpManager; + bool mInputState; +#elif defined(TIMANAGER_IMPLEMENTATION) + Manager* mpManager; + u32 mInputState; #else void* mpInputSettings; -#endif u32 mInputState; +#endif +#ifdef TI_CELLPHONE_IMPLEMENTATION + void onCtrlKey_(VKeyCode keyCode); +#endif #endif }; @@ -151,9 +211,18 @@ namespace textinput { virtual void setPredictLanguageDialog(predictlang::LayoutByNW4R* dialog); virtual void setSignWindow(signwindow::LayoutByNW4R* window); #else +#if defined(MYTIMANAGER_IMPLEMENTATION) && defined(TI_CELLPHONE_SAMPLE_CLASS) + LayoutByNW4R(Manager* manager, nw4r::lyt::MultiArcResourceAccessor* resAccessor, EventObserver* observer) + : Base(manager), nw4rmanager::Layout(resAccessor, "fs_VK_cellPhone_a.brlyt", observer), mpSignWindow(NULL) {} +#endif virtual void doNumericMode(bool); +#ifdef TI_CELLPHONE_IMPLEMENTATION + virtual void setPredictLanguageDialog(predictlang::LayoutByNW4R*); + virtual void setSignWindow(signwindow::LayoutByNW4R*); +#else virtual void setPredictLanguageDialog(void*); virtual void setSignWindow(void*); +#endif #endif virtual void doNumericWithDotMode(bool); virtual void setLineFeedButton(bool); @@ -182,7 +251,41 @@ namespace textinput { virtual bool updateInput(int chan, f32 x, f32 y, u32 trig, u32 hold, u32 release, void* data) override; virtual bool updateInput(input::HKBManager& hkbManager) override; #endif -#ifdef TIMANAGER_IMPLEMENTATION +#ifdef TI_CELLPHONE_IMPLEMENTATION + virtual ~LayoutByNW4R(); + virtual void create(MEMAllocator* allocator) override; + virtual void init() override; + virtual void draw() override; + virtual void calc() override; + virtual void update() override; + virtual void onKey(u32 key, void* data) override; + virtual void onActive() override; + virtual void updateFromReceiver(u32 command, void* data) override; + virtual void changeInputMode(InputMode mode) override; + virtual void changePredictLanguage() override; + virtual void setAbcMode(bool enabled) override; + virtual void goSignInputMode() override; + virtual void setInputMode(InputMode mode) override; + virtual void setLanguage(Language language) override; + virtual void setCommandReceiver(CommandReceiver* receiver) override; + + virtual CellPhoneAnmPane* getAnmPane(InputMode mode); + virtual void throwReleaseForAll(); + virtual void changeAnimationAllToNormal(); + virtual void updatePredictLanguage(CommandReceiver::ChangePredictMode* mode); + virtual void changeKeyTop(const PaneNameToCharCode* keys); + virtual void changeSpaceKeyTop(const PaneNameToCharCode* keys); + void setUpperCaseJP(bool enabled); + void setLangKeyActive(bool enabled); + void resetHoldingButton(); + + private: + bool mbLineFeedButton; + GXTexObj mTextures[3]; + EventHandler* mpEventHandler; + predictlang::LayoutByNW4R* mpPredictLanguageDialog; + signwindow::LayoutByNW4R* mpSignWindow; +#elif defined(TIMANAGER_IMPLEMENTATION) virtual nw4rmanager::AnmPane* getAnmPane(InputMode mode); virtual void throwReleaseForAll(); virtual void changeAnimationAllToNormal(); @@ -192,6 +295,71 @@ namespace textinput { #endif }; +#ifdef TI_CELLPHONE_SAMPLE_CLASS + class Sample : public LayoutByNW4R { + public: + Sample(Manager* manager, nw4r::lyt::MultiArcResourceAccessor* resAccessor, EventObserver* observer) + : LayoutByNW4R(manager, resAccessor, observer) {} + virtual ~Sample() {} + }; +#endif + +#ifdef TI_CELLPHONE_IMPLEMENTATION + enum Animation { + ANM_Normal, + ANM_FocusIn, + ANM_FocusOut, + ANM_RollOver, + ANM_Pushed, + ANM_05, + ANM_06, + ANM_ToggleOff, + ANM_Last, + }; + + enum KeyType { + KT_NormalButton, + KT_ControlButton, + }; + + class CellPhoneAnmPane : public nw4rmanager::AnmPane { + public: + CellPhoneAnmPane(nw4r::lyt::Pane* pane, nw4rmanager::AnmObserver* observer) + : nw4rmanager::AnmPane(pane, observer), meState(ANM_Normal), meKeyType(KT_NormalButton) {} + + virtual void init() override; + virtual void onAnmEvent(AnmPaneEvent event) override; + virtual void changeAnimation(u32 id) override; + virtual KeyType getKeyType() const; + u32 getAnimationState() const { return meState; } + virtual ~CellPhoneAnmPane(); + + protected: + Animation meState; + KeyType meKeyType; + }; + + class CellPhoneControlAnmPane : public CellPhoneAnmPane { + public: + CellPhoneControlAnmPane(nw4r::lyt::Pane* pane, nw4rmanager::AnmObserver* observer) + : CellPhoneAnmPane(pane, observer) { meKeyType = KT_ControlButton; } + + virtual void onAnmEvent(AnmPaneEvent event) override; + virtual ~CellPhoneControlAnmPane(); + }; + + class EventHandler : public nw4rmanager::TiEventHandler { + public: + EventHandler(LayoutByNW4R* layout) : mpLayoutByNW4R(layout) {} + virtual ~EventHandler(); + virtual void onTiEvent(gui::PaneComponent* pane, u32 event, Input* input) override; + + private: + LayoutByNW4R* mpLayoutByNW4R; + }; + +#endif + } // namespace cellphonetype } // namespace keyboard } // namespace textinput diff --git a/include/keyboard/tiHKBManager.h b/include/keyboard/tiHKBManager.h index f2a43939..036384ad 100644 --- a/include/keyboard/tiHKBManager.h +++ b/include/keyboard/tiHKBManager.h @@ -187,8 +187,21 @@ namespace textinput { wchar_t szKeySetName[17]; // 0x04 u16 uNum; // 0x26 u16 uType; // 0x28 + +#ifdef TI_CELLPHONE_IMPLEMENTATION + public: + bool IsValid() const; + u32 GetKey() const; + wchar_t GetWChar() const; + KeySet GetNext() const; +#endif }; +#ifdef TI_CELLPHONE_IMPLEMENTATION + KeySet GetTriggeredKeySet() const; + KeySet GetRepeatedKeySet() const; +#endif + #endif private: u8 unk_0x00[0xFC]; diff --git a/include/keyboard/tiKeyboard.h b/include/keyboard/tiKeyboard.h index e641e7e4..ccac4963 100644 --- a/include/keyboard/tiKeyboard.h +++ b/include/keyboard/tiKeyboard.h @@ -26,13 +26,19 @@ namespace textinput { #else virtual void onKey(u32); #endif -#if (defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION)) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION) +#ifdef TI_CELLPHONE_IMPLEMENTATION + virtual u32 getType(); +#elif (defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION)) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION) virtual int getType(); #else virtual void getType(); #endif +#ifdef TI_CELLPHONE_IMPLEMENTATION + virtual void setLanguage(Language language) { meLanguage = language; } +#else virtual void setLanguage(Language language); - #if (defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION)) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION) +#endif +#if (defined(TI_PC_KEYBOARD_IMPLEMENTATION) || defined(TIHWKEYBOARD_IMPLEMENTATION)) || defined(TIMANAGER_IMPLEMENTATION) || defined(TISIGNWINDOW_IMPLEMENTATION) #ifdef TISIGNWINDOW_IMPLEMENTATION virtual Language getLanguage() const; #else diff --git a/include/keyboard/tiPcKeyboard.h b/include/keyboard/tiPcKeyboard.h index 916d79f3..b8a29271 100644 --- a/include/keyboard/tiPcKeyboard.h +++ b/include/keyboard/tiPcKeyboard.h @@ -65,7 +65,11 @@ namespace textinput { virtual void init() override; virtual void updateFromReceiver(u32, void*) override; virtual void onKey(u32, void*) override; +#ifdef TI_CELLPHONE_IMPLEMENTATION + virtual u32 getType() override; +#else virtual void getType() override; +#endif virtual void setLanguage(Language) override; virtual void onActive() override; virtual void inputCharCode(u16); diff --git a/include/keyboard/tiTextInputBase.h b/include/keyboard/tiTextInputBase.h index 3e21198d..15c7b52e 100644 --- a/include/keyboard/tiTextInputBase.h +++ b/include/keyboard/tiTextInputBase.h @@ -54,6 +54,9 @@ namespace textinput { class CommandSender; class CommandReceiver : public Base { public: +#ifdef TI_CELLPHONE_IMPLEMENTATION + struct ChangePredictMode; +#endif #if defined(TIINPUTFORM_IMPLEMENTATION) || defined(TIMANAGER_IMPLEMENTATION) CommandReceiver() { clearSender(); } virtual ~CommandReceiver(); diff --git a/include/keyboard/tiToolBar.h b/include/keyboard/tiToolBar.h index 142704a9..47a1ffe7 100644 --- a/include/keyboard/tiToolBar.h +++ b/include/keyboard/tiToolBar.h @@ -56,7 +56,11 @@ namespace textinput { virtual void onOK(); virtual void onCancel(); virtual void setQwertyWithSE(bool qwerty); +#ifdef TI_CELLPHONE_IMPLEMENTATION + virtual bool isEnableKeytopChange() const { return mbIsEnableQwertyChg; } +#else virtual bool isEnableKeytopChange() const; +#endif virtual void enableKeytopChange(bool enable); #ifdef MYTIMANAGER_MATCHING virtual nw4r::lyt::Pane* getDownArea(); diff --git a/src/keyboard/tiCellPhone.cpp b/src/keyboard/tiCellPhone.cpp new file mode 100644 index 00000000..4fb592d9 --- /dev/null +++ b/src/keyboard/tiCellPhone.cpp @@ -0,0 +1,1606 @@ +#define TI_CELLPHONE_IMPLEMENTATION +#define TI_CELLPHONE_SAMPLE_CLASS +#define MYTIMANAGER_IMPLEMENTATION +#include "keyboard/tiCellPhone.h" + +#include "keyboard/tiPredictLang.h" +#include "keyboard/tiManager.h" +#include "keyboard/tiCandidateBox.h" +#include "keyboard/tiCpData.h" +#include "keyboard/tiUtil.h" + +#include + +namespace textinput { + struct CommandReceiver::ChangePredictMode { + u32 predictMode; + bool enabled; + }; +} + +namespace textinput { + namespace keyboard { + namespace signwindow { + class SignWindowBase : public KeyboardBase { + public: + virtual bool isLocked(); + virtual void setPage(u8 page); + virtual u8 getPage(); + virtual void movePrevSignPage(); + virtual void moveNextSignPage(); + virtual void close(); + }; + + class LayoutByNW4R : public SignWindowBase, public nw4rmanager::Layout, public nw4rmanager::AnmObserver { + public: + virtual ~LayoutByNW4R(); + virtual void create(MEMAllocator* allocator); + virtual void init(); + virtual void draw(); + virtual void open(KeyboardBase* keyboard, bool enabled); + virtual bool isActive(); + virtual void onChangeAnmState(nw4rmanager::AnmObserver::AnmEvent event, + nw4rmanager::AnmPane* pane, nw4rmanager::Anim* animation); + virtual bool updateInput(int point, f32 x, f32 y, u32 trig, u32 hold, u32 release, void* data); + virtual bool updateInput(input::HKBManager& hkbManager); + }; + } + } +} + +namespace textinput { + namespace keyboard { + namespace cellphonetype { + + struct LanguageDependencyData { + u32 flags; + const KeySet* keySets[5]; + }; + + static const wchar_t* csszPredictLanguage[] = { + L"Eng", L"Eng", L"Fra", L"Esp", L"EN", L"DE", L"FR", + L"ES", L"IT", L"NL", L"CN", L"KR", L"" + }; + + struct PaneNameToControlKey { + char name[20]; + u32 controlKey; + }; + + struct AnimationFileForControlKey { + u32 animation; + char filename[64]; + }; + + static const char* csPaneNameNormalKey[] = { + "B_CPkey_00", "B_CPkey_01", "B_CPkey_02", "B_CPkey_03", + "B_CPkey_04", "B_CPkey_05", "B_CPkey_06", "B_CPkey_07", + "B_CPkey_08", "B_CPkey_09", "B_CPkey_10", "B_CPkey_11", + "B_CPkey_LF", "B_CPkey_DELETE", "B_othersBT_JP", "B_othersBT_EU", + "B_spaceBT_JP", "B_ChngTag_00", "B_ChngTag_01", "B_ChngTag_02", + "B_ChngTag_03", "B_SGNkey_close", "B_SGNkey_prev", "B_SGNkey_next", + "B_CPkey_Prdc_JP", "B_prdcModeBT_EU", + }; + + struct PaneNameToAnimationKey { + char name[20]; + const char* animationKey; + }; + + struct TogglePaneName { + char name[16]; + }; + + struct NumericModePaneNames { + char predictionEuropeanMode[16]; + char othersEuropean[16]; + char smallCandidateChange[16]; + char othersJapanese[16]; + char predictionJapanese[16]; + char spaceJapanese[16]; + char key09[12]; + char key11[12]; + }; + + static const char* csNormalAnimationKey = "W_CPkey_00"; + static const char* csToggleAnimationKey = "W_ChngTag_00"; + static const char* csEuropeanAnimationKey = "W_othersBT_EU"; + + static PaneNameToAnimationKey csPaneNameNormalAnimationKey[] = { + {"W_CPkey_00", NULL}, {"W_CPkey_01", NULL}, {"W_CPkey_02", NULL}, + {"W_CPkey_03", NULL}, {"W_CPkey_04", NULL}, {"W_CPkey_05", NULL}, + {"W_CPkey_06", NULL}, {"W_CPkey_07", NULL}, {"W_CPkey_08", NULL}, + {"W_CPkey_09", NULL}, {"W_CPkey_10", NULL}, {"W_CPkey_11", NULL}, + {"W_CPkey_LF", NULL}, {"W_CPkey_DELETE", NULL}, {"W_spaceBT_JP", NULL}, + {"W_othersBT_JP", NULL}, {"W_othersBT_EU", NULL}, + {"W_prdcModeBT_EU", NULL}, {"W_smlCptChngeBT", NULL}, + }; + + static PaneNameToAnimationKey csPaneNameToggleAnimationKey[] = { + {"W_ChngTag_00", NULL}, {"W_ChngTag_01", NULL}, + {"W_ChngTag_02", NULL}, {"W_ChngTag_03", NULL}, + }; + + struct TexturePaneNames { + char names[3][16]; + }; + + static TexturePaneNames csTexturePaneNames = { + {"P_spaceBT_JP", "P_spaceBT_CN", "P_spaceBT_KR"}, + }; + + struct AnimationKeyInitializer { + AnimationKeyInitializer() { + csPaneNameNormalAnimationKey[1].animationKey = csNormalAnimationKey; + csPaneNameNormalAnimationKey[2].animationKey = csNormalAnimationKey; + csPaneNameNormalAnimationKey[3].animationKey = csNormalAnimationKey; + csPaneNameNormalAnimationKey[4].animationKey = csNormalAnimationKey; + csPaneNameNormalAnimationKey[5].animationKey = csNormalAnimationKey; + csPaneNameNormalAnimationKey[6].animationKey = csNormalAnimationKey; + csPaneNameNormalAnimationKey[7].animationKey = csNormalAnimationKey; + csPaneNameNormalAnimationKey[8].animationKey = csNormalAnimationKey; + csPaneNameNormalAnimationKey[9].animationKey = csNormalAnimationKey; + csPaneNameNormalAnimationKey[10].animationKey = csNormalAnimationKey; + csPaneNameNormalAnimationKey[11].animationKey = csNormalAnimationKey; + csPaneNameNormalAnimationKey[12].animationKey = csNormalAnimationKey; + csPaneNameNormalAnimationKey[13].animationKey = csNormalAnimationKey; + csPaneNameNormalAnimationKey[14].animationKey = csNormalAnimationKey; + csPaneNameNormalAnimationKey[15].animationKey = csEuropeanAnimationKey; + csPaneNameToggleAnimationKey[1].animationKey = csToggleAnimationKey; + csPaneNameToggleAnimationKey[2].animationKey = csToggleAnimationKey; + csPaneNameToggleAnimationKey[3].animationKey = csToggleAnimationKey; + } + }; + + static AnimationKeyInitializer sAnimationKeyInitializer; + + static const PaneNameToControlKey csPaneNameToControlKey[] = { + {"B_CPkey_LF", 0}, + {"B_CPkey_DELETE", 1}, + {"B_othersBT_JP", 9}, + {"B_ChngTag_00", 0x12}, + {"B_ChngTag_01", 0x13}, + {"B_ChngTag_02", 0x0B}, + {"B_ChngTag_03", 0x0D}, + {"B_othersBT_EU", 9}, + {"B_CPkey_Prdc_JP", 0x0A}, + {"B_prdcModeBT_EU", 0x0A}, + {"B_smlCptChngeBT", 0x17}, + {"B_spaceBT_JP", 2}, + }; + + static const AnimationFileForControlKey csAninationFileForControlKey[] = { + {0, "fs_VK_cellPhone_a_normal.brlan"}, + {1, "fs_VK_cellPhone_a_Focus-IN.brlan"}, + {2, "fs_VK_cellPhone_a_Focus-OUT.brlan"}, + {4, "fs_VK_cellPhone_a_Pushed.brlan"}, + {3, "fs_VK_cellPhone_a_Roll_over.brlan"}, + {0, "fs_VK_cellPhone_a_normal.brlan"}, + {1, "fs_VK_cellPhone_a_Focus-IN.brlan"}, + {2, "fs_VK_cellPhone_a_Focus-OUT.brlan"}, + {4, "fs_VK_cellPhone_a_Pushed.brlan"}, + {5, "fs_VK_cellPhone_a_toggle-ON.brlan"}, + {6, "fs_VK_cellPhone_a_toggle-OFF.brlan"}, + }; + + static const LanguageDependencyData csLanguageDependencyData[] = { + {0x00040000, {&csKeySetHiragana, &csKeySetKatakana, &csKeySetABCJP, &csKeySetNumber, &csKeySetabcJP}}, + {0x00040000, {&csKeySetUSAbc, &csKeySetUSabc, &csKeySetUSABC, &csKeySetNumber, NULL}}, + {0x00040000, {&csKeySetUKAbc, &csKeySetUKabc, &csKeySetUKABC, &csKeySetNumber, NULL}}, + {0x00040000, {&csKeySetFRAbc, &csKeySetFRabc, &csKeySetFRABC, &csKeySetNumber, NULL}}, + {0x00040000, {&csKeySetDEAbc, &csKeySetDEabc, &csKeySetDEABC, &csKeySetNumber, NULL}}, + {0x00040000, {&csKeySetITAbc, &csKeySetITabc, &csKeySetITABC, &csKeySetNumber, NULL}}, + {0x00040000, {&csKeySetSPAbc, &csKeySetSPabc, &csKeySetSPABC, &csKeySetNumber, NULL}}, + {0x00040000, {&csKeySetNLAbc, &csKeySetNLabc, &csKeySetNLABC, &csKeySetNumber, NULL}}, + {0x00040000, {&csKeySetCNPinyin, &csKeySetCNabc, &csKeySetCNABC, &csKeySetNumber, NULL}}, + {0x00040000, {&csKeySetHangul, &csKeySetUSabc, &csKeySetUSABC, &csKeySetNumber, NULL}}, + }; + + void Base::create(MEMAllocator* allocator) { + mpAllocator = allocator; + mPreviousInputMode = 0; + mCurrentInputMode = 0; + mHoldingButton = 0; + mbInputModeLocked = false; + mbNumericWithDotMode = false; + mbNumericMode = false; + mbUpperCaseMode = true; + mbAbcMode = true; + mbLanguageKeyMode = false; + mpInputModeTable = const_cast(&csLanguageDependencyData[getLanguage()]); + + u32 inputData[3] = {0, 0, 0}; + sendCommand(3, inputData); + } + + void Base::init() { + mPreviousInputMode = 0; + mCurrentInputMode = 0; + mHoldingButton = 0; + mbInputModeLocked = false; + mbNumericWithDotMode = false; + mbNumericMode = false; + mbUpperCaseMode = true; + mbAbcMode = true; + mbLanguageKeyMode = false; + mpInputModeTable = const_cast(&csLanguageDependencyData[getLanguage()]); + + u32 inputData[3] = {0, 0, 0}; + sendCommand(3, inputData); + } + + void Base::calc() {} + + void Base::onKey(u32 event, void* data) { + struct KeyEvent { + const char* paneName; + u8 state; + }; + + struct KeyInputData { + u16 character; + u16 inputMode; + u32 state; + const PaneNameToCharCode* pane; + }; + + const KeyEvent& keyEvent = *static_cast(data); + + if (!mbInputModeLocked && event == gui::EventHandler::ON_TRIG) { + u32 controlKey; + u16 i; + for (i = 0; i < 12; ++i) { + if (util::strcmp(csPaneNameToControlKey[i].name, keyEvent.paneName)) { + controlKey = csPaneNameToControlKey[i].controlKey; + goto controlKeyFound; + } + } + controlKey = 0x1B; + + controlKeyFound: + if (controlKey != 0x1B) { + onCtrlKey_(static_cast(controlKey)); + } else { + bool useKeySetInput = isZiActive(); + if (!useKeySetInput) { + Language language = getLanguage(); + if (language == CN) { + useKeySetInput = true; + } else if (getLanguage() == KR && mHoldingButton != 0) { + useKeySetInput = true; + } else if (getInputType() == 1) { + useKeySetInput = true; + } + } + + if (useKeySetInput) { + LanguageDependencyData* inputModeTable = static_cast(mpInputModeTable); + const KeySet* keySet = inputModeTable->keySets[mCurrentInputMode]; + + if (mHoldingButton == 0) { + if (getLanguage() == JP && mCurrentInputMode == IM_02 && !mbUpperCaseMode) { + mCurrentInputMode = IM_04; + } else if (keySet->uType == KEY_TYPE_ABC_UPPER && !mbUpperCaseMode) { + mCurrentInputMode = IM_01; + } + + keySet = inputModeTable->keySets[mCurrentInputMode]; + for (u16 i = 0; i < 12; ++i) { + if (util::strcmp(keySet->pPaneNameToCharCode[i].szPaneName, keyEvent.paneName)) { + mHoldingButton = &keySet->pPaneNameToCharCode[i]; + break; + } + } + + const PaneNameToCharCode* pane = mHoldingButton; + if (keyEvent.state) { + mPreviousInputMode = 15; + while (pane && pane->wc[mPreviousInputMode] == 0) { + --mPreviousInputMode; + } + } else { + mPreviousInputMode = 0; + } + } else if (keyEvent.state) { + --mPreviousInputMode; + if (static_cast(mPreviousInputMode) < 0) { + mPreviousInputMode = 15; + const PaneNameToCharCode* pane = mHoldingButton; + while (pane->wc[mPreviousInputMode] == 0) { + --mPreviousInputMode; + } + } + } else { + ++mPreviousInputMode; + if (mPreviousInputMode == 16) { + mPreviousInputMode = 0; + } + } + + const PaneNameToCharCode* pane = mHoldingButton; + if (pane && pane->wc[mPreviousInputMode] == 0) { + mPreviousInputMode = 0; + } + + if (pane) { + KeyInputData commandData = {0, 0, 0, NULL}; + commandData.character = pane->wc[mPreviousInputMode]; + commandData.inputMode = mCurrentInputMode; + commandData.pane = pane; + + keySet = inputModeTable->keySets[mCurrentInputMode]; + if (getInputType() == 1 && pane->wc[1] != 0x30 && pane->wc[0] != 0x20) { + commandData.state = 1; + } + if (getLanguage() == KR && mCurrentInputMode != 0) { + commandData.state = 1; + } + if (getLanguage() == CN && mCurrentInputMode != 0) { + commandData.state = 1; + } + + if (keySet->uNum == 0) { + if (mbNumericWithDotMode && commandData.character == 0x2A) { + commandData.character = 0x2E; + } + sendCommand(5, &commandData); + mPreviousInputMode = 0; + mHoldingButton = 0; + } else { + if (!isZiActive() && commandData.character == 0x20 && + getInputMode() != IM_04 && getInputMode() != IM_02) { + commandData.character = 0x3000; + } + sendCommand(3, &commandData); + } + } + } else { + const KeySet& numberKeySet = csKeySetNumber; + for (u16 i = 0; i < 12; ++i) { + const PaneNameToCharCode& pane = numberKeySet.pPaneNameToCharCode[i]; + if (util::strcmp(pane.szPaneName, keyEvent.paneName)) { + KeyInputData commandData = {pane.wc[0], static_cast(mCurrentInputMode), 0, NULL}; + sendCommand(0x20, &commandData); + + if (getLanguage() == KR && pane.wc[0] == 0x30) { + break; + } + + if (mbNumericWithDotMode && commandData.character == 0x2A) { + commandData.character = 0x2E; + } else { + commandData.character = convertToZiCellphoneInput_(commandData.character); + } + sendCommand(5, &commandData); + break; + } + } + } + } + } + + if (event == gui::EventHandler::ON_LEFT && mHoldingButton != 0) { + const PaneNameToCharCode* pane = mHoldingButton; + if (util::strcmp(keyEvent.paneName, pane->szPaneName)) { + u16 character = pane->wc[mPreviousInputMode]; + if (character != 0x309B && character != 0x309C) { + KeyInputData commandData = {character, static_cast(mCurrentInputMode), 0, pane}; + sendCommand(5, &commandData); + } + mPreviousInputMode = 0; + mHoldingButton = 0; + } + } + } + + Base::~Base() {} + + Base::InputMode Base::getInputMode() const { + return static_cast(mCurrentInputMode); + } + + void Base::onCtrlKey_(VKeyCode keyCode) { + switch (keyCode) { + case VK_LINE_FEED: + sendCommand(7, NULL); + break; + case VK_DELETE: + sendCommand(1, NULL); + break; + case VK_INPUT_MODE_00: + sendCommand(6, NULL); + changeInputMode(IM_00); + break; + case VK_INPUT_MODE_01: + sendCommand(6, NULL); + changeInputMode(IM_01); + break; + case VK_INPUT_MODE_02: + sendCommand(6, NULL); + changeInputMode(IM_02); + break; + case VK_INPUT_MODE_03: + sendCommand(6, NULL); + changeInputMode(IM_03); + break; + case VK_SIGN_INPUT: + goSignInputMode(); + break; + case VK_PREDICT_LANGUAGE: + changePredictLanguage(); + break; + case VK_TOGGLE_ABC_MODE: + setAbcMode(!mbUpperCaseMode); + break; + default: + break; + } + } + + void Base::goSignInputMode() {} + + void Base::changePredictLanguage() {} + + void Base::updateFromReceiver(u32 command, void* data) { + if (getLanguage()) { + if (static_cast(command) == 0x21) { + setAbcMode(true); + } + if (static_cast(command) == 5 && !static_cast(data)[5]) { + setAbcMode(false); + mbAbcMode = false; + } + } + } + + bool Base::onClose() {} + + void Base::changeInputMode(InputMode mode) { + u8 activeData[4]; + u8 inactiveData[4]; + mCurrentInputMode = mode; + if (getLanguage()) { + mbUpperCaseMode = true; + mbAbcMode = true; + } + + if (mpManager->getCandidateBox()) { + mpManager->getCandidateBox()->checkValidation(); + } + + if (mode == IM_00) { + activeData[0] = 1; + sendCommand(0x13, activeData); + } + if (mode == IM_01) { + inactiveData[0] = 0; + sendCommand(0x13, inactiveData); + } + + updateFixMode(); + sendCommand(0x29, NULL); + } + + void Base::setInputMode(InputMode) {} + + void Base::setUpperCaseJP(bool) {} + + void Base::draw() {} + + void Base::doInput() {} + + bool Base::isUpperCase() { + return mbUpperCaseMode; + } + + bool Base::isHoldingButton() const { + return mHoldingButton != 0; + } + + bool Base::isNumericWithDot() const { + return mbNumericWithDotMode; + } + + bool Base::isNumeric() const { + return mbNumericMode; + } + + bool Base::isLocked() const { + return mbInputModeLocked; + } + + u32 Base::getType() { + return 1; + } + + bool Base::isZiActive() { + struct ActiveMode { + u32 mode; + bool active; + } input = {0, false}; + sendCommand(0x1F, &input); + s32 mode = static_cast(input.mode); + if (!input.active) { + return false; + } + return mode != 1; + } + + bool Base::isAtokActive() { + struct ActiveMode { + u32 mode; + bool active; + } input = {0, false}; + sendCommand(0x1F, &input); + s32 mode = static_cast(input.mode); + if (input.active) { + if (mode == 1) { + return true; + } + } + return false; + } + + void Base::setAbcMode(bool enabled) { + mbUpperCaseMode = enabled; + if (enabled) { + mbAbcMode = true; + } + } + + void Base::onActive() { + u32 commandData = 0; + u8 activeData[4]; + u8 inactiveData[4]; + sendCommand(0x12, &commandData); + + if (mCurrentInputMode == IM_00) { + activeData[0] = 1; + sendCommand(0x13, activeData); + } + + if (static_cast(mCurrentInputMode) == IM_01) { + inactiveData[0] = 0; + sendCommand(0x13, inactiveData); + } + + if (mCurrentInputMode == IM_00) { + sendCommand(6, NULL); + changeInputMode(static_cast(mCurrentInputMode)); + } + + updateFixMode(); + } + + void Base::doNumericMode(bool enabled) { + mbNumericMode = enabled; + if (enabled) { + input::HKBManager::getInstance().SetModifierState(0x100, 0x100); + getLanguage(); + changeInputMode(IM_03); + + if (mpManager->getToolBar()) { + mpManager->getToolBar()->setQwerty(false); + } + } + } + + void Base::updateFixMode() { + if ((mpManager->getToolBar() && mpManager->getToolBar()->isQwerty()) || getLanguage()) { + return; + } + + u8 fixMode = 0; + if (static_cast(mCurrentInputMode) == IM_04 || static_cast(mCurrentInputMode) == IM_02) { + fixMode = 1; + } else { + fixMode = 0; + } + sendCommand(0x14, &fixMode); + } + + wchar_t Base::convertToZiCellphoneInput_(wchar_t value) { + switch (value) { + case L'0': return 0xEFF1; + case L'1': return 0xEFF2; + case L'2': return 0xEFF3; + case L'3': return 0xEFF4; + case L'4': return 0xEFF5; + case L'5': return 0xEFF6; + case L'6': return 0xEFF7; + case L'7': return 0xEFF8; + case L'8': return 0xEFF9; + case L'9': return 0xEFFA; + default: return value; + } + } + + int Base::getInputType() const { + const LanguageDependencyData* inputModeTable = static_cast(mpInputModeTable); + const KeySet* keySet = inputModeTable->keySets[mCurrentInputMode]; + + if (getLanguage() == KR && keySet->uType == 5) { + return 3; + } + if (getLanguage() == CN && keySet->uType == 4) { + return 4; + } + if (keySet->uType == 3) { + return 1; + } + if (keySet->uType == 0) { + switch (getLanguage()) { + case JP: + return 2; + default: + return 0; + } + } + return 0; + } + + void Base::setLangKeyActive(bool enabled) { + mInputState = enabled; + if (getLanguage() == KR || getLanguage() == CN) { + if (enabled) { + setInputMode(IM_00); + } else if (getInputMode() == IM_00) { + setInputMode(IM_01); + } + } + } + + LayoutByNW4R::~LayoutByNW4R() { + mpEventHandler->~EventHandler(); + MEMFreeToAllocator(mpAllocator, mpEventHandler); + + nw4rmanager::AnmPane* pane = static_cast( + nw4r::ut::List_GetNext(&nw4rmanager::Layout::getAnmPaneList(), NULL)); + while (pane) { + nw4r::ut::List_Remove(&nw4rmanager::Layout::getAnmPaneList(), pane); + pane->destroy(mpAllocator); + pane = static_cast( + nw4r::ut::List_GetNext(&nw4rmanager::Layout::getAnmPaneList(), NULL)); + } + } + + EventHandler::~EventHandler() {} + + static TogglePaneName csPaneNameTogglePanes[] = { + {"W_ChngTag_00"}, {"W_ChngTag_01"}, + {"W_ChngTag_02"}, {"W_ChngTag_03"}, + }; + + static NumericModePaneNames csNumericModePaneNames = { + "W_prdcModeBT_EU", + "W_othersBT_EU", + "W_smlCptChngeBT", + "W_othersBT_JP", + "W_CPkey_Prdc_JP", + "W_spaceBT_JP", + "W_CPkey_09", + "W_CPkey_11", + }; + + void LayoutByNW4R::create(MEMAllocator* allocator) { + Base::create(allocator); + mpEventHandler = new (MEMAllocFromAllocator(allocator, sizeof(EventHandler))) EventHandler(this); + nw4rmanager::Layout::createWithEventHandler(allocator, mpEventHandler); + mpPaneManager->setAllComponentTriggerTarget(false); + mpPaneManager->setAllBoundingBoxComponentTriggerTarget(true); + + for (u16 i = 0; i < sizeof(csPaneNameNormalAnimationKey) / sizeof(csPaneNameNormalAnimationKey[0]); ++i) { + const PaneNameToAnimationKey& paneName = csPaneNameNormalAnimationKey[i]; + void* paneMemory = MEMAllocFromAllocator(allocator, sizeof(CellPhoneAnmPane)); + CellPhoneAnmPane* pane; + if (paneMemory) { + pane = new (paneMemory) CellPhoneAnmPane(getPane(paneName.name), NULL); + pane->init(); + pane->changeAnimation(pane->getAnimationState()); + } else { + pane = NULL; + } + nw4r::ut::List_Append(&mAnmPanes, pane); + + for (u16 j = 0; j < 5; ++j) { + const AnimationFileForControlKey& animation = csAninationFileForControlKey[j]; + void* resource = mpMultiArcResourceAccessor->GetResource(0, animation.filename); + AnimTransformPane* transform = static_cast( + getLayout()->CreateAnimTransform(resource, mpMultiArcResourceAccessor)); + if (paneName.animationKey) { + pane->forceAddAnimation(allocator, animation.animation, transform, + paneName.animationKey, false, true); + } else { + pane->addAnimation(allocator, animation.animation, transform, false, true); + } + } + } + + for (u16 i = 0; i < sizeof(csPaneNameToggleAnimationKey) / sizeof(csPaneNameToggleAnimationKey[0]); ++i) { + const PaneNameToAnimationKey& paneName = csPaneNameToggleAnimationKey[i]; + void* paneMemory = MEMAllocFromAllocator(allocator, sizeof(CellPhoneControlAnmPane)); + CellPhoneControlAnmPane* pane; + if (paneMemory) { + pane = new (paneMemory) CellPhoneControlAnmPane(getPane(paneName.name), NULL); + pane->init(); + pane->changeAnimation(pane->getAnimationState()); + } else { + pane = NULL; + } + nw4r::ut::List_Append(&mAnmPanes, pane); + + for (u16 j = 0; j < 6; ++j) { + const AnimationFileForControlKey& animation = csAninationFileForControlKey[j]; + void* resource = mpMultiArcResourceAccessor->GetResource(0, animation.filename); + AnimTransformPane* transform = static_cast( + getLayout()->CreateAnimTransform(resource, mpMultiArcResourceAccessor)); + if (paneName.animationKey) { + pane->forceAddAnimation(allocator, animation.animation, transform, + paneName.animationKey, false, true); + } else { + pane->addAnimation(allocator, animation.animation, transform, false, true); + } + } + } + + for (u32 i = 0; i < 3; ++i) { + nw4r::lyt::Material* material = mpLayout->GetRootPane()->FindPaneByName(csTexturePaneNames.names[i], true)->GetMaterial(); + material->GetTexture(&mTextures[i], 0); + } + + init(); + onActive(); + changeInputMode(static_cast(mCurrentInputMode)); + } + + void LayoutByNW4R::init() { + Base::init(); + + getAnmPane(IM_00)->changeAnimation(ANM_Normal); + getAnmPane(IM_01)->changeAnimation(ANM_Normal); + getAnmPane(IM_02)->changeAnimation(ANM_Normal); + getAnmPane(IM_03)->changeAnimation(ANM_Normal); + getAnmPane(static_cast(mCurrentInputMode))->changeAnimation(ANM_05); + + setLineFeedButton(true); + doNumericMode(false); + setPredictLanguageButton(true); + setSignWindowButton(true); + setVisible(csPaneNameTogglePanes[0].name, true); + setVisible(csPaneNameTogglePanes[1].name, true); + setVisible(csPaneNameTogglePanes[2].name, true); + setVisible(csPaneNameTogglePanes[3].name, true); + + for (int i = 0; i < 4; ++i) { + const char* paneName = csPaneNameToggleAnimationKey[i].name; + char textPaneName[17]; + memset(textPaneName, 0, sizeof(textPaneName)); + strncpy(textPaneName, paneName, strlen(paneName)); + textPaneName[0] = 'T'; + + nw4r::lyt::Pane* textPane = getPane(textPaneName); + nw4r::lyt::Pane* buttonPane = getPane(paneName); + const KeySet* keySet = static_cast(mpInputModeTable)->keySets[i]; + if (keySet == NULL) { + buttonPane->SetVisible(false); + } else { + buttonPane->SetVisible(true); + static_cast(textPane)->SetString(keySet->szKeySetName, 0); + } + } + + if (getLanguage() == JP) { + setVisible(csNumericModePaneNames.predictionEuropeanMode, false); + setVisible(csNumericModePaneNames.othersEuropean, false); + setVisible(csNumericModePaneNames.smallCandidateChange, true); + setVisible(csNumericModePaneNames.othersJapanese, true); + setVisible(csNumericModePaneNames.predictionJapanese, true); + setVisible(csNumericModePaneNames.spaceJapanese, true); + setVisible(csNumericModePaneNames.key09, true); + setVisible(csNumericModePaneNames.key11, true); + } else if (getLanguage() == CN) { + setVisible(csNumericModePaneNames.predictionEuropeanMode, true); + setVisible(csNumericModePaneNames.othersEuropean, true); + setVisible(csNumericModePaneNames.smallCandidateChange, false); + setVisible(csNumericModePaneNames.othersJapanese, false); + setVisible(csNumericModePaneNames.predictionJapanese, false); + setVisible(csNumericModePaneNames.spaceJapanese, true); + setVisible(csNumericModePaneNames.key09, true); + setVisible(csNumericModePaneNames.key11, false); + setLineFeedButton(false); + } else if (getLanguage() == KR) { + setVisible(csNumericModePaneNames.predictionEuropeanMode, true); + setVisible(csNumericModePaneNames.othersEuropean, true); + setVisible(csNumericModePaneNames.smallCandidateChange, false); + setVisible(csNumericModePaneNames.othersJapanese, false); + setVisible(csNumericModePaneNames.predictionJapanese, false); + setVisible(csNumericModePaneNames.spaceJapanese, true); + setVisible(csNumericModePaneNames.key09, false); + setVisible(csNumericModePaneNames.key11, false); + setLineFeedButton(false); + } else { + setVisible(csNumericModePaneNames.predictionEuropeanMode, true); + setVisible(csNumericModePaneNames.othersEuropean, true); + setVisible(csNumericModePaneNames.smallCandidateChange, false); + setVisible(csNumericModePaneNames.othersJapanese, false); + setVisible(csNumericModePaneNames.predictionJapanese, false); + setVisible(csNumericModePaneNames.spaceJapanese, false); + setVisible(csNumericModePaneNames.key09, false); + setVisible(csNumericModePaneNames.key11, false); + } + + changeInputMode(static_cast(mCurrentInputMode)); + setLangKeyActive(true); + + CommandReceiver::ChangePredictMode predictMode = {0, false}; + sendCommand(0x1F, &predictMode); + updatePredictLanguage(&predictMode); + + nw4rmanager::Layout::initPaneLastDrawReceived(); + mpLayout->Animate(0); + mpLayout->CalculateMtx(mDrawInfo); + + nw4r::lyt::Pane* spacePane = mpLayout->GetRootPane()->FindPaneByName(csTexturePaneNames.names[0], true); + nw4r::lyt::Pane* henkanPane = mpLayout->GetRootPane()->FindPaneByName("P_HENKAN_JP", true); + spacePane->SetVisible(true); + henkanPane->SetVisible(false); + } + + void LayoutByNW4R::setSignWindow(signwindow::LayoutByNW4R* signWindow) { + mpSignWindow = signWindow; + } + + void LayoutByNW4R::setPredictLanguageDialog(predictlang::LayoutByNW4R* dialog) { + mpPredictLanguageDialog = dialog; + } + + bool LayoutByNW4R::updateInput(int channel, f32 x, f32 y, u32 trig, u32 hold, u32 release, void* data) { + return nw4rmanager::Layout::updateInput(channel, x, y, trig, hold, release, data); + } + + void LayoutByNW4R::update() {} + + void LayoutByNW4R::onKey(u32 event, void* data) { + Base::onKey(event, data); + + if (!mbInputModeLocked) { + s32 controlKey; + bool isTrigger = event == gui::EventHandler::ON_TRIG; + u16 i; + const char* paneName = *static_cast(data); + if (isTrigger) { + i = 0; + while (i < 12) { + if (util::strcmp(csPaneNameToControlKey[i].name, paneName)) { + controlKey = csPaneNameToControlKey[i].controlKey; + goto controlKeyFound; + } + ++i; + } + controlKey = 0x1B; + + controlKeyFound: + if (controlKey != 0x1B) { + switch (controlKey) { + case 9: + case 11: + case 13: + case 18: + case 19: + mpEventObserver->onSE(static_cast(0x0D)); + break; + case 23: + if (!mbUpperCaseMode) { + mpEventObserver->onSE(static_cast(0x15)); + } else { + mpEventObserver->onSE(static_cast(0x14)); + } + break; + case 2: + if (mpManager->getInputForm()->canConvert()) { + sendCommand(0x28, NULL); + } else { + u32 commandData[4] = {0x00200000, 0, 0x00010000, 0}; + sendCommand(0, commandData); + } + break; + default: + break; + } + } + } + } + } + + void LayoutByNW4R::onActive() { + u32 commandData = 0; + u8 inactiveData[4]; + u8 activeData[4]; + sendCommand(0x12, &commandData); + + if (static_cast(mCurrentInputMode) == IM_00) { + activeData[0] = 1; + sendCommand(0x13, activeData); + } + if (static_cast(mCurrentInputMode) == IM_01) { + inactiveData[0] = 0; + sendCommand(0x13, inactiveData); + } + + if (static_cast(mCurrentInputMode) == IM_00) { + sendCommand(6, NULL); + changeInputMode(static_cast(mCurrentInputMode)); + } + + updateFixMode(); + nw4rmanager::Layout::init(); + } + + void LayoutByNW4R::draw() { + nw4rmanager::Layout::draw(); + } + + void LayoutByNW4R::calc() { + nw4rmanager::Layout::calc(); + + nw4r::lyt::Pane* spacePane = mpLayout->GetRootPane()->FindPaneByName(csTexturePaneNames.names[0]); + nw4r::lyt::Pane* henkanPane = mpLayout->GetRootPane()->FindPaneByName("P_HENKAN_JP"); + bool canConvert = mpManager->getInputForm()->canConvert(); + if (canConvert) { + spacePane->SetVisible(false); + henkanPane->SetVisible(true); + } else { + spacePane->SetVisible(true); + henkanPane->SetVisible(false); + } + } + + void LayoutByNW4R::doNumericMode(bool enabled) { + mbNumericMode = enabled; + if (enabled) { + input::HKBManager::getInstance().SetModifierState(0x100, 0x100); + getLanguage(); + changeInputMode(IM_03); + + if (mpManager->getToolBar()) { + mpManager->getToolBar()->setQwerty(false); + } + } + + if (enabled) { + setVisible(csNumericModePaneNames.smallCandidateChange, !enabled); + setVisible(csNumericModePaneNames.key09, !enabled); + setVisible("P_CPkey_dakuten", !enabled); + setVisible(csNumericModePaneNames.predictionEuropeanMode, !enabled); + setVisible(csNumericModePaneNames.othersEuropean, !enabled); + setVisible(csNumericModePaneNames.spaceJapanese, !enabled); + setVisible(csNumericModePaneNames.smallCandidateChange, !enabled); + setVisible(csNumericModePaneNames.othersJapanese, !enabled); + setVisible(csNumericModePaneNames.predictionJapanese, !enabled); + setVisible(csNumericModePaneNames.key09, !enabled); + setVisible(csNumericModePaneNames.key11, !enabled); + setVisible(csPaneNameTogglePanes[0].name, !enabled); + setVisible(csPaneNameTogglePanes[1].name, !enabled); + setVisible(csPaneNameTogglePanes[2].name, !enabled); + setVisible(csPaneNameTogglePanes[3].name, !enabled); + } + } + + void LayoutByNW4R::updatePredictLanguage(CommandReceiver::ChangePredictMode* mode) { + if (!getLanguage()) { + return; + } + + if (!mode->enabled) { + setVisible("N_prdc_EU_ON", false); + setVisible("N_prdc_EU_OFF", true); + mbLanguageKeyMode = false; + } else { + setVisible("N_prdc_EU_ON", true); + setVisible("N_prdc_EU_OFF", false); + mbLanguageKeyMode = true; + } + + nw4r::lyt::TextBox* textBox = static_cast(getPane("N_prdc_EU_lang")); + textBox->SetString(csszPredictLanguage[mode->predictMode], 0); + + const LanguageDependencyData* inputModeTable = static_cast(mpInputModeTable); + const KeySet* keySet = inputModeTable->keySets[mCurrentInputMode]; + changeSpaceKeyTop(keySet->pPaneNameToCharCode); + } + + void LayoutByNW4R::doNumericWithDotMode(bool enabled) { + doNumericMode(enabled); + setString("T_CPkey_11", L"."); + setVisible(csNumericModePaneNames.key11, enabled); + mbNumericWithDotMode = true; + } + + void LayoutByNW4R::setLineFeedButton(bool enabled) { + mbLineFeedButton = enabled; + setVisible("W_CPkey_LF", mbLineFeedButton); + } + + bool LayoutByNW4R::updateInput(input::HKBManager& hkbManager) { + if (mpManager->getToolBar()->isEnableKeytopChange()) { + const input::HKBManager::KeySet& keySet = hkbManager.GetTriggeredKeySet(); + if (keySet.IsValid()) { + if (mHoldingButton) { + u32 keyData[2] = {reinterpret_cast(mHoldingButton), 0}; + onKey(1, keyData); + } + + changeAnimationAllToNormal(); + mpManager->getToolBar()->setQwertyWithSE(true); + if (mpManager->getPCKeyboard()->isABC()) { + return false; + } + mpManager->getPCKeyboard()->setABC(true); + return false; + } + return false; + } + + { + input::HKBManager::KeySet triggeredKey(hkbManager.GetTriggeredKeySet()); + while (triggeredKey.IsValid()) { + u32 key = triggeredKey.GetKey(); + nw4rmanager::AnmPane* pane = NULL; + if (key == 0x58 || key == 0x28) { + if (!(hkbManager.GetModifierState() & 4)) { + pane = searchAnmPane("W_CPkey_LF"); + } + } else { + pane = searchAnmPane(triggeredKey.GetWChar()); + } + if (pane) { + pane->onAnmEvent(nw4rmanager::AnmPane::PE_0); + } + triggeredKey = triggeredKey.GetNext(); + } + } + + { + input::HKBManager::KeySet repeatedKey(hkbManager.GetRepeatedKeySet()); + while (repeatedKey.IsValid()) { + u32 key = repeatedKey.GetKey(); + nw4rmanager::AnmPane* pane = NULL; + if (key == 0x4C || (key == 0x2A && !(hkbManager.GetModifierState() & 4))) { + pane = searchAnmPane("W_CPkey_DELETE"); + } + if (pane) { + pane->onAnmEvent(nw4rmanager::AnmPane::PE_0); + } + repeatedKey = repeatedKey.GetNext(); + } + } + return false; + } + + void LayoutByNW4R::setPredictLanguageButton(bool enabled) { + setVisible(csNumericModePaneNames.predictionEuropeanMode, enabled); + } + + void LayoutByNW4R::setSignWindowButton(bool enabled) { + if (!enabled) { + setVisible(csNumericModePaneNames.othersEuropean, enabled); + setVisible(csNumericModePaneNames.othersJapanese, enabled); + } else { + setVisible(csNumericModePaneNames.othersEuropean, false); + setVisible(csNumericModePaneNames.othersJapanese, false); + if (getLanguage() == JP) { + setVisible(csNumericModePaneNames.othersJapanese, true); + } else { + setVisible(csNumericModePaneNames.othersEuropean, true); + } + } + } + + void LayoutByNW4R::setLangKeyActive(bool enabled) { + Base::setLangKeyActive(enabled); + if (getLanguage() == KR || getLanguage() == CN) { + setVisible(csPaneNameTogglePanes[0].name, enabled); + setVisible("T_ChngTag_00", enabled); + } + } + + void LayoutByNW4R::setInputMode(InputMode mode) { + const LanguageDependencyData* inputModeTable = static_cast(mpInputModeTable); + if (!inputModeTable->keySets[mCurrentInputMode]) { + mode = IM_03; + } + + changeInputMode(mode); + getAnmPane(IM_00)->changeAnimation(ANM_Normal); + getAnmPane(IM_01)->changeAnimation(ANM_Normal); + getAnmPane(IM_02)->changeAnimation(ANM_Normal); + getAnmPane(IM_03)->changeAnimation(ANM_Normal); + getAnmPane(static_cast(mCurrentInputMode))->changeAnimation(ANM_05); + mpLayout->Animate(); + mpLayout->CalculateMtx(mDrawInfo); + } + + void LayoutByNW4R::setUpperCaseJP(bool enabled) { + if (getLanguage() == JP) { + mbUpperCaseMode = enabled; + } + } + + void LayoutByNW4R::resetHoldingButton() { + mHoldingButton = 0; + mPreviousInputMode = 0; + } + + void LayoutByNW4R::setCommandReceiver(CommandReceiver* receiver) { + KeyboardBase::setCommandReceiver(receiver); + init(); + } + + bool LayoutByNW4R::onClose() { + initPaneLastDrawReceived(); + changeAnimationAllToNormal(); + } + + void LayoutByNW4R::updateFromReceiver(u32 command, void* data) { + if (getLanguage()) { + if (static_cast(command) == 0x21) { + setAbcMode(true); + } + if (static_cast(command) == 5 && !static_cast(data)[5]) { + setAbcMode(false); + mbAbcMode = false; + } + } + switch (static_cast(command)) { + case 0x1D: + updatePredictLanguage(static_cast(data)); + break; + default: + break; + } + } + + CellPhoneAnmPane* LayoutByNW4R::getAnmPane(InputMode mode) { + switch (mode) { + case IM_02: + return static_cast(searchAnmPane(csPaneNameToggleAnimationKey[2].name)); + case IM_03: + return static_cast(searchAnmPane(csPaneNameToggleAnimationKey[3].name)); + case IM_00: + return static_cast(searchAnmPane(csPaneNameToggleAnimationKey[0].name)); + case IM_01: + return static_cast(searchAnmPane(csPaneNameToggleAnimationKey[1].name)); + default: + return NULL; + } + } + + void LayoutByNW4R::changeInputMode(InputMode mode) { + u8 activeData[4]; + u8 inactiveData[4]; + mCurrentInputMode = mode; + if (getLanguage()) { + mbUpperCaseMode = true; + mbAbcMode = true; + } + + if (mpManager->getCandidateBox()) { + mpManager->getCandidateBox()->checkValidation(); + } + + if (mode == IM_00) { + activeData[0] = 1; + sendCommand(0x13, activeData); + } + if (mode == IM_01) { + inactiveData[0] = 0; + sendCommand(0x13, inactiveData); + } + + updateFixMode(); + sendCommand(0x29, NULL); + + u32 keySetIndex = mode; + if (getLanguage() == JP) { + if (static_cast(keySetIndex) == IM_02 && !mbUpperCaseMode) { + keySetIndex = IM_04; + } + + switch (keySetIndex) { + case IM_00: + setVisible(csNumericModePaneNames.smallCandidateChange, false); + setVisible(csNumericModePaneNames.key09, true); + setVisible(csNumericModePaneNames.spaceJapanese, true); + setVisible(csNumericModePaneNames.smallCandidateChange, false); + break; + case IM_02: + case IM_04: + setVisible(csNumericModePaneNames.smallCandidateChange, true); + setVisible(csNumericModePaneNames.key09, false); + setVisible(csNumericModePaneNames.spaceJapanese, false); + setVisible(csNumericModePaneNames.smallCandidateChange, true); + break; + case IM_03: + setVisible(csNumericModePaneNames.smallCandidateChange, false); + setVisible(csNumericModePaneNames.key09, true); + setVisible(csNumericModePaneNames.spaceJapanese, false); + setVisible(csNumericModePaneNames.smallCandidateChange, false); + break; + default: + break; + } + } else { + setVisible(csNumericModePaneNames.spaceJapanese, false); + } + + changeKeyTop(static_cast(mpInputModeTable) + ->keySets[keySetIndex]->pPaneNameToCharCode); + nw4rmanager::Layout::initPaneLastDrawReceived(); + } + + void LayoutByNW4R::changeKeyTop(const PaneNameToCharCode* keys) { + for (u16 i = 0; i < 12; ++i) { + char textPaneName[17]; + util::replaceChar(textPaneName, sizeof(textPaneName), keys[i].szPaneName, 0, 'T'); + nw4r::lyt::TextBox* textBox = nw4r::ut::DynamicCast( + mpLayout->GetRootPane()->FindPaneByName(textPaneName, true)); + if (textBox) { + textBox->SetString(keys[i].szPaneDisp, 0); + } + } + changeSpaceKeyTop(keys); + } + + void LayoutByNW4R::changeSpaceKeyTop(const PaneNameToCharCode* keys) { + if (getLanguage() != JP) { + char textPaneName[17]; + util::replaceChar(textPaneName, sizeof(textPaneName), keys[10].szPaneName, 0, 'T'); + nw4r::lyt::Pane* pane = mpLayout->GetRootPane()->FindPaneByName(textPaneName, true); + if (keys[10].wc[0] == 0xE057) { + nw4r::lyt::TextBox* textBox = static_cast(pane); + if (!mbLanguageKeyMode) { + textBox->SetString(csSpaceZero, 0); + } else { + textBox->SetString(csSpace, 0); + } + } + } + } + + void LayoutByNW4R::throwReleaseForAll() { + CellPhoneAnmPane* pane = static_cast(nw4r::ut::List_GetNext(&nw4rmanager::Layout::getAnmPaneList(), NULL)); + while (pane) { + if (pane->getKeyType() == KT_NormalButton) { + pane->onAnmEvent(nw4rmanager::AnmPane::PE_2); + } + pane = static_cast(nw4r::ut::List_GetNext(&nw4rmanager::Layout::getAnmPaneList(), pane)); + } + } + + void LayoutByNW4R::changeAnimationAllToNormal() { + CellPhoneAnmPane* pane = static_cast(nw4r::ut::List_GetNext(&nw4rmanager::Layout::getAnmPaneList(), NULL)); + while (pane) { + if (pane->getKeyType() == KT_NormalButton) { + pane->changeAnimation(ANM_Normal); + } + pane = static_cast(nw4r::ut::List_GetNext(&nw4rmanager::Layout::getAnmPaneList(), pane)); + } + } + + void LayoutByNW4R::setLanguage(Language language) { + KeyboardBase::setLanguage(language); + nw4r::lyt::Pane* rootPane = mpLayout->GetRootPane(); + if (language == JP) { + rootPane->FindPaneByName(csTexturePaneNames.names[0], true)->GetMaterial()->SetTexture(0, mTextures[0]); + } else if (language == CN) { + rootPane->FindPaneByName(csTexturePaneNames.names[0], true)->GetMaterial()->SetTexture(0, mTextures[1]); + } else if (language == KR) { + rootPane->FindPaneByName(csTexturePaneNames.names[0], true)->GetMaterial()->SetTexture(0, mTextures[2]); + } + + if (mpLayout) { + init(); + initPaneLastDrawReceived(); + } + } + + void LayoutByNW4R::changePredictLanguage() { + throwReleaseForAll(); + u32 commandData[2] = {0, 0}; + sendCommand(0x1F, commandData); + mpPredictLanguageDialog->open( + static_cast(commandData[0]), this); + } + + void LayoutByNW4R::setAbcMode(bool enabled) { + mbUpperCaseMode = enabled; + if (enabled) { + mbAbcMode = true; + } + + if (getLanguage() == JP) { + u32 keySetIndex = 2; + if (!mbUpperCaseMode) { + keySetIndex = 4; + } + const KeySet* const* keySets = static_cast(mpInputModeTable)->keySets; + const KeySet* keySet = keySets[keySetIndex]; + changeKeyTop(keySet->pPaneNameToCharCode); + mpEventObserver->onSE(static_cast(0x12)); + } else { + const KeySet* const* keySets = static_cast(mpInputModeTable)->keySets; + const KeySet* keySet = keySets[mCurrentInputMode]; + if (keySet->uType == 1) { + u32 keySetIndex = 0; + if (!mbUpperCaseMode) { + keySetIndex = 1; + } + const KeySet* alphabetKeySet = keySets[keySetIndex]; + changeKeyTop(alphabetKeySet->pPaneNameToCharCode); + } + } + } + + void LayoutByNW4R::goSignInputMode() { + bool isNumericMode = false; + if (static_cast(mCurrentInputMode) == IM_03) { + isNumericMode = true; + } + mpSignWindow->open(static_cast(this), isNumericMode); + throwReleaseForAll(); + } + + void EventHandler::onTiEvent(gui::PaneComponent* paneComponent, u32 event, Input* input) { + const char* paneName = paneComponent->getPane()->GetName(); + if (paneName[0] == 'B') { + char animationName[17]; + util::replaceChar(animationName, sizeof(animationName), paneName, 0, 'W'); + CellPhoneAnmPane* animation = static_cast(mpLayoutByNW4R->searchAnmPane(animationName)); + if (animation != NULL) { + switch (event) { + case gui::EventHandler::ON_TRIG: { + bool pressed = (input->field_0x0C & 0x1000) != 0; + bool normalKey = false; + if (!pressed && (input->field_0x0C & 0x800)) { + for (u32 i = 0; i < 12; ++i) { + if (util::strcmp(paneName, csPaneNameNormalKey[i])) { + normalKey = true; + break; + } + } + pressed = normalKey; + } + + if (pressed) { + if (animation->getKeyType() == KT_ControlButton) { + nw4r::ut::List& panes = mpLayoutByNW4R->getAnmPaneList(); + CellPhoneAnmPane* other = static_cast(nw4r::ut::List_GetNext(&panes, NULL)); + while (other) { + if (other != animation && other->getKeyType() == KT_ControlButton) { + other->changeAnimation(ANM_05); + } + other = static_cast(nw4r::ut::List_GetNext(&panes, other)); + } + animation->changeAnimation(ANM_Normal); + } + animation->onAnmEvent(nw4rmanager::AnmPane::PE_0); + } + break; + } + case gui::EventHandler::ON_LEFT: + animation->onAnmEvent(nw4rmanager::AnmPane::PE_2); + break; + case gui::EventHandler::ON_POINT: + mpEventObserver->onSE(static_cast(4)); + mpLayoutByNW4R->setPaneLastDrawReceived(animation->getPane()); + animation->onAnmEvent(nw4rmanager::AnmPane::PE_1); + break; + default: + break; + } + } + } + + struct KeyEvent { + const char* paneName; + u8 state; + u8 repeat; + } keyEvent = {paneName, 0, 0}; + + if (event == gui::EventHandler::ON_TRIG) { + if (input->field_0x0C & 0x1000) { + mpLayoutByNW4R->onKey(event, &keyEvent); + } else if (input->field_0x0C & 0x800) { + for (u32 i = 0; i < 12; ++i) { + if (util::strcmp(paneName, csPaneNameNormalKey[i])) { + keyEvent.state = 1; + mpLayoutByNW4R->onKey(event, &keyEvent); + paneComponent->setFlightDuration(input->field_0x00, 0); + break; + } + } + } + } else if (event == gui::EventHandler::ON_LEFT) { + mpLayoutByNW4R->onKey(event, &keyEvent); + } + + if (event == gui::EventHandler::ON_MOVE && (input->field_0x10 & 0x1000) && + !(input->field_0x0C & 0x1000) && + (util::strcmp(paneName, csPaneNameNormalKey[13]) || + util::strcmp(paneName, csPaneNameNormalKey[16]))) { + if (paneComponent->isDragging(input->field_0x00)) { + u32 duration = mpLayoutByNW4R->getFlightDuration(input->field_0x00, paneName); + if (duration >= 30 && duration % 9 == 0) { + char animationName[17]; + util::replaceChar(animationName, sizeof(animationName), paneName, 0, 'W'); + CellPhoneAnmPane* animation = static_cast(mpLayoutByNW4R->searchAnmPane(animationName)); + if (animation) { + animation->changeAnimation(ANM_Normal); + } + keyEvent.state = 1; + mpLayoutByNW4R->onKey(gui::EventHandler::ON_TRIG, &keyEvent); + } + } + if (mpLayoutByNW4R->getFlightDuration(input->field_0x00, paneName) == 90) { + keyEvent.repeat = 1; + mpLayoutByNW4R->onKey(gui::EventHandler::ON_LEFT, &keyEvent); + } + } + } + + void CellPhoneAnmPane::init() { + meState = ANM_Normal; + } + + KeyType CellPhoneAnmPane::getKeyType() const { + return meKeyType; + } + + void CellPhoneAnmPane::changeAnimation(u32 id) { + meState = static_cast(id); + nw4rmanager::AnmPane::changeAnimation(id == ANM_ToggleOff ? ANM_FocusOut : id); + } + + void CellPhoneAnmPane::onAnmEvent(AnmPaneEvent event) { + switch (meState) { + case ANM_Normal: + if (event == PE_1) { + changeAnimation(ANM_FocusIn); + } + if (event == PE_0) { + changeAnimation(ANM_ToggleOff); + } + break; + case ANM_FocusIn: + if (event == PE_4) { + changeAnimation(ANM_RollOver); + } + if (event == PE_2) { + changeAnimation(ANM_FocusOut); + } + if (event == PE_0) { + changeAnimation(ANM_Pushed); + } + break; + case ANM_FocusOut: + if (event == PE_2) { + changeAnimation(ANM_FocusOut); + } + if (event == PE_0) { + changeAnimation(ANM_Pushed); + } + break; + case ANM_RollOver: + if (event == PE_4) { + changeAnimation(ANM_Normal); + } + if (event == PE_1) { + changeAnimation(ANM_FocusIn); + } + if (event == PE_0) { + changeAnimation(ANM_ToggleOff); + } + break; + case ANM_Pushed: + if (event == PE_4) { + changeAnimation(ANM_RollOver); + } + if (event == PE_2) { + changeAnimation(ANM_FocusOut); + } + if (event == PE_0) { + changeAnimation(ANM_Pushed); + } + break; + case ANM_05: + case ANM_06: + break; + case ANM_ToggleOff: + if (event == PE_4) { + changeAnimation(ANM_Normal); + } + if (event == PE_1) { + changeAnimation(ANM_FocusIn); + } + if (event == PE_0) { + changeAnimation(ANM_ToggleOff); + } + break; + default: + break; + } + } + + void CellPhoneControlAnmPane::onAnmEvent(AnmPaneEvent event) { + if (event == PE_5) { + if (meState == ANM_06) { + } else if (meState == ANM_05) { + changeAnimation(ANM_06); + return; + } else if (meState != ANM_Normal && meState != ANM_FocusOut) { + changeAnimation(ANM_FocusOut); + return; + } + } + + if (event == PE_0) { + changeAnimation(ANM_Pushed); + return; + } + + switch (meState) { + case ANM_Normal: + if (event == PE_1) { + changeAnimation(ANM_FocusIn); + } + break; + case ANM_FocusIn: + if (event == PE_4) { + changeAnimation(ANM_RollOver); + } + if (event == PE_2) { + changeAnimation(ANM_FocusOut); + } + if (event == PE_0) { + changeAnimation(ANM_Pushed); + } + break; + case ANM_RollOver: + if (event == PE_2) { + changeAnimation(ANM_FocusOut); + } + if (event == PE_0) { + changeAnimation(ANM_Pushed); + } + break; + case ANM_FocusOut: + if (event == PE_4) { + changeAnimation(ANM_Normal); + } + break; + case ANM_06: + if (event == PE_4) { + changeAnimation(ANM_Normal); + } + if (event == PE_1) { + changeAnimation(ANM_FocusIn); + } + break; + case ANM_Pushed: + if (event == PE_4) { + changeAnimation(ANM_05); + } + break; + case ANM_05: + default: + break; + } + } + + CellPhoneAnmPane::~CellPhoneAnmPane() {} + + CellPhoneControlAnmPane::~CellPhoneControlAnmPane() {} + + } + } +} -- 2.49.1 From 3cbf4bb3e928de5ac7baf61eefc00082adeadfcc Mon Sep 17 00:00:00 2001 From: coah <100182500+coah80@users.noreply.github.com> Date: Wed, 30 Sep 2026 00:38:19 -0500 Subject: [PATCH 4/5] fa: pf_volume 33/37, pf_dir 29/38, pf_fat 29/35, pf_file 43/45 (worker 4c6c5008) (#336) --- README.md | 4 +- libs/RVL_SDK/src/fa/pf_dir.c | 463 ++++---- libs/RVL_SDK/src/fa/pf_fat.c | 112 +- libs/RVL_SDK/src/fa/pf_file.c | 492 +++----- libs/RVL_SDK/src/fa/pf_volume.c | 1302 ++++++--------------- tools/decomp-assist/attempts/fa-dir.md | 16 + tools/decomp-assist/attempts/fa-fat.md | 13 + tools/decomp-assist/attempts/fa-file.md | 36 + tools/decomp-assist/attempts/fa-volume.md | 11 + 9 files changed, 909 insertions(+), 1540 deletions(-) create mode 100644 tools/decomp-assist/attempts/fa-dir.md create mode 100644 tools/decomp-assist/attempts/fa-fat.md create mode 100644 tools/decomp-assist/attempts/fa-file.md create mode 100644 tools/decomp-assist/attempts/fa-volume.md diff --git a/README.md b/README.md index 7fca1c39..99fd18b5 100644 --- a/README.md +++ b/README.md @@ -53,9 +53,9 @@ Progress | Decompiled | Matched | Linked | Data | |:---:|:---:|:---:|:---:| -| 88.75% | 78.13% | 56.92% | 88.24% | +| 88.96% | 79.07% | 56.92% | 88.24% | -units 752/1027 complete, functions 11441/12563 matched. +units 752/1027 complete, functions 11492/12563 matched. decompiled = code with a C/C++ implementation (objdiff fuzzy), matched = byte-exact code, linked = code actually linked into the DOL, data = byte-exact data diff --git a/libs/RVL_SDK/src/fa/pf_dir.c b/libs/RVL_SDK/src/fa/pf_dir.c index 36003880..6f1017a7 100644 --- a/libs/RVL_SDK/src/fa/pf_dir.c +++ b/libs/RVL_SDK/src/fa/pf_dir.c @@ -102,6 +102,8 @@ typedef struct PFDIR_VOLUME_DIRS { typedef struct PFDIR_GLOBAL_STATE { pf_u8 state_prefix[0x40]; pf_s32 last_error; + pf_u8 driver_and_code_state[0x1C]; + pf_u32 setting; } PFDIR_GLOBAL_STATE; extern PFDIR_GLOBAL_STATE pf_vol_set; @@ -134,6 +136,26 @@ 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); +static inline pf_u32 directory_is_open(PF_DIR_ENT* entry) { + PFDIR_VOLUME_DIRS* volume = (PFDIR_VOLUME_DIRS*)entry->p_vol; + pf_s32 index; + PFDIR_SDD* sdd = volume->sdds; + for (index = 0; index < 3; index++, sdd++) { + 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 1; } + } + return 0; +} + +extern void PFFAT_ResetFFD(PFDIR_FFD*, pf_u32*); +static inline pf_s32 release_directory_chain(PFDIR_FFD* ffd, pf_u32 cluster, pf_u32 count) { + pf_s32 error = PFFAT_FreeChain(ffd, cluster, -1U, count); + if (error != 0) { return error; } + return 0; +} + pf_s32 PFDIR_CheckDirIsEmpty(PF_ENT_ITER* iter, pf_u32* is_empty) { pf_u32 start_cluster = *iter->ffd.p_start_cluster; pf_s32 error; @@ -177,8 +199,8 @@ PFDIR_SDD* PFDIR_GetSDD(PF_VOLUME* volume, PF_DIR_ENT* entry) { pf_s32 i; pf_s32 remaining = 3; - for (i = 0; remaining != 0; i++, free_candidate++, remaining--) { - if ((volume_dirs->sdds[i].stat & 1) == 0 || (volume_dirs->sdds[i].stat & 2) == 0) { + for (i = 0; remaining != 0; remaining--) { + if ((volume_dirs->sdds[i].stat & 1) == 0 || ((volume_dirs->sdds[i].stat & 1) != 0 && (!volume_dirs->sdds[i].stat & 2) != 0)) { if (first_free_sdd == 0) { first_free_sdd = free_candidate; } @@ -187,6 +209,8 @@ PFDIR_SDD* PFDIR_GetSDD(PF_VOLUME* volume, PF_DIR_ENT* entry) { entry->entry_offset == volume_dirs->sdds[i].dir_entry.entry_offset) { return &volume_dirs->sdds[i]; } + free_candidate++; + i++; } if (first_free_sdd == 0) { return 0; @@ -198,12 +222,21 @@ PFDIR_SDD* PFDIR_GetSDD(PF_VOLUME* volume, PF_DIR_ENT* entry) { return first_free_sdd; } +static inline PFDIR_DIR* unused_directory(PF_VOLUME* volume) { + pf_s32 index; + for (index = 0; index < 3; index++) { + if ((((PFDIR_VOLUME_DIRS*)volume)->udds[index].stat & 1) == 0) { + return &((PFDIR_VOLUME_DIRS*)volume)->udds[index]; + } + } + return 0; +} + 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; + pf_s32 i; PFDIR_SDD* sdd; PFDIR_DIR* dir; - PFDIR_DIR* scan_dir; - pf_s32 i; *opened_dir = 0; if ((entry->attr & 0x10) == 0) { @@ -213,15 +246,7 @@ pf_s32 PFDIR_DoFsexecOpenDir(PF_DIR_ENT* entry, PF_ENT_ITER* iter, PFDIR_DIR** o if (sdd == 0) { return 0x15; } - scan_dir = volume_dirs->udds; - for (i = 0; i < 3; i++, scan_dir++) { - if ((scan_dir->stat & 1) == 0) { - dir = &volume_dirs->udds[i]; - goto directory_available; - } - } - dir = 0; -directory_available: + dir = unused_directory((PF_VOLUME*)volume_dirs); if (dir == 0) { return 0x16; } @@ -239,9 +264,9 @@ directory_available: pf_s32 PFDIR_p_opendir(PF_VOLUME* volume, PFDIR_STR* path, PFDIR_DIR** opened_dir) { PF_ENT_ITER iter; PF_DIR_ENT entry; + pf_s32 i; PFDIR_SDD* sdd; PFDIR_DIR* dir; - pf_s32 i; pf_s32 error; if ((PFSTR_StrNCmp(path, (const pf_s8*)"\\", 1, 0, 1) == 0 || @@ -255,9 +280,6 @@ pf_s32 PFDIR_p_opendir(PF_VOLUME* volume, PFDIR_STR* path, PFDIR_DIR** opened_di } 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 && @@ -288,14 +310,7 @@ open_directory: if (sdd == 0) { return 0x15; } - 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; - } - } - dir = 0; -directory_available: + dir = unused_directory(volume); if (dir == 0) { return 0x16; } @@ -349,17 +364,23 @@ pf_s32 PFDIR_p_readdir(PFDIR_DIR* dir, PFDIR_READ_RESULT* result) { return 0; } +extern pf_s32 PFENT_findEntry(PFDIR_FFD*, PF_DIR_ENT*, pf_u32, PFDIR_STR*, pf_u8, pf_u32*, pf_u32*); +extern pf_s32 PFFAT_GetSectorSpecified(PFDIR_FFD*, pf_u32, pf_u32, pf_u32*); +extern pf_s32 PFPATH_transformInUnicode(pf_u16*, const pf_s8*); +extern void PFPATH_SetSearchPattern(pf_s8*, pf_u16*, PFDIR_STR*); +extern pf_u16* pf_w_strcpy(pf_u16*, const pf_u16*); + 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; + PFDIR_STR full_path; + PFDIR_STR dirname; pf_u16 dirname_len; + PF_ENT_ITER parent_iter; PF_DIR_ENT entry; PF_DIR_ENT parent_entry; - PF_ENT_ITER parent_iter; - PF_FFD ffd; + PFDIR_FFD ffd; + PFDIR_FAT_HINT fat_hint; pf_u32 pos; - PF_FAT_HINT fat_hint; pf_u32 prev_chain[2]; pf_u32 new_sector; @@ -368,7 +389,7 @@ pf_s32 PFDIR_p_mkdir(PF_VOLUME* p_vol, PF_STR* p_path, pf_u32 option, PF_DTA* p_ err = 0; new_sector = 0; - err = VFiPFPATH_SplitPath(p_path, &full_path, &dirname); + err = PFPATH_SplitPath((PFDIR_STR*)p_path, &full_path, &dirname); if (err != 0) { return err; } @@ -383,40 +404,39 @@ pf_s32 PFDIR_p_mkdir(PF_VOLUME* p_vol, PF_STR* p_path, pf_u32 option, PF_DTA* p_ 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); + PFFAT_InitFFD(&ffd, &fat_hint, p_vol, &parent_entry.start_cluster); + err = PFENT_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); + dirname_len = PFSTR_StrNumChar(&dirname, 1U); + if (dirname_len + parent_entry.path_len > 0x103U) { return 2; } + if (dirname_len > 0xFFU) { return 1; } + err = VFiPFENT_InitENT(&entry, (PF_STR*)&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); + PFFAT_InitFFD(&ffd, &fat_hint, p_vol, &parent_entry.start_cluster); + err = VFiPFENT_allocateEntry(&entry, (entry.num_entry_LFNs + 1), (PF_FFD*)&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); + PFFAT_InitFFD(&ffd, &fat_hint, p_vol, &entry.start_cluster); + err = PFFAT_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)) { + if ((entry.long_name[0] != 0) && ((pf_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); + PFFAT_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; @@ -428,16 +448,16 @@ pf_s32 PFDIR_p_mkdir(PF_VOLUME* p_vol, PF_STR* p_path, pf_u32 option, PF_DTA* p_ 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); + if (VFiPFSTR_GetCodeMode((PF_STR*)&dirname) == 1) { + PFPATH_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); + PFPATH_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]); + pf_strcpy(p_dta->FileName, &entry.short_name[0]); if ((p_dta->status & 2) == 2) { - VFiPFPATH_transformInUnicode(((PF_DTAW*)p_dta)->FileNameW, p_dta->FileName); + PFPATH_transformInUnicode(((PF_DTAW*)p_dta)->FileNameW, p_dta->FileName); } if (entry.long_name[0] == 0) { p_dta->ordinal = 0; @@ -449,17 +469,17 @@ pf_s32 PFDIR_p_mkdir(PF_VOLUME* p_vol, PF_STR* p_path, pf_u32 option, PF_DTA* p_ } 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; + if ((pf_vol_set.setting & 2) == 2) { + pf_vol_set.setting &= 0xFFFFFFFC; + pf_vol_set.setting |= 1; + PFPATH_transformFromUnicodeToNormal(p_dta->LongName, entry.long_name); + pf_vol_set.setting &= 0xFFFFFFFC; + pf_vol_set.setting |= 2; } else { - VFiPFPATH_transformFromUnicodeToNormal(p_dta->LongName, entry.long_name); + PFPATH_transformFromUnicodeToNormal(p_dta->LongName, entry.long_name); } if ((p_dta->status & 2) == 2) { - VFipf_w_strcpy(((PF_DTAW*)p_dta)->LongNameW, entry.long_name); + pf_w_strcpy(((PF_DTAW*)p_dta)->LongNameW, entry.long_name); } } } @@ -524,7 +544,7 @@ pf_s32 PFDIR_p_chdir(PF_VOLUME* p_vol, PFDIR_STR* p_path_str) { return 0; } -pf_s32 PFDIR_p_chmod(PF_VOLUME* volume, PFDIR_STR* path, pf_u8 attributes) { +pf_s32 PFDIR_p_chmod(PF_VOLUME* volume, PFDIR_STR* path, pf_u32 attributes) { PFDIR_STR directory_path; PFDIR_STR filename; PF_ENT_ITER iter; @@ -544,52 +564,50 @@ pf_s32 PFDIR_p_chmod(PF_VOLUME* volume, PFDIR_STR* path, pf_u8 attributes) { if (error != 0) { return error; } - if (((entry.attr & 0x10) == 0 && (attributes & 0x10) != 0) || - ((entry.attr & 0x10) != 0 && (attributes & 0x10) == 0)) { + 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; + attributes = (pf_u8)(attributes & ~0x40); } - if ((entry.attr & 0x10) == 0) { - if (PFFILE_IsOpened(&entry) != 0) { - return 0x13; - } - } else { + if ((entry.attr & 0x10) != 0) { 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) { + if (directory_is_open(&entry) != 0) { return 0x13; } + + if ((attributes & 4) != 0 && (pf_s32)(attributes & 0xF) != 0xF) { return 10; } attributes |= 0x10; + entry.attr = attributes; + } else { + if (PFFILE_IsOpened(&entry) != 0) { + return 0x13; + } + entry.attr = attributes; } - 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); + PFENT_getcurrentDateTimeForEnt(&entry.access_date, &time); + if (entry.file_size == 0 && (entry.attr & 0x10) == 0) { entry.start_cluster = 0; } + error = PFENT_updateEntry(&entry, 0); + if (error != 0) { return error; } + return 0; } pf_s32 PFDIR_p_rmdir(PF_VOLUME* volume, PFDIR_STR* path) { - PFDIR_VOLUME_DIRS* volume_dirs; + PFDIR_STR directory_path; + PFDIR_STR filename; + PFDIR_FAT_HINT saved_hint; 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 is_empty = 0; 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; @@ -597,30 +615,19 @@ pf_s32 PFDIR_p_rmdir(PF_VOLUME* volume, PFDIR_STR* path) { 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; - } - } + directory_iter = iter; + saved_hint = *iter.ffd.p_hint; + if (directory_is_open(&entry) != 0) { return 0x13; } + error = PFVOL_CheckCurrentDir(volume, entry.start_cluster); - if (error != 0) { - return 0x1C; - } + if (error != 0 || entry.start_cluster == 1 || + (volume->bpb.fat_type == FAT_32 && entry.start_cluster == volume->bpb.root_dir_cluster)) { 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; @@ -628,18 +635,20 @@ pf_s32 PFDIR_p_rmdir(PF_VOLUME* volume, PFDIR_STR* path) { if (is_empty == 0) { return 0x1D; } + iter = directory_iter; + iter.ffd.p_hint = &saved_hint; error = PFENT_RemoveEntry(&entry, &iter); if (error != 0) { return error; } - return PFFAT_FreeChain(&iter.ffd, entry.start_cluster, -1U, -1U); + return release_directory_chain(&iter.ffd, entry.start_cluster, -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 index = 0; pf_s32 error; error = PFENT_ITER_GetEntryOfPath(&iter, &entry, volume, path, 0); @@ -648,32 +657,32 @@ pf_s32 PFDIR_p_fstat(PF_VOLUME* volume, PFDIR_STR* path, PFDIR_FILE_STAT* file_s } 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; + if ((volume_dirs->sfds[index].stat & 1) != 0 && (volume_dirs->sfds[index].stat & 2) != 0 && + entry.p_vol == volume_dirs->sfds[index].dir_entry.p_vol && + entry.entry_sector == volume_dirs->sfds[index].dir_entry.entry_sector && + entry.entry_offset == volume_dirs->sfds[index].dir_entry.entry_offset) { + file_stat->file_size = volume_dirs->sfds[index].dir_entry.file_size; + file_stat->attributes = volume_dirs->sfds[index].dir_entry.attr; + file_stat->modify_time = volume_dirs->sfds[index].dir_entry.modify_time; + file_stat->modify_date = volume_dirs->sfds[index].dir_entry.modify_date; + file_stat->access_date = volume_dirs->sfds[index].dir_entry.access_date; + file_stat->create_time = volume_dirs->sfds[index].dir_entry.create_time; + file_stat->create_date = volume_dirs->sfds[index].dir_entry.create_date; + file_stat->small_letter_flag = volume_dirs->sfds[index].dir_entry.create_time_ms; 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; + if ((entry.attr & 0x10) != 0) { file_stat->file_size = 0; } + else { file_stat->file_size = entry.file_size; } + file_stat->attributes = entry.attr; file_stat->modify_time = entry.modify_time; file_stat->modify_date = entry.modify_date; + file_stat->access_date = entry.access_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; + file_stat->small_letter_flag = entry.create_time_ms; } return 0; } @@ -721,14 +730,18 @@ pf_s32 PFDIR_p_rename(PF_VOLUME* volume, PF_STR* old_path, PF_STR* new_path) { PFDIR_STR destination_directory; PFDIR_STR destination_name; pf_s8 normalized_name[512]; + pf_u32 code_mode; const pf_s8* name; pf_u32 entry_position; + pf_u16 filename_length; pf_s32 error; error = PFPATH_SplitPath((PFDIR_STR*)old_path, &source_directory, &source_name); if (error != 0) { return error; } + filename_length = PFSTR_StrNumChar(&source_name, 1); + if (filename_length > 0xFF) { return 1; } if (PFSTR_GetCodeMode(&source_name) == 2) { if (PFSTR_StrNumChar(&source_name, 1) > 0xFF) { return 1; @@ -755,7 +768,7 @@ pf_s32 PFDIR_p_rename(PF_VOLUME* volume, PF_STR* old_path, PF_STR* new_path) { if (error != 0) { return error; } - if (entry_position == 0) { + if (entry_position == 999999) { return 3; } if ((source_entry.attr & 0x10) != 0) { @@ -784,7 +797,7 @@ pf_s32 PFDIR_p_rename(PF_VOLUME* volume, PF_STR* old_path, PF_STR* new_path) { if (source_iter.ffd.start_cluster != destination_parent.start_cluster) { return 0x1F; } - if (PFSTR_GetCodeMode(&destination_name) == 2) { + if ((code_mode = PFSTR_GetCodeMode(&destination_name)) == 2) { if (PFSTR_StrNumChar(&destination_name, 1) > 0xFF) { return 1; } @@ -822,8 +835,10 @@ pf_s32 PFDIR_p_move(PF_VOLUME* volume, PF_STR* old_path, PF_STR* new_path) { PFDIR_STR destination_name; PFDIR_VOLUME_DIRS* volume_dirs; pf_s8 normalized_name[512]; + pf_u32 code_mode; pf_u32 entry_position; - pf_u32 index; + pf_u16 filename_length; + pf_s32 index = 0; pf_s32 error; error = PFENT_ITER_GetEntryOfPath(&source_iter, &source_entry, volume, @@ -839,7 +854,9 @@ pf_s32 PFDIR_p_move(PF_VOLUME* volume, PF_STR* old_path, PF_STR* new_path) { if (error != 0) { return error; } - if (PFSTR_GetCodeMode(&destination_name) == 2) { + filename_length = PFSTR_StrNumChar(&destination_name, 1); + if (filename_length > 0xFF) { return 1; } + if ((code_mode = PFSTR_GetCodeMode(&destination_name)) == 2) { if (PFSTR_StrNumChar(&destination_name, 1) > 0xFF) { return 1; } @@ -869,15 +886,7 @@ pf_s32 PFDIR_p_move(PF_VOLUME* volume, PF_STR* old_path, PF_STR* new_path) { 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; - } - } + if (directory_is_open(&source_entry) != 0) { return 0x13; } } else if (PFFILE_IsOpened(&source_entry) != 0) { return 0x13; } @@ -908,9 +917,10 @@ 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_u32 is_empty = 0; + pf_s32 index = 0; + pf_u32 start_cluster; + pf_u32 chain_size; pf_s32 error; if ((entry->attr & 1) != 0) { @@ -922,32 +932,30 @@ pf_s32 PFDIR_p_fsexec_remove(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter) 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; - } - } + if (directory_is_open(entry) != 0) { return 0x13; } + directory_iter = *iter; - PFFAT_InitFFD(&directory_iter.ffd, &hint, entry->p_vol, &entry->start_cluster); - error = PFENT_ITER_IteratorInitialize(&directory_iter, 0); + hint = *iter->ffd.p_hint; + PFFAT_ResetFFD(&iter->ffd, &entry->start_cluster); + error = PFENT_ITER_IteratorInitialize(iter, 0); if (error != 0) { return error; } - is_empty = 0; - error = PFDIR_CheckDirIsEmpty(&directory_iter, &is_empty); + error = PFDIR_CheckDirIsEmpty(iter, &is_empty); if (error != 0) { return error; } if (is_empty == 0) { return 0x1D; } - } else if (PFFILE_IsOpened(entry) != 0) { - return 0x13; + *iter = directory_iter; + iter->ffd.p_hint = &hint; + chain_size = -1U; + } else { + if (PFFILE_IsOpened(entry) != 0) { return 0x13; } + chain_size = entry->file_size; } + start_cluster = entry->start_cluster; entry->num_entry_LFNs = data->num_entry_LFNs; entry->ordinal = data->ordinal; entry->check_sum = data->check_sum; @@ -955,21 +963,29 @@ pf_s32 PFDIR_p_fsexec_remove(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter) if (error != 0) { return error; } - return PFFAT_FreeChain(&iter->ffd, start_cluster, -1U, -1U); + return release_directory_chain(&iter->ffd, start_cluster, chain_size); } -pf_s32 PFDIR_p_fsexec_chmod(PF_DTA* data, PF_DIR_ENT* entry, pf_u32 attributes, pf_u32 mode) { + +pf_s32 PFDIR_p_fsexec_chmod(PF_DTA* data, PF_DIR_ENT* entry, pf_u32 mode, pf_u32 attributes) { 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 index = 0; pf_s32 error; if ((attributes & 0x40) != 0) { - attributes &= ~0x40; + attributes = (pf_u8)(attributes & ~0x40); } - if ((entry->attr & 0x10) == 0) { + if ((entry->attr & 0x10) != 0) { + if ((attributes & 4) != 0) { + return 10; + } + if (directory_is_open(entry) != 0) { return 0x13; } + + entry->attr = attributes | 0x10; + } else { if ((attributes & 0x10) != 0) { return 10; } @@ -977,25 +993,8 @@ pf_s32 PFDIR_p_fsexec_chmod(PF_DTA* data, PF_DIR_ENT* entry, pf_u32 attributes, 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; + PFENT_getcurrentDateTimeForEnt(&entry->access_date, &time); error = PFENT_updateEntry(entry, 0); if (error != 0) { return error; @@ -1003,7 +1002,9 @@ pf_s32 PFDIR_p_fsexec_chmod(PF_DTA* data, PF_DIR_ENT* entry, pf_u32 attributes, if ((mode & 0x80000000) == 0) { data->Attribute = entry->attr; } - return PFCACHE_FlushDataCacheSpecific(entry->p_vol, 0); + error = PFCACHE_FlushDataCacheSpecific(entry->p_vol, 0); + if (error != 0) { return error; } + return 0; } pf_s32 PFDIR_p_fsexec_fopen(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter, pf_u32 flags, @@ -1062,9 +1063,9 @@ pf_s32 PFDIR_p_fsexec_opendir(PF_DTA* data, PF_DIR_ENT* entry, PF_ENT_ITER* iter } pf_s32 PFDIR_p_fsexec(PF_DTA* data, pf_u32 flags, pf_u32 mode) { + PF_ENT_ITER iter; PFDIR_FFD ffd; PFDIR_FAT_HINT hint; - PF_ENT_ITER iter; PF_DIR_ENT entry; PFDIR_STR pattern; pf_u32 logical_position; @@ -1074,32 +1075,34 @@ pf_s32 PFDIR_p_fsexec(PF_DTA* data, pf_u32 flags, pf_u32 mode) { const pf_s8* name; pf_s32 error; - if ((flags & 0x26) == 0 && (flags & 1) == 0) { + if ((flags & 6) == 0 && (flags & 1) == 0 && (flags & 0x10) == 0 && (flags & 0x20) == 0) { return 10; } - if ((flags & 0x26) != 0 || (flags & 1) != 0 || ((flags & 0x10) != 0 && mode != 2)) { + if ((flags & 6) != 0 || (flags & 1) != 0 || ((flags & 0x10) != 0 && mode != 2)) { error = PFVOL_CheckForWrite(data->p_vol); if (error != 0) { return error; } } + entry.start_cluster = data->parent_start_cluster; + entry.check_sum = 0; + PFFAT_InitFFD(&ffd, &hint, data->p_vol, &entry.start_cluster); + iter.p_vol = data->p_vol; + iter.ffd = ffd; 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) { + if ((data->status & 1) == 1) { code_mode = 1; name = data->FileName; } else { code_mode = 2; - if ((VFipf_vol_set.setting & 2) != 0) { + if ((pf_vol_set.setting & 2) != 0) { name = (const pf_s8*)((PF_DTAW*)data)->LongNameW; } else { name = (const pf_s8*)((PF_DTAW*)data)->FileNameW; @@ -1109,7 +1112,7 @@ pf_s32 PFDIR_p_fsexec(PF_DTA* data, pf_u32 flags, pf_u32 mode) { if (error != 0) { return error; } - if ((VFipf_vol_set.setting & 2) != 0) { + if ((pf_vol_set.setting & 2) != 0) { PFSTR_SetLocalStr(&pattern, (pf_u32)data->LongName); } else { PFSTR_SetLocalStr(&pattern, (pf_u32)data->FileName); @@ -1137,7 +1140,7 @@ pf_s32 PFDIR_p_fsexec(PF_DTA* data, pf_u32 flags, pf_u32 mode) { return error; } if ((flags & 6) != 0) { - return PFDIR_p_fsexec_chmod(data, &entry, flags, mode); + return PFDIR_p_fsexec_chmod(data, &entry, mode, flags); } if ((flags & 1) != 0) { return PFDIR_p_fsexec_remove(data, &entry, &iter); @@ -1316,7 +1319,7 @@ void PFDIR_opendir(PF_STR* path, PFDIR_DIR** dir) { pf_vol_set.last_error = error; ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; } else { - ((PFDIR_VOLUME_DIRS*)volume)->num_opened_directories++; + ((PFDIR_VOLUME_DIRS*)volume)->num_opened_directories += 1; } } @@ -1507,9 +1510,15 @@ pf_s32 PFDIR_chdir(PF_STR* path) { if (error != 0) { pf_vol_set.last_error = error; ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; - return error; + } else { + PFVOL_SetCurrentVolume(volume); } - PFVOL_SetCurrentVolume(volume); + return error; +} + +static inline pf_s32 set_directory_context(PF_VOLUME* volume, PF_DIR_ENT* entry) { + pf_s32 error = PFVOL_SetCurrentDir(volume, entry); + if (error != 0) { return error; } return 0; } @@ -1528,14 +1537,14 @@ pf_s32 PFDIR_fchdir(PFDIR_DIR* dir) { ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; return error; } - error = PFVOL_SetCurrentDir(volume, &dir->p_sdd->dir_entry); + error = set_directory_context(volume, &dir->p_sdd->dir_entry); if (error != 0) { pf_vol_set.last_error = error; ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; - return error; + } else { + PFVOL_SetCurrentVolume(volume); } - PFVOL_SetCurrentVolume(volume); - return 0; + return error; } void PFDIR_chmod(PF_STR* path, pf_u8 attributes) { @@ -1580,7 +1589,7 @@ void PFDIR_chdmod(PF_STR* path, pf_u8 attributes) { return; } volume_dirs->cache_signature = 0; - error = PFDIR_p_chmod(volume, (PFDIR_STR*)path, attributes | 0x10); + error = PFDIR_p_chmod(volume, (PFDIR_STR*)path, (pf_u8)(attributes | 0x10)); if (error != 0) { pf_vol_set.last_error = error; ((PFDIR_VOLUME_DIRS*)volume)->last_error = error; @@ -1608,7 +1617,7 @@ pf_s32 PFDIR_p_fsnext(PF_DTA* data) { pf_u32 logical_position = 0; pf_u32 entry_position = 0; pf_u32 code_mode; - pf_u32 index; + pf_s32 index = 0; pf_s32 error; if ((data->status & 1) == 1) { @@ -1621,63 +1630,55 @@ pf_s32 PFDIR_p_fsnext(PF_DTA* data) { 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); + PFSTR_SetLocalStr(&pattern, (pf_u32)data->reg_exp); + while (entry_position < 999999) { + if (data->parent_pos >= 999999) { return 10; } + entry.start_cluster = data->parent_start_cluster; + PFFAT_InitFFD(&ffd, &hint, data->p_vol, &entry.start_cluster); error = PFENT_findEntryPos(&ffd, &entry, data->parent_pos, &pattern, data->attr, 0, &logical_position, &entry_position); - if (error != 0) { - return error; - } + if (error != 0) { return error; } data->parent_pos = entry_position + 1; - if (entry_position == 0xF423F) { - return 3; - } + if (entry_position == 999999) { 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; + if (entry.long_name[0] != 0) { + if ((pf_vol_set.setting & 2) == 2) { + pf_vol_set.setting &= 0xFFFFFFFC; + pf_vol_set.setting |= 1; PFPATH_transformFromUnicodeToNormal(data->LongName, entry.long_name); - VFipf_vol_set.setting &= 0xFFFFFFFC; - VFipf_vol_set.setting |= 2; + pf_vol_set.setting &= 0xFFFFFFFC; + pf_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); } + } else { + data->LongName[0] = 0; + if ((data->status & 2) == 2) { + ((PF_DTAW*)data)->LongNameW[0] = 0; + } } 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; + if ((((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].stat & 1) != 0 && (((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].stat & 2) != 0 && + entry.p_vol == ((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].dir_entry.p_vol && + ((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].dir_entry.entry_sector == entry.entry_sector && + ((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].dir_entry.entry_offset == entry.entry_offset) { + data->FileSize = ((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].dir_entry.file_size; + data->Time = ((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].dir_entry.modify_time; + data->Date = ((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].dir_entry.modify_date; + data->Attribute = ((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].dir_entry.attr; + data->num_entry_LFNs = ((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].dir_entry.num_entry_LFNs; + data->ordinal = ((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].dir_entry.ordinal; + data->check_sum = ((PFDIR_VOLUME_DIRS*)data->p_vol)->sfds[index].dir_entry.check_sum; break; } - sfd++; } } if (((PFDIR_VOLUME_DIRS*)data->p_vol)->num_opened_files == 0 || index == 5) { diff --git a/libs/RVL_SDK/src/fa/pf_fat.c b/libs/RVL_SDK/src/fa/pf_fat.c index 57b7fdf5..97a65db5 100644 --- a/libs/RVL_SDK/src/fa/pf_fat.c +++ b/libs/RVL_SDK/src/fa/pf_fat.c @@ -358,8 +358,8 @@ s32 PFFAT_FindClusterLink(PFFAT_FFD* file, u32 chainIndex, u32* cluster, u32 nextCluster; s32 error; - *found = 0; nextCluster = -1; + *found = 0; if (file->cluster_link.position == 0) { return 0; } @@ -388,6 +388,7 @@ s32 PFFAT_FindClusterLink(PFFAT_FFD* file, u32 chainIndex, u32* cluster, &nextCluster); break; default: + nextCluster = -1; error = 15; break; } @@ -486,6 +487,7 @@ s32 PFFAT_ReadCluster(PFFAT_FFD* file, u32 cluster, u32 chainIndex, u32* nextCluster, u32* checkClusterLink) { s32 error; + u32 value; *nextCluster = -1; if (file->cluster_link.buffer != 0 && *checkClusterLink == 1) { @@ -515,22 +517,22 @@ s32 PFFAT_ReadCluster(PFFAT_FFD* file, u32 cluster, u32 chainIndex, if (error != 0) { return error; } - if (*nextCluster == 0) { + value = *nextCluster; + if (value == 0) { return 13; } - if (*nextCluster == -1) { + if (value == -1) { return 6; } - } - if (file->cluster_link.buffer != 0 && - *nextCluster != fat_special_values[file->p_vol->bpb.fat_type].eoc2) { + if (file->cluster_link.buffer != 0 && + value != fat_special_values[file->p_vol->bpb.fat_type].eoc2) { if (file->cluster_link.max_count > file->cluster_link.position && file->cluster_link.max_count != 0) { if (chainIndex == file->cluster_link.position * (file->cluster_link.interval + 1)) { file->cluster_link.interval_offset = 0; file->cluster_link.buffer[file->cluster_link.position] = - *nextCluster; + value; file->cluster_link.position++; } else { file->cluster_link.interval_offset++; @@ -538,6 +540,7 @@ s32 PFFAT_ReadCluster(PFFAT_FFD* file, u32 cluster, u32 chainIndex, file->cluster_link.save_index = chainIndex; } } + } return 0; } @@ -546,6 +549,7 @@ s32 PFFAT_ReadClusterWithBuf(PFFAT_FFD* file, u32 cluster, u32 chainIndex, PF_CACHE_PAGE* page) { s32 error; + u32 value; *nextCluster = -1; if (file->cluster_link.buffer != 0 && *checkClusterLink == 1) { @@ -576,22 +580,22 @@ s32 PFFAT_ReadClusterWithBuf(PFFAT_FFD* file, u32 cluster, u32 chainIndex, if (error != 0) { return error; } - if (*nextCluster == 0) { + value = *nextCluster; + if (value == 0) { return 13; } - if (*nextCluster == -1) { + if (value == -1) { return 6; } - } - if (file->cluster_link.buffer != 0 && - *nextCluster != fat_special_values[file->p_vol->bpb.fat_type].eoc2) { + if (file->cluster_link.buffer != 0 && + value != fat_special_values[file->p_vol->bpb.fat_type].eoc2) { if (file->cluster_link.max_count > file->cluster_link.position && file->cluster_link.max_count != 0) { if (chainIndex == file->cluster_link.position * (file->cluster_link.interval + 1)) { file->cluster_link.interval_offset = 0; file->cluster_link.buffer[file->cluster_link.position] = - *nextCluster; + value; file->cluster_link.position++; } else { file->cluster_link.interval_offset++; @@ -599,6 +603,7 @@ s32 PFFAT_ReadClusterWithBuf(PFFAT_FFD* file, u32 cluster, u32 chainIndex, file->cluster_link.save_index = chainIndex; } } + } return 0; } @@ -608,6 +613,7 @@ s32 PFFAT_WriteCluster(PFFAT_FFD* file, u32 cluster, u32 chainIndex, u32 accessCluster; u32 position; u32 divisor; + u32* linkBuffer; u32 precedingIndex; s32 error; @@ -641,14 +647,15 @@ s32 PFFAT_WriteCluster(PFFAT_FFD* file, u32 cluster, u32 chainIndex, if (error != 0) { return error; } - if (file->cluster_link.buffer != 0 && useClusterLink == 1) { + linkBuffer = file->cluster_link.buffer; + if (linkBuffer != 0 && useClusterLink == 1) { if (nextCluster == 0) { divisor = file->cluster_link.interval + 1; position = chainIndex / divisor; if (file->cluster_link.max_count >= position) { if (chainIndex % divisor == 0) { - file->cluster_link.buffer[position] = 0; + linkBuffer[position] = 0; } if (file->cluster_link.save_index >= chainIndex) { precedingIndex = chainIndex - 1; @@ -694,6 +701,7 @@ s32 PFFAT_WriteClusterWithBuf(PFFAT_FFD* file, u32 cluster, u32 chainIndex, u32 accessCluster; u32 position; u32 divisor; + u32* linkBuffer; u32 precedingIndex; s32 error; @@ -729,14 +737,15 @@ s32 PFFAT_WriteClusterWithBuf(PFFAT_FFD* file, u32 cluster, u32 chainIndex, if (error != 0) { return error; } - if (file->cluster_link.buffer != 0 && useClusterLink == 1) { + linkBuffer = file->cluster_link.buffer; + if (linkBuffer != 0 && useClusterLink == 1) { if (nextCluster == 0) { divisor = file->cluster_link.interval + 1; position = chainIndex / divisor; if (file->cluster_link.max_count >= position) { if (chainIndex % divisor == 0) { - file->cluster_link.buffer[position] = 0; + linkBuffer[position] = 0; } if (file->cluster_link.save_index >= chainIndex) { precedingIndex = chainIndex - 1; @@ -1108,14 +1117,25 @@ s32 PFFAT_GetClusterAllocatedInChain(PFFAT_FFD* file, u32 initialCluster, return 0; } +static inline s32 find_cluster_in_chain(PFFAT_FFD* file, u32 index, u32 mode, u32 count, u32 useFirst, u32* cluster) { + u32 firstCluster; + u32 lastCluster; + u32 candidate; + s32 error = PFFAT_GetClusterInChain(file, index, mode, count, &firstCluster, &lastCluster); + if (error != 0) { return error; } + candidate = useFirst ? firstCluster : lastCluster; + if (candidate >= 2 && candidate < file->p_vol->bpb.num_clusters + 2) { *cluster = candidate; } + return 0; +} + s32 PFFAT_GetClusterSpecified(PFFAT_FFD* file, u32 chainIndex, u32 mayAllocate, u32* cluster) { PFFAT_HINT* hint; u32 fatType; u32 found; - u32 locateEnd; u32 locateStart; + u32 locateEnd; s32 error; fatType = file->p_vol->bpb.fat_type; @@ -1144,20 +1164,7 @@ s32 PFFAT_GetClusterSpecified(PFFAT_FFD* file, u32 chainIndex, } } *cluster = -1; - error = PFFAT_GetClusterInChain(file, chainIndex, mayAllocate != 0, 0, - &locateStart, &locateEnd); - if (error == 0) { - goto cluster_lookup_succeeded; - } - goto cluster_lookup_complete; - -cluster_lookup_succeeded: - if (locateEnd >= 2 && locateEnd < file->p_vol->bpb.num_clusters + 2) { - *cluster = locateEnd; - } - error = 0; - -cluster_lookup_complete: + error = find_cluster_in_chain(file, chainIndex, mayAllocate != 0, 0, 0, cluster); if (error != 0) { return error; } @@ -1173,10 +1180,10 @@ cluster_lookup_complete: s32 PFFAT_GetClusterAllocated(PFFAT_FFD* file, u32 chainIndex, u32 numClusters, u32* cluster) { - u32 fatType; PFFAT_HINT* hint; - u32 locateEnd; + u32 fatType; u32 locateStart; + u32 locateEnd; s32 error; fatType = file->p_vol->bpb.fat_type; @@ -1189,15 +1196,7 @@ s32 PFFAT_GetClusterAllocated(PFFAT_FFD* file, u32 chainIndex, *file->p_start_cluster = file->p_vol->bpb.root_dir_cluster; } *cluster = -1; - error = PFFAT_GetClusterInChain(file, chainIndex, 2, numClusters, - &locateStart, &locateEnd); - if (error == 0) { - if (locateStart >= 2 && - locateStart < file->p_vol->bpb.num_clusters + 2) { - *cluster = locateStart; - } - error = 0; - } + error = find_cluster_in_chain(file, chainIndex, 2, numClusters, 1, cluster); if (error != 0) { return error; } @@ -1225,17 +1224,18 @@ s32 PFFAT_GetSector(PFFAT_FFD* file, u32 fileSectorIndex, u32 mode, u32 size, u32* sector) { PF_VOLUME* volume; + u32 fatType; u32 chainIndex; u32 cluster; - u32 numDivide; u32 numRemainder; - u32 numSectors; + u32 numDivide; u32 numClusters; + u32 numSectors; s32 error; volume = file->p_vol; - if (*file->p_start_cluster == 1 && - (u32)volume->bpb.fat_type <= FAT_16) { + fatType = volume->bpb.fat_type; + if (*file->p_start_cluster == 1 && fatType <= FAT_16) { error = PFFAT_GetSectorInRootDirRegion(volume, fileSectorIndex, sector); if (error != 0) { return error; @@ -1244,13 +1244,12 @@ s32 PFFAT_GetSector(PFFAT_FFD* file, u32 fileSectorIndex, u32 mode, } chainIndex = fileSectorIndex >> volume->bpb.log2_sectors_per_cluster; if (mode == 2) { - numDivide = size / volume->bpb.bytes_per_sector; - numRemainder = (size % volume->bpb.bytes_per_sector) != 0; - numSectors = numDivide + numRemainder; + numSectors = (size / volume->bpb.bytes_per_sector) + + ((size % volume->bpb.bytes_per_sector) != 0); numDivide = numSectors / volume->bpb.sectors_per_cluster; numRemainder = (numSectors % volume->bpb.sectors_per_cluster) != 0; - numClusters = numDivide + numRemainder; + numClusters = numRemainder + numDivide; error = PFFAT_GetClusterAllocated(file, chainIndex, numClusters, &cluster); if (error != 0) { @@ -1375,7 +1374,8 @@ s32 PFFAT_CountAllocatedClusters(PFFAT_FFD* file, u32 size, *numAllocatedClusters = file->p_hint->chain_index; cluster = file->p_hint->cluster; chainIndex = file->p_hint->chain_index + 1; - size -= file->p_hint->chain_index * bytesPerCluster; + size -= file->p_hint->chain_index * + (file->p_vol->bpb.bytes_per_sector * file->p_vol->bpb.sectors_per_cluster); } else { cluster = *file->p_start_cluster; chainIndex = 1; @@ -1520,9 +1520,9 @@ s32 PFFAT_FreeChain(PFFAT_FFD* file, u32 startCluster, u32 chainIndex, } if (nextCluster == 0) { s32 firstFlushError; - u32 fatSector; - u16 fatIndex; PF_CACHE_PAGE* flushPage; + u16 fatIndex; + u32 fatSector; firstFlushError = 0; flushPage = page; @@ -1857,7 +1857,8 @@ s32 PFFAT_RefreshFSINFO(PF_VOLUME* volume) if ((volume->fsi_flag & 4) != 0) { error = PFCACHE_AllocateDataPage(volume, -1, &page, &alreadyAllocated); - if (error == 0) { + if (error != 0) { goto finished; } + { error = PFSEC_ReadData( volume, page->p_buf, volume->bpb.fs_info_sector, 0, volume->bpb.bytes_per_sector, &completedBytes, 0); @@ -1896,6 +1897,7 @@ s32 PFFAT_RefreshFSINFO(PF_VOLUME* volume) PFCACHE_FreeDataPage(volume, page); } } +finished: return error; } diff --git a/libs/RVL_SDK/src/fa/pf_file.c b/libs/RVL_SDK/src/fa/pf_file.c index 97857189..c029c635 100644 --- a/libs/RVL_SDK/src/fa/pf_file.c +++ b/libs/RVL_SDK/src/fa/pf_file.c @@ -1,3 +1,4 @@ +#define PF_FA_STR_LAYOUT #include #include #include @@ -414,16 +415,24 @@ pf_s32 PFFILE_Cursor_Read(PFFILE_FILE* file, pf_u8* buffer, pf_u32 size, pf_u32* return 0; } +static inline void advance_write_cursor(PFFILE_FILE* file, pf_u32 size, pf_u32 sector) { + PF_VOLUME* volume = file == PF_NULL ? PF_NULL : file->p_sfd->dir_entry.p_vol; + pf_u32 position = file->cursor.offset_in_sector + size; + pf_u32 next_sector = sector + (position >> volume->bpb.log2_bytes_per_sector); + if (((volume->bpb.bytes_per_sector - 1) & position) != 0) { file->cursor.sector = next_sector; } + else { file->cursor.sector = -1; } + file->cursor.position += size; + if (file->cursor.position > file->p_sfd->dir_entry.file_size) { + file->p_sfd->dir_entry.file_size = file->cursor.position; + } + PFFILE_Cursor_Recalc(file); + PFCLUSTER_UpdateLastAccessCluster(file, next_sector); +} + pf_s32 PFFILE_Cursor_WriteHeadSector(PFFILE_FILE* file, const pf_u8* buffer, pf_u32 size, pf_u32* size_written) { pf_s32 error; pf_u32 success_size; - pf_u32 next_position; - pf_u32 new_position; - pf_u32 current_sector; - pf_u32 written_size; - pf_u32 sector_advance; - pf_u32 next_sector; PF_VOLUME* volume; *size_written = 0; @@ -452,24 +461,7 @@ pf_s32 PFFILE_Cursor_WriteHeadSector(PFFILE_FILE* file, const pf_u8* buffer, pf_ return error; } *size_written = success_size; - current_sector = file->cursor.sector; - written_size = success_size; - volume = file == PF_NULL ? PF_NULL : file->p_sfd->dir_entry.p_vol; - next_position = file->cursor.offset_in_sector + written_size; - sector_advance = next_position >> volume->bpb.log2_bytes_per_sector; - next_sector = current_sector + sector_advance; - if (((volume->bpb.bytes_per_sector - 1) & next_position) != 0) { - file->cursor.sector = next_sector; - } else { - file->cursor.sector = -1; - } - new_position = file->cursor.position + success_size; - file->cursor.position = new_position; - if (new_position > file->p_sfd->dir_entry.file_size) { - file->p_sfd->dir_entry.file_size = new_position; - } - PFFILE_Cursor_Recalc(file); - PFCLUSTER_UpdateLastAccessCluster(file); + advance_write_cursor(file, success_size, file->cursor.sector); if (success_size != size) { return error; } @@ -481,7 +473,6 @@ pf_s32 PFFILE_Cursor_WriteBodySectors(PFFILE_FILE* file, const pf_u8* buffer, pf pf_s32 error; pf_u32 num_sectors; pf_u32 success_size; - pf_u32 next_position; PF_VOLUME* volume; *size_written = 0; @@ -506,18 +497,7 @@ pf_s32 PFFILE_Cursor_WriteBodySectors(PFFILE_FILE* file, const pf_u8* buffer, pf return error; } *size_written = success_size; - next_position = file->cursor.offset_in_sector + success_size; - if (((volume->bpb.bytes_per_sector - 1) & next_position) != 0) { - file->cursor.sector += next_position >> volume->bpb.log2_bytes_per_sector; - } else { - file->cursor.sector = -1; - } - file->cursor.position += success_size; - if (file->cursor.position > file->p_sfd->dir_entry.file_size) { - file->p_sfd->dir_entry.file_size = file->cursor.position; - } - PFFILE_Cursor_Recalc(file); - PFCLUSTER_UpdateLastAccessCluster(file); + advance_write_cursor(file, success_size, file->cursor.sector); if (success_size != size - (size & (volume->bpb.bytes_per_sector - 1))) { return error; } @@ -528,12 +508,6 @@ pf_s32 PFFILE_Cursor_WriteTailSector(PFFILE_FILE* file, const pf_u8* buffer, pf_ pf_u32* size_written) { pf_s32 error; pf_u32 success_size; - pf_u32 next_position; - pf_u32 current_sector; - pf_u32 written_size; - pf_u32 sector_advance; - pf_u32 next_sector; - pf_u32 new_position; PF_VOLUME* volume; *size_written = 0; @@ -563,24 +537,7 @@ pf_s32 PFFILE_Cursor_WriteTailSector(PFFILE_FILE* file, const pf_u8* buffer, pf_ return error; } *size_written = success_size; - current_sector = file->cursor.sector; - written_size = success_size; - volume = file == PF_NULL ? PF_NULL : file->p_sfd->dir_entry.p_vol; - next_position = file->cursor.offset_in_sector + written_size; - sector_advance = next_position >> volume->bpb.log2_bytes_per_sector; - next_sector = current_sector + sector_advance; - if (((volume->bpb.bytes_per_sector - 1) & next_position) != 0) { - file->cursor.sector = next_sector; - } else { - file->cursor.sector = -1; - } - new_position = file->cursor.position + success_size; - file->cursor.position = new_position; - if (new_position > file->p_sfd->dir_entry.file_size) { - file->p_sfd->dir_entry.file_size = new_position; - } - PFFILE_Cursor_Recalc(file); - PFCLUSTER_UpdateLastAccessCluster(file); + advance_write_cursor(file, success_size, file->cursor.sector); if (success_size != size) { return error; } @@ -697,15 +654,16 @@ PFFILE_SFD* PFFILE_GetSFD(PF_VOLUME* volume, PF_DIR_ENT* entry) { pf_u32 index = 0; for (; index < 5; index++, sfd++) { - if ((sfd->stat & 1) == 0 || (sfd->stat & 2) == 0) { + if ((volume_dirs->sfds[index].stat & 1) == 0 || + ((volume_dirs->sfds[index].stat & 1) != 0 && (!volume_dirs->sfds[index].stat & 2) != 0)) { if (first_free_sfd == PF_NULL) { first_free_sfd = sfd; first_free_index = index; } - } else if (entry->p_vol == sfd->dir_entry.p_vol && - entry->entry_sector == sfd->dir_entry.entry_sector && - entry->entry_offset == sfd->dir_entry.entry_offset) { - return sfd; + } else if (entry->p_vol == volume_dirs->sfds[index].dir_entry.p_vol && + entry->entry_sector == volume_dirs->sfds[index].dir_entry.entry_sector && + entry->entry_offset == volume_dirs->sfds[index].dir_entry.entry_offset) { + return &volume_dirs->sfds[index]; } } @@ -744,22 +702,23 @@ PFFILE_SFD* PFFILE_GetSFD(PF_VOLUME* volume, PF_DIR_ENT* entry) { pf_s32 PFFILE_createEmptyFile(PF_VOLUME* volume, PF_DIR_ENT* entry, PF_STR* filename) { PF_DIR_ENT parent_entry = *entry; PFFILE_FFD ffd; - PF_FAT_HINT hint; + PFFILE_FAT_HINT hint; pf_u32 previous_sectors[2]; + pf_u32* previous_sector; + pf_u32 success_size; pf_u32 entry_position; - pf_u32 num_chars; - pf_u32 num_entries; + pf_s32 num_chars; + pf_u8 num_entries; + pf_u8 checksum; pf_u32 ordinal; pf_u32 sector; - pf_u32 success_size; pf_s32 error; pf_u8 short_entry_buffer[13]; pf_u8 long_entry_buffer[32]; num_chars = PFSTR_StrNumChar(filename, 1) & 0xFFFF; - if (num_chars + parent_entry.path_len >= 0x104 || num_chars >= 0x100) { - return 1; - } + if (num_chars + parent_entry.path_len > 0x103) { return 1; } + if (num_chars > 0xFF) { return 1; } PFFAT_InitFFD(&ffd, &hint, parent_entry.p_vol, &parent_entry.start_cluster); if (((PFFILE_VOLUME_DIRS*)volume)->num_opened_files >= 5) { return 0x15; @@ -768,9 +727,7 @@ pf_s32 PFFILE_createEmptyFile(PF_VOLUME* volume, PF_DIR_ENT* entry, PF_STR* file if (error != 0 && entry->short_name[0] == 0) { return 1; } - if (error == 0) { - entry->long_name[0] = 0; - } else { + if (error != 0) { error = PFENT_AdjustSFN(&parent_entry, entry->short_name); if (error != 0) { return error; @@ -780,8 +737,11 @@ pf_s32 PFFILE_createEmptyFile(PF_VOLUME* volume, PF_DIR_ENT* entry, PF_STR* file } else { pf_w_strcpy(entry->long_name, (const pf_u16*)PFSTR_GetStrPos(filename, 1)); } + } else { + entry->long_name[0] = 0; } - entry->start_cluster = volume->bpb.fat_type == FAT_32 ? 1 : 0; + if (volume->bpb.fat_type == FAT_32) { entry->start_cluster = 1; } + else { entry->start_cluster = 0; } entry->file_size = 0; entry->p_vol = volume; entry->small_letter_flag = 0; @@ -798,14 +758,16 @@ pf_s32 PFFILE_createEmptyFile(PF_VOLUME* volume, PF_DIR_ENT* entry, PF_STR* file if (error != 0) { return error; } - if ((pf_vol_set.file_settings & 2) != 0) { + if ((pf_vol_set.file_settings & 2) == 2) { PFPATH_AdjustExtShortName(entry->short_name, entry_position); } entry->num_entry_LFNs = num_entries; sector = entry->entry_sector; - for (ordinal = num_entries; ordinal != 0; ordinal--) { + checksum = PFENT_CalcCheckSum(entry); + previous_sector = previous_sectors; + for (ordinal = num_entries; ordinal >= 1; ordinal--) { PFENT_storeLFNEntryFieldsToBuf(long_entry_buffer, entry, ordinal, - PFENT_CalcCheckSum(entry), ordinal == num_entries); + checksum, ordinal == num_entries); error = PFSEC_WriteData(volume, long_entry_buffer, sector, entry->entry_offset, 0x20, &success_size, 0); if (error != 0) { @@ -817,8 +779,7 @@ pf_s32 PFFILE_createEmptyFile(PF_VOLUME* volume, PF_DIR_ENT* entry, PF_STR* file entry->entry_offset += 0x20; if (entry->entry_offset >= volume->bpb.bytes_per_sector) { entry->entry_offset = 0; - sector = previous_sectors[0]; - previous_sectors[0] = previous_sectors[1]; + sector = *previous_sector++; } } entry->entry_sector = sector; @@ -834,14 +795,25 @@ pf_s32 PFFILE_createEmptyFile(PF_VOLUME* volume, PF_DIR_ENT* entry, PF_STR* file return PFENT_updateEntry(entry, 1); } +static inline pf_u32 file_is_open(PF_DIR_ENT* entry) { + pf_s32 index; + for (index = 0; index < 5; index++) { + PFFILE_SFD* sfd = &((PFFILE_VOLUME_DIRS*)entry->p_vol)->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) { return 1; } + } + return 0; +} + pf_s32 PFFILE_p_remove(PF_VOLUME* volume, PF_STR* path) { PF_STR directory; PF_STR filename; PF_DIR_ENT entry; PFFILE_ENT_ITER iter; - PFFILE_VOLUME_DIRS* volume_dirs = (PFFILE_VOLUME_DIRS*)volume; pf_s32 error; - pf_u32 index; + PFFILE_FAT_HINT hint; + pf_u32 start_cluster; error = PFPATH_SplitPath(path, &directory, &filename); if (error != 0) { @@ -851,39 +823,34 @@ pf_s32 PFFILE_p_remove(PF_VOLUME* volume, PF_STR* path) { if (error != 0) { return error; } + hint = *(PFFILE_FAT_HINT*)iter.ffd.p_hint; if ((entry.attr & 0x19) != 0) { return 0xB; } - for (index = 0; index < 5; index++) { - if ((volume_dirs->sfds[index].stat & 1) != 0 && - (volume_dirs->sfds[index].stat & 2) != 0 && - entry.p_vol == volume_dirs->sfds[index].dir_entry.p_vol && - entry.entry_sector == volume_dirs->sfds[index].dir_entry.entry_sector && - entry.entry_offset == volume_dirs->sfds[index].dir_entry.entry_offset) { - return 0x13; - } - } + if (file_is_open(&entry) != 0) { return 0x13; } + iter.ffd.p_hint = (PF_FAT_HINT*)&hint; + start_cluster = entry.start_cluster; error = PFENT_RemoveEntry(&entry, &iter); if (error != 0) { return error; } - return PFFAT_FreeChain(&iter.ffd, entry.start_cluster, 0xFFFFFFFF, entry.file_size); + return PFFAT_FreeChain(&iter.ffd, start_cluster, 0xFFFFFFFF, entry.file_size); } +static PFFILE_FILE* PFFILE_GetFreeUFD(PF_VOLUME* volume); + pf_s32 PFFILE_p_fopen(PF_VOLUME* volume, PF_STR* path, pf_u32 open_mode, PFFILE_FILE** result) { - PF_STR directory; PF_STR filename; + PF_STR directory; PF_DIR_ENT entry; PFFILE_ENT_ITER iter; PFFILE_FFD ffd; - PF_FAT_HINT hint; + PFFILE_FAT_HINT hint; PFFILE_SFD* sfd; PFFILE_FILE* file; pf_s8 normalized_filename[0x200]; - pf_u32 num_chars; - pf_u32 index; - pf_u32 success_size; + pf_s32 num_chars; pf_u16 access_time; pf_s32 error; @@ -908,49 +875,7 @@ pf_s32 PFFILE_p_fopen(PF_VOLUME* volume, PF_STR* path, pf_u32 open_mode, (const pf_u16*)PFSTR_GetStrPos(&filename, 1)); } PFSTR_SetLocalStr(&filename, normalized_filename); - if ((open_mode & 2) == 0) { - error = PFFILE_createEmptyFile(volume, &entry, &filename); - if (error == 8) { - if ((open_mode & 0x10) != 0) { - return 8; - } - if ((open_mode & 1) != 0) { - for (index = 0; index < 5; index++) { - if ((((PFFILE_VOLUME_DIRS*)entry.p_vol)->sfds[index].stat & 3) == 3 && - entry.p_vol == - ((PFFILE_VOLUME_DIRS*)entry.p_vol)->sfds[index].dir_entry.p_vol && - entry.entry_sector == - ((PFFILE_VOLUME_DIRS*)entry.p_vol)->sfds[index].dir_entry.entry_sector && - entry.entry_offset == - ((PFFILE_VOLUME_DIRS*)entry.p_vol)->sfds[index].dir_entry.entry_offset) { - return 8; - } - } - } - if ((entry.attr & 1) != 0 && - ((open_mode & 1) != 0 || (open_mode & 4) != 0 || (open_mode & 8) != 0)) { - return 0xA; - } - if ((entry.attr & 0x10) != 0) { - return 0x17; - } - if ((open_mode & 1) != 0) { - PFFAT_InitFFD(&ffd, &hint, entry.p_vol, &entry.start_cluster); - if (entry.start_cluster > 1 && entry.start_cluster != 0xFFFFFFFF && - entry.file_size != 0) { - PFFAT_FreeChain(&ffd, entry.start_cluster, 0xFFFFFFFF, entry.file_size); - } - entry.start_cluster = 0; - entry.file_size = 0; - PFENT_getcurrentDateTimeForEnt(&entry.modify_date, &entry.modify_time); - entry.access_date = entry.modify_date; - } else { - PFENT_getcurrentDateTimeForEnt(&entry.access_date, &access_time); - } - } else if (error != 0) { - return error; - } - } else { + if ((open_mode & 2) != 0) { PFFAT_InitFFD(&ffd, &hint, entry.p_vol, &entry.start_cluster); error = PFENT_findEntry(&ffd, &entry, 0, &filename, 0x7F, 0); if (error != 0) { @@ -963,37 +888,61 @@ pf_s32 PFFILE_p_fopen(PF_VOLUME* volume, PF_STR* path, pf_u32 open_mode, return 0x17; } PFENT_getcurrentDateTimeForEnt(&entry.access_date, &access_time); + } else { + error = PFFILE_createEmptyFile(volume, &entry, &filename); + if (error == 8) { + if ((open_mode & 0x10) != 0) { + return 8; + } + if ((open_mode & 1) != 0) { + if (file_is_open(&entry) != 0) { return 8; } + } + if ((entry.attr & 1) != 0 && + ((open_mode & 1) != 0 || (open_mode & 4) != 0 || (open_mode & 8) != 0)) { + return 0xA; + } + if ((entry.attr & 0x10) != 0) { + return 0x17; + } + if ((open_mode & 1) != 0) { + if (entry.start_cluster >= 2 && entry.start_cluster != 0xFFFFFFFF && + entry.file_size != 0) { + PFFAT_FreeChain(&iter.ffd, entry.start_cluster, 0xFFFFFFFF, entry.file_size); + } + entry.start_cluster = 0; + entry.file_size = 0; + PFENT_getcurrentDateTimeForEnt(&entry.modify_date, &entry.modify_time); + entry.access_date = entry.modify_date; + } else { + PFENT_getcurrentDateTimeForEnt(&entry.access_date, &access_time); + } + } else if (error != 0) { + return error; + } } volume = entry.p_vol; sfd = PFFILE_GetSFD(volume, &entry); if (sfd == PF_NULL) { return 0x15; } - file = PF_NULL; - for (index = 0; index < 5; index++) { - if ((((PFFILE_VOLUME_DIRS*)volume)->ufds[index].stat & 1) == 0) { - file = &((PFFILE_VOLUME_DIRS*)volume)->ufds[index]; - break; - } - } + file = PFFILE_GetFreeUFD(volume); if (file == PF_NULL) { return 0x16; } file->p_sfd = sfd; file->stat = 1; file->open_mode = open_mode; - file->last_access_data.state.last_access_chain_index = 0; file->last_access_data.state.last_error = 0; file->lock_count = 0; PFFAT_InitHint(&file->hint); - file->cursor.position = 0; file->cursor.sector = 0xFFFFFFFF; + file->cursor.position = 0; PFFILE_Cursor_Recalc(file); if ((open_mode & 1) != 0) { - sfd->stat |= 4; + file->p_sfd->stat |= 4; } - if ((open_mode & 4) != 0) { - file->cursor.position = entry.file_size; + if ((file->open_mode & 4) != 0) { + file->cursor.position = file->p_sfd->dir_entry.file_size; PFFILE_Cursor_Recalc(file); } sfd->handler_count++; @@ -1002,7 +951,26 @@ pf_s32 PFFILE_p_fopen(PF_VOLUME* volume, PF_STR* path, pf_u32 open_mode, } pf_s32 PFFILE_p_fread(PF_VOLUME* volume, pf_u8* buffer, pf_u32 size, pf_u32 count, - PFFILE_FILE* file, pf_u32* count_read); + PFFILE_FILE* file, pf_u32* count_read) { + pf_u32 bytes_read = 0; + pf_s32 error; + + *count_read = 0; + if ((file->open_mode & 8) == 0 && + ((file->open_mode & 1) != 0 || (file->open_mode & 4) != 0)) { + return 0xA; + } + if ((file->p_sfd->lock.mode & 3) != 0 && file->lock_count == 0) { + return 0x19; + } + if (file->cursor.position >= file->p_sfd->dir_entry.file_size) { + return 0x1C; + } + error = PFFILE_Cursor_Read(file, buffer, size * count, &bytes_read); + *count_read = bytes_read / size; + error &= (-error | error) >> 31; + return error; +} pf_s32 PFFILE_p_fwrite(PF_VOLUME* volume, const pf_u8* buffer, pf_u32 size, pf_u32 count, PFFILE_FILE* file, pf_u32* count_written) { @@ -1028,32 +996,30 @@ pf_s32 PFFILE_p_fwrite(PF_VOLUME* volume, const pf_u8* buffer, pf_u32 size, pf_u if (file->cursor.position > file->p_sfd->dir_entry.file_size) { remaining = file->cursor.position - file->p_sfd->dir_entry.file_size; file->cursor.position = file->p_sfd->dir_entry.file_size; - PFFILE_Cursor_Recalc(file); + file->cursor.file_sector_index = file->cursor.position >> volume->bpb.log2_bytes_per_sector; + file->cursor.offset_in_sector = file->cursor.position & (volume->bpb.bytes_per_sector - 1); error = PFCACHE_AllocateDataPage(volume, 0xFFFFFFFF, &page, &allocation_option); if (error != 0) { return error; } pf_memset(page->p_buf, 0, volume->bpb.bytes_per_sector); while (remaining != 0) { - if (remaining <= volume->bpb.bytes_per_sector) { + if (remaining > volume->bpb.bytes_per_sector) { + error = PFFILE_Cursor_Write(file, page->p_buf, volume->bpb.bytes_per_sector, &bytes_written); + if (error != 0) { return error; } + } else { error = PFFILE_Cursor_Write(file, page->p_buf, remaining, &bytes_written); - if (error != 0) { - return error; - } + if (error != 0) { return error; } break; } - error = PFFILE_Cursor_Write(file, page->p_buf, volume->bpb.bytes_per_sector, - &bytes_written); - if (error != 0) { - return error; - } remaining -= volume->bpb.bytes_per_sector; } PFCACHE_FreeDataPage(volume, page); } error = PFFILE_Cursor_Write(file, buffer, size * count, &bytes_written); *count_written = bytes_written / size; - return error; + if (error != 0) { return error; } + return 0; } pf_s32 PFFILE_p_fappend(PFFILE_FILE* file, pf_u32 size, pf_u32* size_appended) { @@ -1126,10 +1092,8 @@ pf_s32 PFFILE_p_combine(PF_VOLUME* volume, PF_STR* first_path, PF_STR* second_pa PFFILE_ENT_ITER second_iter_copy; PF_DIR_ENT first_entry; PF_DIR_ENT second_entry; - PF_FAT_HINT first_hint; - PF_FAT_HINT second_hint; - pf_u32 index; - pf_s32 found; + PFFILE_FAT_HINT first_hint; + PFFILE_FAT_HINT second_hint; pf_s32 error; error = PFENT_ITER_GetEntryOfPath(&first_iter, &first_entry, volume, first_path, 0); @@ -1146,41 +1110,12 @@ pf_s32 PFFILE_p_combine(PF_VOLUME* volume, PF_STR* first_path, PF_STR* second_pa if ((first_entry.attr & 1) != 0 || (second_entry.attr & 1) != 0) { return 0x18; } - found = 0; - for (index = 0; index < 5; index++) { - PFFILE_SFD* sfd = &((PFFILE_VOLUME_DIRS*)first_entry.p_vol)->sfds[index]; - - if ((sfd->stat & 1) != 0 && (sfd->stat & 2) != 0 && - first_entry.p_vol == sfd->dir_entry.p_vol && - first_entry.entry_sector == sfd->dir_entry.entry_sector && - first_entry.entry_offset == sfd->dir_entry.entry_offset) { - found = 1; - break; - } - } - if (found != 0) { - return 0x13; - } - found = 0; - for (index = 0; index < 5; index++) { - PFFILE_SFD* sfd = &((PFFILE_VOLUME_DIRS*)second_entry.p_vol)->sfds[index]; - - if ((sfd->stat & 1) != 0 && (sfd->stat & 2) != 0 && - second_entry.p_vol == sfd->dir_entry.p_vol && - second_entry.entry_sector == sfd->dir_entry.entry_sector && - second_entry.entry_offset == sfd->dir_entry.entry_offset) { - found = 1; - break; - } - } - if (found != 0) { - return 0x13; - } + if (file_is_open(&first_entry) != 0 || file_is_open(&second_entry) != 0) { return 0x13; } if (first_entry.entry_sector == second_entry.entry_sector && first_entry.entry_offset == second_entry.entry_offset) { return 0xA; } - if (0xFFFFFFFF - second_entry.file_size < first_entry.file_size) { + if (0xFFFFFFFF - first_entry.file_size < second_entry.file_size) { return 0x25; } PFFAT_InitHint(&first_hint); @@ -1204,24 +1139,20 @@ pf_s32 PFFILE_p_combine(PF_VOLUME* volume, PF_STR* first_path, PF_STR* second_pa pf_s32 PFFILE_p_divide(PF_VOLUME* volume, PF_STR* source_path, PF_STR* destination_path, pf_u32 split_size) { - PF_STR destination_directory; PF_STR destination_filename; + PF_STR destination_directory; PF_DIR_ENT source_entry; - PF_DIR_ENT source_entry_copy; PF_DIR_ENT destination_entry; + PF_DIR_ENT source_entry_copy; PFFILE_ENT_ITER source_iter; PFFILE_ENT_ITER destination_iter; - PFFILE_ENT_ITER destination_file_iter; - PFFILE_FFD source_ffd; - PFFILE_FFD destination_ffd; - PF_FAT_HINT source_hint; - PF_FAT_HINT destination_hint; + PFFILE_FAT_HINT source_hint; + PFFILE_FAT_HINT destination_hint; pf_s8 normalized_filename[0x200]; - pf_u32 original_start_cluster; pf_u32 original_size; - pf_u32 index; - pf_u16 current_time; + pf_u32 original_start_cluster; pf_s32 error; + pf_s32 divide_error; error = PFENT_ITER_GetEntryOfPath(&source_iter, &source_entry, volume, source_path, 0); if (error != 0) { @@ -1233,17 +1164,7 @@ pf_s32 PFFILE_p_divide(PF_VOLUME* volume, PF_STR* source_path, PF_STR* destinati if ((source_entry.attr & 1) != 0) { return 0x18; } - for (index = 0; index < 5; index++) { - if ((((PFFILE_VOLUME_DIRS*)source_entry.p_vol)->sfds[index].stat & 3) == 3 && - source_entry.p_vol == - ((PFFILE_VOLUME_DIRS*)source_entry.p_vol)->sfds[index].dir_entry.p_vol && - source_entry.entry_sector == - ((PFFILE_VOLUME_DIRS*)source_entry.p_vol)->sfds[index].dir_entry.entry_sector && - source_entry.entry_offset == - ((PFFILE_VOLUME_DIRS*)source_entry.p_vol)->sfds[index].dir_entry.entry_offset) { - return 0x13; - } - } + if (file_is_open(&source_entry) != 0) { return 0x13; } if (source_entry.file_size == 0) { return 0xA; } @@ -1255,7 +1176,7 @@ pf_s32 PFFILE_p_divide(PF_VOLUME* volume, PF_STR* source_path, PF_STR* destinati return 1; } if (PFSTR_GetCodeMode(&destination_filename) == 2) { - if ((PFSTR_StrNumChar(&destination_filename, 1) & 0xFFFF) > 0xFF) { + if ((pf_s32)(PFSTR_StrNumChar(&destination_filename, 1) & 0xFFFF) > 0xFF) { return 1; } PFPATH_transformFromUnicodeToNormal( @@ -1274,13 +1195,13 @@ pf_s32 PFFILE_p_divide(PF_VOLUME* volume, PF_STR* source_path, PF_STR* destinati if (error != 0) { return error; } - PFFAT_InitHint(&destination_hint); - PFFAT_InitFFD(&destination_ffd, &destination_hint, volume, &destination_entry.start_cluster); PFFAT_InitHint(&source_hint); - PFFAT_InitFFD(&source_ffd, &source_hint, volume, &source_entry.start_cluster); + PFFAT_InitFFD(&source_iter.ffd, &source_hint, volume, &source_entry.start_cluster); + PFFAT_InitHint(&destination_hint); + PFFAT_InitFFD(&destination_iter.ffd, &destination_hint, volume, &destination_entry.start_cluster); pf_memcpy(&source_entry_copy, &source_entry, sizeof(source_entry_copy)); - original_start_cluster = source_entry.start_cluster; original_size = source_entry.file_size; + original_start_cluster = source_entry.start_cluster; PFENT_getcurrentDateTimeForEnt(&source_entry.modify_date, &source_entry.modify_time); source_entry.access_date = source_entry.modify_date; if (split_size == 0) { @@ -1288,32 +1209,30 @@ pf_s32 PFFILE_p_divide(PF_VOLUME* volume, PF_STR* source_path, PF_STR* destinati } source_entry.file_size = split_size; error = PFENT_updateEntry(&source_entry, 1); - if (error == 0 && - ((((PFFILE_VOLUME_DIRS*)volume)->cache_control & 4) == 0 || - PFCACHE_FlushDataCacheSpecific(volume, 0) == 0)) { - error = PFCLUSTER_DivideFile(&source_iter, &destination_iter, &source_entry_copy, - &destination_entry, split_size); - if (error == 0) { - destination_entry.create_time = source_entry.modify_time; - destination_entry.create_date = source_entry.modify_date; - destination_entry.modify_time = source_entry.modify_time; - destination_entry.modify_date = source_entry.modify_date; - destination_entry.access_date = source_entry.access_date; - destination_entry.attr = source_entry.attr; - error = PFENT_updateEntry(&destination_entry, 1); - return error & (-error | error) >> 31; - } - PFCACHE_FlushFATCache(volume); - source_entry.start_cluster = original_start_cluster; - source_entry.file_size = original_size; - PFENT_updateEntry(&source_entry, 1); - error = PFENT_ITER_GetEntryOfPath(&destination_file_iter, &destination_entry, volume, - destination_path, 0); - if (error == 0) { - PFENT_RemoveEntry(&destination_entry, &destination_file_iter); - } + if (error != 0) { return error; } + if ((((PFFILE_VOLUME_DIRS*)volume)->cache_control & 4) != 0) { + error = PFCACHE_FlushDataCacheSpecific(volume, 0); + if (error != 0) { return error; } } - return error; + error = PFCLUSTER_DivideFile(&source_iter, &destination_iter, &source_entry_copy, + &destination_entry, split_size); + divide_error = error; + if (error != 0) { + PFCACHE_FlushFATCache(volume); + source_entry.file_size = original_size; + source_entry.start_cluster = original_start_cluster; + PFENT_updateEntry(&source_entry, 1); + PFENT_ITER_GetEntryOfPath(&destination_iter, &destination_entry, volume, + destination_path, 0); + PFENT_RemoveEntry(&destination_entry, &destination_iter); + return divide_error; + } + destination_entry.modify_date = source_entry.modify_date; + destination_entry.modify_time = source_entry.modify_time; + destination_entry.access_date = source_entry.access_date; + destination_entry.attr = source_entry.attr; + error = PFENT_updateEntry(&destination_entry, 1); + return error & (-error | error) >> 31; } pf_s32 PFFILE_p_cinsert(PF_VOLUME* volume, PF_STR* path, pf_u32 cluster_index, @@ -1403,20 +1322,15 @@ pf_s32 PFFILE_p_cdelete(PF_VOLUME* volume, PF_STR* path, pf_u32 cluster_index, pf_s32 PFFILE_p_flock(PFFILE_FILE* file, pf_u32 mode) { if ((mode & 3) != 0) { - if ((file->p_sfd->lock.mode & 3) != 0 && (mode & 0x10) != 0) { - if ((mode & 1) != 0) { - if ((file->p_sfd->lock.mode & 2) != 0) { - return 0x27; - } - } else if ((mode & 2) != 0 && (file->p_sfd->lock.mode & 1) != 0) { - return 0x27; - } - if (file->p_sfd->lock.owner != 0 && file->p_sfd->lock.owner != (PF_FILE*)file) { + if ((file->p_sfd->lock.mode & 3) != 0 && (mode & 8) != 0) { + if (((mode & 1) != 0 && (file->p_sfd->lock.mode & 2) != 0) || + ((mode & 2) != 0 && (file->p_sfd->lock.mode & 1) != 0) || + (file->p_sfd->lock.owner != 0 && file->p_sfd->lock.owner != (PF_FILE*)file)) { return 0x27; } } if ((mode & 1) != 0) { - if (file->p_sfd->lock.count == 0 || (file->p_sfd->lock.mode & 2) == 0) { + if (file->p_sfd->lock.count == 0 || (file->p_sfd->lock.mode & 2) != 0) { file->p_sfd->lock.wcount++; PF_LockFile((PF_FILE*)file, 0); file->p_sfd->lock.wcount--; @@ -1432,7 +1346,7 @@ pf_s32 PFFILE_p_flock(PFFILE_FILE* file, pf_u32 mode) { } file->p_sfd->lock.count++; file->lock_count++; - return 0; + goto complete; } if (file->lock_count == 0 || file->p_sfd->lock.count == 0) { return 0x27; @@ -1440,23 +1354,14 @@ pf_s32 PFFILE_p_flock(PFFILE_FILE* file, pf_u32 mode) { if ((file->p_sfd->lock.mode & 2) != 0 && file->p_sfd->lock.owner != (PF_FILE*)file) { return 0x27; } - if ((file->p_sfd->lock.mode & 1) != 0) { - file->p_sfd->lock.count -= file->lock_count; - file->lock_count = 0; - if (file->p_sfd->lock.count == 0) { - PF_UnLockFile((PF_FILE*)file); - } - file->p_sfd->lock.mode &= ~3; - } else { - if (file->p_sfd->lock.owner != (PF_FILE*)file) { - return 0x27; - } - file->p_sfd->lock.count = 0; - file->lock_count = 0; - file->p_sfd->lock.owner = 0; + file->lock_count--; + file->p_sfd->lock.count--; + if (file->p_sfd->lock.count == 0) { PF_UnLockFile((PF_FILE*)file); + if ((file->p_sfd->lock.mode & 2) != 0) { file->p_sfd->lock.owner = 0; } file->p_sfd->lock.mode &= ~3; } +complete: return 0; } @@ -1708,10 +1613,12 @@ close_file_complete: pf_s32 PFFILE_fread(pf_u8* buffer, pf_u32 size, pf_u32 count, PFFILE_FILE* file, pf_u32* count_read) { - PF_VOLUME* volume = file == PF_NULL ? PF_NULL : file->p_sfd->dir_entry.p_vol; + PF_VOLUME* volume; pf_s32 error; + pf_u32 completed_count; *count_read = 0; + volume = file == PF_NULL ? PF_NULL : file->p_sfd->dir_entry.p_vol; error = PFVOL_CheckForRead(volume); if (error != 0) { pf_vol_set.last_error = error; @@ -1724,7 +1631,8 @@ pf_s32 PFFILE_fread(pf_u8* buffer, pf_u32 size, pf_u32 count, return 0x26; } ((PFFILE_VOLUME_DIRS*)volume)->cache_signature = file; - error = PFFILE_p_fread(volume, buffer, size, count, file, count_read); + error = PFFILE_p_fread(volume, buffer, size, count, file, &completed_count); + *count_read = completed_count; ((PFFILE_VOLUME_DIRS*)volume)->cache_signature = PF_NULL; if (error != 0) { pf_vol_set.last_error = error; @@ -1869,8 +1777,8 @@ pf_s32 PFFILE_fsetclstlink(PFFILE_FILE* file, pf_u32 mode, file->p_sfd->ffd.cluster_link.interval_offset = 0; file->p_sfd->ffd.cluster_link.position = 0; file->p_sfd->ffd.cluster_link.save_index = 0; - if (file->p_sfd->dir_entry.file_size != 0 && settings->link_max != 0) { - settings->buffer[0] = *file->p_sfd->ffd.p_start_cluster; + if (file->p_sfd->dir_entry.file_size != 0 && file->p_sfd->ffd.cluster_link.max_count != 0) { + file->p_sfd->ffd.cluster_link.buffer[0] = *file->p_sfd->ffd.p_start_cluster; file->p_sfd->ffd.cluster_link.position++; } if (file->p_sfd->ffd.p_hint != PF_NULL) { @@ -2217,25 +2125,3 @@ pf_s32 PFFILE_flock(PFFILE_FILE* file, pf_u32 mode) { } return error; } - -pf_s32 PFFILE_p_fread(PF_VOLUME* volume, pf_u8* buffer, pf_u32 size, pf_u32 count, - PFFILE_FILE* file, pf_u32* count_read) { - pf_u32 bytes_read = 0; - pf_s32 error; - - *count_read = 0; - if ((file->open_mode & 8) == 0 && - ((file->open_mode & 1) != 0 || (file->open_mode & 4) != 0)) { - return 0xA; - } - if ((file->p_sfd->lock.mode & 3) != 0 && file->lock_count == 0) { - return 0x19; - } - if (file->cursor.position >= file->p_sfd->dir_entry.file_size) { - return 0x1C; - } - error = PFFILE_Cursor_Read(file, buffer, size * count, &bytes_read); - *count_read = bytes_read / size; - error &= (-error | error) >> 31; - return error; -} diff --git a/libs/RVL_SDK/src/fa/pf_volume.c b/libs/RVL_SDK/src/fa/pf_volume.c index 87af2a9f..9f8db06c 100644 --- a/libs/RVL_SDK/src/fa/pf_volume.c +++ b/libs/RVL_SDK/src/fa/pf_volume.c @@ -169,7 +169,8 @@ typedef struct PFVOL_CLUSTER_SETTING { struct PFVOL_VOLUME { PFVOL_BPB bpb; u32 num_free_clusters; - u8 gap_003C[0xD10]; + u32 last_free_cluster; + u8 gap_0040[0xD0C]; PFVOL_OPEN_FILE files[5]; u8 gap_0E3C[0x7E0]; u32 num_open_files; @@ -190,8 +191,10 @@ struct PFVOL_VOLUME { u32 last_driver_error; u32 reserved_1f88; u16 flags; - u16 options; + s8 drv_char; + u8 drive_state; u16 fsi_flag; + u16 reserved_1f92; u16 cluster_link_flags; u16 cluster_link_interval; u32* cluster_link_buffer; @@ -286,6 +289,95 @@ extern s32 PFCODE_CP932_isUnicodeMBchar(u16 value, s32 mode); extern void* pf_memset(void* dst, int value, u32 size); extern s32 pf_memcmp(const void* left, const void* right, u32 size); +static inline u32 check_context_registered(s32 context_id) { + u32 index; + for (index = 1; index < 4; index++) { + if ((pf_vol_set.context[index - 1].stat &= 1) != 0 && + context_id == pf_vol_set.context[index - 1].context_id) { return 1; } + } + return 0; +} +static inline s32 clear_mount(PFVOL_VOLUME* volume) { + s32 error; + if ((volume->flags & 8) == 0) { + error = PFVOL_DoMountVolume(volume); + if (error != 0) { return error; } + volume->fsi_flag &= ~7; + PFDRV_ClearUnmountRequested(volume); + pf_vol_set.num_mounted_volumes++; + } + PFDRV_ClearMountRequested(volume); + return 0; +} +static inline s32 clear_unmount(PFVOL_VOLUME* volume, u32 mode) { + s32 error = PFDRV_unmount(volume, mode); + if (error != 0) { return error; } + if (volume->flags & 8) { + volume->current_dir[0].stat = 0; + volume->current_dir[1].stat = 0; + volume->current_dir[2].stat = 0; + volume->current_dir[3].stat = 0; + } + volume->flags &= ~8; + return 0; +} +static inline s32 check_driver_requests(PFVOL_VOLUME* volume) { + s32 error; + if (PFDRV_IsInserted(volume) != 0) { + if (PFDRV_IsUnmountRequested(volume) != 0 && (volume->flags & 8) == 0) { + PFFILE_FinalizeAllFiles(volume); + PFDIR_FinalizeAllDirs(volume); + clear_unmount(volume, 1); + PFDRV_ClearUnmountRequested(volume); + pf_vol_set.num_mounted_volumes--; + } + if (PFDRV_IsMountRequested(volume) != 0) { + error = clear_mount(volume); + if (error != 0) { return error; } + } + } else { + if (PFDRV_IsUnmountRequested(volume) != 0 && (volume->flags & 8) == 0) { + PFFILE_FinalizeAllFiles(volume); + PFDIR_FinalizeAllDirs(volume); + clear_unmount(volume, 1); + PFDRV_ClearUnmountRequested(volume); + pf_vol_set.num_mounted_volumes--; + } + if (PFDRV_IsMountRequested(volume) != 0) { PFDRV_ClearMountRequested(volume); } + } + return 0; +} +static inline s32 init_current_dir(PFVOL_VOLUME* volume) { + s32 error; + s32 context_id; + u32 index; + if ((volume->flags & 8) == 0) { return 9; } + PFSYS_GetCurrentContextID(&context_id); + volume->current_dir[0].stat |= 1; + if (check_context_registered(context_id)) { + volume->current_dir[1].stat |= 1; + volume->current_dir[1].context_id = context_id; + } + for (index = 0; index < 4; index++) { + error = PFENT_GetRootDir(volume, &volume->current_dir[index].directory); + if (error != 0) { return error; } + } + return 0; +} +static inline s32 finalize_volume(PFVOL_VOLUME* volume) { + s32 error = PFDRV_finalize(volume); + if (error != 0) { return error; } + return 0; +} +static inline s32 copy_codeset(const PFVOL_CHARCODE* code_set) { + pf_vol_set.codeset.oem2unicode = code_set->oem2unicode; + pf_vol_set.codeset.unicode2oem = code_set->unicode2oem; + pf_vol_set.codeset.oem_char_width = code_set->oem_char_width; + pf_vol_set.codeset.is_oem_mb_char = code_set->is_oem_mb_char; + pf_vol_set.codeset.unicode_char_width = code_set->unicode_char_width; + pf_vol_set.codeset.is_unicode_mb_char = code_set->is_unicode_mb_char; + return 0; +} s32 PFVOL_DoMountVolume(PFVOL_VOLUME* volume) { s32 error; s32 context_id; @@ -310,29 +402,7 @@ s32 PFVOL_DoMountVolume(PFVOL_VOLUME* volume) { return error; } volume->flags |= 8; - if ((volume->flags & 8) == 0) { - return 9; - } - error = PFSYS_GetCurrentContextID(&context_id); - volume->current_dir[0].stat |= 1; - context_registered = 0; - for (i = 0; i < 3; i++) { - pf_vol_set.context[i].stat &= 1; - if (pf_vol_set.context[i].stat != 0 && pf_vol_set.context[i].context_id == context_id) { - context_registered = 1; - break; - } - } - if (context_registered != 0) { - volume->current_dir[0].stat |= 1; - volume->current_dir[0].context_id = context_id; - } - for (i = 0; i < 4; i++) { - error = PFENT_GetRootDir(volume, &volume->current_dir[i].directory); - if (error != 0) { - break; - } - } + error = init_current_dir(volume); if (error == 0 && (volume->flags & 0x40) != 0) { error = PFDRV_format(volume, volume->format_options); if (error == 0 && (volume->flags & 0x80) == 0) { @@ -363,19 +433,7 @@ s32 PFVOL_p_unmount(PFVOL_VOLUME* volume, u32 mode) { } if (error == 0 || (mode & 1) != 0) { PFCACHE_FreeAllCaches(volume); - error = PFDRV_unmount(volume, mode); - if (error != 0) { - goto unmount_done; - } - if ((volume->flags & 8) != 0) { - volume->current_dir[0].stat = 0; - volume->current_dir[1].stat = 0; - volume->current_dir[2].stat = 0; - volume->current_dir[3].stat = 0; - } - error = 0; - volume->flags &= ~8; -unmount_done: + error = clear_unmount(volume, mode); if (error != 0 && prior_error == 0) { prior_error = error; } @@ -388,74 +446,46 @@ unmount_done: return prior_error; } +static inline s32 initialize_fat(PFVOL_VOLUME* volume) { + s32 error = PFFAT_InitFATRegion(volume); + if (error != 0) { return error; } + error = PFENT_MakeRootDir(volume); + if (error != 0) { return error; } + if (volume->bpb.fat_type != 2) { volume->fsi_flag &= ~3; } + if (volume->bpb.fat_type == 2 && (volume->fsi_flag & 2) != 0) { + error = PFFAT_RefreshFSINFO(volume); + if (error != 0) { return error; } + } + return 0; +} s32 PFVOL_p_format(PFVOL_VOLUME* volume, const u8* format_options) { s32 error; u32 free_clusters; - - if (volume == 0) { - return 10; - } - if ((volume->flags & 2) != 0) { - return 11; - } + if (volume == 0) { return 10; } + if ((volume->flags & 2) != 0) { return 11; } error = PFDRV_format(volume, format_options); - if (error != 0) { - return error; - } + if (error != 0) { return error; } if ((volume->flags & 8) != 0) { PFCACHE_FreeAllCaches(volume); error = PFVOL_p_unmount(volume, 0); - if (error != 0) { - return error; - } + if (error != 0) { return error; } } - if ((volume->flags & 8) == 0) { - error = PFVOL_DoMountVolume(volume); - if (error != 0) { - goto mount_done; - } - volume->fsi_flag &= ~7; - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes++; - } - PFDRV_ClearMountRequested(volume); - error = 0; -mount_done: - if (error == 0) { - if ((volume->flags & 2) != 0) { - error = 11; - } else if ((volume->flags & 0x80) == 0) { - error = PFFAT_InitFATRegion(volume); - if (error == 0) { - error = PFENT_MakeRootDir(volume); - if (error == 0) { - if (volume->bpb.fat_type != 2) { - volume->fsi_flag &= ~3; - } - if ((volume->bpb.fat_type != 2 || (volume->fsi_flag & 2) == 0) || - (error = PFFAT_RefreshFSINFO(volume)) == 0) { - error = 0; - } - } - } + error = clear_mount(volume); + if (error != 0) { return error; } + if ((volume->flags & 2) != 0) { return 11; } + if ((volume->flags & 0x80) != 0) { + if (volume->bpb.fat_type == 2 && (volume->fsi_flag & 2) != 0) { + volume->fsi_flag |= 4; + PFFAT_RefreshFSINFO(volume); } else { - if (volume->bpb.fat_type == 2 && (volume->fsi_flag & 2) != 0) { - volume->fsi_flag |= 4; - PFFAT_RefreshFSINFO(volume); - } else { - volume->fsi_flag &= ~4; - if (volume->bpb.fat_type != 2) { - volume->fsi_flag &= ~7; - } - error = PFFAT_CountFreeClusters(volume, &free_clusters); - if (error != 0) { - return error; - } - } - error = 0; + volume->fsi_flag &= ~4; + if (volume->bpb.fat_type != 2) { volume->fsi_flag &= ~3; } + error = PFFAT_CountFreeClusters(volume, &free_clusters); + if (error != 0) { return error; } } + return 0; } - return error; + return initialize_fat(volume); } s32 PFVOL_p_setvol(PFVOL_VOLUME* volume, const s8* label) { @@ -506,8 +536,6 @@ s32 PFVOL_p_setvol(PFVOL_VOLUME* volume, const s8* label) { PFENT_getcurrentDateTimeForEnt(&entry.modify_date, &entry.modify_time); error = PFENT_updateEntry(&entry, 0); } - } else { - return error; } return error; } @@ -556,7 +584,7 @@ s32 PFVOL_p_rmvvol(PFVOL_VOLUME* volume) { u32 logical_position; u32 entry_position; u32 processed; - u8 deleted = 0xE5; + u8 deleted = (u8)"\xE5"[0]; s32 error; error = PFENT_GetRootDir(volume, &root_entry); @@ -627,161 +655,22 @@ s32 PFVOL_InitModule(u32 config, void* user_data) { (volume)->current_dir[3].stat = 0; \ } while (0) -#define PFVOL_UPDATE_DRIVER_REQUESTS(volume, result) \ - do { \ - if (PFDRV_IsInserted(volume) == 0) { \ - if (PFDRV_IsUnmountRequested(volume) != 0 && ((volume)->flags & 8) == 0) { \ - PFFILE_FinalizeAllFiles(volume); \ - PFDIR_FinalizeAllDirs(volume); \ - (result) = PFDRV_unmount(volume, 1); \ - if ((result) == 0) { \ - if (((volume)->flags & 8) != 0) { \ - PFVOL_CLEAR_CURRENT_DIRS(volume); \ - } \ - (volume)->flags &= ~8; \ - } \ - PFDRV_ClearUnmountRequested(volume); \ - pf_vol_set.num_mounted_volumes--; \ - } \ - if (PFDRV_IsMountRequested(volume) != 0) { \ - PFDRV_ClearMountRequested(volume); \ - } \ - (result) = 0; \ - } else { \ - if (PFDRV_IsUnmountRequested(volume) != 0 && ((volume)->flags & 8) == 0) { \ - PFFILE_FinalizeAllFiles(volume); \ - PFDIR_FinalizeAllDirs(volume); \ - (result) = PFDRV_unmount(volume, 1); \ - if ((result) == 0) { \ - if (((volume)->flags & 8) != 0) { \ - PFVOL_CLEAR_CURRENT_DIRS(volume); \ - } \ - (volume)->flags &= ~8; \ - } \ - PFDRV_ClearUnmountRequested(volume); \ - pf_vol_set.num_mounted_volumes--; \ - } \ - if (PFDRV_IsMountRequested(volume) != 0) { \ - if (((volume)->flags & 8) == 0) { \ - (result) = PFVOL_DoMountVolume(volume); \ - if ((result) == 0) { \ - (volume)->fsi_flag &= ~7; \ - PFDRV_ClearUnmountRequested(volume); \ - pf_vol_set.num_mounted_volumes++; \ - } \ - } \ - if (((volume)->flags & 8) != 0 || (result) == 0) { \ - PFDRV_ClearMountRequested(volume); \ - (result) = 0; \ - } \ - } else { \ - (result) = 0; \ - } \ - } \ - } while (0) +#define PFVOL_UPDATE_DRIVER_REQUESTS(volume, result) ((result) = check_driver_requests(volume)) -s32 PFVOL_CheckForRead(PFVOL_VOLUME* volume) { - s32 error; - - if (PFDRV_IsUnmountRequested(volume) != 0 && (volume->flags & 8) == 0) { - PFFILE_FinalizeAllFiles(volume); - PFDIR_FinalizeAllDirs(volume); - error = PFDRV_unmount(volume, 1); - if (error == 0) { - if ((volume->flags & 8) != 0) { - PFVOL_CLEAR_CURRENT_DIRS(volume); - } - volume->flags &= ~8; - } - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes--; - } - if (PFDRV_IsInserted(volume) == 0) { - if (PFDRV_IsMountRequested(volume) != 0) { - PFDRV_ClearMountRequested(volume); - } - } else if (PFDRV_IsMountRequested(volume) != 0) { - if ((volume->flags & 8) == 0) { - error = PFVOL_DoMountVolume(volume); - if (error != 0) { - goto check_result; - } - volume->fsi_flag &= ~7; - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes++; - } - PFDRV_ClearMountRequested(volume); - error = 0; - } - error = 0; -check_result: - if (error == 0) { - error = (((volume->flags >> 3) & 1) - 1) & 9; - } - return error; +static inline s32 check_read(PFVOL_VOLUME* volume) { + s32 error = check_driver_requests(volume); + if (error != 0) { return error; } + return (volume->flags & 8) ? 0 : 9; } - -s32 PFVOL_CheckForWrite(PFVOL_VOLUME* volume) { - s32 error = 0; - - if (PFDRV_IsInserted(volume) == 0) { - if (PFDRV_IsUnmountRequested(volume) != 0 && (volume->flags & 8) == 0) { - PFFILE_FinalizeAllFiles(volume); - PFDIR_FinalizeAllDirs(volume); - error = PFDRV_unmount(volume, 1); - if (error == 0) { - if ((volume->flags & 8) != 0) { - PFVOL_CLEAR_CURRENT_DIRS(volume); - } - volume->flags &= ~8; - } - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes--; - } - if (PFDRV_IsMountRequested(volume) != 0) { - PFDRV_ClearMountRequested(volume); - } - } else { - if (PFDRV_IsUnmountRequested(volume) != 0 && (volume->flags & 8) == 0) { - PFFILE_FinalizeAllFiles(volume); - PFDIR_FinalizeAllDirs(volume); - error = PFDRV_unmount(volume, 1); - if (error == 0) { - if ((volume->flags & 8) != 0) { - PFVOL_CLEAR_CURRENT_DIRS(volume); - } - volume->flags &= ~8; - } - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes--; - } - if (PFDRV_IsMountRequested(volume) != 0) { - if ((volume->flags & 8) == 0) { - error = PFVOL_DoMountVolume(volume); - if (error == 0) { - volume->fsi_flag &= ~7; - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes++; - PFDRV_ClearMountRequested(volume); - error = 0; - } - } else { - PFDRV_ClearMountRequested(volume); - error = 0; - } - if (error != 0) { - return error; - } - } - } - if ((volume->flags & 8) == 0) { - return 9; - } - if ((volume->flags & 2) != 0) { - return 11; - } +static inline s32 check_write(PFVOL_VOLUME* volume) { + s32 error = check_driver_requests(volume); + if (error != 0) { return error; } + if ((volume->flags & 8) == 0) { return 9; } + if ((volume->flags & 2) != 0) { return 11; } return 0; } +s32 PFVOL_CheckForRead(PFVOL_VOLUME* volume) { return check_read(volume); } +s32 PFVOL_CheckForWrite(PFVOL_VOLUME* volume) { return check_write(volume); } s32 PFVOL_CheckCurrentDir(PFVOL_VOLUME* volume, u32 start_cluster) { s32 context_id; @@ -825,16 +714,7 @@ s32 PFVOL_SetCurrentDir(PFVOL_VOLUME* volume, PFVOL_DIR_ENTRY* directory) { } } if (current_dir_index == 4) { - if (((pf_vol_set.context[0].stat &= 1) != 0 && - context_id == pf_vol_set.context[0].context_id) || - ((pf_vol_set.context[1].stat &= 1) != 0 && - context_id == pf_vol_set.context[1].context_id) || - ((pf_vol_set.context[2].stat &= 1) != 0 && - context_id == pf_vol_set.context[2].context_id)) { - context_registered = 1; - } else { - context_registered = 0; - } + context_registered = check_context_registered(context_id); if (context_registered != 0) { for (current_dir_index = 1; current_dir_index < 4; current_dir_index++) { if ((volume->current_dir[current_dir_index].stat & 1) == 0) { @@ -868,16 +748,7 @@ s32 PFVOL_GetCurrentDir(PFVOL_VOLUME* volume, PFVOL_DIR_ENTRY* directory) { } } if (current_dir_index == 4) { - if (((pf_vol_set.context[0].stat &= 1) != 0 && - context_id == pf_vol_set.context[0].context_id) || - ((pf_vol_set.context[1].stat &= 1) != 0 && - context_id == pf_vol_set.context[1].context_id) || - ((pf_vol_set.context[2].stat &= 1) != 0 && - context_id == pf_vol_set.context[2].context_id)) { - context_registered = 1; - } else { - context_registered = 0; - } + context_registered = check_context_registered(context_id); if (context_registered != 0) { for (current_dir_index = 1; current_dir_index < 4; current_dir_index++) { if ((volume->current_dir[current_dir_index].stat & 1) == 0) { @@ -909,14 +780,7 @@ void PFVOL_SetCurrentVolume(PFVOL_VOLUME* volume) { } } if (context_index == 4) { - for (context_index = 1; context_index < 4; context_index++) { - pf_vol_set.context[context_index - 1].stat &= 1; - if (pf_vol_set.context[context_index - 1].stat != 0 && - pf_vol_set.context[context_index - 1].context_id == context_id) { - context_registered = 1; - break; - } - } + context_registered = check_context_registered(context_id); if (context_registered != 0) { for (context_index = 1; context_index < 4; context_index++) { if ((pf_vol_set.context_volume[context_index - 1].stat & 1) == 0) { @@ -947,14 +811,7 @@ PFVOL_VOLUME* PFVOL_GetCurrentVolume(void) { } } if (context_index == 4) { - for (context_index = 1; context_index < 4; context_index++) { - pf_vol_set.context[context_index - 1].stat &= 1; - if (pf_vol_set.context[context_index - 1].stat != 0 && - pf_vol_set.context[context_index - 1].context_id == context_id) { - context_registered = 1; - break; - } - } + context_registered = check_context_registered(context_id); if (context_registered != 0) { for (context_index = 1; context_index < 4; context_index++) { if ((pf_vol_set.context_volume[context_index - 1].stat & 1) == 0) { @@ -1012,66 +869,11 @@ void PFVOL_setvol(s8 drive, const s8* label) { volume = &pf_vol_set.volumes[volume_index]; } label_length = PFSTR_StrLen(label); - error = PFDRV_IsInserted(volume); + error = check_write(volume); if (error != 0) { - if (PFDRV_IsUnmountRequested(volume) != 0 && (volume->flags & 8) == 0) { - PFFILE_FinalizeAllFiles(volume); - PFDIR_FinalizeAllDirs(volume); - error = PFDRV_unmount(volume, 1); - if (error == 0) { - if ((volume->flags & 8) != 0) { - PFVOL_CLEAR_CURRENT_DIRS(volume); - } - volume->flags &= ~8; - } - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes--; - } - error = PFDRV_IsMountRequested(volume); - if (error != 0) { - if ((volume->flags & 8) == 0) { - error = PFVOL_DoMountVolume(volume); - if (error == 0) { - volume->fsi_flag &= ~7; - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes++; - PFDRV_ClearMountRequested(volume); - error = 0; - } - } else { - PFDRV_ClearMountRequested(volume); - error = 0; - } - if (error != 0) { - goto save_error; - } - } - } else { - if (PFDRV_IsUnmountRequested(volume) != 0 && (volume->flags & 8) == 0) { - PFFILE_FinalizeAllFiles(volume); - PFDIR_FinalizeAllDirs(volume); - error = PFDRV_unmount(volume, 1); - if (error == 0) { - if ((volume->flags & 8) != 0) { - PFVOL_CLEAR_CURRENT_DIRS(volume); - } - volume->flags &= ~8; - } - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes--; - } - if (PFDRV_IsMountRequested(volume) != 0) { - PFDRV_ClearMountRequested(volume); - } - } - error = 0; - if ((volume->flags & 8) == 0) { - error = 9; - } else if ((volume->flags & 2) != 0) { - error = 11; - } - if (error != 0) { - goto save_error; + pf_vol_set.last_error = error; + volume->last_error = error; + return; } PFSTR_ToUpperNStr(label, 11, upper_label); if (label_length < 11) { @@ -1079,26 +881,25 @@ void PFVOL_setvol(s8 drive, const s8* label) { } error = PFVOL_p_setvol(volume, upper_label); if (error != 0) { - goto save_error; + pf_vol_set.last_error = error; + volume->last_error = error; + return; } error = PFCACHE_FlushFATCache(volume); - if (error != 0) { - goto save_error; - } - error = PFCACHE_FlushDataCacheSpecific(volume, 0); - if (error != 0) { - goto save_error; + if (error != 0) { pf_vol_set.last_error = error; volume->last_error = error; } + else { + error = PFCACHE_FlushDataCacheSpecific(volume, 0); + if (error != 0) { pf_vol_set.last_error = error; volume->last_error = error; } } + if (error != 0) { return; } error = PFDRV_StoreVolumeLabelToBPB(volume, upper_label); if (error != 0) { - goto save_error; + pf_vol_set.last_error = error; + volume->last_error = error; + return; } return; -save_error: - pf_vol_set.last_error = error; - volume->last_error = error; - return; } s32 PFVOL_getvol(s8 drive, PFVOL_VOLUME_INFO* volume_info) { @@ -1117,74 +918,20 @@ s32 PFVOL_getvol(s8 drive, PFVOL_VOLUME_INFO* volume_info) { volume->last_error = 3; return 3; } - if (PFDRV_IsInserted(volume) != 0) { - if (PFDRV_IsUnmountRequested(volume) != 0 && (volume->flags & 8) == 0) { - PFFILE_FinalizeAllFiles(volume); - PFDIR_FinalizeAllDirs(volume); - error = PFDRV_unmount(volume, 1); - if (error == 0) { - if ((volume->flags & 8) != 0) { - PFVOL_CLEAR_CURRENT_DIRS(volume); - } - volume->flags &= ~8; - } - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes--; - } - error = PFDRV_IsMountRequested(volume); - if (error != 0) { - if ((volume->flags & 8) == 0) { - error = PFVOL_DoMountVolume(volume); - if (error == 0) { - volume->fsi_flag &= ~7; - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes++; - PFDRV_ClearMountRequested(volume); - error = 0; - } - } else { - PFDRV_ClearMountRequested(volume); - error = 0; - } - if (error != 0) { - goto save_error; - } - } - } else { - if (PFDRV_IsUnmountRequested(volume) != 0 && (volume->flags & 8) == 0) { - PFFILE_FinalizeAllFiles(volume); - PFDIR_FinalizeAllDirs(volume); - error = PFDRV_unmount(volume, 1); - if (error == 0) { - if ((volume->flags & 8) != 0) { - PFVOL_CLEAR_CURRENT_DIRS(volume); - } - volume->flags &= ~8; - } - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes--; - } - if (PFDRV_IsMountRequested(volume) != 0) { - PFDRV_ClearMountRequested(volume); - } - } - error = 0; - if ((volume->flags & 8) == 0) { - error = 9; - } + error = check_read(volume); if (error != 0) { - goto save_error; + pf_vol_set.last_error = error; + volume->last_error = error; + return error; } error = PFVOL_p_getvol(volume, volume_info); if (error != 0) { - goto save_error; + pf_vol_set.last_error = error; + volume->last_error = error; + return error; } return 0; -save_error: - pf_vol_set.last_error = error; - volume->last_error = error; - return error; } s32 PFVOL_rmvvol(s8 drive) { @@ -1203,84 +950,32 @@ s32 PFVOL_rmvvol(s8 drive) { volume->last_error = 3; return 3; } - if (PFDRV_IsInserted(volume) != 0) { - if (PFDRV_IsUnmountRequested(volume) != 0 && (volume->flags & 8) == 0) { - PFFILE_FinalizeAllFiles(volume); - PFDIR_FinalizeAllDirs(volume); - error = PFDRV_unmount(volume, 1); - if (error == 0) { - if ((volume->flags & 8) != 0) { - PFVOL_CLEAR_CURRENT_DIRS(volume); - } - volume->flags &= ~8; - } - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes--; - } - error = PFDRV_IsMountRequested(volume); - if (error != 0) { - if ((volume->flags & 8) == 0) { - error = PFVOL_DoMountVolume(volume); - if (error == 0) { - volume->fsi_flag &= ~7; - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes++; - PFDRV_ClearMountRequested(volume); - error = 0; - } - } else { - PFDRV_ClearMountRequested(volume); - error = 0; - } - if (error != 0) { - goto save_error; - } - } - } else { - if (PFDRV_IsUnmountRequested(volume) != 0 && (volume->flags & 8) == 0) { - PFFILE_FinalizeAllFiles(volume); - PFDIR_FinalizeAllDirs(volume); - error = PFDRV_unmount(volume, 1); - if (error == 0) { - if ((volume->flags & 8) != 0) { - PFVOL_CLEAR_CURRENT_DIRS(volume); - } - volume->flags &= ~8; - } - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes--; - } - if (PFDRV_IsMountRequested(volume) != 0) { - PFDRV_ClearMountRequested(volume); - } - } - error = 0; - if ((volume->flags & 8) == 0) { - error = 9; - } else if ((volume->flags & 2) != 0) { - error = 11; - } + error = check_write(volume); if (error != 0) { - goto save_error; + pf_vol_set.last_error = error; + volume->last_error = error; + return error; } error = PFDRV_StoreVolumeLabelToBPB(volume, (const s8*)"NO NAME "); if (error != 0) { - goto save_error; + pf_vol_set.last_error = error; + volume->last_error = error; + return error; } error = PFVOL_p_rmvvol(volume); if (error != 0) { - goto save_error; + pf_vol_set.last_error = error; + volume->last_error = error; + return error; } error = PFCACHE_FlushDataCacheSpecific(volume, 0); if (error != 0) { - goto save_error; + pf_vol_set.last_error = error; + volume->last_error = error; + return error; } - return 0; - -save_error: - pf_vol_set.last_error = error; - volume->last_error = error; return error; + } s32 PFVOL_getdev(s8 drive, u32* device_info) { @@ -1294,77 +989,23 @@ s32 PFVOL_getdev(s8 drive, u32* device_info) { } else { volume = &pf_vol_set.volumes[volume_index]; } - if (PFDRV_IsInserted(volume) != 0) { - if (PFDRV_IsUnmountRequested(volume) != 0 && (volume->flags & 8) == 0) { - PFFILE_FinalizeAllFiles(volume); - PFDIR_FinalizeAllDirs(volume); - error = PFDRV_unmount(volume, 1); - if (error == 0) { - if ((volume->flags & 8) != 0) { - PFVOL_CLEAR_CURRENT_DIRS(volume); - } - volume->flags &= ~8; - } - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes--; - } - error = PFDRV_IsMountRequested(volume); - if (error != 0) { - if ((volume->flags & 8) == 0) { - error = PFVOL_DoMountVolume(volume); - if (error == 0) { - volume->fsi_flag &= ~7; - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes++; - PFDRV_ClearMountRequested(volume); - error = 0; - } - } else { - PFDRV_ClearMountRequested(volume); - error = 0; - } - if (error != 0) { - goto save_error; - } - } - } else { - if (PFDRV_IsUnmountRequested(volume) != 0 && (volume->flags & 8) == 0) { - PFFILE_FinalizeAllFiles(volume); - PFDIR_FinalizeAllDirs(volume); - error = PFDRV_unmount(volume, 1); - if (error == 0) { - if ((volume->flags & 8) != 0) { - PFVOL_CLEAR_CURRENT_DIRS(volume); - } - volume->flags &= ~8; - } - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes--; - } - if (PFDRV_IsMountRequested(volume) != 0) { - PFDRV_ClearMountRequested(volume); - } - } - error = 0; - if ((volume->flags & 8) == 0) { - error = 9; - } + error = check_read(volume); if (error != 0) { - goto save_error; + pf_vol_set.last_error = error; + volume->last_error = error; + return error; } device_info[2] = volume->bpb.bytes_per_sector; device_info[3] = volume->bpb.sectors_per_cluster; device_info[0] = volume->bpb.num_clusters; error = PFFAT_CountFreeClusters(volume, &device_info[1]); if (error != 0) { - goto save_error; + pf_vol_set.last_error = error; + volume->last_error = error; + return error; } return 0; -save_error: - pf_vol_set.last_error = error; - volume->last_error = error; - return error; } s32 PFVOL_buffering(s8 drive, u32 mode) { @@ -1378,183 +1019,91 @@ s32 PFVOL_buffering(s8 drive, u32 mode) { } else { volume = &pf_vol_set.volumes[volume_index]; } - if (PFDRV_IsInserted(volume) != 0) { - if (PFDRV_IsUnmountRequested(volume) != 0 && (volume->flags & 8) == 0) { - PFFILE_FinalizeAllFiles(volume); - PFDIR_FinalizeAllDirs(volume); - error = PFDRV_unmount(volume, 1); - if (error == 0) { - if ((volume->flags & 8) != 0) { - PFVOL_CLEAR_CURRENT_DIRS(volume); - } - volume->flags &= ~8; - } - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes--; - } - error = PFDRV_IsMountRequested(volume); - if (error != 0) { - if ((volume->flags & 8) == 0) { - error = PFVOL_DoMountVolume(volume); - if (error == 0) { - volume->fsi_flag &= ~7; - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes++; - PFDRV_ClearMountRequested(volume); - error = 0; - } - } else { - PFDRV_ClearMountRequested(volume); - error = 0; - } - if (error != 0) { - goto save_error; - } - } + error = check_write(volume); + if (error != 0) { pf_vol_set.last_error = error; volume->last_error = error; return error; } + if ((mode & 4) != 0 && (volume->cache_flags & 1) == 0) { + error = PFCACHE_FlushFATCache(volume); + if (error != 0) { pf_vol_set.last_error = error; volume->last_error = error; return error; } + } + if (mode & 1) { + error = PFCACHE_SetWriteThroughMode(volume); + if (error != 0) { pf_vol_set.last_error = error; volume->last_error = error; return error; } } else { - if (PFDRV_IsUnmountRequested(volume) != 0 && (volume->flags & 8) == 0) { - PFFILE_FinalizeAllFiles(volume); - PFDIR_FinalizeAllDirs(volume); - error = PFDRV_unmount(volume, 1); - if (error == 0) { - if ((volume->flags & 8) != 0) { - PFVOL_CLEAR_CURRENT_DIRS(volume); - } - volume->flags &= ~8; - } - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes--; - } - if (PFDRV_IsMountRequested(volume) != 0) { - PFDRV_ClearMountRequested(volume); - } - } - error = 0; - if ((volume->flags & 8) == 0) { - error = 9; - } else if ((volume->flags & 2) != 0) { - error = 11; - } - if (error == 0) { - if ((mode & 4) == 0 || (volume->cache_flags & 1) != 0) { - error = 0; - } else { - error = PFCACHE_FlushFATCache(volume); - if (error != 0) { - goto save_error; - } - } - if (error == 0) { - if ((mode & 1) == 0) { - error = PFCACHE_SetWriteBackMode(volume); - } else { - error = PFCACHE_SetWriteThroughMode(volume); - } - if (error != 0) { - goto save_error; - } - if ((mode & 4) != 0) { - volume->cache_flags |= 4; - } else { - volume->cache_flags &= ~4; - } - if ((mode & 2) != 0) { - volume->cache_flags |= 2; - } else { - volume->cache_flags &= ~2; - } - } - } else { - goto save_error; + error = PFCACHE_SetWriteBackMode(volume); + if (error != 0) { pf_vol_set.last_error = error; volume->last_error = error; return error; } } + if (mode & 2) { volume->cache_flags |= 2; } else { volume->cache_flags &= ~2; } + if (mode & 4) { volume->cache_flags |= 4; } else { volume->cache_flags &= ~4; } return 0; +} -save_error: - pf_vol_set.last_error = error; - volume->last_error = error; - return error; +static inline s32 initialize_volume_cache(PFVOL_VOLUME* volume, PFVOL_DRIVER* driver) { + s32 error = PFDRV_init(volume); + if (error != 0) { return error; } + PFCACHE_SetCache(volume, driver->cache->pages, driver->cache->buffers, + driver->cache->num_fat_pages, driver->cache->num_data_pages); + PFCACHE_SetFATBufferSize(volume, driver->cache->num_fat_buf_size); + PFCACHE_SetDataBufferSize(volume, driver->cache->num_data_buf_size); + return 0; +} + +static inline s32 attach_mount(PFVOL_VOLUME* volume, PFVOL_DRIVER* driver) { + s32 error = clear_mount(volume); + if (error != 0) { pf_vol_set.last_error = error; volume->last_error = error; return error; } + driver->stat |= 2; + return 0; } s32 PFVOL_attach(PFVOL_DRIVER* driver, s32 notify_command, void* callback_data) { - PFVOL_CACHE_SETTING* cache; - PFVOL_VOLUME* volume; s32 volume_index; + PFVOL_VOLUME* volume; + PFVOL_VOLUME* candidate; s32 error; - cache = driver->cache; - if (cache->num_fat_buf_size == 0) { - cache->num_fat_buf_size = 1; + if (driver->cache->num_fat_buf_size == 0) { + driver->cache->num_fat_buf_size = 1; } - if (cache->num_data_buf_size == 0) { - cache->num_data_buf_size = 1; + if (driver->cache->num_data_buf_size == 0) { + driver->cache->num_data_buf_size = 1; } - driver->drive = 0; driver->stat = 0; + driver->drive = 0; if (notify_command != 0 && fa_nanddrv_NotifyNANDFile(notify_command, callback_data) != 0) { pf_vol_set.last_error = 17; return 17; } - volume_index = 0; - volume = pf_vol_set.volumes; - while (volume_index < 26) { - if ((volume->flags & 1) == 0) { - break; - } - volume++; - volume_index++; - if ((volume->flags & 1) == 0) { - break; - } - volume++; - volume_index++; + candidate = pf_vol_set.volumes; + for (volume_index = 0; volume_index < 26; volume_index++) { + volume = candidate; + if ((candidate->flags & 1) == 0) { break; } + candidate++; } if (volume_index < 0 || volume_index >= 26 || pf_vol_set.num_attached_drives < 0 || pf_vol_set.num_attached_drives >= 26) { pf_vol_set.last_error = 4; return 4; } - volume->last_error = -1; - volume->last_driver_error = -1; + volume->num_free_clusters = -1; + volume->last_free_cluster = -1; pf_memset(volume, 0, 0x1FAC); volume->driver_partition = driver->partition; - volume->options = volume_index + 'A'; + volume->drv_char = (s16)volume_index + 'A'; volume->file_buffer_count = 1; volume->current_file_buffer = &volume->file_buffers; - error = PFDRV_init(volume); - if (error == 0) { - PFCACHE_SetCache(volume, cache->pages, cache->buffers, cache->num_fat_pages, - cache->num_data_pages); - PFCACHE_SetFATBufferSize(volume, cache->num_fat_buf_size); - PFCACHE_SetDataBufferSize(volume, cache->num_data_buf_size); - } + error = initialize_volume_cache(volume, driver); if (error != 0) { pf_vol_set.last_error = error; return error; } volume->flags |= 1; driver->stat |= 1; - volume->options = volume_index + 'A'; + volume->drv_char = volume_index + 'A'; driver->drive = volume_index + 'A'; pf_vol_set.num_attached_drives++; - if (PFDRV_IsInserted(volume) == 0) { - return 0; + if (PFDRV_IsInserted(volume) != 0) { + driver->stat |= 0x10; + attach_mount(volume, driver); } - driver->stat |= 0x10; - if ((volume->flags & 8) == 0) { - error = PFVOL_DoMountVolume(volume); - if (error == 0) { - volume->fsi_flag &= ~7; - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes++; - } - } - if (error == 0) { - PFDRV_ClearMountRequested(volume); - driver->stat |= 2; - return 0; - } - pf_vol_set.last_error = error; - volume->last_error = error; return 0; } @@ -1570,31 +1119,31 @@ s32 PFVOL_detach(s8 drive) { volume = &pf_vol_set.volumes[volume_index]; } if ((volume->flags & 8) != 0) { - error = 10; - pf_vol_set.last_error = error; - volume->last_error = error; - } else if ((volume->flags & 1) == 0) { - error = 10; - pf_vol_set.last_error = error; - volume->last_error = error; - } else { - error = PFDRV_finalize(volume); - if (error == 0) { - volume->flags &= ~1; - pf_vol_set.num_attached_drives--; - } else { - pf_vol_set.last_error = error; - volume->last_error = error; - } + pf_vol_set.last_error = 10; + volume->last_error = 10; + return 10; } - return error; + if ((volume->flags & 1) == 0) { + pf_vol_set.last_error = 10; + volume->last_error = 10; + return 10; + } + error = finalize_volume(volume); + if (error != 0) { + pf_vol_set.last_error = error; + volume->last_error = error; + return error; + } + volume->flags &= ~1; + pf_vol_set.num_attached_drives--; + return 0; } s32 PFVOL_format(s8 drive, const u8* format_options) { s16 volume_index; PFVOL_VOLUME* volume; s32 error; - u8 mount_requested; + u8 mount_requested = 0; volume_index = pf_toupper(drive) - 'A'; if (volume_index < 0 || volume_index >= 26) { @@ -1604,97 +1153,36 @@ s32 PFVOL_format(s8 drive, const u8* format_options) { } if ((volume->flags & 1) == 0) { error = 10; - goto save_error; + pf_vol_set.last_error = error; + volume->last_error = error; + return error; } if (PFDRV_IsInserted(volume) == 0) { error = 9; - goto save_error; - } - mount_requested = PFDRV_IsMountRequested(volume) != 0; - if (mount_requested != 0) { - PFDRV_ClearMountRequested(volume); - } - if (PFDRV_IsInserted(volume) != 0) { - if (PFDRV_IsUnmountRequested(volume) != 0 && (volume->flags & 8) == 0) { - PFFILE_FinalizeAllFiles(volume); - PFDIR_FinalizeAllDirs(volume); - error = PFDRV_unmount(volume, 1); - if (error == 0) { - if ((volume->flags & 8) != 0) { - PFVOL_CLEAR_CURRENT_DIRS(volume); - } - volume->flags &= ~8; - } - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes--; - } - error = PFDRV_IsMountRequested(volume); - if (error != 0) { - if ((volume->flags & 8) == 0) { - error = PFVOL_DoMountVolume(volume); - if (error == 0) { - volume->fsi_flag &= ~7; - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes++; - PFDRV_ClearMountRequested(volume); - error = 0; - } - } else { - PFDRV_ClearMountRequested(volume); - error = 0; - } - if (error != 0) { - goto after_mount; - } - } - } else { - if (PFDRV_IsUnmountRequested(volume) != 0 && (volume->flags & 8) == 0) { - PFFILE_FinalizeAllFiles(volume); - PFDIR_FinalizeAllDirs(volume); - error = PFDRV_unmount(volume, 1); - if (error == 0) { - if ((volume->flags & 8) != 0) { - PFVOL_CLEAR_CURRENT_DIRS(volume); - } - volume->flags &= ~8; - } - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes--; - } - if (PFDRV_IsMountRequested(volume) != 0) { - PFDRV_ClearMountRequested(volume); - } - } - error = 0; -after_mount: - if (error == 0) { - if (volume->num_open_files != 0) { - PFFILE_FinalizeAllFiles(volume); - PFCACHE_FreeAllCaches(volume); - } - if (volume->num_open_dirs != 0) { - PFDIR_FinalizeAllDirs(volume); - } - error = PFVOL_p_format(volume, format_options); - if (error == 0) { - volume->fsi_flag |= 4; - volume->num_free_clusters = volume->bpb.num_clusters - (volume->bpb.fat_type == 2); - return 0; - } - } - if (mount_requested) { - volume->flags |= 0x10; - } - if (error != 0) { pf_vol_set.last_error = error; volume->last_error = error; + return error; } - return error; - -save_error: - pf_vol_set.last_error = error; - volume->last_error = error; - return error; + if (PFDRV_IsMountRequested(volume) != 0) { + PFDRV_ClearMountRequested(volume); + mount_requested = 1; + } + error = check_driver_requests(volume); + if (error != 0) { + if (mount_requested) { volume->flags |= 0x10; } + pf_vol_set.last_error = error; volume->last_error = error; return error; + } + if (volume->num_open_files != 0) { PFFILE_FinalizeAllFiles(volume); PFCACHE_FreeAllCaches(volume); } + if (volume->num_open_dirs != 0) { PFDIR_FinalizeAllDirs(volume); } + error = PFVOL_p_format(volume, format_options); + if (error != 0) { + if (mount_requested) { volume->flags |= 0x10; } + pf_vol_set.last_error = error; volume->last_error = error; return error; + } + volume->fsi_flag |= 4; + if (volume->bpb.fat_type == 2) { volume->num_free_clusters = volume->bpb.num_clusters - 1; } + else { volume->num_free_clusters = volume->bpb.num_clusters; } + return 0; } s32 PFVOL_mount(s8 drive) { @@ -1708,27 +1196,13 @@ s32 PFVOL_mount(s8 drive) { } else { volume = &pf_vol_set.volumes[volume_index]; } - PFVOL_UPDATE_DRIVER_REQUESTS(volume, error); - if (error == 0) { - if (PFDRV_IsInserted(volume) != 0) { - if ((volume->flags & 8) == 0) { - error = PFVOL_DoMountVolume(volume); - if (error == 0) { - volume->fsi_flag &= ~7; - PFDRV_ClearUnmountRequested(volume); - pf_vol_set.num_mounted_volumes++; - PFDRV_ClearMountRequested(volume); - } - } - } else { - error = 9; - } - } - if (error != 0) { - pf_vol_set.last_error = error; - volume->last_error = error; - } - return error; + error = check_driver_requests(volume); + if (error != 0) { pf_vol_set.last_error = error; volume->last_error = error; return error; } + if (PFDRV_IsInserted(volume) == 0) { pf_vol_set.last_error = 9; volume->last_error = 9; return 9; } + if ((volume->flags & 8) != 0) { return 0; } + error = clear_mount(volume); + if (error != 0) { pf_vol_set.last_error = error; volume->last_error = error; return error; } + return 0; } s32 PFVOL_unmount(s8 drive, u32 mode) { @@ -1779,7 +1253,7 @@ s32 PFVOL_unmount(s8 drive, u32 mode) { return result; } -s32 PFVOL_setupfsi(s8 drive, u32 mode) { +s32 PFVOL_setupfsi(s8 drive, s32 mode) { s16 volume_index; PFVOL_VOLUME* volume; s32 error; @@ -1792,34 +1266,16 @@ s32 PFVOL_setupfsi(s8 drive, u32 mode) { } else { volume = &pf_vol_set.volumes[volume_index]; } - PFVOL_UPDATE_DRIVER_REQUESTS(volume, error); - if (error == 0 && (volume->flags & 8) == 0) { - error = 9; - } - if (error == 0) { - if (volume->bpb.fat_type == 2) { - if ((mode & 1) == 1) { - volume->fsi_flag |= 5; - } else if ((mode & 2) == 2) { - volume->fsi_flag &= ~1; - } - if ((mode & 4) == 4) { - volume->fsi_flag |= 2; - if ((volume->fsi_flag & 4) == 0) { - PFFAT_CountFreeClusters(volume, &free_clusters); - } - } else if ((mode & 8) == 8) { - volume->fsi_flag &= ~2; - } - } else { - error = 12; - } - } - if (error != 0) { - pf_vol_set.last_error = error; - volume->last_error = error; - } - return error; + error = check_read(volume); + if (error != 0) { pf_vol_set.last_error = error; volume->last_error = error; return error; } + if (volume->bpb.fat_type != 2) { pf_vol_set.last_error = 12; volume->last_error = 12; return 12; } + if ((mode & 1) == 1) { volume->fsi_flag |= 5; } + else if ((mode & 2) == 2) { volume->fsi_flag &= ~1; } + if ((mode & 4) == 4) { + volume->fsi_flag |= 2; + if ((volume->fsi_flag & 4) == 0) { PFFAT_CountFreeClusters(volume, &free_clusters); } + } else if ((mode & 8) == 8) { volume->fsi_flag &= ~2; } + return 0; } s32 PFVOL_setclstlink(s8 drive, s32 mode, PFVOL_CLUSTER_SETTING* setting) { @@ -1838,16 +1294,10 @@ s32 PFVOL_setclstlink(s8 drive, s32 mode, PFVOL_CLUSTER_SETTING* setting) { volume->last_error = 19; return 19; } - PFVOL_UPDATE_DRIVER_REQUESTS(volume, error); - if (error == 0) { - if ((volume->flags & 8) == 0) { - error = 9; - } else if ((volume->flags & 2) != 0) { - error = 11; - } - } - if (error == 0) { - if (mode == 1) { + error = check_read(volume); + if (error != 0) { pf_vol_set.last_error = error; volume->last_error = error; return error; } + { + if ((u32)mode == 1) { if (setting->buffer == 0) { pf_vol_set.last_error = 10; volume->last_error = 10; @@ -1866,12 +1316,7 @@ s32 PFVOL_setclstlink(s8 drive, s32 mode, PFVOL_CLUSTER_SETTING* setting) { volume->cluster_link_capacity = 0; } } - if (error != 0) { - pf_vol_set.last_error = error; - volume->last_error = error; - return error; - } - return 0; + return error; } s32 PFVOL_sync(s8 drive, s32 mode) { @@ -1879,7 +1324,7 @@ s32 PFVOL_sync(s8 drive, s32 mode) { PFVOL_VOLUME* volume; PFVOL_OPEN_FILE* file; s32 error; - u32 file_index; + u16 file_index; volume_index = pf_toupper(drive) - 'A'; if (volume_index < 0 || volume_index >= 26) { @@ -1887,40 +1332,19 @@ s32 PFVOL_sync(s8 drive, s32 mode) { } else { volume = &pf_vol_set.volumes[volume_index]; } - PFVOL_UPDATE_DRIVER_REQUESTS(volume, error); - if (error == 0) { - if ((volume->flags & 8) == 0) { - error = 9; - } else if ((volume->flags & 2) != 0) { - error = 11; + error = check_write(volume); + if (error != 0) { pf_vol_set.last_error = error; volume->last_error = error; return error; } + error = PFCACHE_FlushFATCache(volume); + if (error != 0) { pf_vol_set.last_error = error; volume->last_error = error; return error; } + for (file_index = 0; file_index < 5; file_index++) { + if ((volume->files[file_index].stat & 1) != 0) { + error = PFENT_updateEntry(&volume->files[file_index].stream->directory_entry, 1); + if (error != 0) { pf_vol_set.last_error = error; volume->last_error = error; return error; } } } - if (error == 0) { - error = PFCACHE_FlushFATCache(volume); - if (error == 0) { - file_index = 0; - do { - file = &volume->files[file_index]; - if ((file->stat & 1) != 0) { - error = PFENT_updateEntry(&file->stream->directory_entry, 1); - if (error != 0) { - pf_vol_set.last_error = error; - volume->last_error = error; - return error; - } - } - file_index++; - } while (file_index < 5); - error = PFCACHE_FlushDataCache(volume); - if (error == 0 && mode == 1) { - PFCACHE_FreeAllCaches(volume); - } - } - } - if (error != 0) { - pf_vol_set.last_error = error; - volume->last_error = error; - } + error = PFCACHE_FlushDataCache(volume); + if (error != 0) { pf_vol_set.last_error = error; volume->last_error = error; return error; } + if ((u32)mode == 1) { PFCACHE_FreeAllCaches(volume); } return error; } @@ -1935,16 +1359,13 @@ void PFVOL_settailbuf(s8 drive, u32 count, void* buffer) { } else { volume = &pf_vol_set.volumes[volume_index]; } - PFVOL_UPDATE_DRIVER_REQUESTS(volume, error); - if (error == 0 && (volume->flags & 8) == 0) { - error = 9; - } - if (error == 0) { - volume->file_buffer_count = count; - volume->current_file_buffer = buffer; - } else { + error = check_read(volume); + if (error != 0) { pf_vol_set.last_error = error; volume->last_error = error; + } else { + volume->file_buffer_count = count; + volume->current_file_buffer = buffer; } } @@ -1959,8 +1380,7 @@ s32 PFVOL_setvolcfg(s8 drive, u32* config) { } else if ((config[0] & 0x20000) != 0) { pf_vol_set.config &= ~0x10000; } - return 0; - } + } else { volume_index = pf_toupper(drive) - 'A'; if (volume_index < 0 || volume_index >= 26) { volume = 0; @@ -1973,7 +1393,7 @@ s32 PFVOL_setvolcfg(s8 drive, u32* config) { if (config[3] == 0) { config[3] = 1; } - PFVOL_UPDATE_DRIVER_REQUESTS(volume, error); + check_driver_requests(volume); if (volume->num_open_files != 0 || volume->num_open_dirs != 0) { pf_vol_set.last_error = 19; volume->last_error = 19; @@ -2001,6 +1421,7 @@ s32 PFVOL_setvolcfg(s8 drive, u32* config) { } else if ((config[1] & 2) != 0) { volume->reserved_1f88 &= ~1; } + } return 0; } @@ -2018,95 +1439,78 @@ s32 PFVOL_getvolcfg(s8 drive, u32* config) { config[1] = 0; config[2] = 0; config[3] = 0; - return 0; - } + } else { volume_index = pf_toupper(drive) - 'A'; if (volume_index < 0 || volume_index >= 26) { volume = 0; } else { volume = &pf_vol_set.volumes[volume_index]; } - PFVOL_UPDATE_DRIVER_REQUESTS(volume, error); + check_driver_requests(volume); config[0] = 0; config[1] = volume->reserved_1f88; - if ((volume->reserved_1f88 & 1) == 0) { + if ((volume->reserved_1f88 & 1) != 1) { config[1] |= 2; } config[2] = volume->num_fat_buf_size; config[3] = volume->num_data_buf_size; + } return 0; } s32 PFVOL_setcode(const PFVOL_CHARCODE* code_set) { - if (pf_vol_set.num_attached_drives > 0) { + if (pf_vol_set.num_mounted_volumes > 0) { pf_vol_set.last_error = 36; return 36; } - pf_vol_set.codeset.oem2unicode = code_set->oem2unicode; - pf_vol_set.codeset.unicode2oem = code_set->unicode2oem; - pf_vol_set.codeset.oem_char_width = code_set->oem_char_width; - pf_vol_set.codeset.is_oem_mb_char = code_set->is_oem_mb_char; - pf_vol_set.codeset.unicode_char_width = code_set->unicode_char_width; - pf_vol_set.codeset.is_unicode_mb_char = code_set->is_unicode_mb_char; - return 0; + return copy_codeset(code_set); } s32 PFVOL_regctx(void) { - PFVOL_CONTEXT* context; s32 context_id; - s32 error; + s32 free_context_index; u32 context_index; - u32 free_context_index = 0; - + s32 error; error = PFSYS_GetCurrentContextID(&context_id); - if (error != 0) { - pf_vol_set.last_error = 26; - return 26; + if (error != 0) { pf_vol_set.last_error = 26; return 26; } + free_context_index = 0; + for (context_index = 1; context_index < 4; context_index++) { + u32 stat; + stat = pf_vol_set.context[context_index - 1].stat & 1; + if (stat != 0 && pf_vol_set.context[context_index - 1].context_id == context_id) { break; } + if (stat == 0 && free_context_index == 0) { free_context_index = context_index; } } - context = pf_vol_set.context; - for (context_index = 1; context_index <= 3; context_index++) { - if ((context->stat & 1) != 0) { - if (context->context_id == context_id) { - return 0; - } - } else if (free_context_index == 0) { - free_context_index = context_index; - } - context++; + if (context_index == 4) { + if (free_context_index != 0) { + pf_vol_set.context[free_context_index - 1].stat = 1; + pf_vol_set.context[free_context_index - 1].context_id = context_id; + } else { pf_vol_set.last_error = 26; error = 26; } } - if (free_context_index == 0) { - pf_vol_set.last_error = 26; - return 26; - } - context = &pf_vol_set.context[free_context_index - 1]; - context->stat = 1; - context->context_id = context_id; - return 0; + return error; } s32 PFVOL_unregctx(void) { s32 context_id; s32 error; u32 context_index; - u32 volume_index; u32 current_dir_index; + u32 volume_index; u32 current_volume_index; - s32 found = 0; error = PFSYS_GetCurrentContextID(&context_id); if (error != 0) { pf_vol_set.last_error = 26; return 26; } - for (context_index = 0; context_index < 3; context_index++) { - if ((pf_vol_set.context[context_index].stat & 1) != 0 && - pf_vol_set.context[context_index].context_id == context_id) { - pf_vol_set.context[context_index].stat &= ~1; - found = 1; - for (current_volume_index = 0; current_volume_index < 3; current_volume_index++) { - if ((pf_vol_set.context_volume[current_volume_index].stat & 1) != 0 && - pf_vol_set.context_volume[current_volume_index].context_id == context_id) { - pf_vol_set.context_volume[current_volume_index].stat &= ~1; + for (context_index = 1; context_index < 4; context_index++) { + if ((pf_vol_set.context[context_index - 1].stat & 1) != 0 && + pf_vol_set.context[context_index - 1].context_id == context_id) { + pf_vol_set.context[context_index - 1].stat &= ~1; + for (current_volume_index = 1; current_volume_index < 4; current_volume_index++) { + if ((pf_vol_set.context_volume[current_volume_index - 1].stat & 1) != 0 && + pf_vol_set.context_volume[current_volume_index - 1].context_id == context_id) { + pf_vol_set.context_volume[current_volume_index - 1].stat &= ~1; + break; } } for (volume_index = 0; volume_index < 26; volume_index++) { @@ -2121,11 +1525,11 @@ s32 PFVOL_unregctx(void) { break; } } - if (found == 0) { + if (context_index == 4) { pf_vol_set.last_error = 26; - return 26; + error = 26; } - return 0; + return error; } s32 PFVOL_setencode(u32 mode) { diff --git a/tools/decomp-assist/attempts/fa-dir.md b/tools/decomp-assist/attempts/fa-dir.md new file mode 100644 index 00000000..5523a591 --- /dev/null +++ b/tools/decomp-assist/attempts/fa-dir.md @@ -0,0 +1,16 @@ +# fa/pf_dir + +Baseline 22/38 exact. VF source diff inspected before editing. Sources already contained all 38 bodies; several large bodies lacked fa-specific operations. + +Remaining attempts, instruction counts (source/target), retained source in the final commit: +- GetSDD: original flag condition 67/69; status-word negation 68/69; retain flag prerequisite 69/69 with two increment-order differences; update pointer in body, measured below. +- opendir: explicit += count update 39/39 two register differences; invert successful branch 39/39 nine differences; inline status helper 39/39 nine differences. Restored first form. +- p_fsnext: local pattern, loop and global setting correction 186/193; signed indexed file scan 191/193; while loop 193/193, 39 differences (loop-limit hoisting). +- p_rmdir: opened-directory helper 165/202; normalize FreeChain result 169/202; add path split and iterator/hint copies 186/202; restore saved iterator/hint before removal 203/202. Stack/copy scheduling remains. +- p_fsexec_remove: opened-directory helper 159/176; initialize a separate iterator 153/176; delay cluster load 151/176; reset supplied iterator and restore its saved state, with file size bound 178/176. Stack/control scheduling remains. +- p_mkdir: port API calls and fa FFD/STR/hint types 254/562; order iterator workspace and split name-length errors 256/562; order hint before position 256/562. Missing original inline entry initialization/allocation operations remain. +- p_rename: unconditional filename validation 190/625; swapped iterator workspaces and corrected end sentinel 191/625; explicit destination code-mode local and restored iterator order 191/625. Original long-name allocation/update operations remain missing. +- p_move: unconditional filename validation 211/631; use opened-directory helper and workspace order 215/631; explicit code-mode local and restored iterator order 215/631. Original cross-directory entry allocation/update remains missing. +- p_fsexec: correct flags and use entry start-cluster storage 206/280; move iterator setup before start-position selection 206/280; reorder workspaces and compare status explicitly 207/280. Original name-search/control paths still differ. + +New exact functions include directory allocation, open-by-path, chmod, stat, fsexec chmod and context changes. No shared headers changed. diff --git a/tools/decomp-assist/attempts/fa-fat.md b/tools/decomp-assist/attempts/fa-fat.md new file mode 100644 index 00000000..ab999ea4 --- /dev/null +++ b/tools/decomp-assist/attempts/fa-fat.md @@ -0,0 +1,13 @@ +# fa/pf_fat + +Baseline 22/35 exact. Diff against Matching vf source inspected first. Final source preserves all 35 function bodies and changes no headers. + +Remaining attempts, source/target instruction counts: +- DoAllocateChain: page-before-sector initialization (216/216, five register differences); initialize flush error after loading page (same); reorder page/sector locals (same); direct page buffer alias (217/216). Restored original 216/216. +- GetClusterAllocated: reorder hint/fat type loads (69/70, 45 differences); reorder first/last cluster locals (same); isolate range check in traversal helper (70/70, eight differences); restore original load ordering (70/70, six differences); reorder hint/fat type declarations (unchanged). Six pointer register differences remain. +- GetSector: preload FAT type before root check (88/88, seven register differences); swap quotient/remainder declaration order (same); reverse addition operand order (same); spell rounded sector count directly (same). Division span and quotient registers remain swapped. +- GetSectorSpecified: immediate error return (17/17, four differences, compiler uses arithmetic normalization); explicit success/error scopes (16/17); inline wrapper boundary (20/17). Restored original 16/17, one conditional branch expansion remains. +- FreeChain: remove page alias (260/254); reorder flush scan locals (256/254, 113 differences); cache FAT type before the loop (different register/control stream). Restored 256/254. Status lifetime and flush registers remain different. +- RefreshFSINFO: reorder endian expression (88/93); explicit FSINFO buffer local (87/93); shared allocation-failure exit (93/93, fourteen differences). Restored endian expression and retained common return; remaining allocation status branch and endian store scheduling differ. + +Other experiments yielded exact read/write cluster functions, cluster-link traversal, allocated-cluster counting and specified cluster traversal. Invalid intermediate code with an uninitialized alias was corrected immediately and is absent from the final source. diff --git a/tools/decomp-assist/attempts/fa-file.md b/tools/decomp-assist/attempts/fa-file.md new file mode 100644 index 00000000..aeb8375c --- /dev/null +++ b/tools/decomp-assist/attempts/fa-file.md @@ -0,0 +1,36 @@ +# fa/pf_file + +Baseline 32/45 exact, 10384/17820 code bytes. Compared the existing fa source against the Matching vf counterpart before changing it. Final source defines the existing PF_FA_STR_LAYOUT header guard locally; no shared headers changed. + +Remaining attempts, source/target instruction counts: +- GetSFD: corrected free-slot predicate and indexed return (113/113, 28 differences); indexed entry comparisons (113/113, 18 differences); move index initialization before pointer initialization and reverse loop updates (113/113, 42 differences); extract SFD initialization into an inline helper and remove the volume alias (113/113, 38 differences); restore original declarations and reverse loop increments (113/113, 18 differences, different increment ordering). Retained original declarations and loop order: 113/113, 18 differences. Callee-saved registers and two loop increments still differ; objdiff 99.09734%. +- fread: move p_fread definition into object order (96/67, still inlined); use a separate completed-count local (96/67); initialize that local to zero (96/67); introduce a separate read-status scope (96/67); put output initialization before volume lookup and remove the extra status scope (97/67, 28 comparison differences). Retained the last form, which follows the target's output and volume initialization order. The compiler inlines p_fread into this wrapper whereas the original calls it separately; objdiff 48.208954%. p_fread itself remains instruction exact. + +New exact functions: Cursor_WriteHeadSector, Cursor_WriteBodySectors, Cursor_WriteTailSector, createEmptyFile, p_remove, p_fopen, p_fwrite, p_combine, p_divide, p_flock, fsetclstlink. + +Key source corrections: pass the next sector to the last-access update; use the fa hint and string layouts; retain the removal iterator hint and original first cluster; compute the LFN checksum once and advance the previous-sector pointer; reuse the free-UFD helper; initialize the divide iterators directly and preserve its error through cleanup; propagate cache flush failures; use the target lock flags and release one lock at a time. + +The other units' remaining function attempts and evidence are in fa-volume.md, fa-dir.md and fa-fat.md. No configuration state changed. + +Remaining objdiff scores across the batch: +- PFVOL_p_setvol 98.82979%; reason and three or more attempts recorded in fa-volume.md. +- PFVOL_attach 98.72159%; reason and three or more attempts recorded in fa-volume.md. +- PFVOL_setcode 53.869564%; reason and three or more attempts recorded in fa-volume.md. +- PFVOL_regctx 99.0%; reason and three or more attempts recorded in fa-volume.md. +- PFDIR_GetSDD 99.710144%; reason and three or more attempts recorded in fa-dir.md. +- PFDIR_p_mkdir 24.046263%; reason and three or more attempts recorded in fa-dir.md. +- PFDIR_p_rmdir 81.4802%; reason and three or more attempts recorded in fa-dir.md. +- PFDIR_p_rename 24.0336%; reason and three or more attempts recorded in fa-dir.md. +- PFDIR_p_move 25.359747%; reason and three or more attempts recorded in fa-dir.md. +- PFDIR_p_fsnext 97.74612%; reason and three or more attempts recorded in fa-dir.md. +- PFDIR_p_fsexec_remove 98.46591%; reason and three or more attempts recorded in fa-dir.md. +- PFDIR_p_fsexec 63.478573%; reason and three or more attempts recorded in fa-dir.md. +- PFDIR_opendir 99.74359%; reason and three or more attempts recorded in fa-dir.md. +- PFFAT_DoAllocateChain 99.83796%; reason and three or more attempts recorded in fa-fat.md. +- PFFAT_GetClusterAllocated 99.57143%; reason and three or more attempts recorded in fa-fat.md. +- PFFAT_GetSector 99.431816%; reason and three or more attempts recorded in fa-fat.md. +- PFFAT_GetSectorSpecified 93.52941%; reason and three or more attempts recorded in fa-fat.md. +- PFFAT_FreeChain 97.95276%; reason and three or more attempts recorded in fa-fat.md. +- PFFAT_RefreshFSINFO 96.62366%; reason and three or more attempts recorded in fa-fat.md. +- PFFILE_GetSFD 99.09734%; register allocation and loop increment ordering. +- PFFILE_fread 48.208954%; compiler inlines the separate read operation. diff --git a/tools/decomp-assist/attempts/fa-volume.md b/tools/decomp-assist/attempts/fa-volume.md new file mode 100644 index 00000000..d9cf5e88 --- /dev/null +++ b/tools/decomp-assist/attempts/fa-volume.md @@ -0,0 +1,11 @@ +# fa/pf_volume + +Baseline: 7/37 exact, 1048/17992 code bytes. Matching vf source compared first; this fa variant has 26 volumes and three context slots. + +Remaining experiments (ctxdiff evidence in /tmp during matching): +- PFVOL_p_setvol: inline whole operation (93/94, different stack slots); normalize helper result (97/94, different stack slots); remove redundant root error else (93/94, only first conditional branch expansion). Retained original stack layout, 93/94. +- PFVOL_attach: correct free-cluster and drive fields (170/176); canonical search loop (169/176); split driver/cache initialization and mount status (173/176); reorder locals and signed drive conversion (174/176); separate mount helper (174/176, unchanged). Remaining status return boundary, 174/176. +- PFVOL_setcode: six named pointer assignments (23/23, 17 diffs); aggregate assignment (same); word loop (same); inline copy helper (same). Compiler schedules loads before stores and allocates a different base register. +- PFVOL_regctx: indexed context loop (79/75); initialize free index after system call (77/75); return system status (75/75, 20 register differences); reorder free/index declarations (75/75, 15 register differences); split masked status declaration and assignment (unchanged). Retained 75/75. + +Other corrected operations now instruction exact: driver request handling, read/write checks, formatting, context removal, label removal, cache flush status, buffering, mount/unmount and configuration. No shared headers changed. -- 2.49.1 From 86b2e951c6b5c85d47972acff6b2bb6d25f648a0 Mon Sep 17 00:00:00 2001 From: devin Date: Wed, 30 Sep 2026 05:45:29 +0000 Subject: [PATCH 5/5] fa: link 6 more pf units (service,fopen,fseek,fsfirst,fsnext,fstat) - objdiff 100% Co-Authored-By: wch --- configure.py | 12 ++++---- libs/RVL_SDK/src/fa/pf_fopen.c | 49 +++++++++++++++++--------------- libs/RVL_SDK/src/fa/pf_fseek.c | 15 ++++------ libs/RVL_SDK/src/fa/pf_fsfirst.c | 40 +++++++++++++------------- libs/RVL_SDK/src/fa/pf_fsnext.c | 17 ++++------- libs/RVL_SDK/src/fa/pf_fstat.c | 32 +++++++++++++++++++++ 6 files changed, 97 insertions(+), 68 deletions(-) create mode 100644 libs/RVL_SDK/src/fa/pf_fstat.c diff --git a/configure.py b/configure.py index eaa5c416..8d4df0d8 100644 --- a/configure.py +++ b/configure.py @@ -1684,7 +1684,7 @@ config.libs = [ RVLSDKLib("fa", [ Object(Matching, "fa/pf_clib.c"), Object(Matching, "fa/pf_code.c"), - Object(NonMatching, "fa/pf_service.c"), + Object(Matching, "fa/pf_service.c"), Object(Matching, "fa/pf_str.c"), Object(Matching, "fa/pf_driver.c"), Object(NonMatching, "fa/pdm_api.c"), @@ -1733,15 +1733,15 @@ config.libs = [ Object(Matching, "fa/pf_ferror.c"), Object(NonMatching, "fa/pf_finfo.c"), Object(Matching, "fa/pf_flock.c"), - Object(NonMatching, "fa/pf_fopen.c"), + Object(Matching, "fa/pf_fopen.c"), Object(NonMatching, "fa/pf_format.c"), Object(Matching, "fa/pf_fread.c"), - Object(NonMatching, "fa/pf_fseek.c"), + Object(Matching, "fa/pf_fseek.c"), Object(NonMatching, "fa/pf_fsetclstlink.c"), Object(NonMatching, "fa/pf_fsexec.c"), - Object(NonMatching, "fa/pf_fsfirst.c"), - Object(NonMatching, "fa/pf_fsnext.c"), - Object(NonMatching, "fa/pf_fstat.c"), + Object(Matching, "fa/pf_fsfirst.c"), + Object(Matching, "fa/pf_fsnext.c"), + Object(Matching, "fa/pf_fstat.c"), Object(Matching, "fa/pf_fsync.c"), Object(Matching, "fa/pf_fwrite.c"), Object(NonMatching, "fa/pf_getdev.c"), diff --git a/libs/RVL_SDK/src/fa/pf_fopen.c b/libs/RVL_SDK/src/fa/pf_fopen.c index 251bdf44..d137ada1 100644 --- a/libs/RVL_SDK/src/fa/pf_fopen.c +++ b/libs/RVL_SDK/src/fa/pf_fopen.c @@ -1,38 +1,41 @@ -#define PF_FA_STR_LAYOUT -#define VFiPFAPI_ParseOpenModeString PFAPI_ParseOpenModeString -#define VFiPFAPI_convertReturnValue2NULL PFAPI_convertReturnValue2NULL -#define VFiPFFILE_fopen PFFILE_fopen -#define VFiPFSTR_InitStr PFSTR_InitStr -#include +#include -typedef struct PFAPI_GLOBAL_STATE { - pf_u8 volume_state[0x40]; - pf_s32 last_error; -} PFAPI_GLOBAL_STATE; -extern PFAPI_GLOBAL_STATE pf_vol_set; +typedef struct PFF2_STR { + const s8* p_head; + const s8* p_tail; + const s8* p_current; + u32 code_mode; +} PFF2_STR; +typedef struct PFF2_VOL_SET { + u8 reserved[0x40]; + s32 last_error; +} PFF2_VOL_SET; -#include -#include +extern PFF2_VOL_SET pf_vol_set; +extern s32 PFAPI_ParseOpenModeString(const char* mode_str); +extern s32 PFSTR_InitStr(PFF2_STR* path, const s8* text, u32 code_mode); +extern s32 PFFILE_fopen(PFF2_STR* path, s32 mode, FAFILE** result); +extern FAFILE* PFAPI_convertReturnValue2NULL(s32 err, FAFILE* p_stream); -PF_FILE* pf2_fopen(const pf_ch8* path, const pf_ch8* mode) { - pf_u32 open_mode; - PF_FILE* p_file; - PF_STR path_str; - pf_s32 err; +FAFILE* pf2_fopen(const char* path, const char* mode) { + u32 open_mode; + FAFILE* p_file; + PFF2_STR path_str; + s32 err; - open_mode = VFiPFAPI_ParseOpenModeString(mode); + open_mode = PFAPI_ParseOpenModeString(mode); if (open_mode == 0) { pf_vol_set.last_error = 10; - p_file = PF_NULL; + p_file = NULL; } else { - err = VFiPFSTR_InitStr(&path_str, (pf_s8*)path, 1U); + err = PFSTR_InitStr(&path_str, (const s8*)path, 1); if (err == 0) { - err = VFiPFFILE_fopen(&path_str, open_mode, &p_file); + err = PFFILE_fopen(&path_str, open_mode, &p_file); } else { pf_vol_set.last_error = err; } - p_file = VFiPFAPI_convertReturnValue2NULL(err, p_file); + p_file = PFAPI_convertReturnValue2NULL(err, p_file); } return p_file; } diff --git a/libs/RVL_SDK/src/fa/pf_fseek.c b/libs/RVL_SDK/src/fa/pf_fseek.c index b504cf24..9fcfad95 100644 --- a/libs/RVL_SDK/src/fa/pf_fseek.c +++ b/libs/RVL_SDK/src/fa/pf_fseek.c @@ -1,13 +1,10 @@ -#define PF_FA_STR_LAYOUT -#define VFiPFAPI_convertReturnValue PFAPI_convertReturnValue -#define VFiPFFILE_fseek PFFILE_fseek -#include +#include -#include -#include +extern s32 PFFILE_fseek(FAFILE* stream, s32 offset, int origin); +extern s32 PFAPI_convertReturnValue(s32 err); -pf_int32 pf2_fseek(PF_FILE* pFile, pf_s32 lOffset, pf_int32 nOrigin) { - pf_s32 err = VFiPFFILE_fseek(pFile, lOffset, nOrigin); - err = VFiPFAPI_convertReturnValue(err); +FAError pf2_fseek(FAFILE* stream, s32 offset, int origin) { + s32 err = PFFILE_fseek(stream, offset, origin); + err = PFAPI_convertReturnValue(err); return err; } diff --git a/libs/RVL_SDK/src/fa/pf_fsfirst.c b/libs/RVL_SDK/src/fa/pf_fsfirst.c index 01ad1f47..df29f5aa 100644 --- a/libs/RVL_SDK/src/fa/pf_fsfirst.c +++ b/libs/RVL_SDK/src/fa/pf_fsfirst.c @@ -1,30 +1,32 @@ -#define PF_FA_STR_LAYOUT -#define VFiPFAPI_convertReturnValue PFAPI_convertReturnValue -#define VFiPFDIR_fsfirst PFDIR_fsfirst -#define VFiPFSTR_InitStr PFSTR_InitStr -#include +#include -typedef struct PFAPI_GLOBAL_STATE { - pf_u8 volume_state[0x40]; - pf_s32 last_error; -} PFAPI_GLOBAL_STATE; -extern PFAPI_GLOBAL_STATE pf_vol_set; +typedef struct PFF2_STR { + const s8* p_head; + const s8* p_tail; + const s8* p_current; + u32 code_mode; +} PFF2_STR; +typedef struct PFF2_VOL_SET { + u8 reserved[0x40]; + s32 last_error; +} PFF2_VOL_SET; -#include -#include +extern PFF2_VOL_SET pf_vol_set; +extern s32 PFSTR_InitStr(PFF2_STR* path, const s8* text, u32 code_mode); +extern s32 PFDIR_fsfirst(PFF2_STR* path, u8 attributes, FADta* data); +extern s32 PFAPI_convertReturnValue(s32 err); -pf_int32 pf2_fsfirst(const pf_ch8* path, pf_u8 attrs, PF_DTA* p_dta) { - pf_s32 err; - PF_STR path_str; +FAError pf2_fsfirst(const char* dirName, u8 attr, FADta* dta) { + s32 err; + PFF2_STR path_str; - err = VFiPFSTR_InitStr(&path_str, (pf_s8*)path, 1U); + err = PFSTR_InitStr(&path_str, (const s8*)dirName, 1); if (err == 0) { - err = VFiPFDIR_fsfirst(&path_str, attrs, p_dta); + err = PFDIR_fsfirst(&path_str, attr, dta); } else { pf_vol_set.last_error = err; } - err = VFiPFAPI_convertReturnValue(err); - + err = PFAPI_convertReturnValue(err); return err; } diff --git a/libs/RVL_SDK/src/fa/pf_fsnext.c b/libs/RVL_SDK/src/fa/pf_fsnext.c index 4bf035eb..9675453d 100644 --- a/libs/RVL_SDK/src/fa/pf_fsnext.c +++ b/libs/RVL_SDK/src/fa/pf_fsnext.c @@ -1,15 +1,10 @@ -#define PF_FA_STR_LAYOUT -#define VFiPFAPI_convertReturnValue PFAPI_convertReturnValue -#define VFiPFDIR_fsnext PFDIR_fsnext -#include +#include -#include -#include +extern s32 PFDIR_fsnext(FADta* data); +extern s32 PFAPI_convertReturnValue(s32 err); -pf_int32 pf2_fsnext(PF_DTA* p_dta) { - pf_s32 err; - - err = VFiPFDIR_fsnext(p_dta); - err = VFiPFAPI_convertReturnValue(err); +FAError pf2_fsnext(FADta* dta) { + s32 err = PFDIR_fsnext(dta); + err = PFAPI_convertReturnValue(err); return err; } diff --git a/libs/RVL_SDK/src/fa/pf_fstat.c b/libs/RVL_SDK/src/fa/pf_fstat.c new file mode 100644 index 00000000..ea96aff3 --- /dev/null +++ b/libs/RVL_SDK/src/fa/pf_fstat.c @@ -0,0 +1,32 @@ +#include + +typedef struct PFF2_STR { + const s8* p_head; + const s8* p_tail; + const s8* p_current; + u32 code_mode; +} PFF2_STR; + +typedef struct PFF2_VOL_SET { + u8 reserved[0x40]; + s32 last_error; +} PFF2_VOL_SET; + +extern PFF2_VOL_SET pf_vol_set; +extern s32 PFSTR_InitStr(PFF2_STR* path, const s8* text, u32 code_mode); +extern s32 PFDIR_fstat(PFF2_STR* path, FAFileStat* file_stat); +extern s32 PFAPI_convertReturnValue(s32 err); + +FAError pf2_fstat(const char* fileName, FAFileStat* stat) { + s32 err; + PFF2_STR path_str; + + err = PFSTR_InitStr(&path_str, (const s8*)fileName, 1); + if (err == 0) { + err = PFDIR_fstat(&path_str, stat); + } else { + pf_vol_set.last_error = err; + } + err = PFAPI_convertReturnValue(err); + return err; +} -- 2.49.1