id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
22,900
ControllerState.cpp
cemu-project_Cemu/src/input/api/ControllerState.cpp
#include "input/api/ControllerState.h" bool ControllerState::operator==(const ControllerState& other) const { return buttons == other.buttons; /*&& (std::signbit(axis.x) == std::signbit(other.axis.x) && std::abs(axis.x - other.axis.x) <= kAxisThreshold) && (std::signbit(axis.y) == std::signbit(other.axis.y) && std::abs(axis.y - other.axis.y) <= kAxisThreshold) && (std::signbit(rotation.x) == std::signbit(other.rotation.x) && std::abs(rotation.x - other.rotation.x) <= kAxisThreshold) && (std::signbit(rotation.y) == std::signbit(other.rotation.y) && std::abs(rotation.y - other.rotation.y) <= kAxisThreshold) && (std::signbit(trigger.x) == std::signbit(other.trigger.x) && std::abs(trigger.x - other.trigger.x) <= kAxisThreshold) && (std::signbit(trigger.y) == std::signbit(other.trigger.y) && std::abs(trigger.y - other.trigger.y) <= kAxisThreshold);*/ }
880
C++
.cpp
11
77.181818
126
0.683295
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,901
DirectInputControllerProvider.cpp
cemu-project_Cemu/src/input/api/DirectInput/DirectInputControllerProvider.cpp
#include "input/api/DirectInput/DirectInputControllerProvider.h" #include "input/api/DirectInput/DirectInputController.h" DirectInputControllerProvider::DirectInputControllerProvider() { /*m_module = LoadLibraryA("dinput8.dll"); if (!m_module) throw std::runtime_error("can't load any xinput dll"); m_DirectInput8Create = (decltype(&DirectInput8Create))GetProcAddress(m_module, "DirectInput8Create"); m_GetdfDIJoystick = (decltype(&GetdfDIJoystick))GetProcAddress(m_module, "GetdfDIJoystick"); if (!m_DirectInput8Create) { FreeLibrary(m_module); throw std::runtime_error("can't find the DirectInput8Create export"); }*/ const auto r = DirectInput8Create(GetModuleHandle(nullptr), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&m_dinput8, nullptr); if (FAILED(r) || !m_dinput8) { const auto error = GetLastError(); //FreeLibrary(m_module); throw std::runtime_error(fmt::format("can't create direct input object (error: {:#x})", error)); } } DirectInputControllerProvider::~DirectInputControllerProvider() { if (m_dinput8) m_dinput8->Release(); /*if (m_module) FreeLibrary(m_module); */ } std::vector<std::shared_ptr<ControllerBase>> DirectInputControllerProvider::get_controllers() { std::vector<std::shared_ptr<ControllerBase>> result; m_dinput8->EnumDevices(DI8DEVCLASS_GAMECTRL, [](LPCDIDEVICEINSTANCE lpddi, LPVOID pvRef) -> BOOL { auto* controllers = (decltype(&result))pvRef; std::string display_name = boost::nowide::narrow(lpddi->tszProductName); controllers->emplace_back(std::make_shared<DirectInputController>(lpddi->guidInstance, display_name)); return DIENUM_CONTINUE; }, &result, DIEDFL_ALLDEVICES); return result; } LPCDIDATAFORMAT DirectInputControllerProvider::get_data_format() const { /*if (m_GetdfDIJoystick) return m_GetdfDIJoystick();*/ return GetdfDIJoystick(); }
1,864
C++
.cpp
49
35.489796
130
0.769788
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,902
DirectInputController.cpp
cemu-project_Cemu/src/input/api/DirectInput/DirectInputController.cpp
#include "input/api/DirectInput/DirectInputController.h" #include "gui/guiWrapper.h" DirectInputController::DirectInputController(const GUID& guid) : base_type(StringFromGUID(guid), fmt::format("[{}]", StringFromGUID(guid))), m_guid{ guid } { } DirectInputController::DirectInputController(const GUID& guid, std::string_view display_name) : base_type(StringFromGUID(guid), display_name), m_guid(guid) { } DirectInputController::~DirectInputController() { if (m_effect) m_effect->Release(); if (m_device) { m_device->Unacquire(); // TODO: test if really needed // workaround for gamecube controllers crash on release? bool should_release_device = true; if (m_product_guid == GUID{}) { DIDEVICEINSTANCE info{}; info.dwSize = sizeof(DIDEVICEINSTANCE); if (SUCCEEDED(m_device->GetDeviceInfo(&info))) { m_product_guid = info.guidProduct; } } // info.guidProduct = {18440079-0000-0000-0000-504944564944} constexpr GUID kGameCubeController = { 0x18440079, 0, 0, {0,0,0x50,0x49,0x44,0x56,0x49,0x44} }; if (kGameCubeController == m_product_guid) should_release_device = false; if (should_release_device) m_device->Release(); } } void DirectInputController::save(pugi::xml_node& node) { base_type::save(node); node.append_child("product_guid").append_child(pugi::node_pcdata).set_value( fmt::format("{}", StringFromGUID(m_product_guid)).c_str()); } void DirectInputController::load(const pugi::xml_node& node) { base_type::load(node); if (const auto value = node.child("product_guid")) { if (GUIDFromString(value.child_value(), m_product_guid) && m_product_guid != GUID{} && !is_connected()) { // test if another controller with the same product guid is connectable and replace for(const auto& c : m_provider->get_controllers()) { if(const auto ptr = std::dynamic_pointer_cast<DirectInputController>(c)) { if (ptr->is_connected() && ptr->get_product_guid() == m_product_guid) { const auto tmp_guid = m_guid; m_guid = ptr->get_guid(); if (connect()) break; // couldn't connect m_guid = tmp_guid; } } } } } } bool DirectInputController::connect() { if (is_connected()) return true; m_effect = nullptr; std::scoped_lock lock(m_mutex); HRESULT hr = m_provider->get_dinput()->CreateDevice(m_guid, &m_device, nullptr); if (FAILED(hr) || m_device == nullptr) return false; DIDEVICEINSTANCE idi{}; idi.dwSize = sizeof(DIDEVICEINSTANCE); if (SUCCEEDED(m_device->GetDeviceInfo(&idi))) { // overwrite guid name with "real" display name m_display_name = boost::nowide::narrow(idi.tszProductName); } // set data format if (FAILED(m_device->SetDataFormat(m_provider->get_data_format()))) { SAFE_RELEASE(m_device); return false; } HWND hwndMainWindow = gui_getWindowInfo().window_main.hwnd; // set access if (FAILED(m_device->SetCooperativeLevel(hwndMainWindow, DISCL_BACKGROUND | DISCL_EXCLUSIVE))) { if (FAILED(m_device->SetCooperativeLevel(hwndMainWindow, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE))) { SAFE_RELEASE(m_device); return false; } // rumble can only be used with exclusive access } else { GUID guid_effect = GUID_NULL; // check if constant force is supported HRESULT result = m_device->EnumEffects([](LPCDIEFFECTINFOW eff, LPVOID guid) -> BOOL { *(GUID*)guid = eff->guid; return DIENUM_STOP; }, &guid_effect, DIEFT_CONSTANTFORCE); if (SUCCEEDED(result) && guid_effect != GUID_NULL) { DWORD dwAxes[2] = { DIJOFS_X, DIJOFS_Y }; LONG lDirection[2] = { 1, 0 }; DICONSTANTFORCE constant_force = { DI_FFNOMINALMAX }; // DI_FFNOMINALMAX -> should be max normally?! DIEFFECT effect{}; effect.dwSize = sizeof(DIEFFECT); effect.dwFlags = DIEFF_CARTESIAN | DIEFF_OBJECTOFFSETS; effect.dwDuration = INFINITE; // DI_SECONDS; effect.dwGain = DI_FFNOMINALMAX; // No scaling effect.dwTriggerButton = DIEB_NOTRIGGER; // Not a button response DIEB_NOTRIGGER DIJOFS_BUTTON0 effect.cAxes = 2; effect.rgdwAxes = dwAxes; effect.rglDirection = lDirection; effect.cbTypeSpecificParams = sizeof(DICONSTANTFORCE); effect.lpvTypeSpecificParams = &constant_force; m_device->CreateEffect(guid_effect, &effect, &m_effect, nullptr); } } DIDEVICEINSTANCE info{}; info.dwSize = sizeof(DIDEVICEINSTANCE); if (SUCCEEDED(m_device->GetDeviceInfo(&info))) { m_product_guid = info.guidProduct; } std::fill(m_min_axis.begin(), m_min_axis.end(), 0); std::fill(m_max_axis.begin(), m_max_axis.end(), std::numeric_limits<uint16>::max()); m_device->EnumObjects( [](LPCDIDEVICEOBJECTINSTANCE lpddoi, LPVOID pvRef) -> BOOL { auto* thisptr = (DirectInputController*)pvRef; const auto instance = DIDFT_GETINSTANCE(lpddoi->dwType); // some tools may use state.rglSlider properties, so they have 8 instead of 6 axis if(instance >= thisptr->m_min_axis.size()) { return DIENUM_CONTINUE; } DIPROPRANGE range{}; range.diph.dwSize = sizeof(range); range.diph.dwHeaderSize = sizeof(range.diph); range.diph.dwHow = DIPH_BYID; range.diph.dwObj = lpddoi->dwType; if (thisptr->m_device->GetProperty(DIPROP_RANGE, &range.diph) == DI_OK) { thisptr->m_min_axis[instance] = range.lMin; thisptr->m_max_axis[instance] = range.lMax; } return DIENUM_CONTINUE; }, this, DIDFT_AXIS); m_device->Acquire(); return true; } bool DirectInputController::is_connected() { std::shared_lock lock(m_mutex); return m_device != nullptr; } bool DirectInputController::has_rumble() { return m_effect != nullptr; } void DirectInputController::start_rumble() { if (!has_rumble()) return; } void DirectInputController::stop_rumble() { if (!has_rumble()) return; } std::string DirectInputController::get_button_name(uint64 button) const { switch(button) { case kAxisXP: return "X+"; case kAxisYP: return "Y+"; case kAxisXN: return "X-"; case kAxisYN: return "Y-"; case kRotationXP: return "RX+"; case kRotationYP: return "RY+"; case kRotationXN: return "RX-"; case kRotationYN: return "RY-"; case kTriggerXP: return "Z+"; case kTriggerYP: return "RZ+"; case kTriggerXN: return "Z-"; case kTriggerYN: return "RZ-"; } return base_type::get_button_name(button); } ControllerState DirectInputController::raw_state() { ControllerState result{}; if (!is_connected()) return result; HRESULT hr = m_device->Poll(); if (FAILED(hr)) { if (hr == DIERR_INPUTLOST || hr == DIERR_NOTACQUIRED) { result.last_state = hr; m_device->Acquire(); } return result; } DIJOYSTATE state{}; hr = m_device->GetDeviceState(sizeof(state), &state); if (FAILED(hr)) { if (hr == DIERR_INPUTLOST || hr == DIERR_NOTACQUIRED) { result.last_state = hr; m_device->Acquire(); } return result; } result.last_state = hr; // buttons for (size_t i = 0; i < std::size(state.rgbButtons); ++i) { if (HAS_BIT(state.rgbButtons[i], 7)) result.buttons.SetButtonState(i, true); } // axis constexpr float kThreshold = 0.001f; float v = (float(state.lX - m_min_axis[0]) / float(m_max_axis[0] - m_min_axis[0])) * 2.0f - 1.0f; if (std::abs(v) >= kThreshold) result.axis.x = v; v = (float(state.lY - m_min_axis[1]) / float(m_max_axis[1] - m_min_axis[1])) * 2.0f - 1.0f; if (std::abs(v) >= kThreshold) result.axis.y = -v; // Right Stick v = (float(state.lRx - m_min_axis[3]) / float(m_max_axis[3] - m_min_axis[3])) * 2.0f - 1.0f; if (std::abs(v) >= kThreshold) result.rotation.x = v; v = (float(state.lRy - m_min_axis[4]) / float(m_max_axis[4] - m_min_axis[4])) * 2.0f - 1.0f; if (std::abs(v) >= kThreshold) result.rotation.y = -v; // Trigger v = (float(state.lZ - m_min_axis[2]) / float(m_max_axis[2] - m_min_axis[2])) * 2.0f - 1.0f; if (std::abs(v) >= kThreshold) result.trigger.x = v; v = (float(state.lRz - m_min_axis[5]) / float(m_max_axis[5] - m_min_axis[5])) * 2.0f - 1.0f; if (std::abs(v) >= kThreshold) result.trigger.y = -v; // dpad const auto pov = state.rgdwPOV[0]; if (pov != static_cast<DWORD>(-1)) { switch (pov) { case 0: result.buttons.SetButtonState(kButtonUp, true); break; case 4500: result.buttons.SetButtonState(kButtonUp, true); // up + right case 9000: result.buttons.SetButtonState(kButtonRight, true); break; case 13500: result.buttons.SetButtonState(kButtonRight, true); // right + down case 18000: result.buttons.SetButtonState(kButtonDown, true); break; case 22500: result.buttons.SetButtonState(kButtonDown, true); // down + left case 27000: result.buttons.SetButtonState(kButtonLeft, true); break; case 31500: result.buttons.SetButtonState(kButtonLeft, true); // left + up result.buttons.SetButtonState(kButtonUp, true); // left + up break; } } return result; }
8,788
C++
.cpp
279
28.512545
105
0.695997
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,903
XInputController.cpp
cemu-project_Cemu/src/input/api/XInput/XInputController.cpp
#include "input/api/XInput/XInputController.h" XInputController::XInputController(uint32 index) : base_type(fmt::format("{}", index), fmt::format("Controller {}", index + 1)) { if (index >= XUSER_MAX_COUNT) throw std::runtime_error(fmt::format("invalid xinput index {} (must be smaller than {})", index, XUSER_MAX_COUNT)); m_index = index; m_settings.axis.deadzone = m_settings.rotation.deadzone = m_settings.trigger.deadzone = 0.15f; } bool XInputController::connect() { if (m_connected) return true; m_has_battery = false; XINPUT_CAPABILITIES caps{}; m_connected = m_provider->m_XInputGetCapabilities(m_index, XINPUT_FLAG_GAMEPAD, &caps) != ERROR_DEVICE_NOT_CONNECTED; if (!m_connected) return false; m_has_rumble = (caps.Vibration.wLeftMotorSpeed > 0) || (caps.Vibration.wRightMotorSpeed > 0); if (m_provider->m_XInputGetBatteryInformation) { XINPUT_BATTERY_INFORMATION battery{}; if (m_provider->m_XInputGetBatteryInformation(m_index, BATTERY_DEVTYPE_GAMEPAD, &battery) == ERROR_SUCCESS) { m_has_battery = (battery.BatteryType == BATTERY_TYPE_ALKALINE || battery.BatteryType == BATTERY_TYPE_NIMH); } } return m_connected; } bool XInputController::is_connected() { return m_connected; } void XInputController::start_rumble() { if (!has_rumble() || m_settings.rumble <= 0) return; XINPUT_VIBRATION vibration; vibration.wLeftMotorSpeed = static_cast<WORD>(m_settings.rumble * std::numeric_limits<uint16>::max()); vibration.wRightMotorSpeed = static_cast<WORD>(m_settings.rumble * std::numeric_limits<uint16>::max()); m_provider->m_XInputSetState(m_index, &vibration); } void XInputController::stop_rumble() { if (!has_rumble()) return; XINPUT_VIBRATION vibration{}; m_provider->m_XInputSetState(m_index, &vibration); } bool XInputController::has_low_battery() { if (!has_battery()) return false; XINPUT_BATTERY_INFORMATION battery{}; if (m_provider->m_XInputGetBatteryInformation(m_index, BATTERY_DEVTYPE_GAMEPAD, &battery) == ERROR_SUCCESS) { return (battery.BatteryType == BATTERY_TYPE_ALKALINE || battery.BatteryType == BATTERY_TYPE_NIMH) && battery .BatteryLevel <= BATTERY_LEVEL_LOW; } return false; } std::string XInputController::get_button_name(uint64 button) const { switch (1ULL << button) { case XINPUT_GAMEPAD_A: return "A"; case XINPUT_GAMEPAD_B: return "B"; case XINPUT_GAMEPAD_X: return "X"; case XINPUT_GAMEPAD_Y: return "Y"; case XINPUT_GAMEPAD_LEFT_SHOULDER: return "L"; case XINPUT_GAMEPAD_RIGHT_SHOULDER: return "R"; case XINPUT_GAMEPAD_START: return "Start"; case XINPUT_GAMEPAD_BACK: return "Select"; case XINPUT_GAMEPAD_LEFT_THUMB: return "L-Stick"; case XINPUT_GAMEPAD_RIGHT_THUMB: return "R-Stick"; case XINPUT_GAMEPAD_DPAD_UP: return "DPAD-Up"; case XINPUT_GAMEPAD_DPAD_DOWN: return "DPAD-Down"; case XINPUT_GAMEPAD_DPAD_LEFT: return "DPAD-Left"; case XINPUT_GAMEPAD_DPAD_RIGHT: return "DPAD-Right"; } return Controller::get_button_name(button); } ControllerState XInputController::raw_state() { ControllerState result{}; if (!m_connected) return result; XINPUT_STATE state; if (m_provider->m_XInputGetState(m_index, &state) != ERROR_SUCCESS) { m_connected = false; return result; } // Buttons for(int i=0;i<std::numeric_limits<WORD>::digits;i++) result.buttons.SetButtonState(i, (state.Gamepad.wButtons & (1 << i)) != 0); if (state.Gamepad.sThumbLX > 0) result.axis.x = (float)state.Gamepad.sThumbLX / std::numeric_limits<sint16>::max(); else if (state.Gamepad.sThumbLX < 0) result.axis.x = (float)-state.Gamepad.sThumbLX / std::numeric_limits<sint16>::min(); if (state.Gamepad.sThumbLY > 0) result.axis.y = (float)state.Gamepad.sThumbLY / std::numeric_limits<sint16>::max(); else if (state.Gamepad.sThumbLY < 0) result.axis.y = (float)-state.Gamepad.sThumbLY / std::numeric_limits<sint16>::min(); // Right Stick if (state.Gamepad.sThumbRX > 0) result.rotation.x = (float)state.Gamepad.sThumbRX / std::numeric_limits<sint16>::max(); else if (state.Gamepad.sThumbRX < 0) result.rotation.x = (float)-state.Gamepad.sThumbRX / std::numeric_limits<sint16>::min(); if (state.Gamepad.sThumbRY > 0) result.rotation.y = (float)state.Gamepad.sThumbRY / std::numeric_limits<sint16>::max(); else if (state.Gamepad.sThumbRY < 0) result.rotation.y = (float)-state.Gamepad.sThumbRY / std::numeric_limits<sint16>::min(); // Trigger result.trigger.x = (float)state.Gamepad.bLeftTrigger / std::numeric_limits<uint8>::max(); result.trigger.y = (float)state.Gamepad.bRightTrigger / std::numeric_limits<uint8>::max(); return result; }
4,639
C++
.cpp
120
36.016667
110
0.732441
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,904
XInputControllerProvider.cpp
cemu-project_Cemu/src/input/api/XInput/XInputControllerProvider.cpp
#include <Windows.h> #include "input/api/XInput/XInputControllerProvider.h" #include "input/api/XInput/XInputController.h" XInputControllerProvider::XInputControllerProvider() { // try to load newest to oldest m_module = LoadLibraryA("XInput1_4.DLL"); if (!m_module) { m_module = LoadLibraryA("XInput1_3.DLL"); if (!m_module) { m_module = LoadLibraryA("XInput9_1_0.dll"); if (!m_module) throw std::runtime_error("can't load any xinput dll"); } } #define GET_XINPUT_PROC(__FUNC__) m_##__FUNC__ = (decltype(m_##__FUNC__))GetProcAddress(m_module, #__FUNC__) GET_XINPUT_PROC(XInputGetCapabilities); GET_XINPUT_PROC(XInputGetState); GET_XINPUT_PROC(XInputSetState); if (!m_XInputGetCapabilities || !m_XInputGetState || !m_XInputSetState) { FreeLibrary(m_module); throw std::runtime_error("can't find necessary xinput functions"); } // only available in XInput1_4 and XInput1_3 GET_XINPUT_PROC(XInputGetBatteryInformation); #undef GET_XINPUT_PROC } XInputControllerProvider::~XInputControllerProvider() { if (m_module) FreeLibrary(m_module); } std::vector<std::shared_ptr<ControllerBase>> XInputControllerProvider::get_controllers() { std::vector<std::shared_ptr<ControllerBase>> result; for(DWORD i = 0; i < XUSER_MAX_COUNT; ++i) { XINPUT_CAPABILITIES caps; if (m_XInputGetCapabilities(i, XINPUT_FLAG_GAMEPAD, &caps) == ERROR_SUCCESS) { result.emplace_back(std::make_shared<XInputController>(i)); } } return result; }
1,476
C++
.cpp
48
28.4375
108
0.740662
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,905
DSUMessages.cpp
cemu-project_Cemu/src/input/api/DSU/DSUMessages.cpp
#include "input/api/DSU/DSUMessages.h" #include "util/crypto/crc32.h" constexpr uint32_t kMagicClient = 'CUSD'; constexpr uint32_t kMagicServer = 'SUSD'; constexpr uint16_t kProtocolVersion = 1001; MessageHeader::MessageHeader(uint32_t magic, uint32_t uid) : m_magic(magic), m_protocol_version(kProtocolVersion), m_uid(uid) { } void MessageHeader::Finalize(size_t size) { m_packet_size = (uint16_t)(size - sizeof(MessageHeader)); m_crc32 = CRC32(size); } uint32_t MessageHeader::CRC32(size_t size) const { uint32_t tmp, tmp2; tmp = m_crc32; m_crc32 = 0; tmp2 = crc32_calc(this, size); m_crc32 = tmp; return tmp2; } bool MessageHeader::IsClientMessage() const { return m_magic == kMagicClient; } bool MessageHeader::IsServerMessage() const { return m_magic == kMagicServer; } Message::Message(uint32_t magic, uint32_t uid, MessageType type) : MessageHeader(magic, uid), m_message_type(type) { } ClientMessage::ClientMessage(uint32_t uid, MessageType message_type) : Message(kMagicClient, uid, message_type) { } VersionRequest::VersionRequest(uint32_t uid) : ClientMessage(uid, MessageType::Version) { Finalize(sizeof(VersionRequest)); } ListPorts::ListPorts(uint32_t uid, uint32_t num_pads_requests, const std::array<uint8_t, 4>& request_indices) : ClientMessage(uid, MessageType::Information), m_count(num_pads_requests), m_indices(request_indices) { Finalize(sizeof(ListPorts)); } DataRequest::DataRequest(uint32_t uid) : ClientMessage(uid, MessageType::Data), m_reg_flags(RegisterFlag::AllPads), m_index(0), m_mac_address({}) { Finalize(sizeof(DataRequest)); } DataRequest::DataRequest(uint32_t uid, uint8_t index) : ClientMessage(uid, MessageType::Data), m_reg_flags(RegisterFlag::Index), m_index(index), m_mac_address({}) { Finalize(sizeof(DataRequest)); } DataRequest::DataRequest(uint32_t uid, const MACAddress_t& mac_address) : ClientMessage(uid, MessageType::Data), m_reg_flags(RegisterFlag::MACAddress), m_index(0), m_mac_address(mac_address) { Finalize(sizeof(DataRequest)); } DataRequest::DataRequest(uint32_t uid, uint8_t index, const MACAddress_t& mac_address) : ClientMessage(uid, MessageType::Data), m_reg_flags(RegisterFlag::Index | RegisterFlag::MACAddress), m_index(index), m_mac_address(mac_address) { Finalize(sizeof(DataRequest)); } bool ServerMessage::ValidateCRC32(size_t size) const { return GetCRC32() == CRC32(size); } bool VersionResponse::IsValid() const { return ValidateCRC32(sizeof(VersionResponse)); } bool PortInfo::IsValid() const { return ValidateCRC32(sizeof(PortInfo)); } bool DataResponse::IsValid() const { return ValidateCRC32(sizeof(DataResponse)); }
2,640
C++
.cpp
75
33.56
145
0.769654
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,906
DSUController.cpp
cemu-project_Cemu/src/input/api/DSU/DSUController.cpp
#include "input/api/DSU/DSUController.h" #include <boost/program_options/value_semantic.hpp> DSUController::DSUController(uint32 index) : base_type(fmt::format("{}", index), fmt::format("Controller {}", index + 1)), m_index(index) { if (index >= DSUControllerProvider::kMaxClients) throw std::runtime_error(fmt::format("max {} dsu controllers are supported! given index: {}", DSUControllerProvider::kMaxClients, index)); } DSUController::DSUController(uint32 index, const DSUProviderSettings& settings) : base_type(fmt::format("{}", index), fmt::format("Controller {}", index + 1), settings), m_index(index) { if (index >= DSUControllerProvider::kMaxClients) throw std::runtime_error(fmt::format("max {} dsu controllers are supported! given index: {}", DSUControllerProvider::kMaxClients, index)); } void DSUController::save(pugi::xml_node& node) { base_type::save(node); node.append_child("ip").append_child(pugi::node_pcdata).set_value( fmt::format("{}", m_provider->get_settings().ip).c_str()); node.append_child("port").append_child(pugi::node_pcdata).set_value( fmt::format("{}", m_provider->get_settings().port).c_str()); } void DSUController::load(const pugi::xml_node& node) { base_type::load(node); DSUProviderSettings settings; if (const auto value = node.child("ip")) settings.ip = value.child_value(); if (const auto value = node.child("port")) settings.port = ConvertString<uint16>(value.child_value()); const auto provider = InputManager::instance().get_api_provider(api(), settings); update_provider(std::dynamic_pointer_cast<DSUControllerProvider>(provider)); connect(); } bool DSUController::connect() { if (is_connected()) return true; m_provider->request_pad_data(m_index); return is_connected(); } bool DSUController::is_connected() { return m_provider->is_connected(m_index); } MotionSample DSUController::get_motion_sample() { return m_provider->get_motion_sample(m_index); } bool DSUController::has_position() { const auto state = m_provider->get_state(m_index); return state.data.tpad1.active || state.data.tpad2.active; } glm::vec2 DSUController::get_position() { // touchpad resolution is 1920x942 const auto state = m_provider->get_state(m_index); if (state.data.tpad1.active) return glm::vec2{(float)state.data.tpad1.x / 1920.0f, (float)state.data.tpad1.y / 942.0f}; if (state.data.tpad2.active) return glm::vec2{(float)state.data.tpad2.x / 1920.0f, (float)state.data.tpad2.y / 942.0f}; return {}; } glm::vec2 DSUController::get_prev_position() { const auto state = m_provider->get_prev_state(m_index); if (state.data.tpad1.active) return glm::vec2{(float)state.data.tpad1.x / 1920.0f, (float)state.data.tpad1.y / 942.0f}; if (state.data.tpad2.active) return glm::vec2{(float)state.data.tpad2.x / 1920.0f, (float)state.data.tpad2.y / 942.0f}; return {}; } PositionVisibility DSUController::GetPositionVisibility() { const auto state = m_provider->get_prev_state(m_index); return (state.data.tpad1.active || state.data.tpad2.active) ? PositionVisibility::FULL : PositionVisibility::NONE; } std::string DSUController::get_button_name(uint64 button) const { switch (button) { case kButton0: return "Share"; case kButton1: return "Stick L"; case kButton2: return "Stick R"; case kButton3: return "Options"; case kButton4: return "Up"; case kButton5: return "Right"; case kButton6: return "Down"; case kButton7: return "Left"; case kButton8: return "ZL"; case kButton9: return "ZR"; case kButton10: return "L"; case kButton11: return "R"; case kButton12: return "Triangle"; case kButton13: return "Circle"; case kButton14: return "Cross"; case kButton15: return "Square"; case kButton16: return "Touch"; } return base_type::get_button_name(button); } ControllerState DSUController::raw_state() { ControllerState result{}; if (!is_connected()) return result; const auto state = m_provider->get_state(m_index); // didn't read any data from the controller yet if (state.info.state != DsState::Connected) return result; int bitindex = 0; for (int i = 0; i < 8; ++i, ++bitindex) { if (HAS_BIT(state.data.state1, i)) { result.buttons.SetButtonState(bitindex, true); } } for (int i = 0; i < 8; ++i, ++bitindex) { if (HAS_BIT(state.data.state2, i)) { result.buttons.SetButtonState(bitindex, true); } } if (state.data.touch) result.buttons.SetButtonState(kButton16, true); result.axis.x = (float)state.data.lx / std::numeric_limits<uint8>::max(); result.axis.x = (result.axis.x * 2.0f) - 1.0f; result.axis.y = (float)state.data.ly / std::numeric_limits<uint8>::max(); result.axis.y = (result.axis.y * 2.0f) - 1.0f; result.rotation.x = (float)state.data.rx / std::numeric_limits<uint8>::max(); result.rotation.x = (result.rotation.x * 2.0f) - 1.0f; result.rotation.y = (float)state.data.ry / std::numeric_limits<uint8>::max(); result.rotation.y = (result.rotation.y * 2.0f) - 1.0f; result.trigger.x = (float)state.data.l2 / std::numeric_limits<uint8>::max(); result.trigger.y = (float)state.data.r2 / std::numeric_limits<uint8>::max(); return result; }
5,176
C++
.cpp
142
33.971831
115
0.718087
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,907
DSUControllerProvider.cpp
cemu-project_Cemu/src/input/api/DSU/DSUControllerProvider.cpp
#include "input/api/DSU/DSUControllerProvider.h" #include "input/api/DSU/DSUController.h" #if BOOST_OS_WINDOWS #include <boost/asio/detail/socket_option.hpp> #include <winsock2.h> #elif BOOST_OS_LINUX || BOOST_OS_MACOS #include <sys/time.h> #include <sys/socket.h> #endif DSUControllerProvider::DSUControllerProvider() : base_type(), m_uid(rand()), m_socket(m_io_service) { if (!connect()) { throw std::runtime_error("dsu client can't open the udp connection"); } m_running = true; m_reader_thread = std::thread(&DSUControllerProvider::reader_thread, this); m_writer_thread = std::thread(&DSUControllerProvider::writer_thread, this); request_version(); } DSUControllerProvider::DSUControllerProvider(const DSUProviderSettings& settings) : base_type(settings), m_uid(rand()), m_socket(m_io_service) { if (!connect()) { throw std::runtime_error("dsu client can't open the udp connection"); } m_running = true; m_reader_thread = std::thread(&DSUControllerProvider::reader_thread, this); m_writer_thread = std::thread(&DSUControllerProvider::writer_thread, this); request_version(); } DSUControllerProvider::~DSUControllerProvider() { if (m_running) { m_running = false; m_writer_thread.join(); m_reader_thread.join(); } } std::vector<std::shared_ptr<ControllerBase>> DSUControllerProvider::get_controllers() { std::vector<ControllerPtr> result; std::array<uint8_t, kMaxClients> indices; for (auto i = 0; i < kMaxClients; ++i) indices[i] = get_packet_index(i); request_pad_info(); const auto controller_result = wait_update(indices, 3000); for (auto i = 0; i < kMaxClients; ++i) { if (controller_result[i] && is_connected(i)) result.emplace_back(std::make_shared<DSUController>(i, m_settings)); } return result; } bool DSUControllerProvider::connect() { // already connected? if (m_receiver_endpoint.address().to_string() == get_settings().ip && m_receiver_endpoint.port() == get_settings().port) return true; try { using namespace boost::asio; ip::udp::resolver resolver(m_io_service); const ip::udp::resolver::query query(ip::udp::v4(), get_settings().ip, fmt::format("{}", get_settings().port), ip::udp::resolver::query::canonical_name); m_receiver_endpoint = *resolver.resolve(query); if (m_socket.is_open()) m_socket.close(); m_socket.open(ip::udp::v4()); // set timeout for our threads to give a chance to exit #if BOOST_OS_WINDOWS m_socket.set_option(boost::asio::detail::socket_option::integer<SOL_SOCKET, SO_RCVTIMEO>{200}); #elif BOOST_OS_LINUX || BOOST_OS_MACOS timeval timeout{.tv_usec = 200 * 1000}; setsockopt(m_socket.native_handle(), SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeval)); #endif // reset data m_state = {}; m_prev_state = {}; // restart threads return true; } catch (const std::exception& ex) { cemuLog_log(LogType::Force, "dsu client connect error: {}", ex.what()); return false; } } bool DSUControllerProvider::is_connected(uint8_t index) const { if (index >= kMaxClients) return false; std::scoped_lock lock(m_mutex[index]); return m_state[index].info.state == DsState::Connected; } DSUControllerProvider::ControllerState DSUControllerProvider::get_state(uint8_t index) const { if (index >= kMaxClients) return {}; std::scoped_lock lock(m_mutex[index]); return m_state[index]; } DSUControllerProvider::ControllerState DSUControllerProvider::get_prev_state(uint8_t index) const { if (index >= kMaxClients) return {}; std::scoped_lock lock(m_mutex[index]); return m_prev_state[index]; } std::array<bool, DSUControllerProvider::kMaxClients> DSUControllerProvider::wait_update( const std::array<uint8_t, kMaxClients>& indices, size_t timeout) const { std::array<bool, kMaxClients> result{false, false, false, false}; const auto end = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout); do { for (int i = 0; i < kMaxClients; ++i) { if (result[i]) continue; std::unique_lock lock(m_mutex[i]); result[i] = indices[i] < m_state[i].packet_index; } if (std::all_of(result.cbegin(), result.cend(), [](const bool& v) { return v == true; })) break; //std::this_thread::sleep_for(std::chrono::milliseconds(1)); std::this_thread::yield(); } while (std::chrono::steady_clock::now() < end); return result; } bool DSUControllerProvider::wait_update(uint8_t index, uint32_t packet_index, size_t timeout) const { if (index >= kMaxClients) return false; std::unique_lock lock(m_mutex[index]); if (packet_index < m_state[index].packet_index) return true; const auto result = m_wait_cond[index].wait_for(lock, std::chrono::milliseconds(timeout), [this, index, packet_index]() { return packet_index < m_state[index].packet_index; }); return result; } uint32_t DSUControllerProvider::get_packet_index(uint8_t index) const { std::scoped_lock lock(m_mutex[index]); return m_state[index].packet_index; } void DSUControllerProvider::request_version() { auto msg = std::make_unique<VersionRequest>(m_uid); std::scoped_lock lock(m_writer_mutex); m_writer_jobs.push(std::move(msg)); m_writer_cond.notify_one(); } void DSUControllerProvider::request_pad_info() { auto msg = std::make_unique<ListPorts>(m_uid, 4, std::array<uint8_t, 4>{0, 1, 2, 3}); std::scoped_lock lock(m_writer_mutex); m_writer_jobs.push(std::move(msg)); m_writer_cond.notify_one(); } void DSUControllerProvider::request_pad_info(uint8_t index) { if (index >= kMaxClients) return; auto msg = std::make_unique<ListPorts>(m_uid, 1, std::array<uint8_t, 4>{index}); std::scoped_lock lock(m_writer_mutex); m_writer_jobs.push(std::move(msg)); m_writer_cond.notify_one(); } void DSUControllerProvider::request_pad_data() { auto msg = std::make_unique<DataRequest>(m_uid); std::scoped_lock lock(m_writer_mutex); m_writer_jobs.push(std::move(msg)); m_writer_cond.notify_one(); } void DSUControllerProvider::request_pad_data(uint8_t index) { if (index >= kMaxClients) return; auto msg = std::make_unique<DataRequest>(m_uid, index); std::scoped_lock lock(m_writer_mutex); m_writer_jobs.push(std::move(msg)); m_writer_cond.notify_one(); } MotionSample DSUControllerProvider::get_motion_sample(uint8_t index) const { if (index >= kMaxClients) return MotionSample(); std::scoped_lock lock(m_mutex[index]); return m_state[index].motion_sample; } void DSUControllerProvider::reader_thread() { SetThreadName("DSU-reader"); bool first_read = true; while (m_running.load(std::memory_order_relaxed)) { ServerMessage* msg; //try //{ std::array<char, 100> recv_buf; // NOLINT(cppcoreguidelines-pro-type-member-init, hicpp-member-init) boost::asio::ip::udp::endpoint sender_endpoint; boost::system::error_code ec{}; const size_t len = m_socket.receive_from(boost::asio::buffer(recv_buf), sender_endpoint, 0, ec); if (ec) { #ifdef DEBUG_DSU_CLIENT printf(" DSUControllerProvider::ReaderThread: exception %s\n", ec.what()); #endif // there's probably no server listening on the given address:port if (first_read) // workaroud: first read always fails? first_read = false; else { std::this_thread::sleep_for(std::chrono::milliseconds(250)); std::this_thread::yield(); } continue; } #ifdef DEBUG_DSU_CLIENT printf(" DSUControllerProvider::ReaderThread: received message with len: 0x%llx\n", len); #endif if (len < sizeof(ServerMessage)) // cant be a valid message continue; msg = (ServerMessage*)recv_buf.data(); // } // catch (const std::exception&) // { //#ifdef DEBUG_DSU_CLIENT // printf(" DSUControllerProvider::ReaderThread: exception %s\n", ex.what()); //#endif // // // there's probably no server listening on the given address:port // if (first_read) // workaroud: first read always fails? // first_read = false; // else // { // std::this_thread::sleep_for(std::chrono::milliseconds(250)); // std::this_thread::yield(); // } // continue; // } uint8_t index = 0xFF; switch (msg->GetMessageType()) { case MessageType::Version: { const auto rsp = (VersionResponse*)msg; if (!rsp->IsValid()) { #ifdef DEBUG_DSU_CLIENT printf(" DSUControllerProvider::ReaderThread: VersionResponse is invalid!\n"); #endif continue; } #ifdef DEBUG_DSU_CLIENT printf(" DSUControllerProvider::ReaderThread: server version is: 0x%x\n", rsp->GetVersion()); #endif m_server_version = rsp->GetVersion(); // wdc break; } case MessageType::Information: { const auto info = (PortInfo*)msg; if (!info->IsValid()) { #ifdef DEBUG_DSU_CLIENT printf(" DSUControllerProvider::ReaderThread: PortInfo is invalid!\n"); #endif continue; } index = info->GetIndex(); #ifdef DEBUG_DSU_CLIENT printf(" DSUControllerProvider::ReaderThread: received PortInfo for index %d\n", index); #endif auto& mutex = m_mutex[index]; std::scoped_lock lock(mutex); m_prev_state[index] = m_state[index]; m_state[index] = *info; m_wait_cond[index].notify_all(); break; } case MessageType::Data: { const auto rsp = (DataResponse*)msg; if (!rsp->IsValid()) { #ifdef DEBUG_DSU_CLIENT printf(" DSUControllerProvider::ReaderThread: DataResponse is invalid!\n"); #endif continue; } index = rsp->GetIndex(); #ifdef DEBUG_DSU_CLIENT printf(" DSUControllerProvider::ReaderThread: received DataResponse for index %d\n", index); #endif auto& mutex = m_mutex[index]; std::scoped_lock lock(mutex); m_prev_state[index] = m_state[index]; m_state[index] = *rsp; m_wait_cond[index].notify_all(); // update motion info immediately, guaranteeing that we dont drop packets integrate_motion(index, *rsp); break; } } if (index != 0xFF) request_pad_data(index); } } void DSUControllerProvider::writer_thread() { SetThreadName("DSU-writer"); while (m_running.load(std::memory_order_relaxed)) { std::unique_lock lock(m_writer_mutex); while (m_writer_jobs.empty()) { if (m_writer_cond.wait_for(lock, std::chrono::milliseconds(250)) == std::cv_status::timeout) { if (!m_running.load(std::memory_order_relaxed)) return; } } const auto msg = std::move(m_writer_jobs.front()); m_writer_jobs.pop(); lock.unlock(); #ifdef DEBUG_DSU_CLIENT printf(" DSUControllerProvider::WriterThread: sending message: 0x%x (len: 0x%x)\n", (int)msg->GetMessageType(), msg->GetSize()); #endif try { m_socket.send_to(boost::asio::buffer(msg.get(), msg->GetSize()), m_receiver_endpoint); } catch (const std::exception& ec) { #ifdef DEBUG_DSU_CLIENT printf(" DSUControllerProvider::WriterThread: exception %s\n", ec.what()); #endif std::this_thread::sleep_for(std::chrono::milliseconds(250)); } } } void DSUControllerProvider::integrate_motion(uint8_t index, const DataResponse& data_response) { const uint64 ts = data_response.GetMotionTimestamp(); if (ts <= m_last_motion_timestamp[index]) { const uint64 dif = m_last_motion_timestamp[index] - ts; if (dif >= 10000000) // timestamp more than 10 seconds in the past, a controller reset probably happened m_last_motion_timestamp[index] = 0; return; } const uint64 elapsedTime = ts - m_last_motion_timestamp[index]; m_last_motion_timestamp[index] = ts; const double elapsedTimeD = (double)elapsedTime / 1000000.0; const auto& acc = data_response.GetAcceleration(); const auto& gyro = data_response.GetGyro(); m_motion_handler[index].processMotionSample((float)elapsedTimeD, gyro.x * 0.0174533f, gyro.y * 0.0174533f, gyro.z * 0.0174533f, acc.x, -acc.y, -acc.z); m_state[index].motion_sample = m_motion_handler[index].getMotionSample(); } DSUControllerProvider::ControllerState& DSUControllerProvider::ControllerState::operator=(const PortInfo& port_info) { info = port_info.GetInfo(); last_update = std::chrono::steady_clock::now(); packet_index++; // increase packet index for every packet we assign/recv return *this; } DSUControllerProvider::ControllerState& DSUControllerProvider::ControllerState::operator=( const DataResponse& data_response) { this->operator=(static_cast<const PortInfo&>(data_response)); data = data_response.GetData(); return *this; }
12,759
C++
.cpp
390
28.705128
130
0.683581
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,908
GameCubeControllerProvider.cpp
cemu-project_Cemu/src/input/api/GameCube/GameCubeControllerProvider.cpp
#include "input/api/GameCube/GameCubeControllerProvider.h" #include "input/api/GameCube/GameCubeController.h" #include "util/libusbWrapper/libusbWrapper.h" #if HAS_GAMECUBE constexpr uint16_t kVendorId = 0x57e, kProductId = 0x337; GameCubeControllerProvider::GameCubeControllerProvider() { m_libusb = libusbWrapper::getInstance(); m_libusb->init(); if(!m_libusb->isAvailable()) throw std::runtime_error("libusbWrapper not available"); m_libusb->p_libusb_init(&m_context); for(auto i = 0; i < kMaxAdapters; ++i) { auto device = fetch_usb_device(i); if(std::get<0>(device)) { m_adapters[i].m_device_handle = std::get<0>(device); m_adapters[i].m_endpoint_reader = std::get<1>(device); m_adapters[i].m_endpoint_writer = std::get<2>(device); } } if (m_libusb->p_libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) { m_libusb->p_libusb_hotplug_register_callback(m_context, static_cast<libusb_hotplug_event>(LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED | LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT), LIBUSB_HOTPLUG_NO_FLAGS, kVendorId, kProductId, LIBUSB_HOTPLUG_MATCH_ANY, &GameCubeControllerProvider::hotplug_event, this, &m_callback_handle); } m_running = true; m_reader_thread = std::thread(&GameCubeControllerProvider::reader_thread, this); m_writer_thread = std::thread(&GameCubeControllerProvider::writer_thread, this); } GameCubeControllerProvider::~GameCubeControllerProvider() { if (m_running) { m_running = false; m_writer_thread.join(); m_reader_thread.join(); } if (m_callback_handle) { m_libusb->p_libusb_hotplug_deregister_callback(m_context, m_callback_handle); m_callback_handle = 0; } for (auto& a : m_adapters) { m_libusb->p_libusb_close(a.m_device_handle); } if (m_context) { m_libusb->p_libusb_exit(m_context); m_context = nullptr; } } std::vector<ControllerPtr> GameCubeControllerProvider::get_controllers() { std::vector<ControllerPtr> result; const auto adapter_count = get_adapter_count(); for (uint32 adapter_index = 0; adapter_index < adapter_count && adapter_index < kMaxAdapters; ++adapter_index) { // adapter doesn't tell us which one is actually connected, so we return all of them for (int index = 0; index < 4; ++index) result.emplace_back(std::make_shared<GameCubeController>(adapter_index, index)); } return result; } uint32 GameCubeControllerProvider::get_adapter_count() const { uint32 adapter_count = 0; libusb_device** devices; const auto count = m_libusb->p_libusb_get_device_list(nullptr, &devices); if (count < 0) { cemuLog_log(LogType::Force, "libusb error {} at libusb_get_device_list: {}", static_cast<int>(count), m_libusb->p_libusb_error_name(static_cast<int>(count))); return adapter_count; } for (ssize_t i = 0; i < count; ++i) { if (!devices[i]) continue; libusb_device_descriptor desc; int ret = m_libusb->p_libusb_get_device_descriptor(devices[i], &desc); if (ret != 0) { cemuLog_log(LogType::Force, "libusb error {} at libusb_get_device_descriptor: {}", ret, m_libusb->p_libusb_error_name(ret)); continue; } if (desc.idVendor != kVendorId || desc.idProduct != kProductId) continue; ++adapter_count; } m_libusb->p_libusb_free_device_list(devices, 1); return adapter_count; } bool GameCubeControllerProvider::has_rumble_connected(uint32 adapter_index) const { if (adapter_index >= m_adapters.size()) return false; std::scoped_lock lock(m_adapters[adapter_index].m_state_mutex); return m_adapters[adapter_index].m_rumble_connected; } bool GameCubeControllerProvider::is_connected(uint32 adapter_index) const { if (adapter_index >= m_adapters.size()) return false; return m_adapters[adapter_index].m_device_handle != nullptr; } void GameCubeControllerProvider::set_rumble_state(uint32 adapter_index, uint32 index, bool state) { if (adapter_index >= m_adapters.size()) return; if (index >= kMaxIndex) return; std::scoped_lock lock(m_writer_mutex); m_adapters[adapter_index].rumble_states[index] = state; m_rumble_changed = true; m_writer_cond.notify_all(); } GameCubeControllerProvider::GCState GameCubeControllerProvider::get_state(uint32 adapter_index, uint32 index) { if (adapter_index >= m_adapters.size()) return {}; if (index >= kMaxIndex) return {}; std::scoped_lock lock(m_adapters[adapter_index].m_state_mutex); return m_adapters[adapter_index].m_states[index]; } #ifdef interface #undef interface #endif std::tuple<libusb_device_handle*, uint8, uint8> GameCubeControllerProvider::fetch_usb_device(uint32 adapter) const { std::tuple<libusb_device_handle*, uint8, uint8> result{nullptr, 0xFF, 0xFF}; libusb_device** devices; const auto count = m_libusb->p_libusb_get_device_list(nullptr, &devices); if (count < 0) { cemuLog_log(LogType::Force, "libusb error {} at libusb_get_device_list: {}", static_cast<int>(count), m_libusb->p_libusb_error_name(static_cast<int>(count))); return result; } int adapter_index = 0; for (ssize_t i = 0; i < count; ++i) { if (!devices[i]) continue; libusb_device_descriptor desc; int ret = m_libusb->p_libusb_get_device_descriptor(devices[i], &desc); if (ret != 0) { cemuLog_log(LogType::Force, "libusb error {} at libusb_get_device_descriptor: {}", ret, m_libusb->p_libusb_error_name(ret)); continue; } if (desc.idVendor != kVendorId || desc.idProduct != kProductId) continue; if (adapter != adapter_index++) continue; libusb_device_handle* device_handle; ret = m_libusb->p_libusb_open(devices[i], &device_handle); if (ret != 0) { cemuLog_log(LogType::Force, "libusb error {} at libusb_open: {}", ret, m_libusb->p_libusb_error_name(ret)); continue; } if (m_libusb->p_libusb_kernel_driver_active(device_handle, 0) == 1) { ret = m_libusb->p_libusb_detach_kernel_driver(device_handle, 0); if (ret != 0) { cemuLog_log(LogType::Force, "libusb error {} at libusb_detach_kernel_driver: {}", ret, m_libusb->p_libusb_error_name(ret)); m_libusb->p_libusb_close(device_handle); continue; } } ret = m_libusb->p_libusb_claim_interface(device_handle, 0); if (ret != 0) { cemuLog_log(LogType::Force, "libusb error {} at libusb_claim_interface: {}", ret, m_libusb->p_libusb_error_name(ret)); m_libusb->p_libusb_close(device_handle); continue; } libusb_config_descriptor* config = nullptr; m_libusb->p_libusb_get_config_descriptor(devices[i], 0, &config); for (auto ic = 0; ic < config->bNumInterfaces; ic++) { const auto& interface = config->interface[ic]; for (auto j = 0; j < interface.num_altsetting; j++) { const auto& interface_desc = interface.altsetting[j]; for (auto k = 0; k < interface_desc.bNumEndpoints; k++) { const auto& endpoint = interface_desc.endpoint[k]; if (endpoint.bEndpointAddress & LIBUSB_ENDPOINT_IN) std::get<1>(result) = endpoint.bEndpointAddress; else std::get<2>(result) = endpoint.bEndpointAddress; } } } m_libusb->p_libusb_free_config_descriptor(config); // start polling int size = 0; uint8_t payload = 0x13; m_libusb->p_libusb_interrupt_transfer(device_handle, std::get<2>(result), &payload, sizeof(payload), &size, 25); std::get<0>(result) = device_handle; break; } m_libusb->p_libusb_free_device_list(devices, 1); return result; } void GameCubeControllerProvider::reader_thread() { SetThreadName("GCControllerAdapter::reader_thread"); while (m_running.load(std::memory_order_relaxed)) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); std::this_thread::yield(); for(auto& adapter : m_adapters) { if (!adapter.m_device_handle) continue; std::array<uint8_t, 37> data{}; int read; const int result = m_libusb->p_libusb_interrupt_transfer(adapter.m_device_handle, adapter.m_endpoint_reader, data.data(), static_cast<int>(data.size()), &read, 25); if (result == 0) { /* byte 1 0x10 NORMAL STATE 0x20 WAVEBIRD STATE 0x04 RUMBLE POWER */ for (int i = 0; i < 4; ++i) { GCState state; state.valid = true; state.button = *(uint16*)&data[1 + (i * 9) + 1]; state.lstick_x = data[1 + (i * 9) + 3]; state.lstick_y = data[1 + (i * 9) + 4]; state.rstick_x = data[1 + (i * 9) + 5]; state.rstick_y = data[1 + (i * 9) + 6]; state.lstick = data[1 + (i * 9) + 7]; state.rstick = data[1 + (i * 9) + 8]; std::scoped_lock lock(adapter.m_state_mutex); adapter.m_rumble_connected = HAS_FLAG(data[1], 4); adapter.m_states[i] = state; } } else if (result == LIBUSB_ERROR_NO_DEVICE || result == LIBUSB_ERROR_IO) { cemuLog_log(LogType::Force, "libusb error {} at libusb_interrupt_transfer: {}", result, m_libusb->p_libusb_error_name(result)); if (const auto handle = adapter.m_device_handle.exchange(nullptr)) m_libusb->p_libusb_close(handle); } else { cemuLog_log(LogType::Force, "libusb error {} at libusb_interrupt_transfer: {}", result, m_libusb->p_libusb_error_name(result)); } } } } void GameCubeControllerProvider::writer_thread() { SetThreadName("GCControllerAdapter::writer_thread"); std::array<std::array<bool, 4>, kMaxAdapters> rumble_states{}; while (m_running.load(std::memory_order_relaxed)) { std::unique_lock lock(m_writer_mutex); if (!m_rumble_changed && m_writer_cond.wait_for(lock, std::chrono::milliseconds(250)) == std::cv_status::timeout) { if (!m_running) return; continue; } bool cmd_sent = false; for (size_t i = 0; i < kMaxAdapters; ++i) { auto& adapter = m_adapters[i]; if (!adapter.m_device_handle) continue; if (adapter.rumble_states == rumble_states[i]) continue; rumble_states[i] = adapter.rumble_states; m_rumble_changed = false; lock.unlock(); std::array<uint8, 5> rumble{ 0x11, rumble_states[i][0],rumble_states[i][1],rumble_states[i][2], rumble_states[i][3] }; int written; const int result = m_libusb->p_libusb_interrupt_transfer(adapter.m_device_handle, adapter.m_endpoint_writer, rumble.data(), static_cast<int>(rumble.size()), &written, 25); if (result != 0) { cemuLog_log(LogType::Force, "libusb error {} at libusb_interrupt_transfer: {}", result, m_libusb->p_libusb_error_name(result)); } cmd_sent = true; lock.lock(); } if(cmd_sent) { lock.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(50)); } } } int GameCubeControllerProvider::hotplug_event(libusb_context* ctx, libusb_device* dev, libusb_hotplug_event event, void* user_data) { auto* thisptr = static_cast<GameCubeControllerProvider*>(user_data); if (LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED == event) { for (auto i = 0; i < kMaxAdapters; ++i) { if (thisptr->m_adapters[i].m_device_handle) continue; auto device = thisptr->fetch_usb_device(i); if (std::get<0>(device)) { thisptr->m_adapters[i].m_endpoint_reader = std::get<1>(device); thisptr->m_adapters[i].m_endpoint_writer = std::get<2>(device); thisptr->m_adapters[i].m_device_handle = std::get<0>(device); } } } /*else { const auto device_handle = thisptr->m_device_handle.exchange(nullptr); if (device_handle) thisptr->m_libusb->p_libusb_close(device_handle); }*/ return 0; } #endif
11,214
C++
.cpp
322
31.624224
174
0.69721
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,909
GameCubeController.cpp
cemu-project_Cemu/src/input/api/GameCube/GameCubeController.cpp
#include "input/api/GameCube/GameCubeController.h" #ifdef HAS_GAMECUBE GameCubeController::GameCubeController(uint32 adapter, uint32 index) : base_type(fmt::format("{}_{}", adapter, index), fmt::format("Controller {}", index + 1)), m_adapter(adapter), m_index(index) { // update names if multiple adapters are connected if (adapter > 0) m_display_name = fmt::format("Controller {} ({})", index + 1, adapter); m_settings.axis.range = 1.20f; m_settings.rotation.range = 1.25f; m_settings.trigger.range = 1.07f; } bool GameCubeController::is_connected() { return m_provider->is_connected(m_adapter); } bool GameCubeController::has_rumble() { return m_provider->has_rumble_connected(m_adapter); } void GameCubeController::start_rumble() { if (m_settings.rumble <= 0) return; m_provider->set_rumble_state(m_adapter, m_index, true); } void GameCubeController::stop_rumble() { m_provider->set_rumble_state(m_adapter, m_index, false); } std::string GameCubeController::get_button_name(uint64 button) const { switch (button) { case kButton0: return "A"; case kButton1: return "B"; case kButton2: return "X"; case kButton3: return "Y"; case kButton4: return "Left"; case kButton5: return "Right"; case kButton6: return "Down"; case kButton7: return "Up"; case kButton8: return "Start"; case kButton9: return "Z"; case kButton10: return "Trigger R"; case kButton11: return "Trigger L"; } return base_type::get_button_name(button); } ControllerState GameCubeController::raw_state() { ControllerState result{}; if (!is_connected()) return result; const auto state = m_provider->get_state(m_adapter, m_index); if (state.valid) { for (auto i = 0; i <= kButton11; ++i) { if (HAS_BIT(state.button, i)) { result.buttons.set(i); } } // printf("(%d, %d) - (%d, %d) - (%d, %d)\n", state.lstick_x, state.lstick_y, state.rstick_x, state.rstick_y, state.lstick, state.rstick); result.axis.x = (float)state.lstick_x / std::numeric_limits<uint8>::max(); result.axis.x = (result.axis.x * 2.0f) - 1.0f; result.axis.y = (float)state.lstick_y / std::numeric_limits<uint8>::max(); result.axis.y = (result.axis.y * 2.0f) - 1.0f; result.rotation.x = (float)state.rstick_x / std::numeric_limits<uint8>::max(); result.rotation.x = (result.rotation.x * 2.0f) - 1.0f; result.rotation.y = (float)state.rstick_y / std::numeric_limits<uint8>::max(); result.rotation.y = (result.rotation.y * 2.0f) - 1.0f; result.trigger.x = (float)state.lstick / std::numeric_limits<uint8>::max(); result.trigger.y = (float)state.rstick / std::numeric_limits<uint8>::max(); } return result; } #endif
2,650
C++
.cpp
80
30.7875
140
0.70318
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,910
SDLController.cpp
cemu-project_Cemu/src/input/api/SDL/SDLController.cpp
#include "input/api/SDL/SDLController.h" #include "input/api/SDL/SDLControllerProvider.h" SDLController::SDLController(const SDL_JoystickGUID& guid, size_t guid_index) : base_type(fmt::format("{}_", guid_index), fmt::format("Controller {}", guid_index + 1)), m_guid_index(guid_index), m_guid(guid) { char tmp[64]; SDL_JoystickGetGUIDString(m_guid, tmp, std::size(tmp)); m_uuid += tmp; } SDLController::SDLController(const SDL_JoystickGUID& guid, size_t guid_index, std::string_view display_name) : base_type(fmt::format("{}_", guid_index), display_name), m_guid_index(guid_index), m_guid(guid) { char tmp[64]; SDL_JoystickGetGUIDString(m_guid, tmp, std::size(tmp)); m_uuid += tmp; } SDLController::~SDLController() { if (m_controller) SDL_GameControllerClose(m_controller); } bool SDLController::is_connected() { std::scoped_lock lock(m_controller_mutex); if (!m_controller) { return false; } if (!SDL_GameControllerGetAttached(m_controller)) { m_controller = nullptr; return false; } return true; } bool SDLController::connect() { if (is_connected()) { return true; } m_has_rumble = false; const auto index = m_provider->get_index(m_guid_index, m_guid); std::scoped_lock lock(m_controller_mutex); m_diid = SDL_JoystickGetDeviceInstanceID(index); if (m_diid == -1) return false; m_controller = SDL_GameControllerOpen(index); if (!m_controller) return false; if (const char* name = SDL_GameControllerName(m_controller)) m_display_name = name; for (int i = 0; i < SDL_CONTROLLER_BUTTON_MAX; ++i) { m_buttons[i] = SDL_GameControllerHasButton(m_controller, (SDL_GameControllerButton)i); } for (int i = 0; i < SDL_CONTROLLER_AXIS_MAX; ++i) { m_axis[i] = SDL_GameControllerHasAxis(m_controller, (SDL_GameControllerAxis)i); } if (SDL_GameControllerHasSensor(m_controller, SDL_SENSOR_ACCEL)) { m_has_accel = true; SDL_GameControllerSetSensorEnabled(m_controller, SDL_SENSOR_ACCEL, SDL_TRUE); } if (SDL_GameControllerHasSensor(m_controller, SDL_SENSOR_GYRO)) { m_has_gyro = true; SDL_GameControllerSetSensorEnabled(m_controller, SDL_SENSOR_GYRO, SDL_TRUE); } m_has_rumble = SDL_GameControllerRumble(m_controller, 0, 0, 0) == 0; return true; } void SDLController::start_rumble() { std::scoped_lock lock(m_controller_mutex); if (is_connected() && !m_has_rumble) return; if (m_settings.rumble <= 0) return; SDL_GameControllerRumble(m_controller, (Uint16)(m_settings.rumble * 0xFFFF), (Uint16)(m_settings.rumble * 0xFFFF), 5 * 1000); } void SDLController::stop_rumble() { std::scoped_lock lock(m_controller_mutex); if (is_connected() && !m_has_rumble) return; SDL_GameControllerRumble(m_controller, 0, 0, 0); } MotionSample SDLController::get_motion_sample() { if (is_connected() && has_motion()) { return m_provider->motion_sample(m_diid); } return {}; } std::string SDLController::get_button_name(uint64 button) const { if (const char* name = SDL_GameControllerGetStringForButton((SDL_GameControllerButton)button)) return name; return base_type::get_button_name(button); } ControllerState SDLController::raw_state() { ControllerState result{}; std::scoped_lock lock(m_controller_mutex); if (!is_connected()) return result; for (int i = 0; i < SDL_CONTROLLER_BUTTON_MAX; ++i) { if (m_buttons[i] && SDL_GameControllerGetButton(m_controller, (SDL_GameControllerButton)i)) result.buttons.SetButtonState(i, true); } if (m_axis[SDL_CONTROLLER_AXIS_LEFTX]) result.axis.x = (float)SDL_GameControllerGetAxis(m_controller, SDL_CONTROLLER_AXIS_LEFTX) / 32767.0f; if (m_axis[SDL_CONTROLLER_AXIS_LEFTY]) result.axis.y = (float)SDL_GameControllerGetAxis(m_controller, SDL_CONTROLLER_AXIS_LEFTY) / 32767.0f; if (m_axis[SDL_CONTROLLER_AXIS_RIGHTX]) result.rotation.x = (float)SDL_GameControllerGetAxis(m_controller, SDL_CONTROLLER_AXIS_RIGHTX) / 32767.0f; if (m_axis[SDL_CONTROLLER_AXIS_RIGHTY]) result.rotation.y = (float)SDL_GameControllerGetAxis(m_controller, SDL_CONTROLLER_AXIS_RIGHTY) / 32767.0f; if (m_axis[SDL_CONTROLLER_AXIS_TRIGGERLEFT]) result.trigger.x = (float)SDL_GameControllerGetAxis(m_controller, SDL_CONTROLLER_AXIS_TRIGGERLEFT) / 32767.0f; if (m_axis[SDL_CONTROLLER_AXIS_TRIGGERRIGHT]) result.trigger.y = (float)SDL_GameControllerGetAxis(m_controller, SDL_CONTROLLER_AXIS_TRIGGERRIGHT) / 32767.0f; return result; }
4,398
C++
.cpp
130
31.361538
117
0.740014
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,911
SDLControllerProvider.cpp
cemu-project_Cemu/src/input/api/SDL/SDLControllerProvider.cpp
#include "input/api/SDL/SDLControllerProvider.h" #include "input/api/SDL/SDLController.h" #include "util/helpers/TempState.h" #include <SDL2/SDL.h> #include <boost/functional/hash.hpp> struct SDL_JoystickGUIDHash { std::size_t operator()(const SDL_JoystickGUID& guid) const { return boost::hash_value(guid.data); } }; SDLControllerProvider::SDLControllerProvider() { SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1"); SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_PS4, "1"); SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_PS5, "1"); SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_PS4_RUMBLE, "1"); SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_PS5_RUMBLE, "1"); SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_GAMECUBE, "1"); SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_SWITCH, "1"); SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_JOY_CONS, "1"); SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_STADIA, "1"); SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_STEAM, "1"); SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_LUNA, "1"); if (SDL_Init(SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER | SDL_INIT_HAPTIC | SDL_INIT_EVENTS) < 0) throw std::runtime_error(fmt::format("couldn't initialize SDL: {}", SDL_GetError())); if (SDL_GameControllerEventState(SDL_ENABLE) < 0) { cemuLog_log(LogType::Force, "Couldn't enable SDL gamecontroller event polling: {}", SDL_GetError()); } m_running = true; m_thread = std::thread(&SDLControllerProvider::event_thread, this); } SDLControllerProvider::~SDLControllerProvider() { if (m_running) { m_running = false; // wake the thread with a quit event if it's currently waiting for events SDL_Event evt; evt.type = SDL_QUIT; SDL_PushEvent(&evt); // wait until thread exited m_thread.join(); } SDL_QuitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER | SDL_INIT_HAPTIC | SDL_INIT_EVENTS); } std::vector<std::shared_ptr<ControllerBase>> SDLControllerProvider::get_controllers() { std::vector<std::shared_ptr<ControllerBase>> result; std::unordered_map<SDL_JoystickGUID, size_t, SDL_JoystickGUIDHash> guid_counter; TempState lock(SDL_LockJoysticks, SDL_UnlockJoysticks); for (int i = 0; i < SDL_NumJoysticks(); ++i) { if (SDL_JoystickGetDeviceType(i) == SDL_JOYSTICK_TYPE_GAMECONTROLLER) { const auto guid = SDL_JoystickGetDeviceGUID(i); const auto it = guid_counter.try_emplace(guid, 0); if (auto* controller = SDL_GameControllerOpen(i)) { const char* name = SDL_GameControllerName(controller); result.emplace_back(std::make_shared<SDLController>(guid, it.first->second, name)); SDL_GameControllerClose(controller); } else result.emplace_back(std::make_shared<SDLController>(guid, it.first->second)); ++it.first->second; } } return result; } int SDLControllerProvider::get_index(size_t guid_index, const SDL_JoystickGUID& guid) const { size_t index = 0; TempState lock(SDL_LockJoysticks, SDL_UnlockJoysticks); for (int i = 0; i < SDL_NumJoysticks(); ++i) { if (SDL_JoystickGetDeviceType(i) == SDL_JOYSTICK_TYPE_GAMECONTROLLER) { if(guid == SDL_JoystickGetDeviceGUID(i)) { if (index == guid_index) { return i; } ++index; } } } return -1; } MotionSample SDLControllerProvider::motion_sample(int diid) { std::scoped_lock lock(m_motion_data_mtx[diid]); return m_motion_data[diid]; } void SDLControllerProvider::event_thread() { SetThreadName("SDL_events"); while (m_running.load(std::memory_order_relaxed)) { SDL_Event event{}; SDL_WaitEvent(&event); switch (event.type) { case SDL_QUIT: m_running = false; return; case SDL_CONTROLLERAXISMOTION: /**< Game controller axis motion */ { break; } case SDL_CONTROLLERBUTTONDOWN: /**< Game controller button pressed */ { break; } case SDL_CONTROLLERBUTTONUP: /**< Game controller button released */ { break; } case SDL_CONTROLLERDEVICEADDED: /**< A new Game controller has been inserted into the system */ { InputManager::instance().on_device_changed(); break; } case SDL_CONTROLLERDEVICEREMOVED: /**< An opened Game controller has been removed */ { InputManager::instance().on_device_changed(); break; } case SDL_CONTROLLERDEVICEREMAPPED: /**< The controller mapping was updated */ { break; } case SDL_CONTROLLERTOUCHPADDOWN: /**< Game controller touchpad was touched */ { break; } case SDL_CONTROLLERTOUCHPADMOTION: /**< Game controller touchpad finger was moved */ { break; } case SDL_CONTROLLERTOUCHPADUP: /**< Game controller touchpad finger was lifted */ { break; } case SDL_CONTROLLERSENSORUPDATE: /**< Game controller sensor was updated */ { const auto index = event.csensor.which; const auto ts = event.csensor.timestamp; auto& motionTracking = m_motion_tracking[index]; if (event.csensor.sensor == SDL_SENSOR_ACCEL) { const auto dif = ts - motionTracking.lastTimestampAccel; if (dif <= 0) break; if (dif >= 10000) { motionTracking.hasAcc = false; motionTracking.hasGyro = false; motionTracking.lastTimestampAccel = ts; break; } motionTracking.lastTimestampAccel = ts; motionTracking.acc[0] = -event.csensor.data[0] / 9.81f; motionTracking.acc[1] = -event.csensor.data[1] / 9.81f; motionTracking.acc[2] = -event.csensor.data[2] / 9.81f; motionTracking.hasAcc = true; } if (event.csensor.sensor == SDL_SENSOR_GYRO) { const auto dif = ts - motionTracking.lastTimestampGyro; if (dif <= 0) break; if (dif >= 10000) { motionTracking.hasAcc = false; motionTracking.hasGyro = false; motionTracking.lastTimestampGyro = ts; break; } motionTracking.lastTimestampGyro = ts; motionTracking.gyro[0] = event.csensor.data[0]; motionTracking.gyro[1] = -event.csensor.data[1]; motionTracking.gyro[2] = -event.csensor.data[2]; motionTracking.hasGyro = true; } if (motionTracking.hasAcc && motionTracking.hasGyro) { auto ts = std::max(motionTracking.lastTimestampGyro, motionTracking.lastTimestampAccel); if (ts > motionTracking.lastTimestampIntegrate) { const auto tsDif = ts - motionTracking.lastTimestampIntegrate; motionTracking.lastTimestampIntegrate = ts; float tsDifD = (float)tsDif / 1000.0f; if (tsDifD >= 1.0f) tsDifD = 1.0f; m_motion_handler[index].processMotionSample(tsDifD, motionTracking.gyro.x, motionTracking.gyro.y, motionTracking.gyro.z, motionTracking.acc.x, -motionTracking.acc.y, -motionTracking.acc.z); std::scoped_lock lock(m_motion_data_mtx[index]); m_motion_data[index] = m_motion_handler[index].getMotionSample(); } motionTracking.hasAcc = false; motionTracking.hasGyro = false; } break; } } } }
6,754
C++
.cpp
209
28.779904
194
0.713011
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,912
KeyboardControllerProvider.cpp
cemu-project_Cemu/src/input/api/Keyboard/KeyboardControllerProvider.cpp
#include "input/api/Keyboard/KeyboardControllerProvider.h" #include "input/api/Keyboard/KeyboardController.h" std::vector<std::shared_ptr<ControllerBase>> KeyboardControllerProvider::get_controllers() { std::vector<std::shared_ptr<ControllerBase>> result; result.emplace_back(std::make_shared<KeyboardController>()); return result; }
339
C++
.cpp
8
40.75
90
0.81459
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,913
KeyboardController.cpp
cemu-project_Cemu/src/input/api/Keyboard/KeyboardController.cpp
#include <boost/container/small_vector.hpp> #include "input/api/Keyboard/KeyboardController.h" #include "gui/guiWrapper.h" KeyboardController::KeyboardController() : base_type("keyboard", "Keyboard") { } std::string KeyboardController::get_button_name(uint64 button) const { #if BOOST_OS_WINDOWS LONG scan_code = MapVirtualKeyA((UINT)button, MAPVK_VK_TO_VSC_EX); if(HIBYTE(scan_code)) scan_code |= 0x100; // because MapVirtualKey strips the extended bit for some keys switch (button) { case VK_LEFT: case VK_UP: case VK_RIGHT: case VK_DOWN: // arrow keys case VK_PRIOR: case VK_NEXT: // page up and page down case VK_END: case VK_HOME: case VK_INSERT: case VK_DELETE: case VK_DIVIDE: // numpad slash case VK_NUMLOCK: { scan_code |= 0x100; // set extended bit break; } } scan_code <<= 16; char key_name[128]; if (GetKeyNameTextA(scan_code, key_name, std::size(key_name)) != 0) return key_name; else return fmt::format("key_{}", button); #elif BOOST_OS_LINUX return gui_gtkRawKeyCodeToString(button); #else return fmt::format("key_{}", button); #endif } extern WindowInfo g_window_info; ControllerState KeyboardController::raw_state() { ControllerState result{}; boost::container::small_vector<uint32, 16> pressedKeys; g_window_info.iter_keystates([&pressedKeys](const std::pair<const uint32, bool>& keyState) { if (keyState.second) pressedKeys.emplace_back(keyState.first); }); result.buttons.SetPressedButtons(pressedKeys); return result; }
1,487
C++
.cpp
48
29.020833
160
0.751575
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,914
NativeWiimoteController.cpp
cemu-project_Cemu/src/input/api/Wiimote/NativeWiimoteController.cpp
#include "input/api/Wiimote/NativeWiimoteController.h" #include "input/api/Wiimote/WiimoteControllerProvider.h" #include <pugixml.hpp> NativeWiimoteController::NativeWiimoteController(size_t index) : base_type(fmt::format("{}", index), fmt::format("Controller {}", index + 1)), m_index(index) { m_settings.motion = true; } void NativeWiimoteController::save(pugi::xml_node& node) { base_type::save(node); node.append_child("packet_delay").append_child(pugi::node_pcdata).set_value( fmt::format("{}", m_packet_delay).c_str()); } void NativeWiimoteController::load(const pugi::xml_node& node) { base_type::load(node); if (const auto value = node.child("packet_delay")) m_packet_delay = ConvertString<uint32>(value.child_value()); } bool NativeWiimoteController::connect() { if (is_connected()) return true; if (!m_provider->is_registered_device(m_index)) { m_provider->get_controllers(); } if (m_provider->is_connected(m_index)) { m_provider->set_packet_delay(m_index, m_packet_delay); m_provider->set_led(m_index, m_player_index); return true; } return false; } bool NativeWiimoteController::is_connected() { if (m_provider->is_connected(m_index)) { m_provider->set_packet_delay(m_index, m_packet_delay); return true; } return false; } void NativeWiimoteController::set_player_index(size_t player_index) { m_player_index = player_index; m_provider->set_led(m_index, m_player_index); } NativeWiimoteController::Extension NativeWiimoteController::get_extension() const { Extension result = None; const auto ext = m_provider->get_state(m_index).m_extension; if (std::holds_alternative<NunchuckData>(ext)) result = Nunchuck; else if (std::holds_alternative<ClassicData>(ext)) result = Classic; return result; } bool NativeWiimoteController::is_mpls_attached() const { return m_provider->get_state(m_index).m_motion_plus.has_value(); } bool NativeWiimoteController::has_position() { const auto state = m_provider->get_state(m_index); return std::any_of(state.ir_camera.dots.cbegin(), state.ir_camera.dots.cend(), [](const IRDot& v) { return v.visible; }); } glm::vec2 NativeWiimoteController::get_position() { const auto state = m_provider->get_state(m_index); return state.ir_camera.position; } glm::vec2 NativeWiimoteController::get_prev_position() { const auto state = m_provider->get_state(m_index); return state.ir_camera.m_prev_position; } PositionVisibility NativeWiimoteController::GetPositionVisibility() { const auto state = m_provider->get_state(m_index); return state.ir_camera.m_positionVisibility; } bool NativeWiimoteController::has_low_battery() { const auto state = m_provider->get_state(m_index); return HAS_FLAG(state.flags, kBatteryEmpty); } void NativeWiimoteController::start_rumble() { if (m_settings.rumble < 1.0f) { return; } m_provider->set_rumble(m_index, true); } void NativeWiimoteController::stop_rumble() { m_provider->set_rumble(m_index, false); } MotionSample NativeWiimoteController::get_motion_sample() { const auto state = m_provider->get_state(m_index); return state.motion_sample; } MotionSample NativeWiimoteController::get_nunchuck_motion_sample() const { const auto state = m_provider->get_state(m_index); if (std::holds_alternative<NunchuckData>(state.m_extension)) { return std::get<NunchuckData>(state.m_extension).motion_sample; } return {}; } std::string NativeWiimoteController::get_button_name(uint64 button) const { switch (button) { case kWiimoteButton_A: return "A"; case kWiimoteButton_B: return "B"; case kWiimoteButton_One: return "1"; case kWiimoteButton_Two: return "2"; case kWiimoteButton_Plus: return "+"; case kWiimoteButton_Minus: return "-"; case kWiimoteButton_Home: return "HOME"; case kWiimoteButton_Up: return "UP"; case kWiimoteButton_Down: return "DOWN"; case kWiimoteButton_Left: return "LEFT"; case kWiimoteButton_Right: return "RIGHT"; // nunchuck case kWiimoteButton_C: return "C"; case kWiimoteButton_Z: return "Z"; // classic case kHighestWiimote + kClassicButton_A: return "A"; case kHighestWiimote + kClassicButton_B: return "B"; case kHighestWiimote + kClassicButton_Y: return "Y"; case kHighestWiimote + kClassicButton_X: return "X"; case kHighestWiimote + kClassicButton_Plus: return "+"; case kHighestWiimote + kClassicButton_Minus: return "-"; case kHighestWiimote + kClassicButton_Home: return "HOME"; case kHighestWiimote + kClassicButton_Up: return "UP"; case kHighestWiimote + kClassicButton_Down: return "DOWN"; case kHighestWiimote + kClassicButton_Left: return "LEFT"; case kHighestWiimote + kClassicButton_Right: return "RIGHT"; case kHighestWiimote + kClassicButton_L: return "L"; case kHighestWiimote + kClassicButton_R: return "R"; case kHighestWiimote + kClassicButton_ZL: return "ZL"; case kHighestWiimote + kClassicButton_ZR: return "ZR"; } return base_type::get_button_name(button); } uint32 NativeWiimoteController::get_packet_delay() { m_packet_delay = m_provider->get_packet_delay(m_index); return m_packet_delay; } void NativeWiimoteController::set_packet_delay(uint32 delay) { m_packet_delay = delay; m_provider->set_packet_delay(m_index, delay); } ControllerState NativeWiimoteController::raw_state() { ControllerState result{}; if (!is_connected()) return result; const auto state = m_provider->get_state(m_index); for (int i = 0; i < std::numeric_limits<uint16>::digits; i++) result.buttons.SetButtonState(i, (state.buttons & (1 << i)) != 0); if (std::holds_alternative<NunchuckData>(state.m_extension)) { const auto nunchuck = std::get<NunchuckData>(state.m_extension); if (nunchuck.c) result.buttons.SetButtonState(kWiimoteButton_C, true); if (nunchuck.z) result.buttons.SetButtonState(kWiimoteButton_Z, true); result.axis = nunchuck.axis; } else if (std::holds_alternative<ClassicData>(state.m_extension)) { const auto classic = std::get<ClassicData>(state.m_extension); uint64 buttons = (uint64)classic.buttons << kHighestWiimote; for (int i = 0; i < std::numeric_limits<uint64>::digits; i++) { // OR with base buttons if((buttons & (1 << i))) result.buttons.SetButtonState(i, true); } result.axis = classic.left_axis; result.rotation = classic.right_axis; result.trigger = classic.trigger; } return result; }
6,347
C++
.cpp
196
30.183673
95
0.753564
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,915
WiimoteControllerProvider.cpp
cemu-project_Cemu/src/input/api/Wiimote/WiimoteControllerProvider.cpp
#include "input/api/Wiimote/WiimoteControllerProvider.h" #include "input/api/Wiimote/NativeWiimoteController.h" #include "input/api/Wiimote/WiimoteMessages.h" #include "input/api/Wiimote/hidapi/HidapiWiimote.h" #include <numbers> #include <queue> WiimoteControllerProvider::WiimoteControllerProvider() : m_running(true) { m_reader_thread = std::thread(&WiimoteControllerProvider::reader_thread, this); m_writer_thread = std::thread(&WiimoteControllerProvider::writer_thread, this); } WiimoteControllerProvider::~WiimoteControllerProvider() { if (m_running) { m_running = false; m_writer_thread.join(); m_reader_thread.join(); } } std::vector<std::shared_ptr<ControllerBase>> WiimoteControllerProvider::get_controllers() { std::scoped_lock lock(m_device_mutex); std::queue<uint32> disconnected_wiimote_indices; for (auto i{0u}; i < m_wiimotes.size(); ++i){ if (!(m_wiimotes[i].connected = m_wiimotes[i].device->write_data({kStatusRequest, 0x00}))){ disconnected_wiimote_indices.push(i); } } const auto valid_new_device = [&](std::shared_ptr<WiimoteDevice> & device) { const auto writeable = device->write_data({kStatusRequest, 0x00}); const auto not_already_connected = std::none_of(m_wiimotes.cbegin(), m_wiimotes.cend(), [device](const auto& it) { return (*it.device == *device) && it.connected; }); return writeable && not_already_connected; }; for (auto& device : WiimoteDevice_t::get_devices()) { if (!valid_new_device(device)) continue; // Replace disconnected wiimotes if (!disconnected_wiimote_indices.empty()){ const auto idx = disconnected_wiimote_indices.front(); disconnected_wiimote_indices.pop(); m_wiimotes.replace(idx, std::make_unique<Wiimote>(device)); } // Otherwise add them else { m_wiimotes.push_back(std::make_unique<Wiimote>(device)); } } std::vector<std::shared_ptr<ControllerBase>> result; for (size_t i = 0; i < m_wiimotes.size(); ++i) { result.emplace_back(std::make_shared<NativeWiimoteController>(i)); } return result; } bool WiimoteControllerProvider::is_connected(size_t index) { std::shared_lock lock(m_device_mutex); return index < m_wiimotes.size() && m_wiimotes[index].connected; } bool WiimoteControllerProvider::is_registered_device(size_t index) { std::shared_lock lock(m_device_mutex); return index < m_wiimotes.size(); } void WiimoteControllerProvider::set_rumble(size_t index, bool state) { std::shared_lock lock(m_device_mutex); if (index >= m_wiimotes.size()) return; m_wiimotes[index].rumble = state; lock.unlock(); send_packet(index, { kStatusRequest, 0x00 }); } void WiimoteControllerProvider::request_status(size_t index) { send_packet(index, {kStatusRequest, 0x00}); } void WiimoteControllerProvider::set_led(size_t index, size_t player_index) { uint8 mask = 0; mask |= 1 << (4 + (player_index % 4)); if (player_index >= 4) mask |= 1 << (4 + ((player_index - 3) % 4)); send_packet(index, {kLED, mask}); } uint32 WiimoteControllerProvider::get_packet_delay(size_t index) { std::shared_lock lock(m_device_mutex); if (index < m_wiimotes.size()) { return m_wiimotes[index].data_delay; } return kDefaultPacketDelay; } void WiimoteControllerProvider::set_packet_delay(size_t index, uint32 delay) { std::shared_lock lock(m_device_mutex); if (index < m_wiimotes.size()) { m_wiimotes[index].data_delay = delay; } } WiimoteControllerProvider::WiimoteState WiimoteControllerProvider::get_state(size_t index) { std::shared_lock lock(m_device_mutex); if (index < m_wiimotes.size()) { std::shared_lock data_lock(m_wiimotes[index].mutex); return m_wiimotes[index].state; } return {}; } void WiimoteControllerProvider::reader_thread() { SetThreadName("Wiimote-reader"); std::chrono::steady_clock::time_point lastCheck = {}; while (m_running.load(std::memory_order_relaxed)) { const auto now = std::chrono::steady_clock::now(); if (std::chrono::duration_cast<std::chrono::seconds>(now - lastCheck) > std::chrono::seconds(2)) { // check for new connected wiimotes get_controllers(); lastCheck = std::chrono::steady_clock::now(); } bool receivedAnyPacket = false; std::shared_lock lock(m_device_mutex); for (size_t index = 0; index < m_wiimotes.size(); ++index) { auto& wiimote = m_wiimotes[index]; if (!wiimote.connected) continue; const auto read_data = wiimote.device->read_data(); if (!read_data || read_data->empty()) continue; receivedAnyPacket = true; std::shared_lock read_lock(wiimote.mutex); WiimoteState new_state = wiimote.state; read_lock.unlock(); bool update_report = false; const uint8* data = read_data->data(); const auto id = (InputReportId)*data; ++data; switch (id) { case kStatus: { cemuLog_logDebug(LogType::Force,"WiimoteControllerProvider::read_thread: kStatus"); new_state.buttons = (*(uint16*)data) & (~0x60E0); data += 2; new_state.flags = *data; ++data; data += 2; // skip zeroes new_state.battery_level = *data; ++data; new_state.ir_camera.mode = set_ir_camera(index, true); if(!new_state.m_calibrated) calibrate(index); if(!new_state.m_motion_plus) detect_motion_plus(index); if (HAS_FLAG(new_state.flags, kExtensionConnected)) { cemuLog_logDebug(LogType::Force,"Extension flag is set"); if(new_state.m_extension.index() == 0) request_extension(index); } else { new_state.m_extension = {}; } update_report = true; } break; case kRead: { cemuLog_logDebug(LogType::Force,"WiimoteControllerProvider::read_thread: kRead"); new_state.buttons = (*(uint16*)data) & (~0x60E0); data += 2; const uint8 error_flag = *data & 0xF, size = (*data >> 4) + 1; ++data; if (error_flag) { // 7 means that wiimote is already enabled or not available cemuLog_logDebug(LogType::Force,"Received error on data read {:#x}", error_flag); continue; } auto address = *(betype<uint16>*)data; data += 2; if (address == (kRegisterCalibration & 0xFFFF)) { cemuLog_logDebug(LogType::Force,"Calibration received"); cemu_assert(size == 8); new_state.m_calib_acceleration.zero.x = (uint16)*data << 2; ++data; new_state.m_calib_acceleration.zero.y = (uint16)*data << 2; ++data; new_state.m_calib_acceleration.zero.z = (uint16)*data << 2; ++data; // --XXYYZZ new_state.m_calib_acceleration.zero.x |= (*data >> 4) & 0x3; // 5|4 -> 1|0 new_state.m_calib_acceleration.zero.y |= (*data >> 2) & 0x3; // 3|4 -> 1|0 new_state.m_calib_acceleration.zero.z |= *data & 0x3; ++data; new_state.m_calib_acceleration.gravity.x = (uint16)*data << 2; ++data; new_state.m_calib_acceleration.gravity.y = (uint16)*data << 2; ++data; new_state.m_calib_acceleration.gravity.z = (uint16)*data << 2; ++data; new_state.m_calib_acceleration.gravity.x |= (*data >> 4) & 0x3; // 5|4 -> 1|0 new_state.m_calib_acceleration.gravity.y |= (*data >> 2) & 0x3; // 3|4 -> 1|0 new_state.m_calib_acceleration.gravity.z |= *data & 0x3; ++data; new_state.m_calibrated = true; } else if (address == (kRegisterExtensionType & 0xFFFF)) { if (size == 0xf) { cemuLog_logDebug(LogType::Force,"Extension type received but no extension connected"); continue; } cemu_assert(size == 6); auto be_type = *(betype<uint64>*)data; data += 6; // 48 be_type >>= 16; be_type &= 0xFFFFFFFFFFFF; switch (be_type.value()) { case kExtensionNunchuck: cemuLog_logDebug(LogType::Force,"Extension Type Received: Nunchuck"); new_state.m_extension = NunchuckData{}; break; case kExtensionClassic: cemuLog_logDebug(LogType::Force,"Extension Type Received: Classic"); new_state.m_extension = ClassicData{}; break; case kExtensionClassicPro: cemuLog_logDebug(LogType::Force,"Extension Type Received: Classic Pro"); break; case kExtensionGuitar: cemuLog_logDebug(LogType::Force,"Extension Type Received: Guitar"); break; case kExtensionDrums: cemuLog_logDebug(LogType::Force,"Extension Type Received: Drums"); break; case kExtensionBalanceBoard: cemuLog_logDebug(LogType::Force,"Extension Type Received: Balance Board"); break; case kExtensionMotionPlus: cemuLog_logDebug(LogType::Force,"Extension Type Received: MotionPlus"); set_motion_plus(index, true); new_state.m_motion_plus = MotionPlusData{}; break; case kExtensionPartialyInserted: cemuLog_logDebug(LogType::Force,"Extension only partially inserted"); new_state.m_extension = {}; request_status(index); break; default: cemuLog_logDebug(LogType::Force,"Unknown extension: {:#x}", be_type.value()); new_state.m_extension = {}; break; } if (new_state.m_extension.index() != 0) send_read_packet(index, kRegisterMemory, kRegisterExtensionCalibration, 0x10); } else if (address == (kRegisterExtensionCalibration & 0xFFFF)) { cemu_assert(size == 0x10); cemuLog_logDebug(LogType::Force,"Extension calibration received"); std::visit( overloaded { [](auto) { }, [data](MotionPlusData& mp) { // TODO fix }, [data](NunchuckData& nunchuck) { std::array<uint8, 14> zero{}; if (memcmp(zero.data(), data, zero.size()) == 0) { cemuLog_logDebug(LogType::Force,"Extension calibration data is zero"); return; } nunchuck.calibration.zero.x = (uint16)data[0] << 2; nunchuck.calibration.zero.y = (uint16)data[1] << 2; nunchuck.calibration.zero.z = (uint16)data[2] << 2; // --XXYYZZ nunchuck.calibration.zero.x |= (data[3] >> 4) & 0x3; // 5|4 -> 1|0 nunchuck.calibration.zero.y |= (data[3] >> 2) & 0x3; // 3|4 -> 1|0 nunchuck.calibration.zero.z |= data[3] & 0x3; nunchuck.calibration.gravity.x = (uint16)data[4] << 2;; nunchuck.calibration.gravity.y = (uint16)data[5] << 2;; nunchuck.calibration.gravity.z = (uint16)data[6] << 2;; // --XXYYZZ nunchuck.calibration.gravity.x |= (data[7] >> 4) & 0x3; // 5|4 -> 1|0 nunchuck.calibration.gravity.y |= (data[7] >> 2) & 0x3; // 3|4 -> 1|0 nunchuck.calibration.gravity.z |= data[7] & 0x3; nunchuck.calibration.max.x = data[8]; nunchuck.calibration.max.y = data[11]; nunchuck.calibration.min.x = data[9]; nunchuck.calibration.min.y = data[12]; nunchuck.calibration.center.x = data[10]; nunchuck.calibration.center.y = data[13]; } }, new_state.m_extension); } else { cemuLog_logDebug(LogType::Force,"Unhandled read data received"); continue; } update_report = true; } break; case kAcknowledge: { new_state.buttons = *(uint16*)data & (~0x60E0); data += 2; const auto report_id = *data++; const auto error = *data++; if (error) cemuLog_logDebug(LogType::Force, "Error {:#x} from output report {:#x}", error, report_id); break; } case kDataCore: { // 30 BB BB new_state.buttons = *(uint16*)data & (~0x60E0); data += 2; break; } case kDataCoreAcc: { // 31 BB BB AA AA AA new_state.buttons = *(uint16*)data & (~0x60E0); parse_acceleration(new_state, data); break; } case kDataCoreExt8: { // 32 BB BB EE EE EE EE EE EE EE EE new_state.buttons = *(uint16*)data & (~0x60E0); data += 2; break; } case kDataCoreAccIR: { // 33 BB BB AA AA AA II II II II II II II II II II II II new_state.buttons = *(uint16*)data & (~0x60E0); parse_acceleration(new_state, data); data += parse_ir(new_state, data); break; } case kDataCoreExt19: { // 34 BB BB EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE new_state.buttons = *(uint16*)data & (~0x60E0); data += 2; break; } case kDataCoreAccExt: { // 35 BB BB AA AA AA EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE new_state.buttons = *(uint16*)data & (~0x60E0); parse_acceleration(new_state, data); break; } case kDataCoreIRExt: { // 36 BB BB II II II II II II II II II II EE EE EE EE EE EE EE EE EE new_state.buttons = *(uint16*)data & (~0x60E0); data += 2; break; } case kDataCoreAccIRExt: { // 37 BB BB AA AA AA II II II II II II II II II II EE EE EE EE EE EE new_state.buttons = *(uint16*)data & (~0x60E0); parse_acceleration(new_state, data); data += parse_ir(new_state, data); // 10 std::visit( overloaded { [](auto) { }, [data](MotionPlusData& mp) mutable { glm::vec<3, uint16> raw; raw.x = *data; ++data; raw.y = *data; ++data; raw.z = *data; ++data; raw.x |= (uint16)*data << 6; // 7|2 -> 13|8 mp.slow_yaw = *data & 2; mp.slow_pitch = *data & 1; ++data; raw.y |= (uint16)*data << 6; // 7|2 -> 13|8 mp.slow_roll = *data & 2; mp.extension_connected = *data & 1; ++data; raw.z |= (uint16)*data << 6; // 7|2 -> 13|8 auto& calib = mp.calibration; glm::vec3 orientation = raw; /*orientation -= calib.zero; Vector3<float> tmp = calib.gravity; tmp -= calib.zero; orientation /= tmp;*/ mp.orientation = orientation; cemuLog_logDebug(LogType::Force,"MotionPlus: {:.2f}, {:.2f} {:.2f}", mp.orientation.x, mp.orientation.y, mp.orientation.z); }, [data](NunchuckData& nunchuck) mutable { nunchuck.raw_axis.x = *data; ++data; nunchuck.raw_axis.y = *data; ++data; glm::vec<3, uint16> raw_acc; raw_acc.x = (uint16)*data << 2; ++data; raw_acc.y = (uint16)*data << 2; ++data; raw_acc.z = (uint16)*data << 2; ++data; nunchuck.z = (*data & 1) == 0; nunchuck.c = (*data & 2) == 0; raw_acc.x |= (*data >> 2) & 0x3; // 3|2 -> 1|0 raw_acc.y |= (*data >> 4) & 0x3; // 5|4 -> 1|0 raw_acc.z |= (*data >> 6) & 0x3; // 7|6 -> 1|0 auto& calib = nunchuck.calibration; if (nunchuck.raw_axis.x < nunchuck.calibration.center.x) // [-1, 0] nunchuck.axis.x = ((float)nunchuck.raw_axis.x - calib.min.x) / ((float)nunchuck. calibration.center.x - calib.min.x + 0.012f) - 1.0f; else // [0, 1] nunchuck.axis.x = (float)(nunchuck.raw_axis.x - nunchuck.calibration.center.x) / ( nunchuck.calibration.max.x - nunchuck.calibration.center.x + 0.012f); if (nunchuck.raw_axis.y <= nunchuck.calibration.center.y) // [-1, 0] nunchuck.axis.y = ((float)nunchuck.raw_axis.y - calib.min.y) / ((float)nunchuck. calibration.center.y - calib.min.y + 0.012f) - 1.0f; else // [0, 1] nunchuck.axis.y = (float)(nunchuck.raw_axis.y - nunchuck.calibration.center.y) / ( nunchuck.calibration.max.y - nunchuck.calibration.center.y); glm::vec3 acceleration = raw_acc; nunchuck.prev_acceleration = nunchuck.acceleration; nunchuck.acceleration = acceleration - glm::vec3(calib.zero); float acc[3]{ -nunchuck.acceleration.x, -nunchuck.acceleration.z, nunchuck.acceleration.y }; const auto grav = nunchuck.calibration.gravity - nunchuck.calibration.zero; auto tacc = nunchuck.acceleration; auto pacc = nunchuck.prev_acceleration; if (grav != glm::vec<3, uint16>{}) { acc[0] /= (float)grav.x; acc[1] /= (float)grav.y; acc[2] /= (float)grav.z; tacc.x /= (float)grav.x; pacc.x /= (float)grav.x; tacc.y /= (float)grav.y; pacc.y /= (float)grav.y; tacc.z /= (float)grav.z; pacc.z /= (float)grav.z; } float zero3[3]{}; float zero4[4]{}; nunchuck.motion_sample = MotionSample( acc, glm::length(tacc - pacc), zero3, zero3, zero4 ); cemuLog_logDebug(LogType::Force,"Nunchuck: Z={}, C={} | {}, {} | {:.2f}, {:.2f}, {:.2f}", nunchuck.z, nunchuck.c, nunchuck.axis.x, nunchuck.axis.y, RadToDeg(nunchuck.acceleration.x), RadToDeg(nunchuck.acceleration.y), RadToDeg(nunchuck.acceleration.z)); }, [data](ClassicData& classic) mutable { classic.left_raw_axis.x = *data & 0x3F; classic.right_raw_axis.x = (*data & 0xC0) >> 3; // 7|6 -> 4|3 ++data; classic.left_raw_axis.y = *data & 0x3F; classic.right_raw_axis.x |= (*data & 0xC0) >> 5; // 7|6 -> 2|1 ++data; classic.right_raw_axis.y = *data & 0x1F; classic.raw_trigger.x = (*data & 0x60) >> 2; // 6|5 -> 4|3 classic.right_raw_axis.x |= (*data & 0x80) >> 7; // 7 -> 0 ++data; classic.raw_trigger.x |= (*data & 0xE0) >> 5; // 7|5 -> 2|0 classic.raw_trigger.y = (*data & 0x1F); ++data; classic.buttons = ~(*(uint16*)data); data += 2; classic.left_axis = classic.left_raw_axis; classic.left_axis /= 63.0f; classic.left_axis = classic.left_axis * 2.0f - 1.0f; classic.right_axis = classic.right_raw_axis; classic.right_axis /= 31.0f; classic.right_axis = classic.right_axis * 2.0f - 1.0f; classic.trigger = classic.raw_trigger; classic.trigger /= 31.0f; cemuLog_logDebug(LogType::Force,"Classic Controller: Buttons={:b} | {}, {} | {}, {} | {}, {}", classic.buttons, classic.left_axis.x, classic.left_axis.y, classic.right_axis.x, classic.right_axis.y, classic.trigger.x, classic.trigger.y); } }, new_state.m_extension); break; } case kDataExt: { // 3d EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE break; } default: cemuLog_logDebug(LogType::Force,"unhandled input packet id {} for wiimote {}", id, index); } // update motion data //const auto motionnow = std::chrono::high_resolution_clock::now(); //const auto delta_time = (float)std::chrono::duration_cast<std::chrono::milliseconds>(motionnow - new_state.m_last_motion_timestamp).count() / 1000.0f; //new_state.m_last_motion_timestamp = motionnow; float acc[3]{-new_state.m_acceleration.x, -new_state.m_acceleration.z, new_state.m_acceleration.y}; const auto grav = new_state.m_calib_acceleration.gravity - new_state.m_calib_acceleration.zero; auto tacc = new_state.m_acceleration; auto pacc = new_state.m_prev_acceleration; if (grav != glm::vec<3, uint16>{}) { acc[0] /= (float)grav.x; acc[1] /= (float)grav.y; acc[2] /= (float)grav.z; tacc.x /= (float)grav.x; pacc.x /= (float)grav.x; tacc.y /= (float)grav.y; pacc.y /= (float)grav.y; tacc.z /= (float)grav.z; pacc.z /= (float)grav.z; } float zero3[3]{}; float zero4[4]{}; new_state.motion_sample = MotionSample( acc, glm::length(tacc - pacc), zero3, zero3, zero4 ); std::unique_lock data_lock(wiimote.mutex); wiimote.state = new_state; data_lock.unlock(); if (update_report) update_report_type(index); } lock.unlock(); if (!receivedAnyPacket) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } } void WiimoteControllerProvider::parse_acceleration(WiimoteState& wiimote_state, const uint8*& data) { glm::vec<3, uint16> raw_acc; // acc encoded in BB BB raw_acc.x = (*data >> 5) & 3; // 6|5 -> 1|0 ++data; raw_acc.y = (*data >> 4) & 2; // 5 -> 1 raw_acc.z = (*data >> 5) & 2; // 6 -> 1 ++data; raw_acc.x |= (uint16)*data << 2; ++data; raw_acc.y |= (uint16)*data << 2; ++data; raw_acc.z |= (uint16)*data << 2; ++data; wiimote_state.m_prev_acceleration = wiimote_state.m_acceleration; glm::vec3 acceleration = raw_acc; const auto& calib = wiimote_state.m_calib_acceleration; wiimote_state.m_acceleration = acceleration - glm::vec3(calib.zero); glm::vec3 tmp = calib.gravity; tmp -= calib.zero; acceleration = (wiimote_state.m_acceleration / tmp); const float pi_2 = (float)std::numbers::pi / 2.0f; wiimote_state.m_roll = std::atan2(acceleration.z, acceleration.x) - pi_2; } void WiimoteControllerProvider::rotate_ir(WiimoteState& wiimote_state) { const float rot = wiimote_state.m_roll; if (rot == 0.0f) return; const float sin = std::sin(rot); const float cos = std::cos(rot); int i = -1; for (auto& dot : wiimote_state.ir_camera.dots) { i++; if (!dot.visible) continue; // move to center, rotate and move back dot.pos -= 0.5f; dot.pos.x = (dot.pos.x * cos) + (dot.pos.y * (-sin)); dot.pos.y = (dot.pos.x * sin) + (dot.pos.y * cos); dot.pos += 0.5f; } } void WiimoteControllerProvider::calculate_ir_position(WiimoteState& wiimote_state) { auto& ir = wiimote_state.ir_camera; ir.m_prev_position = ir.position; std::pair indices = ir.indices; if (ir.middle.x != 0) { const float last_angle = std::atan(ir.middle.y / ir.middle.x); float best_distance = std::numeric_limits<float>::max(); for (size_t i = 0; i < ir.dots.size(); ++i) { if (!ir.dots[i].visible) continue; for (size_t j = i + 1; j < ir.dots.size(); ++j) { if (!ir.dots[j].visible) continue; const auto mid = (ir.dots[i].pos + ir.dots[j].pos) / 2.0f; if (mid.x == 0) continue; // check if angle is close enough to the last known one float angle = std::atan(mid.y / mid.x); if (std::abs(last_angle - angle) > DegToRad(10.0f)) continue; // check if distance between points is similar to last known distance const float distance = std::abs(ir.distance - glm::length(ir.dots[i].pos - ir.dots[j].pos)); if (distance > 0.1f && distance > best_distance) continue; // found a new pair best_distance = distance; indices = {(sint32)i, (sint32)j}; } } } if (ir.dots[indices.first].visible && ir.dots[indices.second].visible) { ir.prev_dots[indices.first] = ir.dots[indices.first]; ir.prev_dots[indices.second] = ir.dots[indices.second]; ir.position = (ir.dots[indices.first].pos + ir.dots[indices.second].pos) / 2.0f; ir.middle = ir.position; ir.distance = glm::length(ir.dots[indices.first].pos - ir.dots[indices.second].pos); ir.indices = indices; ir.m_positionVisibility = PositionVisibility::FULL; } else if (ir.dots[indices.first].visible) { ir.position = ir.middle + (ir.dots[indices.first].pos - ir.prev_dots[indices.first].pos); ir.m_positionVisibility = PositionVisibility::PARTIAL; } else if (ir.dots[indices.second].visible) { ir.position = ir.middle + (ir.dots[indices.second].pos - ir.prev_dots[indices.second].pos); ir.m_positionVisibility = PositionVisibility::PARTIAL; } else { ir.m_positionVisibility = PositionVisibility::NONE; } } sint32 WiimoteControllerProvider::parse_ir(WiimoteState& wiimote_state, const uint8* data) { switch (wiimote_state.ir_camera.mode) { case kIRDisabled: wiimote_state.ir_camera.dots = {}; return 0; case kBasicIR: { const auto ir = (BasicIR*)data; for (int i = 0; i < 2; ++i) { auto& dot1 = wiimote_state.ir_camera.dots[i * 2]; auto& dot2 = wiimote_state.ir_camera.dots[i * 2 + 1]; dot1.raw.x = ir[i].x1 | (ir[i].bits.x1 << 8); // 9|8 dot1.raw.y = ir[i].y1 | (ir[i].bits.y1 << 8); dot1.size = 0; dot2.raw.x = ir[i].x2 | (ir[i].bits.x2 << 8); dot2.raw.y = ir[i].y2 | (ir[i].bits.y2 << 8); dot2.size = 0; dot1.visible = dot1.raw != glm::vec<2, uint16>(0x3ff, 0x3ff); if (dot1.visible) dot1.pos = glm::vec2(1.0f - dot1.raw.x / 1023.0f, (float)dot1.raw.y / 768.0f); else dot1.pos = {}; dot2.visible = dot2.raw != glm::vec<2, uint16>(0x3ff, 0x3ff); if (dot2.visible) dot2.pos = glm::vec2(1.0f - dot2.raw.x / 1023.0f, (float)dot2.raw.y / 768.0f); else dot2.pos = {}; } rotate_ir(wiimote_state); calculate_ir_position(wiimote_state); return sizeof(BasicIR) * 2; } case kExtendedIR: { const auto ir = (ExtendedIR*)data; for (int i = 0; i < 4; ++i) { auto& dot = wiimote_state.ir_camera.dots[i]; dot.raw.x = ir[i].x; dot.raw.y = ir[i].y; dot.raw.x |= (uint16)ir[i].bits.x << 8; // 9|8 dot.raw.y |= (uint16)ir[i].bits.y << 8; // 9|8 dot.size = ir[i].bits.size; dot.visible = dot.raw != glm::vec<2, uint16>(0x3ff, 0x3ff); if (dot.visible) dot.pos = glm::vec2(1.0f - dot.raw.x / 1023.0f, (float)dot.raw.y / 768.0f); else dot.pos = {}; } rotate_ir(wiimote_state); calculate_ir_position(wiimote_state); return sizeof(ExtendedIR) * 4; } default: cemu_assert(false); break; } return 0; } void WiimoteControllerProvider::request_extension(size_t index) { // send_write_packet(index, kRegisterMemory, kRegisterExtensionEncrypted, { 0x00 }); send_write_packet(index, kRegisterMemory, kRegisterExtension1, {0x55}); send_write_packet(index, kRegisterMemory, kRegisterExtension2, {0x00}); send_read_packet(index, kRegisterMemory, kRegisterExtensionType, 6); } void WiimoteControllerProvider::detect_motion_plus(size_t index) { send_read_packet(index, kRegisterMemory, kRegisterMotionPlusDetect, 6); } void WiimoteControllerProvider::set_motion_plus(size_t index, bool state) { if (state) { send_write_packet(index, kRegisterMemory, kRegisterMotionPlusInit, { 0x55 }); send_write_packet(index, kRegisterMemory, kRegisterMotionPlusEnable, { 0x04 }); } else { send_write_packet(index, kRegisterMemory, kRegisterExtension1, { 0x55 }); } } void WiimoteControllerProvider::writer_thread() { SetThreadName("Wiimote-writer"); while (m_running.load(std::memory_order_relaxed)) { std::unique_lock writer_lock(m_writer_mutex); while (m_write_queue.empty()) { if (m_writer_cond.wait_for(writer_lock, std::chrono::milliseconds(250)) == std::cv_status::timeout) { if (!m_running.load(std::memory_order_relaxed)) return; } } auto index = (size_t)-1; std::vector<uint8> data; std::shared_lock device_lock(m_device_mutex); // get first packet of device which is ready to be sent const auto now = std::chrono::high_resolution_clock::now(); for (auto it = m_write_queue.begin(); it != m_write_queue.end(); ++it) { if (it->first >= m_wiimotes.size()) continue; const auto delay = m_wiimotes[it->first].data_delay.load(std::memory_order_relaxed); if (now >= m_wiimotes[it->first].data_ts + std::chrono::milliseconds(delay)) { index = it->first; data = it->second; m_write_queue.erase(it); break; } } writer_lock.unlock(); if (index != (size_t)-1 && !data.empty()) { if (m_wiimotes[index].rumble) data[1] |= 1; m_wiimotes[index].connected = m_wiimotes[index].device->write_data(data); if (m_wiimotes[index].connected) { m_wiimotes[index].data_ts = std::chrono::high_resolution_clock::now(); } else { m_wiimotes[index].rumble = false; } } device_lock.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(1)); std::this_thread::yield(); } } void WiimoteControllerProvider::calibrate(size_t index) { send_read_packet(index, kEEPROMMemory, kRegisterCalibration, 8); } void WiimoteControllerProvider::update_report_type(size_t index) { std::shared_lock read_lock(m_wiimotes[index].mutex); auto& state = m_wiimotes[index].state; const bool extension = state.m_extension.index() != 0; // TODO || HasMotionPlus(); const bool ir = state.ir_camera.mode != kIRDisabled; const bool motion = true; // UseMotion(); InputReportId report_type; if (extension && ir && motion) report_type = kDataCoreAccIRExt; else if (extension && ir) report_type = kDataCoreIRExt; else if (extension && motion) report_type = kDataCoreAccExt; else if (ir && motion) report_type = kDataCoreAccIR; else if (extension) report_type = kDataCoreExt19; else if (ir) report_type = kDataCoreAccIR; else if (motion) report_type = kDataCoreAcc; else report_type = kDataCore; cemuLog_logDebug(LogType::Force,"Setting report type to {}", report_type); send_packet(index, {kType, 0x04, report_type}); state.ir_camera.mode = set_ir_camera(index, true); } IRMode WiimoteControllerProvider::set_ir_camera(size_t index, bool state) { std::shared_lock read_lock(m_wiimotes[index].mutex); auto& wiimote_state = m_wiimotes[index].state; IRMode mode; if (!state) mode = kIRDisabled; else { mode = wiimote_state.m_extension.index() == 0 ? kExtendedIR : kBasicIR; } if (wiimote_state.ir_camera.mode == mode) return mode; wiimote_state.ir_camera.mode = mode; const uint8_t data = state ? 0x04 : 0x00; send_packet(index, {kIR, data}); send_packet(index, {kIR2, data}); if (state) { send_write_packet(index, kRegisterMemory, kRegisterIR, {0x08}); send_write_packet(index, kRegisterMemory, kRegisterIRSensitivity1, {0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0xaa, 0x00, 0x64}); send_write_packet(index, kRegisterMemory, kRegisterIRSensitivity2, {0x63, 0x03}); send_write_packet(index, kRegisterMemory, kRegisterIRMode, {(uint8)mode}); send_write_packet(index, kRegisterMemory, kRegisterIR, {0x08}); } update_report_type(index); return mode; } void WiimoteControllerProvider::send_packet(size_t index, std::vector<uint8> data) { cemu_assert(data.size() > 1); std::shared_lock device_lock(m_device_mutex); if (index >= m_wiimotes.size()) return; device_lock.unlock(); std::unique_lock lock(m_writer_mutex); m_write_queue.emplace_back(index, data); m_writer_cond.notify_one(); } void WiimoteControllerProvider::send_read_packet(size_t index, MemoryType type, RegisterAddress address, uint16 size) { std::vector<uint8> data(7); data[0] = kReadMemory; data[1] = type; *(betype<uint32>*)(data.data() + 2) = (address & 0xFFFFFF) << 8; // only uint24 *(betype<uint16>*)(data.data() + 2 + 3) = size; send_packet(index, std::move(data)); } void WiimoteControllerProvider::send_write_packet(size_t index, MemoryType type, RegisterAddress address, const std::vector<uint8>& data) { cemu_assert(data.size() <= 16); std::vector<uint8> packet(6 + 16); packet[0] = kWriteMemory; packet[1] = type; *(betype<uint32>*)(packet.data() + 2) = (address & 0xFFFFFF) << 8; // only uint24 *(packet.data() + 2 + 3) = (uint8)data.size(); std::copy(data.begin(), data.end(), packet.data() + 2 + 3 + 1); send_packet(index, std::move(packet)); }
32,200
C++
.cpp
906
29.208609
155
0.611867
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,916
HidapiWiimote.cpp
cemu-project_Cemu/src/input/api/Wiimote/hidapi/HidapiWiimote.cpp
#include "HidapiWiimote.h" #include <cwchar> static constexpr uint16 WIIMOTE_VENDOR_ID = 0x057e; static constexpr uint16 WIIMOTE_PRODUCT_ID = 0x0306; static constexpr uint16 WIIMOTE_MP_PRODUCT_ID = 0x0330; static constexpr uint16 WIIMOTE_MAX_INPUT_REPORT_LENGTH = 22; static constexpr auto PRO_CONTROLLER_NAME = L"Nintendo RVL-CNT-01-UC"; HidapiWiimote::HidapiWiimote(hid_device* dev, std::string_view path) : m_handle(dev), m_path(path) { } bool HidapiWiimote::write_data(const std::vector<uint8> &data) { return hid_write(m_handle, data.data(), data.size()) >= 0; } std::optional<std::vector<uint8>> HidapiWiimote::read_data() { std::array<uint8, WIIMOTE_MAX_INPUT_REPORT_LENGTH> read_data{}; const auto result = hid_read(m_handle, read_data.data(), WIIMOTE_MAX_INPUT_REPORT_LENGTH); if (result < 0) return {}; return {{read_data.cbegin(), read_data.cbegin() + result}}; } std::vector<WiimoteDevicePtr> HidapiWiimote::get_devices() { std::vector<WiimoteDevicePtr> wiimote_devices; hid_init(); const auto device_enumeration = hid_enumerate(WIIMOTE_VENDOR_ID, 0x0); for (auto it = device_enumeration; it != nullptr; it = it->next){ if (it->product_id != WIIMOTE_PRODUCT_ID && it->product_id != WIIMOTE_MP_PRODUCT_ID) continue; if (std::wcscmp(it->product_string, PRO_CONTROLLER_NAME) == 0) continue; auto dev = hid_open_path(it->path); if (!dev){ cemuLog_logDebug(LogType::Force, "Unable to open Wiimote device at {}: {}", it->path, boost::nowide::narrow(hid_error(nullptr))); } else { hid_set_nonblocking(dev, true); wiimote_devices.push_back(std::make_shared<HidapiWiimote>(dev, it->path)); } } hid_free_enumeration(device_enumeration); return wiimote_devices; } bool HidapiWiimote::operator==(WiimoteDevice& o) const { return static_cast<HidapiWiimote const&>(o).m_path == m_path; } HidapiWiimote::~HidapiWiimote() { hid_close(m_handle); }
2,034
C++
.cpp
47
38.234043
141
0.682002
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,917
WPADController.cpp
cemu-project_Cemu/src/input/emulated/WPADController.cpp
#include <api/Controller.h> #include "input/emulated/WPADController.h" #include "input/emulated/ClassicController.h" #include "input/emulated/ProController.h" #include "input/emulated/WiimoteController.h" WPADController::WPADController(size_t player_index, WPADDataFormat data_format) : EmulatedController(player_index), m_data_format(data_format) { } WPADDataFormat WPADController::get_default_data_format() const { switch (get_device_type()) { case kWAPDevCore: return kDataFormat_CORE_ACC_DPD; case kWAPDevFreestyle: return kDataFormat_FREESTYLE_ACC; case kWAPDevClassic: return kDataFormat_CLASSIC; case kWAPDevMPLS: return kDataFormat_MPLS; case kWAPDevMPLSFreeStyle: return kDataFormat_FREESTYLE_ACC_DPD; case kWAPDevMPLSClassic: return kDataFormat_CLASSIC_ACC_DPD; case kWAPDevURCC: return kDataFormat_URCC; default: return kDataFormat_CORE; } } uint32 WPADController::get_emulated_button_flag(WPADDataFormat format, uint32 id) const { switch(format) { case kDataFormat_CORE: case kDataFormat_CORE_ACC: case kDataFormat_CORE_ACC_DPD: case kDataFormat_CORE_ACC_DPD_FULL: case kDataFormat_FREESTYLE: case kDataFormat_FREESTYLE_ACC: case kDataFormat_FREESTYLE_ACC_DPD: case kDataFormat_MPLS: return WiimoteController::s_get_emulated_button_flag(id); case kDataFormat_CLASSIC: case kDataFormat_CLASSIC_ACC: case kDataFormat_CLASSIC_ACC_DPD: return ClassicController::s_get_emulated_button_flag(id); case kDataFormat_TRAIN: break; case kDataFormat_GUITAR: break; case kDataFormat_BALANCE_CHECKER: break; case kDataFormat_DRUM: break; case kDataFormat_TAIKO: break; case kDataFormat_URCC: return ProController::s_get_emulated_button_flag(id); } return 0; } void WPADController::WPADRead(WPADStatus_t* status) { controllers_update_states(); uint32 button = 0; for (uint32 i = 1; i < get_highest_mapping_id(); ++i) { if (is_mapping_down(i)) { const uint32 value = get_emulated_button_flag(m_data_format, i); button |= value; } } m_homebutton_down |= is_home_down(); // todo fill position api from wiimote switch (m_data_format) { case kDataFormat_CORE: case kDataFormat_CORE_ACC: case kDataFormat_CORE_ACC_DPD: case kDataFormat_CORE_ACC_DPD_FULL: { memset(status, 0x00, sizeof(*status)); status->button = button; break; } case kDataFormat_FREESTYLE: case kDataFormat_FREESTYLE_ACC: case kDataFormat_FREESTYLE_ACC_DPD: { WPADFSStatus_t* ex_status = (WPADFSStatus_t*)status; memset(ex_status, 0x00, sizeof(*ex_status)); ex_status->button = button; auto axis = get_axis(); axis *= 127.0f; ex_status->fsStickX = (sint8)axis.x; ex_status->fsStickY = (sint8)axis.y; break; } case kDataFormat_CLASSIC: case kDataFormat_CLASSIC_ACC: case kDataFormat_CLASSIC_ACC_DPD: case kDataFormat_GUITAR: case kDataFormat_DRUM: case kDataFormat_TAIKO: { WPADCLStatus_t* ex_status = (WPADCLStatus_t*)status; memset(ex_status, 0x00, sizeof(*ex_status)); ex_status->clButton = button; auto axis = get_axis(); axis *= 2048.0f; ex_status->clLStickX = (uint16)axis.x; ex_status->clLStickY = (uint16)axis.y; auto rotation = get_rotation(); rotation *= 2048.0f; ex_status->clRStickX = (uint16)rotation.x; ex_status->clRStickY = (uint16)rotation.y; break; } case kDataFormat_TRAIN: { WPADTRStatus_t* ex_status = (WPADTRStatus_t*)status; // TODO break; } case kDataFormat_BALANCE_CHECKER: { WPADBLStatus_t* ex_status = (WPADBLStatus_t*)status; // TODO break; } case kDataFormat_MPLS: { WPADMPStatus_t* ex_status = (WPADMPStatus_t*)status; ex_status->stat = 1; // attached // TODO break; } case kDataFormat_URCC: { WPADUCStatus_t* ex_status = (WPADUCStatus_t*)status; memset(ex_status, 0x00, sizeof(*ex_status)); ex_status->ucButton = button; ex_status->cable = TRUE; ex_status->charge = TRUE; auto axis = get_axis(); axis *= 2048.0f; ex_status->ucLStickX = (uint16)axis.x; ex_status->ucLStickY = (uint16)axis.y; auto rotation = get_rotation(); rotation *= 2048.0f; ex_status->ucRStickX = (uint16)rotation.x; ex_status->ucRStickY = (uint16)rotation.y; break; } default: cemu_assert(false); } status->dev = get_device_type(); status->err = WPAD_ERR_NONE; } void WPADController::KPADRead(KPADStatus_t& status, const BtnRepeat& repeat) { uint32be* hold, *release, *trigger; switch (type()) { case Pro: hold = &status.ex_status.uc.hold; release = &status.ex_status.uc.release; trigger = &status.ex_status.uc.trig; break; case Classic: hold = &status.ex_status.cl.hold; release = &status.ex_status.cl.release; trigger = &status.ex_status.cl.trig; break; default: hold = &status.hold; release = &status.release; trigger = &status.trig; } controllers_update_states(); for (uint32 i = 1; i < get_highest_mapping_id(); ++i) { if (is_mapping_down(i)) { const uint32 value = get_emulated_button_flag(m_data_format, i); *hold |= value; } } m_homebutton_down |= is_home_down(); // button repeat const auto now = std::chrono::steady_clock::now(); if (*hold != m_last_holdvalue) { m_last_hold_change = m_last_pulse = now; } if (repeat.pulse > 0) { if (m_last_hold_change + std::chrono::milliseconds(repeat.delay) >= now) { if ((m_last_pulse + std::chrono::milliseconds(repeat.pulse)) < now) { m_last_pulse = now; *hold |= kWPADButtonRepeat; } } } // axis const auto axis = get_axis(); const auto rotation = get_rotation(); *release = m_last_holdvalue & ~*hold; //status.release = m_last_holdvalue & ~*hold; *trigger = ~m_last_holdvalue & *hold; //status.trig = ~m_last_holdvalue & *hold; m_last_holdvalue = *hold; if (is_mpls_attached()) { status.mpls.dir.X.x = 1; status.mpls.dir.X.y = 0; status.mpls.dir.X.z = 0; status.mpls.dir.Y.x = 0; status.mpls.dir.Y.y = 1; status.mpls.dir.Y.z = 0; status.mpls.dir.Z.x = 0; status.mpls.dir.Z.y = 0; status.mpls.dir.Z.z = 1; } if (has_motion()) { auto motion_sample = get_motion_data(); glm::vec3 acc; motion_sample.getAccelerometer(&acc[0]); status.acc.x = acc.x; status.acc.y = acc.y; status.acc.z = acc.z; status.acc_value = motion_sample.getVPADAccMagnitude(); status.acc_speed = motion_sample.getVPADAccAcceleration(); //glm::vec2 acc_vert; //motion_sample.getVPADAccXY(&acc_vert[0]); //status.acc_vertical.x = acc_vert.x; //status.acc_vertical.y = acc_vert.y; status.accVertical.x = std::min(1.0f, std::abs(acc.x + acc.y)); status.accVertical.y = std::min(std::max(-1.0f, -acc.z), 1.0f); if (is_mpls_attached()) { // todo glm::vec3 gyroChange; motion_sample.getVPADGyroChange(&gyroChange[0]); //const auto& gyroChange = motionSample.getVPADGyroChange(); status.mpls.mpls.x = gyroChange.x; status.mpls.mpls.y = gyroChange.y; status.mpls.mpls.z = gyroChange.z; //debug_printf("GyroChange %7.2lf %7.2lf %7.2lf\n", (float)status.gyroChange.x, (float)status.gyroChange.y, (float)status.gyroChange.z); glm::vec3 gyroOrientation; motion_sample.getVPADOrientation(&gyroOrientation[0]); //const auto& gyroOrientation = motionSample.getVPADOrientation(); status.mpls.angle.x = gyroOrientation.x; status.mpls.angle.y = gyroOrientation.y; status.mpls.angle.z = gyroOrientation.z; float attitude[9]; motion_sample.getVPADAttitudeMatrix(attitude); status.mpls.dir.X.x = attitude[0]; status.mpls.dir.X.y = attitude[1]; status.mpls.dir.X.z = attitude[2]; status.mpls.dir.Y.x = attitude[3]; status.mpls.dir.Y.y = attitude[4]; status.mpls.dir.Y.z = attitude[5]; status.mpls.dir.Z.x = attitude[6]; status.mpls.dir.Z.y = attitude[7]; status.mpls.dir.Z.z = attitude[8]; } } auto visibility = GetPositionVisibility(); if (has_position() && visibility != PositionVisibility::NONE) { if (visibility == PositionVisibility::FULL) status.dpd_valid_fg = 2; else status.dpd_valid_fg = -1; const auto position = get_position(); const auto pos = (position * 2.0f) - 1.0f; status.pos.x = pos.x; status.pos.y = pos.y; const auto delta = position - get_prev_position(); status.vec.x = delta.x; status.vec.y = delta.y; status.speed = glm::length(delta); } else status.dpd_valid_fg = 0; switch (type()) { case Wiimote: status.ex_status.fs.stick.x = axis.x; status.ex_status.fs.stick.y = axis.y; if(has_second_motion()) { auto motion_sample = get_second_motion_data(); glm::vec3 acc; motion_sample.getAccelerometer(&acc[0]); status.ex_status.fs.acc.x = acc.x; status.ex_status.fs.acc.y = acc.y; status.ex_status.fs.acc.z = acc.z; status.ex_status.fs.accValue = motion_sample.getVPADAccMagnitude(); status.ex_status.fs.accSpeed = motion_sample.getVPADAccAcceleration(); } break; case Pro: status.ex_status.uc.lstick.x = axis.x; status.ex_status.uc.lstick.y = axis.y; status.ex_status.uc.rstick.x = rotation.x; status.ex_status.uc.rstick.y = rotation.y; status.ex_status.uc.charge = FALSE; status.ex_status.uc.cable = TRUE; break; case Classic: status.ex_status.cl.lstick.x = axis.x; status.ex_status.cl.lstick.y = axis.y; status.ex_status.cl.rstick.x = rotation.x; status.ex_status.cl.rstick.y = rotation.y; if (HAS_FLAG((uint32)status.ex_status.cl.hold, kCLButton_ZL)) status.ex_status.cl.ltrigger = 1.0f; if (HAS_FLAG((uint32)status.ex_status.cl.hold, kCLButton_ZR)) status.ex_status.cl.rtrigger = 1.0f; break; default: cemu_assert(false); } }
9,508
C++
.cpp
327
26.235474
139
0.715727
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,918
VPADController.cpp
cemu-project_Cemu/src/input/emulated/VPADController.cpp
#include "input/emulated/VPADController.h" #include "input/api/Controller.h" #include "input/api/SDL/SDLController.h" #include "gui/guiWrapper.h" #include "input/InputManager.h" #include "Cafe/HW/Latte/Core/Latte.h" #include "Cafe/CafeSystem.h" #include <wx/intl.h> enum ControllerVPADMapping2 : uint32 { VPAD_A = 0x8000, VPAD_B = 0x4000, VPAD_X = 0x2000, VPAD_Y = 0x1000, VPAD_L = 0x0020, VPAD_R = 0x0010, VPAD_ZL = 0x0080, VPAD_ZR = 0x0040, VPAD_PLUS = 0x0008, VPAD_MINUS = 0x0004, VPAD_HOME = 0x0002, VPAD_UP = 0x0200, VPAD_DOWN = 0x0100, VPAD_LEFT = 0x0800, VPAD_RIGHT = 0x0400, VPAD_STICK_R = 0x00020000, VPAD_STICK_L = 0x00040000, VPAD_STICK_L_UP = 0x10000000, VPAD_STICK_L_DOWN = 0x08000000, VPAD_STICK_L_LEFT = 0x40000000, VPAD_STICK_L_RIGHT = 0x20000000, VPAD_STICK_R_UP = 0x01000000, VPAD_STICK_R_DOWN = 0x00800000, VPAD_STICK_R_LEFT = 0x04000000, VPAD_STICK_R_RIGHT = 0x02000000, // special flag VPAD_REPEAT = 0x80000000, }; void VPADController::VPADRead(VPADStatus_t& status, const BtnRepeat& repeat) { controllers_update_states(); m_mic_active = false; m_screen_active = false; for (uint32 i = kButtonId_A; i < kButtonId_Max; ++i) { // axis will be aplied later if (is_axis_mapping(i)) continue; if (is_mapping_down(i)) { const uint32 value = get_emulated_button_flag(i); if (value == 0) { // special buttons if (i == kButtonId_Mic) m_mic_active = true; else if (i == kButtonId_Screen) m_screen_active = true; continue; } status.hold |= value; } } m_homebutton_down |= is_home_down(); const auto axis = get_axis(); status.leftStick.x = axis.x; status.leftStick.y = axis.y; constexpr float kAxisThreshold = 0.5f; constexpr float kHoldAxisThreshold = 0.1f; const uint32 last_hold = m_last_holdvalue; if (axis.x <= -kAxisThreshold || (HAS_FLAG(last_hold, VPAD_STICK_L_LEFT) && axis.x <= -kHoldAxisThreshold)) status.hold |= VPAD_STICK_L_LEFT; else if (axis.x >= kAxisThreshold || (HAS_FLAG(last_hold, VPAD_STICK_L_RIGHT) && axis.x >= kHoldAxisThreshold)) status.hold |= VPAD_STICK_L_RIGHT; if (axis.y <= -kAxisThreshold || (HAS_FLAG(last_hold, VPAD_STICK_L_DOWN) && axis.y <= -kHoldAxisThreshold)) status.hold |= VPAD_STICK_L_DOWN; else if (axis.y >= kAxisThreshold || (HAS_FLAG(last_hold, VPAD_STICK_L_UP) && axis.y >= kHoldAxisThreshold)) status.hold |= VPAD_STICK_L_UP; const auto rotation = get_rotation(); status.rightStick.x = rotation.x; status.rightStick.y = rotation.y; if (rotation.x <= -kAxisThreshold || (HAS_FLAG(last_hold, VPAD_STICK_R_LEFT) && rotation.x <= -kHoldAxisThreshold)) status.hold |= VPAD_STICK_R_LEFT; else if (rotation.x >= kAxisThreshold || (HAS_FLAG(last_hold, VPAD_STICK_R_RIGHT) && rotation.x >= kHoldAxisThreshold)) status.hold |= VPAD_STICK_R_RIGHT; if (rotation.y <= -kAxisThreshold || (HAS_FLAG(last_hold, VPAD_STICK_R_DOWN) && rotation.y <= -kHoldAxisThreshold)) status.hold |= VPAD_STICK_R_DOWN; else if (rotation.y >= kAxisThreshold || (HAS_FLAG(last_hold, VPAD_STICK_R_UP) && rotation.y >= kHoldAxisThreshold)) status.hold |= VPAD_STICK_R_UP; // button repeat const auto now = std::chrono::high_resolution_clock::now(); if (status.hold != m_last_holdvalue) { m_last_hold_change = m_last_pulse = now; } if (repeat.pulse > 0) { if (m_last_hold_change + std::chrono::milliseconds(repeat.delay) >= now) { if ((m_last_pulse + std::chrono::milliseconds(repeat.pulse)) < now) { m_last_pulse = now; status.hold |= VPAD_REPEAT; } } } // general status.release = m_last_holdvalue & ~status.hold; status.trig = ~m_last_holdvalue & status.hold; m_last_holdvalue = status.hold; // touch update_touch(status); // motion status.dir.x = {1, 0, 0}; status.dir.y = {0, 1, 0}; status.dir.z = {0, 0, 1}; status.accXY = {1.0f, 0.0f}; update_motion(status); } void VPADController::update() { EmulatedController::update(); if (!CafeSystem::IsTitleRunning()) return; std::unique_lock lock(m_rumble_mutex); if (m_rumble_queue.empty()) { m_parser = 0; lock.unlock(); stop_rumble(); return; } const auto tick = now_cached(); if (std::chrono::duration_cast<std::chrono::milliseconds>(tick - m_last_rumble_check).count() < 1000 / 60) return; m_last_rumble_check = tick; const auto& it = m_rumble_queue.front(); if (it[m_parser]) start_rumble(); else stop_rumble(); ++m_parser; if (m_parser >= it.size()) { m_rumble_queue.pop(); m_parser = 0; } } void VPADController::update_touch(VPADStatus_t& status) { status.tpData.touch = kTpTouchOff; status.tpData.validity = kTpInvalid; // keep x,y from previous update // NGDK (Neko Game Development Kit 2) games (e.g. Mysterios Cities of Gold) rely on x/y remaining intact after touch is released status.tpData.x = (uint16)m_last_touch_position.x; status.tpData.y = (uint16)m_last_touch_position.y; auto& instance = InputManager::instance(); bool pad_view; if (has_position()) { const auto mouse = get_position(); status.tpData.touch = kTpTouchOn; status.tpData.validity = kTpValid; status.tpData.x = (uint16)(mouse.x * 3883.0f + 92.0f); status.tpData.y = (uint16)(4095.0f - mouse.y * 3694.0f - 254.0f); m_last_touch_position = glm::ivec2{status.tpData.x, status.tpData.y}; } else if (const auto left_mouse = instance.get_left_down_mouse_info(&pad_view)) { glm::ivec2 image_pos, image_size; LatteRenderTarget_getScreenImageArea(&image_pos.x, &image_pos.y, &image_size.x, &image_size.y, nullptr, nullptr, pad_view); glm::vec2 relative_mouse_pos = left_mouse.value() - image_pos; relative_mouse_pos = { std::min(relative_mouse_pos.x, (float)image_size.x), std::min(relative_mouse_pos.y, (float)image_size.y) }; relative_mouse_pos = { std::max(relative_mouse_pos.x, 0.0f), std::max(relative_mouse_pos.y, 0.0f) }; relative_mouse_pos /= image_size; status.tpData.touch = kTpTouchOn; status.tpData.validity = kTpValid; status.tpData.x = (uint16)((relative_mouse_pos.x * 3883.0f) + 92.0f); status.tpData.y = (uint16)(4095.0f - (relative_mouse_pos.y * 3694.0f) - 254.0f); m_last_touch_position = glm::ivec2{ status.tpData.x, status.tpData.y }; /*cemuLog_log(LogType::Force, "TDATA: {},{} -> {},{} -> {},{} -> {},{} -> {},{} -> {},{}", left_mouse->x, left_mouse->y, (left_mouse.value() - image_pos).x, (left_mouse.value() - image_pos).y, relative_mouse_pos.x, relative_mouse_pos.y, (uint16)(relative_mouse_pos.x * 3883.0 + 92.0), (uint16)(4095.0 - relative_mouse_pos.y * 3694.0 - 254.0), status.tpData.x.value(), status.tpData.y.value(), status.tpData.x.bevalue(), status.tpData.y.bevalue() );*/ } status.tpProcessed1 = status.tpData; status.tpProcessed2 = status.tpData; } void VPADController::update_motion(VPADStatus_t& status) { if (has_motion()) { auto motionSample = get_motion_data(); glm::vec3 acc; motionSample.getVPADAccelerometer(&acc[0]); //const auto& acc = motionSample.getVPADAccelerometer(); status.acc.x = acc.x; status.acc.y = acc.y; status.acc.z = acc.z; status.accMagnitude = motionSample.getVPADAccMagnitude(); status.accAcceleration = motionSample.getVPADAccAcceleration(); glm::vec3 gyroChange; motionSample.getVPADGyroChange(&gyroChange[0]); //const auto& gyroChange = motionSample.getVPADGyroChange(); status.gyroChange.x = gyroChange.x; status.gyroChange.y = gyroChange.y; status.gyroChange.z = gyroChange.z; //debug_printf("GyroChange %7.2lf %7.2lf %7.2lf\n", (float)status.gyroChange.x, (float)status.gyroChange.y, (float)status.gyroChange.z); glm::vec3 gyroOrientation; motionSample.getVPADOrientation(&gyroOrientation[0]); //const auto& gyroOrientation = motionSample.getVPADOrientation(); status.gyroOrientation.x = gyroOrientation.x; status.gyroOrientation.y = gyroOrientation.y; status.gyroOrientation.z = gyroOrientation.z; float attitude[9]; motionSample.getVPADAttitudeMatrix(attitude); status.dir.x.x = attitude[0]; status.dir.x.y = attitude[1]; status.dir.x.z = attitude[2]; status.dir.y.x = attitude[3]; status.dir.y.y = attitude[4]; status.dir.y.z = attitude[5]; status.dir.z.x = attitude[6]; status.dir.z.y = attitude[7]; status.dir.z.z = attitude[8]; return; } bool pad_view; auto& input_manager = InputManager::instance(); if (const auto right_mouse = input_manager.get_right_down_mouse_info(&pad_view)) { const Vector2<float> mousePos(right_mouse->x, right_mouse->y); int w, h; if (pad_view) gui_getPadWindowPhysSize(w, h); else gui_getWindowPhysSize(w, h); float wx = mousePos.x / w; float wy = mousePos.y / h; static glm::vec3 m_lastGyroRotation{}, m_startGyroRotation{}; static bool m_startGyroRotationSet{}; float rotX = (wy * 2 - 1.0f) * 135.0f; // up/down best float rotY = (wx * 2 - 1.0f) * -180.0f; // left/right float rotZ = input_manager.m_mouse_wheel * 14.0f + m_lastGyroRotation.z; input_manager.m_mouse_wheel = 0.0f; if (!m_startGyroRotationSet) { m_startGyroRotation = {rotX, rotY, rotZ}; m_startGyroRotationSet = true; } /* debug_printf("\n\ngyro:\n<%.02f, %.02f, %.02f>\n\n", rotX, rotY, rotZ);*/ Quaternion<float> q(rotX, rotY, rotZ); auto rot = q.GetTransposedRotationMatrix(); /*m_forward = std::get<0>(rot); m_right = std::get<1>(rot); m_up = std::get<2>(rot);*/ status.dir.x = std::get<0>(rot); status.dir.y = std::get<1>(rot); status.dir.z = std::get<2>(rot); /*debug_printf("rot:\n<%.02f, %.02f, %.02f>\n<%.02f, %.02f, %.02f>\n<%.02f, %.02f, %.02f>\n\n", (float)status.dir.x.x, (float)status.dir.x.y, (float)status.dir.x.z, (float)status.dir.y.x, (float)status.dir.y.y, (float)status.dir.y.z, (float)status.dir.z.x, (float)status.dir.z.y, (float)status.dir.z.z);*/ glm::vec3 rotation(rotX - m_lastGyroRotation.x, (rotY - m_lastGyroRotation.y) * 15.0f, rotZ - m_lastGyroRotation.z); rotation.x = std::min(1.0f, std::max(-1.0f, rotation.x / 360.0f)); rotation.y = std::min(1.0f, std::max(-1.0f, rotation.y / 360.0f)); rotation.z = std::min(1.0f, std::max(-1.0f, rotation.z / 360.0f)); /*debug_printf("\n\ngyro:\n<%.02f, %.02f, %.02f>\n\n", rotation.x, rotation.y, rotation.z);*/ constexpr float pi2 = (float)(M_PI * 2); status.gyroChange = {rotation.x, rotation.y, rotation.z}; status.gyroOrientation = {rotation.x, rotation.y, rotation.z}; //status.angle = { rotation.x / pi2, rotation.y / pi2, rotation.z / pi2 }; status.acc = {rotation.x, rotation.y, rotation.z}; status.accAcceleration = 1.0f; status.accMagnitude = 1.0f; status.accXY = {1.0f, 0.0f}; m_lastGyroRotation = {rotX, rotY, rotZ}; } } std::string_view VPADController::get_button_name(ButtonId id) { switch (id) { case kButtonId_A: return "A"; case kButtonId_B: return "B"; case kButtonId_X: return "X"; case kButtonId_Y: return "Y"; case kButtonId_L: return "L"; case kButtonId_R: return "R"; case kButtonId_ZL: return "ZL"; case kButtonId_ZR: return "ZR"; case kButtonId_Plus: return "+"; case kButtonId_Minus: return "-"; case kButtonId_Up: return wxTRANSLATE("up"); case kButtonId_Down: return wxTRANSLATE("down"); case kButtonId_Left: return wxTRANSLATE("left"); case kButtonId_Right: return wxTRANSLATE("right"); case kButtonId_StickL: return wxTRANSLATE("click"); case kButtonId_StickR: return wxTRANSLATE("click"); case kButtonId_StickL_Up: return wxTRANSLATE("up"); case kButtonId_StickL_Down: return wxTRANSLATE("down"); case kButtonId_StickL_Left: return wxTRANSLATE("left"); case kButtonId_StickL_Right: return wxTRANSLATE("right"); case kButtonId_StickR_Up: return wxTRANSLATE("up"); case kButtonId_StickR_Down: return wxTRANSLATE("down"); case kButtonId_StickR_Left: return wxTRANSLATE("left"); case kButtonId_StickR_Right: return wxTRANSLATE("right"); case kButtonId_Home: return wxTRANSLATE("home"); default: cemu_assert_debug(false); return ""; } } void VPADController::clear_rumble() { std::scoped_lock lock(m_rumble_mutex); while (!m_rumble_queue.empty()) m_rumble_queue.pop(); m_parser = 0; } bool VPADController::push_rumble(uint8* pattern, uint8 length) { if (pattern == nullptr || length == 0) { clear_rumble(); return true; } std::scoped_lock lock(m_rumble_mutex); if (m_rumble_queue.size() >= 5) { cemuLog_logDebug(LogType::Force, "too many cmds"); return false; } // len = max 15 bytes of data = 120 bits = 1 seconds // we will use 60 hz for 1 second std::vector<bool> bitset; int byte = 0; int len = (int)length; while (len > 0) { const uint8 p = pattern[byte]; for (int j = 0; j < 8 && j < len; j += 2) { const bool set = (p & (3 << j)) != 0; bitset.push_back(set); } ++byte; len -= 8; } m_rumble_queue.emplace(std::move(bitset)); m_last_rumble_check = {}; return true; } uint32 VPADController::get_emulated_button_flag(uint32 id) const { switch (id) { case kButtonId_A: return VPAD_A; case kButtonId_B: return VPAD_B; case kButtonId_X: return VPAD_X; case kButtonId_Y: return VPAD_Y; case kButtonId_L: return VPAD_L; case kButtonId_R: return VPAD_R; case kButtonId_ZL: return VPAD_ZL; case kButtonId_ZR: return VPAD_ZR; case kButtonId_Plus: return VPAD_PLUS; case kButtonId_Minus: return VPAD_MINUS; case kButtonId_Up: return VPAD_UP; case kButtonId_Down: return VPAD_DOWN; case kButtonId_Left: return VPAD_LEFT; case kButtonId_Right: return VPAD_RIGHT; case kButtonId_StickL: return VPAD_STICK_L; case kButtonId_StickR: return VPAD_STICK_R; case kButtonId_StickL_Up: return VPAD_STICK_L_UP; case kButtonId_StickL_Down: return VPAD_STICK_L_DOWN; case kButtonId_StickL_Left: return VPAD_STICK_L_LEFT; case kButtonId_StickL_Right: return VPAD_STICK_L_RIGHT; case kButtonId_StickR_Up: return VPAD_STICK_R_UP; case kButtonId_StickR_Down: return VPAD_STICK_R_DOWN; case kButtonId_StickR_Left: return VPAD_STICK_R_LEFT; case kButtonId_StickR_Right: return VPAD_STICK_R_RIGHT; } return 0; } glm::vec2 VPADController::get_axis() const { const auto left = get_axis_value(kButtonId_StickL_Left); const auto right = get_axis_value(kButtonId_StickL_Right); const auto up = get_axis_value(kButtonId_StickL_Up); const auto down = get_axis_value(kButtonId_StickL_Down); glm::vec2 result; result.x = (left > right) ? -left : right; result.y = (up > down) ? up : -down; return length(result) > 1.0f ? normalize(result) : result; } glm::vec2 VPADController::get_rotation() const { const auto left = get_axis_value(kButtonId_StickR_Left); const auto right = get_axis_value(kButtonId_StickR_Right); const auto up = get_axis_value(kButtonId_StickR_Up); const auto down = get_axis_value(kButtonId_StickR_Down); glm::vec2 result; result.x = (left > right) ? -left : right; result.y = (up > down) ? up : -down; return length(result) > 1.0f ? normalize(result) : result; } glm::vec2 VPADController::get_trigger() const { const auto left = get_axis_value(kButtonId_ZL); const auto right = get_axis_value(kButtonId_ZR); return {left, right}; } bool VPADController::set_default_mapping(const std::shared_ptr<ControllerBase>& controller) { std::vector<std::pair<uint64, uint64>> mapping; switch (controller->api()) { case InputAPI::SDLController: { const auto sdl_controller = std::static_pointer_cast<SDLController>(controller); if (sdl_controller->get_guid() == SDLController::kLeftJoyCon) { mapping = { {kButtonId_L, kButton9}, {kButtonId_ZL, kTriggerXP}, {kButtonId_Minus, kButton4}, {kButtonId_Up, kButton11}, {kButtonId_Down, kButton12}, {kButtonId_Left, kButton13}, {kButtonId_Right, kButton14}, {kButtonId_StickL, kButton7}, {kButtonId_StickL_Up, kAxisYN}, {kButtonId_StickL_Down, kAxisYP}, {kButtonId_StickL_Left, kAxisXN}, {kButtonId_StickL_Right, kAxisXP}, {kButtonId_Mic, kButton15}, }; } else if (sdl_controller->get_guid() == SDLController::kRightJoyCon) { mapping = { {kButtonId_A, kButton0}, {kButtonId_B, kButton1}, {kButtonId_X, kButton2}, {kButtonId_Y, kButton3}, {kButtonId_R, kButton10}, {kButtonId_ZR, kTriggerYP}, {kButtonId_Plus, kButton6}, {kButtonId_StickR, kButton8}, {kButtonId_StickR_Up, kRotationYN}, {kButtonId_StickR_Down, kRotationYP}, {kButtonId_StickR_Left, kRotationXN}, {kButtonId_StickR_Right, kRotationXP}, }; } else if (sdl_controller->get_guid() == SDLController::kSwitchProController) { // Switch Pro Controller is similar to default mapping, but with a/b and x/y swapped mapping = { {kButtonId_A, kButton0}, {kButtonId_B, kButton1}, {kButtonId_X, kButton2}, {kButtonId_Y, kButton3}, {kButtonId_L, kButton9}, {kButtonId_R, kButton10}, {kButtonId_ZL, kTriggerXP}, {kButtonId_ZR, kTriggerYP}, {kButtonId_Plus, kButton6}, {kButtonId_Minus, kButton4}, {kButtonId_Up, kButton11}, {kButtonId_Down, kButton12}, {kButtonId_Left, kButton13}, {kButtonId_Right, kButton14}, {kButtonId_StickL, kButton7}, {kButtonId_StickR, kButton8}, {kButtonId_StickL_Up, kAxisYN}, {kButtonId_StickL_Down, kAxisYP}, {kButtonId_StickL_Left, kAxisXN}, {kButtonId_StickL_Right, kAxisXP}, {kButtonId_StickR_Up, kRotationYN}, {kButtonId_StickR_Down, kRotationYP}, {kButtonId_StickR_Left, kRotationXN}, {kButtonId_StickR_Right, kRotationXP}, }; } else { mapping = { {kButtonId_A, kButton1}, {kButtonId_B, kButton0}, {kButtonId_X, kButton3}, {kButtonId_Y, kButton2}, {kButtonId_L, kButton9}, {kButtonId_R, kButton10}, {kButtonId_ZL, kTriggerXP}, {kButtonId_ZR, kTriggerYP}, {kButtonId_Plus, kButton6}, {kButtonId_Minus, kButton4}, {kButtonId_Up, kButton11}, {kButtonId_Down, kButton12}, {kButtonId_Left, kButton13}, {kButtonId_Right, kButton14}, {kButtonId_StickL, kButton7}, {kButtonId_StickR, kButton8}, {kButtonId_StickL_Up, kAxisYN}, {kButtonId_StickL_Down, kAxisYP}, {kButtonId_StickL_Left, kAxisXN}, {kButtonId_StickL_Right, kAxisXP}, {kButtonId_StickR_Up, kRotationYN}, {kButtonId_StickR_Down, kRotationYP}, {kButtonId_StickR_Left, kRotationXN}, {kButtonId_StickR_Right, kRotationXP}, }; } break; } case InputAPI::XInput: { mapping = { {kButtonId_A, kButton13}, {kButtonId_B, kButton12}, {kButtonId_X, kButton15}, {kButtonId_Y, kButton14}, {kButtonId_L, kButton8}, {kButtonId_R, kButton9}, {kButtonId_ZL, kTriggerXP}, {kButtonId_ZR, kTriggerYP}, {kButtonId_Plus, kButton4}, {kButtonId_Minus, kButton5}, {kButtonId_Up, kButton0}, {kButtonId_Down, kButton1}, {kButtonId_Left, kButton2}, {kButtonId_Right, kButton3}, {kButtonId_StickL, kButton6}, {kButtonId_StickR, kButton7}, {kButtonId_StickL_Up, kAxisYP}, {kButtonId_StickL_Down, kAxisYN}, {kButtonId_StickL_Left, kAxisXN}, {kButtonId_StickL_Right, kAxisXP}, {kButtonId_StickR_Up, kRotationYP}, {kButtonId_StickR_Down, kRotationYN}, {kButtonId_StickR_Left, kRotationXN}, {kButtonId_StickR_Right, kRotationXP}, }; break; } } bool mapping_updated = false; std::for_each(mapping.cbegin(), mapping.cend(), [this, &controller, &mapping_updated](const auto& m) { if (m_mappings.find(m.first) == m_mappings.cend()) { set_mapping(m.first, controller, m.second); mapping_updated = true; } }); return mapping_updated; } void VPADController::load(const pugi::xml_node& node) { if (const auto value = node.child("toggle_display")) m_screen_active_toggle = ConvertString<bool>(value.child_value()); } void VPADController::save(pugi::xml_node& node) { node.append_child("toggle_display").append_child(pugi::node_pcdata).set_value(fmt::format("{}", (int)m_screen_active_toggle).c_str()); }
19,826
C++
.cpp
578
31.217993
138
0.698562
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,919
ClassicController.cpp
cemu-project_Cemu/src/input/emulated/ClassicController.cpp
#include "input/emulated/ClassicController.h" #include "input/api/Controller.h" #include "input/api/SDL/SDLController.h" #include <wx/intl.h> ClassicController::ClassicController(size_t player_index) : WPADController(player_index, kDataFormat_CLASSIC) { } uint32 ClassicController::get_emulated_button_flag(uint32 id) const { return s_get_emulated_button_flag(id); } uint32 ClassicController::s_get_emulated_button_flag(uint32 id) { switch (id) { case kButtonId_A: return kCLButton_A; case kButtonId_B: return kCLButton_B; case kButtonId_X: return kCLButton_X; case kButtonId_Y: return kCLButton_Y; case kButtonId_Plus: return kCLButton_Plus; case kButtonId_Minus: return kCLButton_Minus; case kButtonId_Up: return kCLButton_Up; case kButtonId_Down: return kCLButton_Down; case kButtonId_Left: return kCLButton_Left; case kButtonId_Right: return kCLButton_Right; case kButtonId_L: return kCLButton_L; case kButtonId_ZL: return kCLButton_ZL; case kButtonId_R: return kCLButton_R; case kButtonId_ZR: return kCLButton_ZR; } return 0; } std::string_view ClassicController::get_button_name(ButtonId id) { switch (id) { case kButtonId_A: return "A"; case kButtonId_B: return "B"; case kButtonId_X: return "X"; case kButtonId_Y: return "Y"; case kButtonId_L: return "L"; case kButtonId_R: return "R"; case kButtonId_ZL: return "ZL"; case kButtonId_ZR: return "ZR"; case kButtonId_Plus: return "+"; case kButtonId_Minus: return "-"; case kButtonId_Home: return wxTRANSLATE("home"); case kButtonId_Up: return wxTRANSLATE("up"); case kButtonId_Down: return wxTRANSLATE("down"); case kButtonId_Left: return wxTRANSLATE("left"); case kButtonId_Right: return wxTRANSLATE("right"); case kButtonId_StickL_Up: return wxTRANSLATE("up"); case kButtonId_StickL_Down: return wxTRANSLATE("down"); case kButtonId_StickL_Left: return wxTRANSLATE("left"); case kButtonId_StickL_Right: return wxTRANSLATE("right"); case kButtonId_StickR_Up: return wxTRANSLATE("up"); case kButtonId_StickR_Down: return wxTRANSLATE("down"); case kButtonId_StickR_Left: return wxTRANSLATE("left"); case kButtonId_StickR_Right: return wxTRANSLATE("right"); default: return ""; } } glm::vec2 ClassicController::get_axis() const { const auto left = get_axis_value(kButtonId_StickL_Left); const auto right = get_axis_value(kButtonId_StickL_Right); const auto up = get_axis_value(kButtonId_StickL_Up); const auto down = get_axis_value(kButtonId_StickL_Down); glm::vec2 result; result.x = (left > right) ? -left : right; result.y = (up > down) ? up : -down; return length(result) > 1.0f ? normalize(result) : result; } glm::vec2 ClassicController::get_rotation() const { const auto left = get_axis_value(kButtonId_StickR_Left); const auto right = get_axis_value(kButtonId_StickR_Right); const auto up = get_axis_value(kButtonId_StickR_Up); const auto down = get_axis_value(kButtonId_StickR_Down); glm::vec2 result; result.x = (left > right) ? -left : right; result.y = (up > down) ? up : -down; return length(result) > 1.0f ? normalize(result) : result; } glm::vec2 ClassicController::get_trigger() const { const auto left = get_axis_value(kButtonId_ZL); const auto right = get_axis_value(kButtonId_ZR); return { left, right }; } bool ClassicController::set_default_mapping(const std::shared_ptr<ControllerBase>& controller) { std::vector<std::pair<uint64, uint64>> mapping; switch (controller->api()) { case InputAPI::SDLController: { const auto sdl_controller = std::static_pointer_cast<SDLController>(controller); if (sdl_controller->get_guid() == SDLController::kLeftJoyCon) { mapping = { {kButtonId_L, kButton9}, {kButtonId_ZL, kTriggerXP}, {kButtonId_Minus, kButton4}, {kButtonId_Up, kButton11}, {kButtonId_Down, kButton12}, {kButtonId_Left, kButton13}, {kButtonId_Right, kButton14}, {kButtonId_StickL_Up, kAxisYN}, {kButtonId_StickL_Down, kAxisYP}, {kButtonId_StickL_Left, kAxisXN}, {kButtonId_StickL_Right, kAxisXP}, }; } else if (sdl_controller->get_guid() == SDLController::kRightJoyCon) { mapping = { {kButtonId_A, kButton0}, {kButtonId_B, kButton1}, {kButtonId_X, kButton2}, {kButtonId_Y, kButton3}, {kButtonId_R, kButton10}, {kButtonId_ZR, kTriggerYP}, {kButtonId_Plus, kButton6}, {kButtonId_StickR_Up, kRotationYN}, {kButtonId_StickR_Down, kRotationYP}, {kButtonId_StickR_Left, kRotationXN}, {kButtonId_StickR_Right, kRotationXP}, }; } else { mapping = { {kButtonId_A, kButton1}, {kButtonId_B, kButton0}, {kButtonId_X, kButton3}, {kButtonId_Y, kButton2}, {kButtonId_L, kButton9}, {kButtonId_R, kButton10}, {kButtonId_ZL, kTriggerXP}, {kButtonId_ZR, kTriggerYP}, {kButtonId_Plus, kButton6}, {kButtonId_Minus, kButton4}, {kButtonId_Up, kButton11}, {kButtonId_Down, kButton12}, {kButtonId_Left, kButton13}, {kButtonId_Right, kButton14}, {kButtonId_StickL_Up, kAxisYN}, {kButtonId_StickL_Down, kAxisYP}, {kButtonId_StickL_Left, kAxisXN}, {kButtonId_StickL_Right, kAxisXP}, {kButtonId_StickR_Up, kRotationYN}, {kButtonId_StickR_Down, kRotationYP}, {kButtonId_StickR_Left, kRotationXN}, {kButtonId_StickR_Right, kRotationXP}, }; } } case InputAPI::XInput: { mapping = { {kButtonId_A, kButton13}, {kButtonId_B, kButton12}, {kButtonId_X, kButton15}, {kButtonId_Y, kButton14}, {kButtonId_L, kButton8}, {kButtonId_R, kButton9}, {kButtonId_ZL, kTriggerXP}, {kButtonId_ZR, kTriggerYP}, {kButtonId_Plus, kButton4}, {kButtonId_Minus, kButton5}, {kButtonId_Up, kButton0}, {kButtonId_Down, kButton1}, {kButtonId_Left, kButton2}, {kButtonId_Right, kButton3}, {kButtonId_StickL_Up, kAxisYP}, {kButtonId_StickL_Down, kAxisYN}, {kButtonId_StickL_Left, kAxisXN}, {kButtonId_StickL_Right, kAxisXP}, {kButtonId_StickR_Up, kRotationYP}, {kButtonId_StickR_Down, kRotationYN}, {kButtonId_StickR_Left, kRotationXN}, {kButtonId_StickR_Right, kRotationXP}, }; break; } } bool mapping_updated = false; std::for_each(mapping.cbegin(), mapping.cend(), [this, &controller, &mapping_updated](const auto& m) { if (m_mappings.find(m.first) == m_mappings.cend()) { set_mapping(m.first, controller, m.second); mapping_updated = true; } }); return mapping_updated; }
6,461
C++
.cpp
217
26.612903
101
0.722303
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,920
WiimoteController.cpp
cemu-project_Cemu/src/input/emulated/WiimoteController.cpp
#include "input/emulated/WiimoteController.h" #include "input/api/Controller.h" #include "input/api/Wiimote/NativeWiimoteController.h" #include <wx/intl.h> WiimoteController::WiimoteController(size_t player_index) : WPADController(player_index, kDataFormat_CORE_ACC_DPD) { } void WiimoteController::set_device_type(WPADDeviceType device_type) { m_device_type = device_type; m_data_format = get_default_data_format(); } bool WiimoteController::is_mpls_attached() { return m_device_type == kWAPDevMPLS || m_device_type == kWAPDevMPLSClassic || m_device_type == kWAPDevMPLSFreeStyle; } uint32 WiimoteController::get_emulated_button_flag(uint32 id) const { return s_get_emulated_button_flag(id); } bool WiimoteController::set_default_mapping(const std::shared_ptr<ControllerBase>& controller) { std::vector<std::pair<uint64, uint64>> mapping; switch (controller->api()) { case InputAPI::Wiimote: { const auto sdl_controller = std::static_pointer_cast<NativeWiimoteController>(controller); mapping = { {kButtonId_A, kWiimoteButton_A}, {kButtonId_B, kWiimoteButton_B}, {kButtonId_1, kWiimoteButton_One}, {kButtonId_2, kWiimoteButton_Two}, {kButtonId_Home, kWiimoteButton_Home}, {kButtonId_Plus, kWiimoteButton_Plus}, {kButtonId_Minus, kWiimoteButton_Minus}, {kButtonId_Up, kWiimoteButton_Up}, {kButtonId_Down, kWiimoteButton_Down}, {kButtonId_Left, kWiimoteButton_Left}, {kButtonId_Right, kWiimoteButton_Right}, {kButtonId_Nunchuck_Z, kWiimoteButton_Z}, {kButtonId_Nunchuck_C, kWiimoteButton_C}, {kButtonId_Nunchuck_Up, kAxisYP}, {kButtonId_Nunchuck_Down, kAxisYN}, {kButtonId_Nunchuck_Left, kAxisXN}, {kButtonId_Nunchuck_Right, kAxisXP}, }; } } bool mapping_updated = false; std::for_each(mapping.cbegin(), mapping.cend(), [this, &controller, &mapping_updated](const auto& m) { if (m_mappings.find(m.first) == m_mappings.cend()) { set_mapping(m.first, controller, m.second); mapping_updated = true; } }); return mapping_updated; } glm::vec2 WiimoteController::get_axis() const { const auto left = get_axis_value(kButtonId_Nunchuck_Left); const auto right = get_axis_value(kButtonId_Nunchuck_Right); const auto up = get_axis_value(kButtonId_Nunchuck_Up); const auto down = get_axis_value(kButtonId_Nunchuck_Down); glm::vec2 result; result.x = (left > right) ? -left : right; result.y = (up > down) ? up : -down; return result; } glm::vec2 WiimoteController::get_rotation() const { return {}; } glm::vec2 WiimoteController::get_trigger() const { return {}; } void WiimoteController::load(const pugi::xml_node& node) { base_type::load(node); if (const auto value = node.child("device_type")) m_device_type = ConvertString<WPADDeviceType>(value.child_value()); } void WiimoteController::save(pugi::xml_node& node) { base_type::save(node); node.append_child("device_type").append_child(pugi::node_pcdata).set_value(fmt::format("{}", (int)m_device_type).c_str()); } uint32 WiimoteController::s_get_emulated_button_flag(uint32 id) { switch (id) { case kButtonId_A: return kWPADButton_A; case kButtonId_B: return kWPADButton_B; case kButtonId_1: return kWPADButton_1; case kButtonId_2: return kWPADButton_2; case kButtonId_Plus: return kWPADButton_Plus; case kButtonId_Minus: return kWPADButton_Minus; case kButtonId_Home: return kWPADButton_Home; case kButtonId_Up: return kWPADButton_Up; case kButtonId_Down: return kWPADButton_Down; case kButtonId_Left: return kWPADButton_Left; case kButtonId_Right: return kWPADButton_Right; case kButtonId_Nunchuck_Z: return kWPADButton_Z; case kButtonId_Nunchuck_C: return kWPADButton_C; } return 0; } std::string_view WiimoteController::get_button_name(ButtonId id) { switch (id) { case kButtonId_A: return "A"; case kButtonId_B: return "B"; case kButtonId_1: return "1"; case kButtonId_2: return "2"; case kButtonId_Home: return wxTRANSLATE("home"); case kButtonId_Plus: return "+"; case kButtonId_Minus: return "-"; case kButtonId_Up: return wxTRANSLATE("up"); case kButtonId_Down: return wxTRANSLATE("down"); case kButtonId_Left: return wxTRANSLATE("left"); case kButtonId_Right: return wxTRANSLATE("right"); case kButtonId_Nunchuck_Z: return "Z"; case kButtonId_Nunchuck_C: return "C"; case kButtonId_Nunchuck_Up: return wxTRANSLATE("up"); case kButtonId_Nunchuck_Down: return wxTRANSLATE("down"); case kButtonId_Nunchuck_Left: return wxTRANSLATE("left"); case kButtonId_Nunchuck_Right: return wxTRANSLATE("right"); default: return ""; } }
4,609
C++
.cpp
149
28.342282
123
0.749153
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,921
ProController.cpp
cemu-project_Cemu/src/input/emulated/ProController.cpp
#include "input/emulated/ProController.h" #include "input/api/Controller.h" #include "input/api/SDL/SDLController.h" #include <wx/intl.h> ProController::ProController(size_t player_index) : WPADController(player_index, kDataFormat_URCC) { } uint32 ProController::get_emulated_button_flag(uint32 id) const { return s_get_emulated_button_flag(id); } uint32 ProController::s_get_emulated_button_flag(uint32 id) { switch (id) { case kButtonId_A: return kProButton_A; case kButtonId_B: return kProButton_B; case kButtonId_X: return kProButton_X; case kButtonId_Y: return kProButton_Y; case kButtonId_Plus: return kProButton_Plus; case kButtonId_Minus: return kProButton_Minus; case kButtonId_Up: return kProButton_Up; case kButtonId_Down: return kProButton_Down; case kButtonId_Left: return kProButton_Left; case kButtonId_Right: return kProButton_Right; case kButtonId_StickL: return kProButton_StickL; case kButtonId_StickR: return kProButton_StickR; case kButtonId_L: return kProButton_L; case kButtonId_ZL: return kProButton_ZL; case kButtonId_R: return kProButton_R; case kButtonId_ZR: return kProButton_ZR; default: return 0; } } std::string_view ProController::get_button_name(ButtonId id) { switch (id) { case kButtonId_A: return "A"; case kButtonId_B: return "B"; case kButtonId_X: return "X"; case kButtonId_Y: return "Y"; case kButtonId_L: return "L"; case kButtonId_R: return "R"; case kButtonId_ZL: return "ZL"; case kButtonId_ZR: return "ZR"; case kButtonId_Plus: return "+"; case kButtonId_Minus: return "-"; case kButtonId_Up: return wxTRANSLATE("up"); case kButtonId_Down: return wxTRANSLATE("down"); case kButtonId_Left: return wxTRANSLATE("left"); case kButtonId_Right: return wxTRANSLATE("right"); case kButtonId_StickL: return wxTRANSLATE("click"); case kButtonId_StickR: return wxTRANSLATE("click"); case kButtonId_StickL_Up: return wxTRANSLATE("up"); case kButtonId_StickL_Down: return wxTRANSLATE("down"); case kButtonId_StickL_Left: return wxTRANSLATE("left"); case kButtonId_StickL_Right: return wxTRANSLATE("right"); case kButtonId_StickR_Up: return wxTRANSLATE("up"); case kButtonId_StickR_Down: return wxTRANSLATE("down"); case kButtonId_StickR_Left: return wxTRANSLATE("left"); case kButtonId_StickR_Right: return wxTRANSLATE("right"); case kButtonId_Home: return wxTRANSLATE("home"); default: cemu_assert_debug(false); return ""; } } glm::vec2 ProController::get_axis() const { const auto left = get_axis_value(kButtonId_StickL_Left); const auto right = get_axis_value(kButtonId_StickL_Right); const auto up = get_axis_value(kButtonId_StickL_Up); const auto down = get_axis_value(kButtonId_StickL_Down); glm::vec2 result; result.x = (left > right) ? -left : right; result.y = (up > down) ? up : -down; return result; } glm::vec2 ProController::get_rotation() const { const auto left = get_axis_value(kButtonId_StickR_Left); const auto right = get_axis_value(kButtonId_StickR_Right); const auto up = get_axis_value(kButtonId_StickR_Up); const auto down = get_axis_value(kButtonId_StickR_Down); glm::vec2 result; result.x = (left > right) ? -left : right; result.y = (up > down) ? up : -down; return result; } glm::vec2 ProController::get_trigger() const { const auto left = get_axis_value(kButtonId_ZL); const auto right = get_axis_value(kButtonId_ZR); return { left, right }; } bool ProController::set_default_mapping(const std::shared_ptr<ControllerBase>& controller) { std::vector<std::pair<uint64, uint64>> mapping; switch (controller->api()) { case InputAPI::SDLController: { const auto sdl_controller = std::static_pointer_cast<SDLController>(controller); if (sdl_controller->get_guid() == SDLController::kLeftJoyCon) { mapping = { {kButtonId_L, kButton9}, {kButtonId_ZL, kTriggerXP}, {kButtonId_Minus, kButton4}, {kButtonId_Up, kButton11}, {kButtonId_Down, kButton12}, {kButtonId_Left, kButton13}, {kButtonId_Right, kButton14}, {kButtonId_StickL, kButton7}, {kButtonId_StickL_Up, kAxisYN}, {kButtonId_StickL_Down, kAxisYP}, {kButtonId_StickL_Left, kAxisXN}, {kButtonId_StickL_Right, kAxisXP}, }; } else if (sdl_controller->get_guid() == SDLController::kRightJoyCon) { mapping = { {kButtonId_A, kButton0}, {kButtonId_B, kButton1}, {kButtonId_X, kButton2}, {kButtonId_Y, kButton3}, {kButtonId_R, kButton10}, {kButtonId_ZR, kTriggerYP}, {kButtonId_Plus, kButton6}, {kButtonId_StickR, kButton8}, {kButtonId_StickR_Up, kRotationYN}, {kButtonId_StickR_Down, kRotationYP}, {kButtonId_StickR_Left, kRotationXN}, {kButtonId_StickR_Right, kRotationXP}, }; } else { mapping = { {kButtonId_A, kButton1}, {kButtonId_B, kButton0}, {kButtonId_X, kButton3}, {kButtonId_Y, kButton2}, {kButtonId_L, kButton9}, {kButtonId_R, kButton10}, {kButtonId_ZL, kTriggerXP}, {kButtonId_ZR, kTriggerYP}, {kButtonId_Plus, kButton6}, {kButtonId_Minus, kButton4}, {kButtonId_Up, kButton11}, {kButtonId_Down, kButton12}, {kButtonId_Left, kButton13}, {kButtonId_Right, kButton14}, {kButtonId_StickL, kButton7}, {kButtonId_StickR, kButton8}, {kButtonId_StickL_Up, kAxisYN}, {kButtonId_StickL_Down, kAxisYP}, {kButtonId_StickL_Left, kAxisXN}, {kButtonId_StickL_Right, kAxisXP}, {kButtonId_StickR_Up, kRotationYN}, {kButtonId_StickR_Down, kRotationYP}, {kButtonId_StickR_Left, kRotationXN}, {kButtonId_StickR_Right, kRotationXP}, }; } break; } case InputAPI::XInput: { mapping = { {kButtonId_A, kButton13}, {kButtonId_B, kButton12}, {kButtonId_X, kButton15}, {kButtonId_Y, kButton14}, {kButtonId_L, kButton8}, {kButtonId_R, kButton9}, {kButtonId_ZL, kTriggerXP}, {kButtonId_ZR, kTriggerYP}, {kButtonId_Plus, kButton4}, {kButtonId_Minus, kButton5}, {kButtonId_Up, kButton0}, {kButtonId_Down, kButton1}, {kButtonId_Left, kButton2}, {kButtonId_Right, kButton3}, {kButtonId_StickL, kButton6}, {kButtonId_StickR, kButton7}, {kButtonId_StickL_Up, kAxisYP}, {kButtonId_StickL_Down, kAxisYN}, {kButtonId_StickL_Left, kAxisXN}, {kButtonId_StickL_Right, kAxisXP}, {kButtonId_StickR_Up, kRotationYP}, {kButtonId_StickR_Down, kRotationYN}, {kButtonId_StickR_Left, kRotationXN}, {kButtonId_StickR_Right, kRotationXP}, }; break; } } bool mapping_updated = false; std::for_each(mapping.cbegin(), mapping.cend(), [this, &controller, &mapping_updated](const auto& m) { if (m_mappings.find(m.first) == m_mappings.cend()) { set_mapping(m.first, controller, m.second); mapping_updated = true; } }); return mapping_updated; }
6,802
C++
.cpp
232
26.150862
101
0.723541
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,922
EmulatedController.cpp
cemu-project_Cemu/src/input/emulated/EmulatedController.cpp
#include "input/emulated/EmulatedController.h" #include "input/api/Controller.h" #ifdef SUPPORTS_WIIMOTE #include "input/api/Wiimote/NativeWiimoteController.h" #endif std::string_view EmulatedController::type_to_string(Type type) { switch (type) { case VPAD: return "Wii U GamePad"; case Pro: return "Wii U Pro Controller"; case Classic: return "Wii U Classic Controller"; case Wiimote: return "Wiimote"; } throw std::runtime_error(fmt::format("unknown emulated controller: {}", to_underlying(type))); } EmulatedController::Type EmulatedController::type_from_string(std::string_view str) { if (str == "Wii U GamePad") return VPAD; else if (str == "Wii U Pro Controller") return Pro; else if (str == "Wii U Classic Controller") return Classic; else if (str == "Wiimote") return Wiimote; throw std::runtime_error(fmt::format("unknown emulated controller: {}", str)); } EmulatedController::EmulatedController(size_t player_index) : m_player_index(player_index) { } void EmulatedController::calibrate() { std::shared_lock lock(m_mutex); for (const auto& controller : m_controllers) { controller->calibrate(); } } void EmulatedController::connect() { std::shared_lock lock(m_mutex); for (const auto& controller : m_controllers) { controller->connect(); } } void EmulatedController::update() { std::shared_lock lock(m_mutex); for(const auto& controller : m_controllers) { controller->update(); } } void EmulatedController::controllers_update_states() { std::shared_lock lock(m_mutex); for (const auto& controller : m_controllers) { controller->update_state(); } } void EmulatedController::start_rumble() { m_rumble = true; std::shared_lock lock(m_mutex); for (const auto& controller : m_controllers) { controller->start_rumble(); } } void EmulatedController::stop_rumble() { if (!m_rumble) return; m_rumble = false; std::shared_lock lock(m_mutex); for (const auto& controller : m_controllers) { controller->stop_rumble(); } } bool EmulatedController::is_battery_low() const { std::shared_lock lock(m_mutex); return std::any_of(m_controllers.cbegin(), m_controllers.cend(), [](const auto& c) {return c->has_low_battery(); }); } bool EmulatedController::has_motion() const { std::shared_lock lock(m_mutex); return std::any_of(m_controllers.cbegin(), m_controllers.cend(), [](const auto& c) {return c->use_motion(); }); } MotionSample EmulatedController::get_motion_data() const { std::shared_lock lock(m_mutex); for (const auto& controller : m_controllers) { if (controller->use_motion()) return controller->get_motion_sample(); } return {}; } bool EmulatedController::has_second_motion() const { int motion = 0; std::shared_lock lock(m_mutex); for(const auto& controller : m_controllers) { if(controller->use_motion()) { // if wiimote has nunchuck connected, we use its acceleration #if SUPPORTS_WIIMOTE if(controller->api() == InputAPI::Wiimote) { if(((NativeWiimoteController*)controller.get())->get_extension() == NativeWiimoteController::Nunchuck) { return true; } } #endif motion++; } } return motion >= 2; } MotionSample EmulatedController::get_second_motion_data() const { int motion = 0; std::shared_lock lock(m_mutex); for (const auto& controller : m_controllers) { if (controller->use_motion()) { // if wiimote has nunchuck connected, we use its acceleration #ifdef SUPPORTS_WIIMOTE if (controller->api() == InputAPI::Wiimote) { if (((NativeWiimoteController*)controller.get())->get_extension() == NativeWiimoteController::Nunchuck) { return ((NativeWiimoteController*)controller.get())->get_nunchuck_motion_sample(); } } #endif motion++; if(motion == 2) { return controller->get_motion_sample(); } } } return {}; } bool EmulatedController::has_position() const { std::shared_lock lock(m_mutex); return std::any_of(m_controllers.cbegin(), m_controllers.cend(), [](const auto& c) {return c->has_position(); }); } glm::vec2 EmulatedController::get_position() const { std::shared_lock lock(m_mutex); for (const auto& controller : m_controllers) { if (controller->has_position()) return controller->get_position(); } return {}; } glm::vec2 EmulatedController::get_prev_position() const { std::shared_lock lock(m_mutex); for (const auto& controller : m_controllers) { if (controller->has_position()) return controller->get_prev_position(); } return {}; } PositionVisibility EmulatedController::GetPositionVisibility() const { std::shared_lock lock(m_mutex); for (const auto& controller : m_controllers) { if (controller->has_position()) return controller->GetPositionVisibility(); } return PositionVisibility::NONE; } void EmulatedController::add_controller(std::shared_ptr<ControllerBase> controller) { controller->connect(); #ifdef SUPPORTS_WIIMOTE if (const auto wiimote = std::dynamic_pointer_cast<NativeWiimoteController>(controller)) { wiimote->set_player_index(m_player_index); } #endif std::scoped_lock lock(m_mutex); m_controllers.emplace_back(std::move(controller)); } void EmulatedController::remove_controller(const std::shared_ptr<ControllerBase>& controller) { std::scoped_lock lock(m_mutex); const auto it = std::find(m_controllers.cbegin(), m_controllers.cend(), controller); if (it != m_controllers.cend()) { m_controllers.erase(it); for(auto m = m_mappings.begin(); m != m_mappings.end();) { if(auto mc = m->second.controller.lock()) { if(*mc == *controller) { m = m_mappings.erase(m); continue; } } ++m; } } } void EmulatedController::clear_controllers() { std::scoped_lock lock(m_mutex); m_controllers.clear(); } float EmulatedController::get_axis_value(uint64 mapping) const { const auto it = m_mappings.find(mapping); if (it != m_mappings.cend()) { if (const auto controller = it->second.controller.lock()) { return controller->get_axis_value(it->second.button); } } return 0; } bool EmulatedController::is_mapping_down(uint64 mapping) const { const auto it = m_mappings.find(mapping); if (it != m_mappings.cend()) { if (const auto controller = it->second.controller.lock()) return controller->get_state().buttons.GetButtonState(it->second.button); } return false; } std::string EmulatedController::get_mapping_name(uint64 mapping) const { const auto it = m_mappings.find(mapping); if (it != m_mappings.cend()) { if (const auto controller = it->second.controller.lock()) { return controller->get_button_name(it->second.button); } } return {}; } std::shared_ptr<ControllerBase> EmulatedController::get_mapping_controller(uint64 mapping) const { const auto it = m_mappings.find(mapping); if (it != m_mappings.cend()) { if (const auto controller = it->second.controller.lock()) { return controller; } } return {}; } void EmulatedController::delete_mapping(uint64 mapping) { m_mappings.erase(mapping); } void EmulatedController::clear_mappings() { m_mappings.clear(); } void EmulatedController::set_mapping(uint64 mapping, const std::shared_ptr<ControllerBase>& controller, uint64 button) { m_mappings[mapping] = { controller, button }; } bool EmulatedController::operator==(const EmulatedController& o) const { return type() == o.type() && m_player_index == o.m_player_index; } bool EmulatedController::operator!=(const EmulatedController& o) const { return !(*this == o); }
7,554
C++
.cpp
290
23.455172
117
0.717256
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,923
ShaderCacheMerger.cpp
cemu-project_Cemu/src/tools/ShaderCacheMerger.cpp
#include "Cemu/FileCache/FileCache.h" #include "Cafe/HW/Latte/Core/LatteShaderCache.h" #include <regex> #include <cinttypes> void MergeShaderCacheFile(std::string fileName) { // parse titleId from fileName uint64 titleId = 0; if (sscanf(fileName.c_str(), "%" SCNx64, &titleId) != 1) return; const std::string mainPath = "shaderCache/transferable/" + fileName; const std::string mergeSourcePath = "shaderCache/transferable/merge/" + fileName; if (!fs::exists(mainPath) || !fs::exists(mergeSourcePath)) return; // open both caches FileCache* mainCache = FileCache::Open(boost::nowide::widen(mainPath)); FileCache* sourceCache = FileCache::Open(boost::nowide::widen(mergeSourcePath)); if (!mainCache && !sourceCache) { printf("Failed to open cache files for %s\n", fileName.c_str()); if (mainCache) delete mainCache; if (sourceCache) delete sourceCache; return; } // begin merging printf("Merging shaders %" PRIx64 "...", titleId); uint32 numMergedEntries = 0; // number of files added to the main cache file for (sint32 i = 0; i < sourceCache->GetFileCount(); i++) { uint64 name1, name2; std::vector<uint8> fileData; if (!sourceCache->GetFileByIndex(i, &name1, &name2, fileData)) continue; std::vector<uint8> existingfileData; if (mainCache->HasFile({ name1, name2 })) continue; mainCache->AddFile({ name1, name2 }, fileData.data(), (sint32)fileData.size()); numMergedEntries++; } printf(" -> Added %d new shaders for a total of %d\n", numMergedEntries, mainCache->GetFileCount()); delete mainCache; delete sourceCache; fs::remove(mergeSourcePath); } void MergePipelineCacheFile(std::string fileName) { // parse titleId from fileName uint64 titleId = 0; if (sscanf(fileName.c_str(), "%" SCNx64, &titleId) != 1) return; const std::string mainPath = "shaderCache/transferable/" + fileName; const std::string mergeSourcePath = "shaderCache/transferable/merge/" + fileName; if (!fs::exists(mainPath) || !fs::exists(mergeSourcePath)) return; // open both caches const uint32 cacheFileVersion = 1; FileCache* mainCache = FileCache::Open(boost::nowide::widen(mainPath)); FileCache* sourceCache = FileCache::Open(boost::nowide::widen(mergeSourcePath)); if (!mainCache && !sourceCache) { printf("Failed to open cache files for %s\n", fileName.c_str()); if (mainCache) delete mainCache; if (sourceCache) delete sourceCache; return; } // begin merging printf("Merging pipelines %" PRIx64 "...", titleId); uint32 numMergedEntries = 0; // number of files added to the main cache file for (sint32 i = 0; i < sourceCache->GetFileCount(); i++) { uint64 name1, name2; std::vector<uint8> fileData; if (!sourceCache->GetFileByIndex(i, &name1, &name2, fileData)) continue; std::vector<uint8> existingfileData; if (mainCache->HasFile({ name1, name2 })) continue; mainCache->AddFile({ name1, name2 }, fileData.data(), (sint32)fileData.size()); numMergedEntries++; } printf(" -> Added %d new pipelines for a total of %d\n", numMergedEntries, mainCache->GetFileCount()); delete mainCache; delete sourceCache; fs::remove(mergeSourcePath); } void MergeShaderAndPipelineCacheFiles() { printf("Scanning for shader cache files to merge...\n"); for (const auto& it : fs::directory_iterator("shaderCache/transferable/")) { if (fs::is_directory(it)) continue; auto filename = it.path().filename().generic_string(); if (std::regex_match(filename, std::regex("^[0-9a-fA-F]{16}(?:_shaders.bin)"))) MergeShaderCacheFile(filename); } printf("\nScanning for pipeline cache files to merge...\n"); for (const auto& it : fs::directory_iterator("shaderCache/transferable/")) { if (fs::is_directory(it)) continue; auto filename = it.path().filename().generic_string(); if (std::regex_match(filename, std::regex("^[0-9a-fA-F]{16}(?:_vkpipeline.bin)"))) MergePipelineCacheFile(filename); } } void ToolShaderCacheMerger() { printf("****************************************************\n"); printf("****************************************************\n"); printf("Shader and pipeline cache merging tool\n"); printf("This tool will merge any shader caches placed in:\n"); printf("shaderCache/transferable/merge/\n"); printf("into the files of the same name in:\n"); printf("shaderCache/transferable/\n"); printf("****************************************************\n"); printf("****************************************************\n"); printf("\n"); MergeShaderAndPipelineCacheFiles(); printf("done!\n"); while (true) Sleep(1000); exit(0); }
4,576
C++
.cpp
128
33.328125
103
0.687486
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,924
SysAllocator.cpp
cemu-project_Cemu/src/Common/SysAllocator.cpp
#include "SysAllocator.h" void SysAllocatorContainer::Initialize() { for (SysAllocatorBase* sysAlloc : m_sysAllocList) { sysAlloc->Initialize(); } } void SysAllocatorContainer::PushSysAllocator(SysAllocatorBase* base) { m_sysAllocList.push_back(base); } SysAllocatorContainer& SysAllocatorContainer::GetInstance() { static SysAllocatorContainer s_instance; return s_instance; } SysAllocatorBase::SysAllocatorBase() { SysAllocatorContainer::GetInstance().PushSysAllocator(this); }
492
C++
.cpp
21
21.857143
68
0.826923
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,925
cpu_features.cpp
cemu-project_Cemu/src/Common/cpu_features.cpp
#include "cpu_features.h" // wrappers with uniform prototype for implementation-specific x86 CPU id #if defined(ARCH_X86_64) #ifdef __GNUC__ #include <cpuid.h> #endif inline void cpuid(int cpuInfo[4], int functionId) { #if defined(_MSC_VER) __cpuid(cpuInfo, functionId); #elif defined(__GNUC__) __cpuid(functionId, cpuInfo[0], cpuInfo[1], cpuInfo[2], cpuInfo[3]); #else #error No definition for cpuid #endif } inline void cpuidex(int cpuInfo[4], int functionId, int subFunctionId) { #if defined(_MSC_VER) __cpuidex(cpuInfo, functionId, subFunctionId); #elif defined(__GNUC__) __cpuid_count(functionId, subFunctionId, cpuInfo[0], cpuInfo[1], cpuInfo[2], cpuInfo[3]); #else #error No definition for cpuidex #endif } #endif CPUFeaturesImpl::CPUFeaturesImpl() { #if defined(ARCH_X86_64) int cpuInfo[4]; cpuid(cpuInfo, 0x80000001); x86.lzcnt = ((cpuInfo[2] >> 5) & 1) != 0; cpuid(cpuInfo, 0x1); x86.movbe = ((cpuInfo[2] >> 22) & 1) != 0; x86.avx = ((cpuInfo[2] >> 28) & 1) != 0; x86.aesni = ((cpuInfo[2] >> 25) & 1) != 0; x86.ssse3 = ((cpuInfo[2] >> 9) & 1) != 0; x86.sse4_1 = ((cpuInfo[2] >> 19) & 1) != 0; cpuidex(cpuInfo, 0x7, 0); x86.avx2 = ((cpuInfo[1] >> 5) & 1) != 0; x86.bmi2 = ((cpuInfo[1] >> 8) & 1) != 0; cpuid(cpuInfo, 0x80000007); x86.invariant_tsc = ((cpuInfo[3] >> 8) & 1); // get CPU brand name uint32_t nExIds, i = 0; memset(m_cpuBrandName, 0, sizeof(m_cpuBrandName)); cpuid(cpuInfo, 0x80000000); nExIds = (uint32_t)cpuInfo[0]; for (uint32_t i = 0x80000000; i <= nExIds; ++i) { cpuid(cpuInfo, i); if (i == 0x80000002) memcpy(m_cpuBrandName, cpuInfo, sizeof(cpuInfo)); else if (i == 0x80000003) memcpy(m_cpuBrandName + 16, cpuInfo, sizeof(cpuInfo)); else if (i == 0x80000004) memcpy(m_cpuBrandName + 32, cpuInfo, sizeof(cpuInfo)); } #endif } std::string CPUFeaturesImpl::GetCPUName() { return { m_cpuBrandName }; } std::string CPUFeaturesImpl::GetCommaSeparatedExtensionList() { std::string tmp; auto appendExt = [&tmp](const char* str) { if (!tmp.empty()) tmp.append(", "); tmp.append(str); }; if (x86.ssse3) appendExt("SSSE3"); if (x86.sse4_1) appendExt("SSE4.1"); if (x86.avx) appendExt("AVX"); if (x86.avx2) appendExt("AVX2"); if (x86.lzcnt) appendExt("LZCNT"); if (x86.movbe) appendExt("MOVBE"); if (x86.bmi2) appendExt("BMI2"); if (x86.aesni) appendExt("AES-NI"); if(x86.invariant_tsc) appendExt("INVARIANT-TSC"); return tmp; } CPUFeaturesImpl g_CPUFeatures;
2,467
C++
.cpp
93
24.548387
90
0.677515
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,926
ExceptionHandler_win32.cpp
cemu-project_Cemu/src/Common/ExceptionHandler/ExceptionHandler_win32.cpp
#include "Common/precompiled.h" #include "Cafe/CafeSystem.h" #include "ExceptionHandler.h" #include <Windows.h> #include <Dbghelp.h> #include <shellapi.h> #include "config/ActiveSettings.h" #include "config/CemuConfig.h" #include "Cafe/OS/libs/coreinit/coreinit_Thread.h" #include "Cafe/HW/Espresso/PPCState.h" #include "Cafe/HW/Espresso/Debugger/GDBStub.h" LONG handleException_SINGLE_STEP(PEXCEPTION_POINTERS pExceptionInfo) { return EXCEPTION_CONTINUE_SEARCH; } #include <boost/algorithm/string.hpp> BOOL CALLBACK MyMiniDumpCallback(PVOID pParam, const PMINIDUMP_CALLBACK_INPUT pInput, PMINIDUMP_CALLBACK_OUTPUT pOutput) { if (!pInput || !pOutput) return FALSE; switch (pInput->CallbackType) { case IncludeModuleCallback: case IncludeThreadCallback: case ThreadCallback: case ThreadExCallback: return TRUE; case ModuleCallback: if (!(pOutput->ModuleWriteFlags & ModuleReferencedByMemory)) pOutput->ModuleWriteFlags &= ~ModuleWriteModule; return TRUE; } return FALSE; } bool CreateMiniDump(CrashDump dump, EXCEPTION_POINTERS* pep) { if (dump == CrashDump::Disabled) return true; fs::path p = ActiveSettings::GetUserDataPath("crashdump"); std::error_code ec; fs::create_directories(p, ec); if (ec) return false; const auto now = std::chrono::system_clock::now(); const auto temp_time = std::chrono::system_clock::to_time_t(now); const auto& time = *std::gmtime(&temp_time); p /= fmt::format("crash_{:04d}{:02d}{:02d}_{:02d}{:02d}{:02d}.dmp", 1900 + time.tm_year, time.tm_mon + 1, time.tm_mday, time.tm_year, time.tm_hour, time.tm_min, time.tm_sec); const auto hFile = CreateFileW(p.wstring().c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (hFile == INVALID_HANDLE_VALUE) return false; MINIDUMP_EXCEPTION_INFORMATION mdei; mdei.ThreadId = GetCurrentThreadId(); mdei.ExceptionPointers = pep; mdei.ClientPointers = FALSE; MINIDUMP_CALLBACK_INFORMATION mci; mci.CallbackRoutine = (MINIDUMP_CALLBACK_ROUTINE)MyMiniDumpCallback; mci.CallbackParam = nullptr; MINIDUMP_TYPE mdt; if (dump == CrashDump::Full) { mdt = (MINIDUMP_TYPE)(MiniDumpWithPrivateReadWriteMemory | MiniDumpWithDataSegs | MiniDumpWithHandleData | MiniDumpWithFullMemoryInfo | MiniDumpWithThreadInfo | MiniDumpWithUnloadedModules); } else { mdt = (MINIDUMP_TYPE)(MiniDumpWithIndirectlyReferencedMemory | MiniDumpScanMemory); } const auto result = MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, mdt, &mdei, nullptr, &mci); CloseHandle(hFile); return result != FALSE; } void DumpThreadStackTrace() { HANDLE process = GetCurrentProcess(); SymInitialize(process, NULL, TRUE); char dumpLine[1024 * 4]; void* stack[100]; const unsigned short frames = CaptureStackBackTrace(0, 40, stack, NULL); SYMBOL_INFO* symbol = (SYMBOL_INFO*)calloc(sizeof(SYMBOL_INFO) + 256 * sizeof(char), 1); symbol->MaxNameLen = 255; symbol->SizeOfStruct = sizeof(SYMBOL_INFO); CrashLog_WriteHeader("Stack trace"); for (unsigned int i = 0; i < frames; i++) { DWORD64 stackTraceOffset = (DWORD64)stack[i]; SymFromAddr(process, stackTraceOffset, 0, symbol); sprintf(dumpLine, "0x%016I64x ", (uint64)(size_t)stack[i]); cemuLog_writePlainToLog(dumpLine); // module name HMODULE stackModule; if (GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCSTR)stackTraceOffset, &stackModule)) { char moduleName[512]; moduleName[0] = '\0'; GetModuleFileNameA(stackModule, moduleName, 512); sint32 moduleNameStartIndex = std::max((sint32)0, (sint32)strlen(moduleName) - 1); while (moduleNameStartIndex > 0) { if (moduleName[moduleNameStartIndex] == '\\' || moduleName[moduleNameStartIndex] == '/') { moduleNameStartIndex++; break; } moduleNameStartIndex--; } DWORD64 moduleAddress = (DWORD64)GetModuleHandleA(moduleName); sint32 relativeOffset = 0; if (moduleAddress != 0) relativeOffset = stackTraceOffset - moduleAddress; sprintf(dumpLine, "+0x%08x %-16s", relativeOffset, moduleName + moduleNameStartIndex); cemuLog_writePlainToLog(dumpLine); } else { sprintf(dumpLine, "+0x00000000 %-16s", "NULL"); cemuLog_writePlainToLog(dumpLine); } // function name sprintf(dumpLine, " %s\n", symbol->Name); cemuLog_writePlainToLog(dumpLine); } free(symbol); } void createCrashlog(EXCEPTION_POINTERS* e, PCONTEXT context) { if(!CrashLog_Create()) return; // give up if crashlog was already created const auto crash_dump = GetConfig().crash_dump.GetValue(); const auto dump_written = CreateMiniDump(crash_dump, e); if (!dump_written) cemuLog_writeLineToLog(fmt::format("couldn't write minidump {:#x}", GetLastError()), false, true); char dumpLine[1024 * 4]; // info about Cemu version sprintf(dumpLine, "\nCrashlog for %s\n", BUILD_VERSION_WITH_NAME_STRING); cemuLog_writePlainToLog(dumpLine); SYSTEMTIME sysTime; GetSystemTime(&sysTime); sprintf(dumpLine, "Date: %02d-%02d-%04d %02d:%02d:%02d\n\n", (sint32)sysTime.wDay, (sint32)sysTime.wMonth, (sint32)sysTime.wYear, (sint32)sysTime.wHour, (sint32)sysTime.wMinute, (sint32)sysTime.wSecond); cemuLog_writePlainToLog(dumpLine); DumpThreadStackTrace(); // info about exception if (e->ExceptionRecord) { HMODULE exceptionModule; if (GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCSTR)(e->ExceptionRecord->ExceptionAddress), &exceptionModule)) { char moduleName[512]; moduleName[0] = '\0'; GetModuleFileNameA(exceptionModule, moduleName, 512); sint32 moduleNameStartIndex = std::max((sint32)0, (sint32)strlen(moduleName) - 1); while (moduleNameStartIndex > 0) { if (moduleName[moduleNameStartIndex] == '\\' || moduleName[moduleNameStartIndex] == '/') { moduleNameStartIndex++; break; } moduleNameStartIndex--; } sprintf(dumpLine, "Exception 0x%08x at 0x%I64x(+0x%I64x) in module %s\n", (uint32)e->ExceptionRecord->ExceptionCode, (uint64)e->ExceptionRecord->ExceptionAddress, (uint64)e->ExceptionRecord->ExceptionAddress - (uint64)exceptionModule, moduleName + moduleNameStartIndex); cemuLog_writePlainToLog(dumpLine); } else { sprintf(dumpLine, "Exception 0x%08x at 0x%I64x\n", (uint32)e->ExceptionRecord->ExceptionCode, (uint64)e->ExceptionRecord->ExceptionAddress); cemuLog_writePlainToLog(dumpLine); } } sprintf(dumpLine, "cemu.exe at 0x%I64x\n", (uint64)GetModuleHandle(NULL)); cemuLog_writePlainToLog(dumpLine); // register info sprintf(dumpLine, "\n"); cemuLog_writePlainToLog(dumpLine); sprintf(dumpLine, "RAX=%016I64x RBX=%016I64x RCX=%016I64x RDX=%016I64x\n", context->Rax, context->Rbx, context->Rcx, context->Rdx); cemuLog_writePlainToLog(dumpLine); sprintf(dumpLine, "RSP=%016I64x RBP=%016I64x RDI=%016I64x RSI=%016I64x\n", context->Rsp, context->Rbp, context->Rdi, context->Rsi); cemuLog_writePlainToLog(dumpLine); sprintf(dumpLine, "R8 =%016I64x R9 =%016I64x R10=%016I64x R11=%016I64x\n", context->R8, context->R9, context->R10, context->R11); cemuLog_writePlainToLog(dumpLine); sprintf(dumpLine, "R12=%016I64x R13=%016I64x R14=%016I64x R15=%016I64x\n", context->R12, context->R13, context->R14, context->R15); cemuLog_writePlainToLog(dumpLine); CrashLog_SetOutputChannels(false, true); ExceptionHandler_LogGeneralInfo(); CrashLog_SetOutputChannels(true, true); cemuLog_waitForFlush(); // save log with the dump if (dump_written && crash_dump != CrashDump::Disabled) { const auto now = std::chrono::system_clock::now(); const auto temp_time = std::chrono::system_clock::to_time_t(now); const auto& time = *std::gmtime(&temp_time); fs::path p = ActiveSettings::GetUserDataPath("crashdump"); p /= fmt::format("log_{:04d}{:02d}{:02d}_{:02d}{:02d}{:02d}.txt", 1900 + time.tm_year, time.tm_mon + 1, time.tm_mday, time.tm_year, time.tm_hour, time.tm_min, time.tm_sec); std::error_code ec; fs::copy_file(ActiveSettings::GetUserDataPath("log.txt"), p, ec); } exit(0); return; } bool logCrashlog; int crashlogThread(void* exceptionInfoRawPtr) { PEXCEPTION_POINTERS pExceptionInfo = (PEXCEPTION_POINTERS)exceptionInfoRawPtr; createCrashlog(pExceptionInfo, pExceptionInfo->ContextRecord); logCrashlog = true; return 0; } void debugger_handleSingleStepException(uint64 dr6); LONG WINAPI VectoredExceptionHandler(PEXCEPTION_POINTERS pExceptionInfo) { if (pExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_SINGLE_STEP) { LONG r = handleException_SINGLE_STEP(pExceptionInfo); if (r != EXCEPTION_CONTINUE_SEARCH) return r; if (GetBits(pExceptionInfo->ContextRecord->Dr6, 0, 1) || GetBits(pExceptionInfo->ContextRecord->Dr6, 1, 1)) debugger_handleSingleStepException(pExceptionInfo->ContextRecord->Dr6); else if (GetBits(pExceptionInfo->ContextRecord->Dr6, 2, 1) || GetBits(pExceptionInfo->ContextRecord->Dr6, 3, 1)) g_gdbstub->HandleAccessException(pExceptionInfo->ContextRecord->Dr6); return EXCEPTION_CONTINUE_EXECUTION; } return EXCEPTION_CONTINUE_SEARCH; } LONG WINAPI cemu_unhandledExceptionFilter(EXCEPTION_POINTERS* pExceptionInfo) { createCrashlog(pExceptionInfo, pExceptionInfo->ContextRecord); return EXCEPTION_NONCONTINUABLE_EXCEPTION; } void ExceptionHandler_Init() { SetUnhandledExceptionFilter(cemu_unhandledExceptionFilter); AddVectoredExceptionHandler(1, VectoredExceptionHandler); SetErrorMode(SEM_FAILCRITICALERRORS); }
9,426
C++
.cpp
238
36.827731
273
0.756757
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,927
ExceptionHandler.cpp
cemu-project_Cemu/src/Common/ExceptionHandler/ExceptionHandler.cpp
#include "config/ActiveSettings.h" #include "config/CemuConfig.h" #include "Cafe/CafeSystem.h" #include "Cafe/OS/libs/coreinit/coreinit_Thread.h" #include "Cafe/HW/Espresso/PPCState.h" #include "Cafe/HW/Espresso/Debugger/GDBStub.h" #include "ExceptionHandler.h" bool crashLogCreated = false; bool CrashLog_Create() { if (crashLogCreated) return false; // only create one crashlog crashLogCreated = true; cemuLog_createLogFile(true); CrashLog_SetOutputChannels(true, true); return true; } static bool s_writeToStdErr{true}; static bool s_writeToLogTxt{true}; void CrashLog_SetOutputChannels(bool writeToStdErr, bool writeToLogTxt) { s_writeToStdErr = writeToStdErr; s_writeToLogTxt = writeToLogTxt; } // outputs to both stderr and log.txt void CrashLog_WriteLine(std::string_view text, bool newLine) { if(s_writeToLogTxt) cemuLog_writeLineToLog(text, false, newLine); if(s_writeToStdErr) { fwrite(text.data(), sizeof(char), text.size(), stderr); if(newLine) fwrite("\n", sizeof(char), 1, stderr); } } void CrashLog_WriteHeader(const char* header) { CrashLog_WriteLine("-----------------------------------------"); CrashLog_WriteLine(" ", false); CrashLog_WriteLine(header); CrashLog_WriteLine("-----------------------------------------"); } void ExceptionHandler_LogGeneralInfo() { char dumpLine[1024]; // info about game CrashLog_WriteLine(""); CrashLog_WriteHeader("Game info"); if (CafeSystem::IsTitleRunning()) { CrashLog_WriteLine("Game: ", false); CrashLog_WriteLine(CafeSystem::GetForegroundTitleName()); // title id CrashLog_WriteLine(fmt::format("TitleId: {:016x}", CafeSystem::GetForegroundTitleId())); // rpx hash sprintf(dumpLine, "RPXHash: %08x (Update: %08x)", CafeSystem::GetRPXHashBase(), CafeSystem::GetRPXHashUpdated()); CrashLog_WriteLine(dumpLine); } else { CrashLog_WriteLine("Not running"); } // info about active PPC instance: CrashLog_WriteLine(""); CrashLog_WriteHeader("Active PPC instance"); PPCInterpreter_t* hCPU = PPCInterpreter_getCurrentInstance(); if (hCPU) { OSThread_t* currentThread = coreinit::OSGetCurrentThread(); uint32 threadPtr = memory_getVirtualOffsetFromPointer(coreinit::OSGetCurrentThread()); sprintf(dumpLine, "IP 0x%08x LR 0x%08x Thread 0x%08x", hCPU->instructionPointer, hCPU->spr.LR, threadPtr); CrashLog_WriteLine(dumpLine); // GPR info CrashLog_WriteLine(""); auto gprs = hCPU->gpr; sprintf(dumpLine, "r0 =%08x r1 =%08x r2 =%08x r3 =%08x r4 =%08x r5 =%08x r6 =%08x r7 =%08x", gprs[0], gprs[1], gprs[2], gprs[3], gprs[4], gprs[5], gprs[6], gprs[7]); CrashLog_WriteLine(dumpLine); sprintf(dumpLine, "r8 =%08x r9 =%08x r10=%08x r11=%08x r12=%08x r13=%08x r14=%08x r15=%08x", gprs[8], gprs[9], gprs[10], gprs[11], gprs[12], gprs[13], gprs[14], gprs[15]); CrashLog_WriteLine(dumpLine); sprintf(dumpLine, "r16=%08x r17=%08x r18=%08x r19=%08x r20=%08x r21=%08x r22=%08x r23=%08x", gprs[16], gprs[17], gprs[18], gprs[19], gprs[20], gprs[21], gprs[22], gprs[23]); CrashLog_WriteLine(dumpLine); sprintf(dumpLine, "r24=%08x r25=%08x r26=%08x r27=%08x r28=%08x r29=%08x r30=%08x r31=%08x", gprs[24], gprs[25], gprs[26], gprs[27], gprs[28], gprs[29], gprs[30], gprs[31]); CrashLog_WriteLine(dumpLine); // stack trace MPTR currentStackVAddr = hCPU->gpr[1]; CrashLog_WriteLine(""); CrashLog_WriteHeader("PPC stack trace"); DebugLogStackTrace(currentThread, currentStackVAddr, true); // stack dump CrashLog_WriteLine(""); CrashLog_WriteHeader("PPC stack dump"); for (uint32 i = 0; i < 16; i++) { MPTR lineAddr = currentStackVAddr + i * 8 * 4; if (memory_isAddressRangeAccessible(lineAddr, 8 * 4)) { sprintf(dumpLine, "[0x%08x] %08x %08x %08x %08x - %08x %08x %08x %08x", lineAddr, memory_readU32(lineAddr + 0), memory_readU32(lineAddr + 4), memory_readU32(lineAddr + 8), memory_readU32(lineAddr + 12), memory_readU32(lineAddr + 16), memory_readU32(lineAddr + 20), memory_readU32(lineAddr + 24), memory_readU32(lineAddr + 28)); CrashLog_WriteLine(dumpLine); } else { sprintf(dumpLine, "[0x%08x] ?", lineAddr); CrashLog_WriteLine(dumpLine); } } } else { CrashLog_WriteLine("Not active"); } // PPC thread log CrashLog_WriteLine(""); CrashLog_WriteHeader("PPC threads"); if (activeThreadCount == 0) { CrashLog_WriteLine("None active"); } for (sint32 i = 0; i < activeThreadCount; i++) { MPTR threadItrMPTR = activeThread[i]; OSThread_t* threadItrBE = (OSThread_t*)memory_getPointerFromVirtualOffset(threadItrMPTR); // get thread state OSThread_t::THREAD_STATE threadState = threadItrBE->state; const char* threadStateStr = "UNDEFINED"; if (threadItrBE->suspendCounter != 0) threadStateStr = "SUSPENDED"; else if (threadState == OSThread_t::THREAD_STATE::STATE_NONE) threadStateStr = "NONE"; else if (threadState == OSThread_t::THREAD_STATE::STATE_READY) threadStateStr = "READY"; else if (threadState == OSThread_t::THREAD_STATE::STATE_RUNNING) threadStateStr = "RUNNING"; else if (threadState == OSThread_t::THREAD_STATE::STATE_WAITING) threadStateStr = "WAITING"; else if (threadState == OSThread_t::THREAD_STATE::STATE_MORIBUND) threadStateStr = "MORIBUND"; // generate log line uint8 affinity = threadItrBE->attr; sint32 effectivePriority = threadItrBE->effectivePriority; const char* threadName = "NULL"; if (!threadItrBE->threadName.IsNull()) threadName = threadItrBE->threadName.GetPtr(); sprintf(dumpLine, "%08x Ent %08x IP %08x LR %08x %-9s Aff %d%d%d Pri %2d Name %s", threadItrMPTR, threadItrBE->entrypoint.GetMPTR(), threadItrBE->context.srr0, _swapEndianU32(threadItrBE->context.lr), threadStateStr, (affinity >> 0) & 1, (affinity >> 1) & 1, (affinity >> 2) & 1, effectivePriority, threadName); // write line to log CrashLog_WriteLine(dumpLine); } }
6,498
C++
.cpp
148
36.817568
343
0.637898
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,928
ExceptionHandler_posix.cpp
cemu-project_Cemu/src/Common/ExceptionHandler/ExceptionHandler_posix.cpp
#include <signal.h> #include <execinfo.h> #include <string.h> #include <string> #include "config/CemuConfig.h" #include "util/helpers/StringHelpers.h" #include "ExceptionHandler.h" #include "Cafe/HW/Espresso/Debugger/GDBStub.h" #include "Cafe/HW/Espresso/Debugger/GDBBreakpoints.h" #if BOOST_OS_LINUX #include "ELFSymbolTable.h" #endif #if BOOST_OS_LINUX void DemangleAndPrintBacktrace(char** backtrace, size_t size) { ELFSymbolTable symTable; for (char** i = backtrace; i < backtrace + size; i++) { std::string_view traceLine{*i}; // basic check to see if the backtrace line matches expected format size_t parenthesesOpen = traceLine.find_last_of('('); size_t parenthesesClose = traceLine.find_last_of(')'); size_t offsetPlus = traceLine.find_last_of('+'); if (!parenthesesOpen || !parenthesesClose || !offsetPlus || offsetPlus < parenthesesOpen || offsetPlus > parenthesesClose) { // fall back to default string CrashLog_WriteLine(traceLine); continue; } // attempt to resolve symbol from regular symbol table if missing from dynamic symbol table uint64 newOffset = -1; std::string_view symbolName = traceLine.substr(parenthesesOpen+1, offsetPlus-parenthesesOpen-1); if (symbolName.empty()) { uint64 symbolOffset = StringHelpers::ToInt64(traceLine.substr(offsetPlus+1,offsetPlus+1-parenthesesClose-1)); symbolName = symTable.OffsetToSymbol(symbolOffset, newOffset); } CrashLog_WriteLine(traceLine.substr(0, parenthesesOpen+1), false); CrashLog_WriteLine(boost::core::demangle(symbolName.empty() ? "" : symbolName.data()), false); // print relative or existing symbol offset. CrashLog_WriteLine("+", false); if (newOffset != -1) { CrashLog_WriteLine(fmt::format("0x{:x}", newOffset), false); CrashLog_WriteLine(traceLine.substr(parenthesesClose)); } else { CrashLog_WriteLine(traceLine.substr(offsetPlus+1)); } } } #endif // handle signals that would dump core, print stacktrace and then dump depending on config void handlerDumpingSignal(int sig, siginfo_t *info, void *context) { #if defined(ARCH_X86_64) && BOOST_OS_LINUX // Check for hardware breakpoints if (info->si_signo == SIGTRAP && info->si_code == TRAP_HWBKPT) { uint64 dr6 = _ReadDR6(); g_gdbstub->HandleAccessException(dr6); return; } #endif if(!CrashLog_Create()) return; // give up if crashlog was already created char* sigName = strsignal(sig); if (sigName) { printf("%s!\n", sigName); } else { // should never be the case printf("Unknown core dumping signal!\n"); } void* backtraceArray[128]; size_t size; // get void*'s for all entries on the stack size = backtrace(backtraceArray, 128); // replace the deepest entry with the actual crash address #if defined(ARCH_X86_64) && BOOST_OS_LINUX > 0 ucontext_t *uc = (ucontext_t *)context; backtraceArray[0] = (void *)uc->uc_mcontext.gregs[REG_RIP]; #endif CrashLog_WriteLine(fmt::format("Error: signal {}:", sig)); #if BOOST_OS_LINUX char** symbol_trace = backtrace_symbols(backtraceArray, size); if (symbol_trace) { DemangleAndPrintBacktrace(symbol_trace, size); free(symbol_trace); } else { CrashLog_WriteLine("Failed to read backtrace"); } #else backtrace_symbols_fd(backtraceArray, size, STDERR_FILENO); #endif std::cerr << fmt::format("\nStacktrace and additional info written to:") << std::endl; std::cerr << cemuLog_GetLogFilePath().generic_string() << std::endl; CrashLog_SetOutputChannels(false, true); ExceptionHandler_LogGeneralInfo(); CrashLog_SetOutputChannels(true, true); if (GetConfig().crash_dump == CrashDump::Enabled) { // reset signal handler to default and re-raise signal to dump core signal(sig, SIG_DFL); raise(sig); return; } // exit process ignoring all issues _Exit(1); } void handler_SIGINT(int sig) { /* * Received when pressing CTRL + C in a console * Ideally should be exiting cleanly after saving settings but currently * there's no clean exit pathway (at least on linux) and exiting the app * by any mean ends up with a SIGABRT from the standard library destroying * threads. */ _Exit(0); } void ExceptionHandler_Init() { struct sigaction action; action.sa_flags = 0; sigfillset(&action.sa_mask); // don't allow signals to be interrupted action.sa_handler = handler_SIGINT; sigaction(SIGINT, &action, nullptr); sigaction(SIGTERM, &action, nullptr); action.sa_flags = SA_SIGINFO; action.sa_handler = nullptr; action.sa_sigaction = handlerDumpingSignal; sigaction(SIGABRT, &action, nullptr); sigaction(SIGBUS, &action, nullptr); sigaction(SIGFPE, &action, nullptr); sigaction(SIGILL, &action, nullptr); sigaction(SIGIOT, &action, nullptr); sigaction(SIGQUIT, &action, nullptr); sigaction(SIGSEGV, &action, nullptr); sigaction(SIGSYS, &action, nullptr); sigaction(SIGTRAP, &action, nullptr); }
4,950
C++
.cpp
149
30.127517
112
0.726455
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,929
ELFSymbolTable.cpp
cemu-project_Cemu/src/Common/ExceptionHandler/ELFSymbolTable.cpp
#include "Common/ExceptionHandler/ELFSymbolTable.h" #include "Common/FileStream.h" #include <sys/mman.h> #include <fcntl.h> uint16 ELFSymbolTable::FindSection(int type, const std::string_view& name) { if (!shTable || !shStrTable) return 0; for (uint16 i = 0; i < header->e_shnum; ++i) { auto& entry = shTable[i]; if(entry.sh_type == type && std::string_view{&shStrTable[entry.sh_name]} == name) { return i; } } return 0; } void* ELFSymbolTable::SectionPointer(uint16 index) { return SectionPointer(shTable[index]); } void* ELFSymbolTable::SectionPointer(const Elf64_Shdr& section) { return (void*)(mappedExecutable + section.sh_offset); } ELFSymbolTable::ELFSymbolTable() { // create file handle int fd = open("/proc/self/exe", O_RDONLY); if (!fd) return; // retrieve file size. struct stat filestats; if (fstat(fd, &filestats)) { close(fd); return; } mappedExecutableSize = filestats.st_size; // attempt to map the file mappedExecutable = (uint8*)(mmap(nullptr, mappedExecutableSize, PROT_READ, MAP_PRIVATE, fd, 0)); close(fd); if (!mappedExecutable) return; // verify signature header = (Elf64_Ehdr*)(mappedExecutable); constexpr uint8 signature[] = {0x7f, 0x45, 0x4c, 0x46}; for (size_t i = 0; i < 4; ++i) { if (signature[i] != header->e_ident[i]) { return; } } shTable = (Elf64_Shdr*)(mappedExecutable + header->e_shoff); Elf64_Shdr& shStrn = shTable[header->e_shstrndx]; shStrTable = (char*)(mappedExecutable + shStrn.sh_offset); strTable = (char*)SectionPointer(FindSection(SHT_STRTAB, ".strtab")); Elf64_Shdr& symTabShdr = shTable[FindSection(SHT_SYMTAB, ".symtab")]; if (symTabShdr.sh_entsize == 0) return; symTableLen = symTabShdr.sh_size / symTabShdr.sh_entsize; symTable = (Elf64_Sym*)(SectionPointer(symTabShdr)); } ELFSymbolTable::~ELFSymbolTable() { if (mappedExecutable) munmap(mappedExecutable, mappedExecutableSize); } std::string_view ELFSymbolTable::OffsetToSymbol(uint64 ptr, uint64& fromStart) const { if(!symTable || !strTable) { fromStart = -1; return {}; } for (auto entry = symTable+1; entry < symTable+symTableLen; ++entry) { if (ELF64_ST_TYPE(entry->st_info) != STT_FUNC) continue; auto begin = entry->st_value; auto size = entry->st_size; if(ptr >= begin && ptr < begin+size) { fromStart = ptr-begin; return &strTable[entry->st_name]; } } fromStart = -1; return {}; }
2,414
C++
.cpp
92
23.956522
97
0.711188
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,930
platform.cpp
cemu-project_Cemu/src/Common/unix/platform.cpp
#include <cstdint> #include <ctime> uint32_t GetTickCount() { #if BOOST_OS_LINUX struct timespec ts; clock_gettime(CLOCK_MONOTONIC_RAW, &ts); return (1000 * ts.tv_sec + ts.tv_nsec / 1000000); #elif BOOST_OS_MACOS return clock_gettime_nsec_np(CLOCK_MONOTONIC_RAW) / 1000000; #endif }
288
C++
.cpp
12
22.583333
61
0.752727
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,931
FileStream_unix.cpp
cemu-project_Cemu/src/Common/unix/FileStream_unix.cpp
#include "Common/unix/FileStream_unix.h" #include <cstdarg> fs::path findPathCI(const fs::path& path) { if (fs::exists(path)) return path; fs::path fName = path.filename(); fs::path parentPath = path.parent_path(); if (!fs::exists(parentPath)) { auto CIParent = findPathCI(parentPath); if (fs::exists(CIParent)) return findPathCI(CIParent / fName); } std::error_code listErr; for (auto&& dirEntry : fs::directory_iterator(parentPath, listErr)) if (boost::iequals(dirEntry.path().filename().string(), fName.string())) return dirEntry; return parentPath / fName; } FileStream* FileStream::openFile(std::string_view path) { return openFile2(path, false); } FileStream* FileStream::openFile(const wchar_t* path, bool allowWrite) { return openFile2(path, allowWrite); } FileStream* FileStream::openFile2(const fs::path& path, bool allowWrite) { FileStream* fs = new FileStream(path, true, allowWrite); if (fs->m_isValid) return fs; delete fs; return nullptr; } FileStream* FileStream::createFile(const wchar_t* path) { return createFile2(path); } FileStream* FileStream::createFile(std::string_view path) { return createFile2(path); } FileStream* FileStream::createFile2(const fs::path& path) { FileStream* fs = new FileStream(path, false, false); if (fs->m_isValid) return fs; delete fs; return nullptr; } std::optional<std::vector<uint8>> FileStream::LoadIntoMemory(const fs::path& path) { FileStream* fs = openFile2(path); if (!fs) return std::nullopt; uint64 fileSize = fs->GetSize(); if (fileSize > 0xFFFFFFFFull) { delete fs; return std::nullopt; } std::optional<std::vector<uint8>> v(fileSize); if (fs->readData(v->data(), (uint32)fileSize) != (uint32)fileSize) { delete fs; return std::nullopt; } delete fs; return v; } void FileStream::SetPosition(uint64 pos) { cemu_assert(m_isValid); if (m_prevOperationWasWrite) m_fileStream.seekp((std::streampos)pos); else m_fileStream.seekg((std::streampos)pos); } uint64 FileStream::GetSize() { cemu_assert(m_isValid); auto currentPos = m_fileStream.tellg(); m_fileStream.seekg(0, std::ios::end); auto fileSize = m_fileStream.tellg(); m_fileStream.seekg(currentPos, std::ios::beg); uint64 fs = (uint64)fileSize; return fs; } bool FileStream::SetEndOfFile() { assert_dbg(); return true; //return ::SetEndOfFile(m_hFile) != 0; } void FileStream::extract(std::vector<uint8>& data) { uint64 fileSize = GetSize(); SetPosition(0); data.resize(fileSize); readData(data.data(), fileSize); } uint32 FileStream::readData(void* data, uint32 length) { SyncReadWriteSeek(false); m_fileStream.read((char*)data, length); size_t bytesRead = m_fileStream.gcount(); return (uint32)bytesRead; } bool FileStream::readU64(uint64& v) { return readData(&v, sizeof(uint64)) == sizeof(uint64); } bool FileStream::readU32(uint32& v) { return readData(&v, sizeof(uint32)) == sizeof(uint32); } bool FileStream::readU8(uint8& v) { return readData(&v, sizeof(uint8)) == sizeof(uint8); } bool FileStream::readLine(std::string& line) { line.clear(); uint8 c; bool isEOF = true; while (readU8(c)) { isEOF = false; if (c == '\r') continue; if (c == '\n') break; line.push_back((char)c); } return !isEOF; } sint32 FileStream::writeData(const void* data, sint32 length) { SyncReadWriteSeek(true); m_fileStream.write((const char*)data, length); return length; } void FileStream::writeU64(uint64 v) { writeData(&v, sizeof(uint64)); } void FileStream::writeU32(uint32 v) { writeData(&v, sizeof(uint32)); } void FileStream::writeU8(uint8 v) { writeData(&v, sizeof(uint8)); } void FileStream::writeStringFmt(const char* format, ...) { char buffer[2048]; va_list args; va_start(args, format); vsnprintf(buffer, sizeof(buffer), format, args); writeData(buffer, (sint32)strlen(buffer)); } void FileStream::writeString(const char* str) { writeData(str, (sint32)strlen(str)); } void FileStream::writeLine(const char* str) { writeData(str, (sint32)strlen(str)); writeData("\r\n", 2); } FileStream::~FileStream() { if (m_isValid) { m_fileStream.close(); } // CloseHandle(m_hFile); } FileStream::FileStream(const fs::path& path, bool isOpen, bool isWriteable) { fs::path CIPath = findPathCI(path); if (isOpen) { m_fileStream.open(CIPath, isWriteable ? (std::ios_base::in | std::ios_base::out | std::ios_base::binary) : (std::ios_base::in | std::ios_base::binary)); m_isValid = m_fileStream.is_open(); } else { m_fileStream.open(CIPath, std::ios_base::in | std::ios_base::out | std::ios_base::binary | std::ios_base::trunc); m_isValid = m_fileStream.is_open(); } if(m_isValid && fs::is_directory(path)) { m_isValid = false; m_fileStream.close(); } } void FileStream::SyncReadWriteSeek(bool nextOpIsWrite) { // nextOpIsWrite == false -> read. Otherwise write if (nextOpIsWrite == m_prevOperationWasWrite) return; if (nextOpIsWrite) m_fileStream.seekp(m_fileStream.tellg(), std::ios::beg); else m_fileStream.seekg(m_fileStream.tellp(), std::ios::beg); m_prevOperationWasWrite = nextOpIsWrite; }
5,079
C++
.cpp
210
22.271429
154
0.728607
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,932
platform.cpp
cemu-project_Cemu/src/Common/windows/platform.cpp
#include <Windows.h> SlimRWLock::SlimRWLock() { static_assert(sizeof(m_lock) == sizeof(SRWLOCK)); RTL_SRWLOCK* srwLock = (RTL_SRWLOCK*)&m_lock; *srwLock = SRWLOCK_INIT; //m_lock = { SRWLOCK_INIT }; } void SlimRWLock::LockRead() { AcquireSRWLockShared((SRWLOCK*)&m_lock); } void SlimRWLock::UnlockRead() { ReleaseSRWLockShared((SRWLOCK*)&m_lock); } void SlimRWLock::LockWrite() { AcquireSRWLockExclusive((SRWLOCK*)&m_lock); } void SlimRWLock::UnlockWrite() { ReleaseSRWLockExclusive((SRWLOCK*)&m_lock); } uint32_t GetExceptionError() { return (uint32_t)GetLastError(); }
584
C++
.cpp
28
19.357143
50
0.751361
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,933
FileStream_win32.cpp
cemu-project_Cemu/src/Common/windows/FileStream_win32.cpp
#include "Common/windows/FileStream_win32.h" FileStream* FileStream::openFile(std::string_view path) { HANDLE hFile = CreateFileW(boost::nowide::widen(path.data(), path.size()).c_str(), FILE_GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0); if (hFile == INVALID_HANDLE_VALUE) return nullptr; return new FileStream(hFile); } FileStream* FileStream::openFile(const wchar_t* path, bool allowWrite) { HANDLE hFile = CreateFileW(path, allowWrite ? (FILE_GENERIC_READ | FILE_GENERIC_WRITE) : FILE_GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0); if (hFile == INVALID_HANDLE_VALUE) return nullptr; return new FileStream(hFile); } FileStream* FileStream::openFile2(const fs::path& path, bool allowWrite) { return openFile(path.generic_wstring().c_str(), allowWrite); } FileStream* FileStream::createFile(const wchar_t* path) { HANDLE hFile = CreateFileW(path, FILE_GENERIC_READ | FILE_GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, 0); if (hFile == INVALID_HANDLE_VALUE) return nullptr; return new FileStream(hFile); } FileStream* FileStream::createFile(std::string_view path) { auto w = boost::nowide::widen(path.data(), path.size()); HANDLE hFile = CreateFileW(w.c_str(), FILE_GENERIC_READ | FILE_GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, 0); if (hFile == INVALID_HANDLE_VALUE) return nullptr; return new FileStream(hFile); } FileStream* FileStream::createFile2(const fs::path& path) { return createFile(path.generic_wstring().c_str()); } std::optional<std::vector<uint8>> FileStream::LoadIntoMemory(const fs::path& path) { FileStream* fs = openFile2(path); if (!fs) return std::nullopt; uint64 fileSize = fs->GetSize(); if(fileSize > 0xFFFFFFFFull) { delete fs; return std::nullopt; } std::optional<std::vector<uint8>> v(fileSize); if (fs->readData(v->data(), (uint32)fileSize) != (uint32)fileSize) { delete fs; return std::nullopt; } delete fs; return v; } void FileStream::SetPosition(uint64 pos) { LONG posHigh = (LONG)(pos >> 32); LONG posLow = (LONG)(pos); SetFilePointer(m_hFile, posLow, &posHigh, FILE_BEGIN); } uint64 FileStream::GetSize() { DWORD fileSizeHigh = 0; DWORD fileSizeLow = 0; fileSizeLow = GetFileSize(m_hFile, &fileSizeHigh); return ((uint64)fileSizeHigh << 32) | (uint64)fileSizeLow; } bool FileStream::SetEndOfFile() { return ::SetEndOfFile(m_hFile) != 0; } void FileStream::extract(std::vector<uint8>& data) { DWORD fileSize = GetFileSize(m_hFile, nullptr); data.resize(fileSize); SetFilePointer(m_hFile, 0, 0, FILE_BEGIN); DWORD bt; ReadFile(m_hFile, data.data(), fileSize, &bt, nullptr); } uint32 FileStream::readData(void* data, uint32 length) { DWORD bytesRead = 0; ReadFile(m_hFile, data, length, &bytesRead, NULL); return bytesRead; } bool FileStream::readU64(uint64& v) { return readData(&v, sizeof(uint64)) == sizeof(uint64); } bool FileStream::readU32(uint32& v) { return readData(&v, sizeof(uint32)) == sizeof(uint32); } bool FileStream::readU8(uint8& v) { return readData(&v, sizeof(uint8)) == sizeof(uint8); } bool FileStream::readLine(std::string& line) { line.clear(); uint8 c; bool isEOF = true; while (readU8(c)) { isEOF = false; if(c == '\r') continue; if (c == '\n') break; line.push_back((char)c); } return !isEOF; } sint32 FileStream::writeData(const void* data, sint32 length) { DWORD bytesWritten = 0; WriteFile(m_hFile, data, length, &bytesWritten, NULL); return bytesWritten; } void FileStream::writeU64(uint64 v) { writeData(&v, sizeof(uint64)); } void FileStream::writeU32(uint32 v) { writeData(&v, sizeof(uint32)); } void FileStream::writeU8(uint8 v) { writeData(&v, sizeof(uint8)); } void FileStream::writeStringFmt(const char* format, ...) { char buffer[2048]; va_list args; va_start(args, format); vsnprintf(buffer, sizeof(buffer), format, args); writeData(buffer, (sint32)strlen(buffer)); } void FileStream::writeString(const char* str) { writeData(str, (sint32)strlen(str)); } void FileStream::writeLine(const char* str) { writeData(str, (sint32)strlen(str)); writeData("\r\n", 2); } FileStream::~FileStream() { if(m_isValid) CloseHandle(m_hFile); } FileStream::FileStream(HANDLE hFile) { m_hFile = hFile; m_isValid = true; }
4,325
C++
.cpp
162
24.901235
172
0.734171
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,934
ppcAssembler.cpp
cemu-project_Cemu/src/Cemu/PPCAssembler/ppcAssembler.cpp
#include "Cemu/PPCAssembler/ppcAssembler.h" #include "Cafe/HW/Espresso/PPCState.h" #include "Cafe/HW/Espresso/Interpreter/PPCInterpreterInternal.h" #include "Cemu/ExpressionParser/ExpressionParser.h" #include "util/helpers/helpers.h" #include <boost/container/small_vector.hpp> #include <boost/static_string/static_string.hpp> struct ppcAssemblerStr_t { ppcAssemblerStr_t(const char* start, const char* end) : str(start, end - start) {}; ppcAssemblerStr_t(const char* start, size_t len) : str(start, len) {}; std::string_view str; }; struct PPCAssemblerContext { PPCAssemblerInOut* ctx; boost::container::small_vector<ppcAssemblerStr_t, 8> listOperandStr; struct PPCInstructionDef* iDef; uint32 opcode; }; // table based assembler/disassembler #define operand0Bit (1<<0) #define operand1Bit (1<<1) #define operand2Bit (1<<2) #define operand3Bit (1<<3) #define operand4Bit (1<<4) #define OPC_NONE (0xFFFF) #define OPC_EXTENDED_BIT (0x8000) // use extended sub opcode enum { OP_FORM_UNUSED, OP_FORM_XL_CR, // CRXOR, CRAND etc. OP_FORM_OP3_A_CMP, OP_FORM_OP3_A_IMM, // rA, rS, rB is imm - has RC bit OP_FORM_BRANCH_S16, OP_FORM_BRANCH_S24, OP_FORM_OP2_D_HSIMM, // rD, signed imm shifted imm (high half) OP_FORM_RLWINM, OP_FORM_RLWINM_EXTENDED, // alternative mnemonics of rlwinm OP_FORM_RLWNM, OP_FORM_RLWNM_EXTENDED, // alternative mnemonics of rlwnm OP_FORM_CMP_SIMM, // cr, rD, r OP_FORM_NO_OPERAND, // FP OP_FORM_X_FP_CMP, // new generic form with operand encoding stored in the table entry, everything above is deprecated OP_FORM_DYNAMIC, }; const char* ppcAssembler_getInstructionName(uint32 ppcAsmOp) { switch (ppcAsmOp) { case PPCASM_OP_UKN: return "UKN"; case PPCASM_OP_ADDI: return "ADDI"; case PPCASM_OP_SUBI: return "SUBI"; case PPCASM_OP_ADDIS: return "ADDIS"; case PPCASM_OP_ADDIC: return "ADDIC"; case PPCASM_OP_ADDIC_: return "ADDIC."; case PPCASM_OP_ADD: return "ADD"; case PPCASM_OP_ADD_: return "ADD."; case PPCASM_OP_SUBF: return "SUBF"; case PPCASM_OP_SUBF_: return "SUBF."; case PPCASM_OP_SUBFC: return "SUBFC"; case PPCASM_OP_SUBFC_: return "SUBFC."; case PPCASM_OP_SUBFE: return "SUBFE"; case PPCASM_OP_SUBFE_: return "SUBFE."; case PPCASM_OP_SUBFIC: return "SUBFIC"; case PPCASM_OP_SUB: return "SUB"; case PPCASM_OP_SUB_: return "SUB."; case PPCASM_OP_MULLI: return "MULLI"; case PPCASM_OP_MULLW: return "MULLW"; case PPCASM_OP_MULLW_: return "MULLW."; case PPCASM_OP_MULHW: return "MULHW"; case PPCASM_OP_MULHW_: return "MULHW."; case PPCASM_OP_MULHWU: return "MULHWU"; case PPCASM_OP_MULHWU_: return "MULHWU."; case PPCASM_OP_DIVW: return "DIVW"; case PPCASM_OP_DIVW_: return "DIVW."; case PPCASM_OP_DIVWU: return "DIVWU"; case PPCASM_OP_DIVWU_: return "DIVWU."; case PPCASM_OP_AND: return "AND"; case PPCASM_OP_AND_: return "AND."; case PPCASM_OP_ANDC: return "ANDC"; case PPCASM_OP_ANDC_: return "ANDC."; case PPCASM_OP_ANDI_: return "ANDI."; case PPCASM_OP_ANDIS_: return "ANDIS."; case PPCASM_OP_OR: return "OR"; case PPCASM_OP_OR_: return "OR."; case PPCASM_OP_ORI: return "ORI"; case PPCASM_OP_ORIS: return "ORIS"; case PPCASM_OP_ORC: return "ORC"; case PPCASM_OP_XOR: return "XOR"; case PPCASM_OP_NOR: return "NOR"; case PPCASM_OP_NOR_: return "NOR."; case PPCASM_OP_NOT: return "NOT"; case PPCASM_OP_NOT_: return "NOT."; case PPCASM_OP_NEG: return "NEG"; case PPCASM_OP_NEG_: return "NEG."; case PPCASM_OP_XORI: return "XORI"; case PPCASM_OP_XORIS: return "XORIS"; case PPCASM_OP_SRAW: return "SRAW"; case PPCASM_OP_SRAW_: return "SRAW."; case PPCASM_OP_SRAWI: return "SRAWI"; case PPCASM_OP_SRAWI_: return "SRAWI."; case PPCASM_OP_SLW: return "SLW"; case PPCASM_OP_SLW_: return "SLW."; case PPCASM_OP_SRW: return "SRW"; case PPCASM_OP_SRW_: return "SRW."; case PPCASM_OP_RLWINM: return "RLWINM"; case PPCASM_OP_RLWINM_: return "RLWINM."; case PPCASM_OP_RLWIMI: return "RLWIMI"; case PPCASM_OP_RLWIMI_: return "RLWIMI."; case PPCASM_OP_EXTLWI: return "EXTLWI"; case PPCASM_OP_EXTLWI_: return "EXTLWI."; case PPCASM_OP_EXTRWI: return "EXTRWI"; case PPCASM_OP_EXTRWI_: return "EXTRWI."; case PPCASM_OP_ROTLWI: return "ROTLWI"; case PPCASM_OP_ROTLWI_: return "ROTLWI."; case PPCASM_OP_ROTRWI: return "ROTRWI"; case PPCASM_OP_ROTRWI_: return "ROTRWI."; case PPCASM_OP_SLWI: return "SLWI"; case PPCASM_OP_SLWI_: return "SLWI."; case PPCASM_OP_SRWI: return "SRWI"; case PPCASM_OP_SRWI_: return "SRWI."; case PPCASM_OP_CLRLWI: return "CLRLWI"; case PPCASM_OP_CLRLWI_: return "CLRLWI."; case PPCASM_OP_CLRRWI: return "CLRRWI"; case PPCASM_OP_CLRRWI_: return "CLRRWI."; case PPCASM_OP_RLWNM: return "RLWNM"; case PPCASM_OP_RLWNM_: return "RLWNM."; case PPCASM_OP_ROTLW: return "ROTLW"; case PPCASM_OP_ROTLW_: return "ROTLW."; case PPCASM_OP_CMPWI: return "CMPWI"; case PPCASM_OP_CMPLWI: return "CMPLWI"; case PPCASM_OP_CMPW: return "CMPW"; case PPCASM_OP_CMPLW: return "CMPLW"; case PPCASM_OP_MR: return "MR"; case PPCASM_OP_MR_: return "MR."; case PPCASM_OP_EXTSB: return "EXTSB"; case PPCASM_OP_EXTSH: return "EXTSH"; case PPCASM_OP_CNTLZW: return "CNTLZW"; case PPCASM_OP_EXTSB_: return "EXTSB."; case PPCASM_OP_EXTSH_: return "EXTSH."; case PPCASM_OP_CNTLZW_: return "CNTLZW."; case PPCASM_OP_MFSPR: return "MFSPR"; case PPCASM_OP_MTSPR: return "MTSPR"; case PPCASM_OP_LMW: return "LMW"; case PPCASM_OP_LWZ: return "LWZ"; case PPCASM_OP_LWZU: return "LWZU"; case PPCASM_OP_LWZX: return "LWZX"; case PPCASM_OP_LWZUX: return "LWZUX"; case PPCASM_OP_LHZ: return "LHZ"; case PPCASM_OP_LHZU: return "LHZU"; case PPCASM_OP_LHZX: return "LHZX"; case PPCASM_OP_LHZUX: return "LHZUX"; case PPCASM_OP_LHA: return "LHA"; case PPCASM_OP_LHAU: return "LHAU"; case PPCASM_OP_LHAX: return "LHAX"; case PPCASM_OP_LHAUX: return "LHAUX"; case PPCASM_OP_LBZ: return "LBZ"; case PPCASM_OP_LBZU: return "LBZU"; case PPCASM_OP_LBZX: return "LBZX"; case PPCASM_OP_LBZUX: return "LBZUX"; case PPCASM_OP_STMW: return "STMW"; case PPCASM_OP_STW: return "STW"; case PPCASM_OP_STWU: return "STWU"; case PPCASM_OP_STWX: return "STWX"; case PPCASM_OP_STWUX: return "STWUX"; case PPCASM_OP_STH: return "STH"; case PPCASM_OP_STHU: return "STHU"; case PPCASM_OP_STHX: return "STHX"; case PPCASM_OP_STHUX: return "STHUX"; case PPCASM_OP_STB: return "STB"; case PPCASM_OP_STBU: return "STBU"; case PPCASM_OP_STBX: return "STBX"; case PPCASM_OP_STBUX: return "STBUX"; case PPCASM_OP_STSWI: return "STSWI"; case PPCASM_OP_STWBRX: return "STWBRX"; case PPCASM_OP_STHBRX: return "STHBRX"; case PPCASM_OP_LWARX: return "LWARX"; case PPCASM_OP_STWCX_: return "STWCX."; case PPCASM_OP_B: return "B"; case PPCASM_OP_BL: return "BL"; case PPCASM_OP_BA: return "BA"; case PPCASM_OP_BLA: return "BLA"; case PPCASM_OP_BC: return "BC"; case PPCASM_OP_BNE: return "BNE"; case PPCASM_OP_BEQ: return "BEQ"; case PPCASM_OP_BGE: return "BGE"; case PPCASM_OP_BGT: return "BGT"; case PPCASM_OP_BLT: return "BLT"; case PPCASM_OP_BLE: return "BLE"; case PPCASM_OP_BDZ: return "BDZ"; case PPCASM_OP_BDNZ: return "BDNZ"; case PPCASM_OP_BLR: return "BLR"; case PPCASM_OP_BLTLR: return "BLTLR"; case PPCASM_OP_BLELR: return "BLELR"; case PPCASM_OP_BEQLR: return "BEQLR"; case PPCASM_OP_BGELR: return "BGELR"; case PPCASM_OP_BGTLR: return "BGTLR"; case PPCASM_OP_BNELR: return "BNELR"; case PPCASM_OP_BCTR: return "BCTR"; case PPCASM_OP_BCTRL: return "BCTRL"; case PPCASM_OP_LFS: return "LFS"; case PPCASM_OP_LFSU: return "LFSU"; case PPCASM_OP_LFSX: return "LFSX"; case PPCASM_OP_LFSUX: return "LFSUX"; case PPCASM_OP_LFD: return "LFD"; case PPCASM_OP_LFDU: return "LFDU"; case PPCASM_OP_LFDX: return "LFDX"; case PPCASM_OP_LFDUX: return "LFDUX"; case PPCASM_OP_STFS: return "STFS"; case PPCASM_OP_STFSU: return "STFSU"; case PPCASM_OP_STFSX: return "STFSX"; case PPCASM_OP_STFSUX: return "STFSUX"; case PPCASM_OP_STFD: return "STFD"; case PPCASM_OP_STFDU: return "STFDU"; case PPCASM_OP_STFDX: return "STFDX"; case PPCASM_OP_STFDUX: return "STFDUX"; case PPCASM_OP_STFIWX: return "STFIWX"; case PPCASM_OP_PS_MERGE00: return "PS_MERGE00"; case PPCASM_OP_PS_MERGE01: return "PS_MERGE01"; case PPCASM_OP_PS_MERGE10: return "PS_MERGE10"; case PPCASM_OP_PS_MERGE11: return "PS_MERGE11"; case PPCASM_OP_PS_ADD: return "PS_ADD"; case PPCASM_OP_PS_SUB: return "PS_SUB"; case PPCASM_OP_PS_DIV: return "PS_DIV"; case PPCASM_OP_PS_MUL: return "PS_MUL"; case PPCASM_OP_PS_MADD: return "PS_MADD"; case PPCASM_OP_PS_MSUB: return "PS_MSUB"; case PPCASM_OP_PS_NMADD: return "PS_NMADD"; case PPCASM_OP_PS_NMSUB: return "PS_NMSUB"; case PPCASM_OP_FMR: return "FMR"; case PPCASM_OP_FNEG: return "FNEG"; case PPCASM_OP_FRSP: return "FRSP"; case PPCASM_OP_FRSQRTE: return "FRSQRTE"; case PPCASM_OP_FADD: return "FADD"; case PPCASM_OP_FADDS: return "FADDS"; case PPCASM_OP_FSUB: return "FSUB"; case PPCASM_OP_FSUBS: return "FSUBS"; case PPCASM_OP_FMUL: return "FMUL"; case PPCASM_OP_FMULS: return "FMULS"; case PPCASM_OP_FDIV: return "FDIV"; case PPCASM_OP_FDIVS: return "FDIVS"; case PPCASM_OP_FMADD: return "FMADD"; case PPCASM_OP_FMADDS: return "FMADDS"; case PPCASM_OP_FNMADD: return "FNMADD"; case PPCASM_OP_FNMADDS: return "FNMADDS"; case PPCASM_OP_FMSUB: return "FMSUB"; case PPCASM_OP_FMSUBS: return "FMSUBS"; case PPCASM_OP_FNMSUB: return "FNMSUB"; case PPCASM_OP_FNMSUBS: return "FNMSUBS"; case PPCASM_OP_FCTIWZ: return "FCTIWZ"; case PPCASM_OP_FCMPU: return "FCMPU"; case PPCASM_OP_FCMPO: return "FCMPO"; case PPCASM_OP_ISYNC: return "ISYNC"; case PPCASM_OP_NOP: return "NOP"; case PPCASM_OP_LI: return "LI"; case PPCASM_OP_LIS: return "LIS"; case PPCASM_OP_MFLR: return "MFLR"; case PPCASM_OP_MTLR: return "MTLR"; case PPCASM_OP_MFCTR: return "MFCTR"; case PPCASM_OP_MTCTR: return "MTCTR"; case PPCASM_OP_CROR: return "CROR"; case PPCASM_OP_CRNOR: return "CRNOR"; case PPCASM_OP_CRORC: return "CRORC"; case PPCASM_OP_CRXOR: return "CRXOR"; case PPCASM_OP_CREQV: return "CREQV"; case PPCASM_OP_CRAND: return "CRAND"; case PPCASM_OP_CRNAND: return "CRNAND"; case PPCASM_OP_CRANDC: return "CRANDC"; case PPCASM_OP_CRSET: return "CRSET"; case PPCASM_OP_CRCLR: return "CRCLR"; case PPCASM_OP_CRMOVE: return "CRMOVE"; case PPCASM_OP_CRNOT: return "CRNOT"; default: return "UNDEF"; } return ""; } #define C_MASK_RC (PPC_OPC_RC) #define C_MASK_LK (PPC_OPC_LK) #define C_MASK_AA (PPC_OPC_AA) #define C_MASK_OE (1<<10) #define C_MASK_BO (0x1F<<21) #define C_MASK_BO_COND (0x1E<<21) // BO mask for true/false conditions. With hint bit excluded #define C_MASK_BI_CRBIT (0x3<<16) #define C_MASK_BI_CRIDX (0x7<<18) #define C_BIT_RC (PPC_OPC_RC) #define C_BIT_LK (PPC_OPC_LK) #define C_BIT_AA (PPC_OPC_AA) #define C_BIT_BO_FALSE (0x4<<21) // CR bit not set #define C_BIT_BO_TRUE (0xC<<21) // CR bit set #define C_BIT_BO_ALWAYS (0x14<<21) #define C_BIT_BO_DNZ (0x10<<21) #define C_BIT_BO_DZ (0x12<<21) #define C_BITS_BI_LT (0x0<<16) #define C_BITS_BI_GT (0x1<<16) #define C_BITS_BI_EQ (0x2<<16) #define C_BITS_BI_SO (0x3<<16) void ppcAssembler_setError(PPCAssemblerInOut* ctx, std::string_view errorMsg); bool ppcOp_extraCheck_extlwi(uint32 opcode) { sint32 rS, rA, SH, MB, ME; PPC_OPC_TEMPL_M(opcode, rS, rA, SH, MB, ME); return MB == 0; } bool ppcOp_extraCheck_extrwi(uint32 opcode) { sint32 rS, rA, SH, MB, ME; PPC_OPC_TEMPL_M(opcode, rS, rA, SH, MB, ME); if (ME != 31) return false; sint8 n = 32 - MB; sint8 b = SH - n; return b >= 0; } bool ppcOp_extraCheck_slwi(uint32 opcode) { sint32 rS, rA, SH, MB, ME; PPC_OPC_TEMPL_M(opcode, rS, rA, SH, MB, ME); return MB == 0 && SH == (31 - ME); } bool ppcOp_extraCheck_srwi(uint32 opcode) { sint32 rS, rA, SH, MB, ME; PPC_OPC_TEMPL_M(opcode, rS, rA, SH, MB, ME); return ME == 31 && (32 - SH) == MB; } bool ppcOp_extraCheck_clrlwi(uint32 opcode) { sint32 rS, rA, SH, MB, ME; PPC_OPC_TEMPL_M(opcode, rS, rA, SH, MB, ME); return SH == 0 && ME == 31; } bool ppcOp_extraCheck_clrrwi(uint32 opcode) { sint32 rS, rA, SH, MB, ME; PPC_OPC_TEMPL_M(opcode, rS, rA, SH, MB, ME); return SH == 0 && MB == 0; } bool ppcOp_extraCheck_rotlw(uint32 opcode) { sint32 rS, rA, SH, MB, ME; PPC_OPC_TEMPL_M(opcode, rS, rA, SH, MB, ME); return MB == 0 && ME == 31; } #define FLG_DEFAULT 0 #define FLG_SKIP_OP0 operand0Bit #define FLG_SKIP_OP1 operand1Bit #define FLG_SKIP_OP2 operand2Bit #define FLG_SKIP_OP3 operand3Bit #define FLG_SKIP_OP4 operand4Bit #define FLG_SWAP_OP0_OP1 (1<<6) // todo - maybe this should be implemented as a fully configurable matrix of indices instead of predefined constants? #define FLG_SWAP_OP1_OP2 (1<<7) #define FLG_SWAP_OP2_OP3 (1<<8) #define FLG_UNSIGNED_IMM (1<<10) // always consider immediate unsigned but still allow signed values when assembling class EncodedOperand_None { public: EncodedOperand_None() {} bool AssembleOperand(PPCAssemblerContext* assemblerCtx, PPCInstructionDef* iDef, uint32& opcode, size_t index) { if (index < assemblerCtx->listOperandStr.size() && !assemblerCtx->listOperandStr[index].str.empty()) { ppcAssembler_setError(assemblerCtx->ctx, "Too many operands"); return false; } return true; } void DisassembleOperand(PPCDisassembledInstruction* disInstr, PPCInstructionDef* iDef, const uint32 opcode, size_t index) { } }; static int _parseRegIndex(std::string_view sv, const char* prefix) { while (*prefix) { if (sv.empty()) return -1; char c = sv[0]; if (c >= 'A' && c <= 'Z') c -= ('A' - 'a'); if (c != *prefix) return -1; sv.remove_prefix(1); prefix++; } int r = 0; const std::from_chars_result result = std::from_chars(sv.data(), sv.data() + sv.size(), r); if (result.ec == std::errc::invalid_argument || result.ec == std::errc::result_out_of_range) return -1; if (result.ptr != sv.data() + sv.size()) return -1; return r; } template<bool TAllowEAZero = false> // if true, "r0" can be substituted with "0" class EncodedOperand_GPR { public: EncodedOperand_GPR(uint8 bitPos) : m_bitPos(bitPos) {} bool AssembleOperand(PPCAssemblerContext* assemblerCtx, PPCInstructionDef* iDef, uint32& opcode, size_t index) { if (index >= assemblerCtx->listOperandStr.size()) { ppcAssembler_setError(assemblerCtx->ctx, "Missing operand"); return false; } auto operandStr = assemblerCtx->listOperandStr[index].str; if constexpr (TAllowEAZero) { if (operandStr.size() == 1 && operandStr[0] == '0') { opcode &= ~((uint32)0x1F << m_bitPos); opcode |= ((uint32)0 << m_bitPos); return true; } } sint32 regIndex = _parseRegIndex(operandStr, "r"); if (regIndex < 0 || regIndex >= 32) { ppcAssembler_setError(assemblerCtx->ctx, fmt::format("Operand \"{}\" is not a valid GPR (expected r0 - r31)", assemblerCtx->listOperandStr[index].str)); return false; } opcode &= ~((uint32)0x1F << m_bitPos); opcode |= ((uint32)regIndex << m_bitPos); return true; } void DisassembleOperand(PPCDisassembledInstruction* disInstr, PPCInstructionDef* iDef, const uint32 opcode, size_t index) { uint32 regIndex = (opcode >> m_bitPos) & 0x1F; disInstr->operandMask |= (1 << index); disInstr->operand[index].type = PPCASM_OPERAND_TYPE_GPR; disInstr->operand[index].registerIndex = regIndex; } private: uint8 m_bitPos; }; class EncodedOperand_FPR { public: EncodedOperand_FPR(uint8 bitPos) : m_bitPos(bitPos) {} bool AssembleOperand(PPCAssemblerContext* assemblerCtx, PPCInstructionDef* iDef, uint32& opcode, size_t index) { if (index >= assemblerCtx->listOperandStr.size()) { ppcAssembler_setError(assemblerCtx->ctx, "Missing operand"); return false; } sint32 regIndex = _parseRegIndex(assemblerCtx->listOperandStr[index].str, "f"); if (regIndex < 0 || regIndex >= 32) { ppcAssembler_setError(assemblerCtx->ctx, fmt::format("Operand \"{}\" is not a valid FPR (expected f0 - f31)", assemblerCtx->listOperandStr[index].str)); return false; } opcode &= ~((uint32)0x1F << m_bitPos); opcode |= ((uint32)regIndex << m_bitPos); return true; } void DisassembleOperand(PPCDisassembledInstruction* disInstr, PPCInstructionDef* iDef, const uint32 opcode, size_t index) { uint32 regIndex = (opcode >> m_bitPos) & 0x1F; disInstr->operandMask |= (1<<index); disInstr->operand[index].type = PPCASM_OPERAND_TYPE_FPR; disInstr->operand[index].registerIndex = regIndex; } private: uint8 m_bitPos; }; class EncodedOperand_SPR { public: EncodedOperand_SPR() {} bool AssembleOperand(PPCAssemblerContext* assemblerCtx, PPCInstructionDef* iDef, uint32& opcode, size_t index) { if (index >= assemblerCtx->listOperandStr.size()) { ppcAssembler_setError(assemblerCtx->ctx, "Missing operand"); return false; } sint32 regIndex = _parseRegIndex(assemblerCtx->listOperandStr[index].str, "spr"); if (regIndex < 0 || regIndex >= 1024) { ppcAssembler_setError(assemblerCtx->ctx, fmt::format("Operand \"{}\" is not a valid GPR (expected spr0 - spr1023)", assemblerCtx->listOperandStr[index].str)); return false; } sint32 sprLow = (regIndex) & 0x1F; sint32 sprHigh = (regIndex>>5) & 0x1F; opcode &= ~((uint32)0x1F << 16); opcode |= ((uint32)sprLow << 16); opcode &= ~((uint32)0x1F << 11); opcode |= ((uint32)sprHigh << 11); return true; } void DisassembleOperand(PPCDisassembledInstruction* disInstr, PPCInstructionDef* iDef, const uint32 opcode, size_t index) { uint32 sprLow = (opcode >> 16) & 0x1F; uint32 sprHigh = (opcode >> 11) & 0x1F; disInstr->operandMask |= (1 << index); disInstr->operand[index].type = PPCASM_OPERAND_TYPE_SPR; disInstr->operand[index].registerIndex = sprLow | (sprHigh << 5); } }; class EncodedOperand_MemLoc { public: EncodedOperand_MemLoc() {} bool AssembleOperand(PPCAssemblerContext* assemblerCtx, PPCInstructionDef* iDef, uint32& opcode, size_t index) { if (index >= assemblerCtx->listOperandStr.size()) { ppcAssembler_setError(assemblerCtx->ctx, "Missing operand"); return false; } std::basic_string_view<char> svOpText(assemblerCtx->listOperandStr[index].str); // first we parse the memory register part at the end auto startPtr = svOpText.data(); auto endPtr = startPtr + svOpText.size(); // trim whitespaces while (endPtr > startPtr) { const char c = endPtr[-1]; if (c != ' ' && c != '\t') break; endPtr--; } if (endPtr == startPtr || endPtr[-1] != ')') { ppcAssembler_setError(assemblerCtx->ctx, fmt::format("\'{}\' does not end with valid memory register syntax. Memory operand must have the form offset(gpr). Example: 0x20(r3)", svOpText)); return false; } endPtr--; // find parenthesis open auto memoryRegEnd = endPtr; const char* memoryRegBegin = nullptr; while (endPtr > startPtr) { const char c = endPtr[-1]; if (c == '(') { memoryRegBegin = endPtr; endPtr--; // move end pointer beyond the parenthesis break; } endPtr--; } if (memoryRegBegin == nullptr) { ppcAssembler_setError(assemblerCtx->ctx, fmt::format("\'{}\' does not end with valid memory register syntax. Memory operand must have the form offset(gpr). Example: 0x20(r3)", svOpText)); return false; } std::string_view svExpressionPart(startPtr, endPtr - startPtr); std::string_view svRegPart(memoryRegBegin, memoryRegEnd - memoryRegBegin); sint32 memGpr = _parseRegIndex(svRegPart, "r"); //if (_ppcAssembler_parseRegister(svRegPart, "r", memGpr) == false || (memGpr < 0 || memGpr >= 32)) //{ // sprintf(_assemblerErrorMessageDepr, "\'%.*s\' is not a valid GPR", (int)(memoryRegEnd - memoryRegBegin), memoryRegBegin); // ppcAssembler_setError(internalCtx.ctx, _assemblerErrorMessageDepr); // return false; //} if (memGpr < 0 || memGpr >= 32) { ppcAssembler_setError(assemblerCtx->ctx, fmt::format("Memory operand register \"{}\" is not a valid GPR (expected r0 - r31)", svRegPart)); return false; } opcode &= ~(0x1F << 16); opcode |= (memGpr << 16); // parse expression ExpressionParser ep; double immD = 0.0f; try { if (ep.IsConstantExpression(svExpressionPart)) { immD = ep.Evaluate(svExpressionPart); sint32 imm = (sint32)immD; if (imm < -32768 || imm > 32767) { std::string msg = fmt::format("\"{}\" evaluates to offset out of range (Valid range is -32768 to 32767)", svExpressionPart); ppcAssembler_setError(assemblerCtx->ctx, msg); return false; } opcode &= ~0xFFFF; opcode |= ((uint32)imm & 0xFFFF); } else { assemblerCtx->ctx->list_relocs.emplace_back(PPCASM_RELOC::U32_MASKED_IMM, std::string(svExpressionPart), 0, 0, 16); return true; } } catch (std::exception* e) { std::string msg = fmt::format("\"{}\" could not be evaluated. Error: {}", svExpressionPart, e->what()); ppcAssembler_setError(assemblerCtx->ctx, msg); return false; } return true; } void DisassembleOperand(PPCDisassembledInstruction* disInstr, PPCInstructionDef* iDef, const uint32 opcode, size_t index) { uint32 imm = (opcode & 0xFFFF); if (imm & 0x8000) imm |= 0xFFFF0000; uint32 regIndex = (opcode >> 16) & 0x1F; disInstr->operandMask |= (1 << index); disInstr->operand[index].type = PPCASM_OPERAND_TYPE_MEM; disInstr->operand[index].registerIndex = regIndex; disInstr->operand[index].immS32 = (sint32)imm; disInstr->operand[index].immWidth = 16; disInstr->operand[index].isSignedImm = true; } }; bool _CanStoreInteger(uint32 value, uint32 numBits, bool isSigned) { if (isSigned) { sint32 storedValue = (sint32)value; storedValue <<= (32 - numBits); storedValue >>= (32 - numBits); return (uint32)storedValue == value; } // unsigned uint32 storedValue = value; storedValue <<= (32 - numBits); storedValue >>= (32 - numBits); return storedValue == value; } class EncodedOperand_IMM { public: EncodedOperand_IMM(uint8 bitPos, uint8 bits, bool isSigned, bool negate = false, bool extendedRange = false) : m_bitPos(bitPos), m_bits(bits), m_isSigned(isSigned), m_negate(negate), m_extendedRange(extendedRange) {} bool AssembleOperand(PPCAssemblerContext* assemblerCtx, PPCInstructionDef* iDef, uint32& opcode, size_t index) { if (index >= assemblerCtx->listOperandStr.size()) { ppcAssembler_setError(assemblerCtx->ctx, "Missing operand"); return false; } // parse expression std::string expressionString(assemblerCtx->listOperandStr[index].str); if (m_negate) { expressionString.insert(0, "0-("); expressionString.append(")"); } ExpressionParser ep; double immD = 0.0f; try { if (ep.IsConstantExpression(expressionString)) { immD = ep.Evaluate(expressionString); } else { assemblerCtx->ctx->list_relocs.emplace_back(PPCASM_RELOC::U32_MASKED_IMM, expressionString, 0, m_bitPos, m_bits); return true; } } catch (std::exception* e) { // check if expression is invalid or if it contains unknown constants std::string msg = fmt::format("\"{}\" could not be evaluated. Error: {}", expressionString.c_str(), e->what()); ppcAssembler_setError(assemblerCtx->ctx, msg); return false; } uint32 imm = (uint32)(sint32)immD; bool canStore = _CanStoreInteger(imm, m_bits, m_isSigned); if(!canStore && m_extendedRange) // always allow unsigned canStore = _CanStoreInteger(imm, m_bits, false); if (!canStore) { std::string msg = fmt::format("Value of operand \"{}\" is out of range", assemblerCtx->listOperandStr[index].str); ppcAssembler_setError(assemblerCtx->ctx, msg); return false; } uint32 mask = (1<<m_bits)-1; imm &= mask; opcode &= ~(mask << m_bitPos); opcode |= (imm << m_bitPos); return true; } void DisassembleOperand(PPCDisassembledInstruction* disInstr, PPCInstructionDef* iDef, const uint32 opcode, size_t index) { uint32 mask = (1 << m_bits) - 1; uint32 immValue = (opcode >> m_bitPos) & mask; if (m_isSigned) { sint32 tmpValue = (sint32)immValue; tmpValue <<= (32 - m_bits); tmpValue >>= (32 - m_bits); immValue = (uint32)tmpValue; } disInstr->operandMask |= (1 << index); disInstr->operand[index].type = PPCASM_OPERAND_TYPE_IMM; disInstr->operand[index].immS32 = immValue; disInstr->operand[index].immWidth = m_bits; disInstr->operand[index].isSignedImm = m_isSigned; } private: uint8 m_bitPos; uint8 m_bits; bool m_isSigned; bool m_negate; bool m_extendedRange; }; class EncodedOperand_U5Reverse { public: EncodedOperand_U5Reverse(uint8 bitPos, uint8 base) : m_bitPos(bitPos), m_base(base) {} bool AssembleOperand(PPCAssemblerContext* assemblerCtx, PPCInstructionDef* iDef, uint32& opcode, size_t index) { if (index >= assemblerCtx->listOperandStr.size()) { ppcAssembler_setError(assemblerCtx->ctx, "Missing operand"); return false; } // parse expression std::string expressionString(assemblerCtx->listOperandStr[index].str); expressionString.insert(0, fmt::format("{}-(", m_base)); expressionString.append(")"); ExpressionParser ep; double immD = 0.0f; try { if (ep.IsConstantExpression(expressionString)) { immD = ep.Evaluate(expressionString); } else { assemblerCtx->ctx->list_relocs.emplace_back(PPCASM_RELOC::U32_MASKED_IMM, expressionString, 0, m_bitPos, 5); return true; } } catch (std::exception* e) { // check if expression is invalid or if it contains unknown constants std::string msg = fmt::format("\"{}\" could not be evaluated. Error: {}", expressionString.c_str(), e->what()); ppcAssembler_setError(assemblerCtx->ctx, msg); return false; } uint32 imm = (uint32)(sint32)immD; bool canStore = _CanStoreInteger(imm, 5, false); if (!canStore) { std::string msg = fmt::format("Value of operand \"{}\" is out of range", assemblerCtx->listOperandStr[index].str); ppcAssembler_setError(assemblerCtx->ctx, msg); return false; } uint32 mask = (1 << 5) - 1; imm &= mask; opcode &= ~(mask << m_bitPos); opcode |= (imm << m_bitPos); return true; } void DisassembleOperand(PPCDisassembledInstruction* disInstr, PPCInstructionDef* iDef, const uint32 opcode, size_t index) { uint32 mask = (1 << 5) - 1; uint32 immValue = (opcode >> m_bitPos) & mask; immValue = m_base - immValue; disInstr->operandMask |= (1 << index); disInstr->operand[index].type = PPCASM_OPERAND_TYPE_IMM; disInstr->operand[index].immS32 = immValue; disInstr->operand[index].immWidth = 5; disInstr->operand[index].isSignedImm = false; } private: uint8 m_bitPos; uint8 m_base; }; class EncodedConstraint_None { public: EncodedConstraint_None() {} void AssembleConstraint(PPCAssemblerContext* assemblerCtx, PPCInstructionDef* iDef, uint32& opcode) { } bool DisassembleCheckConstraint(PPCDisassembledInstruction* disInstr, PPCInstructionDef* iDef, const uint32 opcode) { return true; } }; class EncodedConstraint_MirrorU5 { public: EncodedConstraint_MirrorU5(uint8 srcBitPos, uint8 dstBitPos) : m_srcBitPos(srcBitPos), m_dstBitPos(dstBitPos) {} void AssembleConstraint(PPCAssemblerContext* assemblerCtx, PPCInstructionDef* iDef, uint32& opcode) { uint32 regIndex = (opcode >> m_srcBitPos) & 0x1F; opcode &= ~((uint32)0x1F << m_dstBitPos); opcode |= ((uint32)regIndex << m_dstBitPos); } bool DisassembleCheckConstraint(PPCDisassembledInstruction* disInstr, PPCInstructionDef* iDef, const uint32 opcode) { uint32 regSrc = (opcode >> m_srcBitPos) & 0x1F; uint32 regDst = (opcode >> m_dstBitPos) & 0x1F; return regSrc == regDst; } private: const uint8 m_srcBitPos, m_dstBitPos; }; // same as _MirrorU5, but the destination must match invBase - src class EncodedConstraint_MirrorReverseU5 { public: EncodedConstraint_MirrorReverseU5(uint8 srcBitPos, uint8 dstBitPos, uint8 invBase) : m_srcBitPos(srcBitPos), m_dstBitPos(dstBitPos), m_invBase(invBase) {} void AssembleConstraint(PPCAssemblerContext* assemblerCtx, PPCInstructionDef* iDef, uint32& opcode) { uint32 regIndex = (opcode >> m_srcBitPos) & 0x1F; regIndex = m_invBase - regIndex; opcode &= ~((uint32)0x1F << m_dstBitPos); opcode |= ((uint32)regIndex << m_dstBitPos); } bool DisassembleCheckConstraint(PPCDisassembledInstruction* disInstr, PPCInstructionDef* iDef, const uint32 opcode) { uint32 regSrc = (opcode >> m_srcBitPos) & 0x1F; uint32 regDst = (opcode >> m_dstBitPos) & 0x1F; regSrc = m_invBase - regSrc; if (regSrc >= 32) return false; return regSrc == regDst; } private: const uint8 m_srcBitPos, m_dstBitPos, m_invBase; }; class EncodedConstraint_FixedU5 { public: EncodedConstraint_FixedU5(uint8 bitPos, uint8 expectedReg) : m_bitPos(bitPos), m_expectedReg(expectedReg) {} void AssembleConstraint(PPCAssemblerContext* assemblerCtx, PPCInstructionDef* iDef, uint32& opcode) { uint32 regIndex = m_expectedReg; opcode &= ~((uint32)0x1F << m_bitPos); opcode |= ((uint32)regIndex << m_bitPos); } bool DisassembleCheckConstraint(PPCDisassembledInstruction* disInstr, PPCInstructionDef* iDef, const uint32 opcode) { uint32 reg = (opcode >> m_bitPos) & 0x1F; return (uint8)reg == m_expectedReg; } private: const uint8 m_bitPos; const uint8 m_expectedReg; }; using EncodedConstraint_FixedRegister = EncodedConstraint_FixedU5; using EncodedConstraint_MirrorRegister = EncodedConstraint_MirrorU5; // checks bit value, but does not overwrite it on assemble class EncodedConstraint_CheckSignBit { public: EncodedConstraint_CheckSignBit(uint8 bitPos, uint8 expectedValue) : m_bitPos(bitPos), m_expectedValue(expectedValue) {} void AssembleConstraint(PPCAssemblerContext* assemblerCtx, PPCInstructionDef* iDef, uint32& opcode) { // dont overwrite the existing sign bit } bool DisassembleCheckConstraint(PPCDisassembledInstruction* disInstr, PPCInstructionDef* iDef, const uint32 opcode) { return ((opcode >> m_bitPos) & 1) == m_expectedValue; } private: const uint8 m_bitPos; const uint8 m_expectedValue; }; //class EncodedConstraint_ExpectBit //{ //public: // EncodedConstraint_ExpectBit(uint8 bitPos, bool val) : m_bitPos(bitPos), m_expectedValue(val ? 1 : 0) {} // // void AssembleConstraint(PPCAssemblerContext* assemblerCtx, PPCInstructionDef* iDef, uint32& opcode) // { // if (m_expectedValue) // opcode |= (1 << m_bitPos); // else // opcode &= ~(1 << m_bitPos); // } // // bool DisassembleCheckConstraint(PPCDisassembledInstruction* disInstr, PPCInstructionDef* iDef, const uint32 opcode) // { // return ((opcode >> m_bitPos) & 1) == m_expectedValue; // } // //private: // const uint8 m_bitPos; // const uint8 m_expectedValue; //}; class EncodedConstraint_FixedSPR { public: EncodedConstraint_FixedSPR(uint16 sprIndex) : m_sprIndex(sprIndex) {} void AssembleConstraint(PPCAssemblerContext* assemblerCtx, PPCInstructionDef* iDef, uint32& opcode) { sint32 sprLow = (m_sprIndex) & 0x1F; sint32 sprHigh = (m_sprIndex >> 5) & 0x1F; opcode &= ~((uint32)0x1F << 16); opcode |= ((uint32)sprLow << 16); opcode &= ~((uint32)0x1F << 11); opcode |= ((uint32)sprHigh << 11); } bool DisassembleCheckConstraint(PPCDisassembledInstruction* disInstr, PPCInstructionDef* iDef, const uint32 opcode) { uint32 sprLow = (opcode >> 16) & 0x1F; uint32 sprHigh = (opcode >> 11) & 0x1F; uint32 sprIndex = sprLow | (sprHigh << 5); return (uint16)sprIndex == m_sprIndex; } private: const uint16 m_sprIndex; }; struct PPCInstructionDef { uint16 ppcAsmOp; // instruction type identifier uint8 priority; uint16 opc0; uint16 opc1; uint16 opc2; uint8 instructionForm; // encoding uint16 flags; uint32 maskBits; uint32 compareBits; bool(*extraCheck)(uint32 opcode); // used for unique criteria (e.g. SRWI checks SH/mask) -> Replaced by constraints std::array<std::variant<EncodedOperand_None, EncodedOperand_GPR<false>, EncodedOperand_GPR<true>, EncodedOperand_FPR, EncodedOperand_SPR, EncodedOperand_IMM, EncodedOperand_U5Reverse, EncodedOperand_MemLoc>, 4> encodedOperands{}; // note: The default constructor of std::variant will default-construct the first type (which we want to be EncodedOperand_None) std::array<std::variant<EncodedConstraint_None, EncodedConstraint_MirrorRegister, EncodedConstraint_MirrorReverseU5, EncodedConstraint_FixedRegister, EncodedConstraint_FixedSPR, EncodedConstraint_CheckSignBit>, 3> constraints{}; }; PPCInstructionDef ppcInstructionTable[] = { {PPCASM_OP_PS_MERGE00, 0, 4, 16, 16, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(11)}}, {PPCASM_OP_PS_MERGE01, 0, 4, 16, 17, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(11)}}, {PPCASM_OP_PS_MERGE10, 0, 4, 16, 18, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(11)}}, {PPCASM_OP_PS_MERGE11, 0, 4, 16, 19, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(11)}}, {PPCASM_OP_PS_DIV, 0, 4, 18, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(11)}}, {PPCASM_OP_PS_SUB, 0, 4, 20, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(11)}}, {PPCASM_OP_PS_ADD, 0, 4, 21, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(11)}}, {PPCASM_OP_PS_MUL, 0, 4, 25, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(6)}}, {PPCASM_OP_PS_MSUB, 0, 4, 28, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(6), EncodedOperand_FPR(11)}}, {PPCASM_OP_PS_MADD, 0, 4, 29, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(6), EncodedOperand_FPR(11)}}, {PPCASM_OP_PS_NMSUB, 0, 4, 30, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(6), EncodedOperand_FPR(11)}}, {PPCASM_OP_PS_NMADD, 0, 4, 31, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(6), EncodedOperand_FPR(11)}}, {PPCASM_OP_MULLI, 0, 7, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_IMM(0, 16, true)}}, {PPCASM_OP_SUBFIC, 0, 8, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_IMM(0, 16, true)} }, {PPCASM_OP_CMPLWI, 0, 10, OPC_NONE, OPC_NONE, OP_FORM_CMP_SIMM, FLG_DEFAULT, 0, 0, nullptr}, {PPCASM_OP_CMPWI, 0, 11, OPC_NONE, OPC_NONE, OP_FORM_CMP_SIMM, FLG_DEFAULT, 0, 0, nullptr}, {PPCASM_OP_ADDIC, 0, 12, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_IMM(0, 16, true)}}, {PPCASM_OP_ADDIC_, 0, 13, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_IMM(0, 16, true)}}, {PPCASM_OP_ADDI, 0, 14, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_IMM(0, 16, true)}}, {PPCASM_OP_SUBI, 1, 14, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_IMM(0, 16, true, true)}, {EncodedConstraint_CheckSignBit(15, 1)}}, // special form of ADDI for negative immediate {PPCASM_OP_LI, 1, 14, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_IMM(0, 16, true, false, true)}, {EncodedConstraint_FixedRegister(16, 0)}}, {PPCASM_OP_ADDIS, 0, 15, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_IMM(0, 16, true, false, true)}}, {PPCASM_OP_LIS, 1, 15, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_IMM(0, 16, true, false, true)}, {EncodedConstraint_FixedRegister(16, 0)}}, {PPCASM_OP_BC, 0, 16, OPC_NONE, OPC_NONE, OP_FORM_BRANCH_S16, FLG_DEFAULT, 0, 0, nullptr}, {PPCASM_OP_BNE, 1, 16, OPC_NONE, OPC_NONE, OP_FORM_BRANCH_S16, FLG_DEFAULT, C_MASK_BO_COND | C_MASK_BI_CRBIT, C_BIT_BO_FALSE | C_BITS_BI_EQ, nullptr}, {PPCASM_OP_BEQ, 1, 16, OPC_NONE, OPC_NONE, OP_FORM_BRANCH_S16, FLG_DEFAULT, C_MASK_BO_COND | C_MASK_BI_CRBIT, C_BIT_BO_TRUE | C_BITS_BI_EQ, nullptr}, {PPCASM_OP_BGE, 1, 16, OPC_NONE, OPC_NONE, OP_FORM_BRANCH_S16, FLG_DEFAULT, C_MASK_BO_COND | C_MASK_BI_CRBIT, C_BIT_BO_FALSE | C_BITS_BI_LT, nullptr}, {PPCASM_OP_BGT, 1, 16, OPC_NONE, OPC_NONE, OP_FORM_BRANCH_S16, FLG_DEFAULT, C_MASK_BO_COND | C_MASK_BI_CRBIT, C_BIT_BO_TRUE | C_BITS_BI_GT, nullptr}, {PPCASM_OP_BLT, 1, 16, OPC_NONE, OPC_NONE, OP_FORM_BRANCH_S16, FLG_DEFAULT, C_MASK_BO_COND | C_MASK_BI_CRBIT, C_BIT_BO_TRUE | C_BITS_BI_LT, nullptr}, {PPCASM_OP_BLE, 1, 16, OPC_NONE, OPC_NONE, OP_FORM_BRANCH_S16, FLG_DEFAULT, C_MASK_BO_COND | C_MASK_BI_CRBIT, C_BIT_BO_FALSE | C_BITS_BI_GT, nullptr}, {PPCASM_OP_BDZ, 1, 16, OPC_NONE, OPC_NONE, OP_FORM_BRANCH_S16, FLG_DEFAULT, C_MASK_BO, C_BIT_BO_DZ, nullptr}, {PPCASM_OP_BDNZ, 1, 16, OPC_NONE, OPC_NONE, OP_FORM_BRANCH_S16, FLG_DEFAULT, C_MASK_BO, C_BIT_BO_DNZ, nullptr}, {PPCASM_OP_B, 0, 18, OPC_NONE, OPC_NONE, OP_FORM_BRANCH_S24, FLG_DEFAULT, C_MASK_LK | C_MASK_AA, 0, nullptr}, {PPCASM_OP_BL, 0, 18, OPC_NONE, OPC_NONE, OP_FORM_BRANCH_S24, FLG_DEFAULT, C_MASK_LK | C_MASK_AA, C_BIT_LK, nullptr}, {PPCASM_OP_BA, 0, 18, OPC_NONE, OPC_NONE, OP_FORM_BRANCH_S24, FLG_DEFAULT, C_MASK_LK | C_MASK_AA, C_BIT_AA, nullptr}, {PPCASM_OP_BLA, 0, 18, OPC_NONE, OPC_NONE, OP_FORM_BRANCH_S24, FLG_DEFAULT, C_MASK_LK | C_MASK_AA, C_BIT_LK|C_BIT_AA, nullptr}, {PPCASM_OP_BLR, 0, 19, 16, OPC_NONE, OP_FORM_NO_OPERAND, FLG_DEFAULT, C_MASK_BO | C_MASK_LK, C_BIT_BO_ALWAYS, nullptr}, {PPCASM_OP_BLTLR, 0, 19, 16, OPC_NONE, OP_FORM_NO_OPERAND, FLG_DEFAULT, C_MASK_BO | C_MASK_BI_CRBIT | C_MASK_LK, C_BIT_BO_TRUE | C_BITS_BI_LT, nullptr}, // less {PPCASM_OP_BGTLR, 0, 19, 16, OPC_NONE, OP_FORM_NO_OPERAND, FLG_DEFAULT, C_MASK_BO | C_MASK_BI_CRBIT | C_MASK_LK, C_BIT_BO_TRUE | C_BITS_BI_GT, nullptr}, // greater {PPCASM_OP_BEQLR, 0, 19, 16, OPC_NONE, OP_FORM_NO_OPERAND, FLG_DEFAULT, C_MASK_BO | C_MASK_BI_CRBIT | C_MASK_LK, C_BIT_BO_TRUE | C_BITS_BI_EQ, nullptr}, // equal {PPCASM_OP_BLELR, 0, 19, 16, OPC_NONE, OP_FORM_NO_OPERAND, FLG_DEFAULT, C_MASK_BO | C_MASK_BI_CRBIT | C_MASK_LK, C_BIT_BO_FALSE | C_BITS_BI_GT, nullptr}, // less or equal (not greater) {PPCASM_OP_BGELR, 0, 19, 16, OPC_NONE, OP_FORM_NO_OPERAND, FLG_DEFAULT, C_MASK_BO | C_MASK_BI_CRBIT | C_MASK_LK, C_BIT_BO_FALSE | C_BITS_BI_LT, nullptr}, // greater or equal (not less) {PPCASM_OP_BNELR, 0, 19, 16, OPC_NONE, OP_FORM_NO_OPERAND, FLG_DEFAULT, C_MASK_BO | C_MASK_BI_CRBIT | C_MASK_LK, C_BIT_BO_FALSE | C_BITS_BI_EQ, nullptr}, // not equal {PPCASM_OP_ISYNC, 0, 19, 150, OPC_NONE, OP_FORM_NO_OPERAND, FLG_DEFAULT, 0, 0, nullptr}, {PPCASM_OP_CRNOR, 0, 19, 33, OPC_NONE, OP_FORM_XL_CR, FLG_DEFAULT, 0, 0, nullptr}, {PPCASM_OP_CRANDC, 0, 19, 129, OPC_NONE, OP_FORM_XL_CR, FLG_DEFAULT, 0, 0, nullptr}, {PPCASM_OP_CRXOR, 0, 19, 193, OPC_NONE, OP_FORM_XL_CR, FLG_DEFAULT, 0, 0, nullptr}, {PPCASM_OP_CRNAND, 0, 19, 255, OPC_NONE, OP_FORM_XL_CR, FLG_DEFAULT, 0, 0, nullptr}, {PPCASM_OP_CRAND, 0, 19, 257, OPC_NONE, OP_FORM_XL_CR, FLG_DEFAULT, 0, 0, nullptr}, {PPCASM_OP_CREQV, 0, 19, 289, OPC_NONE, OP_FORM_XL_CR, FLG_DEFAULT, 0, 0, nullptr}, {PPCASM_OP_CRORC, 0, 19, 417, OPC_NONE, OP_FORM_XL_CR, FLG_DEFAULT, 0, 0, nullptr}, {PPCASM_OP_CROR, 0, 19, 449, OPC_NONE, OP_FORM_XL_CR, FLG_DEFAULT, 0, 0, nullptr}, {PPCASM_OP_BCTR, 0, 19, 528, OPC_NONE, OP_FORM_NO_OPERAND, FLG_DEFAULT, C_MASK_BO | C_MASK_LK, C_BIT_BO_ALWAYS, nullptr}, {PPCASM_OP_BCTRL, 0, 19, 528, OPC_NONE, OP_FORM_NO_OPERAND, FLG_DEFAULT, C_MASK_BO | C_MASK_LK, C_BIT_BO_ALWAYS | C_BIT_LK, nullptr}, {PPCASM_OP_RLWIMI, 0, 20, OPC_NONE, OPC_NONE, OP_FORM_RLWINM, FLG_DEFAULT, C_MASK_RC, 0, nullptr}, {PPCASM_OP_RLWIMI_, 0, 20, OPC_NONE, OPC_NONE, OP_FORM_RLWINM, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr}, {PPCASM_OP_RLWINM, 0, 21, OPC_NONE, OPC_NONE, OP_FORM_RLWINM, FLG_DEFAULT, C_MASK_RC, 0, nullptr}, {PPCASM_OP_RLWINM_, 0, 21, OPC_NONE, OPC_NONE, OP_FORM_RLWINM, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr}, {PPCASM_OP_ROTLWI, 2, 21, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_IMM(11, 5, false)}, {EncodedConstraint_FixedU5(6, 0), EncodedConstraint_FixedU5(1, 31)}}, {PPCASM_OP_ROTLWI_, 2, 21, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_IMM(11, 5, false)}, {EncodedConstraint_FixedU5(6, 0), EncodedConstraint_FixedU5(1, 31)}}, // rotrwi RA, RS, n -> rlwinm RA, RS, 32-n, 0, 31 // only assembler {PPCASM_OP_ROTRWI, 0, 21, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_U5Reverse(11, 32)}, {EncodedConstraint_FixedU5(6, 0), EncodedConstraint_FixedU5(1, 31)}}, {PPCASM_OP_ROTRWI_, 0, 21, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_U5Reverse(11, 32)}, {EncodedConstraint_FixedU5(6, 0), EncodedConstraint_FixedU5(1, 31)}}, {PPCASM_OP_EXTLWI, 1, 21, OPC_NONE, OPC_NONE, OP_FORM_RLWINM_EXTENDED, FLG_DEFAULT, C_MASK_RC, 0, ppcOp_extraCheck_extlwi}, {PPCASM_OP_EXTLWI_, 1, 21, OPC_NONE, OPC_NONE, OP_FORM_RLWINM_EXTENDED, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, ppcOp_extraCheck_extlwi}, {PPCASM_OP_EXTRWI, 1, 21, OPC_NONE, OPC_NONE, OP_FORM_RLWINM_EXTENDED, FLG_DEFAULT, C_MASK_RC, 0, ppcOp_extraCheck_extrwi}, {PPCASM_OP_EXTRWI_, 1, 21, OPC_NONE, OPC_NONE, OP_FORM_RLWINM_EXTENDED, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, ppcOp_extraCheck_extrwi}, {PPCASM_OP_SLWI, 2, 21, OPC_NONE, OPC_NONE, OP_FORM_RLWINM_EXTENDED, FLG_DEFAULT, C_MASK_RC, 0, ppcOp_extraCheck_slwi}, {PPCASM_OP_SLWI_, 2, 21, OPC_NONE, OPC_NONE, OP_FORM_RLWINM_EXTENDED, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, ppcOp_extraCheck_slwi}, {PPCASM_OP_SRWI, 2, 21, OPC_NONE, OPC_NONE, OP_FORM_RLWINM_EXTENDED, FLG_DEFAULT, C_MASK_RC, 0, ppcOp_extraCheck_srwi}, {PPCASM_OP_SRWI_, 2, 21, OPC_NONE, OPC_NONE, OP_FORM_RLWINM_EXTENDED, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, ppcOp_extraCheck_srwi}, {PPCASM_OP_CLRLWI, 2, 21, OPC_NONE, OPC_NONE, OP_FORM_RLWINM_EXTENDED, FLG_DEFAULT, C_MASK_RC, 0, ppcOp_extraCheck_clrlwi}, {PPCASM_OP_CLRLWI_, 2, 21, OPC_NONE, OPC_NONE, OP_FORM_RLWINM_EXTENDED, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, ppcOp_extraCheck_clrlwi}, {PPCASM_OP_CLRRWI, 2, 21, OPC_NONE, OPC_NONE, OP_FORM_RLWINM_EXTENDED, FLG_DEFAULT, C_MASK_RC, 0, ppcOp_extraCheck_clrrwi}, {PPCASM_OP_CLRRWI_, 2, 21, OPC_NONE, OPC_NONE, OP_FORM_RLWINM_EXTENDED, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, ppcOp_extraCheck_clrrwi}, {PPCASM_OP_RLWNM, 0, 23, OPC_NONE, OPC_NONE, OP_FORM_RLWNM, FLG_DEFAULT, C_MASK_RC, 0, nullptr}, {PPCASM_OP_RLWNM_, 0, 23, OPC_NONE, OPC_NONE, OP_FORM_RLWNM, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr}, {PPCASM_OP_ROTLW, 0, 23, OPC_NONE, OPC_NONE, OP_FORM_RLWNM_EXTENDED, FLG_DEFAULT, C_MASK_RC, 0, ppcOp_extraCheck_rotlw}, {PPCASM_OP_ROTLW_, 0, 23, OPC_NONE, OPC_NONE, OP_FORM_RLWNM_EXTENDED, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, ppcOp_extraCheck_rotlw}, {PPCASM_OP_ORI, 0, 24, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_IMM(0, 16, false)}}, {PPCASM_OP_NOP, 1, 24, OPC_NONE, OPC_NONE, OP_FORM_NO_OPERAND, FLG_DEFAULT, 0x3FFFFFF, 0, nullptr}, // ORI r0, r0, 0 -> NOP {PPCASM_OP_ORIS, 0, 25, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_IMM(0, 16, true, false, true)}}, {PPCASM_OP_XORI, 0, 26, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_IMM(0, 16, false)} }, {PPCASM_OP_XORIS, 0, 27, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_IMM(0, 16, true, false, true)} }, {PPCASM_OP_ANDI_, 0, 28, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_IMM(0, 16, false)} }, {PPCASM_OP_ANDIS_, 0, 29, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_IMM(0, 16, true, false, true)} }, // group 31 {PPCASM_OP_CMPW, 0, 31, 0, OPC_NONE, OP_FORM_OP3_A_CMP, FLG_DEFAULT, 0, 0, nullptr}, {PPCASM_OP_SUBFC, 1, 31, 8, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_SUBFC_, 1, 31, 8, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_MULHWU, 0, 31, 11, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_MULHWU_, 0, 31, 11, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_CMPLW, 0, 31, 32, OPC_NONE, OP_FORM_OP3_A_CMP, FLG_DEFAULT, 0, 0, nullptr}, {PPCASM_OP_SUBF, 1, 31, 40, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_SUBF_, 1, 31, 40, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_SUB, 0, 31, 40, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(11), EncodedOperand_GPR(16)} }, {PPCASM_OP_SUB_, 0, 31, 40, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(11), EncodedOperand_GPR(16)} }, {PPCASM_OP_MULHW, 0, 31, 75, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_MULHW_, 0, 31, 75, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_NEG, 0, 31, 104, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC | C_MASK_OE, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16)}}, {PPCASM_OP_NEG_, 0, 31, 104, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC | C_MASK_OE, C_BIT_RC, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16)} }, {PPCASM_OP_NOR, 0, 31, 124, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_GPR(11)} }, {PPCASM_OP_NOR_, 0, 31, 124, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_GPR(11)} }, // alias for NOR where rA == rB {PPCASM_OP_NOT, 1, 31, 124, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(11)}, {EncodedConstraint_MirrorRegister(11, 21)}}, {PPCASM_OP_NOT_, 1, 31, 124, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(11)}, {EncodedConstraint_MirrorRegister(11, 21)} }, {PPCASM_OP_SUBFE, 1, 31, 136, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_SUBFE_, 1, 31, 136, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_MULLW, 0, 31, 235, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_MULLW_, 0, 31, 235, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_MFSPR, 0, 31, 339, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_SPR()} }, {PPCASM_OP_MTSPR, 0, 31, 467, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_SPR(), EncodedOperand_GPR(21)} }, {PPCASM_OP_MFLR, 0, 31, 339, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21)}, {EncodedConstraint_FixedSPR(8)}}, {PPCASM_OP_MTLR, 0, 31, 467, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21)}, {EncodedConstraint_FixedSPR(8)} }, {PPCASM_OP_MFCTR, 0, 31, 339, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21)}, {EncodedConstraint_FixedSPR(9)} }, {PPCASM_OP_MTCTR, 0, 31, 467, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21)}, {EncodedConstraint_FixedSPR(9)} }, {PPCASM_OP_ADD, 0, 31, 266, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_ADD_, 0, 31, 266, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_SLW, 0, 31, 24, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_GPR(11)} }, {PPCASM_OP_SLW_, 0, 31, 24, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_GPR(11)} }, {PPCASM_OP_SRW, 0, 31, 536, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_GPR(11)} }, {PPCASM_OP_SRW_, 0, 31, 536, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_GPR(11)} }, {PPCASM_OP_SRAW, 0, 31, 792, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_GPR(11)} }, {PPCASM_OP_SRAW_, 0, 31, 792, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_GPR(11)} }, {PPCASM_OP_AND, 0, 31, 28, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_GPR(11)} }, {PPCASM_OP_AND_, 0, 31, 28, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_GPR(11)} }, {PPCASM_OP_ANDC, 0, 31, 60, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_GPR(11)} }, {PPCASM_OP_ANDC_, 0, 31, 60, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_GPR(11)} }, {PPCASM_OP_XOR, 0, 31, 316, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_GPR(11)} }, {PPCASM_OP_ORC, 0, 31, 412, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_GPR(11)} }, // has RC? {PPCASM_OP_OR, 0, 31, 444, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_GPR(11)} }, {PPCASM_OP_OR_, 0, 31, 444, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21), EncodedOperand_GPR(11)} }, {PPCASM_OP_MR, 1, 31, 444, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(11)}, {EncodedConstraint_MirrorRegister(11, 21)} }, {PPCASM_OP_MR_, 1, 31, 444, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(11)}, {EncodedConstraint_MirrorRegister(11, 21)} }, {PPCASM_OP_DIVWU, 0, 31, 459, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_DIVWU_, 0, 31, 459, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_DIVW, 0, 31, 491, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_DIVW_, 0, 31, 491, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_SRAWI, 0, 31, 824, OPC_NONE, OP_FORM_OP3_A_IMM, FLG_DEFAULT, C_MASK_RC, 0, nullptr}, {PPCASM_OP_SRAWI_, 0, 31, 824, OPC_NONE, OP_FORM_OP3_A_IMM, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr}, {PPCASM_OP_CNTLZW, 0, 31, 26, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21)} }, {PPCASM_OP_EXTSB, 0, 31, 954, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21)} }, {PPCASM_OP_EXTSH, 0, 31, 922, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, 0, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21)} }, {PPCASM_OP_CNTLZW_, 0, 31, 26, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21)} }, {PPCASM_OP_EXTSB_, 0, 31, 954, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21)} }, {PPCASM_OP_EXTSH_, 0, 31, 922, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(16), EncodedOperand_GPR(21)} }, {PPCASM_OP_LWZX, 0, 31, 23, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_LWZUX, 0, 31, 55, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_LBZX, 0, 31, 87, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_LBZUX, 0, 31, 119, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_LHZX, 0, 31, 279, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_LHZUX, 0, 31, 311, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_LHAX, 0, 31, 343, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_LHAUX, 0, 31, 375, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_STWX, 0, 31, 151, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_STWUX, 0, 31, 183, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_STHX, 0, 31, 407, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_STHUX, 0, 31, 439, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_STBX, 0, 31, 215, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_STBUX, 0, 31, 247, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_STWBRX, 0, 31, 662, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_STHBRX, 0, 31, 918, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_LFSX, 0, 31, 535, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_LFSUX, 0, 31, 567, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_STFSX, 0, 31, 663, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_STFSUX, 0, 31, 695, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_STSWI, 0, 31, 725, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR(16), EncodedOperand_IMM(11, 5, false)} }, {PPCASM_OP_LWARX, 0, 31, 20, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_STWCX_, 0, 31, 150, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, C_MASK_RC, C_BIT_RC, nullptr, {EncodedOperand_GPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_LFDX, 0, 31, 599, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_LFDUX, 0, 31, 631, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_STFDX, 0, 31, 727, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_STFDUX, 0, 31, 759, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, {PPCASM_OP_STFIWX, 0, 31, 983, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_GPR<true>(16), EncodedOperand_GPR(11)} }, // load/store {PPCASM_OP_LWZ, 0, 32, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_MemLoc()} }, {PPCASM_OP_LWZU, 0, 33, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_MemLoc()} }, {PPCASM_OP_LBZ, 0, 34, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_MemLoc()} }, {PPCASM_OP_LBZU, 0, 35, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_MemLoc()} }, {PPCASM_OP_STW, 0, 36, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_MemLoc()} }, {PPCASM_OP_STWU, 0, 37, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_MemLoc()} }, {PPCASM_OP_STB, 0, 38, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_MemLoc()} }, {PPCASM_OP_STBU, 0, 39, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_MemLoc()} }, {PPCASM_OP_LHZ, 0, 40, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_MemLoc()} }, {PPCASM_OP_LHZU, 0, 41, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_MemLoc()} }, {PPCASM_OP_LHA, 0, 42, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_MemLoc()} }, {PPCASM_OP_LHAU, 0, 43, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_MemLoc()} }, {PPCASM_OP_STH, 0, 44, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_MemLoc()} }, {PPCASM_OP_STHU, 0, 45, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_MemLoc()} }, {PPCASM_OP_LMW, 0, 46, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_MemLoc()} }, {PPCASM_OP_STMW, 0, 47, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_GPR(21), EncodedOperand_MemLoc()} }, {PPCASM_OP_LFS, 0, 48, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_MemLoc()} }, {PPCASM_OP_LFSU, 0, 49, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_MemLoc()} }, {PPCASM_OP_LFD, 0, 50, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_MemLoc()} }, {PPCASM_OP_LFDU, 0, 51, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_MemLoc()} }, {PPCASM_OP_STFS, 0, 52, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_MemLoc()} }, {PPCASM_OP_STFSU, 0, 53, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_MemLoc()} }, {PPCASM_OP_STFD, 0, 54, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_MemLoc()} }, {PPCASM_OP_STFDU, 0, 55, OPC_NONE, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_MemLoc()} }, // FP {PPCASM_OP_FDIVS, 0, 59, 18, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, { EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(11) } }, {PPCASM_OP_FSUBS, 0, 59, 20, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, { EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(11) } }, {PPCASM_OP_FADDS, 0, 59, 21, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, { EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(11) } }, {PPCASM_OP_FMULS, 0, 59, 25, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, { EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(6) } }, {PPCASM_OP_FMSUBS, 0, 59, 28, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, { EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(6), EncodedOperand_FPR(11) } }, {PPCASM_OP_FMADDS, 0, 59, 29, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, { EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(6), EncodedOperand_FPR(11) } }, {PPCASM_OP_FNMSUBS, 0, 59, 30, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, { EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(6), EncodedOperand_FPR(11) } }, {PPCASM_OP_FNMADDS, 0, 59, 31, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, { EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(6), EncodedOperand_FPR(11) } }, {PPCASM_OP_FCMPU, 0, 63, 0, OPC_NONE, OP_FORM_X_FP_CMP, FLG_DEFAULT, 0, 0, nullptr }, {PPCASM_OP_FCTIWZ, 0, 63, 15, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, {EncodedOperand_FPR(21), EncodedOperand_FPR(11)}}, {PPCASM_OP_FDIV, 0, 63, 18, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, { EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(11) } }, {PPCASM_OP_FSUB, 0, 63, 20, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, { EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(11) } }, {PPCASM_OP_FADD, 0, 63, 21, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, { EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(11) } }, {PPCASM_OP_FMUL, 0, 63, 25, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, { EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(6) } }, {PPCASM_OP_FRSQRTE, 0, 63, 26, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, { EncodedOperand_FPR(21), EncodedOperand_FPR(11) } }, {PPCASM_OP_FMSUB, 0, 63, 28, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, { EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(6), EncodedOperand_FPR(11) } }, {PPCASM_OP_FMADD, 0, 63, 29, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, { EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(6), EncodedOperand_FPR(11) } }, {PPCASM_OP_FNMSUB, 0, 63, 30, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, { EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(6), EncodedOperand_FPR(11) } }, {PPCASM_OP_FNMADD, 0, 63, 31, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, { EncodedOperand_FPR(21), EncodedOperand_FPR(16), EncodedOperand_FPR(6), EncodedOperand_FPR(11) } }, {PPCASM_OP_FRSP, 0, 63, 12, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, { EncodedOperand_FPR(21), EncodedOperand_FPR(11) } }, // 63 extended opcode {PPCASM_OP_FCMPO, 0, 63, 32|OPC_EXTENDED_BIT, OPC_NONE, OP_FORM_X_FP_CMP, FLG_DEFAULT, 0, 0, nullptr }, {PPCASM_OP_FNEG, 0, 63, 40|OPC_EXTENDED_BIT, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, { EncodedOperand_FPR(21), EncodedOperand_FPR(11) } }, {PPCASM_OP_FMR, 0, 63, 72|OPC_EXTENDED_BIT, OPC_NONE, OP_FORM_DYNAMIC, FLG_DEFAULT, 0, 0, nullptr, { EncodedOperand_FPR(21), EncodedOperand_FPR(11) } }, }; #define opcMask_setBits(__index, __bitCount, __value) opcodeMask |= (((1<<__bitCount)-1)<<(31-__index)); opcodeBits |= ((__value)<<(31-__index)); void ppcAssembler_buildOpcMask(PPCInstructionDef* iDef, uint32& maskOut, uint32& bitsOut) { uint32 opc0 = iDef->opc0; uint32 opc1 = iDef->opc1; uint32 opc2 = iDef->opc2; uint32 opcodeMask = 0x3F<<26; uint32 opcodeBits = opc0<<26; // handle groups if (opc0 == 31) { // group 31 opcMask_setBits(30, 10, opc1); } else if (opc0 == 19) { // group 19 opcMask_setBits(30, 10, opc1); } else if (opc0 == 4) { // group 4 (paired single) opcMask_setBits(30, 5, opc1); //opc1 = PPC_getBits(opcode, 30, 5); if (opc1 == 16) { // group 4->16 (ps_merge) opcMask_setBits(25, 5, opc2); //opc2 = PPC_getBits(opcode, 25, 5); } } else if (opc0 == 59) { // group 59 (FP float) opcMask_setBits(30, 5, opc1); //opc1 = PPC_getBits(opcode, 30, 5); } else if (opc0 == 63) { // group 63 (FP double) if ((opc1&OPC_EXTENDED_BIT) != 0) { opcMask_setBits(30, 10, (opc1&~OPC_EXTENDED_BIT)); } else { opcMask_setBits(30, 5, opc1); } } maskOut = opcodeMask; bitsOut = opcodeBits; } // given an internal instruction operand index, return the text encoding index sint32 _getOpIndex(PPCInstructionDef* iDef, sint32 operandIndex) { if ((operandIndex == 0 || operandIndex == 1) && (iDef->flags & FLG_SWAP_OP0_OP1) != 0) operandIndex ^= 1; if ((iDef->flags & FLG_SWAP_OP1_OP2) != 0) { if (operandIndex == 1) operandIndex = 2; else if (operandIndex == 2) operandIndex = 1; } if ((iDef->flags & FLG_SWAP_OP2_OP3) != 0) { if (operandIndex == 2) operandIndex = 3; else if (operandIndex == 3) operandIndex = 2; } return operandIndex; } // given an internal instruction operand index, return the operand index for the text encoding. Returns -1 when operand is not present // replaces _getOpIndex //sint32 _operandInternalToTextIndex(ppcInstructionDef_t* iDef, sint32 operandIndex) //{ // if ((operandIndex == 0 || operandIndex == 1) && (iDef->flags & FLG_SWAP_OP0_OP1) != 0) // operandIndex ^= 1; // if ((operandIndex == 2 || operandIndex == 3) && (iDef->flags & FLG_SWAP_OP2_OP3) != 0) // operandIndex ^= 1; // sint32 outputIndex = operandIndex; // if ((iDef->flags & (1 << outputIndex))) // return -1; // for (sint32 i = 0; i < operandIndex; i++) // { // if ((iDef->flags & (1 << i))) // outputIndex--; // } // return outputIndex; //} // //int _operandTextToInternalIndex(ppcInstructionDef_t* iDef, sint32 operandIndex) //{ // for (sint32 i = 0; i < 8; i++) // { // if (_operandInternalToTextIndex(iDef, i) == operandIndex) // return i; // } // return -1; //} void _disasmOpGPR(PPCDisassembledInstruction* disInstr, PPCInstructionDef* iDef, uint32 operandIndex, sint32 regIndex) { if ((iDef->flags & (FLG_SKIP_OP0 << operandIndex)) != 0) return; disInstr->operandMask |= (1 << operandIndex); sint32 opIdx = _getOpIndex(iDef, operandIndex); disInstr->operand[opIdx].type = PPCASM_OPERAND_TYPE_GPR; disInstr->operand[opIdx].registerIndex = regIndex; } void ppcAssembler_disassemble(uint32 virtualAddress, uint32 opcode, PPCDisassembledInstruction* disInstr) { auto makeOpCRBit = [&](size_t opIndex, uint8 regIndex) { disInstr->operandMask |= (1 << opIndex); disInstr->operand[opIndex].type = PPCASM_OPERAND_TYPE_CR_BIT; disInstr->operand[opIndex].registerIndex = regIndex; }; auto makeOpFPR = [&](size_t opIndex, uint8 regIndex) { disInstr->operandMask |= (1 << opIndex); disInstr->operand[opIndex].type = PPCASM_OPERAND_TYPE_FPR; disInstr->operand[opIndex].registerIndex = regIndex; }; memset(disInstr, 0, sizeof(PPCDisassembledInstruction)); // find match in table sint32 bestMatchIndex = -1; uint8 bestMatchPriority = 0; for (sint32 i = 0; i < sizeof(ppcInstructionTable) / sizeof(PPCInstructionDef); i++) { PPCInstructionDef* iDef = ppcInstructionTable + i; // check opcode uint32 opcMask; uint32 opcBits; ppcAssembler_buildOpcMask(iDef, opcMask, opcBits); if ((opcode&opcMask) != opcBits) continue; // check bits if((opcode&iDef->maskBits) != iDef->compareBits) continue; // check special condition if(iDef->extraCheck && iDef->extraCheck(opcode) == false ) continue; // check priority if(iDef->priority < bestMatchPriority) continue; // check constraints bool allConstraintsMatch = true; for (auto& it : iDef->constraints) { if (!std::visit([&](auto&& op) -> bool { return op.DisassembleCheckConstraint(disInstr, iDef, opcode); }, it)) { allConstraintsMatch = false; break; } } if (!allConstraintsMatch) continue; // select entry bestMatchIndex = i; bestMatchPriority = iDef->priority; } // if we have found an entry, parse operand data if (bestMatchIndex >= 0) { PPCInstructionDef* iDef = ppcInstructionTable + bestMatchIndex; // setup general instruction info disInstr->ppcAsmCode = iDef->ppcAsmOp; // parse operands if (iDef->instructionForm == OP_FORM_DYNAMIC) { disInstr->operandMask = 0; for (size_t i = 0; i < iDef->encodedOperands.size(); i++) { std::visit([&](auto&& op) { op.DisassembleOperand(disInstr, iDef, opcode, i); }, iDef->encodedOperands[i]); } } else if (iDef->instructionForm == OP_FORM_OP3_A_CMP) { sint32 rS, rA, rB; PPC_OPC_TEMPL_X(opcode, rS, rA, rB); disInstr->operandMask = (rS!=0?operand0Bit:0); disInstr->operand[0].type = PPCASM_OPERAND_TYPE_CR; disInstr->operand[0].registerIndex = rS >> 2; if((rS & 3) != 0) cemuLog_log(LogType::Force, "[PPC-Disassembler] Unexpected CR encoding for instruction 0x{0:08x}", opcode); _disasmOpGPR(disInstr, iDef, 1, rA); _disasmOpGPR(disInstr, iDef, 2, rB); } else if (iDef->instructionForm == OP_FORM_OP3_A_IMM) { sint32 rS, rA, SH; PPC_OPC_TEMPL_X(opcode, rS, rA, SH); disInstr->operandMask = operand0Bit | operand1Bit | operand2Bit; sint32 op0Idx = _getOpIndex(iDef, 0); sint32 op1Idx = _getOpIndex(iDef, 1); sint32 op2Idx = _getOpIndex(iDef, 2); // operand 0 disInstr->operand[op0Idx].type = PPCASM_OPERAND_TYPE_GPR; disInstr->operand[op0Idx].registerIndex = rA; // operand 1 disInstr->operand[op1Idx].type = PPCASM_OPERAND_TYPE_GPR; disInstr->operand[op1Idx].registerIndex = rS; // operand 2 disInstr->operand[op2Idx].type = PPCASM_OPERAND_TYPE_IMM; disInstr->operand[op2Idx].immS32 = SH; disInstr->operand[op2Idx].immWidth = 5; disInstr->operand[op2Idx].isSignedImm = false; } else if (iDef->instructionForm == OP_FORM_BRANCH_S16) { uint32 BO, BI, dest; PPC_OPC_TEMPL_B(opcode, BO, BI, dest); uint8 crIndex = BI >> 2; if ((opcode & PPC_OPC_AA) == 0) dest += virtualAddress; if (iDef->ppcAsmOp == PPCASM_OP_BC) { // generic conditional branch of form <BO>, CR+LT/GT/EQ/SO, <dst> disInstr->operandMask = operand0Bit | operand1Bit | operand2Bit; // operand 0 disInstr->operand[0].type = PPCASM_OPERAND_TYPE_CIMM; disInstr->operand[0].registerIndex = BO; // operand 1 disInstr->operand[1].type = PPCASM_OPERAND_TYPE_CR_BIT; disInstr->operand[1].registerIndex = BI; // operand 2 disInstr->operand[2].type = PPCASM_OPERAND_TYPE_CIMM; disInstr->operand[2].immU32 = dest; // hint bit disInstr->branchHintBitSet = (BO & 1) != 0; } else { if (crIndex != 0) { disInstr->operandMask = operand0Bit | operand1Bit; // operand 0 disInstr->operand[0].type = PPCASM_OPERAND_TYPE_CR; disInstr->operand[0].registerIndex = crIndex; // operand 1 disInstr->operand[1].type = PPCASM_OPERAND_TYPE_CIMM; disInstr->operand[1].immU32 = dest; } else { disInstr->operandMask = operand0Bit; disInstr->operand[0].type = PPCASM_OPERAND_TYPE_CIMM; disInstr->operand[0].immU32 = dest; } // hint bit disInstr->branchHintBitSet = (BO & 1) != 0; } } else if (iDef->instructionForm == OP_FORM_BRANCH_S24) { uint32 dest; PPC_OPC_TEMPL_I(opcode, dest); if ((opcode & PPC_OPC_AA) == 0) dest += virtualAddress; disInstr->operandMask = operand0Bit; // operand 0 disInstr->operand[0].type = PPCASM_OPERAND_TYPE_CIMM; disInstr->operand[0].immU32 = dest; } else if (iDef->instructionForm == OP_FORM_OP2_D_HSIMM) { sint32 rD, rA; uint32 imm; PPC_OPC_TEMPL_D_SImm(opcode, rD, rA, imm); disInstr->operandMask = operand0Bit | operand1Bit; // operand 0 disInstr->operand[0].type = PPCASM_OPERAND_TYPE_GPR; disInstr->operand[0].registerIndex = rD; // operand 1 disInstr->operand[1].type = PPCASM_OPERAND_TYPE_IMM; disInstr->operand[1].immS32 = imm & 0xFFFF; disInstr->operand[1].immWidth = 16; disInstr->operand[1].isSignedImm = true; } else if (iDef->instructionForm == OP_FORM_CMP_SIMM) { uint32 cr; sint32 rA; uint32 imm; PPC_OPC_TEMPL_D_SImm(opcode, cr, rA, imm); cr /= 4; // rS is cr disInstr->operandMask = operand1Bit | operand2Bit; if (cr != 0) disInstr->operandMask |= operand0Bit; // operand 0 disInstr->operand[0].type = PPCASM_OPERAND_TYPE_CR; disInstr->operand[0].registerIndex = cr; // operand 1 disInstr->operand[1].type = PPCASM_OPERAND_TYPE_GPR; disInstr->operand[1].registerIndex = rA; // operand 2 disInstr->operand[2].type = PPCASM_OPERAND_TYPE_IMM; disInstr->operand[2].immS32 = imm; disInstr->operand[2].immWidth = 16; disInstr->operand[2].isSignedImm = true; } else if (iDef->instructionForm == OP_FORM_NO_OPERAND) { disInstr->operandMask = 0; } else if (iDef->instructionForm == OP_FORM_X_FP_CMP) { sint32 rA, crIndex, rB; PPC_OPC_TEMPL_X(opcode, crIndex, rA, rB); cemu_assert_debug((crIndex % 4) == 0); crIndex /= 4; disInstr->operandMask = operand0Bit | operand1Bit | operand2Bit; // operand 0 disInstr->operand[0].type = PPCASM_OPERAND_TYPE_CR; disInstr->operand[0].registerIndex = crIndex; // operand 1 disInstr->operand[1].type = PPCASM_OPERAND_TYPE_FPR; disInstr->operand[1].registerIndex = rA; // operand 2 disInstr->operand[2].type = PPCASM_OPERAND_TYPE_FPR; disInstr->operand[2].registerIndex = rB; } else if (iDef->instructionForm == OP_FORM_RLWINM) { sint32 rS, rA, SH, MB, ME; PPC_OPC_TEMPL_M(opcode, rS, rA, SH, MB, ME); disInstr->operandMask = operand0Bit | operand1Bit | operand2Bit | operand3Bit | operand4Bit; // operand 0 disInstr->operand[0].type = PPCASM_OPERAND_TYPE_GPR; disInstr->operand[0].registerIndex = rA; // operand 1 disInstr->operand[1].type = PPCASM_OPERAND_TYPE_GPR; disInstr->operand[1].registerIndex = rS; // operand 2 disInstr->operand[2].type = PPCASM_OPERAND_TYPE_IMM; disInstr->operand[2].immS32 = SH; disInstr->operand[2].immWidth = 8; // operand 3 disInstr->operand[3].type = PPCASM_OPERAND_TYPE_IMM; disInstr->operand[3].immS32 = MB; disInstr->operand[3].immWidth = 8; // operand 4 disInstr->operand[4].type = PPCASM_OPERAND_TYPE_IMM; disInstr->operand[4].immS32 = ME; disInstr->operand[4].immWidth = 8; } else if (iDef->instructionForm == OP_FORM_RLWINM_EXTENDED) { sint32 rS, rA, SH, MB, ME; PPC_OPC_TEMPL_M(opcode, rS, rA, SH, MB, ME); // operand 0 disInstr->operand[0].type = PPCASM_OPERAND_TYPE_GPR; disInstr->operand[0].registerIndex = rA; // operand 1 disInstr->operand[1].type = PPCASM_OPERAND_TYPE_GPR; disInstr->operand[1].registerIndex = rS; if (iDef->ppcAsmOp == PPCASM_OP_EXTLWI || iDef->ppcAsmOp == PPCASM_OP_EXTLWI_) { disInstr->operandMask = operand0Bit | operand1Bit | operand2Bit | operand3Bit; // operand 2 disInstr->operand[2].type = PPCASM_OPERAND_TYPE_IMM; disInstr->operand[2].immS32 = ME + 1; disInstr->operand[2].immWidth = 8; // operand 3 disInstr->operand[3].type = PPCASM_OPERAND_TYPE_IMM; disInstr->operand[3].immS32 = SH; disInstr->operand[3].immWidth = 8; } else if (iDef->ppcAsmOp == PPCASM_OP_EXTRWI || iDef->ppcAsmOp == PPCASM_OP_EXTRWI_) { disInstr->operandMask = operand0Bit | operand1Bit | operand2Bit | operand3Bit; sint8 n = 32 - MB; sint8 b = SH - n; // operand 2 disInstr->operand[2].type = PPCASM_OPERAND_TYPE_IMM; disInstr->operand[2].immS32 = n; disInstr->operand[2].immWidth = 8; // operand 3 disInstr->operand[3].type = PPCASM_OPERAND_TYPE_IMM; disInstr->operand[3].immS32 = b; disInstr->operand[3].immWidth = 8; } else if (iDef->ppcAsmOp == PPCASM_OP_SLWI || iDef->ppcAsmOp == PPCASM_OP_SLWI_) { disInstr->operandMask = operand0Bit | operand1Bit | operand2Bit; sint8 n = SH; // operand 2 disInstr->operand[2].type = PPCASM_OPERAND_TYPE_IMM; disInstr->operand[2].immS32 = n; disInstr->operand[2].immWidth = 8; } else if (iDef->ppcAsmOp == PPCASM_OP_SRWI || iDef->ppcAsmOp == PPCASM_OP_SRWI_) { disInstr->operandMask = operand0Bit | operand1Bit | operand2Bit; sint8 n = 32 - SH; // operand 2 disInstr->operand[2].type = PPCASM_OPERAND_TYPE_IMM; disInstr->operand[2].immS32 = n; disInstr->operand[2].immWidth = 8; } else if (iDef->ppcAsmOp == PPCASM_OP_CLRLWI || iDef->ppcAsmOp == PPCASM_OP_CLRLWI_) { disInstr->operandMask = operand0Bit | operand1Bit | operand2Bit; sint8 n = MB; // operand 2 disInstr->operand[2].type = PPCASM_OPERAND_TYPE_IMM; disInstr->operand[2].immS32 = n; disInstr->operand[2].immWidth = 8; } else if (iDef->ppcAsmOp == PPCASM_OP_CLRRWI || iDef->ppcAsmOp == PPCASM_OP_CLRRWI_) { disInstr->operandMask = operand0Bit | operand1Bit | operand2Bit; sint8 n = 31 - ME; // operand 2 disInstr->operand[2].type = PPCASM_OPERAND_TYPE_IMM; disInstr->operand[2].immS32 = n; disInstr->operand[2].immWidth = 8; } else { cemu_assert_debug(false); } } else if (iDef->instructionForm == OP_FORM_RLWNM) { sint32 rS, rA, rB, MB, ME; PPC_OPC_TEMPL_M(opcode, rS, rA, rB, MB, ME); disInstr->operandMask = operand0Bit | operand1Bit | operand2Bit | operand3Bit | operand4Bit; // operand 0 disInstr->operand[0].type = PPCASM_OPERAND_TYPE_GPR; disInstr->operand[0].registerIndex = rA; // operand 1 disInstr->operand[1].type = PPCASM_OPERAND_TYPE_GPR; disInstr->operand[1].registerIndex = rS; // operand 2 disInstr->operand[2].type = PPCASM_OPERAND_TYPE_GPR; disInstr->operand[2].registerIndex = rB; // operand 3 disInstr->operand[3].type = PPCASM_OPERAND_TYPE_IMM; disInstr->operand[3].immS32 = MB; disInstr->operand[3].immWidth = 8; // operand 4 disInstr->operand[4].type = PPCASM_OPERAND_TYPE_IMM; disInstr->operand[4].immS32 = ME; disInstr->operand[4].immWidth = 8; } else if (iDef->instructionForm == OP_FORM_RLWNM_EXTENDED) { sint32 rS, rA, rB, MB, ME; PPC_OPC_TEMPL_M(opcode, rS, rA, rB, MB, ME); // operand 0 disInstr->operand[0].type = PPCASM_OPERAND_TYPE_GPR; disInstr->operand[0].registerIndex = rA; // operand 1 disInstr->operand[1].type = PPCASM_OPERAND_TYPE_GPR; disInstr->operand[1].registerIndex = rS; // operand 2 disInstr->operand[2].type = PPCASM_OPERAND_TYPE_GPR; disInstr->operand[2].registerIndex = rB; if (iDef->ppcAsmOp == PPCASM_OP_ROTLW || iDef->ppcAsmOp == PPCASM_OP_ROTLW_) { disInstr->operandMask = operand0Bit | operand1Bit | operand2Bit; // no additional operands displayed } } else if (iDef->instructionForm == OP_FORM_XL_CR) { PPC_OPC_TEMPL_X_CR(); // todo - detect and emit simplified mnemonics (e.g. CRSET) makeOpCRBit(0, crD); makeOpCRBit(1, crA); makeOpCRBit(2, crB); } else { cemu_assert_debug(false); } disInstr->operandMask &= ~(iDef->flags & 0x1F); } else { // no match disInstr->ppcAsmCode = PPCASM_OP_UKN; } } void ppcAssembler_setError(PPCAssemblerInOut* ctx, char const* errorMsg) { ctx->errorMsg = errorMsg; } void ppcAssembler_setError(PPCAssemblerInOut* ctx, std::string_view errorMsg) { ctx->errorMsg = errorMsg; } char _assemblerErrorMessageDepr[1024]; bool _ppcAssembler_getOperandTextIndex(PPCAssemblerContext& internalCtx, sint32 operandIndex, sint32& textIndex) { // get swapped index operandIndex = _getOpIndex(internalCtx.iDef, operandIndex); // check if operand is optional if ((internalCtx.iDef->flags&(1 << operandIndex))) { // operand not used textIndex = -1; return true; } // get operand text index sint32 opTextIdx = 0; for (sint32 i = 0; i < operandIndex; i++) { if ((internalCtx.iDef->flags&(1 << i))) continue; // skip operand opTextIdx++; } if (opTextIdx >= internalCtx.listOperandStr.size()) { ppcAssembler_setError(internalCtx.ctx, "Missing operand"); return false; } textIndex = opTextIdx; return true; } bool _ppcAssembler_parseRegister(std::string_view str, const char* prefix, sint32& regIndex) { const char* startPtr = str.data(); const char* endPtr = str.data() + str.size(); // skip whitespaces while (startPtr < endPtr) { if (*startPtr != ' ') break; startPtr++; } // trim whitespaces at end while (endPtr > startPtr) { if (endPtr[-1] != ' ') break; endPtr--; } // parse register name if (startPtr + 2 > endPtr) return false; while (true) { if (startPtr >= endPtr) return false; if (*prefix == '\0') break; if (tolower(*prefix) != tolower(*startPtr)) return false; prefix++; startPtr++; } sint32 parsedIndex = 0; while (startPtr < endPtr) { parsedIndex *= 10; if (*startPtr < '0' || *startPtr > '9') return false; parsedIndex += (*startPtr - '0'); startPtr++; } if (parsedIndex >= 32) return false; regIndex = parsedIndex; return true; } bool _ppcAssembler_processRegisterOperand(PPCAssemblerContext& internalCtx, sint32 operandIndex, sint32 bitIndex, const char* prefix, const sint32 registerCount) { sint32 opTextIdx; if (_ppcAssembler_getOperandTextIndex(internalCtx, operandIndex, opTextIdx) == false) return false; if (opTextIdx < 0) return true; // skipped operand // parse GPR sint32 gprIndex; if (_ppcAssembler_parseRegister(internalCtx.listOperandStr[opTextIdx].str, prefix, gprIndex) == false) { ppcAssembler_setError(internalCtx.ctx, fmt::format("\'{0}\' is not a valid register operand (must be {1}0 to {1}{2})", internalCtx.listOperandStr[opTextIdx].str, prefix, registerCount-1)); return false; } if (gprIndex < 0 || gprIndex >= registerCount) { ppcAssembler_setError(internalCtx.ctx, fmt::format("\'{0}\' is not a valid register operand (must be {1}0 to {1}{2})", internalCtx.listOperandStr[opTextIdx].str, prefix, registerCount - 1)); return false; } internalCtx.opcode |= (gprIndex << bitIndex); return true; } bool _ppcAssembler_processGPROperand(PPCAssemblerContext& internalCtx, sint32 operandIndex, sint32 bitIndex) { return _ppcAssembler_processRegisterOperand(internalCtx, operandIndex, bitIndex, "r", 32); } bool _ppcAssembler_processCROperand(PPCAssemblerContext& internalCtx, sint32 operandIndex, sint32 bitIndex, bool isEncodedAsBitIndex) { return _ppcAssembler_processRegisterOperand(internalCtx, operandIndex, bitIndex + (isEncodedAsBitIndex?2:0), "cr", 8); } template<typename TExprResult> bool _ppcAssembler_evaluateConstantExpression(PPCAssemblerContext& internalCtx, TExpressionParser<TExprResult>& ep, std::string_view expr, TExprResult& result) { if (!ep.IsValidExpression(expr)) { ppcAssembler_setError(internalCtx.ctx, fmt::format("'{}' is not a valid expression", expr)); return false; } if (!ep.IsConstantExpression(expr)) { ppcAssembler_setError(internalCtx.ctx, fmt::format("'{}' does not evaluate to a constant expression", expr)); return false; } try { result = ep.Evaluate(expr); } catch (std::exception* e) { ppcAssembler_setError(internalCtx.ctx, fmt::format("\'{0}\' could not be evaluated. Error: {1}", expr, e->what())); return false; } return true; } bool _ppcAssembler_processBIOperand(PPCAssemblerContext& internalCtx, sint32 operandIndex, sint32 bitIndex) { sint32 opTextIdx; if (_ppcAssembler_getOperandTextIndex(internalCtx, operandIndex, opTextIdx) == false) return false; if (opTextIdx < 0) return true; // skipped operand // parse expression // syntax examples: // single condition bit of cr0: lt, gt, eq, so // condition bit with cr index: 4*cr1+lt TExpressionParser<sint32> ep; ep.AddConstant("lt", 0); ep.AddConstant("gt", 1); ep.AddConstant("eq", 2); ep.AddConstant("so", 3); ep.AddConstant("cr0", 0); ep.AddConstant("cr1", 1); ep.AddConstant("cr2", 2); ep.AddConstant("cr3", 3); ep.AddConstant("cr4", 4); ep.AddConstant("cr5", 5); ep.AddConstant("cr6", 6); ep.AddConstant("cr7", 7); std::string_view expr = internalCtx.listOperandStr[opTextIdx].str; sint32 bi = 0; if (!_ppcAssembler_evaluateConstantExpression(internalCtx, ep, expr, bi)) return false; if (bi < 0 || bi >= (8 * 4)) { ppcAssembler_setError(internalCtx.ctx, fmt::format("CR bit operand \'{0}\' evaluated to {1} which is out of range", expr, bi)); return false; } internalCtx.opcode &= ~(0x1F << bitIndex); internalCtx.opcode |= (bi << bitIndex); return true; } bool _ppcAssembler_processFPROperand(PPCAssemblerContext& internalCtx, sint32 operandIndex, sint32 bitIndex) { return _ppcAssembler_processRegisterOperand(internalCtx, operandIndex, bitIndex, "f", 32); } bool _ppcAssembler_processImmediateOperandS16(PPCAssemblerContext& internalCtx, sint32 operandIndex, sint32 bitIndex, bool isNegative = false) { sint32 opTextIdx; if (_ppcAssembler_getOperandTextIndex(internalCtx, operandIndex, opTextIdx) == false) return false; if (opTextIdx < 0) return true; // skipped operand // parse expression std::string expressionString(internalCtx.listOperandStr[opTextIdx].str); if (isNegative) { expressionString.insert(0, "0-("); expressionString.append(")"); } ExpressionParser ep; double immD = 0.0f; try { if (ep.IsConstantExpression(expressionString)) { immD = ep.Evaluate(expressionString); } else { internalCtx.ctx->list_relocs.emplace_back(PPCASM_RELOC::U32_MASKED_IMM, expressionString, 0, bitIndex, 16); return true; } } catch (std::exception* e) { // check if expression is invalid or if it contains unknown constants sprintf(_assemblerErrorMessageDepr, "\'%s\' could not be evaluated. Error: %s", expressionString.c_str(), e->what()); ppcAssembler_setError(internalCtx.ctx, _assemblerErrorMessageDepr); return false; } uint32 imm = (uint32)(sint32)immD; imm &= 0xFFFF; internalCtx.opcode |= (imm << bitIndex); return true; } bool _ppcAssembler_processImmediateOperandU5(PPCAssemblerContext& internalCtx, sint32 operandIndex, sint32 bitIndex) { sint32 opTextIdx; if (_ppcAssembler_getOperandTextIndex(internalCtx, operandIndex, opTextIdx) == false) return false; if (opTextIdx < 0) return true; // skipped operand // parse expression ExpressionParser ep; double immD = 0.0f; try { immD = ep.Evaluate(internalCtx.listOperandStr[opTextIdx].str); } catch (std::exception*) { // check if expression is invalid or if it contains unknown constants ppcAssembler_setError(internalCtx.ctx, fmt::format("\'{}\' is not a valid expression", internalCtx.listOperandStr[opTextIdx].str)); return false; } sint32 immS32 = (sint32)immD; if (immS32 < 0 || immS32 >= 32) { ppcAssembler_setError(internalCtx.ctx, fmt::format("\'{}\' is not in range 0-31", internalCtx.listOperandStr[opTextIdx].str)); return false; } uint32 imm = (uint32)immS32; imm &= 0x1F; internalCtx.opcode |= (imm << bitIndex); return true; } bool _ppcAssembler_processImmediateOperandU5Const(PPCAssemblerContext& internalCtx, sint32 operandIndex, sint8& value) { sint32 opTextIdx; if (_ppcAssembler_getOperandTextIndex(internalCtx, operandIndex, opTextIdx) == false) return false; if (opTextIdx < 0) return true; // skipped operand // parse expression TExpressionParser<sint32> ep; auto expr = internalCtx.listOperandStr[opTextIdx].str; sint32 r; if (!_ppcAssembler_evaluateConstantExpression(internalCtx, ep, expr, r)) return false; if (r < 0 || r >= 32) { ppcAssembler_setError(internalCtx.ctx, fmt::format("Expression '\'{0}\' which evaluates to {1} is not in range 0-31", expr, r)); return false; } value = (sint8)r; return true; } bool _ppcAssembler_isConstantBranchTargetExpr(std::string& expressionString, sint32& relativeAddr) { if (expressionString.length() > 0 && expressionString[0] == '.') { ExpressionParser ep; double branchDistance = 0.0f; try { branchDistance = ep.Evaluate(expressionString.substr(1).insert(0, "0")); } catch (std::exception&) { return false; } relativeAddr = (sint32)branchDistance; return true; } return false; } bool _ppcAssembler_processBranchOperandS16(PPCAssemblerContext& internalCtx, sint32 operandIndex) { sint32 opTextIdx; if (_ppcAssembler_getOperandTextIndex(internalCtx, operandIndex, opTextIdx) == false) return false; if (opTextIdx < 0) return true; // skipped operand std::string expressionString(internalCtx.listOperandStr[opTextIdx].str); sint32 relativeAddr; if (_ppcAssembler_isConstantBranchTargetExpr(expressionString, relativeAddr)) { if (relativeAddr < -32768 || relativeAddr > 32767) { sprintf(_assemblerErrorMessageDepr, "Branch target out of range"); ppcAssembler_setError(internalCtx.ctx, _assemblerErrorMessageDepr); return false; } if (relativeAddr&3) { sprintf(_assemblerErrorMessageDepr, "Branch target must be aligned to 4"); ppcAssembler_setError(internalCtx.ctx, _assemblerErrorMessageDepr); return false; } internalCtx.opcode |= (relativeAddr & 0xFFFC); return true; } // create reloc internalCtx.ctx->list_relocs.emplace_back(PPCASM_RELOC::BRANCH_S16, expressionString, 0, 0, 0); return true; } bool _ppcAssembler_processBranchOperandS26(PPCAssemblerContext& internalCtx, sint32 operandIndex) { sint32 opTextIdx; if (_ppcAssembler_getOperandTextIndex(internalCtx, operandIndex, opTextIdx) == false) return false; if (opTextIdx < 0) return true; // skipped operand std::string expressionString(internalCtx.listOperandStr[opTextIdx].str); sint32 relativeAddr; if (_ppcAssembler_isConstantBranchTargetExpr(expressionString, relativeAddr)) { if (relativeAddr < -33554432 || relativeAddr > 33554431) { ppcAssembler_setError(internalCtx.ctx, "Branch target out of range"); return false; } if (relativeAddr & 3) { ppcAssembler_setError(internalCtx.ctx, "Branch target must be aligned to 4"); return false; } internalCtx.opcode |= (relativeAddr & 0x3FFFFFC); return true; } // create reloc internalCtx.ctx->list_relocs.emplace_back(PPCASM_RELOC::BRANCH_S26, expressionString, 0, 0, 0); return true; } void _ppcAssembler_setAlignment(PPCAssemblerContext& internalInfo, uint32 alignment) { if (internalInfo.ctx->forceNoAlignment) { internalInfo.ctx->alignmentRequirement = 1; internalInfo.ctx->alignmentPaddingSize = 0; internalInfo.ctx->virtualAddressAligned = internalInfo.ctx->virtualAddress; return; } internalInfo.ctx->alignmentRequirement = alignment; if (alignment == 0) { internalInfo.ctx->alignmentPaddingSize = 0; internalInfo.ctx->virtualAddressAligned = internalInfo.ctx->virtualAddress; return; } uint32 alignedVA = (internalInfo.ctx->virtualAddress + alignment - 1) & ~(alignment - 1); internalInfo.ctx->alignmentPaddingSize = alignedVA - internalInfo.ctx->virtualAddress; internalInfo.ctx->virtualAddressAligned = alignedVA; } enum class ASM_DATA_DIRECTIVE { NONE, FLOAT, DOUBLE, U32, U16, U8, // alias to .string }; bool _ppcAssembler_emitDataDirective(PPCAssemblerContext& internalInfo, ASM_DATA_DIRECTIVE dataDirective) { PPCASM_RELOC relocType; switch (dataDirective) { case ASM_DATA_DIRECTIVE::FLOAT: relocType = PPCASM_RELOC::FLOAT; break; case ASM_DATA_DIRECTIVE::DOUBLE: relocType = PPCASM_RELOC::DOUBLE; break; case ASM_DATA_DIRECTIVE::U32: relocType = PPCASM_RELOC::U32; break; case ASM_DATA_DIRECTIVE::U16: relocType = PPCASM_RELOC::U16; break; case ASM_DATA_DIRECTIVE::U8: relocType = PPCASM_RELOC::U8; break; default: cemu_assert_debug(false); return false; } uint32 elementSize = 0; if (relocType == PPCASM_RELOC::FLOAT) elementSize = 4; else if (relocType == PPCASM_RELOC::DOUBLE) elementSize = 8; else if (relocType == PPCASM_RELOC::U32) elementSize = 4; else if (relocType == PPCASM_RELOC::U16) elementSize = 2; else if (relocType == PPCASM_RELOC::U8) elementSize = 1; else cemu_assert_debug(false); _ppcAssembler_setAlignment(internalInfo, elementSize); size_t elementCount = internalInfo.listOperandStr.size(); internalInfo.ctx->outputData.reserve(elementSize * elementCount); size_t writeIndex = 0; for (size_t i = 0; i < elementCount; i++) { std::string_view expressionStr = internalInfo.listOperandStr[i].str; // handle string constants if (internalInfo.listOperandStr[i].str.size() >= 1 && expressionStr[0] == '"') { if (dataDirective != ASM_DATA_DIRECTIVE::U8) { ppcAssembler_setError(internalInfo.ctx, "Strings constants are only allowed in .byte or .string data directives"); return false; } if (expressionStr.size() < 2 || expressionStr[expressionStr.size()-1] != '"') { ppcAssembler_setError(internalInfo.ctx, "String constants must end with a quotation mark. Example: \"text\""); return false; } // write string bytes + null-termination character size_t strConstantLength = expressionStr.size() - 2; internalInfo.ctx->outputData.insert(internalInfo.ctx->outputData.end(), expressionStr.data() + 1, expressionStr.data() + 1 + strConstantLength); internalInfo.ctx->outputData.emplace_back(0); continue; } // numeric constants internalInfo.ctx->outputData.resize(writeIndex + elementSize); uint8* elementPtr = internalInfo.ctx->outputData.data() + writeIndex; for (uint32 b = 0; b < elementSize; b++) { internalInfo.ctx->outputData[writeIndex] = 0; writeIndex++; } ExpressionParser ep; if (ep.IsConstantExpression(expressionStr)) { double solution = ep.Evaluate(expressionStr); switch (relocType) { case PPCASM_RELOC::U32: *(uint32be*)elementPtr = (uint32)solution; break; case PPCASM_RELOC::U16: *(uint16be*)elementPtr = (uint16)solution; break; case PPCASM_RELOC::U8: *(uint8be*)elementPtr = (uint8)solution; break; case PPCASM_RELOC::DOUBLE: *(float64be*)elementPtr = solution; break; case PPCASM_RELOC::FLOAT: *(float32be*)elementPtr = (float)solution; break; default: cemu_assert_debug(false); } } else { // generate reloc if we cant resolve immediately internalInfo.ctx->list_relocs.emplace_back(relocType, std::string(internalInfo.listOperandStr[i].str), (uint32)(elementPtr - internalInfo.ctx->outputData.data()), 0, 0); } } return true; } void _ppcAssembler_emitAlignDirective(PPCAssemblerContext& internalInfo, sint32 alignmentValue) { _ppcAssembler_setAlignment(internalInfo, 1); uint32 currentAddr = internalInfo.ctx->virtualAddress; while ((currentAddr % (uint32)alignmentValue)) { internalInfo.ctx->outputData.emplace_back(0); currentAddr++; } } void _ppcAssembler_translateAlias(boost::static_string<32>& instructionName) { if (instructionName.compare("BNL") == 0) instructionName.assign("BGT"); if (instructionName.compare("BNG") == 0) instructionName.assign("BLE"); } bool ppcAssembler_assembleSingleInstruction(char const* text, PPCAssemblerInOut* ctx) { PPCAssemblerContext internalInfo; internalInfo.ctx = ctx; // tokenize input char const* currentPtr = text; char const* startPtr = text; char const* endPtr = startPtr+strlen(startPtr); // cut off comments for (const char* itrPtr = startPtr; itrPtr < endPtr; itrPtr++) { if (*itrPtr == '#') { endPtr = itrPtr; break; } } // trim whitespaces at end and beginning while (endPtr > currentPtr) { if (endPtr[-1] != ' ' && endPtr[-1] != '\t') break; endPtr--; } while (currentPtr < endPtr) { if (currentPtr[0] != ' ' && currentPtr[0] != '\t') break; currentPtr++; } // parse name of instruction boost::static_string<32> instructionName; while (*currentPtr != ' ' && *currentPtr != '\t' && currentPtr < endPtr) { if (instructionName.size() >= instructionName.capacity()) { ppcAssembler_setError(ctx, "Instruction name exceeds maximum allowed length"); return false; } instructionName.push_back((char)toupper(*currentPtr)); currentPtr++; } if (instructionName.empty()) { ppcAssembler_setError(ctx, "Instruction name is invalid"); return false; } // handle branch hint suffix bool hasBranchHint = false; bool branchHintTaken = false; // '+' -> true, '-' -> false if (instructionName.back() == '+') { hasBranchHint = true; branchHintTaken = true; instructionName.pop_back(); } if (instructionName.back() == '-') { hasBranchHint = true; branchHintTaken = false; instructionName.pop_back(); } // handle instruction name aliases _ppcAssembler_translateAlias(instructionName); // parse operands internalInfo.listOperandStr.clear(); bool isInString = false; while (currentPtr < endPtr) { currentPtr++; startPtr = currentPtr; // find end of operand while (currentPtr < endPtr) { if (*currentPtr == '"') isInString=!isInString; if (*currentPtr == ',' && !isInString) break; currentPtr++; } // trim whitespaces at the beginning and end const char* operandStartPtr = startPtr; const char* operandEndPtr = currentPtr; while (operandStartPtr < endPtr) { if (*operandStartPtr != ' ' && *operandStartPtr != '\t') break; operandStartPtr++; } while (operandEndPtr > operandStartPtr) { if (operandEndPtr[-1] != ' ' && operandEndPtr[-1] != '\t') break; operandEndPtr--; } internalInfo.listOperandStr.emplace_back(operandStartPtr, operandEndPtr); } // check for data directives ASM_DATA_DIRECTIVE dataDirective = ASM_DATA_DIRECTIVE::NONE; if (instructionName.compare(".FLOAT") == 0) dataDirective = ASM_DATA_DIRECTIVE::FLOAT; else if (instructionName.compare(".DOUBLE") == 0) dataDirective = ASM_DATA_DIRECTIVE::DOUBLE; else if (instructionName.compare(".INT") == 0 || instructionName.compare(".UINT") == 0 || instructionName.compare(".PTR") == 0 || instructionName.compare(".U32") == 0 || instructionName.compare(".LONG") == 0) dataDirective = ASM_DATA_DIRECTIVE::U32; else if (instructionName.compare(".WORD") == 0 || instructionName.compare(".U16") == 0 || instructionName.compare(".SHORT") == 0) dataDirective = ASM_DATA_DIRECTIVE::U16; else if (instructionName.compare(".BYTE") == 0 || instructionName.compare(".STRING") == 0 || instructionName.compare(".U8") == 0 || instructionName.compare(".CHAR") == 0) dataDirective = ASM_DATA_DIRECTIVE::U8; if (dataDirective != ASM_DATA_DIRECTIVE::NONE) { if (internalInfo.listOperandStr.size() < 1) { ppcAssembler_setError(ctx, fmt::format("Value expected after data directive {}", instructionName.c_str())); return false; } return _ppcAssembler_emitDataDirective(internalInfo, dataDirective); } // handle .align directive if (instructionName.compare(".ALIGN") == 0) { // handle align data directive if (internalInfo.listOperandStr.size() != 1) { ppcAssembler_setError(ctx, ".align directive must have exactly one operand"); return false; } ExpressionParser ep; try { if (ep.IsConstantExpression(internalInfo.listOperandStr[0].str)) { sint32 alignmentValue = ep.Evaluate<sint32>(internalInfo.listOperandStr[0].str); if (alignmentValue <= 0 || alignmentValue >= 256) { ppcAssembler_setError(ctx, fmt::format("Alignment value \'{}\' is not within the allowed range (1-256)", alignmentValue)); return false; } _ppcAssembler_emitAlignDirective(internalInfo, alignmentValue); return true; } else { ppcAssembler_setError(ctx, fmt::format("Expression \'{}\' for .align directive is not a constant", internalInfo.listOperandStr[0].str)); return false; } } catch (std::exception* e) { ppcAssembler_setError(ctx, fmt::format("Expression \'{}\' for .align directive could not be evaluated. Error: {}", internalInfo.listOperandStr[0].str, e->what())); return false; } } // find match in instruction definition table PPCInstructionDef* iDef = nullptr; for (sint32 i = 0; i < sizeof(ppcInstructionTable) / sizeof(PPCInstructionDef); i++) { PPCInstructionDef* instr = ppcInstructionTable + i; if (instructionName.compare(ppcAssembler_getInstructionName(instr->ppcAsmOp)) == 0) { iDef = instr; internalInfo.iDef = iDef; break; } } if (iDef == nullptr) { ppcAssembler_setError(ctx, fmt::format("Instruction \'{}\' is unknown or not supported", instructionName.c_str())); return false; } // build opcode _ppcAssembler_setAlignment(internalInfo, 4); uint32 opcMask; uint32 opcBits; ppcAssembler_buildOpcMask(iDef, opcMask, opcBits); internalInfo.opcode = opcBits & opcMask; internalInfo.opcode |= (iDef->compareBits&iDef->maskBits); // handle operands if (iDef->instructionForm == OP_FORM_DYNAMIC) { for (size_t i = 0; i < iDef->encodedOperands.size(); i++) { bool r = std::visit([&](auto&& op) -> bool { return op.AssembleOperand(&internalInfo, iDef, internalInfo.opcode, i); }, iDef->encodedOperands[i]); if (!r) return false; } for(auto& it : iDef->constraints) { std::visit([&](auto&& op) { op.AssembleConstraint(&internalInfo, iDef, internalInfo.opcode); }, it); } } else if (iDef->instructionForm == OP_FORM_NO_OPERAND) { // do nothing } else if (iDef->instructionForm == OP_FORM_OP3_A_CMP) { if (internalInfo.listOperandStr.size() == 2) { // implicit cr0 if (_ppcAssembler_processGPROperand(internalInfo, 0, 16) == false) return false; if (_ppcAssembler_processGPROperand(internalInfo, 1, 11) == false) return false; } else { if (_ppcAssembler_processCROperand(internalInfo, 0, 21, true) == false) return false; if (_ppcAssembler_processGPROperand(internalInfo, 1, 16) == false) return false; if (_ppcAssembler_processGPROperand(internalInfo, 2, 11) == false) return false; } } else if (iDef->instructionForm == OP_FORM_CMP_SIMM) { if (internalInfo.listOperandStr.size() == 2) { // implicit cr0 if (_ppcAssembler_processGPROperand(internalInfo, 0, 16) == false) return false; if (_ppcAssembler_processImmediateOperandS16(internalInfo, 1, 0) == false) return false; } else { if (_ppcAssembler_processCROperand(internalInfo, 0, 21, true) == false) return false; if (_ppcAssembler_processGPROperand(internalInfo, 1, 16) == false) return false; if (_ppcAssembler_processImmediateOperandS16(internalInfo, 2, 0) == false) return false; } } else if (iDef->instructionForm == OP_FORM_OP3_A_IMM) { if (_ppcAssembler_processGPROperand(internalInfo, 0, 16) == false) return false; if (_ppcAssembler_processGPROperand(internalInfo, 1, 21) == false) return false; if (_ppcAssembler_processImmediateOperandU5(internalInfo, _getOpIndex(iDef, 2), 11) == false) return false; } else if (iDef->instructionForm == OP_FORM_X_FP_CMP) { if (internalInfo.listOperandStr.size() == 2) { // implicit cr0 if (_ppcAssembler_processFPROperand(internalInfo, 0, 16) == false) return false; if (_ppcAssembler_processFPROperand(internalInfo, 1, 11) == false) return false; } else { if (_ppcAssembler_processCROperand(internalInfo, 0, 21, true) == false) return false; if (_ppcAssembler_processFPROperand(internalInfo, 1, 16) == false) return false; if (_ppcAssembler_processFPROperand(internalInfo, 2, 11) == false) return false; } } else if (iDef->instructionForm == OP_FORM_RLWINM) { if (_ppcAssembler_processGPROperand(internalInfo, 0, 16) == false) return false; if (_ppcAssembler_processGPROperand(internalInfo, 1, 21) == false) return false; if (_ppcAssembler_processImmediateOperandU5(internalInfo, 2, 11) == false) return false; if (_ppcAssembler_processImmediateOperandU5(internalInfo, 3, 6) == false) return false; if (_ppcAssembler_processImmediateOperandU5(internalInfo, 4, 1) == false) return false; } else if (iDef->instructionForm == OP_FORM_RLWINM_EXTENDED) { if (_ppcAssembler_processGPROperand(internalInfo, 0, 16) == false) return false; if (_ppcAssembler_processGPROperand(internalInfo, 1, 21) == false) return false; uint8 SH = 0; uint8 MB = 0; uint8 ME = 0; if (internalInfo.iDef->ppcAsmOp == PPCASM_OP_EXTLWI || internalInfo.iDef->ppcAsmOp == PPCASM_OP_EXTLWI_) { sint8 n, b; if (!_ppcAssembler_processImmediateOperandU5Const(internalInfo, 2, n)) return false; if (!_ppcAssembler_processImmediateOperandU5Const(internalInfo, 3, b)) return false; SH = b; MB = 0; ME = n - 1; } else if (internalInfo.iDef->ppcAsmOp == PPCASM_OP_EXTRWI || internalInfo.iDef->ppcAsmOp == PPCASM_OP_EXTRWI_) { sint8 n, b; if (!_ppcAssembler_processImmediateOperandU5Const(internalInfo, 2, n)) return false; if (!_ppcAssembler_processImmediateOperandU5Const(internalInfo, 3, b)) return false; SH = b + n; MB = 32 - n; ME = 31; } else if (internalInfo.iDef->ppcAsmOp == PPCASM_OP_SLWI || internalInfo.iDef->ppcAsmOp == PPCASM_OP_SLWI_) { sint8 n; if (!_ppcAssembler_processImmediateOperandU5Const(internalInfo, 2, n)) return false; SH = n; MB = 0; ME = 31 - n; } else if (internalInfo.iDef->ppcAsmOp == PPCASM_OP_SRWI || internalInfo.iDef->ppcAsmOp == PPCASM_OP_SRWI_) { sint8 n; if (!_ppcAssembler_processImmediateOperandU5Const(internalInfo, 2, n)) return false; SH = 32 - n; MB = n; ME = 31; } else if (internalInfo.iDef->ppcAsmOp == PPCASM_OP_CLRLWI || internalInfo.iDef->ppcAsmOp == PPCASM_OP_CLRLWI_) { sint8 n; if (!_ppcAssembler_processImmediateOperandU5Const(internalInfo, 2, n)) return false; SH = 0; MB = n; ME = 31; } else if (internalInfo.iDef->ppcAsmOp == PPCASM_OP_CLRRWI || internalInfo.iDef->ppcAsmOp == PPCASM_OP_CLRRWI_) { sint8 n; if (!_ppcAssembler_processImmediateOperandU5Const(internalInfo, 2, n)) return false; SH = 0; MB = 0; ME = 31 - n; } else { cemu_assert_debug(false); } internalInfo.opcode |= (SH << 11); internalInfo.opcode |= (MB << 6); internalInfo.opcode |= (ME << 1); } else if (iDef->instructionForm == OP_FORM_RLWNM) { if (_ppcAssembler_processGPROperand(internalInfo, 0, 16) == false) return false; if (_ppcAssembler_processGPROperand(internalInfo, 1, 21) == false) return false; if (_ppcAssembler_processGPROperand(internalInfo, 2, 11) == false) return false; if (_ppcAssembler_processImmediateOperandU5(internalInfo, 3, 6) == false) return false; if (_ppcAssembler_processImmediateOperandU5(internalInfo, 4, 1) == false) return false; } else if (iDef->instructionForm == OP_FORM_RLWNM_EXTENDED) { if (_ppcAssembler_processGPROperand(internalInfo, 0, 16) == false) return false; if (_ppcAssembler_processGPROperand(internalInfo, 1, 21) == false) return false; if (_ppcAssembler_processGPROperand(internalInfo, 2, 11) == false) return false; uint32 MB = 0, ME = 0; if (internalInfo.iDef->ppcAsmOp == PPCASM_OP_ROTLW || internalInfo.iDef->ppcAsmOp == PPCASM_OP_ROTLW_) { MB = 0; ME = 31; } internalInfo.opcode |= (MB << 6); internalInfo.opcode |= (ME << 1); } else if (iDef->instructionForm == OP_FORM_BRANCH_S16) { if (iDef->ppcAsmOp == PPCASM_OP_BC) { // generic conditional branch // BC <BO>, <BI>, <dst> sint8 bo; if (_ppcAssembler_processImmediateOperandU5Const(internalInfo, 0, bo) == false) return false; if (_ppcAssembler_processBIOperand(internalInfo, 1, 16) == false) return false; if (_ppcAssembler_processBranchOperandS16(internalInfo, 2) == false) return false; internalInfo.opcode |= (bo << 21); } else { // BLE, BGT etc. if (internalInfo.listOperandStr.size() == 2) { // explicit CR if (_ppcAssembler_processCROperand(internalInfo, 0, 16, true) == false) return false; if (_ppcAssembler_processBranchOperandS16(internalInfo, 1) == false) return false; } else { if (_ppcAssembler_processBranchOperandS16(internalInfo, 0) == false) return false; } if (hasBranchHint) internalInfo.opcode |= (1 << 21); } } else if (iDef->instructionForm == OP_FORM_BRANCH_S24) { if (_ppcAssembler_processBranchOperandS26(internalInfo, 0) == false) return false; } else if (iDef->instructionForm == OP_FORM_XL_CR) { if (_ppcAssembler_processBIOperand(internalInfo, 0, 21) == false) return false; if (_ppcAssembler_processBIOperand(internalInfo, 1, 16) == false) return false; if (_ppcAssembler_processBIOperand(internalInfo, 2, 11) == false) return false; } else { cemu_assert_debug(false); // unsupported instruction form return false; } ctx->outputData.resize(4); ctx->outputData[0] = (uint8)((internalInfo.opcode >> 24) & 0xFF); ctx->outputData[1] = (uint8)((internalInfo.opcode >> 16) & 0xFF); ctx->outputData[2] = (uint8)((internalInfo.opcode >> 8) & 0xFF); ctx->outputData[3] = (uint8)((internalInfo.opcode >> 0) & 0xFF); return true; } void _testAsm(uint32 expected, const char* iText) { PPCAssemblerInOut ctx{}; ctx.virtualAddress = 0; if (!ppcAssembler_assembleSingleInstruction(iText, &ctx)) { cemu_assert_debug(false); return; } cemu_assert_debug(ctx.outputData.size() == 4); uint32 opcode = 0; opcode |= ((uint32)ctx.outputData[0] << 24); opcode |= ((uint32)ctx.outputData[1] << 16); opcode |= ((uint32)ctx.outputData[2] << 8); opcode |= ((uint32)ctx.outputData[3] << 0); cemu_assert_debug(expected == opcode); } void _testAsmFail(const char* iText) { PPCAssemblerInOut ctx{}; ctx.virtualAddress = 0; if (!ppcAssembler_assembleSingleInstruction(iText, &ctx)) return; cemu_assert_debug(false); // should fail } void _testAsmArray(std::vector<uint8> expectedArray, const char* iText) { PPCAssemblerInOut ctx{}; ctx.virtualAddress = 0; if (!ppcAssembler_assembleSingleInstruction(iText, &ctx)) { cemu_assert_debug(false); return; } cemu_assert_debug(ctx.outputData.size() == expectedArray.size()); for (size_t offset = 0; offset < expectedArray.size(); offset++) { cemu_assert_debug(ctx.outputData[offset] == expectedArray[offset]); } } void ppcAsmTestDisassembler() { cemu_assert_debug(_CanStoreInteger(5, 10, false)); cemu_assert_debug(_CanStoreInteger(1023, 10, false)); cemu_assert_debug(!_CanStoreInteger(1024, 10, false)); cemu_assert_debug(_CanStoreInteger(511, 10, true)); cemu_assert_debug(!_CanStoreInteger(512, 10, true)); cemu_assert_debug(_CanStoreInteger(-511, 10, true)); cemu_assert_debug(_CanStoreInteger(-512, 10, true)); cemu_assert_debug(!_CanStoreInteger(-513, 10, true)); PPCDisassembledInstruction disasm; auto disassemble = [&](uint32 opcode, PPCASM_OP ppcAsmCode) { disasm = { 0 }; ppcAssembler_disassemble(0x10000000, opcode, &disasm); cemu_assert_debug(disasm.ppcAsmCode == ppcAsmCode); }; auto checkOperandMask = [&](bool op0 = false, bool op1 = false, bool op2 = false, bool op3 = false) { bool hasOp0 = (disasm.operandMask & (1 << 0)); bool hasOp1 = (disasm.operandMask & (1 << 1)); bool hasOp2 = (disasm.operandMask & (1 << 2)); bool hasOp3 = (disasm.operandMask & (1 << 3)); cemu_assert_debug(hasOp0 == op0); cemu_assert_debug(hasOp1 == op1); cemu_assert_debug(hasOp2 == op2); cemu_assert_debug(hasOp3 == op3); }; auto checkOpCR = [&](size_t index, uint8 crIndex) { cemu_assert_debug(disasm.operand[index].type == PPCASM_OPERAND_TYPE_CR); cemu_assert_debug(disasm.operand[index].registerIndex == crIndex); }; auto checkOpCRBit = [&](size_t index, uint8 crIndex) { cemu_assert_debug(disasm.operand[index].type == PPCASM_OPERAND_TYPE_CR_BIT); cemu_assert_debug(disasm.operand[index].registerIndex == crIndex); }; auto checkOpFPR = [&](size_t index, uint8 fprIndex) { cemu_assert_debug(disasm.operand[index].type == PPCASM_OPERAND_TYPE_FPR); cemu_assert_debug(disasm.operand[index].registerIndex == fprIndex); }; auto checkOpGPR = [&](size_t index, uint8 gprIndex) { cemu_assert_debug(disasm.operand[index].type == PPCASM_OPERAND_TYPE_GPR); cemu_assert_debug(disasm.operand[index].registerIndex == gprIndex); }; auto checkOpImm = [&](size_t index, sint32 imm) { cemu_assert_debug(disasm.operand[index].type == PPCASM_OPERAND_TYPE_IMM); cemu_assert_debug(disasm.operand[index].immS32 == imm); }; auto checkOpBranchDst = [&](size_t index, sint32 relOffset) { cemu_assert_debug(disasm.operand[index].type == PPCASM_OPERAND_TYPE_CIMM); cemu_assert_debug(disasm.operand[index].immU32 == 0x10000000 + relOffset); }; auto checkBranchHint = [&](bool isSet) { cemu_assert_debug(disasm.branchHintBitSet == isSet); }; // addi / subi _testAsm(0x3863FFFF, "addi r3, r3, -1"); _testAsm(0x3863FFFF, "subi r3, r3, 1"); _testAsm(0x387E0134, "addi r3, r30, 0x134"); _testAsm(0x387E0134, "subi r3, r30, 0-0x134"); disassemble(0x387E0134, PPCASM_OP_ADDI); checkOperandMask(true, true, true); checkOpGPR(0, 3); checkOpGPR(1, 30); checkOpImm(2, 0x134); // mulli _testAsm(0x1D1E0005, "mulli r8, r30, 5"); disassemble(0x1D1E0005, PPCASM_OP_MULLI); checkOperandMask(true, true, true); checkOpGPR(0, 8); checkOpGPR(1, 30); checkOpImm(2, 5); // mulli _testAsm(0x1CFEFFF8, "mulli r7, r30, 0-(2 + 2 + 2 + 2)"); // -8 disassemble(0x1CFEFFF8, PPCASM_OP_MULLI); checkOperandMask(true, true, true); checkOpGPR(0, 7); checkOpGPR(1, 30); checkOpImm(2, -8); // subfic _testAsm(0x2304002F, "subfic r24, r4, 0x2F"); disassemble(0x2304002F, PPCASM_OP_SUBFIC); checkOperandMask(true, true, true); checkOpGPR(0, 24); checkOpGPR(1, 4); checkOpImm(2, 0x2F); // fcmpu cr7, f1, f0 _testAsm(0xFF810000, "fcmpu cr7, f1, f0"); disassemble(0xFF810000, PPCASM_OP_FCMPU); checkOperandMask(true, true, true); checkOpCR(0, 7); checkOpFPR(1, 1); checkOpFPR(2, 0); // fcmpu cr0, f1, f0 _testAsm(0xFC010000, "fcmpu cr0, f1, f0"); disassemble(0xFC010000, PPCASM_OP_FCMPU); checkOperandMask(true, true, true); checkOpCR(0, 0); checkOpFPR(1, 1); checkOpFPR(2, 0); // cmpwi r9, -1 _testAsm(0x2C09FFFF, "cmpwi r9, -1"); disassemble(0x2C09FFFF, PPCASM_OP_CMPWI); checkOperandMask(false, true, true); checkOpGPR(1, 9); checkOpImm(2, -1); // cmpwi cr7, r9, 0 _testAsm(0x2F890000, "cmpwi cr7, r9, 0"); disassemble(0x2F890000, PPCASM_OP_CMPWI); checkOperandMask(true, true, true); checkOpCR(0, 7); checkOpGPR(1, 9); checkOpImm(2, 0); // cmplwi r3, 0xF _testAsm(0x2803000F, "cmplwi r3, 0xF"); disassemble(0x2803000F, PPCASM_OP_CMPLWI); checkOperandMask(false, true, true); checkOpGPR(1, 3); checkOpImm(2, 0xF); // cmpw cr7, r4, r10 _testAsm(0x7F845000, "cmpw cr7, r4, r10"); disassemble(0x7F845000, PPCASM_OP_CMPW); checkOperandMask(true, true, true); checkOpCR(0, 7); checkOpGPR(1, 4); checkOpGPR(2, 10); // cmplw cr7, r31, r9 _testAsm(0x7F9F4840, "cmplw cr7, r31, r9"); disassemble(0x7F9F4840, PPCASM_OP_CMPLW); checkOperandMask(true, true, true); checkOpCR(0, 7); checkOpGPR(1, 31); checkOpGPR(2, 9); // cmplw r24, r28 _testAsm(0x7C18E040, "cmplw r24, r28"); disassemble(0x7C18E040, PPCASM_OP_CMPLW); checkOperandMask(false, true, true); checkOpGPR(1, 24); checkOpGPR(2, 28); // b .+0x18 _testAsm(0x48000018, "b .+0x18"); // b 0x10000018 //_testAsm(0x48000018, "b 0x10000018"); // bgt cr7, .+0x40 _testAsm(0x419D0040, "bgt cr7, .+0x40"); disassemble(0x419D0040, PPCASM_OP_BGT); checkOperandMask(true, true); checkOpCR(0, 7); checkOpBranchDst(1, 0x40); checkBranchHint(false); // bnl cr7, .+0x40 (alias to bgt) _testAsm(0x419D0040, "bnl cr7, .+0x40"); // beq cr7, .+0x14 _testAsm(0x419E0014, "beq cr7, .+0x14"); disassemble(0x419E0014, PPCASM_OP_BEQ); checkOperandMask(true, true); checkOpCR(0, 7); checkOpBranchDst(1, 0x14); checkBranchHint(false); // beq .-0x4C _testAsm(0x4182FFB4, "beq .-0x4C"); disassemble(0x4182FFB4, PPCASM_OP_BEQ); checkOperandMask(true); checkOpBranchDst(0, -0x4C); checkBranchHint(false); // beq+ .+8 _testAsm(0x41A20008, "beq+ .+8"); disassemble(0x41A20008, PPCASM_OP_BEQ); checkOperandMask(true, false); checkOpBranchDst(0, +0x8); checkBranchHint(true); // cror _testAsm(0x4F5DF382, "cror 4*cr6+eq, 4*cr7+gt, 4*cr7+eq"); _testAsm(0x4C411B82, "cror eq, gt, so"); disassemble(0x4F5DF382, PPCASM_OP_CROR); checkOperandMask(true, true, true); checkOpCRBit(0, 6 * 4 + 2); checkOpCRBit(1, 7 * 4 + 1); checkOpCRBit(2, 7 * 4 + 2); // slw & srw _testAsm(0x7D202030, "slw r0, r9, r4"); _testAsm(0x7D80FC31, "srw. r0, r12, r31"); disassemble(0x7D202030, PPCASM_OP_SLW); checkOperandMask(true, true, true); checkOpGPR(0, 0); checkOpGPR(1, 9); checkOpGPR(2, 4); // FADD _testAsm(0xFC29502A, "fadd f1, f9, f10"); disassemble(0xFC29502A, PPCASM_OP_FADD); checkOperandMask(true, true, true); checkOpFPR(0, 1); checkOpFPR(1, 9); checkOpFPR(2, 10); // FSUB _testAsm(0xFDAB4028, "fsub f13, f11, f8"); _testAsm(0xFD0D4828, "fsub f8, f13, f9"); disassemble(0xFD0D4828, PPCASM_OP_FSUB); checkOperandMask(true, true, true); checkOpFPR(0, 8); checkOpFPR(1, 13); checkOpFPR(2, 9); // FMUL _testAsm(0xFD4B0332, "fmul f10, f11, f12"); disassemble(0xFD4B0332, PPCASM_OP_FMUL); checkOperandMask(true, true, true); checkOpFPR(0, 10); checkOpFPR(1, 11); checkOpFPR(2, 12); // FDIV _testAsm(0xFD885824, "fdiv f12, f8, f11"); disassemble(0xFD885824, PPCASM_OP_FDIV); checkOperandMask(true, true, true); checkOpFPR(0, 12); checkOpFPR(1, 8); checkOpFPR(2, 11); // FMADD _testAsm(0xFC2A0A3A, "fmadd f1, f10, f8, f1"); _testAsm(0xFC0A0B7A, "fmadd f0, f10, f13, f1"); _testAsm(0xFFE0F33A, "fmadd f31, f0, f12, f30"); disassemble(0xFFE0F33A, PPCASM_OP_FMADD); checkOperandMask(true, true, true, true); checkOpFPR(0, 31); checkOpFPR(1, 0); checkOpFPR(2, 12); checkOpFPR(3, 30); // FNMADDS _testAsm(0xED8A627E, "fnmadds f12, f10, f9, f12"); disassemble(0xED8A627E, PPCASM_OP_FNMADDS); checkOperandMask(true, true, true, true); checkOpFPR(0, 12); checkOpFPR(1, 10); checkOpFPR(2, 9); checkOpFPR(3, 12); // still missing test cases: FNMADD, FMADDS // FMSUB _testAsm(0xFC1C0338, "fmsub f0, f28, f12, f0"); _testAsm(0xFD204B38, "fmsub f9, f0, f12, f9"); disassemble(0xFD204B38, PPCASM_OP_FMSUB); checkOperandMask(true, true, true, true); checkOpFPR(0, 9); checkOpFPR(1, 0); checkOpFPR(2, 12); checkOpFPR(3, 9); // FNMSUB _testAsm(0xFD7DCB3C, "fnmsub f11, f29, f12, f25"); disassemble(0xFD7DCB3C, PPCASM_OP_FNMSUB); checkOperandMask(true, true, true, true); checkOpFPR(0, 11); checkOpFPR(1, 29); checkOpFPR(2, 12); checkOpFPR(3, 25); // FMSUBS _testAsm(0xEE3D5838, "fmsubs f17, f29, f0, f11"); _testAsm(0xEDB84AB8, "fmsubs f13, f24, f10, f9"); disassemble(0xEDB84AB8, PPCASM_OP_FMSUBS); checkOperandMask(true, true, true, true); checkOpFPR(0, 13); checkOpFPR(1, 24); checkOpFPR(2, 10); checkOpFPR(3, 9); // FNMSUBS _testAsm(0xED4951BC, "fnmsubs f10, f9, f6, f10"); _testAsm(0xED253AFC, "fnmsubs f9, f5, f11, f7"); disassemble(0xED253AFC, PPCASM_OP_FNMSUBS); checkOperandMask(true, true, true, true); checkOpFPR(0, 9); checkOpFPR(1, 5); checkOpFPR(2, 11); checkOpFPR(3, 7); // FRSQRTE _testAsm(0xFCE06034, "frsqrte f7, f12"); _testAsm(0xFCC06834, "frsqrte f6, f13"); disassemble(0xFCC06834, PPCASM_OP_FRSQRTE); checkOperandMask(true, true); checkOpFPR(0, 6); checkOpFPR(1, 13); // FRSP _testAsm(0xFFA03018, "frsp f29, f6"); disassemble(0xFFA03018, PPCASM_OP_FRSP); checkOperandMask(true, true); checkOpFPR(0, 29); checkOpFPR(1, 6); // FNEG _testAsm(0xFDA05850, "fneg f13, f11"); disassemble(0xFDA05850, PPCASM_OP_FNEG); checkOperandMask(true, true); checkOpFPR(0, 13); checkOpFPR(1, 11); // FMR _testAsm(0xFCE06090, "fmr f7, f12"); disassemble(0xFCE06090, PPCASM_OP_FMR); checkOperandMask(true, true); checkOpFPR(0, 7); checkOpFPR(1, 12); // FCTIWZ _testAsm(0xFD80401E, "fctiwz f12, f8"); disassemble(0xFD80401E, PPCASM_OP_FCTIWZ); checkOperandMask(true, true); checkOpFPR(0, 12); checkOpFPR(1, 8); // PS_MADD _testAsm(0x1168637A, "ps_madd f11, f8, f13, f12"); disassemble(0x1168637A, PPCASM_OP_PS_MADD); checkOperandMask(true, true, true, true); checkOpFPR(0, 11); checkOpFPR(1, 8); checkOpFPR(2, 13); checkOpFPR(3, 12); // PS_MSUB _testAsm(0x11A55FF8, "ps_msub f13, f5, f31, f11"); disassemble(0x11A55FF8, PPCASM_OP_PS_MSUB); checkOperandMask(true, true, true, true); checkOpFPR(0, 13); checkOpFPR(1, 5); checkOpFPR(2, 31); checkOpFPR(3, 11); // PS_NMADD _testAsm(0x118850FE, "ps_nmadd f12, f8, f3, f10"); disassemble(0x118850FE, PPCASM_OP_PS_NMADD); checkOperandMask(true, true, true, true); checkOpFPR(0, 12); checkOpFPR(1, 8); checkOpFPR(2, 3); checkOpFPR(3, 10); // PS_NMSUB _testAsm(0x112832FC, "ps_nmsub f9, f8, f11, f6"); disassemble(0x112832FC, PPCASM_OP_PS_NMSUB); checkOperandMask(true, true, true, true); checkOpFPR(0, 9); checkOpFPR(1, 8); checkOpFPR(2, 11); checkOpFPR(3, 6); // PS_ADD _testAsm(0x112A582A, "ps_add f9, f10, f11"); disassemble(0x112A582A, PPCASM_OP_PS_ADD); checkOperandMask(true, true, true); checkOpFPR(0, 9); checkOpFPR(1, 10); checkOpFPR(2, 11); // PS_SUB _testAsm(0x11663828, "ps_sub f11, f6, f7"); disassemble(0x11663828, PPCASM_OP_PS_SUB); checkOperandMask(true, true, true); checkOpFPR(0, 11); checkOpFPR(1, 6); checkOpFPR(2, 7); // PS_MUL _testAsm(0x11680332, "ps_mul f11, f8, f12"); disassemble(0x11680332, PPCASM_OP_PS_MUL); checkOperandMask(true, true, true); checkOpFPR(0, 11); checkOpFPR(1, 8); checkOpFPR(2, 12); // PS_DIV _testAsm(0x10A45824, "ps_div f5, f4, f11"); disassemble(0x10A45824, PPCASM_OP_PS_DIV); checkOperandMask(true, true, true); checkOpFPR(0, 5); checkOpFPR(1, 4); checkOpFPR(2, 11); // PS_MERGE10 _testAsm(0x10CC6C20, "ps_merge00 f6, f12, f13"); disassemble(0x10CC6C20, PPCASM_OP_PS_MERGE00); checkOperandMask(true, true, true); checkOpFPR(0, 6); checkOpFPR(1, 12); checkOpFPR(2, 13); // random extra tests _testAsm(0x419D0040, "bgt cr7, .+0x40"); _testAsm(0x50AB042E, "rlwimi r11, r5, 0,16,23"); _testAsm(0xFF810000, "fcmpu cr7, f1, f0"); _testAsm(0xFC010000, "fcmpu cr0, f1, f0"); _testAsm(0x7F845000, "cmpw cr7, r4, r10"); _testAsm(0x2C090000, "cmpwi r9, 0"); // implicit cr0 _testAsm(0x2C090000, "cmpwi cr0, r9, 0"); _testAsm(0x2F9E001F, "cmpwi cr7, r30, 0x1F"); _testAsm(0x7D573850, "subf r10, r23, r7"); _testAsm(0x7D573850, "sub r10, r7, r23"); // alias for subf _testAsm(0x7D862851, "subf. r12, r6, r5"); _testAsm(0x7D7C1896, "mulhw r11, r28, r3"); _testAsm(0x7D436016, "mulhwu r10, r3, r12"); _testAsm(0x7FE318F8, "nor r3, r31, r3"); _testAsm(0x7D29F8F8, "nor r9, r9, r31"); _testAsm(0x7F26C8F8, "nor r6, r25, r25"); _testAsm(0x7F26C8F8, "not r6, r25"); // alias for nor where rA == rB _testAsm(0x7FE4FB78, "mr r4, r31"); // alias for or where rA == rB _testAsm(0x7C7EEAA6, "mfspr r3, spr958"); _testAsm(0x7C78E3A6, "mtspr spr920, r3"); _testAsm(0x7D6802A6, "mflr r11"); _testAsm(0x7E6902A6, "mfctr r19"); _testAsm(0x7D430034, "cntlzw r3, r10"); _testAsm(0x7C640774, "extsb r4, r3"); _testAsm(0x1C8A00B8, "mulli r4, r10, 0xB8"); _testAsm(0x1CFEFFF8, "mulli r7, r30, -8"); _testAsm(0x1CFE8000, "mulli r7, r30, -0x8000"); _testAsm(0x1CFE7FFF, "mulli r7, r30, 0x7FFF"); _testAsmFail("mulli r7, r30, -0x8001"); _testAsmFail("mulli r7, r30, 0x8000"); _testAsm(0x38E0FFFF, "li r7, 0xFFFF"); // li/lis allows both signed and unsigned 16-bit range _testAsm(0x38E0FFFF, "li r7, -1"); _testAsm(0x38E08000, "li r7, -0x8000"); _testAsmFail("li r7, -0x8001"); _testAsmFail("li r7, 0xFFFF+1"); // test set 2 _testAsm(0x7c0903a6, "mtctr r0"); _testAsm(0x7c6903a6, "mtctr r3"); _testAsm(0x7d0903a6, "mtctr r8"); _testAsm(0x7d2903a6, "mtctr r9"); _testAsm(0x7c0803a6, "mtlr r0"); _testAsm(0x7c6803a6, "mtlr r3"); _testAsm(0x7c8803a6, "mtlr r4"); _testAsm(0x7c065896, "mulhw r0, r6, r11"); _testAsm(0x7ce85096, "mulhw r7, r8, r10"); _testAsm(0x7d494096, "mulhw r10, r9, r8"); _testAsm(0x7ca4c016, "mulhwu r5, r4, r24"); _testAsm(0x7ce53016, "mulhwu r7, r5, r6"); _testAsm(0x7d373816, "mulhwu r9, r23, r7"); _testAsm(0x7d664816, "mulhwu r11, r6, r9"); _testAsm(0x1d2ae09e, "mulli r9, r10, -0x1F62"); _testAsm(0x1fe900ff, "mulli r31, r9, 0xFF"); _testAsm(0x1ffefffe, "mulli r31, r30, -2"); _testAsm(0x7e4531d6, "mullw r18, r5, r6"); _testAsm(0x7fe429d6, "mullw r31, r4, r5"); _testAsm(0x7d0951d7, "mullw. r8, r9, r10"); _testAsm(0x7f0941d7, "mullw. r24, r9, r8"); _testAsm(0x7c6600d0, "neg r3, r6"); _testAsm(0x7df600d0, "neg r15, r22"); _testAsm(0x7eeb00d0, "neg r23, r11"); _testAsm(0x7ca428f8, "not r4, r5"); _testAsm(0x7df578f8, "not r21, r15"); _testAsm(0x7fe9f8f8, "not r9, r31"); _testAsm(0x7fc83378, "or r8, r30, r6"); _testAsm(0x7de6a379, "or. r6, r15, r20"); _testAsm(0x7f29fb79, "or. r9, r25, r31"); _testAsm(0x7ceafb38, "orc r10, r7, r31"); _testAsm(0x7fbe4338, "orc r30, r29, r8"); _testAsm(0x63a90001, "ori r9, r29, 1"); _testAsm(0x63c3b46e, "ori r3, r30, 0xB46E"); _testAsm(0x63e4ffff, "ori r4, r31, 0xFFFF"); _testAsm(0x650a8000, "oris r10, r8, 0x8000"); _testAsm(0x676c792e, "oris r12, r27, 0x792E"); _testAsm(0x6788ffff, "oris r8, r28, 0xFFFF"); _testAsm(0x67ea3fe0, "oris r10, r31, 0x3FE0"); _testAsm(0x51231fb8, "rlwimi r3, r9, 3,30,28"); _testAsm(0x5249fefe, "rlwimi r9, r18, 31,27,31"); _testAsm(0x52513a20, "rlwimi r17, r18, 7,8,16"); _testAsm(0x53494420, "rlwimi r9, r26, 8,16,16"); _testAsm(0x53657269, "rlwimi. r5, r27, 14,9,20"); _testAsm(0x546906f2, "rlwinm r9, r3, 0,27,25"); _testAsm(0x55284ad6, "rlwinm r8, r9, 9,11,11"); _testAsm(0x57c90428, "rlwinm r9, r30, 0,16,20"); _testAsm(0x57e5d57a, "rlwinm r5, r31, 26,21,29"); _testAsm(0x57ea34b0, "rlwinm r10, r31, 6,18,24"); _testAsm(0x54e1bbb1, "rlwinm. r1, r7, 23,14,24"); _testAsm(0x550707fb, "rlwinm. r7, r8, 0,31,29"); _testAsm(0x552003f1, "rlwinm. r0, r9, 0,15,24"); _testAsm(0x5527022f, "rlwinm. r7, r9, 0,8,23"); _testAsm(0x55270777, "rlwinm. r7, r9, 0,29,27"); _testAsm(0x552a0777, "rlwinm. r10, r9, 0,29,27"); _testAsm(0x552a07b9, "rlwinm. r10, r9, 0,30,28"); _testAsm(0x5d5f583e, "rotlw r31, r10, r11"); _testAsm(0x5eea703e, "rotlw r10, r23, r14"); _testAsm(0x5f0ab03e, "rotlw r10, r24, r22"); _testAsm(0x541a783e, "rotlwi r26, r0, 15"); _testAsm(0x5488383e, "rotlwi r8, r4, 7"); _testAsm(0x5779683e, "rotlwi r25, r27, 13"); _testAsm(0x54e4c83e, "rotrwi r4, r7, 7"); _testAsm(0x7eeaf830, "slw r10, r23, r31"); _testAsm(0x7f68c030, "slw r8, r27, r24"); _testAsm(0x7fe8f030, "slw r8, r31, r30"); _testAsm(0x7f484831, "slw. r8, r26, r9"); _testAsm(0x7f844031, "slw. r4, r28, r8"); _testAsm(0x57e42036, "slwi r4, r31, 4"); _testAsm(0x57e42834, "slwi r4, r31, 5"); _testAsm(0x57f37820, "slwi r19, r31, 15"); _testAsm(0x5488083d, "slwi. r8, r4, 1"); _testAsm(0x552a3033, "slwi. r10, r9, 6"); _testAsm(0x5647083d, "slwi. r7, r18, 1"); _testAsm(0x7c879e30, "sraw r7, r4, r19"); _testAsm(0x7c891e30, "sraw r9, r4, r3"); _testAsm(0x7fca4e30, "sraw r10, r30, r9"); _testAsm(0x7d380e70, "srawi r24, r9, 1"); _testAsm(0x7c79fe71, "srawi. r25, r3, 0x1F"); _testAsm(0x7fb91e71, "srawi. r25, r29, 3"); _testAsm(0x7cc33c30, "srw r3, r6, r7"); _testAsm(0x7d09e430, "srw r9, r8, r28"); _testAsm(0x7d3d4430, "srw r29, r9, r8"); _testAsm(0x5403d97e, "srwi r3, r0, 5"); _testAsm(0x57dc843e, "srwi r28, r30, 16"); _testAsm(0x552a463f, "srwi. r10, r9, 24"); _testAsm(0x5532c9ff, "srwi. r18, r9, 7"); _testAsm(0x57f8f87f, "srwi. r24, r31, 1"); _testAsm(0x9be80201, "stb r31, 0x201(r8)"); _testAsm(0x9bfafffc, "stb r31, -4(r26)"); _testAsm(0x9bfeffff, "stb r31, -1(r30)"); _testAsm(0x9dc3ffff, "stbu r14, -1(r3)"); _testAsm(0x9e55006f, "stbu r18, 0x6F(r21)"); _testAsm(0x9fdc2008, "stbu r30, 0x2008(r28)"); _testAsm(0x7ce521ee, "stbux r7, r5, r4"); _testAsm(0x7d4919ee, "stbux r10, r9, r3"); _testAsm(0x7f6919ee, "stbux r27, r9, r3"); _testAsm(0x7c0531ae, "stbx r0, r5, r6"); _testAsm(0x7d4941ae, "stbx r10, r9, r8"); _testAsm(0x7fdfe9ae, "stbx r30, r31, r29"); _testAsm(0xdb690038, "stfd f27, 0x38(r9)"); _testAsm(0xdb890040, "stfd f28, 0x40(r9)"); _testAsm(0xde230008, "stfdu f17, 8(r3)"); _testAsm(0x7c1235ae, "stfdx f0, r18, r6"); _testAsm(0x7c1f3dae, "stfdx f0, r31, r7"); _testAsm(0x7c1f45ae, "stfdx f0, r31, r8"); _testAsm(0x7c001fae, "stfiwx f0, 0, r3"); _testAsm(0x7c3e4fae, "stfiwx f1, r30, r9"); _testAsm(0x7fa04fae, "stfiwx f29, 0, r9"); _testAsm(0xd008fffc, "stfs f0, -4(r8)"); _testAsm(0xd3ff1604, "stfs f31, 0x1604(r31)"); _testAsm(0xd41e001c, "stfsu f0, 0x1C(r30)"); _testAsm(0x7d87356e, "stfsux f12, r7, r6"); _testAsm(0x7c104d2e, "stfsx f0, r16, r9"); _testAsm(0x7f5d452e, "stfsx f26, r29, r8"); _testAsm(0xb3bf000e, "sth r29, 0xE(r31)"); _testAsm(0xb3f8fffc, "sth r31, -4(r24)"); _testAsm(0xb3fa0000, "sth r31, 0(r26)"); _testAsm(0xb3fd0000, "sth r31, 0(r29)"); _testAsm(0xb528105a, "sthu r9, 0x105A(r8)"); _testAsm(0xb52afffe, "sthu r9, -2(r10)"); _testAsm(0xb53f0002, "sthu r9, 2(r31)"); _testAsm(0x7c69536e, "sthux r3, r9, r10"); _testAsm(0x7c8a3b6e, "sthux r4, r10, r7"); _testAsm(0x7c0ca32e, "sthx r0, r12, r20"); _testAsm(0x7d242b2e, "sthx r9, r4, r5"); _testAsm(0x7fe93b2e, "sthx r31, r9, r7"); _testAsm(0xbdd0b4d0, "stmw r14, -0x4B30(r16)"); _testAsm(0xbed182d1, "stmw r22, -0x7D2F(r17)"); _testAsm(0x7cbb65aa, "stswi r5, r27, 0xC"); _testAsm(0x7cbe05aa, "stswi r5, r30, 0"); _testAsm(0x91348378, "stw r9, -0x7C88(r20)"); _testAsm(0x93e9fddc, "stw r31, -0x224(r9)"); _testAsm(0x93fe45c8, "stw r31, 0x45C8(r30)"); _testAsm(0x7c604d2c, "stwbrx r3, 0, r9"); _testAsm(0x7d20f52c, "stwbrx r9, 0, r30"); _testAsm(0x7fa04d2c, "stwbrx r29, 0, r9"); _testAsm(0x7d20512d, "stwcx. r9, 0, r10"); _testAsm(0x94650208, "stwu r3, 0x208(r5)"); _testAsm(0x953ffffc, "stwu r9, -4(r31)"); _testAsm(0x97fe0208, "stwu r31, 0x208(r30)"); _testAsm(0x7d21196e, "stwux r9, r1, r3"); _testAsm(0x7d23516e, "stwux r9, r3, r10"); _testAsm(0x7d41496e, "stwux r10, r1, r9"); _testAsm(0x7cbc512e, "stwx r5, r28, r10"); _testAsm(0x7d5ce92e, "stwx r10, r28, r29"); _testAsm(0x7ffee92e, "stwx r31, r30, r29"); _testAsm(0x7c1ec050, "subf r0, r30, r24"); _testAsm(0x7fbee050, "subf r29, r30, r28"); _testAsm(0x7fe91850, "subf r31, r9, r3"); _testAsm(0x7c1e5851, "subf. r0, r30, r11"); _testAsm(0x7fc42851, "subf. r30, r4, r5"); _testAsm(0x7fc74851, "subf. r30, r7, r9"); _testAsm(0x7cffd810, "subfc r7, r31, r27"); _testAsm(0x7d053010, "subfc r8, r5, r6"); _testAsm(0x7d093810, "subfc r8, r9, r7"); _testAsm(0x7f884910, "subfe r28, r8, r9"); _testAsm(0x7fe95110, "subfe r31, r9, r10"); _testAsm(0x7fea4910, "subfe r31, r10, r9"); _testAsm(0x20d0b2d1, "subfic r6, r16, -0x4D2F"); _testAsm(0x2109fc02, "subfic r8, r9, -0x3FE"); _testAsm(0x2144001f, "subfic r10, r4, 0x1F"); _testAsm(0x7c04f278, "xor r4, r0, r30"); _testAsm(0x7c08fa78, "xor r8, r0, r31"); _testAsm(0x7c0b4a78, "xor r11, r0, r9"); _testAsm(0x68640008, "xori r4, r3, 8"); _testAsm(0x68652064, "xori r5, r3, 0x2064"); _testAsm(0x692076c3, "xori r0, r9, 0x76C3"); _testAsm(0x6c0a8000, "xoris r10, r0, 0x8000"); _testAsm(0x6c68ffff, "xoris r8, r3, 0xFFFF"); _testAsm(0x6c617267, "xoris r1, r3, 0x7267"); _testAsm(0x6fe98000, "xoris r9, r31, 0x8000"); _testAsm(0x6fe9f000, "xoris r9, r31, 0xF000"); _testAsm(0x6fe9ff00, "xoris r9, r31, 0xFF00"); _testAsm(0x6fe9ffff, "xoris r9, r31, 0xFFFF"); // data directives _testAsmArray({ 0x00, 0x00, 0x00, 0x01 }, ".int 1"); _testAsmArray({ 0x00, 0x00, 0x00, 0x01, 0x11, 0x22, 0x33, 0x44 }, ".int 1, 0x11223344"); _testAsmArray({ 0x42, 0xf6, 0x00, 0x00 }, ".float 123.0"); _testAsmArray({ 0x7f }, ".byte 0x7f"); _testAsmArray({ 0x74, 0x65, 0x73, 0x74, 0x00 }, ".byte \"test\""); _testAsmArray({ 0x41, 0x42, 0x43, 0x00, 0x74, 0x65, 0x73, 0x74, 0x00 }, ".byte \"ABC\", \"test\""); } void ppcAsmTest() { #ifdef CEMU_DEBUG_ASSERT ppcAsmTestDisassembler(); #endif }
135,218
C++
.cpp
3,224
39.284739
359
0.702672
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,935
FileCache.cpp
cemu-project_Cemu/src/Cemu/FileCache/FileCache.cpp
#include "FileCache.h" #include "util/helpers/helpers.h" #include <mutex> #include <condition_variable> #include "zlib.h" #include "Common/FileStream.h" struct FileCacheAsyncJob { FileCache* fileCache; uint64 name1; uint64 name2; std::vector<uint8> fileData; }; struct _FileCacheAsyncWriter { _FileCacheAsyncWriter() { m_isRunning.store(true); m_fileCacheThread = std::thread(&_FileCacheAsyncWriter::FileCacheThread, this); } ~_FileCacheAsyncWriter() { if (m_isRunning.load()) { m_isRunning.store(false); m_fileCacheCondVar.notify_one(); m_fileCacheThread.join(); } } void AddJob(FileCache* fileCache, const FileCache::FileName& name, const uint8* fileData, sint32 fileSize) { FileCacheAsyncJob async; async.fileCache = fileCache; async.name1 = name.name1; async.name2 = name.name2; async.fileData = { fileData, fileData + fileSize }; std::unique_lock lock(m_fileCacheMutex); m_writeRequests.emplace_back(std::move(async)); lock.unlock(); m_fileCacheCondVar.notify_one(); } private: void FileCacheThread() { SetThreadName("fileCache"); while (true) { std::unique_lock lock(m_fileCacheMutex); while (m_writeRequests.empty()) { m_fileCacheCondVar.wait(lock); if (!m_isRunning.load(std::memory_order::relaxed)) return; } std::vector<FileCacheAsyncJob> requestsCopy; requestsCopy.swap(m_writeRequests); // fast copy & clear lock.unlock(); for (const auto& entry : requestsCopy) { entry.fileCache->AddFile({ entry.name1, entry.name2 }, entry.fileData.data(), (sint32)entry.fileData.size()); } } } std::thread m_fileCacheThread; std::mutex m_fileCacheMutex; std::condition_variable m_fileCacheCondVar; std::vector<FileCacheAsyncJob> m_writeRequests; std::atomic_bool m_isRunning; }FileCacheAsyncWriter; #define FILECACHE_MAGIC_V1 0x8371b694 // used prior to Cemu 1.7.4, only supported caches up to 4GB #define FILECACHE_MAGIC_V2 0x8371b695 // added support for large caches #define FILECACHE_MAGIC_V3 0x8371b696 // introduced in Cemu 1.16.0 (non-WIP). Adds zlib compression #define FILECACHE_HEADER_RESV 128 // number of bytes reserved for the header #define FILECACHE_FILETABLE_NAME1 0xEFEFEFEFEFEFEFEFULL #define FILECACHE_FILETABLE_NAME2 0xFEFEFEFEFEFEFEFEULL #define FILECACHE_FILETABLE_FREE_NAME 0ULL FileCache* FileCache::Create(const fs::path& path, uint32 extraVersion) { FileStream* fs = FileStream::createFile2(path); if (!fs) { cemuLog_log(LogType::Force, "Failed to create cache file \"{}\"", _pathToUtf8(path)); return nullptr; } // init file cache auto* fileCache = new FileCache(); fileCache->fileStream = fs; fileCache->dataOffset = FILECACHE_HEADER_RESV; fileCache->fileTableEntryCount = 32; fileCache->fileTableOffset = 0; fileCache->fileTableSize = sizeof(FileTableEntry) * fileCache->fileTableEntryCount; fileCache->fileTableEntries = (FileTableEntry*)malloc(fileCache->fileTableSize); fileCache->extraVersion = extraVersion; memset(fileCache->fileTableEntries, 0, fileCache->fileTableSize); // file table stores info about itself fileCache->fileTableEntries[0].name1 = FILECACHE_FILETABLE_NAME1; fileCache->fileTableEntries[0].name2 = FILECACHE_FILETABLE_NAME2; fileCache->fileTableEntries[0].fileOffset = fileCache->fileTableOffset; fileCache->fileTableEntries[0].fileSize = fileCache->fileTableSize; // write header fs->writeU32(FILECACHE_MAGIC_V3); fs->writeU32(fileCache->extraVersion); fs->writeU64(fileCache->dataOffset); fs->writeU64(fileCache->fileTableOffset); fs->writeU32(fileCache->fileTableSize); // write file table fs->SetPosition(fileCache->dataOffset+fileCache->fileTableOffset); fs->writeData(fileCache->fileTableEntries, fileCache->fileTableSize); // done return fileCache; } FileCache* FileCache::_OpenExisting(const fs::path& path, bool compareExtraVersion, uint32 extraVersion) { FileStream* fs = FileStream::openFile2(path, true); if (!fs) return nullptr; // read header uint32 headerMagic = 0; fs->readU32(headerMagic); bool isV2 = false; if (headerMagic != FILECACHE_MAGIC_V1 && headerMagic != FILECACHE_MAGIC_V2 && headerMagic != FILECACHE_MAGIC_V3) { delete fs; return nullptr; } if (headerMagic == FILECACHE_MAGIC_V1) { // support for V1 file format removed with the addition of V3 delete fs; return nullptr; } if (headerMagic == FILECACHE_MAGIC_V2) isV2 = true; uint32 headerExtraVersion = 0xFFFFFFFF; fs->readU32(headerExtraVersion); if (compareExtraVersion && headerExtraVersion != extraVersion) { delete fs; return nullptr; } if (!compareExtraVersion) { extraVersion = headerExtraVersion; } uint64 headerDataOffset = 0; uint64 headerFileTableOffset = 0; uint32 headerFileTableSize = 0; fs->readU64(headerDataOffset); fs->readU64(headerFileTableOffset); if (!fs->readU32(headerFileTableSize)) { cemuLog_log(LogType::Force, "\"{}\" is corrupted", _pathToUtf8(path)); delete fs; return nullptr; } uint32 fileTableEntryCount = 0; bool invalidFileTableSize = false; // V2 and V3 fileTableEntryCount = headerFileTableSize / sizeof(FileTableEntry); invalidFileTableSize = (headerFileTableSize % sizeof(FileTableEntry)) != 0; if (invalidFileTableSize) { cemuLog_log(LogType::Force, "\"{}\" is corrupted", _pathToUtf8(path)); delete fs; return nullptr; } // init struct auto* fileCache = new FileCache(); fileCache->fileStream = fs; fileCache->extraVersion = extraVersion; fileCache->dataOffset = headerDataOffset; fileCache->fileTableEntryCount = fileTableEntryCount; fileCache->fileTableOffset = headerFileTableOffset; fileCache->fileTableSize = fileTableEntryCount * sizeof(FileTableEntry); fileCache->fileTableEntries = (FileTableEntry*)malloc(fileTableEntryCount * sizeof(FileTableEntry)); memset(fileCache->fileTableEntries, 0, fileTableEntryCount * sizeof(FileTableEntry)); // read file table fileCache->fileStream->SetPosition(fileCache->dataOffset + fileCache->fileTableOffset); bool incompleteFileTable = false; if (isV2) { // read file table entries in old format incompleteFileTable = fileCache->fileStream->readData(fileCache->fileTableEntries, fileCache->fileTableSize) != fileCache->fileTableSize; // in V2 the extra field wasn't guaranteed to have well defined values for (uint32 i = 0; i < fileTableEntryCount; i++) { fileCache->fileTableEntries[i].flags = FileTableEntry::FLAGS::FLAG_NONE; fileCache->fileTableEntries[i].extraReserved1 = 0; fileCache->fileTableEntries[i].extraReserved2 = 0; fileCache->fileTableEntries[i].extraReserved3 = 0; } } else { incompleteFileTable = fileCache->fileStream->readData(fileCache->fileTableEntries, fileCache->fileTableSize) != fileCache->fileTableSize; } if (incompleteFileTable) { cemuLog_log(LogType::Force, "\"{}\" is corrupted (incomplete file table)", _pathToUtf8(path)); delete fileCache; return nullptr; } return fileCache; } FileCache* FileCache::Open(const fs::path& path, bool allowCreate, uint32 extraVersion) { FileCache* fileCache = _OpenExisting(path, true, extraVersion); if (fileCache) return fileCache; if (!allowCreate) return nullptr; return Create(path, extraVersion); } FileCache* FileCache::Open(const fs::path& path) { return _OpenExisting(path, false, 0); } FileCache::~FileCache() { free(this->fileTableEntries); delete fileStream; } void FileCache::fileCache_updateFiletable(sint32 extraEntriesToAllocate) { // recreate file table with bigger size (optional) this->fileTableEntries[0].name1 = FILECACHE_FILETABLE_FREE_NAME; this->fileTableEntries[0].name2 = FILECACHE_FILETABLE_FREE_NAME; sint32 newFileTableEntryCount = this->fileTableEntryCount + extraEntriesToAllocate; this->fileTableEntries = (FileTableEntry*)realloc(this->fileTableEntries, sizeof(FileTableEntry)*newFileTableEntryCount); for (sint32 f = this->fileTableEntryCount; f < newFileTableEntryCount; f++) { this->fileTableEntries[f].name1 = FILECACHE_FILETABLE_FREE_NAME; this->fileTableEntries[f].name2 = FILECACHE_FILETABLE_FREE_NAME; this->fileTableEntries[f].fileOffset = 0; this->fileTableEntries[f].fileSize = 0; this->fileTableEntries[f].flags = FileTableEntry::FLAGS::FLAG_NONE; this->fileTableEntries[f].extraReserved1 = 0; this->fileTableEntries[f].extraReserved2 = 0; this->fileTableEntries[f].extraReserved3 = 0; } this->fileTableEntryCount = newFileTableEntryCount; this->_addFileInternal(FILECACHE_FILETABLE_NAME1, FILECACHE_FILETABLE_NAME2, (uint8*)this->fileTableEntries, sizeof(FileTableEntry)*newFileTableEntryCount, true); // update file table info in struct if (this->fileTableEntries[0].name1 != FILECACHE_FILETABLE_NAME1 || this->fileTableEntries[0].name2 != FILECACHE_FILETABLE_NAME2) { cemuLog_log(LogType::Force, "Corruption in cache file detected"); assert_dbg(); } this->fileTableOffset = this->fileTableEntries[0].fileOffset; this->fileTableSize = this->fileTableEntries[0].fileSize; // update header fileStream->SetPosition(0); fileStream->writeU32(FILECACHE_MAGIC_V3); fileStream->writeU32(this->extraVersion); fileStream->writeU64(this->dataOffset); fileStream->writeU64(this->fileTableOffset); fileStream->writeU32(this->fileTableSize); } uint8* _fileCache_compressFileData(const uint8* fileData, uint32 fileSize, sint32& compressedSize) { // compress data using zlib deflate // stores the size of the uncompressed file in the first 4 bytes Bytef* uncompressedInput = (Bytef*)fileData; uLongf uncompressedLen = fileSize; uLongf compressedLen = compressBound(fileSize); Bytef* compressedData = (Bytef*)malloc(4 + compressedLen); int zret = compress2(compressedData + 4, &compressedLen, uncompressedInput, uncompressedLen, 4); // level 4 has good compression to performance ratio if (zret != Z_OK) { free(compressedData); return nullptr; } compressedData[0] = ((uint32)fileSize >> 24) & 0xFF; compressedData[1] = ((uint32)fileSize >> 16) & 0xFF; compressedData[2] = ((uint32)fileSize >> 8) & 0xFF; compressedData[3] = ((uint32)fileSize >> 0) & 0xFF; compressedSize = 4 + compressedLen; return compressedData; } bool _uncompressFileData(const uint8* rawData, size_t rawSize, std::vector<uint8>& dataOut) { if (rawSize < 4) { dataOut.clear(); return false; } // get size of uncompressed file uint32 fileSize = 0; fileSize |= ((uint32)rawData[0] << 24); fileSize |= ((uint32)rawData[1] << 16); fileSize |= ((uint32)rawData[2] << 8); fileSize |= ((uint32)rawData[3] << 0); // allocate buffer Bytef* compressedInput = (Bytef*)rawData + 4; uLongf compressedLen = (uLongf)(rawSize - 4); uLongf uncompressedLen = fileSize; dataOut.resize(fileSize); int zret = uncompress2(dataOut.data(), &uncompressedLen, compressedInput, &compressedLen); if (zret != Z_OK) { dataOut.clear(); return false; } if (uncompressedLen != fileSize || compressedLen != (rawSize - 4)) { // uncompressed size does not match stored size dataOut.clear(); return false; } return true; } void FileCache::_addFileInternal(uint64 name1, uint64 name2, const uint8* fileData, sint32 fileSize, bool noCompression) { if (fileSize < 0) return; if (!enableCompression) noCompression = true; // compress data sint32 rawSize = 0; uint8* rawData = nullptr; bool isCompressed = false; if (noCompression) { rawData = (uint8*)fileData; rawSize = fileSize; } else { // compress file rawData = _fileCache_compressFileData(fileData, fileSize, rawSize); if (rawData) { isCompressed = true; } else { rawData = (uint8*)fileData; rawSize = fileSize; } } std::unique_lock lock(this->mutex); // find free entry in file table sint32 entryIndex = -1; // scan for already existing entry for (sint32 i = 0; i < this->fileTableEntryCount; i++) { if (this->fileTableEntries[i].name1 == name1 && this->fileTableEntries[i].name2 == name2) { entryIndex = i; break; } } if (entryIndex == -1) { while (true) { // if no entry exists, search for empty one for (sint32 i = 0; i < this->fileTableEntryCount; i++) { if (this->fileTableEntries[i].name1 == FILECACHE_FILETABLE_FREE_NAME && this->fileTableEntries[i].name2 == FILECACHE_FILETABLE_FREE_NAME) { entryIndex = i; break; } } if (entryIndex == -1) { if (name1 == FILECACHE_FILETABLE_NAME1 && name2 == FILECACHE_FILETABLE_NAME2) { cemuLog_log(LogType::Force, "Error in cache file"); cemu_assert_debug(false); } // no free entry, recreate file table with larger size fileCache_updateFiletable(64); // try again continue; } else break; } } // find free space sint64 currentStartOffset = 0; while (true) { bool hasCollision = false; sint64 currentEndOffset = currentStartOffset + rawSize; FileTableEntry* entry = this->fileTableEntries; FileTableEntry* entryLast = this->fileTableEntries + this->fileTableEntryCount; while (entry < entryLast) { if (entry->name1 == FILECACHE_FILETABLE_FREE_NAME && entry->name2 == FILECACHE_FILETABLE_FREE_NAME) { entry++; continue; } if (currentEndOffset >= (sint64)entry->fileOffset && currentStartOffset < (sint64)(entry->fileOffset + entry->fileSize)) { currentStartOffset = entry->fileOffset + entry->fileSize; hasCollision = true; break; } entry++; } // optimized logic to speed up scanning for free offsets // assumes that most of the time entries are stored in direct succession (holds true more often than not) if (hasCollision && (entry + 1) < entryLast) { entry++; while (entry < entryLast) { if (entry->name1 == FILECACHE_FILETABLE_FREE_NAME && entry->name2 == FILECACHE_FILETABLE_FREE_NAME) { entry++; continue; } if (entry->fileOffset == currentStartOffset) { currentStartOffset = entry->fileOffset + entry->fileSize; entry++; continue; } break; } } // retry in case of collision if (hasCollision == false) break; } // update file table entry this->fileTableEntries[entryIndex].name1 = name1; this->fileTableEntries[entryIndex].name2 = name2; this->fileTableEntries[entryIndex].fileOffset = currentStartOffset; this->fileTableEntries[entryIndex].fileSize = rawSize; this->fileTableEntries[entryIndex].flags = isCompressed ? FileTableEntry::FLAGS::FLAG_COMPRESSED : FileTableEntry::FLAGS::FLAG_NONE; this->fileTableEntries[entryIndex].extraReserved1 = 0; this->fileTableEntries[entryIndex].extraReserved2 = 0; this->fileTableEntries[entryIndex].extraReserved3 = 0; // write file data fileStream->SetPosition(this->dataOffset + currentStartOffset); fileStream->writeData(rawData, rawSize); // write file table entry fileStream->SetPosition(this->dataOffset + this->fileTableOffset + (uint64)(sizeof(FileTableEntry)*entryIndex)); fileStream->writeData(this->fileTableEntries + entryIndex, sizeof(FileTableEntry)); if (isCompressed) free(rawData); } void FileCache::AddFile(const FileName&& name, const uint8* fileData, sint32 fileSize) { this->_addFileInternal(name.name1, name.name2, fileData, fileSize, false); } bool FileCache::DeleteFile(const FileName&& name) { if( name.name1 == FILECACHE_FILETABLE_NAME1 && name.name2 == FILECACHE_FILETABLE_NAME2 ) return false; // prevent filetable from being deleted std::unique_lock lock(this->mutex); FileTableEntry* entry = this->fileTableEntries; FileTableEntry* entryLast = this->fileTableEntries+this->fileTableEntryCount; while( entry < entryLast ) { if( entry->name1 == name.name1 && entry->name2 == name.name2 ) { entry->name1 = FILECACHE_FILETABLE_FREE_NAME; entry->name2 = FILECACHE_FILETABLE_FREE_NAME; entry->fileOffset = 0; entry->fileSize = 0; // store updated entry to file cache size_t entryIndex = entry - this->fileTableEntries; fileStream->SetPosition(this->dataOffset+this->fileTableOffset+(uint64)(sizeof(FileTableEntry)*entryIndex)); fileStream->writeData(this->fileTableEntries+entryIndex, sizeof(FileTableEntry)); return true; } entry++; } return false; } void FileCache::AddFileAsync(const FileName& name, const uint8* fileData, sint32 fileSize) { FileCacheAsyncWriter.AddJob(this, name, fileData, fileSize); } bool FileCache::_getFileDataInternal(const FileTableEntry* entry, std::vector<uint8>& dataOut) { std::vector<uint8> rawData(entry->fileSize); fileStream->SetPosition(this->dataOffset + entry->fileOffset); fileStream->readData(rawData.data(), entry->fileSize); if ((entry->flags&FileTableEntry::FLAG_COMPRESSED) == 0) { // uncompressed std::swap(rawData, dataOut); return true; } // decompress sint32 uncompressedSize = 0; if (!_uncompressFileData(rawData.data(), rawData.size(), dataOut)) { dataOut.clear(); return false; } return true; } bool FileCache::GetFile(const FileName&& name, std::vector<uint8>& dataOut) { std::unique_lock lock(this->mutex); FileTableEntry* entry = this->fileTableEntries; FileTableEntry* entryLast = this->fileTableEntries+this->fileTableEntryCount; while( entry < entryLast ) { if( entry->name1 == name.name1 && entry->name2 == name.name2 ) { return _getFileDataInternal(entry, dataOut); } entry++; } dataOut.clear(); return false; } bool FileCache::GetFileByIndex(sint32 index, uint64* name1, uint64* name2, std::vector<uint8>& dataOut) { if (index < 0 || index >= this->fileTableEntryCount) return false; FileTableEntry* entry = this->fileTableEntries + index; if (this->fileTableEntries == nullptr) { cemuLog_log(LogType::Force, "GetFileByIndex() fileTable is NULL"); return false; } if (entry->name1 == FILECACHE_FILETABLE_FREE_NAME && entry->name2 == FILECACHE_FILETABLE_FREE_NAME) return false; if (entry->name1 == FILECACHE_FILETABLE_NAME1 && entry->name2 == FILECACHE_FILETABLE_NAME2) return false; std::unique_lock lock(this->mutex); if(name1) *name1 = entry->name1; if(name2) *name2 = entry->name2; return _getFileDataInternal(entry, dataOut); } bool FileCache::HasFile(const FileName&& name) { std::unique_lock lock(this->mutex); FileTableEntry* entry = this->fileTableEntries; FileTableEntry* entryLast = this->fileTableEntries + this->fileTableEntryCount; while (entry < entryLast) { if (entry->name1 == name.name1 && entry->name2 == name.name2) return true; entry++; } return false; } sint32 FileCache::GetMaximumFileIndex() { return this->fileTableEntryCount; } sint32 FileCache::GetFileCount() { std::unique_lock lock(this->mutex); sint32 fileCount = 0; FileTableEntry* entry = this->fileTableEntries; FileTableEntry* entryLast = this->fileTableEntries+this->fileTableEntryCount; while( entry < entryLast ) { if( entry->name1 == FILECACHE_FILETABLE_FREE_NAME && entry->name2 == FILECACHE_FILETABLE_FREE_NAME ) { entry++; continue; } if( entry->name1 == FILECACHE_FILETABLE_NAME1 && entry->name2 == FILECACHE_FILETABLE_NAME2 ) { entry++; continue; } fileCount++; entry++; } return fileCount; } void fileCache_test() { FileCache* fc = FileCache::Create("testCache.bin", 0); uint32 time1 = GetTickCount(); char* testString1 = (char*)malloc(1024 * 1024 * 8); char* testString2 = (char*)malloc(1024 * 1024 * 8); char* testString3 = (char*)malloc(1024 * 1024 * 8); for (sint32 f = 0; f < 1024 * 1024 * 8; f++) { testString1[f] = 'a' + (f & 7); testString2[f] = 'd' + (f & 3); testString3[f] = 'f' + (f & 3); } for(sint32 i=0; i<2200; i++) { fc->AddFile({ 0x1000001ULL, (uint64)i }, (uint8*)testString1, 1024 * 1024 * 1); fc->AddFile({ 0x1000002ULL, (uint64)i }, (uint8*)testString2, 1024 * 1024 * 1); fc->AddFile({ 0x1000003ULL, (uint64)i }, (uint8*)testString3, 1024 * 1024 * 1); } uint32 time2 = GetTickCount(); debug_printf("Writing took %dms\n", time2-time1); delete fc; // verify if all entries are still valid FileCache* fcRead = FileCache::Open("testCache.bin", 0); uint32 time3 = GetTickCount(); for(sint32 i=0; i<2200; i++) { std::vector<uint8> fileData; bool r = fcRead->GetFile({ 0x1000001ULL, (uint64)i }, fileData); if (!r || fileData.size() != 1024 * 1024 * 1 || memcmp(fileData.data(), testString1, 1024 * 1024 * 1) != 0) cemu_assert_debug(false); r = fcRead->GetFile({ 0x1000002ULL, (uint64)i }, fileData); if( !r || fileData.size() != 1024 * 1024 * 1 || memcmp(fileData.data(), testString2, 1024 * 1024 * 1) != 0 ) cemu_assert_debug(false); r = fcRead->GetFile({ 0x1000003ULL, (uint64)i }, fileData); if( !r || fileData.size() != 1024 * 1024 * 1 || memcmp(fileData.data(), testString3, 1024 * 1024 * 1) != 0 ) cemu_assert_debug(false); } uint32 time4 = GetTickCount(); debug_printf("Reading took %dms\n", time4-time3); delete fcRead; cemu_assert_debug(false); exit(0); }
20,732
C++
.cpp
621
30.827697
163
0.739774
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,936
napi_ec.cpp
cemu-project_Cemu/src/Cemu/napi/napi_ec.cpp
#include "Common/precompiled.h" #include "napi.h" #include "napi_helper.h" #include "curl/curl.h" #include "Cafe/IOSU/legacy/iosu_crypto.h" #include "Cemu/ncrypto/ncrypto.h" #include "util/crypto/md5.h" #include "config/LaunchSettings.h" #include "config/ActiveSettings.h" #include "config/NetworkSettings.h" #include "pugixml.hpp" #include <charconv> namespace NAPI { /* Service URL manager */ struct CachedServiceUrls { std::string s_serviceURL_ContentPrefixURL; std::string s_serviceURL_UncachedContentPrefixURL; std::string s_serviceURL_EcsURL; std::string s_serviceURL_IasURL; std::string s_serviceURL_CasURL; std::string s_serviceURL_NusURL; }; std::unordered_map<NetworkService, CachedServiceUrls> s_cachedServiceUrlsMap; CachedServiceUrls& GetCachedServiceUrls(NetworkService service) { return s_cachedServiceUrlsMap[service]; } std::string _getNUSUrl(NetworkService service) { auto& cachedServiceUrls = GetCachedServiceUrls(service); if (!cachedServiceUrls.s_serviceURL_NusURL.empty()) return cachedServiceUrls.s_serviceURL_NusURL; switch (service) { case NetworkService::Nintendo: return NintendoURLs::NUSURL; case NetworkService::Pretendo: return PretendoURLs::NUSURL; case NetworkService::Custom: return GetNetworkConfig().urls.NUS; default: return NintendoURLs::NUSURL; } } std::string _getIASUrl(NetworkService service) { auto& cachedServiceUrls = GetCachedServiceUrls(service); if (!cachedServiceUrls.s_serviceURL_IasURL.empty()) return cachedServiceUrls.s_serviceURL_IasURL; switch (service) { case NetworkService::Nintendo: return NintendoURLs::IASURL; case NetworkService::Pretendo: return PretendoURLs::IASURL; case NetworkService::Custom: return GetNetworkConfig().urls.IAS; default: return NintendoURLs::IASURL; } } std::string _getECSUrl(NetworkService service) { // this is the first url queried (GetAccountStatus). The others are dynamically set if provided by the server but will fallback to hardcoded defaults otherwise auto& cachedServiceUrls = GetCachedServiceUrls(service); if (!cachedServiceUrls.s_serviceURL_EcsURL.empty()) return cachedServiceUrls.s_serviceURL_EcsURL; switch (service) { case NetworkService::Nintendo: return NintendoURLs::ECSURL; case NetworkService::Pretendo: return PretendoURLs::ECSURL; case NetworkService::Custom: return GetNetworkConfig().urls.ECS; default: return NintendoURLs::ECSURL; } } std::string _getCCSUncachedUrl(NetworkService service) // used for TMD requests { auto& cachedServiceUrls = GetCachedServiceUrls(service); if (!cachedServiceUrls.s_serviceURL_UncachedContentPrefixURL.empty()) return cachedServiceUrls.s_serviceURL_UncachedContentPrefixURL; switch (service) { case NetworkService::Nintendo: return NintendoURLs::CCSUURL; case NetworkService::Pretendo: return PretendoURLs::CCSUURL; case NetworkService::Custom: return GetNetworkConfig().urls.CCSU; default: return NintendoURLs::CCSUURL; } } std::string _getCCSUrl(NetworkService service) // used for game data downloads { auto& cachedServiceUrls = GetCachedServiceUrls(service); if (!cachedServiceUrls.s_serviceURL_ContentPrefixURL.empty()) return cachedServiceUrls.s_serviceURL_ContentPrefixURL; switch (service) { case NetworkService::Nintendo: return NintendoURLs::CCSURL; case NetworkService::Pretendo: return PretendoURLs::CCSURL; case NetworkService::Custom: return GetNetworkConfig().urls.CCS; default: return NintendoURLs::CCSURL; } } /* NUS */ // request ticket for titles which have a public eTicket (usually updates and system titles) NAPI_NUSGetSystemCommonETicket_Result NUS_GetSystemCommonETicket(AuthInfo& authInfo, uint64 titleId) { NAPI_NUSGetSystemCommonETicket_Result result{}; CurlSOAPHelper soapHelper(authInfo.GetService()); soapHelper.SOAP_initate("nus", _getNUSUrl(authInfo.GetService()), "GetSystemCommonETicket", "1.0"); soapHelper.SOAP_addRequestField("DeviceId", fmt::format("{}", authInfo.getDeviceIdWithPlatform())); soapHelper.SOAP_addRequestField("RegionId", NCrypto::GetRegionAsString(authInfo.region)); soapHelper.SOAP_addRequestField("CountryCode", authInfo.country); soapHelper.SOAP_addRequestField("SerialNo", authInfo.serial); soapHelper.SOAP_addRequestField("TitleId", fmt::format("{:016X}", titleId)); if (!soapHelper.submitRequest()) { result.apiError = NAPI_RESULT::FAILED; return result; } // parse result pugi::xml_document doc; pugi::xml_node responseNode; if (!_parseResponseInit(soapHelper, "GetSystemCommonETicketResponse", responseNode, result, doc, responseNode)) return result; const char* eTicketsStr = responseNode.child_value("CommonETicket"); result.eTicket = NCrypto::base64Decode(eTicketsStr); if (result.eTicket.empty()) { cemuLog_log(LogType::Force, "GetSystemCommonETicketResponse: Invalid eTicket data in response"); result.apiError = NAPI_RESULT::DATA_ERROR; return result; } for (pugi::xml_node certNode : responseNode.children("Certs")) { const char* certStringValue = certNode.child_value(); auto certData = NCrypto::base64Decode(certStringValue); if (certData.empty()) { cemuLog_log(LogType::Force, "GetSystemCommonETicketResponse: Invalid cert data in response"); result.apiError = NAPI_RESULT::DATA_ERROR; return result; } result.certs.emplace_back(NCrypto::base64Decode(certStringValue)); } return result; } /* IAS */ NAPI_IASGetChallenge_Result IAS_GetChallenge(AuthInfo& authInfo) { NAPI_IASGetChallenge_Result result{}; CurlSOAPHelper soapHelper(authInfo.GetService()); soapHelper.SOAP_initate("ias", _getIASUrl(authInfo.GetService()), "GetChallenge", "2.0"); soapHelper.SOAP_addRequestField("DeviceId", fmt::format("{}", authInfo.getDeviceIdWithPlatform())); // not validated but the generated Challenge is bound to this DeviceId soapHelper.SOAP_addRequestField("Region", NCrypto::GetRegionAsString(authInfo.region)); soapHelper.SOAP_addRequestField("Country", authInfo.country); if (!soapHelper.submitRequest()) { result.apiError = NAPI_RESULT::FAILED; return result; } /* parse result */ pugi::xml_document doc; pugi::xml_node responseNode; if (!_parseResponseInit(soapHelper, "GetChallengeResponse", responseNode, result, doc, responseNode)) return result; result.challenge = responseNode.child_value("Challenge"); return result; } NAPI_IASGetRegistrationInfo_Result IAS_GetRegistrationInfo_QueryInfo(AuthInfo& authInfo, std::string challenge) { NAPI_IASGetRegistrationInfo_Result result; CurlSOAPHelper soapHelper(authInfo.GetService()); soapHelper.SOAP_initate("ias", _getIASUrl(authInfo.GetService()), "GetRegistrationInfo", "2.0"); soapHelper.SOAP_addRequestField("DeviceId", fmt::format("{}", authInfo.getDeviceIdWithPlatform())); // this must match the DeviceId used to generate Challenge soapHelper.SOAP_addRequestField("Region", NCrypto::GetRegionAsString(authInfo.region)); soapHelper.SOAP_addRequestField("Country", authInfo.country); // string to sign // differs depending on the call mode std::string signString; signString.reserve(1024); signString.append(fmt::format("<Challenge>{}</Challenge>", challenge)); soapHelper.SOAP_addRequestField("Challenge", challenge); uint32 signerTitleIdHigh = 0x00050010; uint32 signerTitleIdLow = 0x10040300; NCrypto::CertECC deviceCert; if (!deviceCert.decodeFromBase64(authInfo.deviceCertBase64)) { result.apiError = NAPI_RESULT::FAILED; return result; } NCrypto::CHash256 hash; NCrypto::GenerateHashSHA256(signString.data(), signString.size(), hash); NCrypto::CertECC certChain; NCrypto::ECCSig signature = NCrypto::signHash(signerTitleIdHigh, signerTitleIdLow, hash.b, sizeof(hash.b), certChain); auto certChainStr = certChain.encodeToBase64(); soapHelper.SOAP_addRequestField("Signature", signature.encodeToBase64()); soapHelper.SOAP_addRequestField("CertChain", certChainStr); soapHelper.SOAP_addRequestField("DeviceCert", deviceCert.encodeToBase64()); if (!soapHelper.submitRequest()) { result.apiError = NAPI_RESULT::FAILED; return result; } // parse result pugi::xml_document doc; pugi::xml_node responseNode; if (!_parseResponseInit(soapHelper, "GetRegistrationInfoResponse", responseNode, result, doc, responseNode)) return result; result.accountId = responseNode.child_value("AccountId"); result.deviceToken = responseNode.child_value("DeviceToken"); if (boost::iequals(responseNode.child_value("DeviceTokenExpired"), "true")) cemuLog_log(LogType::Force, "Unexpected server response: Device token expired"); /* example response: <Version>2.0</Version> <DeviceId>1234567</DeviceId> <MessageId>EC-1234-1234</MessageId> <TimeStamp>123456789</TimeStamp> <ErrorCode>0</ErrorCode> <ServiceStandbyMode>false/true</ServiceStandbyMode> <AccountId>123456</AccountId> <DeviceToken>DEVICE_TOKEN_STR</DeviceToken> <DeviceTokenExpired>false/true</DeviceTokenExpired> <Country>COUNTRYCODE</Country> <ExtAccountId></ExtAccountId> <DeviceStatus>R</DeviceStatus> <Currency>EUR</Currency> */ return result; } /* ECS */ std::string _getDeviceTokenWT(std::string_view deviceToken) { uint8 wtHash[16]; MD5_CTX md5Ctx; MD5_Init(&md5Ctx); MD5_Update(&md5Ctx, deviceToken.data(), (unsigned long)deviceToken.size()); MD5_Final(wtHash, &md5Ctx); std::string wtString; wtString.reserve(4 + 32); wtString.append("WT-"); for (uint8& b : wtHash) { wtString.append(fmt::format("{0:02x}", b)); } return wtString; } NAPI_ECSGetAccountStatus_Result ECS_GetAccountStatus(AuthInfo& authInfo) { NAPI_ECSGetAccountStatus_Result result{}; CurlSOAPHelper soapHelper(authInfo.GetService()); soapHelper.SOAP_initate("ecs", _getECSUrl(authInfo.GetService()), "GetAccountStatus", "2.0"); soapHelper.SOAP_addRequestField("DeviceId", fmt::format("{}", authInfo.getDeviceIdWithPlatform())); soapHelper.SOAP_addRequestField("Region", NCrypto::GetRegionAsString(authInfo.region)); soapHelper.SOAP_addRequestField("Country", authInfo.country); if(!authInfo.IASToken.accountId.empty()) soapHelper.SOAP_addRequestField("AccountId", authInfo.IASToken.accountId); if (!authInfo.IASToken.deviceToken.empty()) soapHelper.SOAP_addRequestField("DeviceToken", _getDeviceTokenWT(authInfo.IASToken.deviceToken)); if (!soapHelper.submitRequest()) { result.apiError = NAPI_RESULT::FAILED; return result; } pugi::xml_document doc; pugi::xml_node responseNode; if (!_parseResponseInit(soapHelper, "GetAccountStatusResponse", responseNode, result, doc, responseNode)) return result; result.accountId = responseNode.child_value("AccountId"); const char* accountStatusStr = responseNode.child_value("AccountStatus"); if (accountStatusStr) { if (accountStatusStr[0] == 'R') result.accountStatus = NAPI_ECSGetAccountStatus_Result::AccountStatus::REGISTERED; else if (accountStatusStr[0] == 'T') result.accountStatus = NAPI_ECSGetAccountStatus_Result::AccountStatus::TRANSFERRED; else if (accountStatusStr[0] == 'U') result.accountStatus = NAPI_ECSGetAccountStatus_Result::AccountStatus::UNREGISTERED; else { cemuLog_log(LogType::Force, "ECS_GetAccountStatus: Account has unknown status code {}", accountStatusStr); } } // extract service URLs for (pugi::xml_node serviceURLNode : responseNode.children("ServiceURLs")) { std::string_view serviceType = serviceURLNode.child_value("Name"); std::string_view url = serviceURLNode.child_value("URI"); if(serviceType.empty() || url.empty()) continue; if (boost::iequals(serviceType, "ContentPrefixURL")) result.serviceURLs.ContentPrefixURL = url; else if (boost::iequals(serviceType, "UncachedContentPrefixURL")) result.serviceURLs.UncachedContentPrefixURL = url; else if (boost::iequals(serviceType, "SystemContentPrefixURL")) result.serviceURLs.SystemContentPrefixURL = url; else if (boost::iequals(serviceType, "SystemUncachedContentPrefixURL")) result.serviceURLs.SystemUncachedContentPrefixURL = url; else if (boost::iequals(serviceType, "EcsURL")) result.serviceURLs.EcsURL = url; else if (boost::iequals(serviceType, "IasURL")) result.serviceURLs.IasURL = url; else if (boost::iequals(serviceType, "CasURL")) result.serviceURLs.CasURL = url; else if (boost::iequals(serviceType, "NusURL")) result.serviceURLs.NusURL = url; else cemuLog_log(LogType::Force, "GetAccountStatus: Unknown service URI type {}", serviceType); } // assign service URLs auto& cachedServiceUrls = GetCachedServiceUrls(authInfo.GetService()); if (!result.serviceURLs.ContentPrefixURL.empty()) cachedServiceUrls.s_serviceURL_ContentPrefixURL = result.serviceURLs.ContentPrefixURL; if (!result.serviceURLs.UncachedContentPrefixURL.empty()) cachedServiceUrls.s_serviceURL_UncachedContentPrefixURL = result.serviceURLs.UncachedContentPrefixURL; if (!result.serviceURLs.IasURL.empty()) cachedServiceUrls.s_serviceURL_IasURL = result.serviceURLs.IasURL; if (!result.serviceURLs.CasURL.empty()) cachedServiceUrls.s_serviceURL_CasURL = result.serviceURLs.CasURL; if (!result.serviceURLs.NusURL.empty()) cachedServiceUrls.s_serviceURL_NusURL = result.serviceURLs.NusURL; if (!result.serviceURLs.EcsURL.empty()) cachedServiceUrls.s_serviceURL_EcsURL = result.serviceURLs.EcsURL; return result; } NAPI_ECSAccountListETicketIds_Result ECS_AccountListETicketIds(AuthInfo& authInfo) { NAPI_ECSAccountListETicketIds_Result result{}; CurlSOAPHelper soapHelper(authInfo.GetService()); soapHelper.SOAP_initate("ecs", _getECSUrl(authInfo.GetService()), "AccountListETicketIds", "2.0"); soapHelper.SOAP_addRequestField("DeviceId", fmt::format("{}", authInfo.getDeviceIdWithPlatform())); soapHelper.SOAP_addRequestField("Region", NCrypto::GetRegionAsString(authInfo.region)); soapHelper.SOAP_addRequestField("Country", authInfo.country); if (!authInfo.IASToken.accountId.empty()) soapHelper.SOAP_addRequestField("AccountId", authInfo.IASToken.accountId); if (!authInfo.IASToken.deviceToken.empty()) soapHelper.SOAP_addRequestField("DeviceToken", _getDeviceTokenWT(authInfo.IASToken.deviceToken)); if (!soapHelper.submitRequest()) { result.apiError = NAPI_RESULT::FAILED; return result; } pugi::xml_document doc; pugi::xml_node responseNode; if (!_parseResponseInit(soapHelper, "AccountListETicketIdsResponse", responseNode, result, doc, responseNode)) return result; // extract ticket IVs for (pugi::xml_node tivNode : responseNode.children("TIV")) { // TIV is encoded as <ticketId>.<ticketVersion> // ticketVersion starts at 0 and increments every time the ticket is updated (e.g. for AOC content, when purchasing additional DLC packages) const char* tivValue = tivNode.child_value(); const char* tivValueEnd = tivValue + strlen(tivValue); const char* tivValueSeparator = std::strchr(tivValue, '.'); if (tivValueSeparator == nullptr) tivValueSeparator = tivValueEnd; // parse ticket id sint64 ticketId = 0; std::from_chars_result fcr = std::from_chars(tivValue, tivValueSeparator, ticketId); if (fcr.ec == std::errc::invalid_argument || fcr.ec == std::errc::result_out_of_range) { result.apiError = NAPI_RESULT::XML_ERROR; return result; } // parse ticket version uint32 ticketVersion = 0; fcr = std::from_chars(tivValueSeparator+1, tivValueEnd, ticketVersion); if (fcr.ec == std::errc::invalid_argument || fcr.ec == std::errc::result_out_of_range) { result.apiError = NAPI_RESULT::XML_ERROR; return result; } result.tivs.push_back({ ticketId , ticketVersion }); } return result; } NAPI_ECSAccountGetETickets_Result ECS_AccountGetETickets(AuthInfo& authInfo, sint64 ticketId) { NAPI_ECSAccountGetETickets_Result result{}; CurlSOAPHelper soapHelper(authInfo.GetService()); soapHelper.SOAP_initate("ecs", _getECSUrl(authInfo.GetService()), "AccountGetETickets", "2.0"); soapHelper.SOAP_addRequestField("DeviceId", fmt::format("{}", authInfo.getDeviceIdWithPlatform())); soapHelper.SOAP_addRequestField("Region", NCrypto::GetRegionAsString(authInfo.region)); soapHelper.SOAP_addRequestField("Country", authInfo.country); if (!authInfo.IASToken.accountId.empty()) soapHelper.SOAP_addRequestField("AccountId", authInfo.IASToken.accountId); if (!authInfo.IASToken.deviceToken.empty()) soapHelper.SOAP_addRequestField("DeviceToken", _getDeviceTokenWT(authInfo.IASToken.deviceToken)); soapHelper.SOAP_addRequestField("DeviceCert", authInfo.deviceCertBase64); soapHelper.SOAP_addRequestField("TicketId", fmt::format("{}", ticketId)); if (!soapHelper.submitRequest()) { result.apiError = NAPI_RESULT::FAILED; return result; } // parse result pugi::xml_document doc; pugi::xml_node responseNode; if (!_parseResponseInit(soapHelper, "AccountGetETicketsResponse", responseNode, result, doc, responseNode)) return result; const char* eTicketsStr = responseNode.child_value("ETickets"); result.eTickets = NCrypto::base64Decode(eTicketsStr); if (result.eTickets.empty()) { cemuLog_log(LogType::Force, "AccountGetETickets: Invalid eTickets data in response"); result.apiError = NAPI_RESULT::DATA_ERROR; return result; } for (pugi::xml_node certNode : responseNode.children("Certs")) { const char* certStringValue = certNode.child_value(); auto certData = NCrypto::base64Decode(certStringValue); if (certData.empty()) { cemuLog_log(LogType::Force, "AccountGetETickets: Invalid cert data in response"); result.apiError = NAPI_RESULT::DATA_ERROR; return result; } result.certs.emplace_back(NCrypto::base64Decode(certStringValue)); } /* example response: <ETickets>BASE64_TIK?</ETickets> <Certs>BASE64_CERT</Certs> <Certs>BASE64_CERT</Certs> */ return result; } /* CCS (content server for raw files, does not use SOAP API) */ NAPI_CCSGetTMD_Result CCS_GetTMD(AuthInfo& authInfo, uint64 titleId, uint16 titleVersion) { NAPI_CCSGetTMD_Result result{}; CurlRequestHelper req; req.initate(authInfo.GetService(), fmt::format("{}/{:016x}/tmd.{}?deviceId={}&accountId={}", _getCCSUncachedUrl(authInfo.GetService()), titleId, titleVersion, authInfo.getDeviceIdWithPlatform(), authInfo.IASToken.accountId), CurlRequestHelper::SERVER_SSL_CONTEXT::CCS); req.setTimeout(180); if (!req.submitRequest(false)) { cemuLog_log(LogType::Force, fmt::format("Failed to request TMD for title {0:016X} v{1}", titleId, titleVersion)); return result; } result.tmdData = req.getReceivedData(); result.isValid = true; return result; } NAPI_CCSGetTMD_Result CCS_GetTMD(AuthInfo& authInfo, uint64 titleId) { NAPI_CCSGetTMD_Result result{}; CurlRequestHelper req; req.initate(authInfo.GetService(), fmt::format("{}/{:016x}/tmd?deviceId={}&accountId={}", _getCCSUncachedUrl(authInfo.GetService()), titleId, authInfo.getDeviceIdWithPlatform(), authInfo.IASToken.accountId), CurlRequestHelper::SERVER_SSL_CONTEXT::CCS); req.setTimeout(180); if (!req.submitRequest(false)) { cemuLog_log(LogType::Force, fmt::format("Failed to request TMD for title {0:016X}", titleId)); return result; } result.tmdData = req.getReceivedData(); result.isValid = true; return result; } NAPI_CCSGetETicket_Result CCS_GetCETK(NetworkService service, uint64 titleId, uint16 titleVersion) { NAPI_CCSGetETicket_Result result{}; CurlRequestHelper req; req.initate(service, fmt::format("{}/{:016x}/cetk", _getCCSUncachedUrl(service), titleId), CurlRequestHelper::SERVER_SSL_CONTEXT::CCS); req.setTimeout(180); if (!req.submitRequest(false)) { cemuLog_log(LogType::Force, fmt::format("Failed to request eTicket for title {0:016X} v{1}", titleId, titleVersion)); return result; } result.cetkData = req.getReceivedData(); result.isValid = true; return result; } bool CCS_GetContentFile(NetworkService service, uint64 titleId, uint32 contentId, bool(*cbWriteCallback)(void* userData, const void* ptr, size_t len, bool isLast), void* userData) { CurlRequestHelper req; req.initate(service, fmt::format("{}/{:016x}/{:08x}", _getCCSUrl(service), titleId, contentId), CurlRequestHelper::SERVER_SSL_CONTEXT::CCS); req.setWriteCallback(cbWriteCallback, userData); req.setTimeout(0); if (!req.submitRequest(false)) { cemuLog_log(LogType::Force, fmt::format("Failed to request content file {:08x} for title {:016X}", contentId, titleId)); return false; } return true; } NAPI_CCSGetContentH3_Result CCS_GetContentH3File(NetworkService service, uint64 titleId, uint32 contentId) { NAPI_CCSGetContentH3_Result result{}; CurlRequestHelper req; req.initate(service, fmt::format("{}/{:016x}/{:08x}.h3", _getCCSUrl(service), titleId, contentId), CurlRequestHelper::SERVER_SSL_CONTEXT::CCS); if (!req.submitRequest(false)) { cemuLog_log(LogType::Force, fmt::format("Failed to request content hash file {:08x}.h3 for title {:016X}", contentId, titleId)); return result; } result.tmdData = req.getReceivedData(); result.isValid = true; return result; } };
21,361
C++
.cpp
515
38.124272
271
0.762836
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,937
napi_version.cpp
cemu-project_Cemu/src/Cemu/napi/napi_version.cpp
#include "Common/precompiled.h" #include "napi.h" #include "napi_helper.h" #include "curl/curl.h" #include "pugixml.hpp" #include "Cemu/ncrypto/ncrypto.h" #include <charconv> #include "config/ActiveSettings.h" #include "config/NetworkSettings.h" namespace NAPI { NAPI_VersionListVersion_Result TAG_GetVersionListVersion(AuthInfo& authInfo) { NAPI_VersionListVersion_Result result; CurlRequestHelper req; std::string requestUrl; switch (authInfo.GetService()) { case NetworkService::Pretendo: requestUrl = PretendoURLs::TAGAYAURL; break; case NetworkService::Custom: requestUrl = GetNetworkConfig().urls.TAGAYA.GetValue(); break; case NetworkService::Nintendo: default: requestUrl = NintendoURLs::TAGAYAURL; break; } requestUrl.append(fmt::format(fmt::runtime("/{}/{}/latest_version"), NCrypto::GetRegionAsString(authInfo.region), authInfo.country.empty() ? "NN" : authInfo.country)); req.initate(authInfo.GetService(), requestUrl, CurlRequestHelper::SERVER_SSL_CONTEXT::TAGAYA); if (!req.submitRequest(false)) { cemuLog_log(LogType::Force, fmt::format("Failed to request version of update list")); return result; } auto& receivedData = req.getReceivedData(); pugi::xml_document doc; if (!doc.load_buffer(receivedData.data(), receivedData.size())) { cemuLog_log(LogType::Force, "Failed to parse title list XML"); return result; } if (!doc.child("version_list_info").child("version") || !doc.child("version_list_info").child("fqdn")) { cemuLog_log(LogType::Force, "Title list XML has missing field"); return result; } result.version = atoi(doc.child("version_list_info").child("version").child_value()); result.fqdnURL = doc.child("version_list_info").child("fqdn").child_value(); result.isValid = true; return result; } NAPI_VersionList_Result TAG_GetVersionList(AuthInfo& authInfo, std::string_view fqdnURL, uint32 versionListVersion) { NAPI_VersionList_Result result; CurlRequestHelper req; req.initate(authInfo.GetService(), fmt::format("https://{}/tagaya/versionlist/{}/{}/list/{}.versionlist", fqdnURL, NCrypto::GetRegionAsString(authInfo.region), authInfo.country.empty() ? "NN" : authInfo.country, versionListVersion), CurlRequestHelper::SERVER_SSL_CONTEXT::TAGAYA); if (!req.submitRequest(false)) { cemuLog_log(LogType::Force, fmt::format("Failed to request update list")); return result; } auto& receivedData = req.getReceivedData(); pugi::xml_document doc; if (!doc.load_buffer(receivedData.data(), receivedData.size())) { cemuLog_log(LogType::Force, "Failed to parse update list XML"); return result; } // example: // <?xml version="1.0" encoding="UTF-8" standalone="yes"?> // <version_list format_version="1.0"><version>1615</version> // <titles> // <title><id>0005000E10100600</id><version>16</version></title> // <title><id>0005000E10101B00</id><version>16</version></title> // ... for (pugi::xml_node title : doc.child("version_list").child("titles").children("title")) { uint64 titleId = 0; uint32 titleVersion = 0; std::string_view str = title.child_value("id"); if (const auto res = std::from_chars(str.data(), str.data() + str.size(), titleId, 16); res.ec != std::errc()) continue; str = title.child_value("version"); if (const auto res = std::from_chars(str.data(), str.data() + str.size(), titleVersion, 10); res.ec != std::errc()) continue; result.titleVersionList.emplace(titleId, titleVersion); } result.isValid = true; return result; } };
3,562
C++
.cpp
93
35.225806
282
0.717838
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,938
napi_idbe.cpp
cemu-project_Cemu/src/Cemu/napi/napi_idbe.cpp
#include "Common/precompiled.h" #include "napi.h" #include "napi_helper.h" #include "curl/curl.h" #include "pugixml.hpp" #include "Cafe/IOSU/legacy/iosu_crypto.h" #include "Cemu/ncrypto/ncrypto.h" #include "openssl/sha.h" #include "util/crypto/aes128.h" #include "util/helpers/StringHelpers.h" #include "config/ActiveSettings.h" #include "config/NetworkSettings.h" namespace NAPI { std::string IDBEIconDataV0::LanguageInfo::GetGameNameUTF8() { return StringHelpers::ToUtf8(gameName); } std::string IDBEIconDataV0::LanguageInfo::GetGameLongNameUTF8() { return StringHelpers::ToUtf8(gameLongName); } std::string IDBEIconDataV0::LanguageInfo::GetPublisherNameUTF8() { return StringHelpers::ToUtf8(publisherName); } void _decryptIDBEAndHash(IDBEIconDataV0* iconData, uint8* hash, uint8 keyIndex) { static uint8 idbeAesKeys[4 * 16] = { 0x4A,0xB9,0xA4,0x0E,0x14,0x69,0x75,0xA8,0x4B,0xB1,0xB4,0xF3,0xEC,0xEF,0xC4,0x7B, 0x90,0xA0,0xBB,0x1E,0x0E,0x86,0x4A,0xE8,0x7D,0x13,0xA6,0xA0,0x3D,0x28,0xC9,0xB8, 0xFF,0xBB,0x57,0xC1,0x4E,0x98,0xEC,0x69,0x75,0xB3,0x84,0xFC,0xF4,0x07,0x86,0xB5, 0x80,0x92,0x37,0x99,0xB4,0x1F,0x36,0xA6,0xA7,0x5F,0xB8,0xB4,0x8C,0x95,0xF6,0x6F }; static uint8 idbeAesIv[16] = { 0xA4,0x69,0x87,0xAE,0x47,0xD8,0x2B,0xB4,0xFA,0x8A,0xBC,0x04,0x50,0x28,0x5F,0xA4 }; const uint8* aesKey = idbeAesKeys + 16 * keyIndex; uint8 iv[16]; memcpy(iv, hash + 16, sizeof(iv)); AES128_CBC_decrypt(hash, hash, 32, aesKey, idbeAesIv); AES128_CBC_decrypt((uint8*)iconData, (uint8*)iconData, sizeof(IDBEIconDataV0), aesKey, iv); } std::vector<uint8> IDBE_RequestRawEncrypted(NetworkService networkService, uint64 titleId) { CurlRequestHelper req; std::string requestUrl; switch (networkService) { case NetworkService::Pretendo: requestUrl = PretendoURLs::IDBEURL; break; case NetworkService::Custom: requestUrl = GetNetworkConfig().urls.IDBE.GetValue(); break; case NetworkService::Nintendo: default: requestUrl = NintendoURLs::IDBEURL; break; } requestUrl.append(fmt::format(fmt::runtime("/{0:02X}/{1:016X}.idbe"), (uint32)((titleId >> 8) & 0xFF), titleId)); req.initate(networkService, requestUrl, CurlRequestHelper::SERVER_SSL_CONTEXT::IDBE); if (!req.submitRequest(false)) { cemuLog_log(LogType::Force, fmt::format("Failed to request IDBE icon for title {0:016X}", titleId)); return {}; } /* format: +0x00 uint8 version (0) +0x01 uint8 keyIndex +0x02 uint8[32] hashSHA256 +0x22 uint8[] EncryptedIconData */ auto& receivedData = req.getReceivedData(); return receivedData; } std::optional<IDBEIconDataV0> IDBE_Request(NetworkService networkService, uint64 titleId) { if (titleId == 0x000500301001500A || titleId == 0x000500301001510A || titleId == 0x000500301001520A) { // friend list has no icon, just fail immediately cemuLog_logDebug(LogType::Force, "Requesting IDBE for Friend List. Return none instead"); return std::nullopt; } std::vector<uint8> idbeData = IDBE_RequestRawEncrypted(networkService, titleId); if (idbeData.size() < 0x22) return std::nullopt; if (idbeData[0] != 0) { cemuLog_log(LogType::Force, "IDBE_Request: File has invalid version"); return std::nullopt; } uint8 keyIndex = idbeData[1]; if (keyIndex >= 4) { cemuLog_log(LogType::Force, "IDBE_Request: Key index out of range"); return std::nullopt; } if (idbeData.size() < (0x22 + sizeof(IDBEIconDataV0))) { cemuLog_log(LogType::Force, "IDBE_Request: File size does not match"); return std::nullopt; } // extract hash and encrypted icon data uint8 hash[32]; std::memcpy(hash, idbeData.data() + 0x2, 32); IDBEIconDataV0 iconDataV0; std::memcpy(&iconDataV0, idbeData.data() + 0x22, sizeof(IDBEIconDataV0)); // decrypt icon data and hash _decryptIDBEAndHash(&iconDataV0, hash, keyIndex); // verify hash of decrypted data uint8 calcHash[SHA256_DIGEST_LENGTH]; SHA256((const unsigned char*) &iconDataV0, sizeof(IDBEIconDataV0), calcHash); if (std::memcmp(calcHash, hash, SHA256_DIGEST_LENGTH) != 0) { cemuLog_log(LogType::Force, "IDBE_Request: Hash mismatch"); return std::nullopt; } return std::optional(iconDataV0); } };
4,236
C++
.cpp
126
30.634921
115
0.736816
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,939
napi_act.cpp
cemu-project_Cemu/src/Cemu/napi/napi_act.cpp
#include "Common/precompiled.h" #include "Cemu/ncrypto/ncrypto.h" #include "napi.h" #include "napi_helper.h" #include "curl/curl.h" #include "pugixml.hpp" #include "Cafe/IOSU/legacy/iosu_crypto.h" #include "config/ActiveSettings.h" #include "util/helpers/StringHelpers.h" #include "util/highresolutiontimer/HighResolutionTimer.h" #include "config/LaunchSettings.h" namespace NAPI { std::string _getACTUrl(NetworkService service) { switch (service) { case NetworkService::Nintendo: return NintendoURLs::ACTURL; case NetworkService::Pretendo: return PretendoURLs::ACTURL; case NetworkService::Custom: return GetNetworkConfig().urls.ACT.GetValue(); default: return NintendoURLs::ACTURL; } } struct ACTOauthToken : public _NAPI_CommonResultACT { std::string token; std::string refreshToken; }; bool _parseActResponse(CurlRequestHelper& requestHelper, _NAPI_CommonResultACT& result, pugi::xml_document& doc) { if (!doc.load_buffer(requestHelper.getReceivedData().data(), requestHelper.getReceivedData().size())) { cemuLog_log(LogType::Force, fmt::format("Invalid XML in account service response")); result.apiError = NAPI_RESULT::XML_ERROR; return false; } // check for error codes pugi::xml_node errors = doc.child("errors"); if (errors) { pugi::xml_node error = errors.child("error"); if (error) { std::string_view errorCodeStr = error.child_value("code"); std::string_view errorCodeMsg = error.child_value("message"); sint32 errorCode = StringHelpers::ToInt(errorCodeStr); if (errorCode == 0) { cemuLog_log(LogType::Force, "Account response with unexpected error code 0"); result.apiError = NAPI_RESULT::XML_ERROR; } else { result.apiError = NAPI_RESULT::SERVICE_ERROR; result.serviceError = (ACT_ERROR_CODE)errorCode; cemuLog_log(LogType::Force, "Account response with error code {}", errorCode); if(!errorCodeMsg.empty()) cemuLog_log(LogType::Force, "Message from server: {}", errorCodeMsg); } } else { result.apiError = NAPI_RESULT::XML_ERROR; } return false; } return true; } void _ACTSetCommonHeaderParameters(CurlRequestHelper& req, AuthInfo& authInfo) { req.addHeaderField("X-Nintendo-Platform-ID", "1"); req.addHeaderField("X-Nintendo-Device-Type", "2"); req.addHeaderField("X-Nintendo-Client-ID", "a2efa818a34fa16b8afbc8a74eba3eda"); req.addHeaderField("X-Nintendo-Client-Secret", "c91cdb5658bd4954ade78533a339cf9a"); req.addHeaderField("Accept", "*/*"); if(authInfo.region == CafeConsoleRegion::USA) req.addHeaderField("X-Nintendo-System-Version", "0270"); else req.addHeaderField("X-Nintendo-System-Version", "0260"); } void _ACTSetDeviceParameters(CurlRequestHelper& req, AuthInfo& authInfo) { req.addHeaderField("X-Nintendo-Device-ID", fmt::format("{}", authInfo.deviceId)); // deviceId without platform field req.addHeaderField("X-Nintendo-Serial-Number", authInfo.serial); } void _ACTSetRegionAndCountryParameters(CurlRequestHelper& req, AuthInfo& authInfo) { req.addHeaderField("X-Nintendo-Region", fmt::format("{}", (uint32)authInfo.region)); req.addHeaderField("X-Nintendo-Country", authInfo.country); } struct OAuthTokenCacheEntry { OAuthTokenCacheEntry(std::string_view accountId, std::array<uint8, 32>& passwordHash, std::string_view token, std::string_view refreshToken, uint64 expiresIn, NetworkService service) : accountId(accountId), passwordHash(passwordHash), token(token), refreshToken(refreshToken), service(service) { expires = HighResolutionTimer::now().getTickInSeconds() + expiresIn; }; bool CheckIfSameAccount(const AuthInfo& authInfo) const { return authInfo.accountId == accountId && authInfo.passwordHash == passwordHash; } bool CheckIfExpired() const { return HighResolutionTimer::now().getTickInSeconds() >= expires; } std::string accountId; std::array<uint8, 32> passwordHash; std::string token; std::string refreshToken; uint64 expires; NetworkService service; }; std::vector<OAuthTokenCacheEntry> g_oauthTokenCache; std::mutex g_oauthTokenCacheMtx; // look up oauth token in cache, otherwise request from server ACTOauthToken ACT_GetOauthToken_WithCache(AuthInfo& authInfo, uint64 titleId, uint16 titleVersion) { ACTOauthToken result{}; // check cache first NetworkService service = authInfo.GetService(); g_oauthTokenCacheMtx.lock(); auto cacheItr = g_oauthTokenCache.begin(); while (cacheItr != g_oauthTokenCache.end()) { if (cacheItr->CheckIfSameAccount(authInfo) && cacheItr->service == service) { if (cacheItr->CheckIfExpired()) { cacheItr = g_oauthTokenCache.erase(cacheItr); continue; } result.token = cacheItr->token; result.refreshToken = cacheItr->refreshToken; result.apiError = NAPI_RESULT::SUCCESS; g_oauthTokenCacheMtx.unlock(); return result; } cacheItr++; } g_oauthTokenCacheMtx.unlock(); // token not cached, request from server via oauth2 CurlRequestHelper req; req.initate(authInfo.GetService(), fmt::format("{}/v1/api/oauth20/access_token/generate", _getACTUrl(authInfo.GetService())), CurlRequestHelper::SERVER_SSL_CONTEXT::ACT); _ACTSetCommonHeaderParameters(req, authInfo); _ACTSetDeviceParameters(req, authInfo); _ACTSetRegionAndCountryParameters(req, authInfo); req.addHeaderField("X-Nintendo-Device-Cert", authInfo.deviceCertBase64); req.addHeaderField("X-Nintendo-FPD-Version", "0000"); req.addHeaderField("X-Nintendo-Environment", "L1"); req.addHeaderField("X-Nintendo-Title-ID", fmt::format("{:016x}", titleId)); uint32 uniqueId = ((titleId >> 8) & 0xFFFFF); req.addHeaderField("X-Nintendo-Unique-ID", fmt::format("{:05x}", uniqueId)); req.addHeaderField("X-Nintendo-Application-Version", fmt::format("{:04x}", titleVersion)); // convert password hash to string char passwordHashString[128]; for (sint32 i = 0; i < 32; i++) sprintf(passwordHashString + i * 2, "%02x", authInfo.passwordHash[i]); req.addPostField("grant_type", "password"); req.addPostField("user_id", authInfo.accountId); req.addPostField("password", passwordHashString); req.addPostField("password_type", "hash"); req.addHeaderField("Content-type", "application/x-www-form-urlencoded"); if (!req.submitRequest(true)) { cemuLog_log(LogType::Force, fmt::format("Failed request /oauth20/access_token/generate")); result.apiError = NAPI_RESULT::FAILED; return result; } /* Response example: <OAuth20> <access_token> <token>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</token> <refresh_token>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</refresh_token> <expires_in>3600</expires_in> </access_token> </OAuth20> */ // parse result pugi::xml_document doc; if (!_parseActResponse(req, result, doc)) return result; pugi::xml_node node = doc.child("OAuth20"); if (!node) { cemuLog_log(LogType::Force, fmt::format("Response does not contain OAuth20 node")); result.apiError = NAPI_RESULT::XML_ERROR; return result; } node = node.child("access_token"); if (!node) { cemuLog_log(LogType::Force, fmt::format("Response does not contain OAuth20/access_token node")); result.apiError = NAPI_RESULT::XML_ERROR; return result; } result.token = node.child_value("token"); result.refreshToken = node.child_value("refresh_token"); std::string_view expires_in = node.child_value("expires_in"); result.apiError = NAPI_RESULT::SUCCESS; if (result.token.empty()) cemuLog_log(LogType::Force, "OAuth20/token is empty"); sint64 expiration = StringHelpers::ToInt64(expires_in); expiration = std::max(expiration - 30LL, 0LL); // subtract a few seconds to compensate for the web request delay // update cache if (expiration > 0) { g_oauthTokenCacheMtx.lock(); g_oauthTokenCache.emplace_back(authInfo.accountId, authInfo.passwordHash, result.token, result.refreshToken, expiration, service); g_oauthTokenCacheMtx.unlock(); } return result; } bool ACT_GetProfile(AuthInfo& authInfo, ACTGetProfileResult& result) { CurlRequestHelper req; req.initate(authInfo.GetService(), fmt::format("{}/v1/api/people/@me/profile", _getACTUrl(authInfo.GetService())), CurlRequestHelper::SERVER_SSL_CONTEXT::ACT); _ACTSetCommonHeaderParameters(req, authInfo); _ACTSetDeviceParameters(req, authInfo); // get oauth2 token ACTOauthToken oauthToken = ACT_GetOauthToken_WithCache(authInfo, 0x0005001010001C00, 0x0001C); cemu_assert_unimplemented(); return true; } struct NexTokenCacheEntry { NexTokenCacheEntry(std::string_view accountId, std::array<uint8, 32>& passwordHash, NetworkService networkService, uint32 gameServerId, ACTNexToken& nexToken) : accountId(accountId), passwordHash(passwordHash), networkService(networkService), nexToken(nexToken), gameServerId(gameServerId) {}; bool IsMatch(const AuthInfo& authInfo, const uint32 gameServerId) const { return authInfo.accountId == accountId && authInfo.passwordHash == passwordHash && authInfo.GetService() == networkService && this->gameServerId == gameServerId; } std::string accountId; std::array<uint8, 32> passwordHash; NetworkService networkService; uint32 gameServerId; ACTNexToken nexToken; }; std::vector<NexTokenCacheEntry> g_nexTokenCache; std::mutex g_nexTokenCacheMtx; ACTGetNexTokenResult ACT_GetNexToken_WithCache(AuthInfo& authInfo, uint64 titleId, uint16 titleVersion, uint32 serverId) { ACTGetNexTokenResult result{}; // check cache g_nexTokenCacheMtx.lock(); for (auto& itr : g_nexTokenCache) { if (itr.IsMatch(authInfo, serverId)) { result.nexToken = itr.nexToken; result.apiError = NAPI_RESULT::SUCCESS; g_nexTokenCacheMtx.unlock(); return result; } } g_nexTokenCacheMtx.unlock(); // get Nex token ACTOauthToken oauthToken = ACT_GetOauthToken_WithCache(authInfo, titleId, titleVersion); if (!oauthToken.isValid()) { cemuLog_log(LogType::Force, "ACT_GetNexToken(): Failed to retrieve OAuth token"); if (oauthToken.apiError == NAPI_RESULT::SERVICE_ERROR) { result.apiError = NAPI_RESULT::SERVICE_ERROR; result.serviceError = oauthToken.serviceError; } else { result.apiError = NAPI_RESULT::DATA_ERROR; } return result; } // do request CurlRequestHelper req; req.initate(authInfo.GetService(), fmt::format("{}/v1/api/provider/nex_token/@me?game_server_id={:08X}", _getACTUrl(authInfo.GetService()), serverId), CurlRequestHelper::SERVER_SSL_CONTEXT::ACT); _ACTSetCommonHeaderParameters(req, authInfo); _ACTSetDeviceParameters(req, authInfo); _ACTSetRegionAndCountryParameters(req, authInfo); req.addHeaderField("X-Nintendo-FPD-Version", "0000"); req.addHeaderField("X-Nintendo-Environment", "L1"); req.addHeaderField("X-Nintendo-Title-ID", fmt::format("{:016x}", titleId)); uint32 uniqueId = ((titleId >> 8) & 0xFFFFF); req.addHeaderField("X-Nintendo-Unique-ID", fmt::format("{:05x}", uniqueId)); req.addHeaderField("X-Nintendo-Application-Version", fmt::format("{:04x}", titleVersion)); req.addHeaderField("Authorization", fmt::format("Bearer {}", oauthToken.token)); if (!req.submitRequest(false)) { cemuLog_log(LogType::Force, fmt::format("Failed request /provider/nex_token/@me")); result.apiError = NAPI_RESULT::FAILED; return result; } /* Example response (success): <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <nex_token> <host>HOST</host> <nex_password>xxxxxxxxxxxxxxxx</nex_password> <pid>123456</pid> <port>60200</port> <token>xxxxxxxxxxxxxxx</token> </nex_token> Example response (error case): <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <errors> <error> <code>1021</code> <message>The requested game server was not found.</message> </error> </errors> */ // code 0124 -> Version lower than useable registered // parse result pugi::xml_document doc; if (!_parseActResponse(req, result, doc)) return result; pugi::xml_node tokenNode = doc.child("nex_token"); if (!tokenNode) { cemuLog_log(LogType::Force, "Response does not contain NexToken node"); result.apiError = NAPI_RESULT::XML_ERROR; return result; } std::string_view host = tokenNode.child_value("host"); std::string_view nex_password = tokenNode.child_value("nex_password"); std::string_view port = tokenNode.child_value("port"); std::string_view token = tokenNode.child_value("token"); memset(&result.nexToken, 0, sizeof(ACTNexToken)); if (host.size() > 15) cemuLog_log(LogType::Force, "NexToken response: host field too long"); if (nex_password.size() > 64) cemuLog_log(LogType::Force, "NexToken response: nex_password field too long"); if (token.size() > 512) cemuLog_log(LogType::Force, "NexToken response: token field too long"); for (size_t i = 0; i < std::min(host.size(), (size_t)15); i++) result.nexToken.host[i] = host[i]; for (size_t i = 0; i < std::min(nex_password.size(), (size_t)64); i++) result.nexToken.nexPassword[i] = nex_password[i]; for (size_t i = 0; i < std::min(token.size(), (size_t)512); i++) result.nexToken.token[i] = token[i]; result.nexToken.port = (uint16)StringHelpers::ToInt(port); result.apiError = NAPI_RESULT::SUCCESS; g_nexTokenCacheMtx.lock(); g_nexTokenCache.emplace_back(authInfo.accountId, authInfo.passwordHash, authInfo.GetService(), serverId, result.nexToken); g_nexTokenCacheMtx.unlock(); return result; } struct IndependentTokenCacheEntry { IndependentTokenCacheEntry(std::string_view accountId, std::array<uint8, 32>& passwordHash, NetworkService networkService, std::string_view clientId, std::string_view independentToken, sint64 expiresIn) : accountId(accountId), passwordHash(passwordHash), networkService(networkService), clientId(clientId), independentToken(independentToken) { expires = HighResolutionTimer::now().getTickInSeconds() + expiresIn; }; bool IsMatch(const AuthInfo& authInfo, const std::string_view clientId) const { return authInfo.accountId == accountId && authInfo.passwordHash == passwordHash && authInfo.GetService() == networkService && this->clientId == clientId; } bool CheckIfExpired() const { return (sint64)HighResolutionTimer::now().getTickInSeconds() >= expires; } std::string accountId; std::array<uint8, 32> passwordHash; NetworkService networkService; std::string clientId; sint64 expires; std::string independentToken; }; std::vector<IndependentTokenCacheEntry> g_IndependentTokenCache; std::mutex g_IndependentTokenCacheMtx; ACTGetIndependentTokenResult ACT_GetIndependentToken_WithCache(AuthInfo& authInfo, uint64 titleId, uint16 titleVersion, std::string_view clientId) { ACTGetIndependentTokenResult result{}; // check cache g_IndependentTokenCacheMtx.lock(); auto itr = g_IndependentTokenCache.begin(); while(itr != g_IndependentTokenCache.end()) { if (itr->CheckIfExpired()) { itr = g_IndependentTokenCache.erase(itr); continue; } else if (itr->IsMatch(authInfo, clientId)) { result.token = itr->independentToken; result.expiresIn = std::max(itr->expires - (sint64)HighResolutionTimer::now().getTickInSeconds(), (sint64)0); result.apiError = NAPI_RESULT::SUCCESS; g_IndependentTokenCacheMtx.unlock(); return result; } itr++; } g_IndependentTokenCacheMtx.unlock(); // get Independent token ACTOauthToken oauthToken = ACT_GetOauthToken_WithCache(authInfo, titleId, titleVersion); if (!oauthToken.isValid()) { cemuLog_log(LogType::Force, "ACT_GetIndependentToken(): Failed to retrieve OAuth token"); if (oauthToken.apiError == NAPI_RESULT::SERVICE_ERROR) { result.apiError = NAPI_RESULT::SERVICE_ERROR; result.serviceError = oauthToken.serviceError; } else { result.apiError = NAPI_RESULT::DATA_ERROR; } return result; } // do request CurlRequestHelper req; req.initate(authInfo.GetService(), fmt::format("{}/v1/api/provider/service_token/@me?client_id={}", _getACTUrl(authInfo.GetService()), clientId), CurlRequestHelper::SERVER_SSL_CONTEXT::ACT); _ACTSetCommonHeaderParameters(req, authInfo); _ACTSetDeviceParameters(req, authInfo); _ACTSetRegionAndCountryParameters(req, authInfo); req.addHeaderField("X-Nintendo-FPD-Version", "0000"); req.addHeaderField("X-Nintendo-Environment", "L1"); req.addHeaderField("X-Nintendo-Title-ID", fmt::format("{:016x}", titleId)); uint32 uniqueId = ((titleId >> 8) & 0xFFFFF); req.addHeaderField("X-Nintendo-Unique-ID", fmt::format("{:05x}", uniqueId)); req.addHeaderField("X-Nintendo-Application-Version", fmt::format("{:04x}", titleVersion)); req.addHeaderField("Authorization", fmt::format("Bearer {}", oauthToken.token)); if (!req.submitRequest(false)) { cemuLog_log(LogType::Force, fmt::format("Failed request /provider/service_token/@me")); result.apiError = NAPI_RESULT::FAILED; return result; } /* Example response (success): <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <service_token> <token>xxxxxxxxxxxx</token> </service_token> */ // parse result pugi::xml_document doc; if (!_parseActResponse(req, result, doc)) return result; pugi::xml_node tokenNode = doc.child("service_token"); if (!tokenNode) { cemuLog_log(LogType::Force, "Response does not contain service_token node"); result.apiError = NAPI_RESULT::XML_ERROR; return result; } std::string_view token = tokenNode.child_value("token"); result.token = token; result.apiError = NAPI_RESULT::SUCCESS; g_IndependentTokenCacheMtx.lock(); g_IndependentTokenCache.emplace_back(authInfo.accountId, authInfo.passwordHash, authInfo.GetService(), clientId, result.token, 3600); g_IndependentTokenCacheMtx.unlock(); return result; } ACTConvertNnidToPrincipalIdResult ACT_ACTConvertNnidToPrincipalId(AuthInfo& authInfo, std::string_view nnid) { ACTConvertNnidToPrincipalIdResult result{}; // get Independent token ACTOauthToken oauthToken = ACT_GetOauthToken_WithCache(authInfo, 0x0005001010001C00, 0); if (!oauthToken.isValid()) { cemuLog_log(LogType::Force, "ACT_ACTConvertNnidToPrincipalId(): Failed to retrieve OAuth token"); if (oauthToken.apiError == NAPI_RESULT::SERVICE_ERROR) { result.apiError = NAPI_RESULT::SERVICE_ERROR; result.serviceError = oauthToken.serviceError; } else { result.apiError = NAPI_RESULT::DATA_ERROR; } return result; } // do request CurlRequestHelper req; req.initate(authInfo.GetService(), fmt::format("{}/v1/api/admin/mapped_ids?input_type=user_id&output_type=pid&input={}", _getACTUrl(authInfo.GetService()), nnid), CurlRequestHelper::SERVER_SSL_CONTEXT::ACT); _ACTSetCommonHeaderParameters(req, authInfo); _ACTSetDeviceParameters(req, authInfo); _ACTSetRegionAndCountryParameters(req, authInfo); req.addHeaderField("X-Nintendo-FPD-Version", "0000"); req.addHeaderField("X-Nintendo-Environment", "L1"); req.addHeaderField("X-Nintendo-Title-ID", fmt::format("{:016x}", 0x0005001010001C00)); uint32 uniqueId = 0x50010; req.addHeaderField("X-Nintendo-Unique-ID", fmt::format("{:05x}", uniqueId)); req.addHeaderField("X-Nintendo-Application-Version", fmt::format("{:04x}", 0)); req.addHeaderField("Authorization", fmt::format("Bearer {}", oauthToken.token)); if (!req.submitRequest(false)) { cemuLog_log(LogType::Force, fmt::format("Failed request /admin/mapped_ids")); result.apiError = NAPI_RESULT::FAILED; return result; } /* Example response (success): <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <mapped_ids> <mapped_id> <in_id>input-nnid</in_id> <out_id>12345</out_id> </mapped_id> </mapped_ids> */ // parse result pugi::xml_document doc; if (!_parseActResponse(req, result, doc)) return result; pugi::xml_node tokenNode = doc.child("mapped_ids"); if (!tokenNode) { cemuLog_log(LogType::Force, "Response does not contain mapped_ids node"); result.apiError = NAPI_RESULT::XML_ERROR; return result; } tokenNode = tokenNode.child("mapped_id"); if (!tokenNode) { cemuLog_log(LogType::Force, "Response does not contain mapped_id node"); result.apiError = NAPI_RESULT::XML_ERROR; return result; } std::string_view pidString = tokenNode.child_value("out_id"); if (!pidString.empty()) { result.isFound = true; result.principalId = StringHelpers::ToInt(pidString); } else { result.isFound = false; result.principalId = 0; } result.apiError = NAPI_RESULT::SUCCESS; return result; } bool NAPI_MakeAuthInfoFromCurrentAccount(AuthInfo& authInfo) { authInfo = {}; if (!NCrypto::SEEPROM_IsPresent()) return false; const Account& account = Account::GetCurrentAccount(); authInfo.accountId = account.GetAccountId(); auto passwordHash = account.GetAccountPasswordCache(); authInfo.passwordHash = passwordHash; if (std::all_of(passwordHash.cbegin(), passwordHash.cend(), [](uint8 v) { return v == 0; })) { static bool s_showedLoginError = false; if (!s_showedLoginError) { cemuLog_log(LogType::Force, "Account login is impossible because the cached password hash is not set"); s_showedLoginError = true; } return false; // password hash not set } authInfo.deviceId = NCrypto::GetDeviceId(); authInfo.serial = NCrypto::GetSerial(); authInfo.region = NCrypto::SEEPROM_GetRegion(); authInfo.country = NCrypto::GetCountryAsString(account.GetCountry()); authInfo.deviceCertBase64 = NCrypto::CertECC::GetDeviceCertificate().encodeToBase64(); return true; } }
21,655
C++
.cpp
563
35.062167
343
0.735658
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,940
napi_helper.cpp
cemu-project_Cemu/src/Cemu/napi/napi_helper.cpp
#include "Common/precompiled.h" #include "napi.h" #include "curl/curl.h" #include "Cafe/IOSU/legacy/iosu_crypto.h" #include "Cemu/ncrypto/ncrypto.h" #include "napi_helper.h" #include "util/highresolutiontimer/HighResolutionTimer.h" #include "config/ActiveSettings.h" #include "config/NetworkSettings.h" #include "config/LaunchSettings.h" #include "pugixml.hpp" #include <charconv> #include"openssl/bn.h" #include"openssl/x509.h" #include"openssl/ssl.h" CURLcode _sslctx_function_NUS(CURL* curl, void* sslctx, void* param) { if (iosuCrypto_addCACertificate(sslctx, 102) == false) { cemuLog_log(LogType::Force, "Invalid CA certificate (102)"); } if (iosuCrypto_addCACertificate(sslctx, 0x69) == false) { cemuLog_log(LogType::Force, "Invalid CA certificate (105)"); } if (iosuCrypto_addClientCertificate(sslctx, 3) == false) { cemuLog_log(LogType::Force, "Certificate error"); } SSL_CTX_set_mode((SSL_CTX*)sslctx, SSL_MODE_AUTO_RETRY); SSL_CTX_set_verify_depth((SSL_CTX*)sslctx, 2); SSL_CTX_set_verify((SSL_CTX*)sslctx, SSL_VERIFY_PEER, nullptr); return CURLE_OK; } CURLcode _sslctx_function_IDBE(CURL* curl, void* sslctx, void* param) { if (iosuCrypto_addCACertificate(sslctx, 105) == false) { cemuLog_log(LogType::Force, "Invalid CA certificate (105)"); } SSL_CTX_set_mode((SSL_CTX*)sslctx, SSL_MODE_AUTO_RETRY); SSL_CTX_set_verify_depth((SSL_CTX*)sslctx, 2); return CURLE_OK; } CURLcode _sslctx_function_SOAP(CURL* curl, void* sslctx, void* param) { if (iosuCrypto_addCACertificate(sslctx, 102) == false) { cemuLog_log(LogType::Force, "Invalid CA certificate (102)"); cemuLog_log(LogType::Force, "Certificate error"); } if (iosuCrypto_addClientCertificate(sslctx, 1) == false) { cemuLog_log(LogType::Force, "Certificate error"); } SSL_CTX_set_mode((SSL_CTX*)sslctx, SSL_MODE_AUTO_RETRY); SSL_CTX_set_verify_depth((SSL_CTX*)sslctx, 2); SSL_CTX_set_verify((SSL_CTX*)sslctx, SSL_VERIFY_PEER, nullptr); return CURLE_OK; } CURLcode _sslctx_function_OLIVE(CURL* curl, void* sslctx, void* param) { if (iosuCrypto_addCACertificate(sslctx, 105) == false) { cemuLog_log(LogType::Force, "Invalid CA certificate (105)"); cemuLog_log(LogType::Force, "Certificate error"); } if (iosuCrypto_addClientCertificate(sslctx, 7) == false) { cemuLog_log(LogType::Force, "Olive client certificate error"); } // NSSLAddServerPKIGroups(sslCtx, 3, &x, &y); { std::vector<sint16> certGroups = { 100, 101, 102, 103, 104, 105, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1019, 1020, 1021, 1022, 1023, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033 }; for (auto& certId : certGroups) iosuCrypto_addCACertificate(sslctx, certId); } SSL_CTX_set_mode((SSL_CTX*)sslctx, SSL_MODE_AUTO_RETRY); SSL_CTX_set_verify_depth((SSL_CTX*)sslctx, 2); SSL_CTX_set_verify((SSL_CTX*)sslctx, SSL_VERIFY_PEER, nullptr); return CURLE_OK; } CurlRequestHelper::CurlRequestHelper() { m_curl = curl_easy_init(); curl_easy_setopt(m_curl, CURLOPT_WRITEFUNCTION, __curlWriteCallback); curl_easy_setopt(m_curl, CURLOPT_WRITEDATA, this); curl_easy_setopt(m_curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(m_curl, CURLOPT_MAXREDIRS, 2); curl_easy_setopt(m_curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); if(GetConfig().proxy_server.GetValue() != "") { curl_easy_setopt(m_curl, CURLOPT_PROXY, GetConfig().proxy_server.GetValue().c_str()); } } CurlRequestHelper::~CurlRequestHelper() { curl_easy_cleanup(m_curl); } void CurlRequestHelper::initate(NetworkService service, std::string url, SERVER_SSL_CONTEXT sslContext) { // reset parameters m_headerExtraFields.clear(); m_postData.clear(); m_cbWriteCallback = nullptr; curl_easy_setopt(m_curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(m_curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_DEFAULT); curl_easy_setopt(m_curl, CURLOPT_TIMEOUT, 60); // SSL curl_easy_setopt(m_curl, CURLOPT_SSL_VERIFYPEER, 1L); if (IsNetworkServiceSSLDisabled(service)) { curl_easy_setopt(m_curl, CURLOPT_SSL_VERIFYPEER, 0L); } else if (sslContext == SERVER_SSL_CONTEXT::ACT || sslContext == SERVER_SSL_CONTEXT::TAGAYA) { curl_easy_setopt(m_curl, CURLOPT_SSL_CTX_FUNCTION, _sslctx_function_NUS); curl_easy_setopt(m_curl, CURLOPT_SSL_CTX_DATA, NULL); } else if (sslContext == SERVER_SSL_CONTEXT::IDBE) { curl_easy_setopt(m_curl, CURLOPT_SSL_CTX_FUNCTION, _sslctx_function_IDBE); curl_easy_setopt(m_curl, CURLOPT_SSL_CTX_DATA, NULL); } else if (sslContext == SERVER_SSL_CONTEXT::IAS || sslContext == SERVER_SSL_CONTEXT::ECS) { curl_easy_setopt(m_curl, CURLOPT_SSL_CTX_FUNCTION, _sslctx_function_SOAP); curl_easy_setopt(m_curl, CURLOPT_SSL_CTX_DATA, NULL); } else if (sslContext == SERVER_SSL_CONTEXT::CCS) { curl_easy_setopt(m_curl, CURLOPT_SSL_CTX_FUNCTION, _sslctx_function_SOAP); curl_easy_setopt(m_curl, CURLOPT_SSL_CTX_DATA, NULL); } else if (sslContext == SERVER_SSL_CONTEXT::OLIVE) { curl_easy_setopt(m_curl, CURLOPT_SSL_CTX_FUNCTION, _sslctx_function_OLIVE); curl_easy_setopt(m_curl, CURLOPT_SSL_CTX_DATA, NULL); } else { cemu_assert(false); } } void CurlRequestHelper::addHeaderField(const char* fieldName, std::string_view value) { m_headerExtraFields.emplace_back(fieldName, value); } void CurlRequestHelper::addPostField(const char* fieldName, std::string_view value) { if (!m_postData.empty()) m_postData.emplace_back('&'); m_postData.insert(m_postData.end(), (uint8*)fieldName, (uint8*)fieldName + strlen(fieldName)); m_postData.emplace_back('='); m_postData.insert(m_postData.end(), (uint8*)value.data(), (uint8*)value.data() + value.size()); } void CurlRequestHelper::setWriteCallback(bool(*cbWriteCallback)(void* userData, const void* ptr, size_t len, bool isLast), void* userData) { m_cbWriteCallback = cbWriteCallback; m_writeCallbackUserData = userData; } void CurlRequestHelper::setTimeout(sint32 time) { curl_easy_setopt(m_curl, CURLOPT_TIMEOUT, time); } size_t CurlRequestHelper::__curlWriteCallback(char* ptr, size_t size, size_t nmemb, void* userdata) { size_t writeByteSize = (size_t)(size * nmemb); CurlRequestHelper* curlHelper = (CurlRequestHelper*)userdata; if (curlHelper->m_cbWriteCallback) { if (!curlHelper->m_cbWriteCallback(curlHelper->m_writeCallbackUserData, ptr, writeByteSize, false)) return 0; return writeByteSize; } curlHelper->m_receiveBuffer.insert(curlHelper->m_receiveBuffer.end(), ptr, ptr + writeByteSize); return writeByteSize; } bool CurlRequestHelper::submitRequest(bool isPost) { // HTTP headers struct curl_slist* headers = nullptr; for (auto& itr : m_headerExtraFields) headers = curl_slist_append(headers, itr.data.c_str()); curl_easy_setopt(m_curl, CURLOPT_HTTPHEADER, headers); // post if (isPost) { if (!m_isUsingMultipartFormData) { curl_easy_setopt(m_curl, CURLOPT_POST, 1); curl_easy_setopt(m_curl, CURLOPT_POSTFIELDS, m_postData.data()); curl_easy_setopt(m_curl, CURLOPT_POSTFIELDSIZE, m_postData.size()); } } else curl_easy_setopt(m_curl, CURLOPT_POST, 0); // submit int res = curl_easy_perform(m_curl); if (res != CURLE_OK) { cemuLog_log(LogType::Force, "CURL web request failed with error {}. Retrying...", res); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // retry res = curl_easy_perform(m_curl); if (res != CURLE_OK) return false; } // check response code long httpCode = 0; curl_easy_getinfo(m_curl, CURLINFO_RESPONSE_CODE, &httpCode); if (httpCode != 200) { cemuLog_log(LogType::Force, "HTTP request received response {} but expected 200", httpCode); // error status codes (4xx or 5xx range) are always considered a failed request, except for code 400 which is usually returned as a response to failed logins etc. if (httpCode >= 400 && httpCode <= 599 && httpCode != 400) return false; // for other status codes we assume success if the message is non-empty if(m_receiveBuffer.empty()) return false; } if (m_cbWriteCallback) m_cbWriteCallback(m_writeCallbackUserData, nullptr, 0, true); // flush write return true; } CurlSOAPHelper::CurlSOAPHelper(NetworkService service) { m_curl = curl_easy_init(); curl_easy_setopt(m_curl, CURLOPT_WRITEFUNCTION, __curlWriteCallback); curl_easy_setopt(m_curl, CURLOPT_WRITEDATA, this); curl_easy_setopt(m_curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); // SSL if (!IsNetworkServiceSSLDisabled(service)) { curl_easy_setopt(m_curl, CURLOPT_SSL_CTX_FUNCTION, _sslctx_function_SOAP); curl_easy_setopt(m_curl, CURLOPT_SSL_CTX_DATA, NULL); curl_easy_setopt(m_curl, CURLOPT_SSL_VERIFYPEER, 1L); } else { curl_easy_setopt(m_curl, CURLOPT_SSL_VERIFYPEER, 0L); } if (GetConfig().proxy_server.GetValue() != "") { curl_easy_setopt(m_curl, CURLOPT_PROXY, GetConfig().proxy_server.GetValue().c_str()); } } CurlSOAPHelper::~CurlSOAPHelper() { curl_easy_cleanup(m_curl); } void CurlSOAPHelper::SOAP_initate(std::string_view serviceType, std::string url, std::string_view requestMethod, std::string_view requestVersion) { curl_easy_setopt(m_curl, CURLOPT_URL, url.c_str()); m_serviceType = serviceType; m_requestMethod = requestMethod; m_requestVersion = requestVersion; m_envelopeExtraParam.reserve(512); m_envelopeExtraParam.clear(); } void CurlSOAPHelper::SOAP_addRequestField(const char* fieldName, std::string_view value) { m_envelopeExtraParam.append(fmt::format("<{}:{}>{}</{}:{}>", m_serviceType, fieldName, value, m_serviceType, fieldName)); } void CurlSOAPHelper::SOAP_generateEnvelope() { m_envelopeStr.reserve(4096); m_envelopeStr.clear(); m_envelopeStr.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); m_envelopeStr.append("<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"\n"); m_envelopeStr.append(" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\"\n"); m_envelopeStr.append(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"); m_envelopeStr.append(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n"); m_envelopeStr.append(fmt::format(" xmlns:{}=\"urn:{}.wsapi.broadon.com\">\n", m_serviceType, m_serviceType)); m_envelopeStr.append("<SOAP-ENV:Body>\n"); m_envelopeStr.append(fmt::format("<{}:{} xsi:type=\"{}:{}RequestType\">\n", m_serviceType, m_requestMethod, m_serviceType, m_requestMethod)); m_envelopeStr.append(fmt::format("<{}:Version>{}</{}:Version>\n", m_serviceType, m_requestVersion, m_serviceType)); // the server echos the message id static uint64 s_msgHigh = 1 + (uint64)HighResolutionTimer::now().getTick()/7; uint64 msgId_high = s_msgHigh; // usually this is set to the deviceId uint64 msgId_low = (uint64)HighResolutionTimer::now().getTick(); // uptime m_envelopeStr.append(fmt::format("<{}:MessageId>EC-{}-{}</{}:MessageId>", m_serviceType, msgId_high, msgId_low, m_serviceType)); m_envelopeStr.append(m_envelopeExtraParam); // some fields are specific to services? // ECS doesnt seem to like RegionId and CountryCode // following fields are shared: // >>> Region, Country, Language // following fields are present when NUS: // >>> RegionId (instead of Region), CountryCode (instead of Country) // following fields are present when CAS or ECS: // >>> ApplicationId, TIN, SerialNo // following fields are present when CAS: // >>> Age // following fields are present when ECS: // >>> SessionHandle, ServiceTicket, ServiceId // following fields for anything that isn't BGS: // >>> DeviceId (the serial) // DeviceId -> All except BGS (deviceId is the console serial) // DeviceToken -> Everything except BGS and NUS // ECS: //m_envelopeStr.append(fmt::format("<{}:Region>EUR</{}:Region>", serviceType, serviceType)); //m_envelopeStr.append(fmt::format("<{}:Country>AT</{}:Country>", serviceType, serviceType)); // device token format: // <ECS:DeviceToken>WT-<md5hash_in_hex></ECS:DeviceToken> // unknown fields: // VirtualDeviceType (shared but optional?) // device cert not needed for ECS:GetAccountStatus ? (it complains if present) //char deviceCertStr[1024 * 4]; //iosuCrypto_getDeviceCertificateBase64Encoded(deviceCertStr); //m_envelopeStr.append(fmt::format("<{}:DeviceCert>{}</{}:DeviceCert>", serviceType, deviceCertStr, serviceType)); // only device token needed // DeviceToken comes from GetRegistrationInfo and is then stored in ec_account_info.exi m_envelopeStr.append(fmt::format("</{}:{}>\n", m_serviceType, m_requestMethod)); m_envelopeStr.append("</SOAP-ENV:Body>\n"); m_envelopeStr.append("</SOAP-ENV:Envelope>\n"); } sint32 iosuCrypto_getDeviceCertificateBase64Encoded(char* output); bool CurlSOAPHelper::submitRequest() { // generate and set envelope SOAP_generateEnvelope(); curl_easy_setopt(m_curl, CURLOPT_POST, 1); curl_easy_setopt(m_curl, CURLOPT_POSTFIELDS, m_envelopeStr.c_str()); curl_easy_setopt(m_curl, CURLOPT_POSTFIELDSIZE, m_envelopeStr.size()); // generate and set headers struct curl_slist* headers = NULL; headers = curl_slist_append(headers, "Content-Type: text/xml; charset=utf-8"); headers = curl_slist_append(headers, "Accept-Charset: UTF-8"); headers = curl_slist_append(headers, fmt::format("SOAPAction: urn:{}.wsapi.broadon.com/{}", m_serviceType, m_requestMethod).c_str()); headers = curl_slist_append(headers, "Accept: */*"); curl_easy_setopt(m_curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(m_curl, CURLOPT_USERAGENT, "EVL NUP 040800 Sep 18 2012 20:20:02"); // send request auto res = curl_easy_perform(m_curl); return res == CURLE_OK; } /* helper functions */ namespace NAPI { bool _findXmlNode(pugi::xml_node& doc, pugi::xml_node& nodeOut, const char* name) { for (auto& itr : doc.children()) { if (boost::iequals(itr.name(), name)) { nodeOut = itr; return true; } if (_findXmlNode(itr, nodeOut, name)) return true; } return false; } bool _parseResponseInit(const CurlSOAPHelper& soapHelper, const char* responseNodeName, pugi::xml_node& node, _NAPI_CommonResultSOAP& result, pugi::xml_document& doc, pugi::xml_node& responseNode) { // parse XML response if (!doc.load_buffer(soapHelper.getReceivedData().data(), soapHelper.getReceivedData().size())) { cemuLog_log(LogType::Force, "Failed to parse GetRegistrationInfo() response"); result.apiError = NAPI_RESULT::XML_ERROR; return false; } if (!_findXmlNode(doc, node, responseNodeName)) { result.apiError = NAPI_RESULT::XML_ERROR; return false; } // parse error code auto errorCodeStr = node.child_value("ErrorCode"); if (!errorCodeStr) { result.apiError = NAPI_RESULT::XML_ERROR; return false; } int parsedErrorCode = 0; std::from_chars_result fcr = std::from_chars(errorCodeStr, errorCodeStr + strlen(errorCodeStr), parsedErrorCode); if (fcr.ec == std::errc::invalid_argument || fcr.ec == std::errc::result_out_of_range) { result.apiError = NAPI_RESULT::XML_ERROR; return false; } if (parsedErrorCode != 0) { result.serviceError = (EC_ERROR_CODE)parsedErrorCode; result.apiError = NAPI_RESULT::SERVICE_ERROR; return false; } result.apiError = NAPI_RESULT::SUCCESS; return true; } };
15,160
C++
.cpp
396
35.962121
197
0.732757
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,941
DownloadManager.cpp
cemu-project_Cemu/src/Cemu/Tools/DownloadManager/DownloadManager.cpp
#include "Cemu/Tools/DownloadManager/DownloadManager.h" #include "Cafe/Account/Account.h" #include "gui/CemuApp.h" #include "util/crypto/md5.h" #include "Cafe/TitleList/TitleId.h" #include "Common/FileStream.h" #include "Cemu/FileCache/FileCache.h" #include "Cemu/ncrypto/ncrypto.h" #include "config/ActiveSettings.h" #include "util/ThreadPool/ThreadPool.h" #include "util/helpers/enum_array.hpp" #include "gui/MainWindow.h" #include "Cafe/Filesystem/FST/FST.h" #include "Cafe/TitleList/TitleList.h" #include <cinttypes> #include <charconv> #include <curl/curl.h> #include <pugixml.hpp> #include "gui/helpers/wxHelpers.h" #include "Cemu/napi/napi.h" #include "util/helpers/Serializer.h" FileCache* s_nupFileCache = nullptr; /* version list */ void DownloadManager::downloadTitleVersionList() { if (m_hasTitleVersionList) return; NAPI::AuthInfo authInfo = GetAuthInfo(false); auto versionListVersionResult = NAPI::TAG_GetVersionListVersion(authInfo); if (!versionListVersionResult.isValid) return; auto versionListResult = TAG_GetVersionList(authInfo, versionListVersionResult.fqdnURL, versionListVersionResult.version); if (!versionListResult.isValid) return; m_titleVersionList = versionListResult.titleVersionList; m_hasTitleVersionList = true; } // grab latest version from TAG version list. Returns false if titleId is not found in the list bool DownloadManager::getTitleLatestVersion(TitleId titleId, uint16& version) { auto titleVersionAvailability = m_titleVersionList.find(titleId); if (titleVersionAvailability == m_titleVersionList.end()) return false; version = titleVersionAvailability->second; return true; } /* helper method to generate list of owned base titles */ DownloadManager::TitleInstallState::TitleInstallState(DownloadManager* dlMgr, uint64 titleId) : titleId(titleId) { uint16 vers; if (CafeTitleList::HasTitle(titleId, vers)) { isInstalled = true; installedTitleVersion = vers; } else { isInstalled = false; installedTitleVersion = 0; } installedTicketVersion = 0; // for DLC we also retrieve the ticket version from the installed title.tik // todo - avoid file reads here due to stalling the UI thread if (TitleIdParser(titleId).GetType() == TitleIdParser::TITLE_TYPE::AOC) { const auto ticketPath = ActiveSettings::GetMlcPath(L"usr/title/{:08x}/{:08x}/code/title.tik", (uint32)(titleId >> 32), (uint32)(titleId & 0xFFFFFFFF)); uint32 tikFileSize = 0; FileStream* fileStream = FileStream::openFile2(ticketPath); if (fileStream) { std::vector<uint8> tikData; fileStream->extract(tikData); NCrypto::ETicketParser eTicket; if (eTicket.parse(tikData.data(), tikData.size())) installedTicketVersion = eTicket.GetTicketVersion(); delete fileStream; } } } DownloadManager::TitleDownloadAvailableState::TitleDownloadAvailableState(DownloadManager* dlMgr, uint64 titleId) : TitleInstallState(dlMgr, titleId) { // get latest available version of this title (from the TAG version list) uint16 vers; if (dlMgr->getTitleLatestVersion(titleId, vers)) { isUpdateAvailable = true; availableTitleVersion = vers; } else { isUpdateAvailable = false; availableTitleVersion = 0; } }; std::set<DownloadManager::TitleInstallState> DownloadManager::getOwnedTitleList() { std::set<DownloadManager::TitleInstallState> ownedTitleList; // add installed games and DLC std::vector<TitleId> installedTitleIds = CafeTitleList::GetAllTitleIds(); for (auto& itr : installedTitleIds) { TitleIdParser titleIdParser(itr); auto titleType = titleIdParser.GetType(); if (titleType == TitleIdParser::TITLE_TYPE::BASE_TITLE || titleType == TitleIdParser::TITLE_TYPE::BASE_TITLE_DEMO || titleType == TitleIdParser::TITLE_TYPE::SYSTEM_OVERLAY_TITLE) { ownedTitleList.emplace(this, itr); } } // add ticket cache for (auto& itr : m_ticketCache) { TitleIdParser titleIdParser(itr.titleId); auto titleType = titleIdParser.GetType(); if (titleType == TitleIdParser::TITLE_TYPE::BASE_TITLE || titleType == TitleIdParser::TITLE_TYPE::BASE_TITLE_DEMO || titleType == TitleIdParser::TITLE_TYPE::SYSTEM_OVERLAY_TITLE || titleType == TitleIdParser::TITLE_TYPE::AOC) { ownedTitleList.emplace(this, itr.titleId); } } return ownedTitleList; } std::set<DownloadManager::TitleDownloadAvailableState> DownloadManager::getFullDownloadList() { std::set<DownloadManager::TitleDownloadAvailableState> fullList; // get list of owned titles std::set<DownloadManager::TitleInstallState> ownedTitleList = getOwnedTitleList(); // add each owned title, but also check for separate updates if available for (auto& itr : ownedTitleList) { TitleIdParser titleIdParser(itr.titleId); fullList.emplace(this, itr.titleId); if (titleIdParser.CanHaveSeparateUpdateTitleId()) { uint64 updateTitleId = titleIdParser.GetSeparateUpdateTitleId(); uint16 tempVers; if (getTitleLatestVersion(updateTitleId, tempVers)) fullList.emplace(this, updateTitleId); } } return fullList; } /* connect */ struct StoredTokenInfo : public SerializerHelper { bool serializeImpl(MemStreamWriter& streamWriter) { streamWriter.writeBE<uint8>(0); streamWriter.writeBE<std::string>(accountId); streamWriter.writeBE<std::string>(deviceToken); return true; } bool deserializeImpl(MemStreamReader& streamReader) { auto version = streamReader.readBE<uint8>(); if (version != 0) return false; accountId = streamReader.readBE<std::string>(); deviceToken = streamReader.readBE<std::string>(); return !streamReader.hasError(); } public: std::string accountId; std::string deviceToken; }; bool DownloadManager::_connect_refreshIASAccountIdAndDeviceToken() { NAPI::AuthInfo authInfo = GetAuthInfo(false); // query IAS/ECS account id and device token (if not cached) auto rChallenge = NAPI::IAS_GetChallenge(authInfo); if (rChallenge.apiError != NAPI_RESULT::SUCCESS) return false; auto rRegistrationInfo = NAPI::IAS_GetRegistrationInfo_QueryInfo(authInfo, rChallenge.challenge); if (rRegistrationInfo.apiError != NAPI_RESULT::SUCCESS) return false; m_iasToken.serviceAccountId = rRegistrationInfo.accountId; m_iasToken.deviceToken = rRegistrationInfo.deviceToken; // store to cache StoredTokenInfo storedTokenInfo; storedTokenInfo.accountId = rRegistrationInfo.accountId; storedTokenInfo.deviceToken = rRegistrationInfo.deviceToken; std::vector<uint8> serializedData; if (!storedTokenInfo.serialize(serializedData)) return false; s_nupFileCache->AddFileAsync({ fmt::format("{}/token_info", m_authInfo.cachefileName) }, serializedData.data(), serializedData.size()); return true; } bool DownloadManager::_connect_queryAccountStatusAndServiceURLs() { NAPI::AuthInfo authInfo = GetAuthInfo(true); NAPI::NAPI_ECSGetAccountStatus_Result accountStatusResult = NAPI::ECS_GetAccountStatus(authInfo); if (accountStatusResult.apiError != NAPI_RESULT::SUCCESS) { cemuLog_log(LogType::Force, "ECS - Failed to query account status (error: {0} {1})", accountStatusResult.apiError, accountStatusResult.serviceError); return false; } if (accountStatusResult.accountStatus == NAPI::NAPI_ECSGetAccountStatus_Result::AccountStatus::UNREGISTERED) { cemuLog_log(LogType::Force, fmt::format("ECS - Account is not registered")); return false; } return true; } // constructor for ticket cache entry DownloadManager::ETicketInfo::ETicketInfo(SOURCE source, uint64 ticketId, uint32 ticketVersion, std::vector<uint8>& eTicket) : source(source), ticketId(ticketId), ticketVersion(ticketVersion), eTicket(eTicket) { NCrypto::ETicketParser eTicketParser; if (!eTicketParser.parse(eTicket.data(), eTicket.size())) { titleId = (uint64)-1; return; } cemu_assert_debug(!eTicketParser.IsPersonalized()); // ticket should have been depersonalized already titleId = eTicketParser.GetTitleId(); ticketVersion = eTicketParser.GetTicketVersion(); cemu_assert_debug(ticketId == eTicketParser.GetTicketId()); cemu_assert_debug(ticketVersion == eTicketParser.GetTicketVersion()); } DownloadManager::ETicketInfo::ETicketInfo(SOURCE source, uint64 ticketId, uint32 ticketVersion, std::vector<uint8>& eTicket, std::vector<std::vector<uint8>>& eTicketCerts) : ETicketInfo(source, ticketId, ticketVersion, eTicket) { this->eTicketCerts = eTicketCerts; } void DownloadManager::ETicketInfo::GetTitleKey(NCrypto::AesKey& key) { NCrypto::ETicketParser eTicketParser; cemu_assert_debug(eTicketParser.parse(eTicket.data(), eTicket.size())); eTicketParser.GetTitleKey(key); } void DownloadManager::loadTicketCache() { m_ticketCache.clear(); cemu_assert_debug(m_ticketCache.empty()); std::vector<uint8> ticketCacheBlob; if (!s_nupFileCache->GetFile({ fmt::format("{}/eticket_cache", m_authInfo.cachefileName) }, ticketCacheBlob)) return; MemStreamReader memReader(ticketCacheBlob.data(), ticketCacheBlob.size()); uint8 version = memReader.readBE<uint8>(); if (version != 1) return; // unsupported version uint32 numTickets = memReader.readBE<uint32>(); for (uint32 i = 0; i < numTickets; i++) { if (memReader.hasError()) { m_ticketCache.clear(); return; } ETicketInfo::SOURCE source = (ETicketInfo::SOURCE)memReader.readBE<uint8>(); if (source != ETicketInfo::SOURCE::ECS_TICKET && source != ETicketInfo::SOURCE::PUBLIC_TICKET) { m_ticketCache.clear(); return; } uint64 ticketId = memReader.readBE<uint64>(); uint64 ticketVersion = memReader.readBE<uint32>(); std::vector<uint8> eTicketData = memReader.readPODVector<uint8>(); std::vector<std::vector<uint8>> eTicketCerts; uint8 certCount = memReader.readBE<uint8>(); for (uint32 c = 0; c < certCount; c++) eTicketCerts.emplace_back(memReader.readPODVector<uint8>()); if (memReader.hasError()) { m_ticketCache.clear(); return; } m_ticketCache.emplace_back(source, ticketId, ticketVersion, eTicketData, eTicketCerts); } } void DownloadManager::storeTicketCache() { MemStreamWriter memWriter(1024*32); memWriter.writeBE<uint8>(1); // version memWriter.writeBE<uint32>((uint32)m_ticketCache.size()); for (auto& eTicket : m_ticketCache) { memWriter.writeBE<uint8>((uint8)eTicket.source); memWriter.writeBE<uint64>(eTicket.ticketId); memWriter.writeBE<uint32>(eTicket.ticketVersion); memWriter.writePODVector(eTicket.eTicket); memWriter.writeBE<uint8>(eTicket.eTicketCerts.size()); for (auto& cert : eTicket.eTicketCerts) memWriter.writePODVector(cert); } auto serializedBlob = memWriter.getResult(); s_nupFileCache->AddFileAsync({ fmt::format("{}/eticket_cache", m_authInfo.cachefileName) }, serializedBlob.data(), serializedBlob.size()); } bool DownloadManager::syncAccountTickets() { NAPI::AuthInfo authInfo = GetAuthInfo(true); // query TIV list from server NAPI::NAPI_ECSAccountListETicketIds_Result resultTicketIds = NAPI::ECS_AccountListETicketIds(authInfo); if (!resultTicketIds.isValid()) return false; // download uncached tickets size_t count = resultTicketIds.tivs.size(); size_t index = 0; for (auto& tiv : resultTicketIds.tivs) { index++; std::string msg = _("Downloading account ticket").utf8_string(); msg.append(fmt::format(" {0}/{1}", index, count)); setStatusMessage(msg, DLMGR_STATUS_CODE::CONNECTING); // skip if already cached ETicketInfo* cachedTicket = findTicketByTicketId(tiv.ticketId); if (cachedTicket) { if(cachedTicket->ticketVersion == tiv.ticketVersion) continue; // ticket version mismatch, redownload deleteTicketByTicketId(tiv.ticketId); } // get ECS ticket auto resultETickets = NAPI::ECS_AccountGetETickets(authInfo, tiv.ticketId); if (!resultETickets.isValid()) { cemuLog_log(LogType::Force, "SyncTicketCache: Account ETicket invalid"); continue; } // verify ticket integrity NCrypto::ETicketParser eTicketParser; if (!eTicketParser.parse(resultETickets.eTickets.data(), resultETickets.eTickets.size())) continue; uint64 titleId = eTicketParser.GetTitleId(); cemu_assert_debug(eTicketParser.GetTicketId() == tiv.ticketId); cemu_assert_debug(eTicketParser.GetTicketVersion() == tiv.ticketVersion); // depersonalize the ticket if (eTicketParser.IsPersonalized()) { NCrypto::ECCPrivKey privKey = NCrypto::ECCPrivKey::getDeviceCertPrivateKey(); if (!eTicketParser.Depersonalize(resultETickets.eTickets.data(), resultETickets.eTickets.size(), m_authInfo.deviceId, privKey)) { cemuLog_log(LogType::Force, "DownloadManager: Failed to depersonalize ticket"); continue; } // reparse cemu_assert(eTicketParser.parse(resultETickets.eTickets.data(), resultETickets.eTickets.size())); } else { cemuLog_log(LogType::Force, "DownloadManager: Unexpected result. ECS ticket not personalized"); continue; } ETicketInfo eTicket(ETicketInfo::SOURCE::ECS_TICKET, tiv.ticketId, tiv.ticketVersion, resultETickets.eTickets, resultETickets.certs); m_ticketCache.emplace_back(eTicket); } return true; } bool DownloadManager::syncSystemTitleTickets() { setStatusMessage(_("Downloading system tickets...").utf8_string(), DLMGR_STATUS_CODE::CONNECTING); NAPI::AuthInfo authInfo = GetAuthInfo(true); auto querySystemTitleTicket = [&](uint64 titleId) -> void { // check if cached already // todo - how do we know which version to query? System titles seem to use hashes? if (findFirstTicketByTitleId(titleId)) return; // request ticket auto resultCommonETicket = NAPI::NUS_GetSystemCommonETicket(authInfo, titleId); if (!resultCommonETicket.isValid()) return; // parse and validate ticket NCrypto::ETicketParser eTicketParser; if (!eTicketParser.parse(resultCommonETicket.eTicket.data(), resultCommonETicket.eTicket.size())) return; if (eTicketParser.GetTitleId() != titleId) return; if (eTicketParser.IsPersonalized()) return; // add to eTicket cache ETicketInfo eTicket(ETicketInfo::SOURCE::PUBLIC_TICKET, eTicketParser.GetTicketId(), eTicketParser.GetTicketVersion(), resultCommonETicket.eTicket, resultCommonETicket.certs); m_ticketCache.emplace_back(eTicket); }; if (m_authInfo.region == CafeConsoleRegion::EUR) { querySystemTitleTicket(0x000500301001420A); // eShop querySystemTitleTicket(0x000500301001520A); // Friend List querySystemTitleTicket(0x000500301001220A); // Internet browser } else if (m_authInfo.region == CafeConsoleRegion::USA) { querySystemTitleTicket(0x000500301001410A); // eShop querySystemTitleTicket(0x000500301001510A); // Friend List querySystemTitleTicket(0x000500301001210A); // Internet browser } else if (m_authInfo.region == CafeConsoleRegion::JPN) { querySystemTitleTicket(0x000500301001400A); // eShop querySystemTitleTicket(0x000500301001500A); // Friend List querySystemTitleTicket(0x000500301001200A); // Internet browser } return true; } // build list of updates for which either an installed game exists or the base title ticket is cached bool DownloadManager::syncUpdateTickets() { setStatusMessage(_("Retrieving update information...").utf8_string(), DLMGR_STATUS_CODE::CONNECTING); // download update version list downloadTitleVersionList(); if (!m_hasTitleVersionList) return false; std::set<DownloadManager::TitleDownloadAvailableState> downloadList = getFullDownloadList(); // count updates size_t numUpdates = 0; for (auto& itr : downloadList) { TitleIdParser titleIdParser(itr.titleId); if (titleIdParser.GetType() == TitleIdParser::TITLE_TYPE::BASE_TITLE_UPDATE) numUpdates++; } // get tickets for all the updates size_t updateIndex = 0; for (auto& itr : downloadList) { TitleIdParser titleIdParser(itr.titleId); if (titleIdParser.GetType() != TitleIdParser::TITLE_TYPE::BASE_TITLE_UPDATE) continue; std::string msg = _("Downloading ticket").utf8_string(); msg.append(fmt::format(" {0}/{1}", updateIndex, numUpdates)); updateIndex++; setStatusMessage(msg, DLMGR_STATUS_CODE::CONNECTING); if (!itr.isUpdateAvailable) continue; // skip if already cached if (findTicketByTitleIdAndVersion(itr.titleId, itr.availableTitleVersion)) continue; auto cetkResult = NAPI::CCS_GetCETK(GetDownloadMgrNetworkService(), itr.titleId, itr.availableTitleVersion); if (!cetkResult.isValid) continue; NCrypto::ETicketParser ticketParser; if (!ticketParser.parse(cetkResult.cetkData.data(), cetkResult.cetkData.size())) continue; uint64 ticketId = ticketParser.GetTicketId(); uint64 ticketTitleId = ticketParser.GetTitleId(); uint16 ticketTitleVersion = ticketParser.GetTicketVersion(); uint16 ticketVersion = ticketTitleVersion; if (ticketTitleId != itr.titleId) continue; if (ticketTitleVersion != itr.availableTitleVersion) { cemuLog_log(LogType::Force, "Ticket for title update has a mismatching version"); continue; } // add to eTicket cache ETicketInfo eTicket(ETicketInfo::SOURCE::PUBLIC_TICKET, ticketId, ticketVersion, cetkResult.cetkData); m_ticketCache.emplace_back(eTicket); } return true; } // synchronize ticket cache with server and request uncached ticket data bool DownloadManager::syncTicketCache() { if (!syncAccountTickets()) return false; syncSystemTitleTickets(); syncUpdateTickets(); storeTicketCache(); // make sure IDBE's are loaded into memory for all eTickets (potential downloads) // this will only download them if they aren't already in the on-disk cache size_t count = m_ticketCache.size(); size_t index = 0; for (auto& ticketInfo : m_ticketCache) { index++; std::string msg = _("Downloading meta data").utf8_string(); msg.append(fmt::format(" {0}/{1}", index, count)); setStatusMessage(msg, DLMGR_STATUS_CODE::CONNECTING); prepareIDBE(ticketInfo.titleId); } setStatusMessage(_("Connected. Right click entries in the list to start downloading").utf8_string(), DLMGR_STATUS_CODE::CONNECTED); return true; } void DownloadManager::searchForIncompleteDownloads() { const fs::path packagePath = ActiveSettings::GetMlcPath("usr/packages/title/"); if (!fs::exists(packagePath)) return; for (auto& p : fs::directory_iterator(packagePath)) { uint64 titleId; uint32 version; std::string name = p.path().filename().generic_string(); if( sscanf(name.c_str(), "cemu_%" PRIx64 "_v%u", &titleId, &version) != 2) continue; std::unique_lock<std::recursive_mutex> _l(m_mutex); for (auto& itr : m_ticketCache) m_unfinishedDownloads.emplace_back(titleId, version); } } void DownloadManager::reportAvailableTitles() { if (!m_cbAddDownloadableTitle) return; std::set<DownloadManager::TitleDownloadAvailableState> downloadList = getFullDownloadList(); for (auto& itr : downloadList) { TitleIdParser titleIdParser(itr.titleId); TitleIdParser::TITLE_TYPE titleType = titleIdParser.GetType(); if (titleType == TitleIdParser::TITLE_TYPE::BASE_TITLE || titleType == TitleIdParser::TITLE_TYPE::BASE_TITLE_DEMO || titleType == TitleIdParser::TITLE_TYPE::SYSTEM_OVERLAY_TITLE || titleType == TitleIdParser::TITLE_TYPE::BASE_TITLE_UPDATE || titleType == TitleIdParser::TITLE_TYPE::AOC) { // show entries only if we were able to retrieve the ticket if (itr.isInstalled) { if (!findFirstTicketByTitleId(itr.titleId)) continue; } DlMgrTitleReport::STATUS status = DlMgrTitleReport::STATUS::INSTALLABLE; bool aocHasUpdate = false; if (itr.isInstalled && titleType == TitleIdParser::TITLE_TYPE::AOC) { ETicketInfo* eTicketInfo = findFirstTicketByTitleId(itr.titleId); if (eTicketInfo && eTicketInfo->ticketVersion > itr.installedTicketVersion) aocHasUpdate = true; } if (itr.isInstalled && itr.installedTitleVersion >= itr.availableTitleVersion && aocHasUpdate == false) { status = DlMgrTitleReport::STATUS::INSTALLED; } if (status == DlMgrTitleReport::STATUS::INSTALLABLE) { if (hasPartialDownload(itr.titleId, itr.availableTitleVersion)) status = DlMgrTitleReport::STATUS::INSTALLABLE_UNFINISHED; if (aocHasUpdate) status = DlMgrTitleReport::STATUS::INSTALLABLE_UPDATE; } DlMgrTitleReport titleInfo(status, itr.titleId, itr.availableTitleVersion, getNameFromCachedIDBE(itr.titleId), 0, 0, false); m_cbAddDownloadableTitle(titleInfo); } else { cemu_assert_debug(false); // unsupported title type } } } /* connection logic */ void DownloadManager::_handle_connect() { m_connectState.store(CONNECT_STATE::PROCESSING); // reset login state m_iasToken.serviceAccountId.clear(); m_iasToken.deviceToken.clear(); setStatusMessage(_("Logging in...").utf8_string(), DLMGR_STATUS_CODE::CONNECTING); // retrieve ECS AccountId + DeviceToken from cache if (s_nupFileCache) { std::vector<uint8> serializationBlob; if (s_nupFileCache->GetFile({ fmt::format("{}/token_info", m_authInfo.cachefileName) }, serializationBlob)) { StoredTokenInfo storedTokenInfo; if (storedTokenInfo.deserialize(serializationBlob)) { m_iasToken.serviceAccountId = storedTokenInfo.accountId; m_iasToken.deviceToken = storedTokenInfo.deviceToken; } } } // .. or request AccountId and DeviceToken if not cached if (m_iasToken.serviceAccountId.empty() || m_iasToken.deviceToken.empty()) { if (!_connect_refreshIASAccountIdAndDeviceToken()) { cemuLog_log(LogType::Force, "Failed to request IAS token"); cemu_assert_debug(false); m_connectState.store(CONNECT_STATE::FAILED); setStatusMessage(_("Login failed. Outdated or incomplete online files?").utf8_string(), DLMGR_STATUS_CODE::FAILED); return; } } // get EC account status and service urls if (!_connect_queryAccountStatusAndServiceURLs()) { m_connectState.store(CONNECT_STATE::FAILED); setStatusMessage(_("Failed to query account status").utf8_string(), DLMGR_STATUS_CODE::FAILED); return; } // load ticket cache and sync setStatusMessage(_("Updating ticket cache").utf8_string(), DLMGR_STATUS_CODE::CONNECTING); loadTicketCache(); if (!syncTicketCache()) { m_connectState.store(CONNECT_STATE::FAILED); setStatusMessage(_("Failed to request tickets").utf8_string(), DLMGR_STATUS_CODE::FAILED); return; } searchForIncompleteDownloads(); // notify about all available downloadable titles reportAvailableTitles(); // print ticket info m_connectState.store(CONNECT_STATE::COMPLETE); } void DownloadManager::connect( std::string_view nnidAccountName, const std::array<uint8, 32>& passwordHash, CafeConsoleRegion region, std::string_view country, uint32 deviceId, std::string_view serial, std::string_view deviceCertBase64) { runManager(); m_authInfo.nnidAccountName = nnidAccountName; m_authInfo.passwordHash = passwordHash; m_authInfo.cachefileName = nnidAccountName.empty() ? "DefaultName" : nnidAccountName; m_authInfo.region = region; m_authInfo.country = country; m_authInfo.deviceCertBase64 = deviceCertBase64; m_authInfo.deviceId = deviceId; m_authInfo.serial = serial; m_connectState.store(CONNECT_STATE::REQUESTED); notifyManager(); queueManagerJob([this]() {_handle_connect(); }); } bool DownloadManager::IsConnected() const { return m_connectState.load() != CONNECT_STATE::UNINITIALIZED; } NetworkService DownloadManager::GetDownloadMgrNetworkService() { return NetworkService::Nintendo; } NAPI::AuthInfo DownloadManager::GetAuthInfo(bool withIasToken) { NAPI::AuthInfo authInfo; authInfo.serviceOverwrite = GetDownloadMgrNetworkService(); authInfo.accountId = m_authInfo.nnidAccountName; authInfo.passwordHash = m_authInfo.passwordHash; authInfo.deviceId = m_authInfo.deviceId; authInfo.serial = m_authInfo.serial; authInfo.country = m_authInfo.country; authInfo.region = m_authInfo.region; authInfo.deviceCertBase64 = m_authInfo.deviceCertBase64; if(withIasToken) { cemu_assert_debug(!m_iasToken.serviceAccountId.empty()); authInfo.IASToken.accountId = m_iasToken.serviceAccountId; authInfo.IASToken.deviceToken = m_iasToken.deviceToken; } return authInfo; } /* package / downloading */ // start/resume/retry download void DownloadManager::initiateDownload(uint64 titleId, uint16 version) { std::unique_lock<std::recursive_mutex> _l(m_mutex); Package* package = getPackage(titleId, version); if (package) { // remove pause state package->state.isPaused = false; // already exists, erase error state if (package->state.hasError) { package->state.hasError = false; reportPackageStatus(package); } checkPackagesState(); return; } // find matching eTicket and get key std::vector<uint8>* ticketData = nullptr; for (auto& ticket : m_ticketCache) { if (ticket.titleId == titleId )//&& ticket.version == version) { ticketData = &ticket.eTicket; break; } } if (!ticketData) return; package = new Package(titleId, version, *ticketData); m_packageList.emplace_back(package); reportPackageStatus(package); checkPackagesState(); // will start downloading this package if none already active } void DownloadManager::pauseDownload(uint64 titleId, uint16 version) { std::unique_lock<std::recursive_mutex> _l(m_mutex); Package* package = getPackage(titleId, version); if (!package || !package->state.isActive) return; package->state.isPaused = true; package->state.isActive = false; reportPackageStatus(package); checkPackagesState(); } DownloadManager::Package* DownloadManager::getPackage(uint64 titleId, uint16 version) { std::unique_lock<std::recursive_mutex> _l(m_mutex); auto itr = std::find_if(m_packageList.begin(), m_packageList.end(), [titleId, version](const Package* v) { return v->titleId == titleId && v->version == version; }); if (itr == m_packageList.end()) return nullptr; return *itr; } fs::path DownloadManager::getPackageDownloadPath(Package* package) { return ActiveSettings::GetMlcPath(fmt::format("usr/packages/title/cemu_{:016x}_v{}/", package->titleId, package->version)); } fs::path DownloadManager::getPackageInstallPath(Package* package) { TitleIdParser tParser(package->titleId); const char* titleBasePath = "usr/title/"; if(tParser.IsSystemTitle()) titleBasePath = "sys/title/"; return ActiveSettings::GetMlcPath(fmt::format("{}{:08x}/{:08x}/", titleBasePath, (uint32)(package->titleId>>32), (uint32)package->titleId)); } // called when a package becomes active (queued to downloading) or when any of it's async download operations finishes // initiates new async download, decrypt or install tasks void DownloadManager::updatePackage(Package* package) { std::unique_lock<std::recursive_mutex> _l(m_mutex); if (!package->state.isActive || package->state.isPaused || package->state.hasError) return; // do we have the TMD downloaded yet? if (!package->state.tmd) { if (!package->state.isDownloadingTMD) { package->state.isDownloadingTMD = true; ThreadPool::FireAndForget(&DownloadManager::asyncPackageDownloadTMD, this, package); } return; } using ContentState = Package::ContentFile::STATE; // count state totals struct ContentCountInfo { uint32 total{}; uint32 processing{}; }; enum_array<Package::ContentFile::STATE, ContentCountInfo> contentCountTable; for (auto& itr : package->state.contentFiles) { auto state = itr.second.currentState; contentCountTable[state].total++; if(itr.second.isBeingProcessed) contentCountTable[state].processing++; } // utility method to grab next inactive content entry with a specific state auto getFirstInactiveContentByState = [&](ContentState state) -> Package::ContentFile* { auto itr = std::find_if(package->state.contentFiles.begin(), package->state.contentFiles.end(), [state](const auto& contentFile) {return contentFile.second.currentState == state && !contentFile.second.isBeingProcessed; }); if (itr == package->state.contentFiles.end()) return nullptr; return &(itr->second); }; /************* content check phase *************/ if (package->state.currentState == Package::STATE::INITIAL) { package->state.currentState = Package::STATE::CHECKING; package->state.progress = 0; package->state.progressMax = (uint32)package->state.contentFiles.size(); reportPackageStatus(package); } while (contentCountTable[ContentState::CHECK].total > 0 && contentCountTable[ContentState::CHECK].processing < 2) { Package::ContentFile* contentPtr = getFirstInactiveContentByState(ContentState::CHECK); if (!contentPtr) break; contentPtr->isBeingProcessed = true; ThreadPool::FireAndForget(&DownloadManager::asyncPackageVerifyFile, this, package, contentPtr->index, true); contentCountTable[ContentState::CHECK].processing++; } if (contentCountTable[ContentState::CHECK].total > 0) return; // dont proceed to next phase until done /************* content download phase *************/ while (contentCountTable[ContentState::DOWNLOAD].total > 0 && contentCountTable[ContentState::DOWNLOAD].processing < 2) { if (package->state.currentState == Package::STATE::CHECKING || package->state.currentState == Package::STATE::VERIFYING) { package->state.currentState = Package::STATE::DOWNLOADING; package->state.progress = 0; package->state.progressMax = 0; reportPackageStatus(package); } // download next file if there aren't 2 active downloads already Package::ContentFile* contentPtr = getFirstInactiveContentByState(ContentState::DOWNLOAD); if (!contentPtr) break; contentPtr->isBeingProcessed = true; ThreadPool::FireAndForget(&DownloadManager::asyncPackageDownloadContentFile, this, package, contentPtr->index); contentCountTable[ContentState::DOWNLOAD].processing++; } if (contentCountTable[ContentState::DOWNLOAD].total > 0) return; /************* content verification phase *************/ if (package->state.currentState != Package::STATE::VERIFYING) { package->state.currentState = Package::STATE::VERIFYING; package->state.progress = 0; package->state.progressMax = (uint32)package->state.contentFiles.size(); reportPackageStatus(package); } while (contentCountTable[ContentState::VERIFY].total > 0 && contentCountTable[ContentState::VERIFY].processing < 2) { Package::ContentFile* contentPtr = getFirstInactiveContentByState(ContentState::VERIFY); if (!contentPtr) break; contentPtr->isBeingProcessed = true; ThreadPool::FireAndForget(&DownloadManager::asyncPackageVerifyFile, this, package, contentPtr->index, true); contentCountTable[ContentState::VERIFY].processing++; } if (contentCountTable[ContentState::VERIFY].total > 0) return; /************* installing phase *************/ if (!package->state.isInstalling) { if (package->state.currentState != Package::STATE::INSTALLING) { package->state.currentState = Package::STATE::INSTALLING; package->state.progress = 0; package->state.progressMax = 0; reportPackageStatus(package); } package->state.isInstalling = true; ThreadPool::FireAndForget(&DownloadManager::asyncPackageInstall, this, package); } } // checks for new packages to download if none are currently active void DownloadManager::checkPackagesState() { std::unique_lock<std::recursive_mutex> _l(m_mutex); bool hasActive = false; hasActive = std::find_if(m_packageList.begin(), m_packageList.end(), [](const Package* p) { return p->state.isActive; }) != m_packageList.end(); if (!hasActive) { // start new download auto it = std::find_if(m_packageList.begin(), m_packageList.end(), [](const Package* p) { return !p->state.isActive && !p->state.hasError && !p->state.isPaused && p->state.currentState != Package::STATE::INSTALLED; }); if (it != m_packageList.end()) { Package* startedPackage = *it; startedPackage->state.isActive = true; updatePackage(startedPackage); reportPackageStatus(startedPackage); } } } void DownloadManager::setPackageError(Package* package, std::string errorMsg) { package->state.isActive = false; if (package->state.hasError) return; // dont overwrite already set error message package->state.hasError = true; package->state.errorMsg = std::move(errorMsg); reportPackageStatus(package); } void DownloadManager::reportPackageStatus(Package* package) { if (!m_cbAddDownloadableTitle) return; m_mutex.lock(); DlMgrTitleReport::STATUS status = DlMgrTitleReport::STATUS::INITIALIZING; if (package->state.hasError) { status = DlMgrTitleReport::STATUS::HAS_ERROR; } else if (package->state.currentState == Package::STATE::INSTALLED) status = DlMgrTitleReport::STATUS::INSTALLED; else if (!package->state.isActive) { if (package->state.tmd) status = DlMgrTitleReport::STATUS::PAUSED; else status = DlMgrTitleReport::STATUS::QUEUED; } else if (package->state.tmd) { if (package->state.currentState == Package::STATE::CHECKING) status = DlMgrTitleReport::STATUS::CHECKING; else if (package->state.currentState == Package::STATE::VERIFYING) status = DlMgrTitleReport::STATUS::VERIFYING; else if (package->state.currentState == Package::STATE::INSTALLING) status = DlMgrTitleReport::STATUS::INSTALLING; else if (package->state.currentState == Package::STATE::INSTALLED) status = DlMgrTitleReport::STATUS::INSTALLED; else status = DlMgrTitleReport::STATUS::DOWNLOADING; } DlMgrTitleReport reportInfo(status, package->titleId, package->version, getNameFromCachedIDBE(package->titleId), package->state.progress, package->state.progressMax, package->state.isPaused); if (package->state.hasError) reportInfo.errorMsg = package->state.errorMsg; m_mutex.unlock(); m_cbAddDownloadableTitle(reportInfo); } void DownloadManager::reportPackageProgress(Package* package, uint32 currentProgress) { // todo - cooldown timer to avoid spamming too many events package->state.progress = currentProgress; reportPackageStatus(package); } void DownloadManager::asyncPackageDownloadTMD(Package* package) { NAPI::AuthInfo authInfo = GetAuthInfo(true); TitleIdParser titleIdParser(package->titleId); NAPI::NAPI_CCSGetTMD_Result tmdResult; if (titleIdParser.GetType() == TitleIdParser::TITLE_TYPE::AOC) { // for AOC we always download the latest TMD // is there a way to get the version beforehand? It doesn't seem to be stored in either the .tik file or the update version list tmdResult = CCS_GetTMD(authInfo, package->titleId); } else { tmdResult = NAPI::CCS_GetTMD(authInfo, package->titleId, package->version); } if (!tmdResult.isValid) { // failed, try to get latest TMD instead tmdResult = CCS_GetTMD(authInfo, package->titleId); } std::unique_lock<std::recursive_mutex> _l(m_mutex); if (!tmdResult.isValid) { setPackageError(package, _("TMD download failed").utf8_string()); package->state.isDownloadingTMD = false; return; } _l.unlock(); // parse NCrypto::TMDParser tmdParser; if (!tmdParser.parse(tmdResult.tmdData.data(), tmdResult.tmdData.size())) { setPackageError(package, _("Invalid TMD").utf8_string()); package->state.isDownloadingTMD = false; return; } // set TMD _l.lock(); package->state.tmdData = tmdResult.tmdData; package->state.tmd = new NCrypto::TMDParser(tmdParser); package->state.isDownloadingTMD = false; // prepare list of content files package->state.contentFiles.clear(); for (auto& itr : package->state.tmd->GetContentList()) { if (package->state.contentFiles.find(itr.index) != package->state.contentFiles.end()) { cemu_assert_debug(false); continue; } package->state.contentFiles.emplace(std::piecewise_construct, std::forward_as_tuple(itr.index), std::forward_as_tuple(itr.index, itr.contentId, itr.size, itr.contentFlags, itr.hash32)); } // create folder auto dir = getPackageDownloadPath(package); fs::create_directories(dir); // continue with downloading reportPackageStatus(package); updatePackage(package); } void DownloadManager::calcPackageDownloadProgress(Package* package) { if (package->state.currentState == Package::STATE::DOWNLOADING) { uint64 totalSize = 0; uint64 totalDownloaded = 0; for (auto& itr : package->state.contentFiles) { totalSize += itr.second.paddedSize; if (itr.second.currentState == Package::ContentFile::STATE::INSTALL || itr.second.currentState == Package::ContentFile::STATE::VERIFY) totalDownloaded += itr.second.paddedSize; // already downloaded, add full size else totalDownloaded += itr.second.amountDownloaded; } uint32 pct10 = (uint32)(totalDownloaded * 1000ull / totalSize); if (package->state.progress != pct10) { package->state.progress = pct10; package->state.progressMax = 1000; reportPackageProgress(package, package->state.progress); } } } void DownloadManager::asyncPackageDownloadContentFile(Package* package, uint16 index) { // get titleId, contentId and file path std::unique_lock<std::recursive_mutex> _l(m_mutex); uint64 titleId = package->titleId; auto contentFileItr = package->state.contentFiles.find(index); cemu_assert(contentFileItr != package->state.contentFiles.end()); uint32 contentId = contentFileItr->second.contentId; contentFileItr->second.amountDownloaded = 0; auto packageDownloadPath = getPackageDownloadPath(package); _l.unlock(); // download h3 hash file (.h3) if flag 0x0002 is set (-> we are using the TMD to verify the hash of the content files) //auto h3Result = NAPI::CCS_GetContentH3File(titleId, contentId); //auto h3Result = NAPI::CCS_GetContentH3File(titleId, contentId); //if (!h3Result.isValid) //{ // setPackageError(package, "Download failed (h3)"); // return; //} //filePathStr = (packageDownloadPath / fmt::format("{:08x}.h3", index)).generic_u8string(); //auto h3File = FileStream::createFile(filePathStr); //if (!h3File) //{ // setPackageError(package, "Cannot create file"); // return; //} //if (h3File->writeData(h3Result.tmdData.data(), h3Result.tmdData.size()) != h3Result.tmdData.size()) //{ // setPackageError(package, "Cannot write file (h3). Disk full?"); // return; //} //delete h3File; // streamed download of content file (.app) // prepare callback parameter struct struct CallbackInfo { DownloadManager* downloadMgr; Package* package; Package::ContentFile* contentFile; std::vector<uint8> receiveBuffer; FileStream* fileOutput; static bool writeCallback(void* userData, const void* ptr, size_t len, bool isLast) { CallbackInfo* callbackInfo = (CallbackInfo*)userData; // append bytes to buffer callbackInfo->receiveBuffer.insert(callbackInfo->receiveBuffer.end(), (const uint8*)ptr, (const uint8*)ptr + len); // flush cache to file if it exceeds 128KiB or if this is the final callback if (callbackInfo->receiveBuffer.size() >= (128 * 1024) || (isLast && !callbackInfo->receiveBuffer.empty())) { size_t bytesWritten = callbackInfo->receiveBuffer.size(); if (callbackInfo->fileOutput->writeData(callbackInfo->receiveBuffer.data(), callbackInfo->receiveBuffer.size()) != (uint32)callbackInfo->receiveBuffer.size()) { callbackInfo->downloadMgr->setPackageError(callbackInfo->package, _("Cannot write file. Disk full?").utf8_string()); return false; } callbackInfo->receiveBuffer.clear(); if (bytesWritten > 0) { callbackInfo->downloadMgr->m_mutex.lock(); callbackInfo->contentFile->amountDownloaded += bytesWritten; callbackInfo->downloadMgr->calcPackageDownloadProgress(callbackInfo->package); callbackInfo->downloadMgr->m_mutex.unlock(); } } return true; } }callbackInfoData{}; callbackInfoData.downloadMgr = this; callbackInfoData.package = package; callbackInfoData.contentFile = &contentFileItr->second; callbackInfoData.fileOutput = FileStream::createFile2(packageDownloadPath / fmt::format("{:08x}.app", contentId)); if (!callbackInfoData.fileOutput) { setPackageError(package, _("Cannot create file").utf8_string()); return; } if (!NAPI::CCS_GetContentFile(GetDownloadMgrNetworkService(), titleId, contentId, CallbackInfo::writeCallback, &callbackInfoData)) { setPackageError(package, _("Download failed").utf8_string()); delete callbackInfoData.fileOutput; return; } delete callbackInfoData.fileOutput; callbackInfoData.fileOutput = nullptr; // mark file as downloaded by requesting verify state _l.lock(); contentFileItr->second.finishProcessing(Package::ContentFile::STATE::VERIFY); _l.unlock(); // start next task updatePackage(package); } void DownloadManager::asyncPackageVerifyFile(Package* package, uint16 index, bool isCheckState) { uint8 tmdContentHash[32]; // get titleId, contentId and file path std::unique_lock<std::recursive_mutex> _l(m_mutex); uint64 titleId = package->titleId; auto contentFileItr = package->state.contentFiles.find(index); cemu_assert(contentFileItr != package->state.contentFiles.end()); uint16 contentIndex = contentFileItr->second.index; uint32 contentId = contentFileItr->second.contentId; uint64 contentSize = contentFileItr->second.size; uint64 contentPaddedSize = contentFileItr->second.paddedSize; auto contentFlags = contentFileItr->second.contentFlags; std::memcpy(tmdContentHash, contentFileItr->second.contentHash, 32); auto packageDownloadPath = getPackageDownloadPath(package); _l.unlock(); NCrypto::AesKey ecsTicketKey = package->ticketKey; Package::ContentFile::STATE newStateOnError = Package::ContentFile::STATE::DOWNLOAD; Package::ContentFile::STATE newStateOnSuccess = Package::ContentFile::STATE::INSTALL; // verify file std::unique_ptr<FileStream> fileStream(FileStream::openFile2(packageDownloadPath / fmt::format("{:08x}.app", contentId))); if (!fileStream) { _l.lock(); contentFileItr->second.finishProcessing(newStateOnError); if (!isCheckState) setPackageError(package, "Missing file during verification"); _l.unlock(); updatePackage(package); return; } bool isSHA1 = HAS_FLAG(contentFlags, NCrypto::TMDParser::TMDContentFlags::FLAG_SHA1); bool isValid = false; if (HAS_FLAG(contentFlags, NCrypto::TMDParser::TMDContentFlags::FLAG_HASHED_CONTENT)) isValid = FSTVerifier::VerifyHashedContentFile(fileStream.get(), &ecsTicketKey, contentIndex, contentSize, contentPaddedSize, isSHA1, tmdContentHash); else isValid = FSTVerifier::VerifyContentFile(fileStream.get(), &ecsTicketKey, contentIndex, contentSize, contentPaddedSize, isSHA1, tmdContentHash); if (!isValid) { _l.lock(); contentFileItr->second.finishProcessing(newStateOnError); if (!isCheckState) setPackageError(package, "Verification failed"); _l.unlock(); updatePackage(package); return; } // file verified successfully _l.lock(); contentFileItr->second.finishProcessing(newStateOnSuccess); reportPackageProgress(package, package->state.progress + 1); _l.unlock(); // start next task updatePackage(package); } bool DownloadManager::asyncPackageInstallRecursiveExtractFiles(Package* package, FSTVolume* fstVolume, const std::string& sourcePath, const fs::path& destinationPath) { std::error_code ec; fs::create_directories(destinationPath, ec); // we dont check the error because it is OS/implementation specific (on Windows this returns ec=0 with false when directory already exists) cemu_assert_debug(sourcePath.back() == '/'); FSTDirectoryIterator dirItr; if (!fstVolume->OpenDirectoryIterator(sourcePath, dirItr)) { std::unique_lock<std::recursive_mutex> _l(m_mutex); setPackageError(package, "Internal error"); return false; } if (fstVolume->HasLinkFlag(dirItr.GetDirHandle())) { cemu_assert_suspicious(); return true; } FSTFileHandle itr; while (fstVolume->Next(dirItr, itr)) { std::string_view nodeName = fstVolume->GetName(itr); if(nodeName.empty() || boost::equals(nodeName, ".") || boost::equals(nodeName, "..") || boost::contains(nodeName, "/") || boost::contains(nodeName, "\\")) continue; std::string sourceFilePath = sourcePath; sourceFilePath.append(nodeName); fs::path nodeDestinationPath = destinationPath; nodeDestinationPath.append(nodeName.data(), nodeName.data() + nodeName.size()); if (fstVolume->IsDirectory(itr)) { if (fstVolume->HasLinkFlag(itr)) { // delete link directories fs::remove_all(nodeDestinationPath, ec); } else { // iterate sourceFilePath.push_back('/'); asyncPackageInstallRecursiveExtractFiles(package, fstVolume, sourceFilePath, nodeDestinationPath); } } else if (fstVolume->IsFile(itr)) { if (fstVolume->HasLinkFlag(itr)) { // delete link files fs::remove_all(nodeDestinationPath, ec); } else { // extract std::vector<uint8> buffer(64 * 1024); FileStream* fileOut = FileStream::createFile2(nodeDestinationPath); if (!fileOut) { setPackageError(package, "Failed to create file"); return false; } uint32 fileSize = fstVolume->GetFileSize(itr); uint32 currentPos = 0; while (currentPos < fileSize) { uint32 numBytesToTransfer = std::min(fileSize - currentPos, (uint32)buffer.size()); if (fstVolume->ReadFile(itr, currentPos, numBytesToTransfer, buffer.data()) != numBytesToTransfer) { setPackageError(package, "Failed to extract data"); return false; } if (fileOut->writeData(buffer.data(), numBytesToTransfer) != numBytesToTransfer) { setPackageError(package, "Failed to write to file. Disk full?"); return false; } currentPos += numBytesToTransfer; } delete fileOut; } // advance progress std::unique_lock<std::recursive_mutex> _l(m_mutex); reportPackageProgress(package, package->state.progress + 1); } else { cemu_assert_debug(false); // unknown node type } } return true; } void DownloadManager::asyncPackageInstall(Package* package) { std::unique_lock<std::recursive_mutex> _l(m_mutex); auto packageDownloadPath = getPackageDownloadPath(package); fs::path installPath = getPackageInstallPath(package); _l.unlock(); // store title.tmd std::unique_ptr<FileStream> fileStream(FileStream::createFile2(packageDownloadPath / "title.tmd")); if (!fileStream || fileStream->writeData(package->state.tmdData.data(), package->state.tmdData.size()) != package->state.tmdData.size()) { _l.lock(); setPackageError(package, "Failed to write title.tmd"); package->state.isInstalling = false; return; } fileStream.reset(); // store title.tik fileStream.reset(FileStream::createFile2(packageDownloadPath / "title.tik")); if (!fileStream || fileStream->writeData(package->eTicketData.data(), package->eTicketData.size()) != package->eTicketData.size()) { _l.lock(); setPackageError(package, "Failed to write title.tik"); package->state.isInstalling = false; return; } fileStream.reset(); // for AOC titles we also 'install' the ticket by copying it next to the code/content/meta folders // on an actual Wii U the ticket gets installed to SLC but currently we only emulate MLC if (TitleIdParser(package->titleId).GetType() == TitleIdParser::TITLE_TYPE::AOC) { std::error_code ec; fs::create_directories(installPath, ec); fs::create_directories(installPath / "code/", ec); fileStream.reset(FileStream::createFile2(installPath / "code/title.tik")); if (!fileStream || fileStream->writeData(package->eTicketData.data(), package->eTicketData.size()) != package->eTicketData.size()) { _l.lock(); setPackageError(package, "Failed to install title.tik"); package->state.isInstalling = false; return; } fileStream.reset(); } // open app FST FSTVolume* fst = FSTVolume::OpenFromContentFolder(packageDownloadPath); if (!fst) { _l.lock(); setPackageError(package, "Failed to extract content"); package->state.isInstalling = false; return; } // count number of files for progress tracking package->state.progressMax = fst->GetFileCount(); package->state.progress = 0; // extract code/content/meta folders into installation directory if (!asyncPackageInstallRecursiveExtractFiles(package, fst, "code/", installPath / "code")) { _l.lock(); setPackageError(package, "Failed to extract code folder"); package->state.isInstalling = false; return; } if (!asyncPackageInstallRecursiveExtractFiles(package, fst, "content/", installPath / "content")) { _l.lock(); setPackageError(package, "Failed to extract content folder"); package->state.isInstalling = false; return; } if (!asyncPackageInstallRecursiveExtractFiles(package, fst, "meta/", installPath / "meta")) { _l.lock(); setPackageError(package, "Failed to extract meta folder"); package->state.isInstalling = false; return; } delete fst; // delete package folder std::error_code ec; fs::remove_all(packageDownloadPath, ec); // mark as complete _l.lock(); package->state.currentState = Package::STATE::INSTALLED; package->state.isInstalling = false; package->state.isActive = false; CafeTitleList::AddTitleFromPath(installPath); reportPackageStatus(package); checkPackagesState(); // lastly request game list to be refreshed MainWindow::RequestGameListRefresh(); return; } /* IDBE cache */ std::unordered_map<uint64, NAPI::IDBEIconDataV0*> s_idbeCache; std::mutex s_idbeCacheMutex; // load IDBE from disk or server into memory cache // stalls while reading disk/downloading void DownloadManager::prepareIDBE(uint64 titleId) { auto hasInCache = [](uint64 titleId) -> bool { s_idbeCacheMutex.lock(); bool hasCached = s_idbeCache.find(titleId) != s_idbeCache.end(); s_idbeCacheMutex.unlock(); return hasCached; }; auto addToCache = [](uint64 titleId, NAPI::IDBEIconDataV0* iconData) -> void { NAPI::IDBEIconDataV0* iconInstance = new NAPI::IDBEIconDataV0(); *iconInstance = *iconData; s_idbeCacheMutex.lock(); if (!s_idbeCache.try_emplace(titleId, iconInstance).second) delete iconInstance; s_idbeCacheMutex.unlock(); }; if (hasInCache(titleId)) return; // try to load from disk cache std::vector<uint8> idbeFile; if (s_nupFileCache->GetFile({ fmt::format("idbe/{0:016x}", titleId) }, idbeFile) && idbeFile.size() == sizeof(NAPI::IDBEIconDataV0)) return addToCache(titleId, (NAPI::IDBEIconDataV0*)(idbeFile.data())); // not cached, query from server std::optional<NAPI::IDBEIconDataV0> iconData = NAPI::IDBE_Request(GetDownloadMgrNetworkService(), titleId); if (!iconData) return; s_nupFileCache->AddFileAsync({ fmt::format("idbe/{0:016x}", titleId) }, (uint8*)&(*iconData), sizeof(NAPI::IDBEIconDataV0)); addToCache(titleId, &*iconData); } std::string DownloadManager::getNameFromCachedIDBE(uint64 titleId) { // workaround for Friend List not having an IDBE if (titleId == 0x000500301001500A || titleId == 0x000500301001510A || titleId == 0x000500301001520A) { return "Friend List"; } std::unique_lock<std::mutex> _l(s_idbeCacheMutex); NAPI::IDBEIconDataV0* iconData = getIDBE(titleId); if (iconData) return iconData->GetLanguageStrings(GetConfig().console_language).GetGameNameUTF8(); return fmt::format("Title {0:016x}", titleId); } // returns IDBE by titleId (or nullptr if not in cache) // assumes s_idbeCacheMutex is held by caller NAPI::IDBEIconDataV0* DownloadManager::getIDBE(uint64 titleId) { auto it = s_idbeCache.find(titleId); if (it == s_idbeCache.end()) return nullptr; return it->second; } /* package manager / downloading */ void DownloadManager::threadFunc() { while (true) { auto cb = m_jobQueue.pop(); cb(); } } // init download manager worker thread and cache void DownloadManager::runManager() { bool prevBool = false; if (!m_threadLaunched.compare_exchange_weak(prevBool, true)) return; // open cache auto cacheFilePath = ActiveSettings::GetMlcPath("usr/save/system/nim/nup/"); fs::create_directories(cacheFilePath); cacheFilePath /= "cemu_cache.dat"; s_nupFileCache = FileCache::Open(cacheFilePath, true); // launch worker thread std::thread t(&DownloadManager::threadFunc, this); t.detach(); } // let manager known there is a new event that needs processing void DownloadManager::notifyManager() { m_queuedEvents.increment(); } void DownloadManager::queueManagerJob(const std::function<void()>& callback) { m_jobQueue.push(callback); }
51,760
C++
.cpp
1,404
34.249288
224
0.759723
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,942
ncrypto.cpp
cemu-project_Cemu/src/Cemu/ncrypto/ncrypto.cpp
#include "Common/precompiled.h" #include "Cemu/ncrypto/ncrypto.h" #include "util/helpers/helpers.h" #include "openssl/bn.h" #include "openssl/ec.h" #include "openssl/x509.h" #include "openssl/ssl.h" #include "openssl/sha.h" #include "openssl/ecdsa.h" #include "util/crypto/aes128.h" void iosuCrypto_getDeviceCertificate(void* certOut, sint32 len); void iosuCrypto_getDeviceCertPrivateKey(void* privKeyOut, sint32 len); bool iosuCrypto_getDeviceId(uint32* deviceId); void iosuCrypto_getDeviceSerialString(char* serialString); void iosuCrypto_readOtpData(void* output, sint32 wordIndex, sint32 size); void iosuCrypto_readSeepromData(void* output, sint32 wordIndex, sint32 size); extern bool hasSeepromMem; // remove later (migrate otp/seeprom loading & parsing to this class) extern bool hasOtpMem; // remove later namespace NCrypto { std::string base64Encode(const void* inputMem, size_t inputLen) { const uint8* input = (const uint8*)inputMem; static const char* base64_charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; std::string strBase64; strBase64.resize((inputLen * 4) / 3 + 16); int i = 0; int j = 0; unsigned char charArray_3[3]; unsigned char charArray_4[4]; sint32 outputLength = 0; while (inputLen--) { charArray_3[i++] = *(input++); if (i == 3) { charArray_4[0] = (charArray_3[0] & 0xfc) >> 2; charArray_4[1] = ((charArray_3[0] & 0x03) << 4) + ((charArray_3[1] & 0xf0) >> 4); charArray_4[2] = ((charArray_3[1] & 0x0f) << 2) + ((charArray_3[2] & 0xc0) >> 6); charArray_4[3] = charArray_3[2] & 0x3f; for (i = 0; (i < 4); i++) { strBase64[outputLength] = base64_charset[charArray_4[i]]; outputLength++; } i = 0; } } if (i) { for (j = i; j < 3; j++) charArray_3[j] = '\0'; charArray_4[0] = (charArray_3[0] & 0xfc) >> 2; charArray_4[1] = ((charArray_3[0] & 0x03) << 4) + ((charArray_3[1] & 0xf0) >> 4); charArray_4[2] = ((charArray_3[1] & 0x0f) << 2) + ((charArray_3[2] & 0xc0) >> 6); charArray_4[3] = charArray_3[2] & 0x3f; for (j = 0; j < (i + 1); j++) { strBase64[outputLength] = base64_charset[charArray_4[j]]; outputLength++; } while (i++ < 3) { strBase64[outputLength] = '='; outputLength++; } } cemu_assert(outputLength <= strBase64.size()); strBase64.resize(outputLength); return strBase64; } std::vector<uint8> base64Decode(std::string_view inputStr) { static constexpr unsigned char kDecodingTable[] = { 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64, 64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64, 64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64 }; size_t in_len = inputStr.size(); if (in_len <= 3 || (in_len & 3) != 0) return std::vector<uint8>(); // invalid length std::vector<uint8> output; size_t out_len = in_len / 4 * 3; if (inputStr[in_len - 1] == '=') out_len--; if (inputStr[in_len - 2] == '=') out_len--; output.resize(out_len); for (size_t i = 0, j = 0; i < in_len;) { uint32 a = inputStr[i] == '=' ? 0 & i++ : kDecodingTable[static_cast<int>(inputStr[i++])]; uint32 b = inputStr[i] == '=' ? 0 & i++ : kDecodingTable[static_cast<int>(inputStr[i++])]; uint32 c = inputStr[i] == '=' ? 0 & i++ : kDecodingTable[static_cast<int>(inputStr[i++])]; uint32 d = inputStr[i] == '=' ? 0 & i++ : kDecodingTable[static_cast<int>(inputStr[i++])]; uint32 triple = (a << 3 * 6) + (b << 2 * 6) + (c << 1 * 6) + (d << 0 * 6); if (j < out_len) output[j++] = (triple >> 2 * 8) & 0xFF; if (j < out_len) output[j++] = (triple >> 1 * 8) & 0xFF; if (j < out_len) output[j++] = (triple >> 0 * 8) & 0xFF; } return output; } void base64Tests() { std::vector<uint8> random; for (sint32 i = 0; i < 100; i++) { random.resize(0 + i); for (size_t x = 0; x < random.size(); x++) random[x] = (uint8)(i * 21 + x * 133); std::string b64 = base64Encode(random.data(), random.size()); std::vector<uint8> dec = base64Decode(b64); cemu_assert(random == dec); } } /* Hashing */ void GenerateHashSHA1(const void* data, size_t len, CHash160& hashOut) { SHA1((const unsigned char*) data, len, hashOut.b); } void GenerateHashSHA256(const void* data, size_t len, CHash256& hashOut) { SHA256((const unsigned char*) data, len, hashOut.b); } /* Ticket */ struct ETicketFileHeaderWiiU { /* Ticket version 0: SHA1 hash Ticket version 1: SHA256 hash + has item rights */ /* +0x000 */ uint32be signatureType; /* +0x004 */ uint8 sig[0x100]; /* +0x104 */ uint8 _ukn104[0x180 - 0x104]; /* +0x180 */ ECCPubKey publicKey; /* +0x1BC */ uint8 ticketFormatVersion; /* +0x1BD */ uint8 _ukn1BD; /* +0x1BE */ uint8 _ukn1BE; /* +0x1BF */ uint8 encryptedTitleKey[16]; /* +0x1CF */ uint8 _ukn1CF; // probably padding /* +0x1D0 */ uint32be ticketIdHigh; /* +0x1D4 */ uint32be ticketIdLow; /* +0x1D8 */ uint32be deviceId; // ticket personalized to this deviceId. Zero if not personalized /* +0x1DC */ uint32be titleIdHigh; /* +0x1E0 */ uint32be titleIdLow; /* +0x1E4 */ uint16be ukn1E4; /* +0x1E6 */ uint16be titleVersion; // also used as ticket version (for AOC content)? /* +0x1E8 */ uint8 _ukn1E8[0x21C - 0x1E8]; /* +0x21C */ uint32be accountId; /* V1 extension header starts at +0x2A4 */ }; struct ETicketFileHeaderExtV1 { /* starts at +0x2A4 */ /* +0x000 */ uint16be headerVersion; /* +0x002 */ uint16be headerSize; /* +0x004 */ uint32be ukn008; /* +0x008 */ uint32be sectionTableOffset; /* +0x00C */ uint16be sectionTableNumEntries; /* +0x00E */ uint16be sectionTableEntrySize; /**/ }; struct ETicketFileHeaderExtV1SectionHeader { enum { SECTION_TYPE_CONTENT_RIGHTS = 3, // content rights }; /* +0x00 */ uint32be sectionOffset; /* +0x04 */ uint32be entryCount; /* +0x08 */ uint32be entrySize; /* +0x0C */ uint32be sectionSize; /* +0x10 */ uint16be type; /* +0x12 */ uint16be ukn00; }; static_assert(sizeof(ETicketFileHeaderWiiU) == 0x220); struct ETicketV1_ContentRights { uint32be baseIndex; // first index for bitmask? uint8be rightBitmask[0x80]; uint32 GetRightsCount() const { return sizeof(rightBitmask) * 8; } bool GetRight(uint32 index) const { cemu_assert_debug(index < GetRightsCount()); if (index >= GetRightsCount()) return false; return ((rightBitmask[(index/8)]>>(index & 7)) & 1) != 0; } }; static_assert(sizeof(ETicketV1_ContentRights) == 0x84); bool ETicketParser::parse(const uint8* data, size_t size) { auto readStruct = [&](uint32 offset, uint32 readSize) -> void* { if ((offset + readSize) > size) return nullptr; return (void*)((const uint8*)data + offset); }; if (size < sizeof(ETicketFileHeaderWiiU)) return false; ETicketFileHeaderWiiU* header = (ETicketFileHeaderWiiU*)readStruct(0, sizeof(ETicketFileHeaderWiiU)); if (!header) return false; m_titleId = MakeU64(header->titleIdHigh, header->titleIdLow); m_ticketId = MakeU64(header->ticketIdHigh, header->ticketIdLow); m_ticketFormatVersion = header->ticketFormatVersion; m_titleVersion = header->titleVersion; uint32 titleIdHigh = (m_titleId >> 32); if ((titleIdHigh >> 16) != 0x5) return false; // title id should start with 0005... (Wii U platform id?) m_isPersonalized = header->deviceId != 0; m_deviceId = header->deviceId; m_publicKey = header->publicKey; std::memcpy(m_encryptedTitleKey, header->encryptedTitleKey, 16); cemu_assert_debug(header->ukn1E4 == 0); // read V1 extension if (m_ticketFormatVersion >= 1) { if ((titleIdHigh) == 0x0005000c) { ETicketFileHeaderExtV1* extHeader = (ETicketFileHeaderExtV1*)readStruct(0x2A4, sizeof(ETicketFileHeaderExtV1)); // (ETicketFileHeaderExtV1*)((uint8*)header + 0x2A4); if (!extHeader) return false; cemu_assert_debug(extHeader->sectionTableEntrySize == 0x14); for (uint32 i = 0; i < extHeader->sectionTableNumEntries; i++) { ETicketFileHeaderExtV1SectionHeader* sectHeader = (ETicketFileHeaderExtV1SectionHeader*)readStruct(0x2A4 + extHeader->sectionTableOffset, sizeof(ETicketFileHeaderExtV1SectionHeader)); if (!sectHeader) return false; if (sectHeader->type == ETicketFileHeaderExtV1SectionHeader::SECTION_TYPE_CONTENT_RIGHTS) { if (sectHeader->entrySize != sizeof(ETicketV1_ContentRights)) { cemuLog_log(LogType::Force, "ETicket: Failed to parse ticket with invalid rights size"); return false; } cemu_assert_debug(sectHeader->entryCount == 1); for (uint32 r = 0; r < sectHeader->entryCount; r++) { ETicketV1_ContentRights* rights = (ETicketV1_ContentRights*)readStruct(0x2A4 + sectHeader->sectionOffset + r * sectHeader->entrySize, sizeof(ETicketV1_ContentRights)); cemu_assert_debug(rights->baseIndex == 0); if (rights->baseIndex > 0x1000) { cemuLog_log(LogType::Force, "ETicket: Invalid content rights index ({})", (uint32)rights->baseIndex); continue; } size_t maxRightsCount = rights->baseIndex + rights->GetRightsCount(); if (maxRightsCount > m_contentRights.size()) m_contentRights.resize(maxRightsCount); for (uint32 x = 0; x < rights->GetRightsCount(); x++) m_contentRights[x + rights->baseIndex] = rights->GetRight(x); } } else { cemu_assert_debug(false); } } } } return true; } void ETicketParser::GetTitleKey(AesKey& key) { // the key is encrypted using the titleId as IV + 8 zero bytes uint8 iv[16]{}; *(uint64be*)iv = m_titleId; uint8 commonKey[16] = { 0xD7,0xB0,0x04,0x02,0x65,0x9B,0xA2,0xAB,0xD2,0xCB,0x0D,0xB2,0x7F,0xA2,0xB6,0x56 }; AES128_CBC_decrypt(key.b, m_encryptedTitleKey, 16, commonKey, iv); } // personalized tickets have an extra layer of encryption for the title key bool ETicketParser::Depersonalize(uint8* ticketData, size_t ticketSize, uint32 deviceId, const ECCPrivKey& devicePrivKey) { ETicketParser ticketParser; if (!ticketParser.parse(ticketData, ticketSize)) return false; if (!ticketParser.IsPersonalized()) return false; if (ticketParser.m_deviceId != deviceId) { cemuLog_log(LogType::Force, "Personalized ticket does not match deviceId"); return false; } // decrypt personalized titlekey EC_KEY* ec_privKey = devicePrivKey.getPrivateKey(); EC_POINT* ec_publicKey = ticketParser.m_publicKey.getPublicKeyAsPoint(); uint8 sharedKey[128]{}; int sharedKeyLen = ECDH_compute_key(sharedKey, sizeof(sharedKey), ec_publicKey, ec_privKey, nullptr); cemu_assert(sharedKeyLen > 16); EC_KEY_free(ec_privKey); EC_POINT_free(ec_publicKey); NCrypto::CHash160 sharedKeySHA1; NCrypto::GenerateHashSHA1(sharedKey, sharedKeyLen, sharedKeySHA1); uint8 aesSharedKey[16]{}; std::memcpy(aesSharedKey, sharedKeySHA1.b, 16); uint8 iv[16]{}; *(uint64be*)iv = ticketParser.m_ticketId; uint8 ticketKey[16]; AES128_CBC_decrypt(ticketKey, ticketParser.m_encryptedTitleKey, 16, aesSharedKey, iv); // store de-personalized key and remove personal data from ticket ETicketFileHeaderWiiU* header = (ETicketFileHeaderWiiU*)ticketData; std::memcpy(header->encryptedTitleKey, ticketKey, 16); header->deviceId = 0; header->accountId = 0; return true; } /* Title meta data */ struct TMDFileHeaderWiiU { /* +0x000 */ uint32be signatureType; /* +0x004 */ uint8be sig[0x100]; /* +0x104 */ uint8be _padding104[0x140 - 0x104]; /* +0x140 */ uint8be _ukn140[0x40]; /* +0x180 */ uint8be tmdVersion; /* +0x181 */ uint8be _ukn181; /* +0x182 */ uint8be _ukn182; /* +0x183 */ uint8be isVWii; /* +0x184 */ uint32be iosTitleIdHigh; /* +0x188 */ uint32be iosTitleIdLow; /* +0x18C */ uint32be titleIdHigh; /* +0x190 */ uint32be titleIdLow; /* +0x194 */ uint32be titleType; /* +0x198 */ uint16be group; /* +0x19A */ uint16be _ukn19A; /* +0x19C */ uint16be region; /* +0x19E */ uint8be ratings[16]; /* +0x1AE */ uint8be _ukn1AE[12]; /* +0x1BA */ uint8be _ipcMask[12]; /* +0x1C6 */ uint8be _ukn1C6[18]; /* +0x1D8 */ uint32be accessRightsMask; /* +0x1DC */ uint16be titleVersion; /* +0x1DE */ uint16be numContent; /* +0x1E0 */ uint32be _ukn1E0; /* +0x1E4 */ uint8 uknHash[32]; // hash of array at 0x204 /* +0x204 */ struct { // pointer to cert data and cert hash? uint16 ukn00; // index? uint16 ukn02; uint8 hash[32]; }ContentInfo[64]; }; static_assert(sizeof(TMDFileHeaderWiiU) == 0x204 + 64*36); struct TMDFileContentEntryWiiU { /* +0x00 */ uint32be contentId; /* +0x04 */ uint16be index; /* +0x06 */ uint16be type; /* +0x08 */ uint32be sizeHigh; /* +0x0C */ uint32be sizeLow; /* +0x10 */ uint8 hashSHA256[32]; // only the first 20 bytes of the hash seem to be stored? }; static_assert(sizeof(TMDFileContentEntryWiiU) == 0x30); bool TMDParser::parse(const uint8* data, size_t size) { if (size < sizeof(TMDFileHeaderWiiU)) { cemuLog_log(LogType::Force, "TMD size {} below minimum size of {}", size, sizeof(TMDFileHeaderWiiU)); return false; } TMDFileHeaderWiiU* header = (TMDFileHeaderWiiU*)data; m_titleId = ((uint64)header->titleIdHigh << 32) | ((uint64)header->titleIdLow); m_titleVersion = header->titleVersion; size_t expectedSize = sizeof(TMDFileHeaderWiiU) + sizeof(TMDFileContentEntryWiiU) * header->numContent; if (size < expectedSize) { cemuLog_log(LogType::Force, "TMD size {} below expected size of {}. Content count: {}", size, expectedSize, (uint16)header->numContent); return false; } // parse content TMDFileContentEntryWiiU* contentEntry = (TMDFileContentEntryWiiU*)(header + 1); for (uint32 i = 0; i < header->numContent; i++) { ContentEntry c{}; c.contentId = contentEntry->contentId; c.index = contentEntry->index; c.size = MakeU64(contentEntry->sizeHigh, contentEntry->sizeLow); c.contentFlags = static_cast<TMDParser::TMDContentFlags>((uint16)contentEntry->type); std::memcpy(c.hash32, contentEntry->hashSHA256, sizeof(c.hash32)); m_content.emplace_back(c); contentEntry++; } // todo - parse certificates return true; } /* ECC PrivateKey helper functions */ void ECCPrivKey::setPrivateKey(EC_KEY* key) { const BIGNUM* bnPrivKey = EC_KEY_get0_private_key(key); memset(this->keyData, 0, sizeof(this->keyData)); BN_bn2binpad(bnPrivKey, this->keyData, sizeof(this->keyData)); } EC_KEY* ECCPrivKey::getPrivateKey() const { BIGNUM* bn_privKey = BN_new(); BN_bin2bn(this->keyData, sizeof(this->keyData), bn_privKey); EC_KEY* ec_privKey = EC_KEY_new_by_curve_name(NID_sect233r1); EC_KEY_set_private_key(ec_privKey, bn_privKey); BN_free(bn_privKey); return ec_privKey; } ECCPrivKey ECCPrivKey::getDeviceCertPrivateKey() { ECCPrivKey key{}; iosuCrypto_getDeviceCertPrivateKey(key.keyData, sizeof(key.keyData)); return key; } /* ECC PublicKey helper functions */ EC_KEY* ECCPubKey::getPublicKey() { BIGNUM* bn_x = BN_new(); BIGNUM* bn_y = BN_new(); BN_bin2bn(this->x, sizeof(this->x), bn_x); BN_bin2bn(this->y, sizeof(this->y), bn_y); EC_KEY* ec_pubKey = EC_KEY_new_by_curve_name(NID_sect233r1); int r = EC_KEY_set_public_key_affine_coordinates(ec_pubKey, bn_x, bn_y); BN_free(bn_x); BN_free(bn_y); return ec_pubKey; } EC_POINT* ECCPubKey::getPublicKeyAsPoint() { BN_CTX* ctx = BN_CTX_new(); BIGNUM* bn_x = BN_new(); BIGNUM* bn_y = BN_new(); BN_bin2bn(this->x, sizeof(this->x), bn_x); BN_bin2bn(this->y, sizeof(this->y), bn_y); EC_GROUP* group = EC_GROUP_new_by_curve_name(NID_sect233r1); EC_POINT* pubkey = EC_POINT_new(group); EC_POINT_set_affine_coordinates(group, pubkey, bn_x, bn_y, ctx); EC_GROUP_free(group); BN_CTX_free(ctx); BN_free(bn_x); BN_free(bn_y); return pubkey; } ECCPubKey ECCPubKey::generateFromPrivateKey(ECCPrivKey& privKey) { BIGNUM* bn_privKey = BN_new(); BN_bin2bn(privKey.keyData, sizeof(privKey.keyData), bn_privKey); // gen public key from private key EC_GROUP* group = EC_GROUP_new_by_curve_name(NID_sect233r1); EC_POINT* pubkey = EC_POINT_new(group); EC_POINT_mul(group, pubkey, bn_privKey, NULL, NULL, NULL); BIGNUM* bn_x = BN_new(); BIGNUM* bn_y = BN_new(); EC_POINT_get_affine_coordinates(group, pubkey, bn_x, bn_y, NULL); // store public key ECCPubKey genPubKey; BN_bn2binpad(bn_x, genPubKey.x, sizeof(genPubKey.x)); BN_bn2binpad(bn_y, genPubKey.y, sizeof(genPubKey.y)); // clean up and return EC_POINT_free(pubkey); BN_free(bn_y); BN_free(bn_x); BN_free(bn_privKey); return genPubKey; } /* Signature helper functions */ ECDSA_SIG* ECCSig::getSignature() { BIGNUM* bn_r = BN_new(); BIGNUM* bn_s = BN_new(); BN_bin2bn(this->r, 30, bn_r); BN_bin2bn(this->s, 30, bn_s); ECDSA_SIG* ec_sig = ECDSA_SIG_new(); ECDSA_SIG_set0(ec_sig, bn_r, bn_s); // ownership of bn_r and bn_s transferred to SIG as well, do not free manually return ec_sig; } void ECCSig::setSignature(ECDSA_SIG* sig) { const BIGNUM* sig_r = nullptr, * sig_s = nullptr; ECDSA_SIG_get0(sig, &sig_r, &sig_s); sint32 lenR = BN_num_bytes(sig_r); sint32 lenS = BN_num_bytes(sig_s); cemu_assert_debug(lenR <= 30); cemu_assert_debug(lenS <= 30); memset(this->r, 0, sizeof(this->r)); memset(this->s, 0, sizeof(this->s)); BN_bn2binpad(sig_r, this->r, 30); BN_bn2binpad(sig_s, this->s, 30); } /* Certificate */ bool CertECC::decodeFromBase64(std::string_view input) { auto v = base64Decode(input); if (v.size() != sizeof(CertECC)) return false; memcpy(this, v.data(), sizeof(CertECC)); return true; } std::string CertECC::encodeToBase64() { return base64Encode(this, sizeof(CertECC)); } bool CertECC::verifySignatureViaPubKey(ECCPubKey& signerPubKey) { uint8 hash[SHA256_DIGEST_LENGTH]; SHA256((const unsigned char *) this->issuer, 0x100, hash); EC_KEY* ecPubKey = signerPubKey.getPublicKey(); ECDSA_SIG* ecSig = this->signature.getSignature(); int r = ECDSA_do_verify(hash, sizeof(hash), ecSig, ecPubKey); ECDSA_SIG_free(ecSig); EC_KEY_free(ecPubKey); return r == 1; // true if valid signature } void CertECC::sign(ECCPrivKey& signerPrivKey) { uint8 hash[SHA256_DIGEST_LENGTH]; SHA256((const unsigned char *) this->issuer, 0x100, hash); // generate signature EC_KEY* ec_privKey = signerPrivKey.getPrivateKey(); ECDSA_SIG* sig = ECDSA_do_sign(hash, sizeof(hash), ec_privKey); EC_KEY_free(ec_privKey); // store signature const BIGNUM* bn_r = nullptr, *bn_s = nullptr; ECDSA_SIG_get0(sig, &bn_r, &bn_s); BN_bn2binpad(bn_r, this->signature.r, sizeof(this->signature.r)); BN_bn2binpad(bn_s, this->signature.s, sizeof(this->signature.s)); ECDSA_SIG_free(sig); } CertECC CertECC::GetDeviceCertificate() { CertECC deviceCert{}; iosuCrypto_getDeviceCertificate(&deviceCert, sizeof(CertECC)); return deviceCert; } // generate a new public key + certificate from privateKey. Certificate is signed with the device key CertECC CertECC::generateCertificate(uint32 signerTitleIdHigh, uint32 signerTitleIdLow, ECCPrivKey& privKeySigner, ECCPrivKey& privKeyIn, ECCPubKey& pubKeyOut) { CertECC deviceCert = GetDeviceCertificate(); CertECC newCert = deviceCert; cemu_assert(newCert.signatureType == CertECC::SIGTYPE::ECC_SHA256); // update date newCert.date = 0; // update issuer strcat(newCert.issuer, "-"); strcat(newCert.issuer, newCert.ngName); // update subject memset(newCert.ngName, 0, sizeof(newCert.ngName)); sprintf(newCert.ngName, "AP%08x%08x", signerTitleIdHigh, signerTitleIdLow); // calculate public key from input private key newCert.publicKey = ECCPubKey::generateFromPrivateKey(privKeyIn); pubKeyOut = newCert.publicKey; // sign certificate newCert.sign(privKeySigner); return newCert; } ECCSig signHash(uint32 signerTitleIdHigh, uint32 signerTitleIdLow, uint8* hash, sint32 hashLen, CertECC& certChainOut) { // generate key pair (we only care about the private key) EC_KEY* ec_keyPair = EC_KEY_new_by_curve_name(NID_sect233r1); EC_KEY_generate_key(ec_keyPair); ECCPrivKey privKey; privKey.setPrivateKey(ec_keyPair); EC_KEY_free(ec_keyPair); // get public key and certificate ECCPubKey pubKey; ECCPrivKey signerPrivKey = ECCPrivKey::getDeviceCertPrivateKey(); certChainOut = CertECC::generateCertificate(signerTitleIdHigh, signerTitleIdLow, signerPrivKey, privKey, pubKey); // generate signature cemu_assert_debug(hashLen == 32); EC_KEY* ec_privKey = privKey.getPrivateKey(); ECDSA_SIG* sig = ECDSA_do_sign(hash, hashLen, ec_privKey); EC_KEY_free(ec_privKey); // verify EC_KEY* ec_pubKey = pubKey.getPublicKey(); bool isValid = ECDSA_do_verify(hash, hashLen, sig, ec_pubKey) == 1; EC_KEY_free(ec_pubKey); cemu_assert(isValid); // store signature ECCSig eccSig; const BIGNUM* bn_r = nullptr, * bn_s = nullptr; ECDSA_SIG_get0(sig, &bn_r, &bn_s); BN_bn2binpad(bn_r, eccSig.r, sizeof(eccSig.r)); BN_bn2binpad(bn_s, eccSig.s, sizeof(eccSig.s)); ECDSA_SIG_free(sig); return eccSig; } bool verifyHashSignature(uint8* hash, sint32 hashLen, ECCPubKey& certChainPubKey, ECCSig& sig) { EC_KEY* ec_pubKey = certChainPubKey.getPublicKey(); ECDSA_SIG* ecdsa_sig = sig.getSignature(); bool r = ECDSA_do_verify(hash, hashLen, ecdsa_sig, ec_pubKey) == 1; EC_KEY_free(ec_pubKey); ECDSA_SIG_free(ecdsa_sig); return r; } bool verifyCert(CertECC& cert, NCrypto::ECCPubKey& signerPubKey) { CertECC::SIGTYPE sigType = cert.signatureType; if (sigType == CertECC::SIGTYPE::ECC_SHA256) { // used for Wii U certs NCrypto::CHash256 hash; NCrypto::GenerateHashSHA256(cert.issuer, 0x100, hash); return NCrypto::verifyHashSignature(hash.b, 32, signerPubKey, cert.signature); } else if (sigType == CertECC::SIGTYPE::ECC_SHA1) { // from Wii era NCrypto::CHash160 hash; NCrypto::GenerateHashSHA1(cert.issuer, 0x100, hash); return NCrypto::verifyHashSignature(hash.b, 20, signerPubKey, cert.signature); } else { cemu_assert_unimplemented(); } return false; } uint32 GetDeviceId() { uint32 deviceId; if (!iosuCrypto_getDeviceId(&deviceId)) return 0x11223344; return deviceId; } std::string GetSerial() { char serialBuffer[128]{}; iosuCrypto_getDeviceSerialString(serialBuffer); return serialBuffer; } bool SEEPROM_IsPresent() { return hasSeepromMem; } CafeConsoleRegion SEEPROM_GetRegion() { uint8 seepromRegionU32[4] = {}; iosuCrypto_readSeepromData(seepromRegionU32, 0xA4, 4); if (seepromRegionU32[3] == 0) { cemuLog_log(LogType::Force, "SEEPROM region is invalid (0)"); } return (CafeConsoleRegion)seepromRegionU32[3]; } bool OTP_IsPresent() { return hasOtpMem; } bool HasDataForConsoleCert() { return SEEPROM_IsPresent() && OTP_IsPresent(); } std::string GetRegionAsString(CafeConsoleRegion regionCode) { if (regionCode == CafeConsoleRegion::EUR) return "EUR"; else if (regionCode == CafeConsoleRegion::USA) return "USA"; else if (regionCode == CafeConsoleRegion::JPN) return "JPN"; else if (regionCode == CafeConsoleRegion::CHN) return "CHN"; else if (regionCode == CafeConsoleRegion::KOR) return "KOR"; else if (regionCode == CafeConsoleRegion::TWN) return "TWN"; cemuLog_log(LogType::Force, "Unknown region code 0x{:x}", (uint32)regionCode); return "UKN"; } const std::unordered_map<sint32, const char*> g_countryTable = { {1,"JP"}, {8,"AI"}, {9,"AG"}, {10,"AR"}, {11,"AW"}, {12,"BS"}, {13,"BB"}, {14,"BZ"}, {15,"BO"}, {16,"BR"}, {17,"VG"}, {18,"CA"}, {19,"KY"}, {20,"CL"}, {21,"CO"}, {22,"CR"}, {23,"DM"}, {24,"DO"}, {25,"EC"}, {26,"SV"}, {27,"GF"}, {28,"GD"}, {29,"GP"}, {30,"GT"}, {31,"GY"}, {32,"HT"}, {33,"HN"}, {34,"JM"}, {35,"MQ"}, {36,"MX"}, {37,"MS"}, {38,"AN"}, {39,"NI"}, {40,"PA"}, {41,"PY"}, {42,"PE"}, {43,"KN"}, {44,"LC"}, {45,"VC"}, {46,"SR"}, {47,"TT"}, {48,"TC"}, {49,"US"}, {50,"UY"}, {51,"VI"}, {52,"VE"}, {64,"AL"}, {65,"AU"}, {66,"AT"}, {67,"BE"}, {68,"BA"}, {69,"BW"}, {70,"BG"}, {71,"HR"}, {72,"CY"}, {73,"CZ"}, {74,"DK"}, {75,"EE"}, {76,"FI"}, {77,"FR"}, {78,"DE"}, {79,"GR"}, {80,"HU"}, {81,"IS"}, {82,"IE"}, {83,"IT"}, {84,"LV"}, {85,"LS"}, {86,"LI"}, {87,"LT"}, {88,"LU"}, {89,"MK"}, {90,"MT"}, {91,"ME"}, {92,"MZ"}, {93,"NA"}, {94,"NL"}, {95,"NZ"}, {96,"NO"}, {97,"PL"}, {98,"PT"}, {99,"RO"}, {100,"RU"}, {101,"RS"}, {102,"SK"}, {103,"SI"}, {104,"ZA"}, {105,"ES"}, {106,"SZ"}, {107,"SE"}, {108,"CH"}, {109,"TR"}, {110,"GB"}, {111,"ZM"}, {112,"ZW"}, {113,"AZ"}, {114,"MR"}, {115,"ML"}, {116,"NE"}, {117,"TD"}, {118,"SD"}, {119,"ER"}, {120,"DJ"}, {121,"SO"}, {122,"AD"}, {123,"GI"}, {124,"GG"}, {125,"IM"}, {126,"JE"}, {127,"MC"}, {128,"TW"}, {136,"KR"}, {144,"HK"}, {145,"MO"}, {152,"ID"}, {153,"SG"}, {154,"TH"}, {155,"PH"}, {156,"MY"}, {160,"CN"}, {168,"AE"}, {170,"EG"}, {171,"OM"}, {172,"QA"}, {173,"KW"}, {174,"SA"}, {175,"SY"}, {176,"BH"}, {177,"JO"}, {184,"SM"}, {185,"VA"}, {186,"BM"}, {187,"IN"}, {192,"NG"}, {193,"AO"}, {194,"GH"} }; const char* GetCountryAsString(sint32 index) { const auto it = g_countryTable.find(index); if (it == g_countryTable.cend()) return "NN"; return it->second; } size_t GetCountryCount() { return g_countryTable.size(); } void unitTests() { base64Tests(); } };
26,538
C++
.cpp
836
28.410287
188
0.66214
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,943
nexThread.cpp
cemu-project_Cemu/src/Cemu/nex/nexThread.cpp
#include "prudp.h" #include "nex.h" #include "nexThread.h" std::mutex mtx_queuedServices; std::vector<nexService*> list_queuedServices; std::vector<nexService*> list_activeNexServices; void nexThread_run() { while (true) { // check for new services mtx_queuedServices.lock(); for(auto& it : list_queuedServices) list_activeNexServices.push_back(it); list_queuedServices.clear(); mtx_queuedServices.unlock(); // if service list is empty then pause if (list_activeNexServices.empty()) { std::this_thread::sleep_for(std::chrono::milliseconds(200)); continue; } // update for (auto& it : list_activeNexServices) { it->update(); } // delete services marked for destruction sint32 idx = 0; sint32 listSize = (sint32)list_activeNexServices.size(); while (idx < listSize) { if (list_activeNexServices[idx]->isMarkedForDestruction()) { list_activeNexServices[idx]->destroy(); listSize--; list_activeNexServices[idx] = list_activeNexServices[listSize]; } idx++; } if (listSize != list_activeNexServices.size()) { list_activeNexServices.resize(listSize); } // idle for short time // todo - find a better way to handle this with lower latency. Maybe using select() with loopback socket for interrupting the select on service change std::this_thread::sleep_for(std::chrono::milliseconds(1)); } } bool _nexThreadLaunched = false; std::thread::id nexThreadId; void nexThread_init() { if (_nexThreadLaunched) return; std::thread t(nexThread_run); nexThreadId = t.get_id(); t.detach(); _nexThreadLaunched = true; } void nexThread_registerService(nexService* service) { mtx_queuedServices.lock(); nexThread_init(); list_queuedServices.push_back(service); mtx_queuedServices.unlock(); } bool nexThread_isCurrentThread() { if (_nexThreadLaunched == false) return false; return std::this_thread::get_id() == nexThreadId; }
1,916
C++
.cpp
73
23.684932
152
0.736383
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,944
nex.cpp
cemu-project_Cemu/src/Cemu/nex/nex.cpp
#include "prudp.h" #include "nex.h" #include "nexThread.h" #include "util/crypto/md5.h" // for inet_pton: #if BOOST_OS_WINDOWS #include <WS2tcpip.h> #else #include <arpa/inet.h> #endif uint32 _currentCallId = 1; sint32 nexService_parseResponse(uint8* data, sint32 length, nexServiceResponse_t* response) { if (length < 4) return 0; // get length field uint32 responseLength = *(uint32*)(data + 0x0); length -= 4; if (responseLength > (uint32)length) return 0; if (responseLength < 6) return 0; uint8 protocolId = *(uint8*)(data + 0x04); bool isRequest = (protocolId & 0x80) != 0; protocolId &= 0x7F; if (isRequest) { #ifdef CEMU_DEBUG_ASSERT assert_dbg(); // should never reach since we handle requests before this function is called #endif } uint8 success = *(uint8*)(data + 0x5); if (success == 0) { // error uint32 errorCode; if (length < 0xA) { return 0; } errorCode = *(uint32*)(data + 0x6); response->errorCode = errorCode; response->callId = *(uint32*)(data + 0xA); response->isSuccessful = false; response->protocolId = protocolId; response->methodId = 0xFFFFFFFF; return responseLength + 4; } else { if (responseLength < 0xA) return 0; response->errorCode = 0; response->isSuccessful = true; response->protocolId = protocolId; response->callId = *(uint32*)(data + 0x6); response->methodId = (*(uint32*)(data + 0xA)) & 0x7FFF; response->data = nexPacketBuffer(data + 0xE, responseLength - (0xE - 4), false); return responseLength+4; } return 0; } sint32 nexService_parseRequest(uint8* data, sint32 length, nexServiceRequest_t* request) { if (length < 4) return 0; // get length field uint32 requestLength = *(uint32*)(data + 0x0) + 4; if (requestLength > (uint32)length) return 0; if (requestLength < 13) return 0; uint8 protocolId = *(uint8*)(data + 0x4); bool isRequest = (protocolId & 0x80) != 0; protocolId &= 0x7F; if(isRequest == false) assert_dbg(); uint32 callId = *(uint32*)(data + 0x5); uint32 methodId = *(uint32*)(data + 0x9); uint8* dataPtr = (data + 0xD); sint32 dataLength = (sint32)(requestLength - 0xD); request->callId = callId; request->methodId = methodId; request->protocolId = protocolId; request->data = nexPacketBuffer(dataPtr, dataLength, false); return requestLength; } nexService::nexService() { connectionState = STATE_CONNECTING; conNexService = nullptr; isAsync = false; isDestroyed = false; isSecureService = false; } nexService::nexService(prudpClient* con) : nexService() { if (con->IsConnected() == false) cemu_assert_suspicious(); this->conNexService = con; bufferReceive = std::vector<uint8>(1024 * 4); } nexService::nexService(uint32 ip, uint16 port, const char* accessKey) : nexService() { // unsecured connection isSecureService = false; conNexService = new prudpClient(ip, port, accessKey); bufferReceive = std::vector<uint8>(1024 * 4); } nexService::~nexService() { // call error handlers for unfinished method calls for (auto& it : list_activeRequests) { nexServiceResponse_t response = { 0 }; response.isSuccessful = false; response.errorCode = ERR_TIMEOUT; response.custom = it.custom; if (it.nexServiceResponse) it.nexServiceResponse(this, &response); else { it.cb2(&response); } } if (conNexService) delete conNexService; } void nexService::destroy() { if (nexThread_isCurrentThread()) { delete this; return; } if (this->isAsync) isDestroyed = true; else delete this; } bool nexService::isMarkedForDestruction() { return isDestroyed; } void nexService::callMethod(uint8 protocolId, uint32 methodId, nexPacketBuffer* parameter, void(*nexServiceResponse)(nexService* nex, nexServiceResponse_t* serviceResponse), void* custom, bool callHandlerIfError) { queuedRequest_t queueRequest = { 0 }; queueRequest.protocolId = protocolId; queueRequest.methodId = methodId; queueRequest.parameterData.assign(parameter->getDataPtr(), parameter->getDataPtr() + parameter->getWriteIndex()); queueRequest.nexServiceResponse = nexServiceResponse; queueRequest.custom = custom; queueRequest.callHandlerIfError = callHandlerIfError; mtx_queuedRequests.lock(); queuedRequests.push_back(queueRequest); mtx_queuedRequests.unlock(); } void nexService::callMethod(uint8 protocolId, uint32 methodId, nexPacketBuffer* parameter, std::function<void(nexServiceResponse_t*)> cb, bool callHandlerIfError) { queuedRequest_t queueRequest = { 0 }; queueRequest.protocolId = protocolId; queueRequest.methodId = methodId; queueRequest.parameterData.assign(parameter->getDataPtr(), parameter->getDataPtr() + parameter->getWriteIndex()); queueRequest.nexServiceResponse = nullptr; queueRequest.cb2 = cb; queueRequest.callHandlerIfError = callHandlerIfError; mtx_queuedRequests.lock(); queuedRequests.push_back(queueRequest); mtx_queuedRequests.unlock(); } void nexService::processQueuedRequest(queuedRequest_t* queuedRequest) { uint32 callId = _currentCallId; _currentCallId++; // check state of connection if (conNexService->GetConnectionState() != prudpClient::ConnectionState::Connected) { nexServiceResponse_t response = { 0 }; response.isSuccessful = false; response.errorCode = ERR_NO_CONNECTION; response.custom = queuedRequest->custom; if (queuedRequest->nexServiceResponse) queuedRequest->nexServiceResponse(this, &response); else { queuedRequest->cb2(&response); } return; } uint8 packetBuffer[1024 * 8]; *(uint32*)(packetBuffer + 0x00) = 1 + 4 + 4 + (uint32)queuedRequest->parameterData.size(); // size *(uint8*)(packetBuffer + 0x04) = queuedRequest->protocolId | PROTOCOL_BIT_REQUEST; *(uint32*)(packetBuffer + 0x05) = callId; *(uint32*)(packetBuffer + 0x09) = queuedRequest->methodId; if (queuedRequest->parameterData.size() >= 1024 * 7) assert_dbg(); memcpy((packetBuffer + 0x0D), &queuedRequest->parameterData.front(), queuedRequest->parameterData.size()); sint32 length = 0xD + (sint32)queuedRequest->parameterData.size(); conNexService->SendDatagram(packetBuffer, length, true); // remember request nexActiveRequestInfo_t requestInfo = { 0 }; requestInfo.callId = callId; requestInfo.methodId = queuedRequest->methodId; requestInfo.protocolId = queuedRequest->protocolId; if (queuedRequest->nexServiceResponse) { requestInfo.nexServiceResponse = queuedRequest->nexServiceResponse; requestInfo.custom = queuedRequest->custom; } else { requestInfo.cb2 = queuedRequest->cb2; } requestInfo.handleError = queuedRequest->callHandlerIfError; requestInfo.requestTime = prudpGetMSTimestamp(); list_activeRequests.push_back(requestInfo); } void nexService::update() { if (connectionState == STATE_CONNECTED) { updateNexServiceConnection(); // process any queued requests mtx_queuedRequests.lock(); for (auto& request : queuedRequests) { processQueuedRequest(&request); } queuedRequests.clear(); mtx_queuedRequests.unlock(); } else if (connectionState == STATE_CONNECTING) { updateTemporaryConnections(); } // handle request timeouts uint32 currentTimestamp = prudpGetMSTimestamp(); sint32 idx = 0; while (idx < list_activeRequests.size()) { auto& it = list_activeRequests[idx]; if ((uint32)(currentTimestamp - it.requestTime) >= 10000) { // time out after 10 seconds nexServiceResponse_t response = { 0 }; response.isSuccessful = false; response.errorCode = ERR_TIMEOUT; response.custom = it.custom; if (it.nexServiceResponse) it.nexServiceResponse(this, &response); else { it.cb2(&response); } list_activeRequests.erase(list_activeRequests.cbegin()+idx); continue; } idx++; } } prudpClient* nexService::getPRUDPConnection() { return conNexService; } sint32 nexService::getState() { return connectionState; } void nexService::registerForAsyncProcessing() { if (isAsync) return; nexThread_registerService(this); isAsync = true; } void nexService::updateTemporaryConnections() { // check for connection conNexService->Update(); if (conNexService->IsConnected()) { if (connectionState == STATE_CONNECTING) connectionState = STATE_CONNECTED; } if (conNexService->GetConnectionState() == prudpClient::ConnectionState::Disconnected) connectionState = STATE_DISCONNECTED; } // returns true if the packet is a nex RPC request, in case of error false is returned bool nexIsRequest(uint8* data, sint32 length) { if (length < 5) return false; uint8 protocolId = *(uint8*)(data + 0x04); bool isRequest = (protocolId & 0x80) != 0; return isRequest; } void nexService::registerProtocolRequestHandler(uint8 protocol, void(*processRequest)(nexServiceRequest_t* request), void* custom) { protocolHandler_t protocolHandler; protocolHandler.protocol = protocol; protocolHandler.processRequest = processRequest; protocolHandler.custom = custom; list_requestHandlers.push_back(protocolHandler); } void nexService::sendRequestResponse(nexServiceRequest_t* request, uint32 errorCode, uint8* data, sint32 length) { cemu_assert_debug(length == 0); // non-zero length is todo uint8 packetBuffer[256]; nexPacketBuffer response(packetBuffer, sizeof(packetBuffer), true); bool isSuccess = (errorCode == 0); // write placeholder for response length response.writeU32(0); // header fields response.writeU8(request->protocolId&0x7F); response.writeU8(isSuccess); if (isSuccess) { response.writeU32(request->callId); response.writeU32(request->methodId); // write data // todo } else { response.writeU32(errorCode); response.writeU32(request->callId); } // update length field *(uint32*)response.getDataPtr() = response.getWriteIndex()-4; if(request->nex->conNexService) request->nex->conNexService->SendDatagram(response.getDataPtr(), response.getWriteIndex(), true); } void nexService::updateNexServiceConnection() { if (conNexService->GetConnectionState() == prudpClient::ConnectionState::Disconnected) { this->connectionState = STATE_DISCONNECTED; return; } conNexService->Update(); sint32 datagramLen = conNexService->ReceiveDatagram(bufferReceive); if (datagramLen > 0) { if (nexIsRequest(&bufferReceive[0], datagramLen)) { // request nexServiceRequest_t nexServiceRequest; sint32 parsedLength = nexService_parseRequest(&bufferReceive[0], datagramLen, &nexServiceRequest); if (parsedLength > 0) { nexServiceRequest.nex = this; // call request handler for (auto& it : list_requestHandlers) { if (it.protocol == nexServiceRequest.protocolId) { nexServiceRequest.custom = it.custom; it.processRequest(&nexServiceRequest); break; } } } cemu_assert_debug(parsedLength == datagramLen); } else { // response nexServiceResponse_t nexServiceResponse; sint32 parsedLength = nexService_parseResponse(&bufferReceive[0], datagramLen, &nexServiceResponse); if (parsedLength > 0) { nexServiceResponse.nex = this; // call response handler for (sint32 i = 0; i < list_activeRequests.size(); i++) { if (nexServiceResponse.callId == list_activeRequests[i].callId && nexServiceResponse.protocolId == list_activeRequests[i].protocolId && (nexServiceResponse.methodId == list_activeRequests[i].methodId || nexServiceResponse.methodId == 0xFFFFFFFF)) { nexServiceResponse.custom = list_activeRequests[i].custom; if (nexServiceResponse.isSuccessful || list_activeRequests[i].handleError) { if (list_activeRequests[i].nexServiceResponse) list_activeRequests[i].nexServiceResponse(this, &nexServiceResponse); else { list_activeRequests[i].cb2(&nexServiceResponse); } } // remove entry list_activeRequests.erase(list_activeRequests.begin() + i); break; } } } cemu_assert_debug(parsedLength == datagramLen); } } } bool _extractStationUrlParamValue(const char* urlStr, const char* paramName, char* output, sint32 maxLength) { size_t paramNameLen = strlen(paramName); const char* optionPtr = strstr(urlStr, paramName); while (optionPtr) { if (optionPtr[paramNameLen] == '=') { output[maxLength - 1] = '\0'; for (sint32 i = 0; i < maxLength - 1; i++) { char c = optionPtr[paramNameLen + 1 + i]; if (c == ';' || c == '\0') { output[i] = '\0'; break; } output[i] = c; } return true; } // next optionPtr = strstr(optionPtr+1, paramName); } return false; } void nexServiceAuthentication_parseStationURL(char* urlStr, prudpStationUrl* stationUrl) { // example: // prudps:/address=34.210.xxx.xxx;port=60181;CID=1;PID=2;sid=1;stream=10;type=2 memset(stationUrl, 0, sizeof(prudpStationUrl)); char optionValue[128]; if (_extractStationUrlParamValue(urlStr, "address", optionValue, sizeof(optionValue))) { inet_pton(AF_INET, optionValue, &stationUrl->ip); } if (_extractStationUrlParamValue(urlStr, "port", optionValue, sizeof(optionValue))) { stationUrl->port = atoi(optionValue); } if (_extractStationUrlParamValue(urlStr, "CID", optionValue, sizeof(optionValue))) { stationUrl->cid = atoi(optionValue); } if (_extractStationUrlParamValue(urlStr, "PID", optionValue, sizeof(optionValue))) { stationUrl->pid = atoi(optionValue); } if (_extractStationUrlParamValue(urlStr, "sid", optionValue, sizeof(optionValue))) { stationUrl->sid = atoi(optionValue); } if (_extractStationUrlParamValue(urlStr, "stream", optionValue, sizeof(optionValue))) { stationUrl->stream = atoi(optionValue); } if (_extractStationUrlParamValue(urlStr, "type", optionValue, sizeof(optionValue))) { stationUrl->type = atoi(optionValue); } } typedef struct { uint32 userPid; uint8 kerberosTicket[1024]; sint32 kerberosTicketSize; uint8 kerberosTicket2[4096]; sint32 kerberosTicket2Size; prudpStationUrl server; // progress info bool hasError; bool done; }authenticationService_t; void nexServiceAuthentication_handleResponse_requestTicket(nexService* nex, nexServiceResponse_t* response) { authenticationService_t* authService = (authenticationService_t*)response->custom; if (response->isSuccessful == false) { cemuLog_log(LogType::Force, "NEX: RPC error while requesting auth ticket with error code 0x{:08x}", response->errorCode); authService->hasError = true; return; } uint32 returnValue = response->data.readU32(); if (returnValue & 0x80000000) { cemuLog_log(LogType::Force, "NEX: Failed to request auth ticket with error code 0x{:08x}", returnValue); authService->hasError = true; } authService->kerberosTicket2Size = response->data.readBuffer(authService->kerberosTicket2, sizeof(authService->kerberosTicket2)); if (response->data.hasReadOutOfBounds()) { authService->hasError = true; cemuLog_log(LogType::Force, "NEX: Out of bounds error while reading auth ticket"); return; } authService->done = true; } void nexServiceAuthentication_handleResponse_login(nexService* nex, nexServiceResponse_t* response) { authenticationService_t* authService = (authenticationService_t*)response->custom; if (response->isSuccessful == false) { authService->hasError = true; cemuLog_log(LogType::Force, "NEX: RPC error in login response 0x{:08x}", response->errorCode); return; } uint32 returnValue = response->data.readU32(); if (returnValue & 0x80000000) { authService->hasError = true; cemuLog_log(LogType::Force, "NEX: Error 0x{:08x} in login response (returnCode 0x{:08x})", response->errorCode, returnValue); return; } uint32 userPid = response->data.readU32(); // kerberos ticket authService->kerberosTicketSize = response->data.readBuffer(authService->kerberosTicket, sizeof(authService->kerberosTicket)); // RVConnection data // server address (regular protocol) char serverAddress[1024]; response->data.readString(serverAddress, sizeof(serverAddress)); nexServiceAuthentication_parseStationURL(serverAddress, &authService->server); // special protocols if (response->data.readU32() != 0) assert_dbg(); // list not empty char specialAddress[32]; response->data.readString(specialAddress, sizeof(specialAddress)); // V1 has extra info here // server name char serverName[256]; response->data.readString(serverName, sizeof(serverName)); if (response->data.hasReadOutOfBounds()) { authService->hasError = true; cemuLog_log(LogType::Force, "NEX: Read out of bounds"); return; } // request ticket data uint8 tempNexBufferArray[1024]; nexPacketBuffer packetBuffer(tempNexBufferArray, sizeof(tempNexBufferArray), true); packetBuffer.writeU32(authService->userPid); packetBuffer.writeU32(authService->server.pid); nex->callMethod(NEX_PROTOCOL_AUTHENTICATION, 3, &packetBuffer, nexServiceAuthentication_handleResponse_requestTicket, authService); } typedef struct { bool isComplete; bool isSuccessful; }nexServiceSecureRegisterExData_t; void nexServiceSecure_handleResponse_RegisterEx(nexService* nex, nexServiceResponse_t* response) { nexServiceSecureRegisterExData_t* info = (nexServiceSecureRegisterExData_t*)response->custom; info->isComplete = true; uint32 returnCode = response->data.readU32(); if (response->isSuccessful == false || response->data.hasReadOutOfBounds()) { cemuLog_log(LogType::Force, "NEX: RPC error in secure register"); info->isSuccessful = false; info->isComplete = true; return; } if (returnCode & 0x80000000) { cemuLog_log(LogType::Force, "NEX: Secure register failed with error code 0x{:08x}", returnCode); info->isSuccessful = false; info->isComplete = true; return; } // remaining data is skipped info->isSuccessful = true; info->isComplete = true; return; } nexService* nex_secureLogin(prudpAuthServerInfo* authServerInfo, const char* accessKey, const char* nexToken) { prudpClient* prudpSecureSock = new prudpClient(authServerInfo->server.ip, authServerInfo->server.port, accessKey, authServerInfo); // wait until connected while (true) { prudpSecureSock->Update(); if (prudpSecureSock->IsConnected()) { break; } if (prudpSecureSock->GetConnectionState() == prudpClient::ConnectionState::Disconnected) { // timeout or disconnected cemuLog_log(LogType::Force, "NEX: Secure login connection time-out"); delete prudpSecureSock; return nullptr; } std::this_thread::sleep_for(std::chrono::milliseconds(1)); } // create nex service layer nexService* nex = new nexService(prudpSecureSock); // secureService: RegisterEx uint8 tempNexBufferArray[4096]; nexPacketBuffer packetBuffer(tempNexBufferArray, sizeof(tempNexBufferArray), true); char clientStationUrl[256]; sprintf(clientStationUrl, "prudp:/port=%u;natf=0;natm=0;pmp=0;sid=15;type=2;upnp=0", (uint32)nex->getPRUDPConnection()->GetSourcePort()); // station url list packetBuffer.writeU32(1); packetBuffer.writeString(clientStationUrl); // login data packetBuffer.writeCustomType(nexNintendoLoginData(nexToken)); nexServiceSecureRegisterExData_t secureRegisterExData = { 0 }; nex->callMethod(NEX_PROTOCOL_SECURE, 4, &packetBuffer, nexServiceSecure_handleResponse_RegisterEx, &secureRegisterExData); while (true) { nex->update(); if (secureRegisterExData.isComplete) break; if (nex->getState() == nexService::STATE_DISCONNECTED) { cemuLog_log(LogType::Force, "NEX: Connection error while registering"); break; } } if (secureRegisterExData.isSuccessful == false) { cemuLog_log(LogType::Force, "NEX: Failed to register to secure server"); nex->destroy(); return nullptr; } return nex; } nexService* nex_establishSecureConnection(uint32 authServerIp, uint16 authServerPort, const char* accessKey, uint32 pid, const char* nexPassword, const char* nexToken) { nexService* authConnection = new nexService(authServerIp, authServerPort, accessKey); // wait until connected while (authConnection->getState() == nexService::STATE_CONNECTING) { authConnection->update(); std::this_thread::sleep_for(std::chrono::milliseconds(1)); } if (authConnection->getState() != nexService::STATE_CONNECTED) { // error authConnection->destroy(); cemuLog_log(LogType::Force, "NEX: Failed to connect to the NEX server"); return nullptr; } // send auth login request uint8 tempNexBufferArray[1024]; nexPacketBuffer packetBuffer(tempNexBufferArray, sizeof(tempNexBufferArray), true); char pidStr[32]; sprintf(pidStr, "%u", pid); packetBuffer.writeString(pidStr); authenticationService_t nexAuthService = { 0 }; nexAuthService.userPid = pid; authConnection->callMethod(NEX_PROTOCOL_AUTHENTICATION, 1, &packetBuffer, nexServiceAuthentication_handleResponse_login, &nexAuthService); while (true) { if (nexAuthService.hasError || nexAuthService.done || authConnection->getState() != nexService::STATE_CONNECTED) break; authConnection->update(); } if (nexAuthService.hasError || authConnection->getState() != nexService::STATE_CONNECTED) { // error authConnection->destroy(); cemuLog_log(LogType::Force, "NEX: Error during authentication"); return nullptr; } // close connection to auth server authConnection->destroy(); // calculate kerberos decryption key uint32 md5LoopCount = 65000 + (pid % 1024); md5LoopCount--; uint8 kerberosKey[16]; MD5_CTX md5Ctx; MD5_Init(&md5Ctx); MD5_Update(&md5Ctx, nexPassword, (unsigned long)strlen(nexPassword)); MD5_Final(kerberosKey, &md5Ctx); for (uint32 i = 0; i < md5LoopCount; i++) { MD5_Init(&md5Ctx); MD5_Update(&md5Ctx, kerberosKey, 16); MD5_Final(kerberosKey, &md5Ctx); } if (nexAuthService.kerberosTicket2Size < 16) { nexAuthService.hasError = true; cemuLog_log(LogType::Force, "NEX: Kerberos ticket too short"); return nullptr; } // check hmac of ticket uint8 hmacTicket[16]; hmacMD5(kerberosKey, 16, nexAuthService.kerberosTicket2, nexAuthService.kerberosTicket2Size - 16, hmacTicket); if (memcmp(hmacTicket, nexAuthService.kerberosTicket2 + nexAuthService.kerberosTicket2Size - 16, 16) != 0) { nexAuthService.hasError = true; cemuLog_log(LogType::Force, "NEX: Kerberos ticket hmac invalid"); return nullptr; } // auth info auto authServerInfo = std::make_unique<prudpAuthServerInfo>(); // decrypt ticket RC4Ctx rc4Ticket; RC4_initCtx(&rc4Ticket, kerberosKey, 16); RC4_transform(&rc4Ticket, nexAuthService.kerberosTicket2, nexAuthService.kerberosTicket2Size - 16, nexAuthService.kerberosTicket2); nexPacketBuffer packetKerberosTicket(nexAuthService.kerberosTicket2, nexAuthService.kerberosTicket2Size - 16, false); uint8 secureKey[16]; // for friends server it's 16 bytes, all others use 32 bytes packetKerberosTicket.readData(secureKey, 16); uint32 ukn = packetKerberosTicket.readU32(); authServerInfo->secureTicketLength = packetKerberosTicket.readBuffer(authServerInfo->secureTicket, sizeof(authServerInfo->secureTicket)); if (packetKerberosTicket.hasReadOutOfBounds()) { cemuLog_log(LogType::Force, "NEX: Parse error"); return nullptr; } memcpy(authServerInfo->kerberosKey, kerberosKey, 16); memcpy(authServerInfo->secureKey, secureKey, 16); memcpy(&authServerInfo->server, &nexAuthService.server, sizeof(prudpStationUrl)); authServerInfo->userPid = pid; return nex_secureLogin(authServerInfo.get(), accessKey, nexToken); }
23,151
C++
.cpp
715
29.825175
212
0.757952
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,945
prudp.cpp
cemu-project_Cemu/src/Cemu/nex/prudp.cpp
#include "prudp.h" #include "util/crypto/md5.h" #include <bitset> #include <random> #include <boost/random/uniform_int.hpp> static void KSA(unsigned char* key, int keyLen, unsigned char* S) { for (int i = 0; i < RC4_N; i++) S[i] = i; int j = 0; for (int i = 0; i < RC4_N; i++) { j = (j + S[i] + key[i % keyLen]) % RC4_N; std::swap(S[i], S[j]); } } static void PRGA(unsigned char* S, unsigned char* input, int len, unsigned char* output) { for (size_t n = 0; n < len; n++) { int i = (i + 1) % RC4_N; int j = (j + S[i]) % RC4_N; std::swap(S[i], S[j]); int rnd = S[(S[i] + S[j]) % RC4_N]; output[n] = rnd ^ input[n]; } } static void RC4(char* key, unsigned char* input, int len, unsigned char* output) { unsigned char S[RC4_N]; KSA((unsigned char*)key, (int)strlen(key), S); PRGA(S, input, len, output); } void RC4_initCtx(RC4Ctx* rc4Ctx, const char* key) { rc4Ctx->i = 0; rc4Ctx->j = 0; KSA((unsigned char*)key, (int)strlen(key), rc4Ctx->S); } void RC4_initCtx(RC4Ctx* rc4Ctx, unsigned char* key, int keyLen) { rc4Ctx->i = 0; rc4Ctx->j = 0; KSA(key, keyLen, rc4Ctx->S); } void RC4_transform(RC4Ctx* rc4Ctx, unsigned char* input, int len, unsigned char* output) { int i = rc4Ctx->i; int j = rc4Ctx->j; for (size_t n = 0; n < len; n++) { i = (i + 1) % RC4_N; j = (j + rc4Ctx->S[i]) % RC4_N; std::swap(rc4Ctx->S[i], rc4Ctx->S[j]); int rnd = rc4Ctx->S[(rc4Ctx->S[i] + rc4Ctx->S[j]) % RC4_N]; output[n] = rnd ^ input[n]; } rc4Ctx->i = i; rc4Ctx->j = j; } uint32 prudpGetMSTimestamp() { return GetTickCount(); } std::mt19937_64 prudpRG(GetTickCount()); // workaround for static asserts when using uniform_int_distribution (see https://github.com/cemu-project/Cemu/issues/48) boost::random::uniform_int_distribution<int> prudpRandomDistribution8(0, 0xFF); boost::random::uniform_int_distribution<int> prudpRandomDistributionPortGen(0, 10000); uint8 prudp_generateRandomU8() { return prudpRandomDistribution8(prudpRG); } uint32 prudp_generateRandomU32() { uint32 v = prudp_generateRandomU8(); v <<= 8; v |= prudp_generateRandomU8(); v <<= 8; v |= prudp_generateRandomU8(); v <<= 8; v |= prudp_generateRandomU8(); return v; } std::bitset<10000> _portUsageMask; static uint16 AllocateRandomSrcPRUDPPort() { while (true) { sint32 p = prudpRandomDistributionPortGen(prudpRG); if (_portUsageMask.test(p)) continue; _portUsageMask.set(p); return 40000 + p; } } static void ReleasePRUDPSrcPort(uint16 port) { cemu_assert_debug(port >= 40000); uint32 bitIndex = port - 40000; cemu_assert_debug(_portUsageMask.test(bitIndex)); _portUsageMask.reset(bitIndex); } static uint8 prudp_calculateChecksum(uint8 checksumBase, uint8* data, sint32 length) { uint32 checksum32 = 0; for (sint32 i = 0; i < length / 4; i++) { checksum32 += *(uint32*)(data + i * 4); } uint8 checksum = checksumBase; for (sint32 i = length & (~3); i < length; i++) { checksum += data[i]; } checksum += (uint8)((checksum32 >> 0) & 0xFF); checksum += (uint8)((checksum32 >> 8) & 0xFF); checksum += (uint8)((checksum32 >> 16) & 0xFF); checksum += (uint8)((checksum32 >> 24) & 0xFF); return checksum; } // calculate the actual size of the packet from the unprocessed raw data // returns 0 on error sint32 prudpPacket::calculateSizeFromPacketData(uint8* data, sint32 length) { // check if packet is long enough to hold basic header if (length < 0xB) return 0; // get flags fields uint16 typeAndFlags = *(uint16*)(data + 0x02); uint16 type = (typeAndFlags & 0xF); uint16 flags = (typeAndFlags >> 4); if ((flags & FLAG_HAS_SIZE) == 0) return length; // without a size field, we cant calculate the length sint32 calculatedSize; if (type == TYPE_SYN) { if (length < (0xB + 0x4 + 2)) return 0; uint16 payloadSize = *(uint16*)(data + 0xB + 0x4); calculatedSize = 0xB + 0x4 + 2 + (sint32)payloadSize + 1; // base header + connection signature (SYN param) + payloadSize field + checksum after payload if (calculatedSize > length) return 0; return calculatedSize; } else if (type == TYPE_CON) { if (length < (0xB + 0x4 + 2)) return 0; uint16 payloadSize = *(uint16*)(data + 0xB + 0x4); calculatedSize = 0xB + 0x4 + 2 + (sint32)payloadSize + 1; // base header + connection signature (CON param) + payloadSize field + checksum after payload // note: For secure connections the extra data is part of the payload if (calculatedSize > length) return 0; return calculatedSize; } else if (type == TYPE_DATA) { if (length < (0xB + 1 + 2)) return 0; uint16 payloadSize = *(uint16*)(data + 0xB + 1); calculatedSize = 0xB + 1 + 2 + (sint32)payloadSize + 1; // base header + fragmentIndex (DATA param) + payloadSize field + checksum after payload if (calculatedSize > length) return 0; return calculatedSize; } else if (type == TYPE_PING) { if (length < (0xB + 2)) return 0; uint16 payloadSize = *(uint16*)(data + 0xB); calculatedSize = 0xB + 2 + (sint32)payloadSize + 1; // base header + payloadSize field + checksum after payload if (calculatedSize > length) return 0; return calculatedSize; } else assert_dbg(); // unknown packet type (todo - add disconnect and ping packet, then make this function return 0 for all unknown types) return length; } prudpPacket::prudpPacket(prudpStreamSettings* streamSettings, uint8 src, uint8 dst, uint8 type, uint16 flags, uint8 sessionId, uint16 sequenceId, uint32 packetSignature) { this->src = src; this->dst = dst; this->type = type; this->flags = flags; this->sessionId = sessionId; this->m_sequenceId = sequenceId; this->specifiedPacketSignature = packetSignature; this->streamSettings = streamSettings; this->fragmentIndex = 0; this->isEncrypted = false; } bool prudpPacket::requiresAck() { return (flags & FLAG_NEED_ACK) != 0; } sint32 prudpPacket::buildData(uint8* output, sint32 maxLength) { // PRUDP V0 // encrypt packet data if (this->type == prudpPacket::TYPE_DATA) { // dont save new rc4 state if the packet is not reliable or requires no ack? if (packetData.size() > 0) { if (isEncrypted == false) // only encrypt once { RC4_transform(&streamSettings->rc4Client, &packetData.front(), (int)packetData.size(), &packetData.front()); isEncrypted = true; } } } // build packet uint8* packetBuffer = output; sint32 writeIndex = 0; // write constant header *(uint8*)(packetBuffer + 0x00) = src; *(uint8*)(packetBuffer + 0x01) = dst; uint16 typeAndFlags = (this->flags << 4) | (this->type); *(uint16*)(packetBuffer + 0x02) = typeAndFlags; *(uint8*)(packetBuffer + 0x04) = sessionId; *(uint32*)(packetBuffer + 0x05) = packetSignature(); *(uint16*)(packetBuffer + 0x09) = m_sequenceId; writeIndex = 0xB; // variable fields if (this->type == TYPE_SYN) { *(uint32*)(packetBuffer + writeIndex) = 0; // connection signature (always 0 for SYN packet) writeIndex += 4; } else if (this->type == TYPE_CON) { // connection signature (+ kerberos data if secure connection) memcpy(packetBuffer + writeIndex, &packetData.front(), packetData.size()); writeIndex += (int)packetData.size(); } else if (this->type == TYPE_DATA) { *(uint8*)(packetBuffer + writeIndex) = fragmentIndex; // fragment index writeIndex += 1; if (packetData.empty() == false) { memcpy(packetBuffer + writeIndex, &packetData.front(), packetData.size()); writeIndex += (int)packetData.size(); } } else if (this->type == TYPE_PING) { // no data } else { cemu_assert_suspicious(); } // checksum *(uint8*)(packetBuffer + writeIndex) = calculateChecksum(packetBuffer, writeIndex); writeIndex++; return writeIndex; } uint32 prudpPacket::packetSignature() { if (type == TYPE_SYN) return 0; else if (type == TYPE_CON || type == TYPE_PING) return specifiedPacketSignature; else if (type == TYPE_DATA) { if (packetData.empty()) return 0x12345678; HMACMD5Ctx ctx; hmacMD5_init_limK_to_64(streamSettings->accessKeyDigest, 16, &ctx); hmacMD5_update(&packetData.front(), (int)packetData.size(), &ctx); uint8 digest[16]; hmacMD5_final(digest, &ctx); uint32 pSig = *(uint32*)digest; return pSig; } assert_dbg(); return 0; } void prudpPacket::setData(uint8* data, sint32 length) { packetData.assign(data, data + length); } void prudpPacket::setFragmentIndex(uint8 fragmentIndex) { this->fragmentIndex = fragmentIndex; } uint8 prudpPacket::calculateChecksum(uint8* data, sint32 length) { return prudp_calculateChecksum(streamSettings->checksumBase, data, length); } prudpIncomingPacket::prudpIncomingPacket() { src = 0; dst = 0; flags = 0; type = 0; sessionId = 0; packetSignature = 0; sequenceId = 0; fragmentIndex = 0; hasData = false; isInvalid = false; streamSettings = nullptr; } prudpIncomingPacket::prudpIncomingPacket(prudpStreamSettings* streamSettings, uint8* data, sint32 length) : prudpIncomingPacket() { if (length < 0xB + 1) { isInvalid = true; return; } this->streamSettings = streamSettings; // verify checksum first uint8 actualChecksum = calculateChecksum(data, length - 1); uint8 packetChecksum = *(uint8*)(data + length - 1); if (actualChecksum != packetChecksum) { isInvalid = true; return; } length--; // remove checksum from length // verify constant header this->src = *(uint8*)(data + 0x00); this->dst = *(uint8*)(data + 0x01); uint16 typeAndFlags = *(uint16*)(data + 0x02); this->flags = (typeAndFlags >> 4) & 0xFFF; this->type = (typeAndFlags & 0xF); this->sessionId = *(uint8*)(data + 0x4); this->packetSignature = *(uint32*)(data + 0x5); this->sequenceId = *(uint16*)(data + 0x9); // read dynamic fields sint32 readIndex = 0xB; if (this->type == prudpPacket::TYPE_SYN) { // SYN packet if (readIndex < 4) { isInvalid = true; return; } packetData.resize(4); *(uint32*)(&packetData.front()) = *(uint32*)(data + readIndex); hasData = true; readIndex += 4; // ignore FLAG_HAS_SIZE (would come here, usually with a value of 0) return; } else if (this->type == prudpPacket::TYPE_CON) { // CON packet if (readIndex < 4) { isInvalid = true; return; } // this packet has another 4 byte signature but it's always zero? (value is ignored for now) // ignore FLAG_HAS_SIZE } else if (this->type == prudpPacket::TYPE_PING) { // PING packet // ignore payload } else if (this->type == prudpPacket::TYPE_DATA) { // can we assume that reliable data packets always need to have a unique sequence id? (Even if it's a multi-fragment frame) // unreliable packets must have a sequence id too or how else would we know when to decrypt it? bool hasPayloadSize = (this->flags & prudpPacket::FLAG_HAS_SIZE) != 0; // verify length if ((length - readIndex) < 1 + (hasPayloadSize ? 2 : 0)) { // too short isInvalid = true; return; } // read fragment index this->fragmentIndex = *(uint8*)(data + readIndex); readIndex += sizeof(uint8); // read payload size (optional) if (hasPayloadSize) { uint16 payloadSize = *(uint32*)(data + readIndex); readIndex += sizeof(uint16); // verify payload size if ((length - readIndex) != payloadSize) { assert_dbg(); // mismatch, ignore packet or use specified payload size? } } // read payload if (readIndex < length) { sint32 dataSize = length - readIndex; packetData.resize(dataSize); memcpy(&packetData.front(), data + readIndex, dataSize); } return; } else if (this->type == prudpPacket::TYPE_DISCONNECT) { // DISCONNECT packet // ignore payload } else { cemu_assert_suspicious(); } } bool prudpIncomingPacket::hasError() { return isInvalid; } uint8 prudpIncomingPacket::calculateChecksum(uint8* data, sint32 length) { return prudp_calculateChecksum(streamSettings->checksumBase, data, length); } void prudpIncomingPacket::decrypt() { if (packetData.empty()) return; RC4_transform(&streamSettings->rc4Server, &packetData.front(), (int)packetData.size(), &packetData.front()); } #define PRUDP_VPORT(__streamType, __port) (((__streamType) << 4) | (__port)) prudpClient::prudpClient() { m_currentConnectionState = ConnectionState::Connecting; m_serverConnectionSignature = 0; m_clientConnectionSignature = 0; m_incomingSequenceId = 0; m_clientSessionId = 0; m_serverSessionId = 0; } prudpClient::prudpClient(uint32 dstIp, uint16 dstPort, const char* key) : prudpClient() { m_dstIp = dstIp; m_dstPort = dstPort; // get unused random source port for (sint32 tries = 0; tries < 5; tries++) { m_srcPort = AllocateRandomSrcPRUDPPort(); // create and bind udp socket m_socketUdp = socket(AF_INET, SOCK_DGRAM, 0); struct sockaddr_in udpServer; udpServer.sin_family = AF_INET; udpServer.sin_addr.s_addr = INADDR_ANY; udpServer.sin_port = htons(m_srcPort); if (bind(m_socketUdp, (struct sockaddr*)&udpServer, sizeof(udpServer)) == SOCKET_ERROR) { ReleasePRUDPSrcPort(m_srcPort); m_srcPort = 0; if (tries == 4) { cemuLog_log(LogType::Force, "PRUDP: Failed to bind UDP socket"); m_currentConnectionState = ConnectionState::Disconnected; return; } closesocket(m_socketUdp); continue; } else break; } // set socket to non-blocking mode #if BOOST_OS_WINDOWS u_long nonBlockingMode = 1; // 1 to enable non-blocking socket ioctlsocket(m_socketUdp, FIONBIO, &nonBlockingMode); #else int flags = fcntl(m_socketUdp, F_GETFL); fcntl(m_socketUdp, F_SETFL, flags | O_NONBLOCK); #endif // generate frequently used parameters m_srcVPort = PRUDP_VPORT(prudpPacket::STREAM_TYPE_SECURE, 0xF); m_dstVPort = PRUDP_VPORT(prudpPacket::STREAM_TYPE_SECURE, 0x1); // set stream settings uint8 checksumBase = 0; for (sint32 i = 0; key[i] != '\0'; i++) { checksumBase += key[i]; } m_streamSettings.checksumBase = checksumBase; MD5_CTX md5Ctx; MD5_Init(&md5Ctx); MD5_Update(&md5Ctx, key, (int)strlen(key)); MD5_Final(m_streamSettings.accessKeyDigest, &md5Ctx); // init stream ciphers RC4_initCtx(&m_streamSettings.rc4Server, "CD&ML"); RC4_initCtx(&m_streamSettings.rc4Client, "CD&ML"); // send syn packet SendCurrentHandshakePacket(); // set incoming sequence id to 1 m_incomingSequenceId = 1; } prudpClient::prudpClient(uint32 dstIp, uint16 dstPort, const char* key, prudpAuthServerInfo* authInfo) : prudpClient(dstIp, dstPort, key) { RC4_initCtx(&m_streamSettings.rc4Server, authInfo->secureKey, 16); RC4_initCtx(&m_streamSettings.rc4Client, authInfo->secureKey, 16); m_isSecureConnection = true; memcpy(&m_authInfo, authInfo, sizeof(prudpAuthServerInfo)); } prudpClient::~prudpClient() { if (m_srcPort != 0) { ReleasePRUDPSrcPort(m_srcPort); closesocket(m_socketUdp); } } void prudpClient::AcknowledgePacket(uint16 sequenceId) { auto it = std::begin(m_dataPacketsWithAckReq); while (it != std::end(m_dataPacketsWithAckReq)) { if (it->packet->GetSequenceId() == sequenceId) { delete it->packet; m_dataPacketsWithAckReq.erase(it); return; } it++; } } void prudpClient::SortIncomingDataPacket(std::unique_ptr<prudpIncomingPacket> incomingPacket) { uint16 sequenceIdIncomingPacket = incomingPacket->sequenceId; // find insert index sint32 insertIndex = 0; while (insertIndex < m_incomingPacketQueue.size()) { uint16 seqDif = sequenceIdIncomingPacket - m_incomingPacketQueue[insertIndex]->sequenceId; if (seqDif & 0x8000) break; // negative seqDif -> insert before current element #ifdef CEMU_DEBUG_ASSERT if (seqDif == 0) assert_dbg(); // same sequence id, sort by fragment index? #endif insertIndex++; } m_incomingPacketQueue.insert(m_incomingPacketQueue.begin() + insertIndex, std::move(incomingPacket)); // debug check if packets are really ordered by sequence id #ifdef CEMU_DEBUG_ASSERT for (sint32 i = 1; i < m_incomingPacketQueue.size(); i++) { uint16 seqDif = m_incomingPacketQueue[i]->sequenceId - m_incomingPacketQueue[i - 1]->sequenceId; if (seqDif & 0x8000) seqDif = -seqDif; if (seqDif >= 0x8000) assert_dbg(); } #endif } sint32 prudpClient::KerberosEncryptData(uint8* input, sint32 length, uint8* output) { RC4Ctx rc4Kerberos; RC4_initCtx(&rc4Kerberos, m_authInfo.secureKey, 16); memcpy(output, input, length); RC4_transform(&rc4Kerberos, output, length, output); // calculate and append hmac hmacMD5(this->m_authInfo.secureKey, 16, output, length, output + length); return length + 16; } // (re)sends either CON or SYN based on what stage of the login we are at // the sequenceId for both is hardcoded for both because we'll never send anything in between void prudpClient::SendCurrentHandshakePacket() { if (!m_hasSynAck) { // send syn (with a fixed sequenceId of 0) prudpPacket synPacket(&m_streamSettings, m_srcVPort, m_dstVPort, prudpPacket::TYPE_SYN, prudpPacket::FLAG_NEED_ACK, 0, 0, 0); DirectSendPacket(&synPacket); } else { // send con (with a fixed sequenceId of 1) prudpPacket conPacket(&m_streamSettings, m_srcVPort, m_dstVPort, prudpPacket::TYPE_CON, prudpPacket::FLAG_NEED_ACK | prudpPacket::FLAG_RELIABLE, this->m_clientSessionId, 1, m_serverConnectionSignature); if (this->m_isSecureConnection) { uint8 tempBuffer[512]; nexPacketBuffer conData(tempBuffer, sizeof(tempBuffer), true); conData.writeU32(m_clientConnectionSignature); conData.writeBuffer(m_authInfo.secureTicket, m_authInfo.secureTicketLength); // encrypted request data uint8 requestData[4 * 3]; uint8 requestDataEncrypted[4 * 3 + 0x10]; *(uint32*)(requestData + 0x0) = m_authInfo.userPid; *(uint32*)(requestData + 0x4) = m_authInfo.server.cid; *(uint32*)(requestData + 0x8) = prudp_generateRandomU32(); // todo - check value sint32 encryptedSize = KerberosEncryptData(requestData, sizeof(requestData), requestDataEncrypted); conData.writeBuffer(requestDataEncrypted, encryptedSize); conPacket.setData(conData.getDataPtr(), conData.getWriteIndex()); } else { conPacket.setData((uint8*)&m_clientConnectionSignature, sizeof(uint32)); } DirectSendPacket(&conPacket); } m_lastHandshakeTimestamp = prudpGetMSTimestamp(); m_handshakeRetryCount++; } void prudpClient::HandleIncomingPacket(std::unique_ptr<prudpIncomingPacket> incomingPacket) { if (incomingPacket->type == prudpPacket::TYPE_PING) { if (incomingPacket->flags & prudpPacket::FLAG_ACK) { // ack for our ping packet if (incomingPacket->flags & prudpPacket::FLAG_NEED_ACK) cemuLog_log(LogType::PRUDP, "[PRUDP] Received unexpected ping packet with both ACK and NEED_ACK set"); if (m_unacknowledgedPingCount > 0) { if (incomingPacket->sequenceId == m_outgoingSequenceId_ping) { cemuLog_log(LogType::PRUDP, "[PRUDP] Received ping packet ACK (unacknowledged count: {})", m_unacknowledgedPingCount); m_unacknowledgedPingCount = 0; } else { cemuLog_log(LogType::PRUDP, "[PRUDP] Received ping packet ACK with wrong sequenceId (expected: {}, received: {})", m_outgoingSequenceId_ping, incomingPacket->sequenceId); } } else { cemuLog_log(LogType::PRUDP, "[PRUDP] Received ping packet ACK which we dont need"); } } else if (incomingPacket->flags & prudpPacket::FLAG_NEED_ACK) { // other side is asking for ping ack cemuLog_log(LogType::PRUDP, "[PRUDP] Received ping packet with NEED_ACK set. Sending ACK back"); prudpPacket ackPacket(&m_streamSettings, m_srcVPort, m_dstVPort, prudpPacket::TYPE_PING, prudpPacket::FLAG_ACK, this->m_clientSessionId, incomingPacket->sequenceId, 0); if(!incomingPacket->packetData.empty()) ackPacket.setData(incomingPacket->packetData.data(), incomingPacket->packetData.size()); DirectSendPacket(&ackPacket); } return; } else if (incomingPacket->type == prudpPacket::TYPE_SYN) { // syn packet from server is expected to have ACK set if (!(incomingPacket->flags & prudpPacket::FLAG_ACK)) { cemuLog_log(LogType::Force, "[PRUDP] Received SYN packet without ACK flag set"); // always log this return; } if (m_hasSynAck || !incomingPacket->hasData || incomingPacket->packetData.size() != 4) { // syn already acked or not a valid syn packet cemuLog_log(LogType::PRUDP, "[PRUDP] Received unexpected SYN packet"); return; } m_hasSynAck = true; this->m_serverConnectionSignature = *(uint32*)&incomingPacket->packetData.front(); // generate client session id and connection signature this->m_clientSessionId = prudp_generateRandomU8(); this->m_clientConnectionSignature = prudp_generateRandomU32(); // send con packet m_handshakeRetryCount = 0; SendCurrentHandshakePacket(); return; } else if (incomingPacket->type == prudpPacket::TYPE_CON) { if (!m_hasSynAck || m_hasConAck) { cemuLog_log(LogType::PRUDP, "[PRUDP] Received unexpected CON packet"); return; } // make sure the packet has the ACK flag set if (!(incomingPacket->flags & prudpPacket::FLAG_ACK)) { cemuLog_log(LogType::Force, "[PRUDP] Received CON packet without ACK flag set"); return; } m_hasConAck = true; m_handshakeRetryCount = 0; cemu_assert_debug(m_currentConnectionState == ConnectionState::Connecting); // connected! m_lastPingTimestamp = prudpGetMSTimestamp(); cemu_assert_debug(m_serverSessionId == 0); m_serverSessionId = incomingPacket->sessionId; m_currentConnectionState = ConnectionState::Connected; cemuLog_log(LogType::PRUDP, "[PRUDP] Connection established. ClientSession {:02x} ServerSession {:02x}", m_clientSessionId, m_serverSessionId); return; } else if (incomingPacket->type == prudpPacket::TYPE_DATA) { // handle ACK if (incomingPacket->flags & prudpPacket::FLAG_ACK) { AcknowledgePacket(incomingPacket->sequenceId); if(!incomingPacket->packetData.empty()) cemuLog_log(LogType::PRUDP, "[PRUDP] Received ACK data packet with payload"); return; } // send ack back if requested if (incomingPacket->flags & prudpPacket::FLAG_NEED_ACK) { prudpPacket ackPacket(&m_streamSettings, m_srcVPort, m_dstVPort, prudpPacket::TYPE_DATA, prudpPacket::FLAG_ACK, this->m_clientSessionId, incomingPacket->sequenceId, 0); DirectSendPacket(&ackPacket); } // skip data packets without payload if (incomingPacket->packetData.empty()) return; // verify sequence id uint16 seqDist = incomingPacket->sequenceId - m_incomingSequenceId; if (seqDist >= 0xC000) { // outdated return; } // check if packet is already queued for (auto& it : m_incomingPacketQueue) { if (it->sequenceId == incomingPacket->sequenceId) { // already queued (should check other values too, like packet type?) cemuLog_log(LogType::PRUDP, "Duplicate PRUDP packet received"); return; } } // put into ordered receive queue SortIncomingDataPacket(std::move(incomingPacket)); } else if (incomingPacket->type == prudpPacket::TYPE_DISCONNECT) { m_currentConnectionState = ConnectionState::Disconnected; return; } else { cemuLog_log(LogType::PRUDP, "[PRUDP] Received unknown packet type"); } } bool prudpClient::Update() { if (m_currentConnectionState == ConnectionState::Disconnected) return false; uint32 currentTimestamp = prudpGetMSTimestamp(); // check for incoming packets uint8 receiveBuffer[4096]; while (true) { sockaddr receiveFrom = {0}; socklen_t receiveFromLen = sizeof(receiveFrom); sint32 r = recvfrom(m_socketUdp, (char*)receiveBuffer, sizeof(receiveBuffer), 0, &receiveFrom, &receiveFromLen); if (r >= 0) { // todo: Verify sender (receiveFrom) // calculate packet size sint32 pIdx = 0; while (pIdx < r) { sint32 packetLength = prudpPacket::calculateSizeFromPacketData(receiveBuffer + pIdx, r - pIdx); if (packetLength <= 0 || (pIdx + packetLength) > r) { cemuLog_log(LogType::Force, "[PRUDP] Invalid packet length"); break; } auto incomingPacket = std::make_unique<prudpIncomingPacket>(&m_streamSettings, receiveBuffer + pIdx, packetLength); pIdx += packetLength; if (incomingPacket->hasError()) { cemuLog_log(LogType::Force, "[PRUDP] Packet error"); break; } if (incomingPacket->type != prudpPacket::TYPE_CON && incomingPacket->sessionId != m_serverSessionId) { cemuLog_log(LogType::PRUDP, "[PRUDP] Invalid session id"); continue; // different session } HandleIncomingPacket(std::move(incomingPacket)); } } else break; } // check for ack timeouts for (auto& it : m_dataPacketsWithAckReq) { if ((currentTimestamp - it.lastRetryTimestamp) >= 2300) { if (it.retryCount >= 7) { // after too many retries consider the connection dead m_currentConnectionState = ConnectionState::Disconnected; } // resend DirectSendPacket(it.packet); it.lastRetryTimestamp = currentTimestamp; it.retryCount++; } } if (m_currentConnectionState == ConnectionState::Connecting) { // check if we need to resend SYN or CON uint32 timeSinceLastHandshake = currentTimestamp - m_lastHandshakeTimestamp; if (timeSinceLastHandshake >= 1200) { if (m_handshakeRetryCount >= 5) { // too many retries, assume the other side doesn't listen m_currentConnectionState = ConnectionState::Disconnected; cemuLog_log(LogType::PRUDP, "PRUDP: Failed to connect"); return false; } SendCurrentHandshakePacket(); } } else if (m_currentConnectionState == ConnectionState::Connected) { // handle pings if (m_unacknowledgedPingCount != 0) // counts how many times we sent a ping packet (for the current sequenceId) without receiving an ack { // we are waiting for the ack of the previous ping, but it hasn't arrived yet so send another ping packet if ((currentTimestamp - m_lastPingTimestamp) >= 1500) { cemuLog_log(LogType::PRUDP, "[PRUDP] Resending ping packet (no ack received)"); if (m_unacknowledgedPingCount >= 10) { // too many unacknowledged pings, assume the connection is dead m_currentConnectionState = ConnectionState::Disconnected; cemuLog_log(LogType::PRUDP, "PRUDP: Connection did not receive a ping response in a while. Assuming disconnect"); return false; } // resend the ping packet prudpPacket pingPacket(&m_streamSettings, m_srcVPort, m_dstVPort, prudpPacket::TYPE_PING, prudpPacket::FLAG_NEED_ACK, this->m_clientSessionId, this->m_outgoingSequenceId_ping, m_serverConnectionSignature); DirectSendPacket(&pingPacket); m_unacknowledgedPingCount++; m_lastPingTimestamp = currentTimestamp; } } else { if ((currentTimestamp - m_lastPingTimestamp) >= 20000) { cemuLog_log(LogType::PRUDP, "[PRUDP] Sending new ping packet with sequenceId {}", this->m_outgoingSequenceId_ping + 1); // start a new ping packet with a new sequenceId. Note that ping packets have their own sequenceId and acknowledgement happens by manually comparing the incoming ping ACK against the last sent sequenceId // only one unacknowledged ping packet can be in flight at a time. We will resend the same ping packet until we receive an ack m_outgoingSequenceId_ping++; // increment before sending. The first ping has a sequenceId of 1 prudpPacket pingPacket(&m_streamSettings, m_srcVPort, m_dstVPort, prudpPacket::TYPE_PING, prudpPacket::FLAG_NEED_ACK, this->m_clientSessionId, this->m_outgoingSequenceId_ping, m_serverConnectionSignature); DirectSendPacket(&pingPacket); m_unacknowledgedPingCount++; m_lastPingTimestamp = currentTimestamp; } } } return false; } void prudpClient::DirectSendPacket(prudpPacket* packet) { uint8 packetBuffer[prudpPacket::PACKET_RAW_SIZE_MAX]; sint32 len = packet->buildData(packetBuffer, prudpPacket::PACKET_RAW_SIZE_MAX); sockaddr_in destAddr; destAddr.sin_family = AF_INET; destAddr.sin_port = htons(m_dstPort); destAddr.sin_addr.s_addr = m_dstIp; sendto(m_socketUdp, (const char*)packetBuffer, len, 0, (const sockaddr*)&destAddr, sizeof(destAddr)); } void prudpClient::QueuePacket(prudpPacket* packet) { cemu_assert_debug(packet->GetType() == prudpPacket::TYPE_DATA); // only data packets should be queued if (packet->requiresAck()) { // remember this packet until we receive the ack m_dataPacketsWithAckReq.emplace_back(packet, prudpGetMSTimestamp()); DirectSendPacket(packet); } else { DirectSendPacket(packet); delete packet; } } void prudpClient::SendDatagram(uint8* input, sint32 length, bool reliable) { cemu_assert_debug(reliable); // non-reliable packets require correct sequenceId handling and testing cemu_assert_debug(m_hasSynAck && m_hasConAck); // cant send data packets before we are connected if (length >= 0x300) { cemuLog_logOnce(LogType::Force, "PRUDP: Datagram too long. Fragmentation not implemented yet"); } // single fragment data packet uint16 flags = prudpPacket::FLAG_NEED_ACK; if (reliable) flags |= prudpPacket::FLAG_RELIABLE; prudpPacket* packet = new prudpPacket(&m_streamSettings, m_srcVPort, m_dstVPort, prudpPacket::TYPE_DATA, flags, m_clientSessionId, m_outgoingReliableSequenceId, 0); if (reliable) m_outgoingReliableSequenceId++; packet->setFragmentIndex(0); packet->setData(input, length); QueuePacket(packet); } sint32 prudpClient::ReceiveDatagram(std::vector<uint8>& outputBuffer) { outputBuffer.clear(); if (m_incomingPacketQueue.empty()) return -1; prudpIncomingPacket* frontPacket = m_incomingPacketQueue[0].get(); if (frontPacket->sequenceId != this->m_incomingSequenceId) return -1; if (frontPacket->fragmentIndex == 0) { // single-fragment packet // decrypt frontPacket->decrypt(); // read data if (!frontPacket->packetData.empty()) { // to conserve memory we will also shrink the buffer if it was previously extended beyond 32KB constexpr size_t BUFFER_TARGET_SIZE = 1024 * 32; if (frontPacket->packetData.size() < BUFFER_TARGET_SIZE && outputBuffer.capacity() > BUFFER_TARGET_SIZE) { outputBuffer.resize(BUFFER_TARGET_SIZE); outputBuffer.shrink_to_fit(); outputBuffer.clear(); } // write packet data to output buffer cemu_assert_debug(outputBuffer.empty()); outputBuffer.insert(outputBuffer.end(), frontPacket->packetData.begin(), frontPacket->packetData.end()); } m_incomingPacketQueue.erase(m_incomingPacketQueue.begin()); // advance expected sequence id this->m_incomingSequenceId++; return (sint32)outputBuffer.size(); } else { // multi-fragment packet if (frontPacket->fragmentIndex != 1) return -1; // first packet of the chain not received yet // verify chain sint32 packetIndex = 1; sint32 chainLength = -1; // if full chain found, set to count of packets for (sint32 i = 1; i < m_incomingPacketQueue.size(); i++) { uint8 itFragmentIndex = m_incomingPacketQueue[packetIndex]->fragmentIndex; // sequence id must increase by 1 for every packet if (m_incomingPacketQueue[packetIndex]->sequenceId != (m_incomingSequenceId + i)) return -1; // missing packets // last fragment in chain is marked by fragment index 0 if (itFragmentIndex == 0) { chainLength = i + 1; break; } packetIndex++; } if (chainLength < 1) return -1; // chain not complete // extract data from packet chain cemu_assert_debug(outputBuffer.empty()); for (sint32 i = 0; i < chainLength; i++) { prudpIncomingPacket* incomingPacket = m_incomingPacketQueue[i].get(); incomingPacket->decrypt(); outputBuffer.insert(outputBuffer.end(), incomingPacket->packetData.begin(), incomingPacket->packetData.end()); } // remove packets from queue m_incomingPacketQueue.erase(m_incomingPacketQueue.begin(), m_incomingPacketQueue.begin() + chainLength); m_incomingSequenceId += chainLength; return (sint32)outputBuffer.size(); } return -1; }
31,586
C++
.cpp
969
29.872033
209
0.722764
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,946
nexFriends.cpp
cemu-project_Cemu/src/Cemu/nex/nexFriends.cpp
#include "prudp.h" #include "nex.h" #include "nexFriends.h" #include "Cafe/CafeSystem.h" static const int NOTIFICATION_SRV_FRIEND_OFFLINE = 0x0A; // the opposite event (friend online) is notified via _PRESENCE_CHANGE static const int NOTIFICATION_SRV_FRIEND_PRESENCE_CHANGE = 0x18; static const int NOTIFICATION_SRV_FRIEND_REMOVED = 0x1A; // also used to indicate that an incoming friend request was canceled static const int NOTIFICATION_SRV_FRIEND_REQUEST_INCOMING = 0x1B; // someone sent a friend request to us static const int NOTIFICATION_SRV_FRIEND_ADDED = 0x1E; // not sent when friend request is accepted locally void NexFriends::processServerNotification_friendOffline(uint32 pid) { std::unique_lock listLock(mtx_lists); for (auto& it : list_friends) { if (it.nnaInfo.principalInfo.principalId == pid) { it.presence.isOnline = 0; generateNotification(NOTIFICATION_TYPE_FRIEND_LOGOFF, pid); return; } } } void NexFriends::processServerNotification_presenceChange(uint32 pid, nexPresenceV2& presence) { std::unique_lock listLock(mtx_lists); for (auto& it : list_friends) { if (it.nnaInfo.principalInfo.principalId == pid) { bool isOnlineChange = (presence.isOnline != it.presence.isOnline); it.presence = presence; if (isOnlineChange) generateNotification((presence.isOnline!=0)?NOTIFICATION_TYPE_FRIEND_LOGIN:NOTIFICATION_TYPE_FRIEND_LOGOFF, pid); generateNotification(NOTIFICATION_TYPE_FRIEND_PRESENCE_CHANGE, pid); return; } } } void NexFriends::processServerNotification_removeFriendOrFriendRequest(uint32 pid) { std::unique_lock listLock(mtx_lists); for (auto it = list_friends.begin(); it != list_friends.end();) { if (it->nnaInfo.principalInfo.principalId == pid) { list_friends.erase(it); generateNotification(NOTIFICATION_TYPE_REMOVED_FRIEND, pid); return; } it++; } for (auto it = list_friendReqIncoming.begin(); it != list_friendReqIncoming.end();) { if (it->principalInfo.principalId == pid) { list_friendReqIncoming.erase(it); generateNotification(NOTIFICATION_TYPE_REMOVED_INCOMING_REQUEST, pid); return; } it++; } } void NexFriends::processServerNotification_incomingFriendRequest(uint32 pid, nexFriendRequest& friendRequest) { std::unique_lock listLock(mtx_lists); // check for duplicate for (auto& it : list_friendReqIncoming) { if (it.principalInfo.principalId == pid) return; } // add friend request and send notification list_friendReqIncoming.push_back(friendRequest); generateNotification(NOTIFICATION_TYPE_ADDED_INCOMING_REQUEST, pid); } void NexFriends::processServerNotification_addedFriend(uint32 pid, nexFriend& frd) { std::unique_lock listLock(mtx_lists); // remove any related incoming friend request for (auto it = list_friendReqIncoming.begin(); it != list_friendReqIncoming.end();) { if (it->principalInfo.principalId == pid) { list_friendReqIncoming.erase(it); generateNotification(NOTIFICATION_TYPE_REMOVED_INCOMING_REQUEST, pid); break; } it++; } // remove any related outgoing friend request for (auto it = list_friendReqOutgoing.begin(); it != list_friendReqOutgoing.end();) { if (it->principalInfo.principalId == pid) { list_friendReqOutgoing.erase(it); generateNotification(NOTIFICATION_TYPE_REMOVED_OUTGOING_REQUEST, pid); break; } it++; } // check for duplicate for (auto& it : list_friendReqIncoming) { if (it.principalInfo.principalId == pid) return; } // add friend list_friends.push_back(frd); generateNotification(NOTIFICATION_TYPE_ADDED_FRIEND, pid); } void NexFriends::processServerNotification(uint32 notificationType, uint32 pid, nexPacketBuffer* notificationData) { nexNotificationEventGeneral notificationGeneral; if (notificationType == NOTIFICATION_SRV_FRIEND_PRESENCE_CHANGE) { nexPresenceV2 presence; if (notificationData->readPlaceholderType(presence)) { this->processServerNotification_presenceChange(pid, presence); } } else if (notificationType == 0x21) { // change comment text if (notificationData->readPlaceholderType(notificationGeneral)) { // todo } } else if (notificationType == NOTIFICATION_SRV_FRIEND_OFFLINE) { // friend now offline if (notificationData->readPlaceholderType(notificationGeneral)) { this->processServerNotification_friendOffline(pid); } } else if (notificationType == NOTIFICATION_SRV_FRIEND_REMOVED) { // friend removed or friend-request removed if (notificationData->readPlaceholderType(notificationGeneral)) { this->processServerNotification_removeFriendOrFriendRequest(pid); } } else if (notificationType == NOTIFICATION_SRV_FRIEND_REQUEST_INCOMING) { nexFriendRequest friendRequest; if (notificationData->readPlaceholderType(friendRequest)) { this->processServerNotification_incomingFriendRequest(pid, friendRequest); } } else if (notificationType == NOTIFICATION_SRV_FRIEND_ADDED) { nexFriend frd; if (notificationData->readPlaceholderType(frd)) { this->processServerNotification_addedFriend(pid, frd); } } else if (true) { cemuLog_logDebug(LogType::Force, "Unsupported friend server notification type 0x{:02x}", notificationType); } } void nexFriends_protocolNotification_processRequest(nexServiceRequest_t* request) { NexFriends* nexFriends = (NexFriends*)request->custom; if (request->methodId == 0x1 || request->methodId == 0x2) { // notification uint32 notificationType = request->data.readU32(); uint32 pid = request->data.readU32(); if (request->data.hasReadOutOfBounds()) { request->nex->sendRequestResponse(request, 0, nullptr, 0); return; } cemuLog_logDebug(LogType::Force, "NN_NOTIFICATION methodId {} type {:02x} pid {:08x}", request->methodId, notificationType, pid); nexFriends->processServerNotification(notificationType, pid, &request->data); request->nex->sendRequestResponse(request, 0, nullptr, 0); return; } // unknown method request->nex->sendRequestResponse(request, 0x80000000, nullptr, 0); } NexFriends::NexFriends(uint32 authServerIp, uint16 authServerPort, const char* accessKey, uint32 pid, const char* nexPassword, const char* nexToken, const char* nnid, uint8* miiData, const wchar_t* miiNickname, uint8 countryCode, nexPresenceV2& myPresence) : nexCon(nullptr) { memcpy(this->miiData, miiData, FFL_SIZE); strcpy(this->nnid, nnid); this->pid = pid; this->countryCode = countryCode; this->myPresence = myPresence; this->miiNickname = boost::nowide::narrow(miiNickname); cemu_assert_debug(this->miiNickname.size() <= 96-1); auth.serverIp = authServerIp; auth.port = authServerPort; auth.accessKey = std::string(accessKey); auth.nexPassword = std::string(nexPassword); auth.nexToken = std::string(nexToken); // login related variables this->lastLoginAttemptTime = prudpGetMSTimestamp() - 1000*60*60; this->isCurrentlyConnected = false; this->hasData = false; this->loginInProcess = false; this->numFailedLogins = 0; this->numSuccessfulLogins = 0; } NexFriends::~NexFriends() { if(nexCon) nexCon->destroy(); } void NexFriends::doAsyncLogin() { nexCon = nex_establishSecureConnection(auth.serverIp, auth.port, auth.accessKey.c_str(), pid, auth.nexPassword.c_str(), auth.nexToken.c_str()); if (nexCon == nullptr) { this->numFailedLogins++; this->loginInProcess = false; return; } nexCon->registerProtocolRequestHandler(0x64, nexFriends_protocolNotification_processRequest, this); nexCon->registerForAsyncProcessing(); this->isCurrentlyConnected = true; this->firstInformationRequest = true; this->loginInProcess = false; this->numSuccessfulLogins++; requestGetAllInformation(); } void NexFriends::initiateLogin() { if (this->isCurrentlyConnected) return; if (this->loginInProcess) return; std::unique_lock loginLock(mtx_login); this->loginInProcess = true; // reset all data std::unique_lock listLock(mtx_lists); list_friends.resize(0); list_friendReqIncoming.resize(0); list_friendReqOutgoing.resize(0); previousState.list_friends.resize(0); previousState.list_friendReqIncoming.resize(0); previousState.list_friendReqOutgoing.resize(0); this->hasData = false; // start login attempt cemuLog_logDebug(LogType::Force, "Attempt to log into friend server..."); std::thread t(&NexFriends::doAsyncLogin, this); t.detach(); } void NexFriends::handleResponse_getAllInformation(nexServiceResponse_t* response, NexFriends* nexFriends, std::function<void(uint32)> cb) { if (response->isSuccessful == false) { if (cb) cb(ERR_RPC_FAILED); return; } NexFriends* session = (NexFriends*)nexFriends; session->myPreference = nexPrincipalPreference(&response->data); auto comment = nexComment(&response->data); session->myComment = comment; if (response->data.hasReadOutOfBounds()) return; // acquire lock on lists std::unique_lock listLock(session->mtx_lists); // remember current state of lists for change tracking session->previousState.list_friends = session->list_friends; session->previousState.list_friendReqIncoming = session->list_friendReqIncoming; session->previousState.list_friendReqOutgoing = session->list_friendReqOutgoing; // parse response and update lists // friends uint32 friendCount = response->data.readU32(); session->list_friends.resize(friendCount); for (uint32 i = 0; i < friendCount; i++) session->list_friends[i].readData(&response->data); // friend requests (outgoing) uint32 friendRequestsOutCount = response->data.readU32(); if (response->data.hasReadOutOfBounds()) return; session->list_friendReqOutgoing.resize(friendRequestsOutCount); for (uint32 i = 0; i < friendRequestsOutCount; i++) session->list_friendReqOutgoing[i].readData(&response->data); // friend requests (incoming) uint32 friendRequestsInCount = response->data.readU32(); if (response->data.hasReadOutOfBounds()) return; session->list_friendReqIncoming.resize(friendRequestsInCount); for (uint32 i = 0; i < friendRequestsInCount; i++) session->list_friendReqIncoming[i].readData(&response->data); if (response->data.hasReadOutOfBounds()) return; // blacklist uint32 blacklistCount = response->data.readU32(); for (uint32 i = 0; i < blacklistCount; i++) { nexBlacklisted blacklisted(&response->data); } // ukn uint8 uknSetting = response->data.readU8(); // ? (usually zero) // persistent notifications uint32 perstNotificationCount = response->data.readU32(); for (uint32 i = 0; i < perstNotificationCount; i++) { nexPersistentNotification notification(&response->data); //printf("--- Notification ---\n"); //printf("ID %016llx pid1 %08x pid2 %08x type %08x\n", notification.messageId, notification.pid1, notification.pid2, notification.type); //printf("Msg %s\n", notification.msg.c_str()); } uint8 isPreferenceInvalid = response->data.readU8(); // if not zero, preferences must be setup if (isPreferenceInvalid) { cemuLog_log(LogType::Force, "NEX: First time login into friend account, setting up default preferences"); session->updatePreferencesAsync(nexPrincipalPreference(1, 1, 0), [](RpcErrorCode err){}); } if (session->firstInformationRequest == false) session->trackNotifications(); else { // first request after login -> send online notification session->generateNotification(NOTIFICATION_TYPE_ONLINE, session->pid); } session->firstInformationRequest = false; session->hasData = true; if (cb) cb(ERR_NONE); } bool NexFriends::requestGetAllInformation() { uint8 tempNexBufferArray[1024]; nexPacketBuffer packetBuffer(tempNexBufferArray, sizeof(tempNexBufferArray), true); nexNNAInfo(this->countryCode, 0, nexPrincipalBasicInfo(pid, nnid, nexMiiV2(miiNickname.c_str(), miiData))).writeData(&packetBuffer); myPresence.writeData(&packetBuffer); packetBuffer.writeU64(0x1f18420000); // birthday (set to 1990-1-1) nexCon->callMethod(NEX_PROTOCOL_FRIENDS_WIIU, 1, &packetBuffer, std::bind(handleResponse_getAllInformation, std::placeholders::_1, this, nullptr), true); return true; } bool NexFriends::requestGetAllInformation(std::function<void(uint32)> cb) { uint8 tempNexBufferArray[1024]; nexPacketBuffer packetBuffer(tempNexBufferArray, sizeof(tempNexBufferArray), true); nexNNAInfo(this->countryCode, 0, nexPrincipalBasicInfo(pid, nnid, nexMiiV2(miiNickname.c_str(), miiData))).writeData(&packetBuffer); nexPresenceV2(0).writeData(&packetBuffer); packetBuffer.writeU64(0x1f18420000); // birthday (set to 1990-1-1) nexCon->callMethod(NEX_PROTOCOL_FRIENDS_WIIU, 1, &packetBuffer, std::bind(handleResponse_getAllInformation, std::placeholders::_1, this, cb), true); return true; } bool NexFriends::updatePreferencesAsync(nexPrincipalPreference newPreferences, std::function<void(RpcErrorCode)> cb) { uint8 tempNexBufferArray[1024]; nexPacketBuffer packetBuffer(tempNexBufferArray, sizeof(tempNexBufferArray), true); newPreferences.writeData(&packetBuffer); nexCon->callMethod(NEX_PROTOCOL_FRIENDS_WIIU, 16, &packetBuffer, [this, cb, newPreferences](nexServiceResponse_t* response) -> void { if (!response->isSuccessful) return cb(NexFriends::ERR_RPC_FAILED); this->myPreference = newPreferences; return cb(NexFriends::ERR_NONE); }, true); // TEST return true; } void NexFriends::getMyPreference(nexPrincipalPreference& preference) { preference = myPreference; } bool NexFriends::updateCommentAsync(nexComment newComment, std::function<void(RpcErrorCode)> cb) { uint8 tempNexBufferArray[1024]; nexPacketBuffer packetBuffer(tempNexBufferArray, sizeof(tempNexBufferArray), true); newComment.writeData(&packetBuffer); nexCon->callMethod( NEX_PROTOCOL_FRIENDS_WIIU, 15, &packetBuffer, [this, cb, newComment](nexServiceResponse_t* response) -> void { if (!response->isSuccessful) return cb(NexFriends::ERR_RPC_FAILED); this->myComment = newComment; return cb(NexFriends::ERR_NONE); }, true); // TEST return true; } void NexFriends::getMyComment(nexComment& comment) { comment = myComment; } bool NexFriends::addProvisionalFriendByPidGuessed(uint32 principalId) { uint8 tempNexBufferArray[512]; nexPacketBuffer packetBuffer(tempNexBufferArray, sizeof(tempNexBufferArray), true); packetBuffer.writeU32(principalId); cemu_assert_unimplemented(); //nexCon->callMethod(NEX_PROTOCOL_FRIENDS_WIIU, 2, &packetBuffer, handleResponse_test, this); return true; } // returns true once connection is established and friend list data is available bool NexFriends::isOnline() { return isCurrentlyConnected && hasData; } void NexFriends::handleResponse_acceptFriendRequest(nexService* nex, nexServiceResponse_t* response) { NexFriends* session = (NexFriends*)response->custom; // returns new state of FriendRequest + FriendInfo (if friend request holds no valid data, it means the friend request was successfully accepted?) } void NexFriends::setNotificationHandler(void(*notificationHandler)(NOTIFICATION_TYPE notificationType, uint32 pid)) { this->notificationHandler = notificationHandler; } void NexFriends::generateNotification(NOTIFICATION_TYPE notificationType, uint32 pid) { if (this->notificationHandler == nullptr) return; this->notificationHandler(notificationType, pid); } // compare previous and current state of friend(-request) lists and generate change-notifications void NexFriends::trackNotifications() { // search for changed and added friend entries for (auto& frNew : list_friends) { bool entryFound = false; for (auto& frPrevious : previousState.list_friends) { if (frNew.nnaInfo.principalInfo.principalId == frPrevious.nnaInfo.principalInfo.principalId) { // todo - scan for changes entryFound = true; break; } } if (entryFound == false) { // friend added generateNotification(NOTIFICATION_TYPE_ADDED_FRIEND, frNew.nnaInfo.principalInfo.principalId); } } // search for removed friends for (auto& frPrevious : previousState.list_friends) { bool entryFound = false; for (auto& frNew : list_friends) { if (frNew.nnaInfo.principalInfo.principalId == frPrevious.nnaInfo.principalInfo.principalId) { entryFound = true; break; } } if (entryFound == false) { // friend removed generateNotification(NOTIFICATION_TYPE_REMOVED_FRIEND, frPrevious.nnaInfo.principalInfo.principalId); } } // search for added friend requests (incoming) for (auto& frqNew : list_friendReqIncoming) { bool entryFound = false; for (auto& frqPrevious : previousState.list_friendReqIncoming) { if (frqNew.principalInfo.principalId == frqPrevious.principalInfo.principalId) { entryFound = true; break; } } if (entryFound == false) { // incoming friend request added generateNotification(NOTIFICATION_TYPE_ADDED_INCOMING_REQUEST, frqNew.principalInfo.principalId); } } // search for removed friend requests (incoming) for (auto& frqPrevious : previousState.list_friendReqIncoming) { bool entryFound = false; for (auto& frqNew : list_friendReqIncoming) { if (frqNew.principalInfo.principalId == frqPrevious.principalInfo.principalId) { entryFound = true; break; } } if (entryFound == false) { // incoming friend request removed generateNotification(NOTIFICATION_TYPE_REMOVED_INCOMING_REQUEST, frqPrevious.principalInfo.principalId); } } // search for added friend requests (outgoing) for (auto& frqNew : list_friendReqOutgoing) { bool entryFound = false; for (auto& frqPrevious : previousState.list_friendReqOutgoing) { if (frqNew.principalInfo.principalId == frqPrevious.principalInfo.principalId) { entryFound = true; break; } } if (entryFound == false) { // outgoing friend request added generateNotification(NOTIFICATION_TYPE_ADDED_OUTGOING_REQUEST, frqNew.principalInfo.principalId); } } // search for removed friend requests (outgoing) for (auto& frqPrevious : previousState.list_friendReqOutgoing) { bool entryFound = false; for (auto& frqNew : list_friendReqOutgoing) { if (frqNew.principalInfo.principalId == frqPrevious.principalInfo.principalId) { entryFound = true; break; } } if (entryFound == false) { // outgoing friend request removed generateNotification(NOTIFICATION_TYPE_REMOVED_OUTGOING_REQUEST, frqPrevious.principalInfo.principalId); } } } void addUniquePidToList(std::vector<uint32>& pidList, uint32 pid) { bool alreadyAdded = false; for (auto& it2 : pidList) { if (it2 == pid) { alreadyAdded = true; break; } } if (alreadyAdded) return; pidList.push_back(pid); } void NexFriends::getFriendPIDs(uint32* pidList, uint32* pidCount, sint32 offset, sint32 count, bool includeFriendRequests) { if (count < 0) { *pidCount = 0; return; } // parse response and update lists std::vector<uint32> allPids; std::unique_lock listLock(this->mtx_lists); for (auto& it : this->list_friends) { uint32 pid = it.nnaInfo.principalInfo.principalId; addUniquePidToList(allPids, pid); } if (includeFriendRequests) { // incoming friend requests are not included for (auto& it : this->list_friendReqOutgoing) { uint32 pid = it.principalInfo.principalId; addUniquePidToList(allPids, pid); } } sint32 copyCount = std::max((sint32)allPids.size() - offset, 0); copyCount = std::min(copyCount, count); if (pidList) { for (sint32 i = 0; i < copyCount; i++) pidList[i] = allPids[offset + i]; } *pidCount = copyCount; } void NexFriends::getFriendRequestPIDs(uint32* pidList, uint32* pidCount, sint32 offset, sint32 count, bool includeIncoming, bool includeOutgoing) { if (count < 0) { *pidCount = 0; return; } // parse response and update lists std::vector<uint32> allPids; std::unique_lock listLock(this->mtx_lists); if (includeIncoming) { for (auto& it : this->list_friendReqIncoming) { uint32 pid = it.principalInfo.principalId; addUniquePidToList(allPids, pid); } } if (includeOutgoing) { for (auto& it : this->list_friendReqOutgoing) { uint32 pid = it.principalInfo.principalId; addUniquePidToList(allPids, pid); } } sint32 copyCount = std::max((sint32)allPids.size() - offset, 0); copyCount = std::min(copyCount, count); if (pidList) { for (sint32 i = 0; i < copyCount; i++) pidList[i] = allPids[offset + i]; } *pidCount = copyCount; } std::string NexFriends::getAccountNameByPid(uint32 principalId) { if (this->pid == principalId) return this->nnid; nexFriend friendData{}; if(getFriendByPID(friendData, principalId)) return friendData.nnaInfo.principalInfo.nnid; nexFriendRequest requestData{}; if (getFriendRequestByPID(requestData, nullptr, principalId)) return requestData.principalInfo.nnid; return {}; } int NexFriends::getPendingFriendRequestCount() { std::unique_lock listLock(this->mtx_lists); return (int)this->list_friendReqIncoming.size(); } bool NexFriends::getFriendByPID(nexFriend& friendData, uint32 searchedPid) { std::unique_lock listLock(this->mtx_lists); for (auto& it : this->list_friends) { uint32 pid = it.nnaInfo.principalInfo.principalId; if (pid == searchedPid) { friendData = it; return true; } } return false; } bool NexFriends::getFriendRequestByPID(nexFriendRequest& friendRequestData, bool* isIncoming, uint32 searchedPid) { std::unique_lock listLock(this->mtx_lists); for (auto& it : this->list_friendReqIncoming) { uint32 pid = it.principalInfo.principalId; if (pid == searchedPid) { friendRequestData = it; if(isIncoming) *isIncoming = true; return true; } } for (auto& it : this->list_friendReqOutgoing) { uint32 pid = it.principalInfo.principalId; if (pid == searchedPid) { friendRequestData = it; if (isIncoming) *isIncoming = false; return true; } } return false; } bool NexFriends::getFriendRequestByMessageId(nexFriendRequest& friendRequestData, bool* isIncoming, uint64 messageId) { std::unique_lock listLock(this->mtx_lists); for (auto& it : this->list_friendReqIncoming) { uint64 mid = it.message.messageId; if(mid == 0) continue; if (mid == messageId) { friendRequestData = it; *isIncoming = true; return true; } } for (auto& it : this->list_friendReqOutgoing) { uint64 mid = it.message.messageId; if (mid == 0) continue; if (mid == messageId) { friendRequestData = it; *isIncoming = false; return true; } } return false; } void addProvisionalFriendHandler(nexServiceResponse_t* nexResponse, std::function<void(uint32)> cb) { if (nexResponse->isSuccessful) cb(0); else { // todo: Properly handle returned error code and data cb(NexFriends::ERR_RPC_FAILED); } } bool NexFriends::addProvisionalFriend(char* name, std::function<void(RpcErrorCode)> cb) { if (nexCon == nullptr || nexCon->getState() != nexService::STATE_CONNECTED) { // not connected cb(ERR_NOT_CONNECTED); return false; } uint8 tempNexBufferArray[128]; nexPacketBuffer packetBuffer(tempNexBufferArray, sizeof(tempNexBufferArray), true); packetBuffer.writeString(name); nexCon->callMethod(NEX_PROTOCOL_FRIENDS_WIIU, 3, &packetBuffer, std::bind(addProvisionalFriendHandler, std::placeholders::_1, cb), true); return true; } void addFriendRequestHandler(nexServiceResponse_t* nexResponse, NexFriends* nexFriends, std::function<void(uint32)> cb) { if (nexResponse->isSuccessful) cb(0); else { // todo: Properly handle returned error code cb(NexFriends::ERR_RPC_FAILED); nexFriends->requestGetAllInformation(); // refresh friend list and send add/remove notifications } } void NexFriends::addFriendRequest(uint32 pid, const char* comment, std::function<void(RpcErrorCode)> cb) { if (nexCon == nullptr || nexCon->getState() != nexService::STATE_CONNECTED) { // not connected cb(ERR_NOT_CONNECTED); return; } uint8 tempNexBufferArray[2048]; nexPacketBuffer packetBuffer(tempNexBufferArray, sizeof(tempNexBufferArray), true); packetBuffer.writeU32(pid); packetBuffer.writeU8(0); // ukn (language of comment?) packetBuffer.writeString(comment); packetBuffer.writeU8(0); // ukn (language of next string?) packetBuffer.writeString(""); // ukn nexGameKey(0, 0).writeData(&packetBuffer); packetBuffer.writeU64(0); // ukn nexCon->callMethod(NEX_PROTOCOL_FRIENDS_WIIU, 5, &packetBuffer, std::bind(addFriendRequestHandler, std::placeholders::_1, this, cb), true); } void NexFriends::requestPrincipleBaseInfoByPID(uint32* pidList, sint32 count, const std::function<void(RpcErrorCode result, std::span<nexPrincipalBasicInfo> basicInfo)>& cb) { if (nexCon == nullptr || nexCon->getState() != nexService::STATE_CONNECTED) return cb(ERR_NOT_CONNECTED, {}); uint8 tempNexBufferArray[512]; nexPacketBuffer packetBuffer(tempNexBufferArray, sizeof(tempNexBufferArray), true); packetBuffer.writeU32(count); for(sint32 i=0; i<count; i++) packetBuffer.writeU32(pidList[i]); nexCon->callMethod(NEX_PROTOCOL_FRIENDS_WIIU, 17, &packetBuffer, [cb, count](nexServiceResponse_t* response) { if (!response->isSuccessful) return cb(NexFriends::ERR_RPC_FAILED, {}); // process result uint32 resultCount = response->data.readU32(); if (resultCount != count) return cb(NexFriends::ERR_UNEXPECTED_RESULT, {}); std::vector<nexPrincipalBasicInfo> nexBasicInfo; nexBasicInfo.resize(count); for (uint32 i = 0; i < resultCount; i++) nexBasicInfo[i].readData(&response->data); if (response->data.hasReadOutOfBounds()) return cb(NexFriends::ERR_UNEXPECTED_RESULT, {}); return cb(NexFriends::ERR_NONE, nexBasicInfo); }, true); } void genericFriendServiceNoResponseHandler(nexServiceResponse_t* nexResponse, std::function<void(uint32)> cb) { if (nexResponse->isSuccessful) cb(0); else { // todo: Properly handle returned error code cb(NexFriends::ERR_RPC_FAILED); } } void NexFriends::removeFriend(uint32 pid, std::function<void(RpcErrorCode)> cb) { if (nexCon == nullptr || nexCon->getState() != nexService::STATE_CONNECTED) { // not connected cb(ERR_NOT_CONNECTED); return; } uint8 tempNexBufferArray[512]; nexPacketBuffer packetBuffer(tempNexBufferArray, sizeof(tempNexBufferArray), true); packetBuffer.writeU32(pid); nexCon->callMethod(NEX_PROTOCOL_FRIENDS_WIIU, 4, &packetBuffer, [this, cb](nexServiceResponse_t* response) -> void { if (!response->isSuccessful) return cb(NexFriends::ERR_RPC_FAILED); else { cb(NexFriends::ERR_NONE); this->requestGetAllInformation(); // refresh friend list and send add/remove notifications return; } }, true); } void NexFriends::cancelOutgoingProvisionalFriendRequest(uint32 pid, std::function<void(RpcErrorCode)> cb) { if (nexCon == nullptr || nexCon->getState() != nexService::STATE_CONNECTED) { // not connected cb(ERR_NOT_CONNECTED); return; } uint8 tempNexBufferArray[512]; nexPacketBuffer packetBuffer(tempNexBufferArray, sizeof(tempNexBufferArray), true); packetBuffer.writeU32(pid); nexCon->callMethod(NEX_PROTOCOL_FRIENDS_WIIU, 4, &packetBuffer, [cb](nexServiceResponse_t* response) -> void { if (!response->isSuccessful) return cb(NexFriends::ERR_RPC_FAILED); else return cb(NexFriends::ERR_NONE); }, true); } void NexFriends::acceptFriendRequest(uint64 messageId, std::function<void(RpcErrorCode)> cb) { if (nexCon == nullptr || nexCon->getState() != nexService::STATE_CONNECTED) return cb(ERR_NOT_CONNECTED); uint8 tempNexBufferArray[128]; nexPacketBuffer packetBuffer(tempNexBufferArray, sizeof(tempNexBufferArray), true); packetBuffer.writeU64(messageId); nexCon->callMethod(NEX_PROTOCOL_FRIENDS_WIIU, 7, &packetBuffer, [cb](nexServiceResponse_t* response) -> void { if (!response->isSuccessful) return cb(NexFriends::ERR_RPC_FAILED); else return cb(NexFriends::ERR_NONE); }, true); } void NexFriends::deleteFriendRequest(uint64 messageId, std::function<void(RpcErrorCode)> cb) { if (nexCon == nullptr || nexCon->getState() != nexService::STATE_CONNECTED) return cb(ERR_NOT_CONNECTED); uint8 tempNexBufferArray[128]; nexPacketBuffer packetBuffer(tempNexBufferArray, sizeof(tempNexBufferArray), true); packetBuffer.writeU64(messageId); nexCon->callMethod(NEX_PROTOCOL_FRIENDS_WIIU, 8, &packetBuffer, [this, cb](nexServiceResponse_t* response) -> void { if (!response->isSuccessful) return cb(NexFriends::ERR_RPC_FAILED); cb(NexFriends::ERR_NONE); this->requestGetAllInformation(); // refresh friend list and send add/remove notifications }, true); } void NexFriends::markFriendRequestsAsReceived(uint64* messageIdList, sint32 count, std::function<void(RpcErrorCode)> cb) { if (nexCon == nullptr || nexCon->getState() != nexService::STATE_CONNECTED) return cb(ERR_NOT_CONNECTED); uint8 tempNexBufferArray[1024]; nexPacketBuffer packetBuffer(tempNexBufferArray, sizeof(tempNexBufferArray), true); packetBuffer.writeU32(count); for(sint32 i=0; i<count; i++) packetBuffer.writeU64(messageIdList[i]); nexCon->callMethod(NEX_PROTOCOL_FRIENDS_WIIU, 10, &packetBuffer, [cb](nexServiceResponse_t* response) -> void { if (!response->isSuccessful) return cb(NexFriends::ERR_RPC_FAILED); else return cb(NexFriends::ERR_NONE); }, true); } void NexFriends::updateMyPresence(nexPresenceV2& myPresence) { this->myPresence = myPresence; if (GetTitleIdHigh(CafeSystem::GetForegroundTitleId()) == 0x00050000) { myPresence.gameKey.titleId = CafeSystem::GetForegroundTitleId(); myPresence.gameKey.ukn = CafeSystem::GetForegroundTitleVersion(); } else { myPresence.gameKey.titleId = 0; // icon will not be ??? or invalid to others myPresence.gameKey.ukn = 0; } if (nexCon == nullptr || nexCon->getState() != nexService::STATE_CONNECTED) { // not connected return; } uint8 tempNexBufferArray[1024]; nexPacketBuffer packetBuffer(tempNexBufferArray, sizeof(tempNexBufferArray), true); myPresence.writeData(&packetBuffer); nexCon->callMethod(NEX_PROTOCOL_FRIENDS_WIIU, 13, &packetBuffer, +[](nexServiceResponse_t* nexResponse){}, false); } void NexFriends::update() { std::unique_lock loginLock(mtx_login); if (!isCurrentlyConnected) { if (loginInProcess) { // wait for login attempt to finish } else { // should we try to reconnect? uint32 timeSinceLastLoginAttempt = prudpGetMSTimestamp() - this->lastLoginAttemptTime; uint32 delayTime = 30; // 30 seconds by default if (this->numFailedLogins < 3) delayTime = 30; else { if (this->numSuccessfulLogins == 0) return; // never try again if (this->numFailedLogins >= 10) return; // stop after 10 failed attempts delayTime = 60 + (this->numFailedLogins - 3) * 60; // add one minute each time it fails } if (timeSinceLastLoginAttempt < delayTime) return; cemuLog_log(LogType::Force, "NEX: Attempt async friend service login"); initiateLogin(); } } else { if (this->nexCon == nullptr || this->nexCon->getState() != nexService::STATE_CONNECTED) { cemuLog_log(LogType::Force, "NEX: Lost friend server session"); if (this->nexCon) { this->nexCon->destroy(); this->nexCon = nullptr; } isCurrentlyConnected = false; } } }
30,997
C++
.cpp
948
30.133966
256
0.759887
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,947
DiscordPresence.cpp
cemu-project_Cemu/src/Cemu/DiscordPresence/DiscordPresence.cpp
#include "DiscordPresence.h" #ifdef ENABLE_DISCORD_RPC #include <discord_rpc.h> #include "Common/version.h" DiscordPresence::DiscordPresence() { DiscordEventHandlers handlers{}; Discord_Initialize("460807638964371468", &handlers, 1, nullptr); UpdatePresence(Idling); } DiscordPresence::~DiscordPresence() { ClearPresence(); Discord_Shutdown(); } void DiscordPresence::UpdatePresence(State state, const std::string& text) const { DiscordRichPresence discord_presence{}; std::string state_string, details_string; switch (state) { case Idling: details_string = "Idling"; break; case Playing: details_string = "Ingame"; state_string = "Playing " + text; break; default: assert(false); break; } discord_presence.details = details_string.c_str(); discord_presence.state = state_string.c_str(); discord_presence.startTimestamp = time(nullptr); discord_presence.largeImageText = BUILD_VERSION_WITH_NAME_STRING; discord_presence.largeImageKey = "logo_icon_big_png"; Discord_UpdatePresence(&discord_presence); } void DiscordPresence::ClearPresence() const { Discord_ClearPresence(); } #endif
1,124
C++
.cpp
44
23.590909
80
0.780784
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,948
ExpressionParser.cpp
cemu-project_Cemu/src/Cemu/ExpressionParser/ExpressionParser.cpp
#include "ExpressionParser.h" template<typename T, typename TInternalType = double> T _testEvaluateToType(const char* expr) { TExpressionParser<TInternalType> ep; T result = (T)ep.Evaluate(expr); return result; } void ExpressionParser_test() { ExpressionParser ep; cemu_assert_debug(_testEvaluateToType<sint64>("0x100005E0") == 0x100005E0); cemu_assert_debug(_testEvaluateToType<uint64>("0x10+0x20+0x40") == 0x70); cemu_assert_debug(_testEvaluateToType<sint64>("0+-3") == -3); cemu_assert_debug(_testEvaluateToType<sint64>("0x0-3") == -3); cemu_assert_debug(_testEvaluateToType<sint64>("01C+0x10") == 0x2C); cemu_assert_debug(_testEvaluateToType<sint64>("+0x10") == 0x10); cemu_assert_debug(_testEvaluateToType<sint64>("01C++0x10") == 0x2C); cemu_assert_debug(_testEvaluateToType<sint64>("01C+(+0x10)") == 0x2C); // arithmetic cemu_assert_debug(_testEvaluateToType<sint64>("(62156250 / 1000) * 30") == 1864687); // truncated 1864687.5 // arithmetic with internal type sint64 cemu_assert_debug(_testEvaluateToType<sint64, sint64>("(62156250 / 1000) * 30") == 1864680); // comparison operators cemu_assert_debug(_testEvaluateToType<sint64>("5 > 3") == 0x1); cemu_assert_debug(_testEvaluateToType<sint64>("5 < -10") == 0x0); cemu_assert_debug(_testEvaluateToType<float>("5 > 3") == 1.0f); cemu_assert_debug(_testEvaluateToType<float>("-5 > 3") == 0.0f); cemu_assert_debug(_testEvaluateToType<float>("5 < 10") == 1.0f); cemu_assert_debug(_testEvaluateToType<float>("5 <= 5") == 1.0f); cemu_assert_debug(_testEvaluateToType<float>("5 <= 4.999") == 0.0f); cemu_assert_debug(_testEvaluateToType<float>("5 <= (4+0.999)") == 0.0f); cemu_assert_debug(_testEvaluateToType<float>("5 >= 3") == 1.0f); cemu_assert_debug(_testEvaluateToType<float>("5 >= 10") == 0.0f); cemu_assert_debug(_testEvaluateToType<float>("10 >= 5") == 1.0f); // complex operations cemu_assert_debug(_testEvaluateToType<float>("5 > 4 > 3 > 2") == 0.0f); // this should evaluate the operations from left to right, (5 > 4) -> 0.0, (0.0 > 4) -> 0.0, (0.0 > 3) -> 0.0, (0.0 > 2) -> 0.0 cemu_assert_debug(_testEvaluateToType<float>("5 > 4 > 3 > -2") == 1.0f); // this should evaluate the operations from left to right, (5 > 4) -> 0.0, (0.0 > 4) -> 0.0, (0.0 > 3) -> 0.0, (0.0 > -2) -> 1.0 cemu_assert_debug(_testEvaluateToType<float>("(5 == 5) > (5 == 6)") == 1.0f); }
2,361
C++
.cpp
40
57.1
202
0.680915
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,949
CemuLogging.cpp
cemu-project_Cemu/src/Cemu/Logging/CemuLogging.cpp
#include "CemuLogging.h" #include "gui/LoggingWindow.h" #include "util/helpers/helpers.h" #include "config/CemuConfig.h" #include "config/ActiveSettings.h" #include <mutex> #include <condition_variable> #include <chrono> #include <fmt/printf.h> uint64 s_loggingFlagMask = cemuLog_getFlag(LogType::Force); struct _LogContext { std::condition_variable_any log_condition; std::recursive_mutex log_mutex; std::ofstream file_stream; std::vector<std::string> text_cache; std::thread log_writer; std::atomic<bool> threadRunning = false; ~_LogContext() { // safely shut down the log writer thread threadRunning.store(false); if (log_writer.joinable()) { log_condition.notify_one(); log_writer.join(); } } }LogContext; const std::map<LogType, std::string> g_logging_window_mapping { {LogType::UnsupportedAPI, "Unsupported API calls"}, {LogType::APIErrors, "Invalid API usage"}, {LogType::CoreinitLogging, "Coreinit Logging"}, {LogType::CoreinitFile, "Coreinit File-Access"}, {LogType::CoreinitThreadSync, "Coreinit Thread-Synchronization"}, {LogType::CoreinitMem, "Coreinit Memory"}, {LogType::CoreinitMP, "Coreinit MP"}, {LogType::CoreinitThread, "Coreinit Thread"}, {LogType::NN_NFP, "nn::nfp"}, {LogType::NN_FP, "nn::fp"}, {LogType::NN_BOSS, "nn::boss"}, {LogType::GX2, "GX2"}, {LogType::SoundAPI, "Audio"}, {LogType::InputAPI, "Input"}, {LogType::Socket, "Socket"}, {LogType::Save, "Save"}, {LogType::H264, "H264"}, {LogType::NFC, "NFC"}, {LogType::NTAG, "NTAG"}, {LogType::Patches, "Graphic pack patches"}, {LogType::TextureCache, "Texture cache"}, {LogType::TextureReadback, "Texture readback"}, {LogType::OpenGLLogging, "OpenGL debug output"}, {LogType::VulkanValidation, "Vulkan validation layer"}, }; bool cemuLog_advancedPPCLoggingEnabled() { return GetConfig().advanced_ppc_logging; } void cemuLog_thread() { SetThreadName("cemuLog_thread"); while (true) { std::unique_lock lock(LogContext.log_mutex); while (LogContext.text_cache.empty()) { LogContext.log_condition.wait(lock); if (!LogContext.threadRunning.load(std::memory_order::relaxed)) return; } std::vector<std::string> cache_copy; cache_copy.swap(LogContext.text_cache); // fast copy & clear lock.unlock(); for (const auto& entry : cache_copy) LogContext.file_stream.write(entry.data(), entry.size()); LogContext.file_stream.flush(); } } fs::path cemuLog_GetLogFilePath() { return ActiveSettings::GetUserDataPath("log.txt"); } void cemuLog_createLogFile(bool triggeredByCrash) { std::unique_lock lock(LogContext.log_mutex); if (LogContext.file_stream.is_open()) return; const auto path = cemuLog_GetLogFilePath(); LogContext.file_stream.open(path, std::ios::out); if (LogContext.file_stream.fail()) { cemu_assert_debug(false); return; } LogContext.threadRunning.store(true); LogContext.log_writer = std::thread(cemuLog_thread); lock.unlock(); } void cemuLog_writeLineToLog(std::string_view text, bool date, bool new_line) { std::unique_lock lock(LogContext.log_mutex); if (date) { const auto now = std::chrono::system_clock::now(); const auto temp_time = std::chrono::system_clock::to_time_t(now); const auto& time = *std::localtime(&temp_time); auto time_str = fmt::format("[{:02d}:{:02d}:{:02d}.{:03d}] ", time.tm_hour, time.tm_min, time.tm_sec, std::chrono::duration_cast<std::chrono::milliseconds>(now - std::chrono::time_point_cast<std::chrono::seconds>(now)).count()); LogContext.text_cache.emplace_back(std::move(time_str)); } LogContext.text_cache.emplace_back(text); if (new_line) LogContext.text_cache.emplace_back("\n"); lock.unlock(); LogContext.log_condition.notify_one(); } bool cemuLog_log(LogType type, std::string_view text) { if (!cemuLog_isLoggingEnabled(type)) return false; cemuLog_writeLineToLog(text); const auto it = std::find_if(g_logging_window_mapping.cbegin(), g_logging_window_mapping.cend(), [type](const auto& entry) { return entry.first == type; }); if (it == g_logging_window_mapping.cend()) LoggingWindow::Log(text); else LoggingWindow::Log(it->second, text); return true; } bool cemuLog_log(LogType type, std::u8string_view text) { std::basic_string_view<char> s((char*)text.data(), text.size()); return cemuLog_log(type, s); } void cemuLog_waitForFlush() { cemuLog_createLogFile(false); std::unique_lock lock(LogContext.log_mutex); while(!LogContext.text_cache.empty()) { lock.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(1)); std::this_thread::yield(); lock.lock(); } } // used to atomically write multiple lines to the log std::unique_lock<decltype(LogContext.log_mutex)> cemuLog_acquire() { return std::unique_lock(LogContext.log_mutex); } void cemuLog_setActiveLoggingFlags(uint64 flagMask) { s_loggingFlagMask = flagMask | cemuLog_getFlag(LogType::Force); }
5,072
C++
.cpp
157
30.095541
129
0.703173
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,950
XAudio2API.cpp
cemu-project_Cemu/src/audio/XAudio2API.cpp
//#if (_WIN32_WINNT >= 0x0602 /*_WIN32_WINNT_WIN8*/) #include <xaudio2.h> #ifndef XAUDIO2_DLL #error wrong <xaudio2.h> included! #endif #include "XAudio2API.h" #include "util/helpers/helpers.h" #include <WbemCli.h> #include <OleAuto.h> #include <system_error> // guid from mmdeviceapi.h static const GUID DEVINTERFACE_AUDIO_RENDER_GUID = { 0xe6327cad, 0xdcec, 0x4949, 0xae, 0x8a, 0x99, 0x1e, 0x97, 0x6a, 0x79, 0xd2 }; #pragma comment(lib, "wbemuuid.lib") static_assert(IAudioAPI::kBlockCount < XAUDIO2_MAX_QUEUED_BUFFERS, "too many xaudio2 buffers"); HMODULE XAudio2API::s_xaudio_dll = nullptr; std::vector<XAudio2API::DeviceDescriptionPtr> XAudio2API::s_devices; XAudio2API::XAudio2API(std::wstring device_id, uint32 samplerate, uint32 channels, uint32 samples_per_block, uint32 bits_per_sample) : IAudioAPI(samplerate, channels, samples_per_block, bits_per_sample), m_device_id(std::move(device_id)) { const auto _XAudio2Create = (decltype(&XAudio2Create))GetProcAddress(s_xaudio_dll, "XAudio2Create"); if (!_XAudio2Create) throw std::runtime_error("can't find XAudio2Create import"); HRESULT hres; IXAudio2* xaudio; if (FAILED((hres = _XAudio2Create(&xaudio, 0, XAUDIO2_DEFAULT_PROCESSOR)))) throw std::runtime_error(fmt::format("can't create xaudio device (hres: {:#x})", hres)); m_xaudio = decltype(m_xaudio)(xaudio); IXAudio2MasteringVoice* mastering_voice; if (FAILED((hres = m_xaudio->CreateMasteringVoice(&mastering_voice, channels, samplerate, 0, m_device_id.empty() ? nullptr : m_device_id.c_str())))) throw std::runtime_error(fmt::format("can't create xaudio mastering voice (hres: {:#x})", hres)); m_mastering_voice = decltype(m_mastering_voice)(mastering_voice); m_wfx.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; m_wfx.Format.nChannels = channels; m_wfx.Format.nSamplesPerSec = samplerate; m_wfx.Format.wBitsPerSample = bits_per_sample; m_wfx.Format.nBlockAlign = (m_wfx.Format.nChannels * m_wfx.Format.wBitsPerSample) / 8; // must equal (nChannels × wBitsPerSample) / 8 m_wfx.Format.nAvgBytesPerSec = m_wfx.Format.nSamplesPerSec * m_wfx.Format.nBlockAlign; // must equal nSamplesPerSec × nBlockAlign. m_wfx.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX); m_wfx.SubFormat = KSDATAFORMAT_SUBTYPE_PCM; m_wfx.Samples.wValidBitsPerSample = bits_per_sample; switch(channels) { case 8: m_wfx.dwChannelMask |= (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_FRONT_LEFT_OF_CENTER | SPEAKER_FRONT_RIGHT_OF_CENTER); break; case 6: m_wfx.dwChannelMask |= (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT); break; case 4: m_wfx.dwChannelMask |= (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT); break; case 2: m_wfx.dwChannelMask |= (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT); break; default: m_wfx.dwChannelMask = 0; break; } IXAudio2SourceVoice* source_voice; if (FAILED((hres = m_xaudio->CreateSourceVoice(&source_voice, &m_wfx.Format, 0, 1.0f)))) throw std::runtime_error(fmt::format("can't create xaudio source voice (hres: {:#x})", hres)); m_source_voice = decltype(m_source_voice)(source_voice); m_sound_buffer_size = kBlockCount * (samples_per_block * channels * (bits_per_sample / 8)); for (uint32 i = 0; i < kBlockCount; ++i) m_audio_buffer[i] = std::make_unique<uint8[]>(m_bytesPerBlock); m_xaudio->StartEngine(); } void XAudio2API::XAudioDeleter::operator()(IXAudio2* ptr) const { if (ptr) ptr->Release(); } void XAudio2API::VoiceDeleter::operator()(IXAudio2Voice* ptr) const { if (ptr) ptr->DestroyVoice(); } XAudio2API::~XAudio2API() { if(m_xaudio) m_xaudio->StopEngine(); XAudio2API::Stop(); m_source_voice.reset(); m_mastering_voice.reset(); m_xaudio.reset(); } void XAudio2API::SetVolume(sint32 volume) { IAudioAPI::SetVolume(volume); m_mastering_voice->SetVolume((float)volume / 100.0f); } bool XAudio2API::Play() { if (m_playing) return true; m_playing = SUCCEEDED(m_source_voice->Start()); return m_playing; } bool XAudio2API::Stop() { if (!m_playing) return true; m_playing = FAILED(m_source_voice->Stop()); m_source_voice->FlushSourceBuffers(); return m_playing; } bool XAudio2API::InitializeStatic() { if (s_xaudio_dll) return true; // win 10 s_xaudio_dll = LoadLibraryEx(XAUDIO2_DLL, nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); try { if (!s_xaudio_dll) throw std::exception(); const auto _XAudio2Create = (decltype(&XAudio2Create))GetProcAddress(s_xaudio_dll, "XAudio2Create"); if (!_XAudio2Create) throw std::exception(); RefreshDevices(); return true; } catch (const std::exception&) { if (s_xaudio_dll) FreeLibrary(s_xaudio_dll); return false; } } void XAudio2API::Destroy() { if (s_xaudio_dll) FreeLibrary(s_xaudio_dll); } const std::vector<XAudio2API::DeviceDescriptionPtr>& XAudio2API::RefreshDevices() { s_devices.clear(); try { struct IWbemLocator *wbem_locator = nullptr; HRESULT hres = CoCreateInstance(__uuidof(WbemLocator), nullptr, CLSCTX_INPROC_SERVER, __uuidof(IWbemLocator), (LPVOID*)&wbem_locator); if (FAILED(hres) || !wbem_locator) throw std::system_error(hres, std::system_category()); std::shared_ptr<OLECHAR> path(SysAllocString(LR"(\\.\root\cimv2)"), SysFreeString); std::shared_ptr<OLECHAR> language(SysAllocString(L"WQL"), SysFreeString); std::shared_ptr<OLECHAR> query(SysAllocString(LR"(SELECT Name,DeviceID FROM Win32_PNPEntity WHERE PNPClass = "AudioEndpoint")"), SysFreeString); std::shared_ptr<OLECHAR> name_row(SysAllocString(L"Name"), SysFreeString); std::shared_ptr<OLECHAR> device_id_row(SysAllocString(L"DeviceID"), SysFreeString); IWbemServices *wbem_services = nullptr; hres = wbem_locator->ConnectServer(path.get(), nullptr, nullptr, nullptr, 0, nullptr, nullptr, &wbem_services); wbem_locator->Release(); // Free memory resources. if (FAILED(hres) || !wbem_services) throw std::system_error(hres, std::system_category()); hres = CoSetProxyBlanket(wbem_services, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, nullptr, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, nullptr, EOAC_NONE); if (FAILED(hres)) throw std::system_error(hres, std::system_category()); IEnumWbemClassObject* wbem_enum = nullptr; hres = wbem_services->ExecQuery(language.get(), query.get(), WBEM_FLAG_RETURN_WBEM_COMPLETE | WBEM_FLAG_FORWARD_ONLY, nullptr, &wbem_enum); if (FAILED(hres) || !wbem_enum) throw std::system_error(hres, std::system_category()); ULONG returned; IWbemClassObject* object[20]; // WBEM_S_TIMEDOUT while (SUCCEEDED(hres = wbem_enum->Next(100, 20, object, &returned)) && returned > 0) { for (ULONG i = 0; i < returned; ++i) { std::wstring name, device_id; VARIANT var; if (SUCCEEDED(object[i]->Get(name_row.get(), 0L, &var, NULL, NULL)) && var.vt == VT_BSTR && var.bstrVal) { name = var.bstrVal; if (SUCCEEDED(object[i]->Get(device_id_row.get(), 0L, &var, NULL, NULL)) && var.vt == VT_BSTR && var.bstrVal) { std::wstring id = var.bstrVal; if(id.find(L"{0.0.0.00000000}") == std::wstring::npos) { object[i]->Release(); continue; } std::replace(id.begin(), id.end(), L'\\', L'#'); // xaudio devices have "#" instead of backslashes std::wstringstream tmp; tmp << L"\\\\?\\" << id << L"#{" << WStringFromGUID(DEVINTERFACE_AUDIO_RENDER_GUID) << L"}"; device_id = tmp.str(); } } auto device = std::make_shared<XAudio2DeviceDescription>(name,device_id); s_devices.emplace_back(device); object[i]->Release(); } } // Only add default device if audio devices exist if (s_devices.size() > 0) { auto default_device = std::make_shared<XAudio2DeviceDescription>(L"Primary Sound Driver", L""); s_devices.insert(s_devices.begin(), default_device); } wbem_enum->Release(); // Clean up wbem_services->Release(); } catch (const std::system_error& ex) { cemuLog_log(LogType::Force, "XAudio2API::RefreshDevices: error while refreshing device list ({} - code: 0x{:08x})", ex.what(), ex.code().value()); } CoUninitialize(); return s_devices; } bool XAudio2API::FeedBlock(sint16* data) { // check if we queued too many blocks if (m_blocks_queued >= kBlockCount) { XAUDIO2_VOICE_STATE state{}; m_source_voice->GetState(&state); m_blocks_queued = state.BuffersQueued; if (m_blocks_queued >= kBlockCount) { cemuLog_logDebug(LogType::Force, "dropped xaudio2 block since too many buffers are queued"); return false; } } memcpy(m_audio_buffer[m_offset].get(), data, m_bytesPerBlock); XAUDIO2_BUFFER buffer{}; buffer.AudioBytes = m_bytesPerBlock; buffer.pAudioData = m_audio_buffer[m_offset].get(); m_source_voice->SubmitSourceBuffer(&buffer); m_offset = (m_offset + 1) % kBlockCount; m_blocks_queued++; return true; } bool XAudio2API::NeedAdditionalBlocks() const { return m_blocks_queued < s_audioDelay; }
9,105
C++
.cpp
234
36.004274
219
0.720086
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,951
CubebAPI.cpp
cemu-project_Cemu/src/audio/CubebAPI.cpp
#include "CubebAPI.h" #if BOOST_OS_WINDOWS #include <combaseapi.h> #include <mmreg.h> #include <mmsystem.h> #pragma comment(lib, "Avrt.lib") #pragma comment(lib, "ksuser.lib") #endif static void state_cb(cubeb_stream* stream, void* user, cubeb_state state) { if (!stream) return; /*switch (state) { case CUBEB_STATE_STARTED: fprintf(stderr, "stream started\n"); break; case CUBEB_STATE_STOPPED: fprintf(stderr, "stream stopped\n"); break; case CUBEB_STATE_DRAINED: fprintf(stderr, "stream drained\n"); break; default: fprintf(stderr, "unknown stream state %d\n", state); }*/ } long CubebAPI::data_cb(cubeb_stream* stream, void* user, const void* inputbuffer, void* outputbuffer, long nframes) { auto* thisptr = (CubebAPI*)user; //const auto size = (size_t)thisptr->m_bytesPerBlock; // (size_t)nframes* thisptr->m_channels; // m_bytesPerBlock = samples_per_block * channels * (bits_per_sample / 8); const auto size = (size_t)nframes * thisptr->m_channels * (thisptr->m_bitsPerSample/8); std::unique_lock lock(thisptr->m_mutex); if (thisptr->m_buffer.empty()) { // we got no data, just write silence memset(outputbuffer, 0x00, size); } else { const auto copied = std::min(thisptr->m_buffer.size(), size); memcpy(outputbuffer, thisptr->m_buffer.data(), copied); thisptr->m_buffer.erase(thisptr->m_buffer.begin(), std::next(thisptr->m_buffer.begin(), copied)); lock.unlock(); // fill rest with silence if (copied != size) memset((uint8*)outputbuffer + copied, 0x00, size - copied); } return nframes; } CubebAPI::CubebAPI(cubeb_devid devid, uint32 samplerate, uint32 channels, uint32 samples_per_block, uint32 bits_per_sample) : IAudioAPI(samplerate, channels, samples_per_block, bits_per_sample) { cubeb_stream_params output_params; output_params.format = CUBEB_SAMPLE_S16LE; output_params.rate = samplerate; output_params.channels = channels; output_params.prefs = CUBEB_STREAM_PREF_NONE; switch (channels) { case 8: output_params.layout = CUBEB_LAYOUT_3F4_LFE; break; case 6: output_params.layout = CUBEB_LAYOUT_3F2_LFE_BACK; break; case 4: output_params.layout = CUBEB_LAYOUT_QUAD; break; case 2: output_params.layout = CUBEB_LAYOUT_STEREO; break; default: output_params.layout = CUBEB_LAYOUT_MONO; break; } uint32 latency = 1; cubeb_get_min_latency(s_context, &output_params, &latency); m_buffer.reserve((size_t)m_bytesPerBlock * kBlockCount); if (cubeb_stream_init(s_context, &m_stream, "Cemu Cubeb output", nullptr, nullptr, devid, &output_params, latency, data_cb, state_cb, this) != CUBEB_OK) { throw std::runtime_error("can't initialize cubeb device"); } } CubebAPI::~CubebAPI() { if (m_stream) { Stop(); cubeb_stream_destroy(m_stream); } } bool CubebAPI::NeedAdditionalBlocks() const { std::shared_lock lock(m_mutex); return m_buffer.size() < s_audioDelay * m_bytesPerBlock; } bool CubebAPI::FeedBlock(sint16* data) { std::unique_lock lock(m_mutex); if (m_buffer.capacity() <= m_buffer.size() + m_bytesPerBlock) { cemuLog_logDebug(LogType::Force, "dropped direct sound block since too many buffers are queued"); return false; } m_buffer.insert(m_buffer.end(), (uint8*)data, (uint8*)data + m_bytesPerBlock); return true; } bool CubebAPI::Play() { if (m_is_playing) return true; if (cubeb_stream_start(m_stream) == CUBEB_OK) { m_is_playing = true; return true; } return false; } bool CubebAPI::Stop() { if (!m_is_playing) return true; if (cubeb_stream_stop(m_stream) == CUBEB_OK) { m_is_playing = false; return true; } return false; } void CubebAPI::SetVolume(sint32 volume) { IAudioAPI::SetVolume(volume); cubeb_stream_set_volume(m_stream, (float)volume / 100.0f); } bool CubebAPI::InitializeStatic() { if (cubeb_init(&s_context, "Cemu Cubeb", nullptr)) { cemuLog_log(LogType::Force, "can't create cubeb audio api"); return false; } return true; } void CubebAPI::Destroy() { if (s_context) cubeb_destroy(s_context); } std::vector<IAudioAPI::DeviceDescriptionPtr> CubebAPI::GetDevices() { cubeb_device_collection devices; if (cubeb_enumerate_devices(s_context, CUBEB_DEVICE_TYPE_OUTPUT, &devices) != CUBEB_OK) return {}; std::vector<DeviceDescriptionPtr> result; result.reserve(devices.count + 1); // Reserve space for the default device // Add the default device to the list auto defaultDevice = std::make_shared<CubebDeviceDescription>(nullptr, "default", L"Default Device"); result.emplace_back(defaultDevice); for (size_t i = 0; i < devices.count; ++i) { // const auto& device = devices.device[i]; if (devices.device[i].state == CUBEB_DEVICE_STATE_ENABLED) { auto device = std::make_shared<CubebDeviceDescription>(devices.device[i].devid, devices.device[i].device_id, boost::nowide::widen( devices.device[i].friendly_name)); result.emplace_back(device); } } cubeb_device_collection_destroy(s_context, &devices); return result; }
5,077
C++
.cpp
178
25.61236
115
0.711614
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,952
IAudioInputAPI.cpp
cemu-project_Cemu/src/audio/IAudioInputAPI.cpp
#include "IAudioInputAPI.h" #if HAS_CUBEB #include "CubebInputAPI.h" #endif std::shared_mutex g_audioInputMutex; AudioInputAPIPtr g_inputAudio; std::array<bool, IAudioInputAPI::AudioInputAPIEnd> IAudioInputAPI::s_availableApis{}; IAudioInputAPI::IAudioInputAPI(uint32 samplerate, uint32 channels, uint32 samples_per_block, uint32 bits_per_sample) : m_samplerate(samplerate), m_channels(channels), m_samplesPerBlock(samples_per_block), m_bitsPerSample(bits_per_sample) { m_bytesPerBlock = samples_per_block * channels * (bits_per_sample / 8); } void IAudioInputAPI::PrintLogging() { cemuLog_log(LogType::Force, "------- Init Audio input backend -------"); cemuLog_log(LogType::Force, "Cubeb: {}", s_availableApis[Cubeb] ? "available" : "not supported"); } void IAudioInputAPI::InitializeStatic() { #if HAS_CUBEB s_availableApis[Cubeb] = CubebInputAPI::InitializeStatic(); #endif } bool IAudioInputAPI::IsAudioInputAPIAvailable(AudioInputAPI api) { if ((size_t)api < s_availableApis.size()) return s_availableApis[api]; cemu_assert_debug(false); return false; } AudioInputAPIPtr IAudioInputAPI::CreateDevice(AudioInputAPI api, const DeviceDescriptionPtr& device, sint32 samplerate, sint32 channels, sint32 samples_per_block, sint32 bits_per_sample) { if (!IsAudioInputAPIAvailable(api)) return {}; switch(api) { #if HAS_CUBEB case Cubeb: { const auto tmp = std::dynamic_pointer_cast<CubebInputAPI::CubebDeviceDescription>(device); return std::make_unique<CubebInputAPI>(tmp->GetDeviceId(), samplerate, channels, samples_per_block, bits_per_sample); } #endif default: throw std::runtime_error(fmt::format("invalid audio api: {}", api)); } } std::vector<IAudioInputAPI::DeviceDescriptionPtr> IAudioInputAPI::GetDevices(AudioInputAPI api) { if (!IsAudioInputAPIAvailable(api)) return {}; switch(api) { #if HAS_CUBEB case Cubeb: { return CubebInputAPI::GetDevices(); } #endif default: throw std::runtime_error(fmt::format("invalid audio api: {}", api)); } }
2,005
C++
.cpp
63
29.984127
186
0.770984
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,953
DirectSoundAPI.cpp
cemu-project_Cemu/src/audio/DirectSoundAPI.cpp
#include "DirectSoundAPI.h" #include "gui/wxgui.h" #include "util/helpers/helpers.h" #include "gui/guiWrapper.h" #pragma comment(lib, "Dsound.lib") std::wstring DirectSoundAPI::DirectSoundDeviceDescription::GetIdentifier() const { return m_guid ? WStringFromGUID(*m_guid) : L"default"; } DirectSoundAPI::DirectSoundAPI(GUID* guid, sint32 samplerate, sint32 channels, sint32 samples_per_block, sint32 bits_per_sample) : IAudioAPI(samplerate, channels, samples_per_block, bits_per_sample) { LPDIRECTSOUND8 direct_sound; if (DirectSoundCreate8(guid, &direct_sound, nullptr) != DS_OK) throw std::runtime_error("can't create directsound device"); m_direct_sound = decltype(m_direct_sound)(direct_sound); if (FAILED(m_direct_sound->SetCooperativeLevel(gui_getWindowInfo().window_main.hwnd, DSSCL_PRIORITY))) throw std::runtime_error("can't set directsound priority"); DSBUFFERDESC bd{}; bd.dwSize = sizeof(DSBUFFERDESC); bd.dwFlags = DSBCAPS_GETCURRENTPOSITION2 | DSBCAPS_CTRLVOLUME | DSBCAPS_GLOBALFOCUS | DSBCAPS_CTRLPOSITIONNOTIFY; bd.dwBufferBytes = kBufferCount * m_bytesPerBlock; // kBlockCount * (samples_per_block * channels * (bits_per_sample / 8)); bd.lpwfxFormat = (LPWAVEFORMATEX)&m_wfx; LPDIRECTSOUNDBUFFER sound_buffer; if (FAILED(m_direct_sound->CreateSoundBuffer(&bd, &sound_buffer, nullptr))) throw std::runtime_error("can't create directsound soundbuffer"); DSBCAPS caps{}; caps.dwSize = sizeof(DSBCAPS); if (FAILED(sound_buffer->GetCaps(&caps))) throw std::runtime_error("can't get directsound soundbuffer size"); m_sound_buffer_size = caps.dwBufferBytes; LPDIRECTSOUNDBUFFER8 sound_buffer8; LPDIRECTSOUNDNOTIFY8 notify8; sound_buffer->QueryInterface(IID_IDirectSoundBuffer8, (void**)&sound_buffer8); if (!sound_buffer8) { sound_buffer->Release(); throw std::runtime_error("can't get directsound buffer interface"); } m_sound_buffer = decltype(m_sound_buffer)(sound_buffer8); sound_buffer->QueryInterface(IID_IDirectSoundNotify8, (void**)&notify8); if (!notify8) { sound_buffer->Release(); throw std::runtime_error("can't get directsound notify interface"); } m_notify = decltype(m_notify)(notify8); sound_buffer->Release(); { // initialize sound buffer void *ptr1, *ptr2; DWORD bytes1, bytes2; m_sound_buffer->Lock(0, m_sound_buffer_size, &ptr1, &bytes1, &ptr2, &bytes2, 0); memset(ptr1, 0x00, bytes1); if (ptr2 && bytes2 > 0) memset(ptr2, 0x00, bytes2); m_sound_buffer->Unlock(ptr1, bytes1, ptr2, bytes2); } m_sound_buffer->SetCurrentPosition(0); DSBPOSITIONNOTIFY notify[kBufferCount]{}; for (size_t i = 0; i < kBufferCount; ++i) { m_notify_event[i] = CreateEvent(nullptr, FALSE, FALSE, nullptr); notify[i].hEventNotify = m_notify_event[i]; //notify[i].dwOffset = ((i*2) + 1) * (m_bytes_per_block / 2); notify[i].dwOffset = (i * m_bytesPerBlock); } if (FAILED(m_notify->SetNotificationPositions(kBufferCount, notify))) throw std::runtime_error("can't set directsound notify positions"); m_running = true; m_thread = std::thread(&DirectSoundAPI::AudioThread, this); #if BOOST_OS_WINDOWS SetThreadPriority(m_thread.native_handle(), THREAD_PRIORITY_TIME_CRITICAL); #endif } void DirectSoundAPI::AudioThread() { while (m_running) { HRESULT hr = WaitForMultipleObjects(m_notify_event.size(), m_notify_event.data(), FALSE, 10); if (WAIT_OBJECT_0 <= hr && hr <= WAIT_OBJECT_0 + kBufferCount) { // write to the following buffer const sint32 position = (hr - WAIT_OBJECT_0 + 1) % kBufferCount; void *ptr1, *ptr2; DWORD bytes1, bytes2; hr = m_sound_buffer->Lock(position * m_bytesPerBlock, m_bytesPerBlock, &ptr1, &bytes1, &ptr2, &bytes2, 0); if (hr == DSERR_BUFFERLOST) { m_sound_buffer->Restore(); hr = m_sound_buffer->Lock(position * m_bytesPerBlock, m_bytesPerBlock, &ptr1, &bytes1, &ptr2, &bytes2, 0); } if (FAILED(hr)) { cemuLog_log(LogType::Force, "DirectSound: Dropped audio block due to locking failure"); continue; } { std::unique_lock lock(m_mutex); if (m_buffer.empty()) { //cemuLog_logDebug(LogType::Force, "DirectSound: writing silence"); // we got no data, just write silence memset(ptr1, 0x00, bytes1); if (ptr2) memset(ptr2, 0x00, bytes2); } else { const auto& buffer = m_buffer.front(); memcpy(ptr1, buffer.get(), bytes1); if (ptr2) memcpy(ptr2, buffer.get() + bytes1, bytes2); m_buffer.pop(); } } m_sound_buffer->Unlock(ptr1, bytes1, ptr2, bytes2); } } } DirectSoundAPI::~DirectSoundAPI() { m_running = false; DirectSoundAPI::Stop(); if(m_thread.joinable()) m_thread.join(); m_notify.reset(); m_sound_buffer.reset(); m_direct_sound.reset(); for(auto entry : m_notify_event) { if (entry) CloseHandle(entry); } } bool DirectSoundAPI::Play() { if (m_playing) return true; m_playing = SUCCEEDED(m_sound_buffer->Play(0, 0, DSBPLAY_LOOPING)); return m_playing; } bool DirectSoundAPI::Stop() { if (!m_playing) return true; m_playing = FAILED(m_sound_buffer->Stop()); return m_playing; } bool DirectSoundAPI::FeedBlock(sint16* data) { std::unique_lock lock(m_mutex); if (m_buffer.size() > kBlockCount) { cemuLog_logDebug(LogType::Force, "dropped direct sound block since too many buffers are queued"); return false; } auto tmp = std::make_unique<uint8[]>(m_bytesPerBlock); memcpy(tmp.get(), data, m_bytesPerBlock); m_buffer.emplace(std::move(tmp)); return true; } void DirectSoundAPI::SetVolume(sint32 volume) { IAudioAPI::SetVolume(volume); const LONG value = pow((float)volume / 100.0f, 0.20f) * (DSBVOLUME_MAX - DSBVOLUME_MIN) + DSBVOLUME_MIN; m_sound_buffer->SetVolume(value); } bool DirectSoundAPI::NeedAdditionalBlocks() const { std::shared_lock lock(m_mutex); return m_buffer.size() < s_audioDelay; } std::vector<DirectSoundAPI::DeviceDescriptionPtr> DirectSoundAPI::GetDevices() { std::vector<DeviceDescriptionPtr> result; DirectSoundEnumerateW( [](LPGUID lpGuid, LPCWSTR lpcstrDescription, LPCWSTR lpcstrModule, LPVOID lpContext) -> BOOL { auto results = (std::vector<DeviceDescriptionPtr>*)lpContext; auto obj = std::make_shared<DirectSoundDeviceDescription>(lpcstrDescription, lpGuid); results->emplace_back(obj); return TRUE; }, &result); //Exclude default primary sound device if no other sound devices are available if (result.size() == 1 && result.at(0).get()->GetIdentifier() == L"default") { result.clear(); } return result; } std::vector<DirectSoundAPI::DeviceDescriptionPtr> DirectSoundAPI::GetInputDevices() { std::vector<DeviceDescriptionPtr> result; DirectSoundCaptureEnumerateW( [](LPGUID lpGuid, LPCWSTR lpcstrDescription, LPCWSTR lpcstrModule, LPVOID lpContext) -> BOOL { auto results = (std::vector<DirectSoundDeviceDescriptionPtr>*)lpContext; auto obj = std::make_shared<DirectSoundDeviceDescription>(lpcstrDescription, lpGuid); results->emplace_back(obj); return TRUE; }, &result); return result; }
7,010
C++
.cpp
202
31.891089
128
0.730502
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,954
CubebInputAPI.cpp
cemu-project_Cemu/src/audio/CubebInputAPI.cpp
#include "CubebInputAPI.h" #if BOOST_OS_WINDOWS #include <combaseapi.h> #include <mmreg.h> #include <mmsystem.h> #pragma comment(lib, "Avrt.lib") #pragma comment(lib, "ksuser.lib") #endif static void state_cb(cubeb_stream* stream, void* user, cubeb_state state) { if (!stream) return; /*switch (state) { case CUBEB_STATE_STARTED: fprintf(stderr, "stream started\n"); break; case CUBEB_STATE_STOPPED: fprintf(stderr, "stream stopped\n"); break; case CUBEB_STATE_DRAINED: fprintf(stderr, "stream drained\n"); break; default: fprintf(stderr, "unknown stream state %d\n", state); }*/ } long CubebInputAPI::data_cb(cubeb_stream* stream, void* user, const void* inputbuffer, void* outputbuffer, long nframes) { auto* thisptr = (CubebInputAPI*)user; const auto size = (size_t)nframes * thisptr->m_channels * (thisptr->m_bitsPerSample / 8); std::unique_lock lock(thisptr->m_mutex); if (thisptr->m_buffer.capacity() <= thisptr->m_buffer.size() + size) { cemuLog_logDebug(LogType::Force, "dropped input sound block since too many buffers are queued"); return nframes; } thisptr->m_buffer.insert(thisptr->m_buffer.end(), (uint8*)inputbuffer, (uint8*)inputbuffer + size); return nframes; } CubebInputAPI::CubebInputAPI(cubeb_devid devid, uint32 samplerate, uint32 channels, uint32 samples_per_block, uint32 bits_per_sample) : IAudioInputAPI(samplerate, channels, samples_per_block, bits_per_sample) { cubeb_stream_params input_params; input_params.format = CUBEB_SAMPLE_S16LE; input_params.rate = samplerate; input_params.channels = channels; input_params.prefs = CUBEB_STREAM_PREF_NONE; switch (channels) { case 8: input_params.layout = CUBEB_LAYOUT_3F4_LFE; break; case 6: input_params.layout = CUBEB_LAYOUT_QUAD_LFE | CHANNEL_FRONT_CENTER; break; case 4: input_params.layout = CUBEB_LAYOUT_QUAD; break; case 2: input_params.layout = CUBEB_LAYOUT_STEREO; break; default: input_params.layout = CUBEB_LAYOUT_MONO; break; } uint32 latency = 1; cubeb_get_min_latency(s_context, &input_params, &latency); m_buffer.reserve((size_t)m_bytesPerBlock * kBlockCount); if (cubeb_stream_init(s_context, &m_stream, "Cemu Cubeb input", devid, &input_params, nullptr, nullptr, latency, data_cb, state_cb, this) != CUBEB_OK) { throw std::runtime_error("can't initialize cubeb device"); } } CubebInputAPI::~CubebInputAPI() { if (m_stream) { Stop(); cubeb_stream_destroy(m_stream); } } bool CubebInputAPI::ConsumeBlock(sint16* data) { std::unique_lock lock(m_mutex); if (m_buffer.empty()) { // we got no data, just write silence memset(data, 0x00, m_bytesPerBlock); } else { const auto copied = std::min(m_buffer.size(), (size_t)m_bytesPerBlock); memcpy(data, m_buffer.data(), copied); m_buffer.erase(m_buffer.begin(), std::next(m_buffer.begin(), copied)); lock.unlock(); // fill rest with silence if (copied != m_bytesPerBlock) memset((uint8*)data + copied, 0x00, m_bytesPerBlock - copied); } return true; } bool CubebInputAPI::Play() { if (m_is_playing) return true; if (cubeb_stream_start(m_stream) == CUBEB_OK) { m_is_playing = true; return true; } return false; } bool CubebInputAPI::Stop() { if (!m_is_playing) return true; if (cubeb_stream_stop(m_stream) == CUBEB_OK) { m_is_playing = false; return true; } return false; } void CubebInputAPI::SetVolume(sint32 volume) { IAudioInputAPI::SetVolume(volume); cubeb_stream_set_volume(m_stream, (float)volume / 100.0f); } bool CubebInputAPI::InitializeStatic() { if (cubeb_init(&s_context, "Cemu Input Cubeb", nullptr)) { cemuLog_log(LogType::Force, "can't create cubeb audio api"); return false; } return true; } void CubebInputAPI::Destroy() { if (s_context) cubeb_destroy(s_context); } std::vector<IAudioInputAPI::DeviceDescriptionPtr> CubebInputAPI::GetDevices() { cubeb_device_collection devices; if (cubeb_enumerate_devices(s_context, CUBEB_DEVICE_TYPE_INPUT, &devices) != CUBEB_OK) return {}; std::vector<DeviceDescriptionPtr> result; result.reserve(devices.count + 1); // Reserve space for the default device // Add the default device to the list auto defaultDevice = std::make_shared<CubebDeviceDescription>(nullptr, "default", L"Default Device"); result.emplace_back(defaultDevice); for (size_t i = 0; i < devices.count; ++i) { // const auto& device = devices.device[i]; if (devices.device[i].state == CUBEB_DEVICE_STATE_ENABLED) { auto device = std::make_shared<CubebDeviceDescription>(devices.device[i].devid, devices.device[i].device_id, boost::nowide::widen( devices.device[i].friendly_name)); result.emplace_back(device); } } cubeb_device_collection_destroy(s_context, &devices); return result; }
4,872
C++
.cpp
171
25.51462
120
0.715081
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,955
XAudio27API.cpp
cemu-project_Cemu/src/audio/XAudio27API.cpp
#include "XAudio27API.h" #include "../dependencies/DirectX_2010/XAudio2.h" static_assert(IAudioAPI::kBlockCount < XAUDIO2_MAX_QUEUED_BUFFERS, "too many xaudio2 buffers"); HMODULE XAudio27API::s_xaudio_dll = nullptr; std::unique_ptr<IXAudio2, XAudio27API::XAudioDeleter> XAudio27API::s_xaudio; XAudio27API::XAudio27API(uint32 device_id, uint32 samplerate, uint32 channels, uint32 samples_per_block, uint32 bits_per_sample) : IAudioAPI(samplerate, channels, samples_per_block, bits_per_sample) { if (!s_xaudio) throw std::runtime_error("xaudio 2.7 not initialized!"); // we use -1 for always selecting the primary device, which is the first one if (device_id == -1) device_id = 0; HRESULT hres; IXAudio2* xaudio; if (FAILED((hres = XAudio2Create(&xaudio, 0, XAUDIO2_DEFAULT_PROCESSOR)))) throw std::runtime_error(fmt::format("can't create xaudio device (hres: {:#x})", hres)); m_xaudio = decltype(m_xaudio)(xaudio); IXAudio2MasteringVoice* mastering_voice; if (FAILED((hres = m_xaudio->CreateMasteringVoice(&mastering_voice, channels, samplerate, 0, device_id)))) throw std::runtime_error(fmt::format("can't create xaudio mastering voice (hres: {:#x})", hres)); m_mastering_voice = decltype(m_mastering_voice)(mastering_voice); m_wfx.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; m_wfx.Format.nChannels = channels; m_wfx.Format.nSamplesPerSec = samplerate; m_wfx.Format.wBitsPerSample = bits_per_sample; m_wfx.Format.nBlockAlign = (m_wfx.Format.nChannels * m_wfx.Format.wBitsPerSample) / 8; // must equal (nChannels × wBitsPerSample) / 8 m_wfx.Format.nAvgBytesPerSec = m_wfx.Format.nSamplesPerSec * m_wfx.Format.nBlockAlign; // must equal nSamplesPerSec × nBlockAlign. m_wfx.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX); m_wfx.SubFormat = KSDATAFORMAT_SUBTYPE_PCM; m_wfx.Samples.wValidBitsPerSample = bits_per_sample; switch (channels) { case 8: m_wfx.dwChannelMask |= (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_FRONT_LEFT_OF_CENTER | SPEAKER_FRONT_RIGHT_OF_CENTER); break; case 6: m_wfx.dwChannelMask |= (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT); break; case 4: m_wfx.dwChannelMask |= (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT); break; case 2: m_wfx.dwChannelMask |= (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT); break; default: m_wfx.dwChannelMask = 0; break; } IXAudio2SourceVoice* source_voice; if (FAILED((hres = m_xaudio->CreateSourceVoice(&source_voice, &m_wfx.Format, 0, 1.0f)))) throw std::runtime_error(fmt::format("can't create xaudio source voice (hres: {:#x})", hres)); m_source_voice = decltype(m_source_voice)(source_voice); m_sound_buffer_size = kBlockCount * (samples_per_block * channels * (bits_per_sample / 8)); for (uint32 i = 0; i < kBlockCount; ++i) m_audio_buffer[i] = std::make_unique<uint8[]>(m_bytesPerBlock); m_xaudio->StartEngine(); } XAudio27API::~XAudio27API() { if(m_xaudio) m_xaudio->StopEngine(); XAudio27API::Stop(); m_source_voice.reset(); m_mastering_voice.reset(); m_xaudio.reset(); } void XAudio27API::SetVolume(sint32 volume) { IAudioAPI::SetVolume(volume); m_mastering_voice->SetVolume((float)volume / 100.0f); } bool XAudio27API::Play() { if (m_playing) return true; m_playing = SUCCEEDED(m_source_voice->Start()); return m_playing; } bool XAudio27API::Stop() { if (!m_playing) return true; m_playing = FAILED(m_source_voice->Stop()); m_source_voice->FlushSourceBuffers(); return m_playing; } bool XAudio27API::InitializeStatic() { if (s_xaudio) return true; #ifdef _DEBUG s_xaudio_dll = LoadLibraryExW(L"XAudioD2_7.DLL", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); if(!s_xaudio_dll) s_xaudio_dll = LoadLibraryExW(L"XAudio2_7.DLL", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); #else s_xaudio_dll = LoadLibraryExW(L"XAudio2_7.DLL", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); #endif try { if (!s_xaudio_dll) throw std::exception(); IXAudio2* xaudio; if (FAILED(XAudio2Create(&xaudio, 0, XAUDIO2_DEFAULT_PROCESSOR))) throw std::exception(); s_xaudio = decltype(s_xaudio)(xaudio); return true; } catch (const std::exception&) { if (s_xaudio_dll) FreeLibrary(s_xaudio_dll); return false; } } void XAudio27API::Destroy() { s_xaudio.reset(); if (s_xaudio_dll) FreeLibrary(s_xaudio_dll); } std::vector<XAudio27API::DeviceDescriptionPtr> XAudio27API::GetDevices() { std::vector<DeviceDescriptionPtr> result; // always add the default device auto default_device = std::make_shared<XAudio27DeviceDescription>(L"Primary Sound Driver", L"", -1); result.emplace_back(default_device); uint32 count = 0; if (FAILED(s_xaudio->GetDeviceCount(&count))) return result; if (!count) return result; result.reserve(count + 1); // first device is always the primary device for (uint32 id = 0; id < count; ++id) { XAUDIO2_DEVICE_DETAILS details; if (SUCCEEDED(s_xaudio->GetDeviceDetails(id, &details))) { auto device = std::make_shared<XAudio27DeviceDescription>(details.DisplayName, details.DeviceID, id); result.emplace_back(device); } } return result; } void XAudio27API::XAudioDeleter::operator()(IXAudio2* ptr) const { if (ptr) ptr->Release(); } void XAudio27API::VoiceDeleter::operator()(IXAudio2Voice* ptr) const { if (ptr) ptr->DestroyVoice(); } bool XAudio27API::FeedBlock(sint16* data) { // check if we queued too many blocks if(m_blocks_queued >= kBlockCount) { XAUDIO2_VOICE_STATE state{}; m_source_voice->GetState(&state); m_blocks_queued = state.BuffersQueued; if (m_blocks_queued >= kBlockCount) { cemuLog_logDebug(LogType::Force, "dropped xaudio2 block since too many buffers are queued"); return false; } } memcpy(m_audio_buffer[m_offset].get(), data, m_bytesPerBlock); XAUDIO2_BUFFER buffer{}; buffer.AudioBytes = m_bytesPerBlock; buffer.pAudioData = m_audio_buffer[m_offset].get(); m_source_voice->SubmitSourceBuffer(&buffer); m_offset = (m_offset + 1) % kBlockCount; m_blocks_queued++; return true; } bool XAudio27API::NeedAdditionalBlocks() const { return m_blocks_queued < s_audioDelay; }
6,302
C++
.cpp
182
32.291209
219
0.742509
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,956
audioDebuggerWindow.cpp
cemu-project_Cemu/src/audio/audioDebuggerWindow.cpp
#include "gui/wxgui.h" #include "audioDebuggerWindow.h" #include "Cafe/OS/libs/snd_core/ax.h" #include "Cafe/OS/libs/snd_core/ax_internal.h" enum { // options REFRESH_ID, CLOSE_ID, VOICELIST_ID, REFRESH_TIMER_ID, }; wxBEGIN_EVENT_TABLE(AudioDebuggerWindow, wxFrame) EVT_BUTTON(CLOSE_ID, AudioDebuggerWindow::OnCloseButton) EVT_BUTTON(REFRESH_ID, AudioDebuggerWindow::OnRefreshButton) EVT_TIMER(REFRESH_TIMER_ID, AudioDebuggerWindow::OnRefreshTimer) EVT_CLOSE(AudioDebuggerWindow::OnClose) wxEND_EVENT_TABLE() AudioDebuggerWindow::AudioDebuggerWindow(wxFrame& parent) : wxFrame(&parent, wxID_ANY, _("AX voice viewer"), wxDefaultPosition, wxSize(1126, 580), wxCLOSE_BOX | wxCLIP_CHILDREN | wxCAPTION | wxRESIZE_BORDER) { wxPanel* mainPane = new wxPanel(this); wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL); voiceListbox = new wxListCtrl(mainPane, VOICELIST_ID, wxPoint(0, 0), wxSize(1126, 570), wxLC_REPORT); voiceListbox->SetFont(wxFont(8, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, false, "Courier New")); // add columns wxListItem col0; col0.SetId(0); col0.SetText("idx"); col0.SetWidth(40); voiceListbox->InsertColumn(0, col0); wxListItem col1; col1.SetId(1); col1.SetText("state"); col1.SetWidth(48); voiceListbox->InsertColumn(1, col1); //wxListItem col2; // format col1.SetId(2); col1.SetText("fmt"); col1.SetWidth(52); voiceListbox->InsertColumn(2, col1); // sample base addr col1.SetId(3); col1.SetText("base"); col1.SetWidth(70); voiceListbox->InsertColumn(3, col1); // current offset col1.SetId(4); col1.SetText("current"); col1.SetWidth(70); voiceListbox->InsertColumn(4, col1); // loop offset col1.SetId(5); col1.SetText("loop"); col1.SetWidth(70); voiceListbox->InsertColumn(5, col1); // end offset col1.SetId(6); col1.SetText("end"); col1.SetWidth(70); voiceListbox->InsertColumn(6, col1); // volume col1.SetId(7); col1.SetText("vol"); col1.SetWidth(46); voiceListbox->InsertColumn(7, col1); // volume delta col1.SetId(8); col1.SetText("volD"); col1.SetWidth(46); voiceListbox->InsertColumn(8, col1); // src col1.SetId(9); col1.SetText("src"); col1.SetWidth(70); voiceListbox->InsertColumn(9, col1); // low-pass filter coef a0 col1.SetId(10); col1.SetText("lpa0"); col1.SetWidth(46); voiceListbox->InsertColumn(10, col1); // low-pass filter coef b0 col1.SetId(11); col1.SetText("lpb0"); col1.SetWidth(46); voiceListbox->InsertColumn(11, col1); // biquad filter coef b0 col1.SetId(12); col1.SetText("bqb0"); col1.SetWidth(46); voiceListbox->InsertColumn(12, col1); // biquad filter coef b0 col1.SetId(13); col1.SetText("bqb1"); col1.SetWidth(46); voiceListbox->InsertColumn(13, col1); // biquad filter coef b0 col1.SetId(14); col1.SetText("bqb2"); col1.SetWidth(46); voiceListbox->InsertColumn(14, col1); // biquad filter coef a0 col1.SetId(15); col1.SetText("bqa1"); col1.SetWidth(46); voiceListbox->InsertColumn(15, col1); // biquad filter coef a1 col1.SetId(16); col1.SetText("bqa2"); col1.SetWidth(46); voiceListbox->InsertColumn(16, col1); // device mix col1.SetId(17); col1.SetText("deviceMix"); col1.SetWidth(186); voiceListbox->InsertColumn(17, col1); sizer->Add(voiceListbox, 1, wxEXPAND | wxBOTTOM, 0); voiceListbox->Connect(wxEVT_RIGHT_DOWN, wxMouseEventHandler(AudioDebuggerWindow::OnVoiceListRightClick), NULL, this); mainPane->SetSizer(sizer); // add empty entries for (sint32 i = 0; i < snd_core::AX_MAX_VOICES; i++) { wxListItem item; item.SetId(i); char tempStr[32]; sprintf(tempStr, "%d", snd_core::AX_MAX_VOICES-i-1); item.SetText(wxString(tempStr)); voiceListbox->InsertItem(item); } RefreshVoiceList(); wxFrame::SetBackgroundColour(*wxWHITE); // start refresh timer static const int INTERVAL = 100; // milliseconds refreshTimer = new wxTimer(this, REFRESH_TIMER_ID); refreshTimer->Start(INTERVAL); } void AudioDebuggerWindow::OnRefreshTimer(wxTimerEvent& event) { RefreshVoiceList(); } void AudioDebuggerWindow::OnCloseButton(wxCommandEvent& event) { Close(); } void AudioDebuggerWindow::OnRefreshButton(wxCommandEvent& event) { RefreshVoiceList(); } void AudioDebuggerWindow::OnClose(wxCloseEvent& event) { Close(); } #define _r(__idx) _swapEndianU32(threadItrBE->context.gpr[__idx]) void AudioDebuggerWindow::RefreshVoiceList_sndgeneric() { if (snd_core::__AXVPBInternalVoiceArray == nullptr || snd_core::__AXVPBArrayPtr == nullptr) return; snd_core::AXVPB tempVoiceArray[snd_core::AX_MAX_VOICES]; memcpy(tempVoiceArray, snd_core::__AXVPBArrayPtr, sizeof(snd_core::AXVPB)*snd_core::AX_MAX_VOICES); voiceListbox->Freeze(); char tempStr[64]; for (sint32 i = 0; i < snd_core::AX_MAX_VOICES; i++) { sint32 voiceIndex = snd_core::AX_MAX_VOICES - 1 - i; snd_core::AXVPBInternal_t* internal = snd_core::__AXVPBInternalVoiceArray + voiceIndex; // index sprintf(tempStr, "%d", (sint32)tempVoiceArray[voiceIndex].index); voiceListbox->SetItem(i, 0, tempStr); // state uint16 playbackState = _swapEndianU16(internal->playbackState); if (playbackState) strcpy(tempStr, "on"); else strcpy(tempStr, "off"); voiceListbox->SetItem(i, 1, tempStr); // if voice index is invalid then stop updating here to prevent crashes if (voiceIndex < 0 || playbackState == 0) { voiceListbox->SetItem(i, 0, ""); voiceListbox->SetItem(i, 1, ""); voiceListbox->SetItem(i, 2, ""); voiceListbox->SetItem(i, 3, ""); voiceListbox->SetItem(i, 4, ""); voiceListbox->SetItem(i, 5, ""); voiceListbox->SetItem(i, 6, ""); voiceListbox->SetItem(i, 7, ""); voiceListbox->SetItem(i, 8, ""); voiceListbox->SetItem(i, 9, ""); voiceListbox->SetItem(i, 10, ""); voiceListbox->SetItem(i, 11, ""); voiceListbox->SetItem(i, 12, ""); voiceListbox->SetItem(i, 13, ""); voiceListbox->SetItem(i, 14, ""); voiceListbox->SetItem(i, 15, ""); voiceListbox->SetItem(i, 16, ""); voiceListbox->SetItem(i, 17, ""); continue; } // format if (tempVoiceArray[voiceIndex].offsets.format == _swapEndianU16(snd_core::AX_FORMAT_ADPCM)) strcpy(tempStr, "adpcm"); else if (tempVoiceArray[voiceIndex].offsets.format == _swapEndianU16(snd_core::AX_FORMAT_PCM16)) strcpy(tempStr, "pcm16"); else if (tempVoiceArray[voiceIndex].offsets.format == _swapEndianU16(snd_core::AX_FORMAT_PCM8)) strcpy(tempStr, "pcm8"); else strcpy(tempStr, "ukn"); voiceListbox->SetItem(i, 2, tempStr); // update offsets snd_core::AXPBOFFSET_t tempOffsets; snd_core::AXGetVoiceOffsets(tempVoiceArray + voiceIndex, &tempOffsets); // sample base sprintf(tempStr, "%08x", _swapEndianU32(tempOffsets.samples)); voiceListbox->SetItem(i, 3, tempStr); // current offset sprintf(tempStr, "%08x", _swapEndianU32(tempOffsets.currentOffset)); voiceListbox->SetItem(i, 4, tempStr); // loop offset if (tempOffsets.loopFlag) sprintf(tempStr, "%08x", _swapEndianU32(tempOffsets.loopOffset)); else sprintf(tempStr, ""); voiceListbox->SetItem(i, 5, tempStr); // end offset sprintf(tempStr, "%08x", _swapEndianU32(tempOffsets.endOffset)); voiceListbox->SetItem(i, 6, tempStr); // volume sprintf(tempStr, "%04x", (uint16)internal->veVolume); voiceListbox->SetItem(i, 7, tempStr); // volume delta sprintf(tempStr, "%04x", (uint16)internal->veDelta); voiceListbox->SetItem(i, 8, tempStr); // src sprintf(tempStr, "%04x%04x", _swapEndianU16(internal->src.ratioHigh), _swapEndianU16(internal->src.ratioLow)); voiceListbox->SetItem(i, 9, tempStr); // lpf if (internal->lpf.on) { sprintf(tempStr, "%04x", _swapEndianU16(internal->lpf.a0)); voiceListbox->SetItem(i, 10, tempStr); sprintf(tempStr, "%04x", _swapEndianU16(internal->lpf.b0)); voiceListbox->SetItem(i, 11, tempStr); } else { voiceListbox->SetItem(i, 10, ""); voiceListbox->SetItem(i, 11, ""); } // biquad if (internal->biquad.on) { sprintf(tempStr, "%04x", _swapEndianU16(internal->biquad.b0)); voiceListbox->SetItem(i, 12, tempStr); sprintf(tempStr, "%04x", _swapEndianU16(internal->biquad.b1)); voiceListbox->SetItem(i, 13, tempStr); sprintf(tempStr, "%04x", _swapEndianU16(internal->biquad.b2)); voiceListbox->SetItem(i, 14, tempStr); sprintf(tempStr, "%04x", _swapEndianU16(internal->biquad.a1)); voiceListbox->SetItem(i, 15, tempStr); sprintf(tempStr, "%04x", _swapEndianU16(internal->biquad.a2)); voiceListbox->SetItem(i, 16, tempStr); } else { voiceListbox->SetItem(i, 12, ""); voiceListbox->SetItem(i, 13, ""); voiceListbox->SetItem(i, 14, ""); voiceListbox->SetItem(i, 15, ""); voiceListbox->SetItem(i, 16, ""); } // device mix for (uint32 f = 0; f < snd_core::AX_TV_CHANNEL_COUNT*snd_core::AX_MAX_NUM_BUS; f++) { sint32 busIndex = f% snd_core::AX_MAX_NUM_BUS; sint32 channelIndex = f / snd_core::AX_MAX_NUM_BUS; //debug_printf("DeviceMix TV Voice %08x b%02d/c%02d vol %04x delta %04x\n", hCPU->gpr[3], busIndex, channelIndex, _swapEndianU16(mixArrayBE[f].vol), _swapEndianU16(mixArrayBE[f].volDelta)); uint32 mixVol = internal->deviceMixTV[channelIndex * 4 + busIndex].vol; mixVol = (mixVol + 0x0FFF) >> (12); sprintf(tempStr + f, "%x", mixVol); //ax.voiceInternal[voiceIndex].deviceMixTVChannel[channelIndex].bus[busIndex].vol = _swapEndianU16(mixArrayBE[f].vol); } voiceListbox->SetItem(i, 17, tempStr); } voiceListbox->Thaw(); } void AudioDebuggerWindow::RefreshVoiceList() { RefreshVoiceList_sndgeneric(); } void AudioDebuggerWindow::OnVoiceListPopupClick(wxCommandEvent &evt) { } void AudioDebuggerWindow::OnVoiceListRightClick(wxMouseEvent& event) { } void AudioDebuggerWindow::Close() { // this->MakeModal(false); refreshTimer->Stop(); this->Destroy(); }
9,731
C++
.cpp
302
29.665563
192
0.723452
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,957
IAudioAPI.cpp
cemu-project_Cemu/src/audio/IAudioAPI.cpp
#include "IAudioAPI.h" #if BOOST_OS_WINDOWS #include "XAudio2API.h" #include "XAudio27API.h" #include "DirectSoundAPI.h" #endif #include "config/CemuConfig.h" #if HAS_CUBEB #include "CubebAPI.h" #endif std::shared_mutex g_audioMutex; AudioAPIPtr g_tvAudio; AudioAPIPtr g_padAudio; std::atomic_int32_t g_padVolume = 0; uint32 IAudioAPI::s_audioDelay = 2; std::array<bool, IAudioAPI::AudioAPIEnd> IAudioAPI::s_availableApis{}; IAudioAPI::IAudioAPI(uint32 samplerate, uint32 channels, uint32 samples_per_block, uint32 bits_per_sample) : m_samplerate(samplerate), m_channels(channels), m_samplesPerBlock(samples_per_block), m_bitsPerSample(bits_per_sample) { m_bytesPerBlock = samples_per_block * channels * (bits_per_sample / 8); InitWFX(m_samplerate, m_channels, m_bitsPerSample); } void IAudioAPI::PrintLogging() { cemuLog_log(LogType::Force, "------- Init Audio backend -------"); cemuLog_log(LogType::Force, "DirectSound: {}", s_availableApis[DirectSound] ? "available" : "not supported"); cemuLog_log(LogType::Force, "XAudio 2.8: {}", s_availableApis[XAudio2] ? "available" : "not supported"); if (!s_availableApis[XAudio2]) { cemuLog_log(LogType::Force, "XAudio 2.7: {}", s_availableApis[XAudio27] ? "available" : "not supported"); } cemuLog_log(LogType::Force, "Cubeb: {}", s_availableApis[Cubeb] ? "available" : "not supported"); } void IAudioAPI::InitWFX(sint32 samplerate, sint32 channels, sint32 bits_per_sample) { #if BOOST_OS_WINDOWS // move this to Windows-specific audio API implementations and use a cross-platform format here m_wfx.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; m_wfx.Format.nChannels = channels; m_wfx.Format.nSamplesPerSec = samplerate; m_wfx.Format.wBitsPerSample = bits_per_sample; m_wfx.Format.nBlockAlign = (m_wfx.Format.nChannels * m_wfx.Format.wBitsPerSample) / 8; // must equal (nChannels � wBitsPerSample) / 8 m_wfx.Format.nAvgBytesPerSec = m_wfx.Format.nSamplesPerSec * m_wfx.Format.nBlockAlign; // must equal nSamplesPerSec � nBlockAlign. m_wfx.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX); m_wfx.SubFormat = KSDATAFORMAT_SUBTYPE_PCM; m_wfx.Samples.wValidBitsPerSample = bits_per_sample; switch (channels) { case 8: m_wfx.dwChannelMask |= (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_FRONT_LEFT_OF_CENTER | SPEAKER_FRONT_RIGHT_OF_CENTER); break; case 6: m_wfx.dwChannelMask |= (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT); break; case 4: m_wfx.dwChannelMask |= (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT); break; case 2: m_wfx.dwChannelMask |= (SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT); break; default: m_wfx.dwChannelMask = 0; break; } #endif } void IAudioAPI::InitializeStatic() { s_audioDelay = GetConfig().audio_delay; #if BOOST_OS_WINDOWS s_availableApis[DirectSound] = true; s_availableApis[XAudio2] = XAudio2API::InitializeStatic(); if(!s_availableApis[XAudio2]) // don't try to initialize the older lib if the newer version is available s_availableApis[XAudio27] = XAudio27API::InitializeStatic(); #endif #if HAS_CUBEB s_availableApis[Cubeb] = CubebAPI::InitializeStatic(); #endif } bool IAudioAPI::IsAudioAPIAvailable(AudioAPI api) { if ((size_t)api < s_availableApis.size()) return s_availableApis[api]; cemu_assert_debug(false); return false; } AudioAPIPtr IAudioAPI::CreateDevice(AudioAPI api, const DeviceDescriptionPtr& device, sint32 samplerate, sint32 channels, sint32 samples_per_block, sint32 bits_per_sample) { if (!IsAudioAPIAvailable(api)) return {}; switch(api) { #if BOOST_OS_WINDOWS case DirectSound: { const auto tmp = std::dynamic_pointer_cast<DirectSoundAPI::DirectSoundDeviceDescription>(device); return std::make_unique<DirectSoundAPI>(tmp->GetGUID(), samplerate, channels, samples_per_block, bits_per_sample); } case XAudio27: { const auto tmp = std::dynamic_pointer_cast<XAudio27API::XAudio27DeviceDescription>(device); return std::make_unique<XAudio27API>(tmp->GetDeviceId(), samplerate, channels, samples_per_block, bits_per_sample); } case XAudio2: { const auto tmp = std::dynamic_pointer_cast<XAudio2API::XAudio2DeviceDescription>(device); return std::make_unique<XAudio2API>(tmp->GetDeviceId(), samplerate, channels, samples_per_block, bits_per_sample); } #endif #if HAS_CUBEB case Cubeb: { const auto tmp = std::dynamic_pointer_cast<CubebAPI::CubebDeviceDescription>(device); return std::make_unique<CubebAPI>(tmp->GetDeviceId(), samplerate, channels, samples_per_block, bits_per_sample); } #endif default: throw std::runtime_error(fmt::format("invalid audio api: {}", api)); } } std::vector<IAudioAPI::DeviceDescriptionPtr> IAudioAPI::GetDevices(AudioAPI api) { if (!IsAudioAPIAvailable(api)) return {}; switch(api) { #if BOOST_OS_WINDOWS case DirectSound: { return DirectSoundAPI::GetDevices(); } case XAudio27: { return XAudio27API::GetDevices(); } case XAudio2: { return XAudio2API::GetDevices(); } #endif #if HAS_CUBEB case Cubeb: { return CubebAPI::GetDevices(); } #endif default: throw std::runtime_error(fmt::format("invalid audio api: {}", api)); } }
5,356
C++
.cpp
150
33.546667
219
0.755693
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,959
resources.cpp
cemu-project_Cemu/src/resource/embedded/resources.cpp
#include "X_GAME_PROFILE.xpm" #include "M_WND_ICON128.xpm" #include "X_BOX.xpm" #include "X_SETTINGS.xpm" #include "icons8-checkmark-yes-32.hpng" #include "icons8-error-32.hpng" #include "PNG_HELP.hpng" #include "PNG_REFRESH.hpng" #include "DEBUGGER_BP.hpng" #include "DEBUGGER_BP_RED.hpng" #include "DEBUGGER_PAUSE.hpng" #include "DEBUGGER_PLAY.hpng" #include "DEBUGGER_STEP_INTO.hpng" #include "DEBUGGER_STEP_OUT.hpng" #include "DEBUGGER_STEP_OVER.hpng" #include "DEBUGGER_GOTO.hpng" #include "INPUT_LOW_BATTERY.hpng" #include "INPUT_CONNECTED.hpng" #include "INPUT_DISCONNECTED.hpng"
590
C++
.cpp
19
29.894737
39
0.78169
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,960
NetworkSettings.cpp
cemu-project_Cemu/src/config/NetworkSettings.cpp
#include "NetworkSettings.h" #include "ActiveSettings.h" #include "LaunchSettings.h" #include "CemuConfig.h" #include "Common/FileStream.h" XMLNetworkConfig_t n_config(L"network_services.xml"); void NetworkConfig::LoadOnce() { n_config.SetFilename(ActiveSettings::GetConfigPath("network_services.xml").generic_wstring()); if (XMLExists()) n_config.Load(); } void NetworkConfig::Load(XMLConfigParser& parser) { auto config = parser.get("content"); networkname = config.get("networkname", "Custom"); disablesslver = config.get("disablesslverification", disablesslver); auto u = config.get("urls"); urls.ACT = u.get("act", NintendoURLs::ACTURL); urls.ECS = u.get("ecs", NintendoURLs::ECSURL); urls.NUS = u.get("nus", NintendoURLs::NUSURL); urls.IAS = u.get("ias", NintendoURLs::IASURL); urls.CCSU = u.get("ccsu", NintendoURLs::CCSUURL); urls.CCS = u.get("ccs", NintendoURLs::CCSURL); urls.IDBE = u.get("idbe", NintendoURLs::IDBEURL); urls.BOSS = u.get("boss", NintendoURLs::BOSSURL); urls.TAGAYA = u.get("tagaya", NintendoURLs::TAGAYAURL); urls.OLV = u.get("olv", NintendoURLs::OLVURL); } bool NetworkConfig::XMLExists() { static std::optional<bool> s_exists; // caches result of fs::exists if(s_exists.has_value()) return *s_exists; std::error_code ec; if (!fs::exists(ActiveSettings::GetConfigPath("network_services.xml"), ec)) { s_exists = false; return false; } s_exists = true; return true; }
1,434
C++
.cpp
43
31.44186
95
0.731795
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,961
LaunchSettings.cpp
cemu-project_Cemu/src/config/LaunchSettings.cpp
#include "LaunchSettings.h" #include "util/helpers/helpers.h" #include "Cafe/Account/Account.h" #include "Cafe/OS/libs/coreinit/coreinit.h" #include "boost/program_options.hpp" #include <wx/msgdlg.h> #include "config/ActiveSettings.h" #include "config/NetworkSettings.h" #include "util/crypto/aes128.h" #include "Cafe/Filesystem/FST/FST.h" void requireConsole(); bool LaunchSettings::HandleCommandline(const wchar_t* lpCmdLine) { #if BOOST_OS_WINDOWS const std::vector<std::wstring> args = boost::program_options::split_winmain(lpCmdLine); return HandleCommandline(args); #else cemu_assert_unimplemented(); return false; #endif } bool LaunchSettings::HandleCommandline(int argc, wchar_t* argv[]) { std::vector<std::wstring> args; args.reserve(argc); for(int i = 0; i < argc; ++i) { args.emplace_back(argv[i]); } return HandleCommandline(args); } bool LaunchSettings::HandleCommandline(int argc, char* argv[]) { std::vector<std::wstring> args; args.reserve(argc); for(int i = 0; i < argc; ++i) { args.emplace_back(boost::nowide::widen(argv[i])); } return HandleCommandline(args); } bool LaunchSettings::HandleCommandline(const std::vector<std::wstring>& args) { namespace po = boost::program_options; po::options_description desc{ "Launch options" }; desc.add_options() ("help,h", "This help screen") ("version,v", "Displays the version of Cemu") ("game,g", po::wvalue<std::wstring>(), "Path of game to launch") ("title-id,t", po::value<std::string>(), "Title ID of the title to be launched (overridden by --game)") ("mlc,m", po::wvalue<std::wstring>(), "Custom mlc folder location") ("fullscreen,f", po::value<bool>()->implicit_value(true), "Launch games in fullscreen mode") ("ud,u", po::value<bool>()->implicit_value(true), "Render output upside-down") ("account,a", po::value<std::string>(), "Persistent id of account") ("force-interpreter", po::value<bool>()->implicit_value(true), "Force interpreter CPU emulation, disables recompiler") ("enable-gdbstub", po::value<bool>()->implicit_value(true), "Enable GDB stub to debug executables inside Cemu using an external debugger"); po::options_description hidden{ "Hidden options" }; hidden.add_options() ("nsight", po::value<bool>()->implicit_value(true), "NSight debugging options") ("legacy", po::value<bool>()->implicit_value(true), "Intel legacy graphic mode"); po::options_description extractor{ "Extractor tool" }; extractor.add_options() ("extract,e", po::wvalue<std::wstring>(), "Path to WUD or WUX file for extraction") ("path,p", po::value<std::string>(), "Path of file to extract (for example meta/meta.xml)") ("output,o", po::wvalue<std::wstring>(), "Output path for extracted file."); po::options_description all; all.add(desc).add(hidden).add(extractor); po::options_description visible; visible.add(desc).add(extractor); try { po::wcommand_line_parser parser{ args }; parser.allow_unregistered().options(all).style(po::command_line_style::allow_long | po::command_line_style::allow_short | po::command_line_style::allow_dash_for_short | po::command_line_style::case_insensitive | po::command_line_style::long_allow_next | po::command_line_style::short_allow_next | po::command_line_style::allow_long_disguise); const auto parsed_options = parser.run(); po::variables_map vm; po::store(parsed_options, vm); notify(vm); if (vm.count("help")) { requireConsole(); std::cout << visible << std::endl; return false; // exit in main } if (vm.count("version")) { requireConsole(); std::string versionStr; #if EMULATOR_VERSION_PATCH == 0 versionStr = fmt::format("{}.{}{}", EMULATOR_VERSION_MAJOR, EMULATOR_VERSION_MINOR, EMULATOR_VERSION_SUFFIX); #else versionStr = fmt::format("{}.{}-{}{}", EMULATOR_VERSION_MAJOR, EMULATOR_VERSION_MINOR, EMULATOR_VERSION_PATCH, EMULATOR_VERSION_SUFFIX); #endif std::cout << versionStr << std::endl; return false; // exit in main } if (vm.count("game")) { std::wstring tmp = vm["game"].as<std::wstring>(); // workaround for boost command_line_parser not trimming token for short name parameters despite short_allow_adjacent if (tmp.size() > 0 && tmp.front() == '=') tmp.erase(tmp.begin()+0); s_load_game_file = tmp; } if (vm.count("title-id")) { auto title_param = vm["title-id"].as<std::string>(); try { if (title_param.starts_with('=')){ title_param.erase(title_param.begin()); } s_load_title_id = std::stoull(title_param, nullptr, 16); } catch (std::invalid_argument const& e) { std::cerr << "Expected title_param ID as an unsigned 64-bit hexadecimal string\n"; } } if (vm.count("mlc")) { std::wstring tmp = vm["mlc"].as<std::wstring>(); // workaround for boost command_line_parser not trimming token for short name parameters despite short_allow_adjacent if (tmp.size() > 0 && tmp.front() == '=') tmp.erase(tmp.begin() + 0); s_mlc_path = tmp; } if (vm.count("account")) { const auto id = ConvertString<uint32>(vm["account"].as<std::string>(), 16); if (id >= Account::kMinPersistendId) s_persistent_id = id; } if (vm.count("fullscreen")) s_fullscreen = vm["fullscreen"].as<bool>(); if (vm.count("ud")) s_render_upside_down = vm["ud"].as<bool>(); if (vm.count("nsight")) s_nsight_mode = vm["nsight"].as<bool>(); if(vm.count("force-interpreter")) s_force_interpreter = vm["force-interpreter"].as<bool>(); if (vm.count("enable-gdbstub")) s_enable_gdbstub = vm["enable-gdbstub"].as<bool>(); std::wstring extract_path, log_path; std::string output_path; if (vm.count("extract")) extract_path = vm["extract"].as<std::wstring>(); if (vm.count("path")) output_path = vm["path"].as<std::string>(); if (vm.count("output")) log_path = vm["output"].as<std::wstring>(); if(!extract_path.empty()) { ExtractorTool(extract_path, output_path, log_path); return false; } return true; } catch (const std::exception& ex) { std::string errorMsg; errorMsg.append("Error while trying to parse command line parameter:\n"); errorMsg.append(ex.what()); #if BOOST_OS_WINDOWS wxMessageBox(errorMsg, "Parameter error", wxICON_ERROR); #else std::cout << errorMsg << std::endl; #endif return false; } } bool LaunchSettings::ExtractorTool(std::wstring_view wud_path, std::string_view output_path, std::wstring_view log_path) { // extracting requires path of file if (output_path.empty()) { requireConsole(); puts("Cannot extract files because no source path was specified (-p)\n"); return false; } // mount wud AES128_init(); FSTVolume* srcVolume = FSTVolume::OpenFromDiscImage(fs::path(wud_path)); if (!srcVolume) { requireConsole(); puts(fmt::format("Unable to open \"%s\"\n", fs::path(wud_path).generic_string()).c_str()); return false; } bool fileFound = false; std::vector<uint8> fileData = srcVolume->ExtractFile(output_path, &fileFound); delete srcVolume; if (!fileFound) { requireConsole(); puts(fmt::format("Unable to read file \"%s\"\n", output_path).c_str()); return false; } // output on console (if no output path was specified) if (!log_path.empty()) { try { fs::path filename(std::wstring{ log_path }); filename /= boost::nowide::widen(std::string(output_path)); fs::path p = filename; p.remove_filename(); fs::create_directories(p); std::ofstream file(filename, std::ios::out | std::ios::binary); file.write((const char*)fileData.data(), fileData.size()); file.flush(); file.close(); } catch (const std::exception& ex) { cemuLog_log(LogType::Force, "can't write file: {}", ex.what()); puts(fmt::format("can't write file: %s\n", ex.what()).c_str()); } } else { // output to console requireConsole(); printf("%.*s", (int)fileData.size(), fileData.data()); fflush(stdout); } return true; }
8,073
C++
.cpp
229
31.60262
213
0.675881
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,962
ActiveSettings.cpp
cemu-project_Cemu/src/config/ActiveSettings.cpp
#include "Cafe/GameProfile/GameProfile.h" #include "Cafe/IOSU/legacy/iosu_crypto.h" #include "Cafe/HW/Latte/Renderer/Vulkan/VulkanAPI.h" #include "Cafe/CafeSystem.h" #include "Cemu/Logging/CemuLogging.h" #include "config/ActiveSettings.h" #include "config/LaunchSettings.h" #include "util/helpers/helpers.h" void ActiveSettings::SetPaths(bool isPortableMode, const fs::path& executablePath, const fs::path& userDataPath, const fs::path& configPath, const fs::path& cachePath, const fs::path& dataPath, std::set<fs::path>& failedWriteAccess) { cemu_assert_debug(!s_setPathsCalled); // can only change paths before loading s_isPortableMode = isPortableMode; s_executable_path = executablePath; s_user_data_path = userDataPath; s_config_path = configPath; s_cache_path = cachePath; s_data_path = dataPath; failedWriteAccess.clear(); for (auto&& path : {userDataPath, configPath, cachePath}) { std::error_code ec; if (!fs::exists(path, ec)) fs::create_directories(path, ec); if (!TestWriteAccess(path)) { cemuLog_log(LogType::Force, "Failed to write to {}", _pathToUtf8(path)); failedWriteAccess.insert(path); } } s_executable_filename = s_executable_path.filename(); s_setPathsCalled = true; } [[nodiscard]] bool ActiveSettings::IsPortableMode() { return s_isPortableMode; } void ActiveSettings::Init() { cemu_assert_debug(s_setPathsCalled); std::string additionalErrorInfo; s_has_required_online_files = iosuCrypt_checkRequirementsForOnlineMode(additionalErrorInfo) == IOS_CRYPTO_ONLINE_REQ_OK; } bool ActiveSettings::LoadSharedLibrariesEnabled() { return g_current_game_profile->ShouldLoadSharedLibraries().value_or(true); } bool ActiveSettings::DisplayDRCEnabled() { return g_current_game_profile->StartWithGamepadView(); } bool ActiveSettings::FullscreenEnabled() { if (LaunchSettings::FullscreenEnabled().has_value()) return LaunchSettings::FullscreenEnabled().value(); return GetConfig().fullscreen; } CPUMode ActiveSettings::GetCPUMode() { auto mode = g_current_game_profile->GetCPUMode().value_or(CPUMode::Auto); if (mode == CPUMode::Auto) { if (GetPhysicalCoreCount() >= 4) mode = CPUMode::MulticoreRecompiler; else mode = CPUMode::SinglecoreRecompiler; } else if (mode == CPUMode::DualcoreRecompiler) // dualcore is disabled now mode = CPUMode::MulticoreRecompiler; return mode; } uint8 ActiveSettings::GetTimerShiftFactor() { return s_timer_shift; } void ActiveSettings::SetTimerShiftFactor(uint8 shiftFactor) { s_timer_shift = shiftFactor; } PrecompiledShaderOption ActiveSettings::GetPrecompiledShadersOption() { return PrecompiledShaderOption::Auto; // g_current_game_profile->GetPrecompiledShadersState().value_or(GetConfig().precompiled_shaders); } bool ActiveSettings::RenderUpsideDownEnabled() { return LaunchSettings::RenderUpsideDownEnabled().value_or(GetConfig().render_upside_down); } bool ActiveSettings::WaitForGX2DrawDoneEnabled() { return GetConfig().gx2drawdone_sync; } GraphicAPI ActiveSettings::GetGraphicsAPI() { GraphicAPI api = g_current_game_profile->GetGraphicsAPI().value_or(GetConfig().graphic_api); // check if vulkan even available if (api == kVulkan && !g_vulkan_available) api = kOpenGL; return api; } bool ActiveSettings::AudioOutputOnlyAux() { return s_audio_aux_only; } void ActiveSettings::EnableAudioOnlyAux(bool state) { s_audio_aux_only = state; } uint32 ActiveSettings::GetPersistentId() { return LaunchSettings::GetPersistentId().value_or(GetConfig().account.m_persistent_id); } bool ActiveSettings::IsOnlineEnabled() { if(!Account::GetAccount(GetPersistentId()).IsValidOnlineAccount()) return false; if(!HasRequiredOnlineFiles()) return false; NetworkService networkService = static_cast<NetworkService>(GetConfig().GetAccountNetworkService(GetPersistentId())); return networkService == NetworkService::Nintendo || networkService == NetworkService::Pretendo || networkService == NetworkService::Custom; } bool ActiveSettings::HasRequiredOnlineFiles() { return s_has_required_online_files; } NetworkService ActiveSettings::GetNetworkService() { return GetConfig().GetAccountNetworkService(GetPersistentId()); } bool ActiveSettings::DumpShadersEnabled() { return s_dump_shaders; } bool ActiveSettings::DumpTexturesEnabled() { return s_dump_textures; } bool ActiveSettings::DumpLibcurlRequestsEnabled() { return s_dump_libcurl_requests; } void ActiveSettings::EnableDumpShaders(bool state) { s_dump_shaders = state; } void ActiveSettings::EnableDumpTextures(bool state) { s_dump_textures = state; } void ActiveSettings::EnableDumpLibcurlRequests(bool state) { s_dump_libcurl_requests = state; } bool ActiveSettings::VPADDelayEnabled() { const uint64 titleId = CafeSystem::GetForegroundTitleId(); // workaround for Art Academy spamming VPADRead return /* Art Academy: Home Studio (US) */ titleId == 0x000500001017BF00 || /* Art Academy: Home Studio (JP) */ titleId == 0x000500001017BE00 || /* Art Academy: Atelier (EU) */ titleId == 0x000500001017B500; } bool ActiveSettings::ShaderPreventInfiniteLoopsEnabled() { const uint64 titleId = CafeSystem::GetForegroundTitleId(); // workaround for NSMBU (and variants) having a bug where shaders can get stuck in infinite loops // update: As of Cemu 1.20.0 this should no longer be required return /* NSMBU JP */ titleId == 0x0005000010101C00 || /* NSMBU US */ titleId == 0x0005000010101D00 || /* NSMBU EU */ titleId == 0x0005000010101E00 || /* NSMBU+L US */ titleId == 0x000500001014B700 || /* NSMBU+L EU */ titleId == 0x000500001014B800 || /* NSLU US */ titleId == 0x0005000010142300 || /* NSLU EU */ titleId == 0x0005000010142400; } bool ActiveSettings::FlushGPUCacheOnSwap() { const uint64 titleId = CafeSystem::GetForegroundTitleId(); // games that require flushing the cache between frames return /* PAC-MAN and the Ghostly Adventures (EU) */ titleId == 0x0005000010147900 || /* PAC-MAN and the Ghostly Adventures (US) */ titleId == 0x0005000010146300 || /* PAC-MAN and the Ghostly Adventures 2 (EU) */ titleId == 0x000500001017E500 || /* PAC-MAN and the Ghostly Adventures 2 (US) */ titleId == 0x000500001017E600; } bool ActiveSettings::ForceSamplerRoundToPrecision() { // some Wayforward games (Duck Tales, Adventure Time Explore The Dungeon) sample textures exactly on the texel edge. On Wii U this is fine because the rounding mode can be controlled // on OpenGL/Vulkan when uv coordinates are converted from (un)normalized to integer the implementation always truncates which causes an off-by-one error in edge cases // In the future we should look into optionally correctly emulating sampler behavior (its quite complex, Latte supports flexible precision levels) const uint64 titleId = CafeSystem::GetForegroundTitleId(); return /* Adventure Time ETDBIDK (EU) */ titleId == 0x000500001014E100 || /* Adventure Time ETDBIDK (US) */ titleId == 0x0005000010144000 || /* DuckTales Remastered (EU) */ titleId == 0x0005000010129200 || /* DuckTales Remastered (US) */ titleId == 0x0005000010129000; return false; } fs::path ActiveSettings::GetMlcPath() { cemu_assert_debug(s_setPathsCalled); if(const auto launch_mlc = LaunchSettings::GetMLCPath(); launch_mlc.has_value()) return launch_mlc.value(); if(const auto config_mlc = GetConfig().mlc_path.GetValue(); !config_mlc.empty()) return _utf8ToPath(config_mlc); return GetDefaultMLCPath(); } bool ActiveSettings::IsCustomMlcPath() { cemu_assert_debug(s_setPathsCalled); return !GetConfig().mlc_path.GetValue().empty(); } bool ActiveSettings::IsCommandLineMlcPath() { return LaunchSettings::GetMLCPath().has_value(); } fs::path ActiveSettings::GetDefaultMLCPath() { return GetUserDataPath("mlc01"); }
7,744
C++
.cpp
223
32.816143
183
0.778209
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,963
CemuConfig.cpp
cemu-project_Cemu/src/config/CemuConfig.cpp
#include "config/CemuConfig.h" #include "util/helpers/helpers.h" #include "config/ActiveSettings.h" #include <wx/language.h> #include "ActiveSettings.h" XMLCemuConfig_t g_config(L"settings.xml"); void CemuConfig::SetMLCPath(fs::path path, bool save) { mlc_path.SetValue(_pathToUtf8(path)); if(save) g_config.Save(); Account::RefreshAccounts(); } void CemuConfig::Load(XMLConfigParser& parser) { auto new_parser = parser.get("content"); if (new_parser.valid()) parser = new_parser; // general settings log_flag = parser.get("logflag", log_flag.GetInitValue()); cemuLog_setActiveLoggingFlags(GetConfig().log_flag.GetValue()); advanced_ppc_logging = parser.get("advanced_ppc_logging", advanced_ppc_logging.GetInitValue()); const char* mlc = parser.get("mlc_path", ""); mlc_path = mlc; permanent_storage = parser.get("permanent_storage", permanent_storage); language = parser.get<sint32>("language", wxLANGUAGE_DEFAULT); use_discord_presence = parser.get("use_discord_presence", true); fullscreen_menubar = parser.get("fullscreen_menubar", false); feral_gamemode = parser.get("feral_gamemode", false); check_update = parser.get("check_update", check_update); receive_untested_updates = parser.get("receive_untested_updates", receive_untested_updates); save_screenshot = parser.get("save_screenshot", save_screenshot); did_show_vulkan_warning = parser.get("vk_warning", did_show_vulkan_warning); did_show_graphic_pack_download = parser.get("gp_download", did_show_graphic_pack_download); did_show_macos_disclaimer = parser.get("macos_disclaimer", did_show_macos_disclaimer); fullscreen = parser.get("fullscreen", fullscreen); proxy_server = parser.get("proxy_server", ""); disable_screensaver = parser.get("disable_screensaver", disable_screensaver); console_language = parser.get("console_language", console_language.GetInitValue()); window_position.x = parser.get("window_position").get("x", -1); window_position.y = parser.get("window_position").get("y", -1); window_size.x = parser.get("window_size").get("x", -1); window_size.y = parser.get("window_size").get("y", -1); window_maximized = parser.get("window_maximized", false); pad_open = parser.get("open_pad", false); pad_position.x = parser.get("pad_position").get("x", -1); pad_position.y = parser.get("pad_position").get("y", -1); pad_size.x = parser.get("pad_size").get("x", -1); pad_size.y = parser.get("pad_size").get("y", -1); pad_maximized = parser.get("pad_maximized", false); auto gamelist = parser.get("GameList"); game_list_style = gamelist.get("style", 0); game_list_column_order = gamelist.get("order", ""); show_icon_column = parser.get("show_icon_column", true); // return default width if value in config file out of range auto loadColumnSize = [&gamelist] (const char *name, uint32 defaultWidth) { sint64 val = gamelist.get(name, DefaultColumnSize::name); if (val < 0 || val > (sint64) std::numeric_limits<uint32>::max) return defaultWidth; return static_cast<uint32>(val); }; column_width.name = loadColumnSize("name_width", DefaultColumnSize::name); column_width.version = loadColumnSize("version_width", DefaultColumnSize::version); column_width.dlc = loadColumnSize("dlc_width", DefaultColumnSize::dlc); column_width.game_time = loadColumnSize("game_time_width", DefaultColumnSize::game_time); column_width.game_started = loadColumnSize("game_started_width", DefaultColumnSize::game_started); column_width.region = loadColumnSize("region_width", DefaultColumnSize::region); column_width.title_id = loadColumnSize("title_id", DefaultColumnSize::title_id); recent_launch_files.clear(); auto launch_parser = parser.get("RecentLaunchFiles"); for (auto element = launch_parser.get("Entry"); element.valid(); element = launch_parser.get("Entry", element)) { const std::string path = element.value(""); if (path.empty()) continue; try { recent_launch_files.emplace_back(path); } catch (const std::exception&) { cemuLog_log(LogType::Force, "config load error: can't load recently launched game file: {}", path); } } recent_nfc_files.clear(); auto nfc_parser = parser.get("RecentNFCFiles"); for (auto element = nfc_parser.get("Entry"); element.valid(); element = nfc_parser.get("Entry", element)) { const std::string path = element.value(""); if (path.empty()) continue; try { recent_nfc_files.emplace_back(path); } catch (const std::exception&) { cemuLog_log(LogType::Force, "config load error: can't load recently launched nfc file: {}", path); } } game_paths.clear(); auto game_path_parser = parser.get("GamePaths"); for (auto element = game_path_parser.get("Entry"); element.valid(); element = game_path_parser.get("Entry", element)) { const std::string path = element.value(""); if (path.empty()) continue; try { game_paths.emplace_back(path); } catch (const std::exception&) { cemuLog_log(LogType::Force, "config load error: can't load game path: {}", path); } } std::unique_lock _lock(game_cache_entries_mutex); game_cache_entries.clear(); auto game_cache_parser = parser.get("GameCache"); for (auto element = game_cache_parser.get("Entry"); element.valid(); element = game_cache_parser.get("Entry", element)) { const char* rpx = element.get("path", ""); try { GameEntry entry{}; entry.rpx_file = boost::nowide::widen(rpx); entry.title_id = element.get<decltype(entry.title_id)>("title_id"); entry.legacy_name = boost::nowide::widen(element.get("name", "")); entry.custom_name = element.get("custom_name", ""); entry.legacy_region = element.get("region", 0); entry.legacy_version = element.get("version", 0); entry.legacy_update_version = element.get("version", 0); entry.legacy_dlc_version = element.get("dlc_version", 0); entry.legacy_time_played = element.get<decltype(entry.legacy_time_played)>("time_played"); entry.legacy_last_played = element.get<decltype(entry.legacy_last_played)>("last_played"); entry.favorite = element.get("favorite", false); game_cache_entries.emplace_back(entry); if (entry.title_id != 0) { if (entry.favorite) game_cache_favorites.emplace(entry.title_id); else game_cache_favorites.erase(entry.title_id); } } catch (const std::exception&) { cemuLog_log(LogType::Force, "config load error: can't load game cache entry: {}", rpx); } } _lock.unlock(); graphic_pack_entries.clear(); auto graphic_pack_parser = parser.get("GraphicPack"); for (auto element = graphic_pack_parser.get("Entry"); element.valid(); element = graphic_pack_parser.get("Entry", element)) { std::string filename = element.get_attribute("filename", ""); if(filename.empty()) // legacy loading { filename = element.get("filename", ""); fs::path path = fs::path(filename).lexically_normal(); graphic_pack_entries.try_emplace(path); const std::string category = element.get("category", ""); const std::string preset = element.get("preset", ""); graphic_pack_entries[filename].try_emplace(category, preset); } else { fs::path path = fs::path(filename).lexically_normal(); graphic_pack_entries.try_emplace(path); const bool disabled = element.get_attribute("disabled", false); if (disabled) { graphic_pack_entries[path].try_emplace("_disabled", "true"); } for (auto preset = element.get("Preset"); preset.valid(); preset = element.get("Preset", preset)) { const std::string category = preset.get("category", ""); const std::string active_preset = preset.get("preset", ""); graphic_pack_entries[path].try_emplace(category, active_preset); } } } // graphics auto graphic = parser.get("Graphic"); graphic_api = graphic.get("api", kOpenGL); graphic.get("device", graphic_device_uuid); vsync = graphic.get("VSync", 0); gx2drawdone_sync = graphic.get("GX2DrawdoneSync", true); upscale_filter = graphic.get("UpscaleFilter", kBicubicHermiteFilter); downscale_filter = graphic.get("DownscaleFilter", kLinearFilter); fullscreen_scaling = graphic.get("FullscreenScaling", kKeepAspectRatio); async_compile = graphic.get("AsyncCompile", async_compile); vk_accurate_barriers = graphic.get("vkAccurateBarriers", true); // this used to be "VulkanAccurateBarriers" but because we changed the default to true in 1.27.1 the option name had to be changed auto overlay_node = graphic.get("Overlay"); if(overlay_node.valid()) { overlay.position = overlay_node.get("Position", ScreenPosition::kDisabled); overlay.text_color = overlay_node.get("TextColor", 0xFFFFFFFF); overlay.text_scale = overlay_node.get("TextScale", 100); overlay.fps = overlay_node.get("FPS", true); overlay.drawcalls = overlay_node.get("DrawCalls", false); overlay.cpu_usage = overlay_node.get("CPUUsage", false); overlay.cpu_per_core_usage = overlay_node.get("CPUPerCoreUsage", false); overlay.ram_usage = overlay_node.get("RAMUsage", false); overlay.vram_usage = overlay_node.get("VRAMUsage", false); overlay.debug = overlay_node.get("Debug", false); notification.controller_profiles = overlay_node.get("ControllerProfiles", true); notification.controller_battery = overlay_node.get("ControllerBattery", true); notification.shader_compiling = overlay_node.get("ShaderCompiling", true); } else { // legacy support overlay.position = graphic.get("OverlayPosition", ScreenPosition::kDisabled); overlay.text_color = graphic.get("OverlayTextColor", 0xFFFFFFFF); overlay.fps = graphic.get("OverlayFPS", true); overlay.drawcalls = graphic.get("OverlayDrawCalls", false); overlay.cpu_usage = graphic.get("OverlayCPUUsage", false); overlay.cpu_per_core_usage = graphic.get("OverlayCPUPerCoreUsage", false); overlay.ram_usage = graphic.get("OverlayRAMUsage", false); notification.controller_profiles = graphic.get("OverlayControllerProfiles", true); notification.controller_battery = graphic.get("OverlayControllerBattery", true); notification.shader_compiling = graphic.get("ShaderCompiling", true); } auto notification_node = graphic.get("Notification"); if (notification_node.valid()) { notification.position = notification_node.get("Position", ScreenPosition::kTopLeft); notification.text_color = notification_node.get("TextColor", 0xFFFFFFFF); notification.text_scale = notification_node.get("TextScale", 100); notification.controller_profiles = notification_node.get("ControllerProfiles", true); notification.controller_battery = notification_node.get("ControllerBattery", false); notification.shader_compiling = notification_node.get("ShaderCompiling", true); notification.friends = notification_node.get("FriendService", true); } // audio auto audio = parser.get("Audio"); audio_api = audio.get("api", 0); audio_delay = audio.get("delay", 2); tv_channels = audio.get("TVChannels", kStereo); pad_channels = audio.get("PadChannels", kStereo); input_channels = audio.get("InputChannels", kMono); tv_volume = audio.get("TVVolume", 20); pad_volume = audio.get("PadVolume", 0); input_volume = audio.get("InputVolume", 20); const auto tv = audio.get("TVDevice", ""); try { tv_device = boost::nowide::widen(tv); } catch (const std::exception&) { cemuLog_log(LogType::Force, "config load error: can't load tv device: {}", tv); } const auto pad = audio.get("PadDevice", ""); try { pad_device = boost::nowide::widen(pad); } catch (const std::exception&) { cemuLog_log(LogType::Force, "config load error: can't load pad device: {}", pad); } const auto input_device_name = audio.get("InputDevice", ""); try { input_device = boost::nowide::widen(input_device_name); } catch (const std::exception&) { cemuLog_log(LogType::Force, "config load error: can't load input device: {}", input_device_name); } // account auto acc = parser.get("Account"); account.m_persistent_id = acc.get("PersistentId", account.m_persistent_id); // legacy online settings, we only parse these for upgrading purposes account.legacy_online_enabled = acc.get("OnlineEnabled", account.legacy_online_enabled); account.legacy_active_service = acc.get("ActiveService",account.legacy_active_service); // per-account online setting auto accService = parser.get("AccountService"); account.service_select.clear(); for (auto element = accService.get("SelectedService"); element.valid(); element = accService.get("SelectedService", element)) { uint32 persistentId = element.get_attribute<uint32>("PersistentId", 0); sint32 serviceIndex = element.get_attribute<sint32>("Service", 0); NetworkService networkService = static_cast<NetworkService>(serviceIndex); if (persistentId < Account::kMinPersistendId) continue; if(networkService == NetworkService::Offline || networkService == NetworkService::Nintendo || networkService == NetworkService::Pretendo || networkService == NetworkService::Custom) account.service_select.emplace(persistentId, networkService); } // debug auto debug = parser.get("Debug"); #if BOOST_OS_WINDOWS crash_dump = debug.get("CrashDumpWindows", crash_dump); #elif BOOST_OS_UNIX crash_dump = debug.get("CrashDumpUnix", crash_dump); #endif gdb_port = debug.get("GDBPort", 1337); // input auto input = parser.get("Input"); auto dsuc = input.get("DSUC"); dsu_client.host = dsuc.get_attribute("host", dsu_client.host); dsu_client.port = dsuc.get_attribute("port", dsu_client.port); // emulatedusbdevices auto usbdevices = parser.get("EmulatedUsbDevices"); emulated_usb_devices.emulate_skylander_portal = usbdevices.get("EmulateSkylanderPortal", emulated_usb_devices.emulate_skylander_portal); emulated_usb_devices.emulate_infinity_base = usbdevices.get("EmulateInfinityBase", emulated_usb_devices.emulate_infinity_base); emulated_usb_devices.emulate_dimensions_toypad = usbdevices.get("EmulateDimensionsToypad", emulated_usb_devices.emulate_dimensions_toypad); } void CemuConfig::Save(XMLConfigParser& parser) { auto config = parser.set("content"); // general settings config.set("logflag", log_flag.GetValue()); config.set("advanced_ppc_logging", advanced_ppc_logging.GetValue()); config.set("mlc_path", mlc_path.GetValue().c_str()); config.set<bool>("permanent_storage", permanent_storage); config.set<sint32>("language", language); config.set<bool>("use_discord_presence", use_discord_presence); config.set<bool>("fullscreen_menubar", fullscreen_menubar); config.set<bool>("feral_gamemode", feral_gamemode); config.set<bool>("check_update", check_update); config.set<bool>("receive_untested_updates", receive_untested_updates); config.set<bool>("save_screenshot", save_screenshot); config.set<bool>("vk_warning", did_show_vulkan_warning); config.set<bool>("gp_download", did_show_graphic_pack_download); config.set<bool>("macos_disclaimer", did_show_macos_disclaimer); config.set<bool>("fullscreen", fullscreen); config.set("proxy_server", proxy_server.GetValue().c_str()); config.set<bool>("disable_screensaver", disable_screensaver); // config.set("cpu_mode", cpu_mode.GetValue()); //config.set("console_region", console_region.GetValue()); config.set("console_language", console_language.GetValue()); auto wpos = config.set("window_position"); wpos.set<sint32>("x", window_position.x); wpos.set<sint32>("y", window_position.y); auto wsize = config.set("window_size"); wsize.set<sint32>("x", window_size.x); wsize.set<sint32>("y", window_size.y); config.set<bool>("window_maximized", window_maximized); config.set<bool>("open_pad", pad_open); auto ppos = config.set("pad_position"); ppos.set<sint32>("x", pad_position.x); ppos.set<sint32>("y", pad_position.y); auto psize = config.set("pad_size"); psize.set<sint32>("x", pad_size.x); psize.set<sint32>("y", pad_size.y); config.set<bool>("pad_maximized", pad_maximized); config.set<bool>("show_icon_column" , show_icon_column); auto gamelist = config.set("GameList"); gamelist.set("style", game_list_style); gamelist.set("order", game_list_column_order); gamelist.set("name_width", column_width.name); gamelist.set("version_width", column_width.version); gamelist.set("dlc_width", column_width.dlc); gamelist.set("game_time_width", column_width.game_time); gamelist.set("game_started_width", column_width.game_started); gamelist.set("region_width", column_width.region); gamelist.set("title_id", column_width.title_id); auto launch_files_parser = config.set("RecentLaunchFiles"); for (const auto& entry : recent_launch_files) { launch_files_parser.set("Entry", entry.c_str()); } auto nfc_files_parser = config.set("RecentNFCFiles"); for (const auto& entry : recent_nfc_files) { nfc_files_parser.set("Entry", entry.c_str()); } // game paths auto game_path_parser = config.set("GamePaths"); for (const auto& entry : game_paths) { game_path_parser.set("Entry", entry.c_str()); } // game list cache std::unique_lock _lock(game_cache_entries_mutex); auto game_cache_parser = config.set("GameCache"); for (const auto& game : game_cache_entries) { auto entry = game_cache_parser.set("Entry"); entry.set("title_id", (sint64)game.title_id); entry.set("name", boost::nowide::narrow(game.legacy_name).c_str()); entry.set("custom_name", game.custom_name.c_str()); entry.set("region", (sint32)game.legacy_region); entry.set("version", (sint32)game.legacy_update_version); entry.set("dlc_version", (sint32)game.legacy_dlc_version); entry.set("path", boost::nowide::narrow(game.rpx_file).c_str()); entry.set("time_played", game.legacy_time_played); entry.set("last_played", game.legacy_last_played); entry.set("favorite", game.favorite); } _lock.unlock(); auto graphic_pack_parser = config.set("GraphicPack"); for (const auto& game : graphic_pack_entries) { auto entry = graphic_pack_parser.set("Entry"); entry.set_attribute("filename",_pathToUtf8(game.first).c_str()); for(const auto& kv : game.second) { // TODO: less hacky pls if(boost::iequals(kv.first, "_disabled")) { entry.set_attribute("disabled", true); continue; } auto preset = entry.set("Preset"); if(!kv.first.empty()) preset.set("category", kv.first.c_str()); preset.set("preset", kv.second.c_str()); } } // graphics auto graphic = config.set("Graphic"); graphic.set("api", graphic_api); graphic.set("device", graphic_device_uuid); graphic.set("VSync", vsync); graphic.set("GX2DrawdoneSync", gx2drawdone_sync); //graphic.set("PrecompiledShaders", precompiled_shaders.GetValue()); graphic.set("UpscaleFilter", upscale_filter); graphic.set("DownscaleFilter", downscale_filter); graphic.set("FullscreenScaling", fullscreen_scaling); graphic.set("AsyncCompile", async_compile.GetValue()); graphic.set("vkAccurateBarriers", vk_accurate_barriers); auto overlay_node = graphic.set("Overlay"); overlay_node.set("Position", overlay.position); overlay_node.set("TextColor", overlay.text_color); overlay_node.set("TextScale", overlay.text_scale); overlay_node.set("FPS", overlay.fps); overlay_node.set("DrawCalls", overlay.drawcalls); overlay_node.set("CPUUsage", overlay.cpu_usage); overlay_node.set("CPUPerCoreUsage", overlay.cpu_per_core_usage); overlay_node.set("RAMUsage", overlay.ram_usage); overlay_node.set("VRAMUsage", overlay.vram_usage); overlay_node.set("Debug", overlay.debug); auto notification_node = graphic.set("Notification"); notification_node.set("Position", notification.position); notification_node.set("TextColor", notification.text_color); notification_node.set("TextScale", notification.text_scale); notification_node.set("ControllerProfiles", notification.controller_profiles); notification_node.set("ControllerBattery", notification.controller_battery); notification_node.set("ShaderCompiling", notification.shader_compiling); notification_node.set("FriendService", notification.friends); // audio auto audio = config.set("Audio"); audio.set("api", audio_api); audio.set("delay", audio_delay); audio.set("TVChannels", tv_channels); audio.set("PadChannels", pad_channels); audio.set("InputChannels", input_channels); audio.set("TVVolume", tv_volume); audio.set("PadVolume", pad_volume); audio.set("InputVolume", input_volume); audio.set("TVDevice", boost::nowide::narrow(tv_device).c_str()); audio.set("PadDevice", boost::nowide::narrow(pad_device).c_str()); audio.set("InputDevice", boost::nowide::narrow(input_device).c_str()); // account auto acc = config.set("Account"); acc.set("PersistentId", account.m_persistent_id.GetValue()); // legacy online mode setting acc.set("OnlineEnabled", account.legacy_online_enabled.GetValue()); acc.set("ActiveService",account.legacy_active_service.GetValue()); // per-account online setting auto accService = config.set("AccountService"); for(auto& it : account.service_select) { auto entry = accService.set("SelectedService"); entry.set_attribute("PersistentId", it.first); entry.set_attribute("Service", static_cast<sint32>(it.second)); } // debug auto debug = config.set("Debug"); #if BOOST_OS_WINDOWS debug.set("CrashDumpWindows", crash_dump.GetValue()); #elif BOOST_OS_UNIX debug.set("CrashDumpUnix", crash_dump.GetValue()); #endif debug.set("GDBPort", gdb_port); // input auto input = config.set("Input"); auto dsuc = input.set("DSUC"); dsuc.set_attribute("host", dsu_client.host); dsuc.set_attribute("port", dsu_client.port); // emulated usb devices auto usbdevices = config.set("EmulatedUsbDevices"); usbdevices.set("EmulateSkylanderPortal", emulated_usb_devices.emulate_skylander_portal.GetValue()); usbdevices.set("EmulateInfinityBase", emulated_usb_devices.emulate_infinity_base.GetValue()); usbdevices.set("EmulateDimensionsToypad", emulated_usb_devices.emulate_dimensions_toypad.GetValue()); } GameEntry* CemuConfig::GetGameEntryByTitleId(uint64 titleId) { // assumes game_cache_entries_mutex is already held for (auto& it : game_cache_entries) { if (it.title_id == titleId) return &it; } return nullptr; } GameEntry* CemuConfig::CreateGameEntry(uint64 titleId) { // assumes game_cache_entries_mutex is already held GameEntry gameEntry; gameEntry.title_id = titleId; game_cache_entries.emplace_back(gameEntry); return &game_cache_entries.back(); } bool CemuConfig::IsGameListFavorite(uint64 titleId) { std::unique_lock _lock(game_cache_entries_mutex); return game_cache_favorites.find(titleId) != game_cache_favorites.end(); } void CemuConfig::SetGameListFavorite(uint64 titleId, bool isFavorite) { std::unique_lock _lock(game_cache_entries_mutex); GameEntry* gameEntry = GetGameEntryByTitleId(titleId); if (!gameEntry) gameEntry = CreateGameEntry(titleId); gameEntry->favorite = isFavorite; if (isFavorite) game_cache_favorites.emplace(titleId); else game_cache_favorites.erase(titleId); } bool CemuConfig::GetGameListCustomName(uint64 titleId, std::string& customName) { std::unique_lock _lock(game_cache_entries_mutex); GameEntry* gameEntry = GetGameEntryByTitleId(titleId); if (gameEntry && !gameEntry->custom_name.empty()) { customName = gameEntry->custom_name; return true; } return false; } void CemuConfig::SetGameListCustomName(uint64 titleId, std::string customName) { std::unique_lock _lock(game_cache_entries_mutex); GameEntry* gameEntry = GetGameEntryByTitleId(titleId); if (!gameEntry) { if (customName.empty()) return; gameEntry = CreateGameEntry(titleId); } gameEntry->custom_name = std::move(customName); } void CemuConfig::AddRecentlyLaunchedFile(std::string_view file) { recent_launch_files.insert(recent_launch_files.begin(), std::string(file)); RemoveDuplicatesKeepOrder(recent_launch_files); while(recent_launch_files.size() > kMaxRecentEntries) recent_launch_files.pop_back(); } void CemuConfig::AddRecentNfcFile(std::string_view file) { recent_nfc_files.insert(recent_nfc_files.begin(), std::string(file)); RemoveDuplicatesKeepOrder(recent_nfc_files); while (recent_nfc_files.size() > kMaxRecentEntries) recent_nfc_files.pop_back(); } NetworkService CemuConfig::GetAccountNetworkService(uint32 persistentId) { auto it = account.service_select.find(persistentId); if (it != account.service_select.end()) { NetworkService serviceIndex = it->second; // make sure the returned service is valid if (serviceIndex != NetworkService::Offline && serviceIndex != NetworkService::Nintendo && serviceIndex != NetworkService::Pretendo && serviceIndex != NetworkService::Custom) return NetworkService::Offline; if( static_cast<NetworkService>(serviceIndex) == NetworkService::Custom && !NetworkConfig::XMLExists() ) return NetworkService::Offline; // custom is selected but no custom config exists return serviceIndex; } // if not found, return the legacy value if(!account.legacy_online_enabled) return NetworkService::Offline; return static_cast<NetworkService>(account.legacy_active_service.GetValue() + 1); // +1 because "Offline" now takes index 0 } void CemuConfig::SetAccountSelectedService(uint32 persistentId, NetworkService serviceIndex) { account.service_select[persistentId] = serviceIndex; }
25,073
C++
.cpp
588
40.098639
195
0.739334
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,964
CemuApp.cpp
cemu-project_Cemu/src/gui/CemuApp.cpp
#include "gui/CemuApp.h" #include "gui/MainWindow.h" #include "gui/wxgui.h" #include "config/CemuConfig.h" #include "Cafe/HW/Latte/Renderer/Vulkan/VulkanAPI.h" #include "Cafe/HW/Latte/Core/LatteOverlay.h" #include "gui/guiWrapper.h" #include "config/ActiveSettings.h" #include "config/LaunchSettings.h" #include "gui/GettingStartedDialog.h" #include "input/InputManager.h" #include "gui/helpers/wxHelpers.h" #include "Cemu/ncrypto/ncrypto.h" #if BOOST_OS_LINUX && HAS_WAYLAND #include "gui/helpers/wxWayland.h" #endif #if __WXGTK__ #include <glib.h> #endif #include <wx/image.h> #include <wx/filename.h> #include <wx/stdpaths.h> #include "wxHelper.h" #include "Cafe/TitleList/TitleList.h" #include "Cafe/TitleList/SaveList.h" wxIMPLEMENT_APP_NO_MAIN(CemuApp); // defined in guiWrapper.cpp extern WindowInfo g_window_info; extern std::shared_mutex g_mutex; // forward declarations from main.cpp void UnitTests(); void CemuCommonInit(); void HandlePostUpdate(); // Translation strings to extract for gettext: void unused_translation_dummy() { void(_("Browse")); void(_("Select a file")); void(_("Select a directory")); void(_("Japanese")); void(_("English")); void(_("French")); void(_("German")); void(_("Italian")); void(_("Spanish")); void(_("Chinese")); void(_("Korean")); void(_("Dutch")); void(_("Portugese")); void(_("Russian")); void(_("Taiwanese")); void(_("unknown")); } #if BOOST_OS_WINDOWS #include <shlobj_core.h> fs::path GetAppDataRoamingPath() { PWSTR path = nullptr; HRESULT result = SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &path); if (result != S_OK || !path) { if (path) CoTaskMemFree(path); return {}; } std::string appDataPath = boost::nowide::narrow(path); CoTaskMemFree(path); return _utf8ToPath(appDataPath); } #endif #if BOOST_OS_WINDOWS void CemuApp::DeterminePaths(std::set<fs::path>& failedWriteAccess) // for Windows { std::error_code ec; bool isPortable = false; fs::path user_data_path, config_path, cache_path, data_path; auto standardPaths = wxStandardPaths::Get(); fs::path exePath(wxHelper::MakeFSPath(standardPaths.GetExecutablePath())); fs::path portablePath = exePath.parent_path() / "portable"; data_path = exePath.parent_path(); // the data path is always the same as the exe path if (fs::exists(portablePath, ec)) { isPortable = true; user_data_path = config_path = cache_path = portablePath; } else { fs::path roamingPath = GetAppDataRoamingPath() / "Cemu"; user_data_path = config_path = cache_path = roamingPath; } // on Windows Cemu used to be portable by default prior to 2.0-89 // to remain backwards compatible with old installations we check for settings.xml in the Cemu directory // if it exists, we use the exe path as the portable directory if(!isPortable) // lower priority than portable directory { if (fs::exists(exePath.parent_path() / "settings.xml", ec)) { isPortable = true; user_data_path = config_path = cache_path = exePath.parent_path(); } } ActiveSettings::SetPaths(isPortable, exePath, user_data_path, config_path, cache_path, data_path, failedWriteAccess); } #endif #if BOOST_OS_LINUX void CemuApp::DeterminePaths(std::set<fs::path>& failedWriteAccess) // for Linux { std::error_code ec; bool isPortable = false; fs::path user_data_path, config_path, cache_path, data_path; auto standardPaths = wxStandardPaths::Get(); fs::path exePath(wxHelper::MakeFSPath(standardPaths.GetExecutablePath())); fs::path portablePath = exePath.parent_path() / "portable"; // GetExecutablePath returns the AppImage's temporary mount location wxString appImagePath; if (wxGetEnv(("APPIMAGE"), &appImagePath)) { exePath = wxHelper::MakeFSPath(appImagePath); portablePath = exePath.parent_path() / "portable"; } if (fs::exists(portablePath, ec)) { isPortable = true; user_data_path = config_path = cache_path = portablePath; // in portable mode assume the data directories (resources, gameProfiles/default/) are next to the executable data_path = exePath.parent_path(); } else { SetAppName("Cemu"); wxString appName = GetAppName(); standardPaths.SetFileLayout(wxStandardPaths::FileLayout::FileLayout_XDG); auto getEnvDir = [&](const wxString& varName, const wxString& defaultValue) { wxString dir; if (!wxGetEnv(varName, &dir) || dir.empty()) return defaultValue; return dir; }; wxString homeDir = wxFileName::GetHomeDir(); user_data_path = (getEnvDir(wxS("XDG_DATA_HOME"), homeDir + wxS("/.local/share")) + "/" + appName).ToStdString(); config_path = (getEnvDir(wxS("XDG_CONFIG_HOME"), homeDir + wxS("/.config")) + "/" + appName).ToStdString(); data_path = standardPaths.GetDataDir().ToStdString(); cache_path = standardPaths.GetUserDir(wxStandardPaths::Dir::Dir_Cache).ToStdString(); cache_path /= appName.ToStdString(); } ActiveSettings::SetPaths(isPortable, exePath, user_data_path, config_path, cache_path, data_path, failedWriteAccess); } #endif #if BOOST_OS_MACOS void CemuApp::DeterminePaths(std::set<fs::path>& failedWriteAccess) // for MacOS { std::error_code ec; bool isPortable = false; fs::path user_data_path, config_path, cache_path, data_path; auto standardPaths = wxStandardPaths::Get(); fs::path exePath(wxHelper::MakeFSPath(standardPaths.GetExecutablePath())); // If run from an app bundle, use its parent directory fs::path appPath = exePath.parent_path().parent_path().parent_path(); fs::path portablePath = appPath.extension() == ".app" ? appPath.parent_path() / "portable" : exePath.parent_path() / "portable"; if (fs::exists(portablePath, ec)) { isPortable = true; user_data_path = config_path = cache_path = portablePath; data_path = exePath.parent_path(); } else { SetAppName("Cemu"); wxString appName = GetAppName(); user_data_path = config_path = standardPaths.GetUserDataDir().ToStdString(); data_path = standardPaths.GetDataDir().ToStdString(); cache_path = standardPaths.GetUserDir(wxStandardPaths::Dir::Dir_Cache).ToStdString(); cache_path /= appName.ToStdString(); } ActiveSettings::SetPaths(isPortable, exePath, user_data_path, config_path, cache_path, data_path, failedWriteAccess); } #endif // create default MLC files or quit if it fails void CemuApp::InitializeNewMLCOrFail(fs::path mlc) { if( CemuApp::CreateDefaultMLCFiles(mlc) ) return; // all good cemu_assert_debug(!ActiveSettings::IsCustomMlcPath()); // should not be possible? if(ActiveSettings::IsCommandLineMlcPath() || ActiveSettings::IsCustomMlcPath()) { // tell user that the custom path is not writable wxMessageBox(formatWxString(_("Cemu failed to write to the custom mlc directory.\nThe path is:\n{}"), wxHelper::FromPath(mlc)), _("Error"), wxOK | wxCENTRE | wxICON_ERROR); exit(0); } wxMessageBox(formatWxString(_("Cemu failed to write to the mlc directory.\nThe path is:\n{}"), wxHelper::FromPath(mlc)), _("Error"), wxOK | wxCENTRE | wxICON_ERROR); exit(0); } void CemuApp::InitializeExistingMLCOrFail(fs::path mlc) { if(CreateDefaultMLCFiles(mlc)) return; // all good // failed to write mlc files if(ActiveSettings::IsCommandLineMlcPath() || ActiveSettings::IsCustomMlcPath()) { // tell user that the custom path is not writable // if it's a command line path then just quit. Otherwise ask if user wants to reset the path if(ActiveSettings::IsCommandLineMlcPath()) { wxMessageBox(formatWxString(_("Cemu failed to write to the custom mlc directory.\nThe path is:\n{}"), wxHelper::FromPath(mlc)), _("Error"), wxOK | wxCENTRE | wxICON_ERROR); exit(0); } // ask user if they want to reset the path const wxString message = formatWxString(_("Cemu failed to write to the custom mlc directory.\n\nThe path is:\n{}\n\nCemu cannot start without a valid mlc path. Do you want to reset the path? You can later change it again in the General Settings."), _pathToUtf8(mlc)); wxMessageDialog dialog(nullptr, message, _("Error"), wxCENTRE | wxYES_NO | wxICON_WARNING); dialog.SetYesNoLabels(_("Reset path"), _("Exit")); const auto dialogResult = dialog.ShowModal(); if (dialogResult == wxID_NO) exit(0); else // reset path { GetConfig().mlc_path = ""; g_config.Save(); } } } bool CemuApp::OnInit() { #if __WXGTK__ GTKSuppressDiagnostics(G_LOG_LEVEL_MASK & ~G_LOG_FLAG_FATAL); #endif std::set<fs::path> failedWriteAccess; DeterminePaths(failedWriteAccess); // make sure default cemu directories exist CreateDefaultCemuFiles(); g_config.SetFilename(ActiveSettings::GetConfigPath("settings.xml").generic_wstring()); std::error_code ec; bool isFirstStart = !fs::exists(ActiveSettings::GetConfigPath("settings.xml"), ec); NetworkConfig::LoadOnce(); if(!isFirstStart) { g_config.Load(); LocalizeUI(static_cast<wxLanguage>(GetConfig().language == wxLANGUAGE_DEFAULT ? wxLocale::GetSystemLanguage() : GetConfig().language.GetValue())); } else { LocalizeUI(static_cast<wxLanguage>(wxLocale::GetSystemLanguage())); } for (auto&& path : failedWriteAccess) { wxMessageBox(formatWxString(_("Cemu can't write to {}!"), wxString::FromUTF8(_pathToUtf8(path))), _("Warning"), wxOK | wxCENTRE | wxICON_EXCLAMATION, nullptr); } if (isFirstStart) { // show the getting started dialog GettingStartedDialog dia(nullptr); dia.ShowModal(); // make sure config is created. Gfx pack UI and input UI may create it earlier already, but we still want to update it g_config.Save(); // create mlc, on failure the user can quit here. So do this after the Getting Started dialog InitializeNewMLCOrFail(ActiveSettings::GetMlcPath()); } else { // check if mlc is valid and recreate default files InitializeExistingMLCOrFail(ActiveSettings::GetMlcPath()); } ActiveSettings::Init(); // this is a bit of a misnomer, right now this call only loads certs for online play. In the future we should move the logic to a more appropriate place HandlePostUpdate(); LatteOverlay_init(); // run a couple of tests if in non-release mode #ifdef CEMU_DEBUG_ASSERT UnitTests(); #endif CemuCommonInit(); wxInitAllImageHandlers(); // fill colour db wxTheColourDatabase->AddColour("ERROR", wxColour(0xCC, 0, 0)); wxTheColourDatabase->AddColour("SUCCESS", wxColour(0, 0xbb, 0)); #if BOOST_OS_WINDOWS const auto parent_path = GetParentProcess(); if(parent_path.has_filename()) { const auto filename = parent_path.filename().generic_string(); if (boost::icontains(filename, "WiiU_USB_Helper")) __fastfail(0); } #endif InitializeGlobalVulkan(); Bind(wxEVT_ACTIVATE_APP, &CemuApp::ActivateApp, this); auto& config = GetConfig(); m_mainFrame = new MainWindow(); std::unique_lock lock(g_mutex); g_window_info.app_active = true; SetTopWindow(m_mainFrame); m_mainFrame->Show(); #if BOOST_OS_LINUX && HAS_WAYLAND if (wxWlIsWaylandWindow(m_mainFrame)) wxWlSetAppId(m_mainFrame, "info.cemu.Cemu"); #endif // show warning on macOS about state of builds #if BOOST_OS_MACOS if (!GetConfig().did_show_macos_disclaimer) { const auto message = _( "Thank you for testing the in-development build of Cemu for macOS.\n \n" "The macOS port is currently purely experimental and should not be considered stable or ready for issue-free gameplay. " "There are also known issues with degraded performance due to the use of MoltenVk and Rosetta for ARM Macs. We appreciate your patience while we improve Cemu for macOS."); wxMessageDialog dialog(nullptr, message, _("Preview version"), wxCENTRE | wxOK | wxICON_WARNING); dialog.SetOKLabel(_("I understand")); dialog.ShowModal(); GetConfig().did_show_macos_disclaimer = true; g_config.Save(); } #endif return true; } int CemuApp::OnExit() { wxApp::OnExit(); #if BOOST_OS_WINDOWS ExitProcess(0); #else _Exit(0); #endif } #if BOOST_OS_WINDOWS void DumpThreadStackTrace(); #endif void CemuApp::OnAssertFailure(const wxChar* file, int line, const wxChar* func, const wxChar* cond, const wxChar* msg) { cemuLog_createLogFile(false); cemuLog_log(LogType::Force, "Encountered wxWidgets assert!"); cemuLog_log(LogType::Force, "File: {0} Line: {1}", wxString(file).utf8_string(), line); cemuLog_log(LogType::Force, "Func: {0} Cond: {1}", wxString(func).utf8_string(), wxString(cond).utf8_string()); cemuLog_log(LogType::Force, "Message: {}", wxString(msg).utf8_string()); #if BOOST_OS_WINDOWS DumpThreadStackTrace(); #endif cemu_assert_debug(false); } int CemuApp::FilterEvent(wxEvent& event) { if(event.GetEventType() == wxEVT_KEY_DOWN) { const auto& key_event = (wxKeyEvent&)event; g_window_info.set_keystate(fix_raw_keycode(key_event.GetRawKeyCode(), key_event.GetRawKeyFlags()), true); } else if(event.GetEventType() == wxEVT_KEY_UP) { const auto& key_event = (wxKeyEvent&)event; g_window_info.set_keystate(fix_raw_keycode(key_event.GetRawKeyCode(), key_event.GetRawKeyFlags()), false); } else if(event.GetEventType() == wxEVT_ACTIVATE_APP) { const auto& activate_event = (wxActivateEvent&)event; if(!activate_event.GetActive()) g_window_info.set_keystatesup(); } return wxApp::FilterEvent(event); } std::vector<const wxLanguageInfo *> CemuApp::GetLanguages() const { std::vector availableLanguages(m_availableTranslations); availableLanguages.insert(availableLanguages.begin(), wxLocale::GetLanguageInfo(wxLANGUAGE_ENGLISH)); return availableLanguages; } void CemuApp::LocalizeUI(wxLanguage languageToUse) { std::unique_ptr<wxTranslations> translationsMgr(new wxTranslations()); m_availableTranslations = GetAvailableTranslationLanguages(translationsMgr.get()); bool isTranslationAvailable = std::any_of(m_availableTranslations.begin(), m_availableTranslations.end(), [languageToUse](const wxLanguageInfo* info) { return info->Language == languageToUse; }); if (languageToUse == wxLANGUAGE_DEFAULT || isTranslationAvailable) { translationsMgr->SetLanguage(static_cast<wxLanguage>(languageToUse)); translationsMgr->AddCatalog("cemu"); if (translationsMgr->IsLoaded("cemu") && wxLocale::IsAvailable(languageToUse)) { m_locale.Init(languageToUse); } // This must be run after wxLocale::Init, as the latter sets up its own wxTranslations instance which we want to override wxTranslations::Set(translationsMgr.release()); } } std::vector<const wxLanguageInfo*> CemuApp::GetAvailableTranslationLanguages(wxTranslations* translationsMgr) { wxFileTranslationsLoader::AddCatalogLookupPathPrefix(wxHelper::FromPath(ActiveSettings::GetDataPath("resources"))); std::vector<const wxLanguageInfo*> languages; for (const auto& langName : translationsMgr->GetAvailableTranslations("cemu")) { const auto* langInfo = wxLocale::FindLanguageInfo(langName); if (langInfo) languages.emplace_back(langInfo); } return languages; } bool CemuApp::CheckMLCPath(const fs::path& mlc) { std::error_code ec; if (!fs::exists(mlc, ec)) return false; if (!fs::exists(mlc / "usr", ec) || !fs::exists(mlc / "sys", ec)) return false; return true; } bool CemuApp::CreateDefaultMLCFiles(const fs::path& mlc) { auto CreateDirectoriesIfNotExist = [](const fs::path& path) { std::error_code ec; if (!fs::exists(path, ec)) return fs::create_directories(path, ec); return true; }; // list of directories to create const fs::path directories[] = { mlc, mlc / "sys", mlc / "usr", mlc / "usr/title/00050000", // base mlc / "usr/title/0005000c", // dlc mlc / "usr/title/0005000e", // update mlc / "usr/save/00050010/1004a000/user/common/db", // Mii Maker save folders {0x500101004A000, 0x500101004A100, 0x500101004A200} mlc / "usr/save/00050010/1004a100/user/common/db", mlc / "usr/save/00050010/1004a200/user/common/db", mlc / "sys/title/0005001b/1005c000/content" // lang files }; for(auto& path : directories) { if(!CreateDirectoriesIfNotExist(path)) return false; } // create sys/usr folder in mlc01 try { const auto langDir = fs::path(mlc).append("sys/title/0005001b/1005c000/content"); auto langFile = fs::path(langDir).append("language.txt"); if (!fs::exists(langFile)) { std::ofstream file(langFile); if (file.is_open()) { const char* langStrings[] = { "ja","en","fr","de","it","es","zh","ko","nl","pt","ru","zh" }; for (const char* lang : langStrings) file << fmt::format(R"("{}",)", lang) << std::endl; file.flush(); file.close(); } } auto countryFile = fs::path(langDir).append("country.txt"); if (!fs::exists(countryFile)) { std::ofstream file(countryFile); for (sint32 i = 0; i < NCrypto::GetCountryCount(); i++) { const char* countryCode = NCrypto::GetCountryAsString(i); if (boost::iequals(countryCode, "NN")) file << "NULL," << std::endl; else file << fmt::format(R"("{}",)", countryCode) << std::endl; } file.flush(); file.close(); } } catch (const std::exception& ex) { return false; } return true; } void CemuApp::CreateDefaultCemuFiles() { // cemu directories try { const auto controllerProfileFolder = ActiveSettings::GetConfigPath("controllerProfiles"); if (!fs::exists(controllerProfileFolder)) fs::create_directories(controllerProfileFolder); const auto memorySearcherFolder = ActiveSettings::GetUserDataPath("memorySearcher"); if (!fs::exists(memorySearcherFolder)) fs::create_directories(memorySearcherFolder); } catch (const std::exception& ex) { wxString errorMsg = formatWxString(_("Couldn't create a required cemu directory or file!\n\nError: {0}"), ex.what()); #if BOOST_OS_WINDOWS const DWORD lastError = GetLastError(); if (lastError != ERROR_SUCCESS) errorMsg << fmt::format("\n\n{}", GetSystemErrorMessage(lastError)); #endif wxMessageBox(errorMsg, _("Error"), wxOK | wxCENTRE | wxICON_ERROR); exit(0); } } void CemuApp::ActivateApp(wxActivateEvent& event) { g_window_info.app_active = event.GetActive(); event.Skip(); }
17,834
C++
.cpp
497
33.448692
250
0.733885
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,965
ChecksumTool.cpp
cemu-project_Cemu/src/gui/ChecksumTool.cpp
#include "gui/ChecksumTool.h" #include "Cafe/TitleList/GameInfo.h" #include "gui/helpers/wxCustomEvents.h" #include "util/helpers/helpers.h" #include "gui/helpers/wxHelpers.h" #include "gui/wxHelper.h" #include "Cafe/Filesystem/WUD/wud.h" #include <zip.h> #include <curl/curl.h> #include <openssl/evp.h> /* EVP_Digest */ #include <openssl/sha.h> /* SHA256_DIGEST_LENGTH */ #include <rapidjson/document.h> #include <rapidjson/istreamwrapper.h> #include <rapidjson/ostreamwrapper.h> #include <rapidjson/prettywriter.h> #include <rapidjson/schema.h> #include <wx/frame.h> #include <wx/translation.h> #include <wx/xrc/xmlres.h> #include <wx/gauge.h> #include <wx/gdicmn.h> #include <wx/string.h> #include <wx/sizer.h> #include <wx/statbox.h> #include <wx/stattext.h> #include <wx/button.h> #include <wx/filedlg.h> #include <wx/dirdlg.h> #include <wx/msgdlg.h> #include "config/ActiveSettings.h" #include "Cafe/TitleList/TitleList.h" const char kSchema[] = R"( { "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { "title_id": { "type": "string" }, "region": { "type": "integer" }, "version": { "type": "integer" }, "wud_hash": { "type": "string" }, "files": { "type": "array", "items": { "type": "object", "properties": { "file": { "type": "string" }, "hash": { "type": "string" } }, "required": [ "file", "hash" ] } } }, "required": [ "title_id", "region", "version", "files" ] })"; ChecksumTool::ChecksumTool(wxWindow* parent, wxTitleManagerList::TitleEntry& entry) : wxDialog(parent, wxID_ANY, formatWxString(_("Title checksum of {:08x}-{:08x}"), (uint32) (entry.title_id >> 32), (uint32) (entry.title_id & 0xFFFFFFFF)), wxDefaultPosition, wxDefaultSize, wxCAPTION | wxFRAME_TOOL_WINDOW | wxSYSTEM_MENU | wxTAB_TRAVERSAL | wxCLOSE_BOX), m_entry(entry) { m_info = CafeTitleList::GetTitleInfoByUID(m_entry.location_uid); if (!m_info.IsValid()) throw std::runtime_error("Invalid title"); // only request online update once static bool s_once = false; if (!s_once) { s_once = true; m_online_ready = std::async(std::launch::async, &ChecksumTool::LoadOnlineData, this); } else m_enable_verify_button = 1; auto* sizer = new wxBoxSizer(wxVERTICAL); { auto* box_sizer = new wxStaticBoxSizer(new wxStaticBox(this, wxID_ANY, _("Verifying integrity of game files...")), wxVERTICAL); auto* box = box_sizer->GetStaticBox(); m_progress = new wxGauge(box, wxID_ANY, 100, wxDefaultPosition, wxDefaultSize, wxGA_HORIZONTAL | wxGA_SMOOTH); m_progress->SetMinSize({ 400, -1 }); m_progress->SetValue(0); box_sizer->Add(m_progress, 0, wxALL | wxEXPAND, 5); m_status = new wxStaticText(box, wxID_ANY, wxEmptyString); m_status->Wrap(-1); box_sizer->Add(m_status, 0, wxLEFT | wxRIGHT | wxBOTTOM | wxEXPAND, 5); sizer->Add(box_sizer, 0, wxEXPAND | wxALL, 5); } { auto* box_sizer = new wxStaticBoxSizer(new wxStaticBox(this, wxID_ANY, _("Control")), wxHORIZONTAL); auto* box = box_sizer->GetStaticBox(); m_verify_online = new wxButton(box, wxID_ANY, _("Verify online")); m_verify_online->SetToolTip(_("Verifies the checksum online")); m_verify_online->Disable(); m_verify_online->Bind(wxEVT_BUTTON, &ChecksumTool::OnVerifyOnline, this); m_verify_online->Bind(wxEVT_ENABLE, [this](wxCommandEvent&) { ++m_enable_verify_button; if (m_enable_verify_button >= 2) { // only enable if we have a file for it const auto title_id_str = fmt::format("{:016x}", m_json_entry.title_id); const auto default_file = fmt::format("{}_v{}.json", title_id_str, m_info.GetAppTitleVersion()); const auto checksum_path = ActiveSettings::GetUserDataPath("resources/checksums/{}", default_file); if (exists(checksum_path)) m_verify_online->Enable(); } }); box_sizer->Add(m_verify_online, 0, wxALL | wxEXPAND, 5); m_verify_local = new wxButton(box, wxID_ANY, _("Verify with local file")); m_verify_online->SetToolTip(_("Verifies the checksum with a local JSON file you can select")); m_verify_local->Disable(); m_verify_local->Bind(wxEVT_BUTTON, &ChecksumTool::OnVerifyLocal, this); box_sizer->Add(m_verify_local, 0, wxALL | wxEXPAND, 5); m_export_button = new wxButton(box, wxID_ANY, _("Export")); m_verify_online->SetToolTip(_("Export the title checksum data to a local JSON file")); m_export_button->Disable(); m_export_button->Bind(wxEVT_BUTTON, &ChecksumTool::OnExportChecksums, this); box_sizer->Add(m_export_button, 0, wxALL | wxEXPAND, 5); sizer->Add(box_sizer, 0, wxEXPAND | wxALL, 5); } this->Bind(wxEVT_SET_GAUGE_VALUE, &ChecksumTool::OnSetGaugevalue, this); m_worker = std::thread(&ChecksumTool::DoWork, this); this->SetSizerAndFit(sizer); this->Centre(wxBOTH); } ChecksumTool::~ChecksumTool() { m_running = false; if (m_worker.joinable()) m_worker.join(); } std::size_t WriteCallback(const char* in, std::size_t size, std::size_t num, std::string* out) { const std::size_t totalBytes(size * num); out->append(in, totalBytes); return totalBytes; } void ChecksumTool::LoadOnlineData() const { try { bool updated_required = true; std::string latest_commit; const auto checksum_path = ActiveSettings::GetUserDataPath("resources/checksums"); if (exists(checksum_path)) { std::string current_commit; // check for current version std::ifstream file(checksum_path / "commit.txt"); if (file.is_open()) { std::getline(file, current_commit); file.close(); } // check latest version /* https://api.github.com/repos/teamcemu/title-checksums/branches/master https://api.github.com/repos/teamcemu/title-checksums/commits?per_page=1 */ std::string data; auto* curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, "https://api.github.com/repos/teamcemu/title-checksums/commits/master"); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0); curl_easy_setopt(curl, CURLOPT_USERAGENT, BUILD_VERSION_WITH_NAME_STRING); curl_easy_perform(curl); long http_code = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code); curl_easy_cleanup(curl); if (http_code == 200 && !data.empty()) { rapidjson::Document doc; doc.Parse(data.c_str(), data.size()); if (!doc.HasParseError() && doc.HasMember("sha")) { latest_commit = doc["sha"].GetString(); if (boost::iequals(current_commit, latest_commit)) { updated_required = false; } } } } else { // create directory since not available yet fs::create_directories(checksum_path); } if (updated_required) { std::string data; auto* curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, "https://github.com/TeamCemu/title-checksums/archive/master.zip"); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_USERAGENT, BUILD_VERSION_WITH_NAME_STRING); curl_easy_perform(curl); long http_code = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code); curl_easy_cleanup(curl); if (http_code == 200 && !data.empty()) { // init zip source zip_error_t error; zip_error_init(&error); zip_source_t* src; if ((src = zip_source_buffer_create(data.data(), data.size(), 1, &error)) == nullptr) { zip_error_fini(&error); return; } auto* za = zip_open_from_source(src, ZIP_RDONLY, &error); if (!za) { wxQueueEvent(m_verify_online, new wxCommandEvent(wxEVT_ENABLE)); return; } const auto numEntries = zip_get_num_entries(za, 0); for (sint64 i = 0; i < numEntries; i++) { zip_stat_t sb = { 0 }; if (zip_stat_index(za, i, 0, &sb) != 0) continue; if (std::strstr(sb.name, "../") != nullptr || std::strstr(sb.name, "..\\") != nullptr) continue; // bad path if (boost::equals(sb.name, "title-checksums-master/")) continue; // title-checksums-master/ const auto path = checksum_path / &sb.name[sizeof("title-checksums-master")]; size_t sbNameLen = strlen(sb.name); if (sbNameLen == 0) continue; if (sb.name[sbNameLen - 1] == '/') { std::error_code ec; fs::create_directories(path, ec); continue; } if (sb.size == 0) continue; if (sb.size > (1024 * 1024 * 128)) continue; // skip unusually huge files zip_file_t* zipFile = zip_fopen_index(za, i, 0); if (zipFile == nullptr) continue; std::vector<char> buffer(sb.size); if (zip_fread(zipFile, buffer.data(), sb.size) == sb.size) { std::ofstream file(path); if (file.is_open()) { file.write(buffer.data(), sb.size); file.flush(); file.close(); } } zip_fclose(zipFile); } std::ofstream file(checksum_path / "commit.txt"); if (file.is_open()) { file << latest_commit; file.close(); } } } } catch(const std::exception& ex) { cemuLog_log(LogType::Force, "error on updating json checksum data: {}", ex.what()); } wxQueueEvent(m_verify_online, new wxCommandEvent(wxEVT_ENABLE)); } void ChecksumTool::OnSetGaugevalue(wxSetGaugeValue& event) { event.GetGauge()->SetValue(event.GetValue()); event.GetTextCtrl()->SetLabelText(event.GetText()); // no error if(event.GetInt() == 0 && event.GetValue() == 100) { m_export_button->Enable(); m_verify_local->Enable(); wxPostEvent(m_verify_online, wxCommandEvent(wxEVT_ENABLE)); } } void ChecksumTool::OnExportChecksums(wxCommandEvent& event) { // TODO: merge if json already exists wxDirDialog dialog(this, _("Export checksum entry"), "", wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST); if (dialog.ShowModal() != wxID_OK || dialog.GetPath().IsEmpty()) return; rapidjson::Document doc; doc.SetObject(); auto& a = doc.GetAllocator(); /* title_id region version wud_hash files: [ {file, hash} ] */ auto title_id_str = fmt::format("{:016x}", m_json_entry.title_id); doc.AddMember("title_id", rapidjson::StringRef(title_id_str.c_str(), title_id_str.size()), a); doc.AddMember("region", (int)m_info.GetMetaRegion(), a); doc.AddMember("version", m_info.GetAppTitleVersion(), a); if (!m_json_entry.wud_hash.empty()) doc.AddMember("wud_hash", rapidjson::StringRef(m_json_entry.wud_hash.c_str(), m_json_entry.wud_hash.size()), a); rapidjson::Value entry_array(rapidjson::kArrayType); rapidjson::Value file_array(rapidjson::kArrayType); for(const auto& file : m_json_entry.file_hashes) { rapidjson::Value file_entry; file_entry.SetObject(); file_entry.AddMember("file", rapidjson::StringRef(file.first.c_str(), file.first.size()), a); file_entry.AddMember("hash", rapidjson::StringRef(file.second.c_str(), file.second.size()), a); file_array.PushBack(file_entry, a); } doc.AddMember("files", file_array, a); std::filesystem::path target_file{ dialog.GetPath().c_str().AsInternal() }; target_file /= fmt::format("{}_v{}.json", title_id_str, m_info.GetAppTitleVersion()); std::ofstream file(target_file); if(file.is_open()) { rapidjson::OStreamWrapper osw(file); rapidjson::PrettyWriter<rapidjson::OStreamWrapper> writer(osw); //rapidjson::GenericSchemaValidator<rapidjson::SchemaDocument, rapidjson::Writer<rapidjson::StringBuffer> > validator(schema, writer); doc.Accept(writer); wxMessageBox(_("Export successful"), wxMessageBoxCaptionStr, wxOK | wxCENTRE, this); } else { wxMessageBox(formatWxString(_("Can't write to file: {}"), target_file.string()), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); } } void ChecksumTool::VerifyJsonEntry(const rapidjson::Document& doc) { rapidjson::Document sdoc; sdoc.Parse(kSchema, std::size(kSchema)); wxASSERT(!sdoc.HasParseError()); rapidjson::SchemaDocument schema(sdoc); rapidjson::SchemaValidator validator(schema); if (!doc.Accept(validator)) { //// validation error: //rapidjson::StringBuffer sb; //validator.GetInvalidSchemaPointer().StringifyUriFragment(sb); //printf("Invalid schema: %s\n", sb.GetString()); //printf("Invalid keyword: %s\n", validator.GetInvalidSchemaKeyword()); //sb.Clear(); //validator.GetInvalidDocumentPointer().StringifyUriFragment(sb); //printf("Invalid document: %s\n", sb.GetString()); ///* //Invalid schema: # //Invalid keyword: required //Invalid document: # // */ wxMessageBox(_("JSON file doesn't satisfy needed schema"), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } try { JsonEntry test_entry{}; test_entry.title_id = ConvertString<uint64>(doc["title_id"].GetString(), 16); test_entry.region = (CafeConsoleRegion)doc["region"].GetInt(); test_entry.version = doc["version"].GetInt(); if (doc.HasMember("wud_hash")) test_entry.wud_hash = doc["wud_hash"].GetString(); for (const auto& v : doc["files"].GetArray()) { std::filesystem::path genericFilePath(v["file"].GetString(), std::filesystem::path::generic_format); // convert path to generic form (forward slashes) test_entry.file_hashes[genericFilePath.generic_string()] = v["hash"].GetString(); } if (m_json_entry.title_id != test_entry.title_id) { wxMessageBox(formatWxString(_("The file you are comparing with is for a different title.")), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } if (m_json_entry.version != test_entry.version) { wxMessageBox(formatWxString(_("Wrong version: {}"), test_entry.version), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } if (m_json_entry.region != test_entry.region) { wxMessageBox(formatWxString(_("Wrong region: {}"), test_entry.region), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } if (!m_json_entry.wud_hash.empty()) { if (test_entry.wud_hash.empty()) { wxMessageBox(_("The verification data doesn't include a WUD hash!"), _("Error"), wxOK | wxCENTRE | wxICON_WARNING, this); return; } if(!boost::iequals(test_entry.wud_hash, m_json_entry.wud_hash)) { wxMessageBox(formatWxString(_("Your game image is invalid!\n\nYour hash:\n{}\n\nExpected hash:\n{}"), m_json_entry.wud_hash, test_entry.wud_hash), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } } else { std::map<std::string_view, std::pair<std::string, std::string>> invalid_hashes; std::vector<std::string_view> missing_files; const auto writeMismatchInfoToLog = [this, &missing_files, &invalid_hashes]() { wxFileDialog dialog(this, _("Select a file to export the errors"), wxEmptyString, wxEmptyString, "Error list (*.txt)|*.txt", wxFD_SAVE | wxFD_OVERWRITE_PROMPT); if (dialog.ShowModal() != wxID_OK || dialog.GetPath().IsEmpty()) return; const std::string path = dialog.GetPath().ToUTF8().data(); std::ofstream file(path); if (file.is_open()) { if (!missing_files.empty()) { file << "The following files are missing:\n"; for (const auto& f : missing_files) file << "\t" << f << "\n"; file << "\n"; } if (!invalid_hashes.empty()) { file << "The following files have an invalid hash (name | current hash | expected hash):\n"; for (const auto& f : invalid_hashes) file << "\t" << f.first << " | " << f.second.first << " | " << f.second.second << "\n"; } file.flush(); file.close(); wxLaunchDefaultBrowser(wxHelper::FromUtf8(fmt::format("file:{}", path))); } else wxMessageBox(_("Can't open file to write!"), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); }; for (const auto& f : test_entry.file_hashes) { const auto it = m_json_entry.file_hashes.find(f.first); if (it == m_json_entry.file_hashes.cend()) { missing_files.emplace_back(f.first); } else if (!boost::iequals(f.second, it->second)) { invalid_hashes[f.first] = std::make_pair(it->second, f.second); } } // files are missing but rest is okay if ((!missing_files.empty() || !invalid_hashes.empty()) && (missing_files.size() + invalid_hashes.size()) < 30) { // the list of missing + invalid hashes is short enough that we can print it to the message box std::stringstream str; if (missing_files.size() > 0) { str << _("The following files are missing:").ToUTF8().data() << "\n"; for (const auto& v : missing_files) str << v << "\n"; if(invalid_hashes.size() > 0) str << "\n"; } if (invalid_hashes.size() > 0) { str << _("The following files are damaged:").ToUTF8().data() << "\n"; for (const auto& v : invalid_hashes) str << v.first << "\n"; } wxMessageBox(str.str(), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } else if (missing_files.empty() && !invalid_hashes.empty()) { const int result = wxMessageBox(formatWxString( _("{} files have an invalid hash!\nDo you want to export a list of them to a file?"), invalid_hashes.size()), _("Error"), wxYES_NO | wxCENTRE | wxICON_ERROR, this); if (result == wxYES) { writeMismatchInfoToLog(); } return; } else if (!missing_files.empty() && !invalid_hashes.empty()) { const int result = wxMessageBox(formatWxString( _("Multiple issues with your game files have been found!\nDo you want to export them to a file?"), invalid_hashes.size()), _("Error"), wxYES_NO | wxCENTRE | wxICON_ERROR, this); if (result == wxYES) { writeMismatchInfoToLog(); } return; } } wxMessageBox(_("Your game files are valid"), _("Success"), wxOK | wxCENTRE, this); } catch (const std::exception& ex) { wxMessageBox(formatWxString(_("JSON parse error: {}"), ex.what()), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); } } void ChecksumTool::OnVerifyOnline(wxCommandEvent& event) { const auto title_id_str = fmt::format("{:016x}", m_json_entry.title_id); const auto default_file = fmt::format("{}_v{}.json", title_id_str, m_info.GetAppTitleVersion()); const auto checksum_path = ActiveSettings::GetUserDataPath("resources/checksums/{}", default_file); if(!exists(checksum_path)) return; std::ifstream file(checksum_path); if (!file.is_open()) { wxMessageBox(_("Can't open file!"), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } rapidjson::IStreamWrapper str(file); rapidjson::Document d; d.ParseStream(str); if (d.HasParseError()) { wxMessageBox(_("Can't parse JSON file!"), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } VerifyJsonEntry(d); } void ChecksumTool::OnVerifyLocal(wxCommandEvent& event) { const auto title_id_str = fmt::format("{:016x}", m_json_entry.title_id); const auto default_file = fmt::format("{}_v{}.json", title_id_str, m_info.GetAppTitleVersion()); wxFileDialog file_dialog(this, _("Open checksum entry"), "", default_file.c_str(),"JSON files (*.json)|*.json", wxFD_OPEN | wxFD_FILE_MUST_EXIST); if (file_dialog.ShowModal() != wxID_OK || file_dialog.GetPath().IsEmpty()) return; std::filesystem::path filename{ file_dialog.GetPath().c_str().AsInternal() }; std::ifstream file(filename); if(!file.is_open()) { wxMessageBox(_("Can't open file!"), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } rapidjson::IStreamWrapper str(file); rapidjson::Document d; d.ParseStream(str); if (d.HasParseError()) { wxMessageBox(_("Can't parse JSON file!"), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } VerifyJsonEntry(d); } static void _fscGetAllFiles(std::set<std::string>& allFilesOut, const std::string& fscBasePath, const std::string& relativePath) { sint32 fscStatus; FSCVirtualFile* fsc = fsc_openDirIterator((fscBasePath + relativePath).c_str(), &fscStatus); cemu_assert(fsc); FSCDirEntry dirEntry; while (fsc_nextDir(fsc, &dirEntry)) { if (dirEntry.isDirectory) { _fscGetAllFiles(allFilesOut, fscBasePath, std::string(relativePath).append(dirEntry.GetPath()).append("/")); } else { allFilesOut.emplace(std::string(relativePath).append(dirEntry.GetPath())); } } delete fsc; } void ChecksumTool::DoWork() { m_json_entry.title_id = m_info.GetAppTitleId(); m_json_entry.region = m_info.GetMetaRegion(); m_json_entry.version = m_info.GetAppTitleVersion(); static_assert(SHA256_DIGEST_LENGTH == 32); std::array<uint8, SHA256_DIGEST_LENGTH> checksum{}; switch (m_info.GetFormat()) { case TitleInfo::TitleDataFormat::WUD: { const auto path = m_entry.path.string(); wxQueueEvent(this, new wxSetGaugeValue(1, m_progress, m_status, formatWxString(_("Reading game image: {}"), path))); wud_t* wud = wud_open(m_info.GetPath()); if (!wud) throw std::runtime_error("can't open game image"); const auto wud_size = wud_getWUDSize(wud); std::vector<uint8> buffer(1024 * 1024 * 8); EVP_MD_CTX *sha256 = EVP_MD_CTX_new(); EVP_DigestInit(sha256, EVP_sha256()); uint32 read = 0; size_t offset = 0; auto size = wud_size; do { if (!m_running.load(std::memory_order_relaxed)) { wud_close(wud); return; } read = wud_readData(wud, buffer.data(), std::min(buffer.size(), (size_t)wud_size - offset), offset); offset += read; size -= read; EVP_DigestUpdate(sha256, buffer.data(), read); wxQueueEvent(this, new wxSetGaugeValue((int)((offset * 90) / wud_size), m_progress, m_status, formatWxString(_("Reading game image: {0}/{1} kB"), offset / 1024, wud_size / 1024))); } while (read != 0 && size > 0); wud_close(wud); wxQueueEvent(this, new wxSetGaugeValue(90, m_progress, m_status, formatWxString(_("Generating checksum of game image: {}"), path))); if (!m_running.load(std::memory_order_relaxed)) return; EVP_DigestFinal_ex(sha256, checksum.data(), NULL); EVP_MD_CTX_free(sha256); std::stringstream str; for (const auto& b : checksum) { str << fmt::format("{:02X}", b); } m_json_entry.wud_hash = str.str(); wxQueueEvent(this, new wxSetGaugeValue(100, m_progress, m_status, formatWxString(_("Generated checksum of game image: {}"), path))); break; } default: // we hash the individual files for all formats except WUD/WUX std::string temporaryMountPath = TitleInfo::GetUniqueTempMountingPath(); m_info.Mount(temporaryMountPath.c_str(), "", FSC_PRIORITY_BASE); wxQueueEvent(this, new wxSetGaugeValue(1, m_progress, m_status, _("Grabbing game files"))); // get list of all files std::set<std::string> files; _fscGetAllFiles(files, temporaryMountPath, ""); const size_t file_count = files.size(); size_t counter = 0; for (const auto& filename : files) { auto fileData = fsc_extractFile((temporaryMountPath + "/" + filename).c_str()); if (!fileData) { cemuLog_log(LogType::Force, "Failed to open {}", filename); continue; } SHA256(fileData->data(), fileData->size(), checksum.data()); std::stringstream str; for (const auto& b : checksum) { str << fmt::format("{:02X}", b); } // store relative path and hash m_json_entry.file_hashes[filename] = str.str(); ++counter; wxQueueEvent(this, new wxSetGaugeValue((int)((counter * 100) / file_count), m_progress, m_status, formatWxString(_("Hashing game file: {}/{}"), counter, file_count))); if (!m_running.load(std::memory_order_relaxed)) { m_info.Unmount(temporaryMountPath.c_str()); return; } } m_info.Unmount(temporaryMountPath.c_str()); wxQueueEvent(this, new wxSetGaugeValue(100, m_progress, m_status, formatWxString(_("Generated checksum of {} game files"), file_count))); break; } }
23,986
C++
.cpp
677
31.574594
201
0.669715
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,966
MemorySearcherTool.cpp
cemu-project_Cemu/src/gui/MemorySearcherTool.cpp
#include "gui/wxgui.h" #include "gui/MemorySearcherTool.h" #include <vector> #include <sstream> #include <thread> #include "config/ActiveSettings.h" #include "gui/helpers/wxHelpers.h" #include "Common/FileStream.h" #include "util/IniParser/IniParser.h" #include "util/helpers/StringHelpers.h" #include "Cafe/CafeSystem.h" enum { COMBOBOX_DATATYPE = wxID_HIGHEST + 1, TEXT_VALUE, BUTTON_START, BUTTON_FILTER, LIST_RESULTS, LIST_ENTRYTABLE, TIMER_REFRESH, LIST_ENTRY_ADD, LIST_ENTRY_REMOVE, }; wxDEFINE_EVENT(wxEVT_SEARCH_FINISHED, wxCommandEvent); wxBEGIN_EVENT_TABLE(MemorySearcherTool, wxFrame) EVT_CLOSE(MemorySearcherTool::OnClose) EVT_BUTTON(BUTTON_START, MemorySearcherTool::OnSearch) EVT_BUTTON(BUTTON_FILTER, MemorySearcherTool::OnFilter) EVT_TIMER(TIMER_REFRESH, MemorySearcherTool::OnTimerTick) wxEND_EVENT_TABLE() constexpr auto kMaxResultCount = 5000; const wxString kDatatypeFloat = "float"; const wxString kDatatypeDouble = "double"; const wxString kDatatypeString = "string"; const wxString kDatatypeInt8 = "int8"; const wxString kDatatypeInt16 = "int16"; const wxString kDatatypeInt32 = "int32"; const wxString kDatatypeInt64 = "int64"; const wxString kDataTypeNames[] = {kDatatypeFloat,kDatatypeDouble,/*DATATYPE_STRING,*/kDatatypeInt8,kDatatypeInt16,kDatatypeInt32,kDatatypeInt64}; MemorySearcherTool::MemorySearcherTool(wxFrame* parent) : wxFrame(parent, wxID_ANY, _("Memory Searcher"), wxDefaultPosition, wxSize(600, 540), wxDEFAULT_FRAME_STYLE | wxTAB_TRAVERSAL) { this->SetSizeHints(wxDefaultSize, wxDefaultSize); this->wxWindowBase::SetBackgroundColour(*wxWHITE); this->wxTopLevelWindowBase::SetMinSize(wxSize(600, 540)); auto* sizer = new wxBoxSizer(wxVERTICAL); auto* row1 = new wxFlexGridSizer(0, 4, 0, 0); row1->AddGrowableCol(1); m_cbDataType = new wxComboBox(this, COMBOBOX_DATATYPE, kDatatypeFloat, wxDefaultPosition, wxDefaultSize, std::size(kDataTypeNames), kDataTypeNames, wxCB_READONLY); m_textValue = new wxTextCtrl(this, TEXT_VALUE); m_buttonStart = new wxButton(this, BUTTON_START, _("Search")); m_buttonFilter = new wxButton(this, BUTTON_FILTER, _("Filter")); m_buttonFilter->Disable(); row1->Add(m_cbDataType, 0, wxALL, 5); row1->Add(m_textValue, 0, wxALL | wxEXPAND, 5); row1->Add(m_buttonStart, 0, wxALL, 5); row1->Add(m_buttonFilter, 0, wxALL, 5); sizer->Add(row1, 0, wxEXPAND, 5); auto* row2 = new wxFlexGridSizer(0, 1, 0, 0); row2->AddGrowableCol(0); m_gauge = new wxGauge(this, wxID_ANY, 100, wxDefaultPosition, wxDefaultSize, wxGA_HORIZONTAL); m_gauge->SetValue(0); m_gauge->Enable(false); m_textEntryTable = new wxStaticText(this, wxID_ANY, _("Results")); m_listResults = new wxListCtrl(this, LIST_RESULTS, wxDefaultPosition, wxDefaultSize, wxLC_REPORT | wxLC_SORT_ASCENDING); m_listResults->Bind(wxEVT_LEFT_DCLICK, &MemorySearcherTool::OnResultListClick, this); { wxListItem col0; col0.SetId(0); col0.SetText(_("Address")); col0.SetWidth(100); m_listResults->InsertColumn(0, col0); wxListItem col1; col1.SetId(1); col1.SetText(_("Value")); col1.SetWidth(250); m_listResults->InsertColumn(1, col1); } auto textEntryTable = new wxStaticText(this, wxID_ANY, _("Stored Entries")); m_listEntryTable = new wxDataViewListCtrl(this, LIST_ENTRYTABLE, wxDefaultPosition, wxSize(420, 200), wxDV_HORIZ_RULES); m_listEntryTable->Bind(wxEVT_DATAVIEW_ITEM_CONTEXT_MENU, &MemorySearcherTool::OnEntryListRightClick, this); m_listEntryTable->Bind(wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_DONE, &MemorySearcherTool::OnItemEdited, this); { m_listEntryTable->AppendTextColumn(_("Description"), wxDATAVIEW_CELL_EDITABLE, 150, wxALIGN_LEFT, wxDATAVIEW_COL_SORTABLE); m_listEntryTable->AppendTextColumn(_("Address"), wxDATAVIEW_CELL_INERT, 100, wxALIGN_LEFT, wxDATAVIEW_COL_SORTABLE); m_listEntryTable->AppendTextColumn(_("Type")); m_listEntryTable->AppendTextColumn(_("Value"), wxDATAVIEW_CELL_EDITABLE); m_listEntryTable->AppendToggleColumn(_("Freeze"), wxDATAVIEW_CELL_ACTIVATABLE, 50, wxALIGN_LEFT, 0); } row2->AddGrowableRow(3); row2->AddGrowableRow(5); row2->Add(m_gauge, 0, wxALL | wxEXPAND, 5); row2->Add(0, 10, 1, wxEXPAND, 5); row2->Add(m_textEntryTable, 0, wxALL, 5); row2->Add(m_listResults, 1, wxALL | wxEXPAND, 5); row2->Add(textEntryTable, 0, wxALL, 5); row2->Add(m_listEntryTable, 1, wxALL | wxEXPAND, 5); sizer->Add(row2, 1, wxEXPAND, 5); // load stored entries Load(); this->Bind(wxEVT_SEARCH_FINISHED, &MemorySearcherTool::OnSearchFinished, this); this->Bind(wxEVT_SET_GAUGE_VALUE, &MemorySearcherTool::OnUpdateGauge, this); m_refresh_timer = new wxTimer(this, TIMER_REFRESH); m_refresh_timer->Start(250); this->SetSizer(sizer); this->wxWindowBase::Layout(); this->Centre(wxBOTH); } MemorySearcherTool::~MemorySearcherTool() { m_refresh_timer->Stop(); m_running = false; if (m_worker.joinable()) m_worker.join(); } void MemorySearcherTool::OnTimerTick(wxTimerEvent& event) { RefreshResultList(); RefreshStashList(); } void MemorySearcherTool::OnClose(wxCloseEvent& event) { Save(); event.Skip(); } void MemorySearcherTool::OnSearchFinished(wxCommandEvent&) { FillResultList(); m_search_running = false; m_buttonStart->Enable(); m_buttonFilter->Enable(); } void MemorySearcherTool::OnUpdateGauge(wxSetGaugeValue& event) { auto* gauge = event.GetGauge(); const auto value = event.GetValue(); if (event.GetRange() != 0) { gauge->SetRange(event.GetRange()); gauge->SetValue(value); return; } debug_printf("update gauge: %d + %d = %d (/%d)\n", gauge->GetValue(), value, gauge->GetValue() + value, gauge->GetRange()); gauge->SetValue(gauge->GetValue() + value); } void MemorySearcherTool::OnSearch(wxCommandEvent&) { if (m_clear_state) { Reset(); return; } if (m_search_running) return; if (m_textValue->IsEmpty()) return; SetSearchDataType(); if (!VerifySearchValue()) { wxMessageBox(_("Your entered value is not valid for the selected datatype."), _("Error"), wxICON_ERROR); return; } m_buttonStart->Disable(); m_buttonFilter->Disable(); m_cbDataType->Disable(); m_buttonStart->SetLabelText(_("Clear")); m_clear_state = true; if (m_worker.joinable()) m_worker.join(); m_worker = std::thread([this]() { m_search_jobs.clear(); uint32 total_size = 0; for (const auto& itr : memory_getMMURanges()) { if (!m_running) return; if (!itr->isMapped()) continue; void* ptr = itr->getPtr(); const uint32 size = itr->getSize(); total_size += (size / kGaugeStep); m_search_jobs.emplace_back(std::async(std::launch::async, [this, ptr, size]() { return SearchValues(m_searchDataType, ptr, size); })); } wxQueueEvent(this, new wxSetGaugeValue(0, total_size, m_gauge)); ListType_t tmp; for (auto& it : m_search_jobs) { const auto result = it.get(); tmp.insert(tmp.end(), result.cbegin(), result.cend()); } std::unique_lock lock(m_mutex); m_searchBuffer.swap(tmp); lock.unlock(); wxQueueEvent(this, new wxCommandEvent(wxEVT_SEARCH_FINISHED)); }); } void MemorySearcherTool::OnFilter(wxCommandEvent& event) { m_buttonStart->Disable(); m_buttonFilter->Disable(); if (m_worker.joinable()) m_worker.join(); m_worker = std::thread([this]() { const auto count = (uint32)m_searchBuffer.size(); wxQueueEvent(this, new wxSetGaugeValue(0, count, m_gauge)); auto tmp = FilterValues(m_searchDataType); std::unique_lock lock(m_mutex); m_searchBuffer.swap(tmp); lock.unlock(); wxQueueEvent(this, new wxCommandEvent(wxEVT_SEARCH_FINISHED)); }); m_gauge->SetValue(0); } void MemorySearcherTool::Load() { const auto memorySearcherPath = ActiveSettings::GetUserDataPath("memorySearcher/{:016x}.ini", CafeSystem::GetForegroundTitleId()); auto memSearcherIniContents = FileStream::LoadIntoMemory(memorySearcherPath); if (!memSearcherIniContents) return; IniParser iniParser(*memSearcherIniContents, _pathToUtf8(memorySearcherPath)); while (iniParser.NextSection()) { auto option_description = iniParser.FindOption("description"); auto option_address = iniParser.FindOption("address"); auto option_type = iniParser.FindOption("type"); auto option_value = iniParser.FindOption("value"); if (!option_description || !option_address || !option_type || !option_value) continue; try { const auto addr = StringHelpers::ToInt64(*option_address); if (!IsAddressValid(addr)) continue; } catch (const std::invalid_argument&) { continue; } bool found = false; for (const auto& entry : kDataTypeNames) { if (boost::iequals(entry.ToStdString(), *option_type)) { found = true; break; } } if (!found && !boost::iequals(kDatatypeString.ToStdString(), *option_type)) continue; wxVector<wxVariant> data; data.push_back(std::string(*option_description).c_str()); data.push_back(std::string(*option_address).c_str()); data.push_back(std::string(*option_type).c_str()); data.push_back(std::string(*option_value).c_str()); data.push_back(!option_value->empty()); m_listEntryTable->AppendItem(data); } } void MemorySearcherTool::Save() { const auto memorySearcherPath = ActiveSettings::GetUserDataPath("memorySearcher/{:016x}.ini", CafeSystem::GetForegroundTitleId()); FileStream* fs = FileStream::createFile2(memorySearcherPath); if (fs) { for (int i = 0; i < m_listEntryTable->GetItemCount(); ++i) { fs->writeLine("[Entry]"); std::string tmp = "description=" + std::string(m_listEntryTable->GetTextValue(i, 0).mbc_str()); fs->writeLine(tmp.c_str()); tmp = "address=" + std::string(m_listEntryTable->GetTextValue(i, 1).mbc_str()); fs->writeLine(tmp.c_str()); tmp = "type=" + std::string(m_listEntryTable->GetTextValue(i, 2).mbc_str()); fs->writeLine(tmp.c_str()); // only save value when FREEZE is active if (m_listEntryTable->GetToggleValue(i, 4)) { tmp = "value=" + std::string(m_listEntryTable->GetTextValue(i, 3).mbc_str()); } else { tmp = "value="; } fs->writeLine(tmp.c_str()); fs->writeLine(""); } delete fs; } } bool MemorySearcherTool::IsAddressValid(uint32 addr) { for (const auto& itr : memory_getMMURanges()) { if (!itr->isMapped()) continue; void* ptr = itr->getPtr(); const uint32 size = itr->getSize(); MEMPTR start((uint8*)ptr); MEMPTR end((uint8*)ptr + size); if (start.GetMPTR() <= addr && addr < end.GetMPTR()) return true; } return false; } void MemorySearcherTool::OnEntryListRightClick(wxDataViewEvent& event) { //void *data = reinterpret_cast<void *>(event.GetItem().GetData()); wxMenu mnu; //mnu.SetClientData(data); mnu.Append(LIST_ENTRY_ADD, _("&Add new entry"))->Enable(false); mnu.Append(LIST_ENTRY_REMOVE, _("&Remove entry")); mnu.Connect(wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MemorySearcherTool::OnPopupClick), nullptr, this); PopupMenu(&mnu); } void MemorySearcherTool::OnResultListClick(wxMouseEvent& event) { long selectedIndex = -1; while (true) { selectedIndex = m_listResults->GetNextItem(selectedIndex, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED); if (selectedIndex == -1) break; long address = m_listResults->GetItemData(selectedIndex); auto currValue = m_listResults->GetItemText(selectedIndex, 1); char addressString[256]; sprintf(addressString, "0x%08lx", address); // description, address, type, value, freeze wxVector<wxVariant> data; data.push_back(""); data.push_back(addressString); data.push_back(m_cbDataType->GetValue()); data.push_back(currValue); data.push_back(false); m_listEntryTable->AppendItem(data); } } void MemorySearcherTool::Reset() { m_searchBuffer.clear(); m_buttonStart->SetLabelText(_("Search")); m_textEntryTable->SetLabelText(_("Results")); m_buttonFilter->Disable(); m_cbDataType->Enable(); m_textValue->SetValue(""); m_listResults->DeleteAllItems(); m_clear_state = false; } bool MemorySearcherTool::VerifySearchValue() const { const auto s1 = m_textValue->GetValue(); const auto s2 = s1.c_str(); const auto inputString = s2.AsChar(); switch (m_searchDataType) { case SearchDataType_String: return true; case SearchDataType_Float: { float value; return ConvertStringToType(inputString, value); } case SearchDataType_Double: { double value; return ConvertStringToType(inputString, value); } case SearchDataType_Int8: { sint8 value; return ConvertStringToType(inputString, value); } case SearchDataType_Int16: { sint16 value; return ConvertStringToType(inputString, value); } case SearchDataType_Int32: { sint32 value; return ConvertStringToType(inputString, value); } case SearchDataType_Int64: { sint64 value; return ConvertStringToType(inputString, value); } default: return false; } } void MemorySearcherTool::FillResultList() { auto text = formatWxString(_("Results ({0})"), m_searchBuffer.size()); m_textEntryTable->SetLabelText(text); m_listResults->DeleteAllItems(); if (m_searchBuffer.empty() || m_searchBuffer.size() > kMaxResultCount) return; for (const auto& address : m_searchBuffer) { const auto index = m_listResults->InsertItem(0, fmt::format("{:#08x}", address.GetMPTR())); m_listResults->SetItemData(index, address.GetMPTR()); m_listResults->SetItem(index, 1, m_textValue->GetValue()); } } void MemorySearcherTool::RefreshResultList() { std::unique_lock lock(m_mutex); if (m_searchBuffer.empty() || m_searchBuffer.size() > kMaxResultCount) return; for (int i = 0; i < m_listResults->GetItemCount(); ++i) { const auto addr = m_listResults->GetItemData(i); switch (m_searchDataType) { case SearchDataType_String: { // TODO Peter break; } case SearchDataType_Float: { const auto value = memory_read<float>(addr); m_listResults->SetItem(i, 1, fmt::format("{}", value)); break; } case SearchDataType_Double: { const auto value = memory_read<double>(addr); m_listResults->SetItem(i, 1, fmt::format("{}", value)); break; } case SearchDataType_Int8: { const auto value = memory_read<sint8>(addr); m_listResults->SetItem(i, 1, fmt::format("{}", value)); break; } case SearchDataType_Int16: { const auto value = memory_read<sint16>(addr); m_listResults->SetItem(i, 1, fmt::format("{}", value)); break; } case SearchDataType_Int32: { const auto value = memory_read<sint32>(addr); m_listResults->SetItem(i, 1, fmt::format("{}", value)); break; } case SearchDataType_Int64: { const auto value = memory_read<sint64>(addr); m_listResults->SetItem(i, 1, fmt::format("{}", value)); break; } } } } void MemorySearcherTool::RefreshStashList() { for (int i = 0; i < m_listEntryTable->GetItemCount(); ++i) { auto freeze = m_listEntryTable->GetToggleValue(i, 4); auto addressText = std::string(m_listEntryTable->GetTextValue(i, 1).mbc_str()); auto type = std::string(m_listEntryTable->GetTextValue(i, 2).mbc_str()); auto address = stol(addressText, nullptr, 16); // if freeze is activated, set the value instead of refreshing it if (freeze) { wxVariant var; m_listEntryTable->GetValue(var, i, 3); if (type == kDatatypeFloat) { auto value = (float)var.GetDouble(); memory_writeFloat(address, value); } else if (type == kDatatypeDouble) { auto value = var.GetDouble(); memory_writeDouble(address, value); } else if (type == kDatatypeInt8) { auto value = var.GetInteger(); memory_writeU8(address, value); } else if (type == kDatatypeInt16) { auto value = var.GetInteger(); memory_writeU16(address, value); } else if (type == kDatatypeInt32) { auto value = var.GetInteger(); memory_writeU32(address, value); } else if (type == kDatatypeInt64) { auto valueText = std::string(var.GetString().mbc_str()); auto value = stoull(valueText); memory_writeU64(address, value); } else if (type == kDatatypeString) { auto valueText = std::string(var.GetString().mbc_str()); for (int i = 0; i < valueText.size(); ++i) { memory_writeU8(address + i, valueText[i]); } memory_writeU8(address + valueText.size(), 0x00); } } else { if (type == kDatatypeFloat) { auto value = memory_readFloat(address); m_listEntryTable->SetValue(fmt::format("{}", value), i, 3); } else if (type == kDatatypeDouble) { auto value = memory_readDouble(address); m_listEntryTable->SetValue(fmt::format("{}", value), i, 3); } else if (type == kDatatypeInt8) { auto value = (sint8)memory_readU8(address); m_listEntryTable->SetValue(fmt::format("{}", (int)value), i, 3); } else if (type == kDatatypeInt16) { auto value = (sint16)memory_readU16(address); m_listEntryTable->SetValue(fmt::format("{}", value), i, 3); } else if (type == kDatatypeInt32) { auto value = (sint32)memory_readU32(address); m_listEntryTable->SetValue(fmt::format("{}", value), i, 3); } else if (type == kDatatypeInt64) { auto value = (sint64)memory_readU64(address); m_listEntryTable->SetValue(fmt::format("{}", value), i, 3); } else if (type == kDatatypeString) { // TODO Peter } } } } void MemorySearcherTool::SetSearchDataType() { const auto type = m_cbDataType->GetStringSelection(); if (type == kDatatypeFloat) m_searchDataType = SearchDataType_Float; else if (type == kDatatypeDouble) m_searchDataType = SearchDataType_Double; else if (type == kDatatypeInt8) m_searchDataType = SearchDataType_Int8; else if (type == kDatatypeInt16) m_searchDataType = SearchDataType_Int16; else if (type == kDatatypeInt32) m_searchDataType = SearchDataType_Int32; else if (type == kDatatypeInt64) m_searchDataType = SearchDataType_Int64; else if (type == kDatatypeString) m_searchDataType = SearchDataType_String; else m_searchDataType = SearchDataType_None; } template <> bool MemorySearcherTool::ConvertStringToType<signed char>(const char* inValue, sint8& outValue) const { sint16 tmp; std::istringstream iss(inValue); iss >> std::noskipws >> tmp; if (iss && iss.eof()) { if (SCHAR_MIN <= tmp && tmp <= SCHAR_MAX) { outValue = tmp; return true; } } return false; } void MemorySearcherTool::OnPopupClick(wxCommandEvent& event) { if (event.GetId() == LIST_ENTRY_REMOVE) { const int row = m_listEntryTable->GetSelectedRow(); if (row == -1) return; m_listEntryTable->DeleteItem(row); } } void MemorySearcherTool::OnItemEdited(wxDataViewEvent& event) { auto column = event.GetColumn(); // Edit description if (column == 0) { } // Edit value else if (column == 3) { auto row = m_listEntryTable->GetSelectedRow(); if (row == -1) return; auto addressText = std::string(m_listEntryTable->GetTextValue(row, 1).mbc_str()); uint32 address = stoul(addressText, nullptr, 16); auto type = m_listEntryTable->GetTextValue(row, 2); if (type == kDatatypeFloat) { auto value = (float)event.GetValue().GetDouble(); memory_writeFloat(address, value); } else if (type == kDatatypeDouble) { auto value = event.GetValue().GetDouble(); memory_writeDouble(address, value); } else if (type == kDatatypeInt8) { auto value = event.GetValue().GetInteger(); memory_writeU8(address, value); } else if (type == kDatatypeInt16) { auto value = event.GetValue().GetInteger(); memory_writeU16(address, value); } else if (type == kDatatypeInt32) { auto value = event.GetValue().GetInteger(); memory_writeU32(address, value); } else if (type == kDatatypeInt64) { auto valueText = std::string(event.GetValue().GetString().mbc_str()); auto value = stoull(valueText); memory_writeU64(address, value); } else if (type == kDatatypeString) { auto valueText = std::string(event.GetValue().GetString().mbc_str()); for (int i = 0; i < valueText.size(); ++i) { memory_writeU8(address + i, valueText[i]); } memory_writeU8(address + valueText.size(), 0x00); } } }
20,083
C++
.cpp
654
27.701835
164
0.713154
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,967
GeneralSettings2.cpp
cemu-project_Cemu/src/gui/GeneralSettings2.cpp
#include "gui/wxgui.h" #include "gui/GeneralSettings2.h" #include "gui/CemuApp.h" #include "gui/helpers/wxControlObject.h" #include "util/helpers/helpers.h" #include "Cafe/OS/libs/snd_core/ax.h" #include <wx/collpane.h> #include <wx/clrpicker.h> #include <wx/cshelp.h> #include <wx/textdlg.h> #include <wx/hyperlink.h> #include "config/CemuConfig.h" #include "config/NetworkSettings.h" #include "audio/IAudioAPI.h" #if BOOST_OS_WINDOWS #include "audio/DirectSoundAPI.h" #include "audio/XAudio27API.h" #endif #include "audio/CubebAPI.h" #include "audio/IAudioInputAPI.h" #include "Cafe/HW/Latte/Renderer/Vulkan/VulkanAPI.h" #include "Cafe/HW/Latte/Renderer/Vulkan/VulkanRenderer.h" #include "Cafe/Account/Account.h" #include <boost/tokenizer.hpp> #include "util/helpers/SystemException.h" #include "gui/dialogs/CreateAccount/wxCreateAccountDialog.h" #if BOOST_OS_WINDOWS #include <VersionHelpers.h> #endif #include "config/LaunchSettings.h" #include "config/ActiveSettings.h" #include "gui/helpers/wxHelpers.h" #include "resource/embedded/resources.h" #include "Cafe/CafeSystem.h" #include "Cemu/ncrypto/ncrypto.h" #include "Cafe/TitleList/TitleList.h" #include "wxHelper.h" #include "util/ScreenSaver/ScreenSaver.h" const wxString kDirectSound("DirectSound"); const wxString kXAudio27("XAudio2.7"); const wxString kXAudio2("XAudio2"); const wxString kCubeb("Cubeb"); const wxString kPropertyPersistentId("PersistentId"); const wxString kPropertyMiiName("MiiName"); const wxString kPropertyBirthday("Birthday"); const wxString kPropertyGender("Gender"); const wxString kPropertyEmail("Email"); const wxString kPropertyCountry("Country"); wxDEFINE_EVENT(wxEVT_ACCOUNTLIST_REFRESH, wxCommandEvent); class wxDeviceDescription : public wxClientData { public: wxDeviceDescription(const IAudioAPI::DeviceDescriptionPtr& description) : m_description(description) {} const IAudioAPI::DeviceDescriptionPtr& GetDescription() const { return m_description; } private: IAudioAPI::DeviceDescriptionPtr m_description; }; class wxInputDeviceDescription : public wxClientData { public: wxInputDeviceDescription(const IAudioInputAPI::DeviceDescriptionPtr& description) : m_description(description) {} const IAudioInputAPI::DeviceDescriptionPtr& GetDescription() const { return m_description; } private: IAudioInputAPI::DeviceDescriptionPtr m_description; }; class wxVulkanUUID : public wxClientData { public: wxVulkanUUID(const VulkanRenderer::DeviceInfo& info) : m_device_info(info) {} const VulkanRenderer::DeviceInfo& GetDeviceInfo() const { return m_device_info; } private: VulkanRenderer::DeviceInfo m_device_info; }; class wxAccountData : public wxClientData { public: wxAccountData(const Account& account) : m_account(account) {} Account& GetAccount() { return m_account; } const Account& GetAccount() const { return m_account; } private: Account m_account; }; wxPanel* GeneralSettings2::AddGeneralPage(wxNotebook* notebook) { auto* panel = new wxPanel(notebook); auto* general_panel_sizer = new wxBoxSizer(wxVERTICAL); { auto* box = new wxStaticBox(panel, wxID_ANY, _("Interface")); auto* box_sizer = new wxStaticBoxSizer(box, wxVERTICAL); { auto* first_row = new wxFlexGridSizer(0, 2, 0, 0); first_row->SetFlexibleDirection(wxBOTH); first_row->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); first_row->Add(new wxStaticText(box, wxID_ANY, _("Language"), wxDefaultPosition, wxDefaultSize, 0), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); wxString language_choices[] = { _("Default") }; m_language = new wxChoice(box, wxID_ANY, wxDefaultPosition, wxDefaultSize, std::size(language_choices), language_choices); m_language->SetSelection(0); m_language->SetToolTip(_("Changes the interface language of Cemu\nAvailable languages are stored in the translation directory\nA restart will be required after changing the language")); for (const auto& language : wxGetApp().GetLanguages()) { m_language->Append(language->DescriptionNative); } first_row->Add(m_language, 0, wxALL | wxEXPAND, 5); box_sizer->Add(first_row, 1, wxEXPAND, 5); } { auto* second_row = new wxFlexGridSizer(0, 3, 0, 0); second_row->SetFlexibleDirection(wxBOTH); second_row->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); sint32 checkboxCount = 0; auto CountRowElement = [&]() { checkboxCount++; if(checkboxCount != 2) return; second_row->AddSpacer(10); checkboxCount = 0; }; auto InsertEmptyRow = [&]() { while(checkboxCount != 0) CountRowElement(); second_row->AddSpacer(10); second_row->AddSpacer(10); second_row->AddSpacer(10); }; const int topflag = wxALIGN_CENTER_VERTICAL | wxALL; m_save_window_position_size = new wxCheckBox(box, wxID_ANY, _("Remember main window position")); m_save_window_position_size->SetToolTip(_("Restores the last known window position and size when starting Cemu")); second_row->Add(m_save_window_position_size, 0, topflag, 5); CountRowElement(); //second_row->AddSpacer(10); m_save_padwindow_position_size = new wxCheckBox(box, wxID_ANY, _("Remember pad window position")); m_save_padwindow_position_size->SetToolTip(_("Restores the last known pad window position and size when opening it")); second_row->Add(m_save_padwindow_position_size, 0, topflag, 5); CountRowElement(); const int botflag = wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT | wxBOTTOM; m_discord_presence = new wxCheckBox(box, wxID_ANY, _("Discord Presence")); m_discord_presence->SetToolTip(_("Enables the Discord Rich Presence feature\nYou will also need to enable it in the Discord settings itself!")); second_row->Add(m_discord_presence, 0, botflag, 5); CountRowElement(); #ifndef ENABLE_DISCORD_RPC m_discord_presence->Disable(); #endif //second_row->AddSpacer(10); m_fullscreen_menubar = new wxCheckBox(box, wxID_ANY, _("Fullscreen menu bar")); m_fullscreen_menubar->SetToolTip(_("Displays the menu bar when Cemu is running in fullscreen mode and the mouse cursor is moved to the top")); second_row->Add(m_fullscreen_menubar, 0, botflag, 5); CountRowElement(); m_save_screenshot = new wxCheckBox(box, wxID_ANY, _("Save screenshot")); m_save_screenshot->SetToolTip(_("Pressing the screenshot key (F12) will save a screenshot directly to the screenshots folder")); second_row->Add(m_save_screenshot, 0, botflag, 5); CountRowElement(); m_disable_screensaver = new wxCheckBox(box, wxID_ANY, _("Disable screen saver")); m_disable_screensaver->SetToolTip(_("Prevents the system from activating the screen saver or going to sleep while running a game.")); second_row->Add(m_disable_screensaver, 0, botflag, 5); CountRowElement(); // Enable/disable feral interactive gamemode #if BOOST_OS_LINUX && defined(ENABLE_FERAL_GAMEMODE) m_feral_gamemode = new wxCheckBox(box, wxID_ANY, _("Enable Feral GameMode")); m_feral_gamemode->SetToolTip(_("Use FeralInteractive GameMode if installed.")); second_row->Add(m_feral_gamemode, 0, botflag, 5); CountRowElement(); #endif // temporary workaround because feature crashes on macOS #if BOOST_OS_MACOS m_disable_screensaver->Enable(false); #endif // InsertEmptyRow(); m_auto_update = new wxCheckBox(box, wxID_ANY, _("Automatically check for updates")); m_auto_update->SetToolTip(_("Automatically checks for new cemu versions on startup")); second_row->Add(m_auto_update, 0, botflag, 5); CountRowElement(); m_receive_untested_releases = new wxCheckBox(box, wxID_ANY, _("Receive untested updates")); m_receive_untested_releases->SetToolTip(_("When checking for updates, include brand new and untested releases. These may contain bugs!")); second_row->Add(m_receive_untested_releases, 0, botflag, 5); #if BOOST_OS_LINUX if (!std::getenv("APPIMAGE")) { m_auto_update->Disable(); } #endif box_sizer->Add(second_row, 0, wxEXPAND, 5); } general_panel_sizer->Add(box_sizer, 0, wxEXPAND | wxALL, 5); } { auto* outerMlcBox = new wxStaticBox(panel, wxID_ANY, _("Custom MLC path")); auto* box_sizer_mlc = new wxStaticBoxSizer(outerMlcBox, wxVERTICAL); box_sizer_mlc->Add(new wxStaticText(box_sizer_mlc->GetStaticBox(), wxID_ANY, _("You can configure a custom path for the emulated internal Wii U storage (MLC).\nThis is where Cemu stores saves, accounts and other Wii U system files."), wxDefaultPosition, wxDefaultSize, 0), 0, wxALL, 5); auto* mlcPathLineSizer = new wxBoxSizer(wxHORIZONTAL); m_mlc_path = new wxTextCtrl(outerMlcBox, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_READONLY); m_mlc_path->SetMinSize(wxSize(150, -1)); m_mlc_path->SetToolTip(_("The mlc directory contains your save games and installed game update/dlc data")); mlcPathLineSizer->Add(m_mlc_path, 1, wxALL | wxEXPAND, 5); auto* changePath = new wxButton(outerMlcBox, wxID_ANY, "Change"); changePath->Bind(wxEVT_BUTTON, &GeneralSettings2::OnMLCPathSelect, this); mlcPathLineSizer->Add(changePath, 0, wxALL, 5); if (LaunchSettings::GetMLCPath().has_value()) changePath->Disable(); auto* clearPath = new wxButton(outerMlcBox, wxID_ANY, "Clear custom path"); clearPath->Bind(wxEVT_BUTTON, &GeneralSettings2::OnMLCPathClear, this); mlcPathLineSizer->Add(clearPath, 0, wxALL, 5); if (LaunchSettings::GetMLCPath().has_value() || !ActiveSettings::IsCustomMlcPath()) clearPath->Disable(); box_sizer_mlc->Add(mlcPathLineSizer, 0, wxEXPAND, 5); general_panel_sizer->Add(box_sizer_mlc, 0, wxEXPAND | wxALL, 5); } { auto* general_gamepath_box = new wxStaticBox(panel, wxID_ANY, _("Game Paths")); auto* general_gamepath_sizer = new wxStaticBoxSizer(general_gamepath_box, wxVERTICAL); m_game_paths = new wxListBox(general_gamepath_box, wxID_ANY); m_game_paths->SetMinSize(wxSize(150, 100)); m_game_paths->SetToolTip(_("Add the root directory of your game(s). It will scan all directories in it for games")); general_gamepath_sizer->Add(m_game_paths, 1, wxALL | wxEXPAND, 5); auto* general_gamepath_buttons = new wxFlexGridSizer(0, 2, 0, 0); general_gamepath_buttons->SetFlexibleDirection(wxBOTH); general_gamepath_buttons->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); auto* general_gamepath_add_button = new wxButton(general_gamepath_box, wxID_ANY, _("Add")); general_gamepath_add_button->Bind(wxEVT_BUTTON, &GeneralSettings2::OnAddPathClicked, this); general_gamepath_add_button->SetToolTip(_("Adds a game path to scan for games displayed in the game list\nIf you have unpacked games, make sure to select the root folder of a game")); general_gamepath_buttons->Add(general_gamepath_add_button, 0, wxALL, 5); auto* general_gamepath_remove_button = new wxButton(general_gamepath_box, wxID_ANY, _("Remove")); general_gamepath_remove_button->Bind(wxEVT_BUTTON, &GeneralSettings2::OnRemovePathClicked, this); general_gamepath_remove_button->SetToolTip(_("Removes the currently selected game path from the game list")); general_gamepath_buttons->Add(general_gamepath_remove_button, 0, wxALL, 5); general_gamepath_sizer->Add(general_gamepath_buttons, 0, wxEXPAND, 5); general_panel_sizer->Add(general_gamepath_sizer, 1, wxEXPAND | wxALL, 5); } panel->SetSizerAndFit(general_panel_sizer); return panel; } wxPanel* GeneralSettings2::AddGraphicsPage(wxNotebook* notebook) { // Graphics page auto graphics_panel = new wxPanel(notebook); auto graphics_panel_sizer = new wxBoxSizer(wxVERTICAL); { auto box = new wxStaticBox(graphics_panel, wxID_ANY, _("General")); auto box_sizer = new wxStaticBoxSizer(box, wxVERTICAL); auto row = new wxFlexGridSizer(0, 2, 0, 0); row->SetFlexibleDirection(wxBOTH); row->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); row->Add(new wxStaticText(box, wxID_ANY, _("Graphics API")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); sint32 api_size = 1; wxString choices[2] = { "OpenGL" }; if (g_vulkan_available) { choices[1] = "Vulkan"; api_size = 2; } m_graphic_api = new wxChoice(box, wxID_ANY, wxDefaultPosition, wxDefaultSize, api_size, choices); m_graphic_api->SetSelection(0); if (api_size > 1) m_graphic_api->SetToolTip(_("Select one of the available graphic back ends")); row->Add(m_graphic_api, 0, wxALL, 5); m_graphic_api->Bind(wxEVT_CHOICE, &GeneralSettings2::OnGraphicAPISelected, this); row->Add(new wxStaticText(box, wxID_ANY, _("Graphics Device")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_graphic_device = new wxChoice(box, wxID_ANY, wxDefaultPosition, { 230, -1 }, api_size, choices); m_graphic_device->SetSelection(0); m_graphic_device->SetToolTip(_("Select the used graphic device")); row->Add(m_graphic_device, 0, wxALL, 5); row->Add(new wxStaticText(box, wxID_ANY, _("VSync")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_vsync = new wxChoice(box, wxID_ANY, wxDefaultPosition, { 230, -1 }); m_vsync->SetToolTip(_("Controls the vsync state")); row->Add(m_vsync, 0, wxALL, 5); box_sizer->Add(row, 0, wxEXPAND, 5); auto* graphic_misc_row = new wxFlexGridSizer(0, 2, 0, 0); m_async_compile = new wxCheckBox(box, wxID_ANY, _("Async shader compile")); m_async_compile->SetToolTip(_("Enables async shader and pipeline compilation. Reduces stutter at the cost of objects not rendering for a short time.\nVulkan only")); graphic_misc_row->Add(m_async_compile, 0, wxALL, 5); m_gx2drawdone_sync = new wxCheckBox(box, wxID_ANY, _("Full sync at GX2DrawDone()")); m_gx2drawdone_sync->SetToolTip(_("If synchronization is requested by the game, the emulated CPU will wait for the GPU to finish all operations.\nThis is more accurate behavior, but may cause lower performance")); graphic_misc_row->Add(m_gx2drawdone_sync, 0, wxALL, 5); box_sizer->Add(graphic_misc_row, 1, wxEXPAND, 5); graphics_panel_sizer->Add(box_sizer, 0, wxEXPAND | wxALL, 5); } { wxString choices[] = { _("Bilinear"), _("Bicubic"), _("Hermite"), _("Nearest Neighbor") }; m_upscale_filter = new wxRadioBox(graphics_panel, wxID_ANY, _("Upscale filter"), wxDefaultPosition, wxDefaultSize, std::size(choices), choices, 5, wxRA_SPECIFY_COLS); m_upscale_filter->SetToolTip(_("Upscaling filters are used when the game resolution is smaller than the window size")); graphics_panel_sizer->Add(m_upscale_filter, 0, wxALL | wxEXPAND, 5); m_downscale_filter = new wxRadioBox(graphics_panel, wxID_ANY, _("Downscale filter"), wxDefaultPosition, wxDefaultSize, std::size(choices), choices, 5, wxRA_SPECIFY_COLS); m_downscale_filter->SetToolTip(_("Downscaling filters are used when the game resolution is bigger than the window size")); graphics_panel_sizer->Add(m_downscale_filter, 0, wxALL | wxEXPAND, 5); } { wxString choices[] = { _("Keep aspect ratio"), _("Stretch") }; m_fullscreen_scaling = new wxRadioBox(graphics_panel, wxID_ANY, _("Fullscreen scaling"), wxDefaultPosition, wxDefaultSize, std::size(choices), choices, 5, wxRA_SPECIFY_COLS); m_fullscreen_scaling->SetToolTip(_("Controls the output aspect ratio when it doesn't match the ratio of the game")); graphics_panel_sizer->Add(m_fullscreen_scaling, 0, wxALL | wxEXPAND, 5); } graphics_panel->SetSizerAndFit(graphics_panel_sizer); return graphics_panel; } wxPanel* GeneralSettings2::AddAudioPage(wxNotebook* notebook) { auto audio_panel = new wxPanel(notebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); auto audio_panel_sizer = new wxBoxSizer(wxVERTICAL); { auto box = new wxStaticBox(audio_panel, wxID_ANY, _("General")); auto box_sizer = new wxStaticBoxSizer(box, wxVERTICAL); auto audio_general_row = new wxFlexGridSizer(0, 3, 0, 0); audio_general_row->SetFlexibleDirection(wxBOTH); audio_general_row->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); audio_general_row->Add(new wxStaticText(box, wxID_ANY, _("API")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_audio_api = new wxChoice(box, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, nullptr); if (IAudioAPI::IsAudioAPIAvailable(IAudioAPI::DirectSound)) m_audio_api->Append(kDirectSound); if (IAudioAPI::IsAudioAPIAvailable(IAudioAPI::XAudio27)) m_audio_api->Append(kXAudio27); if (IAudioAPI::IsAudioAPIAvailable(IAudioAPI::XAudio2)) m_audio_api->Append(kXAudio2); if (IAudioAPI::IsAudioAPIAvailable(IAudioAPI::Cubeb)) m_audio_api->Append(kCubeb); m_audio_api->SetSelection(0); m_audio_api->SetToolTip(_("Select one of the available audio back ends")); audio_general_row->Add(m_audio_api, 0, wxALL, 5); m_audio_api->Bind(wxEVT_CHOICE, &GeneralSettings2::OnAudioAPISelected, this); audio_general_row->AddSpacer(0); audio_general_row->Add(new wxStaticText(box, wxID_ANY, _("Latency")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_audio_latency = new wxSlider(box, wxID_ANY, 2, 0, IAudioAPI::kBlockCount - 1, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL); m_audio_latency->SetToolTip(_("Controls the amount of buffered audio data\nHigher values will create a delay in audio playback, but may avoid audio problems when emulation is too slow")); audio_general_row->Add(m_audio_latency, 0, wxEXPAND | wxALL, 5); auto latency_text = new wxStaticText(box, wxID_ANY, "24ms"); audio_general_row->Add(latency_text, 0, wxALIGN_CENTER_VERTICAL | wxALL | wxALIGN_RIGHT, 5); m_audio_latency->Bind(wxEVT_SLIDER, &GeneralSettings2::OnLatencySliderChanged, this, wxID_ANY, wxID_ANY, new wxControlObject(latency_text)); m_audio_latency->Bind(wxEVT_SLIDER, &GeneralSettings2::OnAudioLatencyChanged, this); box_sizer->Add(audio_general_row, 1, wxEXPAND, 5); audio_panel_sizer->Add(box_sizer, 0, wxEXPAND | wxALL, 5); } const wxString audio_channel_choices[] = { _("Mono"), _("Stereo") , _("Surround") }; { auto box = new wxStaticBox(audio_panel, wxID_ANY, _("TV")); auto box_sizer = new wxStaticBoxSizer(box, wxVERTICAL); auto audio_tv_row = new wxFlexGridSizer(0, 3, 0, 0); audio_tv_row->SetFlexibleDirection(wxBOTH); audio_tv_row->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); audio_tv_row->Add(new wxStaticText(box, wxID_ANY, _("Device")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_tv_device = new wxChoice(box, wxID_ANY); m_tv_device->SetMinSize(wxSize(300, -1)); m_tv_device->SetToolTip(_("Select the active audio output device for Wii U TV")); audio_tv_row->Add(m_tv_device, 0, wxEXPAND | wxALL, 5); audio_tv_row->AddSpacer(0); m_tv_device->Bind(wxEVT_CHOICE, &GeneralSettings2::OnAudioDeviceSelected, this); audio_tv_row->Add(new wxStaticText(box, wxID_ANY, _("Channels")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_tv_channels = new wxChoice(box, wxID_ANY, wxDefaultPosition, wxDefaultSize, std::size(audio_channel_choices), audio_channel_choices); m_tv_channels->SetSelection(1); // set default to stereo m_tv_channels->Bind(wxEVT_CHOICE, &GeneralSettings2::OnAudioChannelsSelected, this); audio_tv_row->Add(m_tv_channels, 0, wxEXPAND | wxALL, 5); audio_tv_row->AddSpacer(0); audio_tv_row->Add(new wxStaticText(box, wxID_ANY, _("Volume")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_tv_volume = new wxSlider(box, wxID_ANY, 100, 0, 100, wxDefaultPosition, wxDefaultSize, wxSL_HORIZONTAL); audio_tv_row->Add(m_tv_volume, 0, wxEXPAND | wxALL, 5); auto audio_tv_volume_text = new wxStaticText(box, wxID_ANY, "100%"); audio_tv_row->Add(audio_tv_volume_text, 0, wxALIGN_CENTER_VERTICAL | wxALL | wxALIGN_RIGHT, 5); m_tv_volume->Bind(wxEVT_SLIDER, &GeneralSettings2::OnSliderChangedPercent, this, wxID_ANY, wxID_ANY, new wxControlObject(audio_tv_volume_text)); m_tv_volume->Bind(wxEVT_SLIDER, &GeneralSettings2::OnVolumeChanged, this); box_sizer->Add(audio_tv_row, 1, wxEXPAND, 5); audio_panel_sizer->Add(box_sizer, 0, wxEXPAND | wxALL, 5); } { auto box = new wxStaticBox(audio_panel, wxID_ANY, _("Gamepad")); auto box_sizer = new wxStaticBoxSizer(box, wxVERTICAL); auto audio_pad_row = new wxFlexGridSizer(0, 3, 0, 0); audio_pad_row->SetFlexibleDirection(wxBOTH); audio_pad_row->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); audio_pad_row->Add(new wxStaticText(box, wxID_ANY, _("Device")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_pad_device = new wxChoice(box, wxID_ANY, wxDefaultPosition); m_pad_device->SetMinSize(wxSize(300, -1)); m_pad_device->SetToolTip(_("Select the active audio output device for Wii U GamePad")); audio_pad_row->Add(m_pad_device, 0, wxEXPAND | wxALL, 5); audio_pad_row->AddSpacer(0); m_pad_device->Bind(wxEVT_CHOICE, &GeneralSettings2::OnAudioDeviceSelected, this); const wxString audio_channel_drc_choices[] = { _("Stereo") }; // stereo for now only audio_pad_row->Add(new wxStaticText(box, wxID_ANY, _("Channels")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_pad_channels = new wxChoice(box, wxID_ANY, wxDefaultPosition, wxDefaultSize, std::size(audio_channel_drc_choices), audio_channel_drc_choices); m_pad_channels->SetSelection(0); // set default to stereo m_pad_channels->Bind(wxEVT_CHOICE, &GeneralSettings2::OnAudioChannelsSelected, this); audio_pad_row->Add(m_pad_channels, 0, wxEXPAND | wxALL, 5); audio_pad_row->AddSpacer(0); audio_pad_row->Add(new wxStaticText(box, wxID_ANY, _("Volume")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_pad_volume = new wxSlider(box, wxID_ANY, 100, 0, 100); audio_pad_row->Add(m_pad_volume, 0, wxEXPAND | wxALL, 5); auto audio_pad_volume_text = new wxStaticText(box, wxID_ANY, "100%"); audio_pad_row->Add(audio_pad_volume_text, 0, wxALIGN_CENTER_VERTICAL | wxALL | wxALIGN_RIGHT, 5); m_pad_volume->Bind(wxEVT_SLIDER, &GeneralSettings2::OnSliderChangedPercent, this, wxID_ANY, wxID_ANY, new wxControlObject(audio_pad_volume_text)); m_pad_volume->Bind(wxEVT_SLIDER, &GeneralSettings2::OnVolumeChanged, this); box_sizer->Add(audio_pad_row, 1, wxEXPAND, 5); audio_panel_sizer->Add(box_sizer, 0, wxEXPAND | wxALL, 5); } { auto box = new wxStaticBox(audio_panel, wxID_ANY, _("Microphone (Experimental)")); auto box_sizer = new wxStaticBoxSizer(box, wxVERTICAL); auto audio_input_row = new wxFlexGridSizer(0, 3, 0, 0); audio_input_row->SetFlexibleDirection(wxBOTH); audio_input_row->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); audio_input_row->Add(new wxStaticText(box, wxID_ANY, _("Device")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_input_device = new wxChoice(box, wxID_ANY, wxDefaultPosition); m_input_device->SetMinSize(wxSize(300, -1)); m_input_device->SetToolTip(_("Select the active audio input device for Wii U GamePad")); audio_input_row->Add(m_input_device, 0, wxEXPAND | wxALL, 5); audio_input_row->AddSpacer(0); m_input_device->Bind(wxEVT_CHOICE, &GeneralSettings2::OnAudioDeviceSelected, this); const wxString audio_channel_drc_choices[] = { _("Mono") }; // mono for now only audio_input_row->Add(new wxStaticText(box, wxID_ANY, _("Channels")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_input_channels = new wxChoice(box, wxID_ANY, wxDefaultPosition, wxDefaultSize, std::size(audio_channel_drc_choices), audio_channel_drc_choices); m_input_channels->SetSelection(0); // set default to stereo m_input_channels->Bind(wxEVT_CHOICE, &GeneralSettings2::OnAudioChannelsSelected, this); audio_input_row->Add(m_input_channels, 0, wxEXPAND | wxALL, 5); audio_input_row->AddSpacer(0); audio_input_row->Add(new wxStaticText(box, wxID_ANY, _("Volume")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_input_volume = new wxSlider(box, wxID_ANY, 100, 0, 100); audio_input_row->Add(m_input_volume, 0, wxEXPAND | wxALL, 5); auto audio_input_volume_text = new wxStaticText(box, wxID_ANY, "100%"); audio_input_row->Add(audio_input_volume_text, 0, wxALIGN_CENTER_VERTICAL | wxALL | wxALIGN_RIGHT, 5); m_input_volume->Bind(wxEVT_SLIDER, &GeneralSettings2::OnSliderChangedPercent, this, wxID_ANY, wxID_ANY, new wxControlObject(audio_input_volume_text)); m_input_volume->Bind(wxEVT_SLIDER, &GeneralSettings2::OnVolumeChanged, this); box_sizer->Add(audio_input_row, 1, wxEXPAND, 5); audio_panel_sizer->Add(box_sizer, 0, wxEXPAND | wxALL, 5); } audio_panel->SetSizerAndFit(audio_panel_sizer); return audio_panel; } wxPanel* GeneralSettings2::AddOverlayPage(wxNotebook* notebook) { auto* panel = new wxPanel(notebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); auto* panel_sizer = new wxBoxSizer(wxVERTICAL); const wxString positions[]{ _("Disabled"), _("Top left"), _("Top center"), _("Top right"), _("Bottom left"), _("Bottom center"), _("Bottom right") }; const wxString text_scale[]{ "50%", "75%", "100%", "125%", "150%", "175%", "200%", "225%", "250%", "275%", "300%" }; { auto box = new wxStaticBox(panel, wxID_ANY, _("Overlay")); auto box_sizer = new wxStaticBoxSizer(box, wxVERTICAL); auto position_row = new wxFlexGridSizer(1, 0, 0, 0); position_row->SetFlexibleDirection(wxBOTH); position_row->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); { position_row->Add(new wxStaticText(box, wxID_ANY, _("Position")), 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_overlay_position = new wxChoice(box, wxID_ANY, wxDefaultPosition, wxDefaultSize, std::size(positions), positions); m_overlay_position->SetSelection(0); m_overlay_position->SetToolTip(_("Controls the overlay which displays technical information while playing")); position_row->Add(m_overlay_position, 0, wxALL, 5); position_row->AddSpacer(25); position_row->Add(new wxStaticText(box, wxID_ANY, _("Text Color")), 0, wxALL | wxALIGN_CENTRE_VERTICAL, 5); m_overlay_font_color = new wxColourPickerCtrl(box, wxID_ANY, *wxWHITE, wxDefaultPosition, wxDefaultSize, wxCLRP_SHOW_ALPHA); m_overlay_font_color->SetToolTip(_("Sets the text color of the overlay")); position_row->Add(m_overlay_font_color, 0, wxEXPAND | wxALL, 5); position_row->AddSpacer(25); position_row->Add(new wxStaticText(box, wxID_ANY, _("Scale")), 0, wxALL | wxALIGN_CENTRE_VERTICAL, 5); m_overlay_scale = new wxChoice(box, wxID_ANY, wxDefaultPosition, wxDefaultSize, std::size(text_scale), text_scale); m_overlay_scale->SetToolTip(_("Sets the scale of the overlay text")); position_row->Add(m_overlay_scale, 0, wxEXPAND | wxALL, 5); } box_sizer->Add(position_row, 0, wxEXPAND, 5); auto settings2_row = new wxFlexGridSizer(0, 4, 2, 0); { m_overlay_fps = new wxCheckBox(box, wxID_ANY, _("FPS")); m_overlay_fps->SetToolTip(_("The number of frames per second. Average over last 5 seconds")); settings2_row->Add(m_overlay_fps, 0, wxALL, 5); m_overlay_drawcalls = new wxCheckBox(box, wxID_ANY, _("Draw calls per frame")); m_overlay_drawcalls->SetToolTip(_("The number of draw calls per frame. Average over last 5 seconds")); settings2_row->Add(m_overlay_drawcalls, 0, wxALL, 5); m_overlay_cpu = new wxCheckBox(box, wxID_ANY, _("CPU usage")); m_overlay_cpu->SetToolTip(_("CPU usage of Cemu in percent")); settings2_row->Add(m_overlay_cpu, 0, wxALL, 5); m_overlay_cpu_per_core = new wxCheckBox(box, wxID_ANY, _("CPU per core usage")); m_overlay_cpu_per_core->SetToolTip(_("Total cpu usage in percent for each core")); settings2_row->Add(m_overlay_cpu_per_core, 0, wxALL, 5); m_overlay_ram = new wxCheckBox(box, wxID_ANY, _("RAM usage")); m_overlay_ram->SetToolTip(_("Cemu RAM usage in MB")); settings2_row->Add(m_overlay_ram, 0, wxALL, 5); m_overlay_vram = new wxCheckBox(box, wxID_ANY, _("VRAM usage")); #if BOOST_OS_WINDOWS using RtlGetVersion_t = LONG(WINAPI*)(PRTL_OSVERSIONINFOW lpVersionInformation); const auto pRtlGetVersion = (RtlGetVersion_t)GetProcAddress(GetModuleHandleA("ntdll.dll"), "RtlGetVersion"); //if(IsWindows8Point1OrGreater()) requires manifest RTL_OSVERSIONINFOW info{}; // Windows 8.1 6.3* if (pRtlGetVersion && pRtlGetVersion(&info) == 0 && ((info.dwMajorVersion == 6 && info.dwMinorVersion >= 3) || info.dwMajorVersion > 6)) m_overlay_vram->SetToolTip(_("The VRAM usage of Cemu in MB")); else { m_overlay_vram->SetToolTip(_("This option requires Win8.1+")); m_overlay_vram->Disable(); } #else m_overlay_vram->SetToolTip(_("The VRAM usage of Cemu in MB")); #endif settings2_row->Add(m_overlay_vram, 0, wxALL, 5); m_overlay_debug = new wxCheckBox(box, wxID_ANY, _("Debug")); m_overlay_debug->SetToolTip(_("Displays internal debug information (Vulkan only)")); settings2_row->Add(m_overlay_debug, 0, wxALL, 5); } box_sizer->Add(settings2_row, 0, wxEXPAND, 5); panel_sizer->Add(box_sizer, 0, wxEXPAND | wxALL, 5); } { auto box = new wxStaticBox(panel, wxID_ANY, _("Notifications")); auto box_sizer = new wxStaticBoxSizer(box, wxVERTICAL); auto position_row = new wxFlexGridSizer(1, 0, 0, 0); position_row->SetFlexibleDirection(wxBOTH); position_row->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); { position_row->Add(new wxStaticText(box, wxID_ANY, _("Position")), 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_notification_position = new wxChoice(box, wxID_ANY, wxDefaultPosition, wxDefaultSize, std::size(positions), positions); m_notification_position->SetSelection(0); m_notification_position->SetToolTip(_("Controls the notification position while playing")); position_row->Add(m_notification_position, 0, wxALL, 5); position_row->AddSpacer(25); position_row->Add(new wxStaticText(box, wxID_ANY, _("Text Color")), 0, wxALL | wxALIGN_CENTRE_VERTICAL, 5); m_notification_font_color = new wxColourPickerCtrl(box, wxID_ANY, *wxWHITE, wxDefaultPosition, wxDefaultSize, wxCLRP_SHOW_ALPHA); m_notification_font_color->SetToolTip(_("Sets the text color of notifications")); position_row->Add(m_notification_font_color, 0, wxEXPAND | wxALL, 5); position_row->Add(new wxStaticText(box, wxID_ANY, _("Scale")), 0, wxALL | wxALIGN_CENTRE_VERTICAL, 5); m_notification_scale = new wxChoice(box, wxID_ANY, wxDefaultPosition, wxDefaultSize, std::size(text_scale), text_scale); m_notification_scale->SetToolTip(_("Sets the scale of the notification text")); position_row->Add(m_notification_scale, 0, wxEXPAND | wxALL, 5); } box_sizer->Add(position_row, 0, wxEXPAND, 5); auto settings1_row = new wxFlexGridSizer(1, 0, 2, 0); { m_controller_profile_name = new wxCheckBox(box, wxID_ANY, _("Controller profiles")); m_controller_profile_name->SetToolTip(_("Displays the active controller profile when starting a game")); settings1_row->Add(m_controller_profile_name, 0, wxALL, 5); m_controller_low_battery = new wxCheckBox(box, wxID_ANY, _("Low battery")); m_controller_low_battery->SetToolTip(_("Shows a notification when a low controller battery has been detected")); settings1_row->Add(m_controller_low_battery, 0, wxALL, 5); m_shader_compiling = new wxCheckBox(box, wxID_ANY, _("Shader compiler")); m_shader_compiling->SetToolTip(_("Shows a notification after shaders have been compiled")); settings1_row->Add(m_shader_compiling, 0, wxALL, 5); m_friends_data = new wxCheckBox(box, wxID_ANY, _("Friend list")); m_friends_data->SetToolTip(_("Shows friend list related data if online")); settings1_row->Add(m_friends_data, 0, wxALL, 5); } box_sizer->Add(settings1_row, 0, wxEXPAND, 5); panel_sizer->Add(box_sizer, 0, wxEXPAND | wxALL, 5); } panel->SetSizerAndFit(panel_sizer); return panel; } wxPanel* GeneralSettings2::AddAccountPage(wxNotebook* notebook) { auto* online_panel = new wxPanel(notebook); auto* online_panel_sizer = new wxBoxSizer(wxVERTICAL); { auto* box = new wxStaticBox(online_panel, wxID_ANY, _("Account settings")); auto* box_sizer = new wxStaticBoxSizer(box, wxVERTICAL); auto* content = new wxFlexGridSizer(0, 4, 0, 0); content->SetFlexibleDirection(wxBOTH); content->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); content->AddGrowableCol(1, 1); content->AddGrowableCol(2, 0); content->AddGrowableCol(3, 0); content->Add(new wxStaticText(box, wxID_ANY, _("Active account")), 1, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_active_account = new wxChoice(box, wxID_ANY); m_active_account->SetMinSize({ 250, -1 }); content->Add(m_active_account, 0, wxEXPAND | wxALL, 5); m_active_account->Bind(wxEVT_CHOICE, &GeneralSettings2::OnActiveAccountChanged, this); m_create_account = new wxButton(box, wxID_ANY, _("Create")); content->Add(m_create_account, 0, wxEXPAND | wxALL | wxALIGN_RIGHT, 5); m_create_account->Bind(wxEVT_BUTTON, &GeneralSettings2::OnAccountCreate, this); m_delete_account = new wxButton(box, wxID_ANY, _("Delete")); content->Add(m_delete_account, 0, wxEXPAND | wxALL | wxALIGN_RIGHT, 5); m_delete_account->Bind(wxEVT_BUTTON, &GeneralSettings2::OnAccountDelete, this); box_sizer->Add(content, 1, wxEXPAND, 5); online_panel_sizer->Add(box_sizer, 0, wxEXPAND | wxALL, 5); if (CafeSystem::IsTitleRunning()) { m_active_account->Enable(false); m_create_account->Enable(false); m_delete_account->Enable(false); } } { wxString choices[] = { _("Offline"), _("Nintendo"), _("Pretendo"), _("Custom") }; m_active_service = new wxRadioBox(online_panel, wxID_ANY, _("Network Service"), wxDefaultPosition, wxDefaultSize, std::size(choices), choices, 4, wxRA_SPECIFY_COLS); if (!NetworkConfig::XMLExists()) m_active_service->Enable(3, false); m_active_service->SetItemToolTip(0, _("Online functionality disabled for this account")); m_active_service->SetItemToolTip(1, _("Connect to the official Nintendo Network Service")); m_active_service->SetItemToolTip(2, _("Connect to the Pretendo Network Service")); m_active_service->SetItemToolTip(3, _("Connect to a custom Network Service (configured via network_services.xml)")); m_active_service->Bind(wxEVT_RADIOBOX, &GeneralSettings2::OnAccountServiceChanged,this); online_panel_sizer->Add(m_active_service, 0, wxEXPAND | wxALL, 5); if (CafeSystem::IsTitleRunning()) { m_active_service->Enable(false); } } { auto* box = new wxStaticBox(online_panel, wxID_ANY, _("Online play requirements")); auto* box_sizer = new wxStaticBoxSizer(box, wxVERTICAL); auto* row = new wxFlexGridSizer(0, 2, 0, 0); row->SetFlexibleDirection(wxBOTH); row->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); const wxImage tmp = wxBITMAP_PNG_FROM_DATA(PNG_ERROR).ConvertToImage(); m_validate_online = new wxBitmapButton(box, wxID_ANY, tmp.Scale(16, 16)); m_validate_online->Bind(wxEVT_BUTTON, &GeneralSettings2::OnShowOnlineValidator, this); row->Add(m_validate_online, 0, wxEXPAND | wxALL, 5); m_online_status = new wxStaticText(box, wxID_ANY, _("No account selected")); row->Add(m_online_status, 1, wxALL | wxALIGN_CENTRE_VERTICAL, 5); box_sizer->Add(row, 1, wxEXPAND, 5); auto* tutorial_link = new wxHyperlinkCtrl(box, wxID_ANY, _("Online play tutorial"), "https://cemu.info/online-guide"); box_sizer->Add(tutorial_link, 0, wxALL, 5); online_panel_sizer->Add(box_sizer, 0, wxEXPAND | wxALL, 5); } { m_account_information = new wxCollapsiblePane(online_panel, wxID_ANY, _("Account information")); #if BOOST_OS_WINDOWS m_account_information->GetControlWidget()->SetBackgroundColour(*wxWHITE); #endif auto win = m_account_information->GetPane(); auto content = new wxBoxSizer(wxVERTICAL); m_account_grid = new wxPropertyGrid(win, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxPG_HIDE_MARGIN | wxPG_STATIC_SPLITTER); m_account_grid->SetExtraStyle(wxPG_EX_HELP_AS_TOOLTIPS); m_account_grid->SetMinSize({ 300, -1 }); //m_account_grid->Append(new wxPropertyCategory("Main")); auto* persistent_id_gprop = m_account_grid->Append(new wxStringProperty("PersistentId", kPropertyPersistentId)); persistent_id_gprop->SetHelpString(_("The persistent id is the internal folder name used for your saves")); m_account_grid->SetPropertyReadOnly(persistent_id_gprop); m_account_grid->Append(new wxStringProperty(_("Mii name"), kPropertyMiiName))->SetHelpString(_("The mii name is the profile name")); m_account_grid->Append(new wxStringProperty(_("Birthday"), kPropertyBirthday)); wxPGChoices gender; gender.Add(_("Female"), 0); gender.Add(_("Male"), 1); m_account_grid->Append(new wxEnumProperty(_("Gender"), kPropertyGender, gender)); m_account_grid->Append(new wxStringProperty(_("Email"), kPropertyEmail)); wxPGChoices countries; for (int i = 0; i < NCrypto::GetCountryCount(); ++i) { const auto country = NCrypto::GetCountryAsString(i); if (country && (i == 0 || !boost::equals(country, "NN"))) { countries.Add(country, i); } } m_account_grid->Append(new wxEnumProperty(_("Country"), kPropertyCountry, countries)); m_account_grid->Bind(wxEVT_PG_CHANGED, &GeneralSettings2::OnAccountSettingsChanged, this); content->Add(m_account_grid, 1, wxEXPAND | wxALL, 5); win->SetSizer(content); content->SetSizeHints(win); online_panel_sizer->Add(m_account_information, 0, wxEXPAND | wxALL, 5); } online_panel->SetSizerAndFit(online_panel_sizer); return online_panel; } wxPanel* GeneralSettings2::AddDebugPage(wxNotebook* notebook) { auto* panel = new wxPanel(notebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); auto* debug_panel_sizer = new wxBoxSizer(wxVERTICAL); { auto* debug_row = new wxFlexGridSizer(0, 2, 0, 0); debug_row->SetFlexibleDirection(wxBOTH); debug_row->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); debug_row->Add(new wxStaticText(panel, wxID_ANY, _("Crash dump"), wxDefaultPosition, wxDefaultSize, 0), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); #if BOOST_OS_WINDOWS wxString dump_choices[] = {_("Disabled"), _("Lite"), _("Full")}; #elif BOOST_OS_UNIX wxString dump_choices[] = {_("Disabled"), _("Enabled")}; #endif m_crash_dump = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, std::size(dump_choices), dump_choices); m_crash_dump->SetSelection(0); #if BOOST_OS_WINDOWS m_crash_dump->SetToolTip(_("Creates a dump when Cemu crashes\nOnly enable when requested by a developer!\nThe Full option will create a very large dump file (includes a full RAM dump of the Cemu process)")); #elif BOOST_OS_UNIX m_crash_dump->SetToolTip(_("Creates a core dump when Cemu crashes\nOnly enable when requested by a developer!")); #endif debug_row->Add(m_crash_dump, 0, wxALL | wxEXPAND, 5); debug_panel_sizer->Add(debug_row, 0, wxALL | wxEXPAND, 5); } { auto* debug_row = new wxFlexGridSizer(0, 2, 0, 0); debug_row->SetFlexibleDirection(wxBOTH); debug_row->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); debug_row->Add(new wxStaticText(panel, wxID_ANY, _("GDB Stub port"), wxDefaultPosition, wxDefaultSize, 0), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_gdb_port = new wxSpinCtrl(panel, wxID_ANY, "1337", wxDefaultPosition, wxDefaultSize, 0, 1000, 65535); m_gdb_port->SetToolTip(_("Changes the port that the GDB stub will use, which you can use by either starting Cemu with the --enable-gdbstub option or by enabling it the Debug tab.")); debug_row->Add(m_gdb_port, 0, wxALL | wxEXPAND, 5); debug_panel_sizer->Add(debug_row, 0, wxALL | wxEXPAND, 5); } panel->SetSizerAndFit(debug_panel_sizer); return panel; } GeneralSettings2::GeneralSettings2(wxWindow* parent, bool game_launched) : wxDialog(parent, wxID_ANY, _("General settings"), wxDefaultPosition, wxDefaultSize, wxCLOSE_BOX | wxCLIP_CHILDREN | wxCAPTION | wxRESIZE_BORDER), m_game_launched(game_launched) { SetIcon(wxICON(X_SETTINGS)); auto* sizer = new wxBoxSizer(wxVERTICAL); auto* notebook = new wxNotebook(this, wxID_ANY); notebook->AddPage(AddGeneralPage(notebook), _("General")); notebook->AddPage(AddGraphicsPage(notebook), _("Graphics")); notebook->AddPage(AddAudioPage(notebook), _("Audio")); notebook->AddPage(AddOverlayPage(notebook), _("Overlay")); notebook->AddPage(AddAccountPage(notebook), _("Account")); notebook->AddPage(AddDebugPage(notebook), _("Debug")); Bind(wxEVT_CLOSE_WINDOW, &GeneralSettings2::OnClose, this); // sizer->Add(notebook, 1, wxEXPAND | wxALL, 5); SetSizerAndFit(sizer); Layout(); Centre(wxBOTH); // UpdateOnlineAccounts(); UpdateAudioDeviceList(); ApplyConfig(); HandleGraphicsApiSelection(); DisableSettings(game_launched); } uint32 GeneralSettings2::GetSelectedAccountPersistentId() { const auto active_account = m_active_account->GetSelection(); if (active_account == wxNOT_FOUND) return GetConfig().account.m_persistent_id.GetInitValue(); return dynamic_cast<wxAccountData*>(m_active_account->GetClientObject(active_account))->GetAccount().GetPersistentId(); } void GeneralSettings2::StoreConfig() { auto* app = (CemuApp*)wxTheApp; auto& config = GetConfig(); config.use_discord_presence = m_discord_presence->IsChecked(); config.fullscreen_menubar = m_fullscreen_menubar->IsChecked(); config.check_update = m_auto_update->IsChecked(); config.save_screenshot = m_save_screenshot->IsChecked(); config.receive_untested_updates = m_receive_untested_releases->IsChecked(); #if BOOST_OS_LINUX && defined(ENABLE_FERAL_GAMEMODE) config.feral_gamemode = m_feral_gamemode->IsChecked(); #endif config.disable_screensaver = m_disable_screensaver->IsChecked(); // Toggle while a game is running if (CafeSystem::IsTitleRunning()) { ScreenSaver::SetInhibit(config.disable_screensaver); } // -1 is default wx widget value -> set to dummy 0 so mainwindow and padwindow will update it config.window_position = m_save_window_position_size->IsChecked() ? Vector2i{ 0,0 } : Vector2i{-1,-1}; config.window_size = m_save_window_position_size->IsChecked() ? Vector2i{ 0,0 } : Vector2i{-1,-1}; config.pad_position = m_save_padwindow_position_size->IsChecked() ? Vector2i{ 0,0 } : Vector2i{-1,-1}; config.pad_size = m_save_padwindow_position_size->IsChecked() ? Vector2i{ 0,0 } : Vector2i{-1,-1}; config.game_paths.clear(); for (auto& path : m_game_paths->GetStrings()) config.game_paths.emplace_back(path.utf8_string()); auto selection = m_language->GetSelection(); if (selection == 0) GetConfig().language = wxLANGUAGE_DEFAULT; else { const auto language = m_language->GetStringSelection(); for (const auto& lang : app->GetLanguages()) { if (lang->DescriptionNative == language) { GetConfig().language = lang->Language; break; } } } // audio if (m_audio_api->GetStringSelection() == kDirectSound) config.audio_api = IAudioAPI::DirectSound; else if (m_audio_api->GetStringSelection() == kXAudio27) config.audio_api = IAudioAPI::XAudio27; else if (m_audio_api->GetStringSelection() == kXAudio2) config.audio_api = IAudioAPI::XAudio2; else if (m_audio_api->GetStringSelection() == kCubeb) config.audio_api = IAudioAPI::Cubeb; config.audio_delay = m_audio_latency->GetValue(); config.tv_channels = (AudioChannels)m_tv_channels->GetSelection(); //config.pad_channels = (AudioChannels)m_pad_channels->GetSelection(); config.pad_channels = kStereo; // (AudioChannels)m_pad_channels->GetSelection(); //config.input_channels = (AudioChannels)m_input_channels->GetSelection(); config.input_channels = kMono; // (AudioChannels)m_input_channels->GetSelection(); config.tv_volume = m_tv_volume->GetValue(); config.pad_volume = m_pad_volume->GetValue(); config.input_volume = m_input_volume->GetValue(); config.tv_device.clear(); const auto tv_device = m_tv_device->GetSelection(); if (tv_device != wxNOT_FOUND && tv_device != 0 && m_tv_device->HasClientObjectData()) { const auto* device_description = (wxDeviceDescription*)m_tv_device->GetClientObject(tv_device); if(device_description) config.tv_device = device_description->GetDescription()->GetIdentifier(); } config.pad_device.clear(); const auto pad_device = m_pad_device->GetSelection(); if (pad_device != wxNOT_FOUND && pad_device != 0 && m_pad_device->HasClientObjectData()) { const auto* device_description = (wxDeviceDescription*)m_pad_device->GetClientObject(pad_device); if (device_description) config.pad_device = device_description->GetDescription()->GetIdentifier(); } config.input_device = L""; const auto input_device = m_input_device->GetSelection(); if (input_device != wxNOT_FOUND && input_device != 0 && m_input_device->HasClientObjectData()) { const auto* device_description = (wxDeviceDescription*)m_input_device->GetClientObject(input_device); if (device_description) config.input_device = device_description->GetDescription()->GetIdentifier(); } // graphics config.graphic_api = (GraphicAPI)m_graphic_api->GetSelection(); selection = m_graphic_device->GetSelection(); if(selection != wxNOT_FOUND) { const auto* info = (wxVulkanUUID*)m_graphic_device->GetClientObject(selection); if(info) config.graphic_device_uuid = info->GetDeviceInfo().uuid; else config.graphic_device_uuid = {}; } else config.graphic_device_uuid = {}; config.vsync = m_vsync->GetSelection(); config.gx2drawdone_sync = m_gx2drawdone_sync->IsChecked(); config.async_compile = m_async_compile->IsChecked(); config.upscale_filter = m_upscale_filter->GetSelection(); config.downscale_filter = m_downscale_filter->GetSelection(); config.fullscreen_scaling = m_fullscreen_scaling->GetSelection(); config.overlay.position = (ScreenPosition)m_overlay_position->GetSelection(); wxASSERT((int)config.overlay.position <= (int)ScreenPosition::kBottomRight); config.overlay.text_color = m_overlay_font_color->GetColour().GetRGBA(); config.overlay.text_scale = m_overlay_scale->GetSelection() * 25 + 50; config.overlay.fps = m_overlay_fps->GetValue(); config.overlay.drawcalls = m_overlay_drawcalls->GetValue(); config.overlay.cpu_usage = m_overlay_cpu->GetValue(); config.overlay.cpu_per_core_usage = m_overlay_cpu_per_core->GetValue(); config.overlay.ram_usage = m_overlay_ram->GetValue(); config.overlay.vram_usage = m_overlay_vram->GetValue(); config.overlay.debug = m_overlay_debug->GetValue(); config.notification.position = (ScreenPosition)m_notification_position->GetSelection(); wxASSERT((int)config.notification.position <= (int)ScreenPosition::kBottomRight); config.notification.text_color = m_notification_font_color->GetColour().GetRGBA(); config.notification.text_scale = m_notification_scale->GetSelection() * 25 + 50; config.notification.controller_profiles = m_controller_profile_name->GetValue(); config.notification.controller_battery = m_controller_low_battery->GetValue(); config.notification.shader_compiling = m_shader_compiling->GetValue(); config.notification.friends = m_friends_data->GetValue(); // account config.account.m_persistent_id = GetSelectedAccountPersistentId(); // debug config.crash_dump = (CrashDump)m_crash_dump->GetSelection(); config.gdb_port = m_gdb_port->GetValue(); g_config.Save(); } GeneralSettings2::~GeneralSettings2() { Unbind(wxEVT_CLOSE_WINDOW, &GeneralSettings2::OnClose, this); } void GeneralSettings2::OnClose(wxCloseEvent& event) { StoreConfig(); if (m_has_account_change) { wxCommandEvent refresh_event(wxEVT_ACCOUNTLIST_REFRESH); GetParent()->ProcessWindowEvent(refresh_event); } event.Skip(); } void GeneralSettings2::ValidateConfig() { g_config.Load(); auto& data = g_config.data(); // todo //data.fullscreen_scaling = min(max(data.fullscreen_scaling,)) } void GeneralSettings2::DisableSettings(bool game_launched) { } void GeneralSettings2::OnAudioLatencyChanged(wxCommandEvent& event) { IAudioAPI::s_audioDelay = event.GetInt(); event.Skip(); } void GeneralSettings2::OnVolumeChanged(wxCommandEvent& event) { if(event.GetEventObject() == m_input_volume) { std::shared_lock lock(g_audioInputMutex); if (g_inputAudio) g_inputAudio->SetVolume(event.GetInt()); } else { std::shared_lock lock(g_audioMutex); if(event.GetEventObject() == m_pad_volume) { if (g_padAudio) { g_padAudio->SetVolume(event.GetInt()); g_padVolume = event.GetInt(); } } else { if (g_tvAudio) g_tvAudio->SetVolume(event.GetInt()); } } event.Skip(); } void GeneralSettings2::OnInputVolumeChanged(wxCommandEvent& event) { std::shared_lock lock(g_audioMutex); if (g_padAudio) { g_padAudio->SetInputVolume(event.GetInt()); g_padVolume = event.GetInt(); } event.Skip(); } void GeneralSettings2::OnSliderChangedPercent(wxCommandEvent& event) { const auto slider = dynamic_cast<wxSlider*>(event.GetEventObject()); wxASSERT(slider); const auto control = dynamic_cast<wxControlObject*>(event.GetEventUserData()); wxASSERT(control); auto slider_text = control->GetControl<wxStaticText>(); wxASSERT(slider_text); const auto value = event.GetInt(); slider->SetValue(value); slider_text->SetLabel(wxString::Format("%d%%", value)); event.Skip(); } void GeneralSettings2::OnLatencySliderChanged(wxCommandEvent& event) { const auto slider = dynamic_cast<wxSlider*>(event.GetEventObject()); wxASSERT(slider); const auto control = dynamic_cast<wxControlObject*>(event.GetEventUserData()); wxASSERT(control); auto slider_text = control->GetControl<wxStaticText>(); wxASSERT(slider_text); const auto value = event.GetInt(); slider->SetValue(value); slider_text->SetLabel(wxString::Format("%dms", value * 12)); event.Skip(); } void GeneralSettings2::UpdateAudioDeviceList() { m_tv_device->Clear(); m_pad_device->Clear(); m_input_device->Clear(); m_tv_device->Append(_("Disabled")); m_pad_device->Append(_("Disabled")); m_input_device->Append(_("Disabled")); const auto audio_api = (IAudioAPI::AudioAPI)GetConfig().audio_api; const auto devices = IAudioAPI::GetDevices(audio_api); for (auto& device : devices) { m_tv_device->Append(device->GetName(), new wxDeviceDescription(device)); m_pad_device->Append(device->GetName(), new wxDeviceDescription(device)); } const auto input_audio_api = IAudioInputAPI::Cubeb; //(IAudioAPI::AudioAPI)GetConfig().input_audio_api; const auto input_devices = IAudioInputAPI::GetDevices(input_audio_api); for (auto& device : input_devices) { m_input_device->Append(device->GetName(), new wxInputDeviceDescription(device)); } if(m_tv_device->GetCount() > 1) m_tv_device->SetSelection(1); else m_tv_device->SetSelection(0); m_pad_device->SetSelection(0); m_input_device->SetSelection(0); // todo reset global instance of audio device } void GeneralSettings2::ResetAccountInformation() { m_account_grid->SetSplitterPosition(100); m_active_account->SetSelection(0); for(auto it = m_account_grid->GetIterator(); !it.AtEnd(); ++it) { (*it)->SetValueToUnspecified(); } // refresh pane size m_account_information->InvalidateBestSize(); #if BOOST_OS_WINDOWS m_account_information->OnStateChange(GetBestSize()); #endif } void GeneralSettings2::OnAccountCreate(wxCommandEvent& event) { wxASSERT(Account::HasFreeAccountSlots()); wxCreateAccountDialog dialog(this); if (dialog.ShowModal() == wxID_CANCEL) return; Account account(dialog.GetPersistentId(), dialog.GetMiiName().ToStdWstring()); account.Save(); Account::RefreshAccounts(); const int index = m_active_account->Append(account.ToString(), new wxAccountData(account)); // update ui m_active_account->SetSelection(index); UpdateAccountInformation(); m_create_account->Enable(m_active_account->GetCount() < 0xC); m_delete_account->Enable(m_active_account->GetCount() > 1); // send main window event wxASSERT(GetParent()); wxCommandEvent refresh_event(wxEVT_ACCOUNTLIST_REFRESH); GetParent()->ProcessWindowEvent(refresh_event); } void GeneralSettings2::OnAccountDelete(wxCommandEvent& event) { if(m_active_account->GetCount() == 1) { wxMessageBox(_("Can't delete the only account!"), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } const auto selection = m_active_account->GetSelection(); wxASSERT(selection != wxNOT_FOUND); auto* obj = dynamic_cast<wxAccountData*>(m_active_account->GetClientObject(selection)); wxASSERT(obj); auto& account = obj->GetAccount(); const std::wstring format_str = _("Are you sure you want to delete the account {} with id {:x}?").ToStdWstring(); const std::wstring msg = fmt::format(fmt::runtime(format_str), std::wstring{ account.GetMiiName() }, account.GetPersistentId()); const int answer = wxMessageBox(msg, _("Confirmation"), wxYES_NO | wxCENTRE | wxICON_QUESTION, this); if (answer == wxNO) return; // todo: ask if saves should be deleted too? const fs::path path = account.GetFileName(); try { fs::remove_all(path.parent_path()); m_active_account->Delete(selection); m_active_account->SetSelection(0); Account::RefreshAccounts(); UpdateAccountInformation(); m_create_account->Enable(m_active_account->GetCount() < 0xC); m_delete_account->Enable(m_active_account->GetCount() > 1); } catch(const std::exception& ex) { SystemException sys(ex); cemuLog_log(LogType::Force, sys.what()); } } void GeneralSettings2::OnAccountSettingsChanged(wxPropertyGridEvent& event) { wxPGProperty* property = event.GetProperty(); if (!property) return; const wxAny value = property->GetValue(); if (value.IsNull()) return; const auto selection = m_active_account->GetSelection(); wxASSERT(selection != wxNOT_FOUND); auto* obj = dynamic_cast<wxAccountData*>(m_active_account->GetClientObject(selection)); wxASSERT(obj); auto& account = obj->GetAccount(); // TODO make id changeable to free ids + current it? bool refresh_accounts = false; if (property->GetName() == kPropertyMiiName) { std::wstring new_name = value.As<wxString>().ToStdWstring(); if (new_name.empty()) new_name = L"default"; account.SetMiiName(new_name); refresh_accounts = true; } else if (property->GetName() == kPropertyBirthday) { const std::string birthday = value.As<wxString>().ToStdString(); const boost::char_separator<char> sep{ "-" }; std::vector<std::string> tokens; for (const auto& token : boost::tokenizer(birthday, sep)) { tokens.emplace_back(token); } if (tokens.size() == 3) { account.SetBirthYear(ConvertString<uint16>(tokens[0])); account.SetBirthMonth(ConvertString<uint8>(tokens[1])); account.SetBirthDay(ConvertString<uint8>(tokens[2])); } } else if (property->GetName() == kPropertyGender) { account.SetGender(value.As<int>()); } else if (property->GetName() == kPropertyEmail) { account.SetEmail(value.As<wxString>().ToStdString()); } else if (property->GetName() == kPropertyCountry) { account.SetCountry(value.As<int>()); } else cemu_assert_debug(false); account.Save(); Account::RefreshAccounts(); // refresh internal account list UpdateAccountInformation(); // refresh on invalid values if(refresh_accounts) { wxCommandEvent refresh_event(wxEVT_ACCOUNTLIST_REFRESH); GetParent()->ProcessWindowEvent(refresh_event); } } void GeneralSettings2::UpdateAccountInformation() { m_account_grid->SetSplitterPosition(100); const auto selection = m_active_account->GetSelection(); if(selection == wxNOT_FOUND) { m_validate_online->SetBitmap(wxBITMAP_PNG_FROM_DATA(PNG_ERROR).ConvertToImage().Scale(16, 16)); m_validate_online->SetWindowStyleFlag(m_validate_online->GetWindowStyleFlag() & ~wxBORDER_NONE); ResetAccountInformation(); m_online_status->SetLabel(_("No account selected")); return; } const auto* obj = dynamic_cast<wxAccountData*>(m_active_account->GetClientObject(selection)); wxASSERT(obj); const auto& account = obj->GetAccount(); m_active_account->SetString(selection, account.ToString()); m_account_grid->GetProperty(kPropertyPersistentId)->SetValueFromString(fmt::format("{:x}", account.GetPersistentId())); m_account_grid->GetProperty(kPropertyMiiName)->SetValueFromString(std::wstring{ account.GetMiiName() }); m_account_grid->GetProperty(kPropertyBirthday)->SetValueFromString(fmt::format("{:04d}-{:02d}-{:02d}", account.GetBirthYear(), account.GetBirthMonth(), account.GetBirthDay())); const auto gender_property = m_account_grid->GetProperty(kPropertyGender); // gender 2 can be also female? gender_property->SetChoiceSelection(std::min(gender_property->GetChoices().GetCount() - 1, (uint32)account.GetGender())); m_account_grid->GetProperty(kPropertyEmail)->SetValueFromString(std::string{ account.GetEmail() }); auto* country_property = dynamic_cast<wxEnumProperty*>(m_account_grid->GetProperty(kPropertyCountry)); wxASSERT(country_property); int index = (country_property)->GetIndexForValue(account.GetCountry()); if (index == wxNOT_FOUND) index = 0; country_property->SetChoiceSelection(index); const bool online_fully_valid = account.IsValidOnlineAccount() && ActiveSettings::HasRequiredOnlineFiles(); if (ActiveSettings::HasRequiredOnlineFiles()) { if(account.IsValidOnlineAccount()) m_online_status->SetLabel(_("Selected account is a valid online account")); else m_online_status->SetLabel(_("Selected account is not linked to a NNID or PNID")); } else { if(NCrypto::OTP_IsPresent() != NCrypto::SEEPROM_IsPresent()) m_online_status->SetLabel(_("OTP.bin or SEEPROM.bin is missing")); else if(NCrypto::OTP_IsPresent() && NCrypto::SEEPROM_IsPresent()) m_online_status->SetLabel(_("OTP and SEEPROM present but no certificate files were found")); else m_online_status->SetLabel(_("Online play is not set up. Follow the guide below to get started")); } if(online_fully_valid) { m_validate_online->SetBitmap(wxBITMAP_PNG_FROM_DATA(PNG_CHECK_YES).ConvertToImage().Scale(16, 16)); m_validate_online->SetWindowStyleFlag(m_validate_online->GetWindowStyleFlag() | wxBORDER_NONE); } else { m_validate_online->SetBitmap(wxBITMAP_PNG_FROM_DATA(PNG_ERROR).ConvertToImage().Scale(16, 16)); m_validate_online->SetWindowStyleFlag(m_validate_online->GetWindowStyleFlag() & ~wxBORDER_NONE); } // enable/disable network service field depending on online requirements m_active_service->Enable(online_fully_valid && !CafeSystem::IsTitleRunning()); if(online_fully_valid) { NetworkService service = GetConfig().GetAccountNetworkService(account.GetPersistentId()); m_active_service->SetSelection(static_cast<int>(service)); // set the config option here for the selected service // this will guarantee that it's actually written to settings.xml // allowing us to eventually get rid of the legacy option in the (far) future GetConfig().SetAccountSelectedService(account.GetPersistentId(), service); } else { m_active_service->SetSelection(0); // force offline } wxString tmp = _("Network service"); tmp.append(" ("); tmp.append(wxString::FromUTF8(boost::nowide::narrow(account.GetMiiName()))); tmp.append(")"); m_active_service->SetLabel(tmp); // refresh pane size m_account_grid->InvalidateBestSize(); //m_account_grid->GetParent()->FitInside(); //m_account_information->OnStateChange(GetBestSize()); idk.. } void GeneralSettings2::UpdateOnlineAccounts() { m_active_account->Clear(); for(const auto& account : Account::GetAccounts()) { m_active_account->Append(fmt::format(L"{} ({:x})", std::wstring{ account.GetMiiName() }, account.GetPersistentId()), new wxAccountData(account)); } m_active_account->SetSelection(0); m_create_account->Enable(m_active_account->GetCount() < 0xC); m_delete_account->Enable(m_active_account->GetCount() > 1); UpdateAccountInformation(); } void GeneralSettings2::HandleGraphicsApiSelection() { int selection = m_vsync->GetSelection(); if(selection == wxNOT_FOUND) selection = GetConfig().vsync; m_vsync->Clear(); if(m_graphic_api->GetSelection() == 0) { // OpenGL m_vsync->AppendString(_("Off")); m_vsync->AppendString(_("On")); if (selection == 0) m_vsync->Select(0); else m_vsync->Select(1); m_graphic_device->Clear(); m_graphic_device->Disable(); m_gx2drawdone_sync->Enable(); m_async_compile->Disable(); } else { // Vulkan m_gx2drawdone_sync->Disable(); m_async_compile->Enable(); m_vsync->AppendString(_("Off")); m_vsync->AppendString(_("Double buffering")); m_vsync->AppendString(_("Triple buffering")); #if BOOST_OS_WINDOWS m_vsync->AppendString(_("Match emulated display (Experimental)")); #endif m_vsync->Select(selection); m_graphic_device->Enable(); auto devices = VulkanRenderer::GetDevices(); m_graphic_device->Clear(); if(!devices.empty()) { for(const auto& device : devices) { m_graphic_device->Append(device.name, new wxVulkanUUID(device)); } m_graphic_device->SetSelection(0); const auto& config = GetConfig(); for(size_t i = 0; i < devices.size(); ++i) { if(config.graphic_device_uuid == devices[i].uuid) { m_graphic_device->SetSelection(i); break; } } } } } void GeneralSettings2::ApplyConfig() { ValidateConfig(); auto& config = GetConfig(); if (LaunchSettings::GetMLCPath().has_value()) m_mlc_path->SetValue(wxHelper::FromPath(LaunchSettings::GetMLCPath().value())); else m_mlc_path->SetValue(wxHelper::FromUtf8(config.mlc_path.GetValue())); m_save_window_position_size->SetValue(config.window_position != Vector2i{-1,-1}); m_save_padwindow_position_size->SetValue(config.pad_position != Vector2i{-1,-1}); m_discord_presence->SetValue(config.use_discord_presence); m_fullscreen_menubar->SetValue(config.fullscreen_menubar); m_auto_update->SetValue(config.check_update); m_receive_untested_releases->SetValue(config.receive_untested_updates); m_save_screenshot->SetValue(config.save_screenshot); m_disable_screensaver->SetValue(config.disable_screensaver); #if BOOST_OS_LINUX && defined(ENABLE_FERAL_GAMEMODE) m_feral_gamemode->SetValue(config.feral_gamemode); #endif // temporary workaround because feature crashes on macOS #if BOOST_OS_MACOS m_disable_screensaver->SetValue(false); #endif m_game_paths->Clear(); for (auto& path : config.game_paths) { m_game_paths->Append(to_wxString(path)); } const auto app = (CemuApp*)wxTheApp; for (const auto& language : app->GetLanguages()) { if (config.language == language->Language) { m_language->SetStringSelection(language->DescriptionNative); break; } } // graphics m_graphic_api->SetSelection(config.graphic_api); m_vsync->SetSelection(config.vsync); m_async_compile->SetValue(config.async_compile); m_gx2drawdone_sync->SetValue(config.gx2drawdone_sync); m_upscale_filter->SetSelection(config.upscale_filter); m_downscale_filter->SetSelection(config.downscale_filter); m_fullscreen_scaling->SetSelection(config.fullscreen_scaling); wxASSERT((uint32)config.overlay.position < m_overlay_position->GetCount()); m_overlay_position->SetSelection((int)config.overlay.position); m_overlay_font_color->SetColour(wxColour((unsigned long)config.overlay.text_color)); uint32 selection = (config.overlay.text_scale - 50) / 25; wxASSERT(selection < m_overlay_scale->GetCount()); m_overlay_scale->SetSelection(selection); m_overlay_fps->SetValue(config.overlay.fps); m_overlay_drawcalls->SetValue(config.overlay.drawcalls); m_overlay_cpu->SetValue(config.overlay.cpu_usage); m_overlay_cpu_per_core->SetValue(config.overlay.cpu_per_core_usage); m_overlay_ram->SetValue(config.overlay.ram_usage); m_overlay_vram->SetValue(config.overlay.vram_usage); m_overlay_debug->SetValue(config.overlay.debug); wxASSERT((uint32)config.notification.position < m_notification_position->GetCount()); m_notification_position->SetSelection((int)config.notification.position); m_notification_font_color->SetColour(wxColour((unsigned long)config.notification.text_color)); selection = (config.notification.text_scale - 50) / 25; wxASSERT(selection < m_notification_scale->GetCount()); m_notification_scale->SetSelection(selection); m_controller_profile_name->SetValue(config.notification.controller_profiles); m_controller_low_battery->SetValue(config.notification.controller_battery); m_shader_compiling->SetValue(config.notification.shader_compiling); m_friends_data->SetValue(config.notification.friends); // audio if(config.audio_api == IAudioAPI::DirectSound) m_audio_api->SetStringSelection(kDirectSound); else if(config.audio_api == IAudioAPI::XAudio27) m_audio_api->SetStringSelection(kXAudio27); else if(config.audio_api == IAudioAPI::XAudio2) m_audio_api->SetStringSelection(kXAudio2); else if(config.audio_api == IAudioAPI::Cubeb) m_audio_api->SetStringSelection(kCubeb); SendSliderEvent(m_audio_latency, config.audio_delay); m_tv_channels->SetSelection(config.tv_channels); //m_pad_channels->SetSelection(config.pad_channels); m_pad_channels->SetSelection(0); //m_input_channels->SetSelection(config.pad_channels); m_input_channels->SetSelection(0); SendSliderEvent(m_tv_volume, config.tv_volume); if (!config.tv_device.empty() && m_tv_device->HasClientObjectData()) { for(uint32 i = 0; i < m_tv_device->GetCount(); ++i) { const auto device_description = (wxDeviceDescription*)m_tv_device->GetClientObject(i); if (device_description && config.tv_device == device_description->GetDescription()->GetIdentifier()) { m_tv_device->SetSelection(i); break; } } } else m_tv_device->SetSelection(0); SendSliderEvent(m_pad_volume, config.pad_volume); if (!config.pad_device.empty() && m_pad_device->HasClientObjectData()) { for (uint32 i = 0; i < m_pad_device->GetCount(); ++i) { const auto device_description = (wxDeviceDescription*)m_pad_device->GetClientObject(i); if (device_description && config.pad_device == device_description->GetDescription()->GetIdentifier()) { m_pad_device->SetSelection(i); break; } } } else m_pad_device->SetSelection(0); SendSliderEvent(m_input_volume, config.input_volume); if (!config.input_device.empty() && m_input_device->HasClientObjectData()) { for (uint32 i = 0; i < m_input_device->GetCount(); ++i) { const auto device_description = (wxInputDeviceDescription*)m_input_device->GetClientObject(i); if (device_description && config.input_device == device_description->GetDescription()->GetIdentifier()) { m_input_device->SetSelection(i); break; } } } else m_input_device->SetSelection(0); // account UpdateOnlineAccounts(); m_active_account->SetSelection(0); for(uint32 i = 0; i < m_active_account->GetCount(); ++i) { const auto* obj = dynamic_cast<wxAccountData*>(m_active_account->GetClientObject(i)); wxASSERT(obj); if(obj->GetAccount().GetPersistentId() == ActiveSettings::GetPersistentId()) { m_active_account->SetSelection(i); break; } } m_active_service->SetSelection((int)config.GetAccountNetworkService(ActiveSettings::GetPersistentId())); UpdateAccountInformation(); // debug m_crash_dump->SetSelection((int)config.crash_dump.GetValue()); m_gdb_port->SetValue(config.gdb_port.GetValue()); } void GeneralSettings2::OnAudioAPISelected(wxCommandEvent& event) { IAudioAPI::AudioAPI api; if (m_audio_api->GetStringSelection() == kDirectSound) api = IAudioAPI::DirectSound; else if (m_audio_api->GetStringSelection() == kXAudio27) api = IAudioAPI::XAudio27; else if (m_audio_api->GetStringSelection() == kXAudio2) api = IAudioAPI::XAudio2; else if (m_audio_api->GetStringSelection() == kCubeb) api = IAudioAPI::Cubeb; else { wxFAIL_MSG("invalid audio api selected!"); return; } GetConfig().audio_api = api; UpdateAudioDeviceList(); OnAudioDeviceSelected(event); } #define AX_FRAMES_PER_GROUP 4 void GeneralSettings2::UpdateAudioDevice() { auto& config = GetConfig(); std::unique_lock lock(g_audioMutex); std::unique_lock inputLock(g_audioInputMutex); // tv audio device { const auto selection = m_tv_device->GetSelection(); if (selection == wxNOT_FOUND) { cemu_assert_debug(false); return; } g_tvAudio.reset(); if (m_tv_device->HasClientObjectData()) { const auto description = (wxDeviceDescription*)m_tv_device->GetClientObject(selection); if (description) { sint32 channels; if (m_game_launched && g_tvAudio) channels = g_tvAudio->GetChannels(); else { switch (config.tv_channels) { case 0: channels = 1; break; case 2: channels = 6; break; default: // stereo channels = 2; break; } } try { g_tvAudio = IAudioAPI::CreateDevice((IAudioAPI::AudioAPI)config.audio_api, description->GetDescription(), 48000, channels, snd_core::AX_SAMPLES_PER_3MS_48KHZ * AX_FRAMES_PER_GROUP, 16); g_tvAudio->SetVolume(m_tv_volume->GetValue()); } catch (std::runtime_error& ex) { cemuLog_log(LogType::Force, "can't initialize tv audio: {}", ex.what()); } } } } // pad audio device { const auto selection = m_pad_device->GetSelection(); if (selection == wxNOT_FOUND) { cemu_assert_debug(false); return; } g_padAudio.reset(); if (m_pad_device->HasClientObjectData()) { const auto description = (wxDeviceDescription*)m_pad_device->GetClientObject(selection); if (description) { sint32 channels; if (m_game_launched && g_padAudio) channels = g_padAudio->GetChannels(); else { switch (config.pad_channels) { case 0: channels = 1; break; case 2: channels = 6; break; default: // stereo channels = 2; break; } } try { g_padAudio = IAudioAPI::CreateDevice((IAudioAPI::AudioAPI)config.audio_api, description->GetDescription(), 48000, channels, snd_core::AX_SAMPLES_PER_3MS_48KHZ * AX_FRAMES_PER_GROUP, 16); g_padAudio->SetVolume(m_pad_volume->GetValue()); g_padVolume = m_pad_volume->GetValue(); } catch (std::runtime_error& ex) { cemuLog_log(LogType::Force, "can't initialize pad audio: {}", ex.what()); } } } } // input audio device { const auto selection = m_input_device->GetSelection(); if (selection == wxNOT_FOUND) { cemu_assert_debug(false); return; } g_inputAudio.reset(); if (m_input_device->HasClientObjectData()) { const auto description = (wxInputDeviceDescription*)m_input_device->GetClientObject(selection); if (description) { sint32 channels; if (m_game_launched && g_inputAudio) channels = g_inputAudio->GetChannels(); else { switch (config.input_channels) { case 0: channels = 1; break; case 2: channels = 6; break; default: // stereo channels = 2; break; } } try { g_inputAudio = IAudioInputAPI::CreateDevice(IAudioInputAPI::AudioInputAPI::Cubeb, description->GetDescription(), 32000, channels, snd_core::AX_SAMPLES_PER_3MS_32KHZ, 16); g_inputAudio->SetVolume(m_input_volume->GetValue()); } catch (std::runtime_error& ex) { cemuLog_log(LogType::Force, "can't initialize pad audio: {}", ex.what()); } } } } } void GeneralSettings2::OnAudioDeviceSelected(wxCommandEvent& event) { UpdateAudioDevice(); } void GeneralSettings2::OnAudioChannelsSelected(wxCommandEvent& event) { const auto obj = wxDynamicCast(event.GetEventObject(), wxChoice); wxASSERT(obj); if (obj->GetSelection() == wxNOT_FOUND) return; auto& config = GetConfig(); if (obj == m_tv_channels) { if (config.tv_channels == (AudioChannels)obj->GetSelection()) return; config.tv_channels = (AudioChannels)obj->GetSelection(); } else if (obj == m_pad_channels) { if (config.pad_channels == (AudioChannels)obj->GetSelection()) return; config.pad_channels = (AudioChannels)obj->GetSelection(); } else cemu_assert_debug(false); if(m_game_launched) wxMessageBox(_("You have to restart the game in order to apply the new settings."), _("Information"), wxOK | wxCENTRE, this); else UpdateAudioDevice(); } void GeneralSettings2::OnGraphicAPISelected(wxCommandEvent& event) { HandleGraphicsApiSelection(); } void GeneralSettings2::OnAddPathClicked(wxCommandEvent& event) { wxDirDialog path_dialog(this, _("Select a directory containing games."), wxEmptyString, wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST); if (path_dialog.ShowModal() != wxID_OK || path_dialog.GetPath().empty()) return; const auto path = path_dialog.GetPath(); // test if already included for (auto& s : m_game_paths->GetStrings()) { if (s == path) return; } m_game_paths->Append(path); m_reload_gamelist = true; // trigger title list rescan with new path configuration CafeTitleList::ClearScanPaths(); for (auto& it : m_game_paths->GetStrings()) CafeTitleList::AddScanPath(wxHelper::MakeFSPath(it)); CafeTitleList::Refresh(); } void GeneralSettings2::OnRemovePathClicked(wxCommandEvent& event) { const auto selection = m_game_paths->GetSelection(); if (selection == wxNOT_FOUND) return; m_game_paths->Delete(selection); m_reload_gamelist = true; // trigger title list rescan with new path configuration CafeTitleList::ClearScanPaths(); for (auto& it : m_game_paths->GetStrings()) CafeTitleList::AddScanPath(wxHelper::MakeFSPath(it)); CafeTitleList::Refresh(); } void GeneralSettings2::OnActiveAccountChanged(wxCommandEvent& event) { UpdateAccountInformation(); m_has_account_change = true; } void GeneralSettings2::OnAccountServiceChanged(wxCommandEvent& event) { auto& config = GetConfig(); uint32 peristentId = GetSelectedAccountPersistentId(); config.SetAccountSelectedService(peristentId, static_cast<NetworkService>(m_active_service->GetSelection())); UpdateAccountInformation(); } void GeneralSettings2::OnMLCPathSelect(wxCommandEvent& event) { if(CafeSystem::IsTitleRunning()) { wxMessageBox(_("Can't change MLC path while a game is running!"), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } // show directory dialog wxDirDialog path_dialog(this, _("Select MLC directory"), wxEmptyString, wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST); if (path_dialog.ShowModal() != wxID_OK || path_dialog.GetPath().empty()) return; // check if the choosen MLC path is an already initialized MLC location fs::path newMlc = wxHelper::MakeFSPath(path_dialog.GetPath()); if(CemuApp::CheckMLCPath(newMlc)) { // ask user if they are sure they want to use this folder and let them know that accounts and saves wont transfer wxString message = _("Note that changing the MLC location will not transfer any accounts or save files. Are you sure you want to change the path?"); wxMessageDialog dialog(this, message, _("Warning"), wxYES_NO | wxCENTRE | wxICON_WARNING); if(dialog.ShowModal() == wxID_NO) return; if( !CemuApp::CreateDefaultMLCFiles(newMlc) ) // creating also acts as a check for read+write access { wxMessageBox(_("Failed to create default MLC files in the selected directory. The MLC path has not been changed"), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } } else { // ask user if they want to create a new mlc structure at the choosen location wxString message = _("The selected directory does not contain the expected MLC structure. Do you want to create a new MLC structure in this directory?\nNote that changing the MLC location will not transfer any accounts or save files."); wxMessageDialog dialog(this, message, _("Warning"), wxYES_NO | wxCENTRE | wxICON_WARNING); if( !CemuApp::CreateDefaultMLCFiles(newMlc) ) { wxMessageBox(_("Failed to create default MLC files in the selected directory. The MLC path has not been changed"), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } } // update MLC path and store any other modified settings GetConfig().SetMLCPath(newMlc); StoreConfig(); wxMessageBox(_("Cemu needs to be restarted for the changes to take effect."), _("Information"), wxOK | wxCENTRE | wxICON_INFORMATION, this); // close settings and then cemu wxCloseEvent closeEvent(wxEVT_CLOSE_WINDOW); wxPostEvent(this, closeEvent); wxPostEvent(GetParent(), closeEvent); } void GeneralSettings2::OnMLCPathClear(wxCommandEvent& event) { if(CafeSystem::IsTitleRunning()) { wxMessageBox(_("Can't change MLC path while a game is running!"), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } wxString message = _("Note that changing the MLC location will not transfer any accounts or save files. Are you sure you want to change the path?"); wxMessageDialog dialog(this, message, _("Warning"), wxYES_NO | wxCENTRE | wxICON_WARNING); if(dialog.ShowModal() == wxID_NO) return; GetConfig().SetMLCPath(""); StoreConfig(); g_config.Save(); wxMessageBox(_("Cemu needs to be restarted for the changes to take effect."), _("Information"), wxOK | wxCENTRE | wxICON_INFORMATION, this); // close settings and then cemu wxCloseEvent closeEvent(wxEVT_CLOSE_WINDOW); wxPostEvent(this, closeEvent); wxPostEvent(GetParent(), closeEvent); } void GeneralSettings2::OnShowOnlineValidator(wxCommandEvent& event) { const auto selection = m_active_account->GetSelection(); if (selection == wxNOT_FOUND) return; const auto* obj = dynamic_cast<wxAccountData*>(m_active_account->GetClientObject(selection)); wxASSERT(obj); const auto& account = obj->GetAccount(); const auto validator = account.ValidateOnlineFiles(); if (validator) // everything valid? shouldn't happen return; wxString err; err << _("The following error(s) have been found:") << '\n'; if (validator.otp == OnlineValidator::FileState::Missing) err << _("otp.bin missing in Cemu directory") << '\n'; else if(validator.otp == OnlineValidator::FileState::Corrupted) err << _("otp.bin is invalid") << '\n'; if (validator.seeprom == OnlineValidator::FileState::Missing) err << _("seeprom.bin missing in Cemu directory") << '\n'; else if(validator.seeprom == OnlineValidator::FileState::Corrupted) err << _("seeprom.bin is invalid") << '\n'; if(!validator.missing_files.empty()) { err << _("Missing certificate and key files:") << '\n'; int counter = 0; for (const auto& f : validator.missing_files) { err << f << '\n'; ++counter; if(counter > 10) { err << "..." << '\n'; break; } } err << '\n'; } if (!validator.valid_account) { err << _("The currently selected account is not a valid or dumped online account:") << '\n'; err << GetOnlineAccountErrorMessage(validator.account_error); } wxMessageBox(err, _("Online Status"), wxOK | wxCENTRE | wxICON_INFORMATION); } wxString GeneralSettings2::GetOnlineAccountErrorMessage(OnlineAccountError error) { switch (error) { case OnlineAccountError::kNoAccountId: return _("AccountId missing (The account is not connected to a NNID/PNID)"); case OnlineAccountError::kNoPasswordCached: return _("IsPasswordCacheEnabled is set to false (The remember password option on your Wii U must be enabled for this account before dumping it)"); case OnlineAccountError::kPasswordCacheEmpty: return _("AccountPasswordCache is empty (The remember password option on your Wii U must be enabled for this account before dumping it)"); case OnlineAccountError::kNoPrincipalId: return _("PrincipalId missing"); default: return "no error"; } }
78,673
C++
.cpp
1,754
41.868871
288
0.735486
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,968
MainWindow.cpp
cemu-project_Cemu/src/gui/MainWindow.cpp
#include "gui/wxgui.h" #include "gui/MainWindow.h" #include "gui/guiWrapper.h" #include <wx/mstream.h> #include <wx/clipbrd.h> #include "gui/GameUpdateWindow.h" #include "gui/PadViewFrame.h" #include "gui/windows/TextureRelationViewer/TextureRelationWindow.h" #include "gui/windows/PPCThreadsViewer/DebugPPCThreadsWindow.h" #include "audio/audioDebuggerWindow.h" #include "gui/canvas/OpenGLCanvas.h" #include "gui/canvas/VulkanCanvas.h" #include "Cafe/OS/libs/nfc/nfc.h" #include "Cafe/OS/libs/swkbd/swkbd.h" #include "gui/debugger/DebuggerWindow2.h" #include "util/helpers/helpers.h" #include "config/CemuConfig.h" #include "Cemu/DiscordPresence/DiscordPresence.h" #include "util/ScreenSaver/ScreenSaver.h" #include "gui/GeneralSettings2.h" #include "gui/GraphicPacksWindow2.h" #include "gui/CemuApp.h" #include "gui/CemuUpdateWindow.h" #include "gui/LoggingWindow.h" #include "config/ActiveSettings.h" #include "config/LaunchSettings.h" #include "Cafe/Filesystem/FST/FST.h" #include "gui/TitleManager.h" #include "gui/EmulatedUSBDevices/EmulatedUSBDeviceFrame.h" #include "Cafe/CafeSystem.h" #include "util/helpers/SystemException.h" #include "gui/DownloadGraphicPacksWindow.h" #include "gui/GettingStartedDialog.h" #include "gui/helpers/wxHelpers.h" #include "Cafe/HW/Latte/Renderer/Vulkan/VsyncDriver.h" #include "gui/input/InputSettings2.h" #include "input/InputManager.h" #if BOOST_OS_WINDOWS #define exit(__c) ExitProcess(__c) #else #define exit(__c) _Exit(__c) #endif #if BOOST_OS_LINUX || BOOST_OS_MACOS #include "resource/embedded/resources.h" #endif #if BOOST_OS_LINUX && HAS_WAYLAND #include "gui/helpers/wxWayland.h" #endif //GameMode support #if BOOST_OS_LINUX && defined(ENABLE_FERAL_GAMEMODE) #include "gamemode_client.h" #endif #include "Cafe/TitleList/TitleInfo.h" #include "Cafe/TitleList/TitleList.h" #include "wxHelper.h" extern WindowInfo g_window_info; extern std::shared_mutex g_mutex; enum { // ui elements MAINFRAME_GAMELIST_ID = 20000, //wxID_HIGHEST + 1, // file MAINFRAME_MENU_ID_FILE_LOAD = 20100, MAINFRAME_MENU_ID_FILE_INSTALL_UPDATE, MAINFRAME_MENU_ID_FILE_OPEN_CEMU_FOLDER, MAINFRAME_MENU_ID_FILE_OPEN_MLC_FOLDER, MAINFRAME_MENU_ID_FILE_EXIT, MAINFRAME_MENU_ID_FILE_END_EMULATION, MAINFRAME_MENU_ID_FILE_RECENT_0, MAINFRAME_MENU_ID_FILE_RECENT_LAST = MAINFRAME_MENU_ID_FILE_RECENT_0 + 15, // options MAINFRAME_MENU_ID_OPTIONS_FULLSCREEN = 20200, MAINFRAME_MENU_ID_OPTIONS_SECOND_WINDOW_PADVIEW, MAINFRAME_MENU_ID_OPTIONS_GRAPHIC, MAINFRAME_MENU_ID_OPTIONS_GRAPHIC_PACKS2, MAINFRAME_MENU_ID_OPTIONS_GENERAL, MAINFRAME_MENU_ID_OPTIONS_GENERAL2, MAINFRAME_MENU_ID_OPTIONS_AUDIO, MAINFRAME_MENU_ID_OPTIONS_INPUT, // options -> account MAINFRAME_MENU_ID_OPTIONS_ACCOUNT_1 = 20350, MAINFRAME_MENU_ID_OPTIONS_ACCOUNT_12 = 20350 + 11, // options -> system language MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_JAPANESE = 20500, MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_ENGLISH, MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_FRENCH, MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_GERMAN, MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_ITALIAN, MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_SPANISH, MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_CHINESE, MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_KOREAN, MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_DUTCH, MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_PORTUGUESE, MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_RUSSIAN, MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_TAIWANESE, // tools MAINFRAME_MENU_ID_TOOLS_MEMORY_SEARCHER = 20600, MAINFRAME_MENU_ID_TOOLS_TITLE_MANAGER, MAINFRAME_MENU_ID_TOOLS_DOWNLOAD_MANAGER, MAINFRAME_MENU_ID_TOOLS_EMULATED_USB_DEVICES, // cpu // cpu->timer speed MAINFRAME_MENU_ID_TIMER_SPEED_1X = 20700, MAINFRAME_MENU_ID_TIMER_SPEED_2X = 20701, MAINFRAME_MENU_ID_TIMER_SPEED_4X = 20702, MAINFRAME_MENU_ID_TIMER_SPEED_8X = 20703, MAINFRAME_MENU_ID_TIMER_SPEED_05X = 20704, MAINFRAME_MENU_ID_TIMER_SPEED_025X = 20705, MAINFRAME_MENU_ID_TIMER_SPEED_0125X = 20706, // nfc->Touch NFC file MAINFRAME_MENU_ID_NFC_TOUCH_NFC_FILE = 21000, MAINFRAME_MENU_ID_NFC_RECENT_0, MAINFRAME_MENU_ID_NFC_RECENT_LAST = MAINFRAME_MENU_ID_NFC_RECENT_0 + 15, // debug MAINFRAME_MENU_ID_DEBUG_RENDER_UPSIDE_DOWN = 21100, MAINFRAME_MENU_ID_DEBUG_VIEW_LOGGING_WINDOW, MAINFRAME_MENU_ID_DEBUG_TOGGLE_GDB_STUB, MAINFRAME_MENU_ID_DEBUG_VIEW_PPC_THREADS, MAINFRAME_MENU_ID_DEBUG_VIEW_PPC_DEBUGGER, MAINFRAME_MENU_ID_DEBUG_VIEW_AUDIO_DEBUGGER, MAINFRAME_MENU_ID_DEBUG_VIEW_TEXTURE_RELATIONS, MAINFRAME_MENU_ID_DEBUG_AUDIO_AUX_ONLY, MAINFRAME_MENU_ID_DEBUG_VK_ACCURATE_BARRIERS, // debug->logging MAINFRAME_MENU_ID_DEBUG_LOGGING0 = 21500, MAINFRAME_MENU_ID_DEBUG_ADVANCED_PPC_INFO = 21599, // debug->dump MAINFRAME_MENU_ID_DEBUG_DUMP_TEXTURES = 21600, MAINFRAME_MENU_ID_DEBUG_DUMP_SHADERS, MAINFRAME_MENU_ID_DEBUG_DUMP_RAM, MAINFRAME_MENU_ID_DEBUG_DUMP_FST, MAINFRAME_MENU_ID_DEBUG_DUMP_CURL_REQUESTS, // help MAINFRAME_MENU_ID_HELP_ABOUT = 21700, MAINFRAME_MENU_ID_HELP_UPDATE, // custom MAINFRAME_ID_TIMER1 = 21800, }; wxDEFINE_EVENT(wxEVT_SET_WINDOW_TITLE, wxCommandEvent); wxDEFINE_EVENT(wxEVT_REQUEST_GAMELIST_REFRESH, wxCommandEvent); wxDEFINE_EVENT(wxEVT_LAUNCH_GAME, wxLaunchGameEvent); wxDEFINE_EVENT(wxEVT_REQUEST_RECREATE_CANVAS, wxCommandEvent); wxBEGIN_EVENT_TABLE(MainWindow, wxFrame) EVT_TIMER(MAINFRAME_ID_TIMER1, MainWindow::OnTimer) EVT_CLOSE(MainWindow::OnClose) EVT_SIZE(MainWindow::OnSizeEvent) EVT_DPI_CHANGED(MainWindow::OnDPIChangedEvent) EVT_MOVE(MainWindow::OnMove) // file menu EVT_MENU(MAINFRAME_MENU_ID_FILE_LOAD, MainWindow::OnFileMenu) EVT_MENU(MAINFRAME_MENU_ID_FILE_INSTALL_UPDATE, MainWindow::OnInstallUpdate) EVT_MENU(MAINFRAME_MENU_ID_FILE_OPEN_CEMU_FOLDER, MainWindow::OnOpenFolder) EVT_MENU(MAINFRAME_MENU_ID_FILE_OPEN_MLC_FOLDER, MainWindow::OnOpenFolder) EVT_MENU(MAINFRAME_MENU_ID_FILE_EXIT, MainWindow::OnFileExit) EVT_MENU(MAINFRAME_MENU_ID_FILE_END_EMULATION, MainWindow::OnFileMenu) EVT_MENU_RANGE(MAINFRAME_MENU_ID_FILE_RECENT_0 + 0, MAINFRAME_MENU_ID_FILE_RECENT_LAST, MainWindow::OnFileMenu) // options -> region menu EVT_MENU_RANGE(MAINFRAME_MENU_ID_OPTIONS_ACCOUNT_1, MAINFRAME_MENU_ID_OPTIONS_ACCOUNT_12, MainWindow::OnAccountSelect) EVT_MENU_RANGE(MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_JAPANESE, MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_TAIWANESE, MainWindow::OnConsoleLanguage) // options menu EVT_MENU(MAINFRAME_MENU_ID_OPTIONS_FULLSCREEN, MainWindow::OnOptionsInput) EVT_MENU(MAINFRAME_MENU_ID_OPTIONS_SECOND_WINDOW_PADVIEW, MainWindow::OnOptionsInput) EVT_MENU(MAINFRAME_MENU_ID_OPTIONS_GRAPHIC, MainWindow::OnOptionsInput) EVT_MENU(MAINFRAME_MENU_ID_OPTIONS_GRAPHIC_PACKS2, MainWindow::OnOptionsInput) EVT_MENU(MAINFRAME_MENU_ID_OPTIONS_GENERAL, MainWindow::OnOptionsInput) EVT_MENU(MAINFRAME_MENU_ID_OPTIONS_GENERAL2, MainWindow::OnOptionsInput) EVT_MENU(MAINFRAME_MENU_ID_OPTIONS_AUDIO, MainWindow::OnOptionsInput) EVT_MENU(MAINFRAME_MENU_ID_OPTIONS_INPUT, MainWindow::OnOptionsInput) // tools menu EVT_MENU(MAINFRAME_MENU_ID_TOOLS_MEMORY_SEARCHER, MainWindow::OnToolsInput) EVT_MENU(MAINFRAME_MENU_ID_TOOLS_TITLE_MANAGER, MainWindow::OnToolsInput) EVT_MENU(MAINFRAME_MENU_ID_TOOLS_DOWNLOAD_MANAGER, MainWindow::OnToolsInput) EVT_MENU(MAINFRAME_MENU_ID_TOOLS_EMULATED_USB_DEVICES, MainWindow::OnToolsInput) // cpu menu EVT_MENU(MAINFRAME_MENU_ID_TIMER_SPEED_8X, MainWindow::OnDebugSetting) EVT_MENU(MAINFRAME_MENU_ID_TIMER_SPEED_4X, MainWindow::OnDebugSetting) EVT_MENU(MAINFRAME_MENU_ID_TIMER_SPEED_2X, MainWindow::OnDebugSetting) EVT_MENU(MAINFRAME_MENU_ID_TIMER_SPEED_1X, MainWindow::OnDebugSetting) EVT_MENU(MAINFRAME_MENU_ID_TIMER_SPEED_05X, MainWindow::OnDebugSetting) EVT_MENU(MAINFRAME_MENU_ID_TIMER_SPEED_025X, MainWindow::OnDebugSetting) EVT_MENU(MAINFRAME_MENU_ID_TIMER_SPEED_0125X, MainWindow::OnDebugSetting) // nfc menu EVT_MENU(MAINFRAME_MENU_ID_NFC_TOUCH_NFC_FILE, MainWindow::OnNFCMenu) EVT_MENU_RANGE(MAINFRAME_MENU_ID_NFC_RECENT_0 + 0, MAINFRAME_MENU_ID_NFC_RECENT_LAST, MainWindow::OnNFCMenu) // debug -> logging menu EVT_MENU_RANGE(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + 0, MAINFRAME_MENU_ID_DEBUG_LOGGING0 + 98, MainWindow::OnDebugLoggingToggleFlagGeneric) EVT_MENU(MAINFRAME_MENU_ID_DEBUG_ADVANCED_PPC_INFO, MainWindow::OnPPCInfoToggle) // debug -> dump menu EVT_MENU(MAINFRAME_MENU_ID_DEBUG_DUMP_TEXTURES, MainWindow::OnDebugDumpUsedTextures) EVT_MENU(MAINFRAME_MENU_ID_DEBUG_DUMP_SHADERS, MainWindow::OnDebugDumpUsedShaders) EVT_MENU(MAINFRAME_MENU_ID_DEBUG_DUMP_CURL_REQUESTS, MainWindow::OnDebugSetting) // debug -> Other options EVT_MENU(MAINFRAME_MENU_ID_DEBUG_RENDER_UPSIDE_DOWN, MainWindow::OnDebugSetting) EVT_MENU(MAINFRAME_MENU_ID_DEBUG_AUDIO_AUX_ONLY, MainWindow::OnDebugSetting) EVT_MENU(MAINFRAME_MENU_ID_DEBUG_VK_ACCURATE_BARRIERS, MainWindow::OnDebugSetting) EVT_MENU(MAINFRAME_MENU_ID_DEBUG_DUMP_RAM, MainWindow::OnDebugSetting) EVT_MENU(MAINFRAME_MENU_ID_DEBUG_DUMP_FST, MainWindow::OnDebugSetting) // debug -> View ... EVT_MENU(MAINFRAME_MENU_ID_DEBUG_VIEW_LOGGING_WINDOW, MainWindow::OnLoggingWindow) EVT_MENU(MAINFRAME_MENU_ID_DEBUG_TOGGLE_GDB_STUB, MainWindow::OnGDBStubToggle) EVT_MENU(MAINFRAME_MENU_ID_DEBUG_VIEW_PPC_THREADS, MainWindow::OnDebugViewPPCThreads) EVT_MENU(MAINFRAME_MENU_ID_DEBUG_VIEW_PPC_DEBUGGER, MainWindow::OnDebugViewPPCDebugger) EVT_MENU(MAINFRAME_MENU_ID_DEBUG_VIEW_AUDIO_DEBUGGER, MainWindow::OnDebugViewAudioDebugger) EVT_MENU(MAINFRAME_MENU_ID_DEBUG_VIEW_TEXTURE_RELATIONS, MainWindow::OnDebugViewTextureRelations) // help menu EVT_MENU(MAINFRAME_MENU_ID_HELP_ABOUT, MainWindow::OnHelpAbout) EVT_MENU(MAINFRAME_MENU_ID_HELP_UPDATE, MainWindow::OnHelpUpdate) // misc EVT_COMMAND(wxID_ANY, wxEVT_REQUEST_GAMELIST_REFRESH, MainWindow::OnRequestGameListRefresh) EVT_COMMAND(wxID_ANY, wxEVT_GAMELIST_BEGIN_UPDATE, MainWindow::OnGameListBeginUpdate) EVT_COMMAND(wxID_ANY, wxEVT_GAMELIST_END_UPDATE, MainWindow::OnGameListEndUpdate) EVT_COMMAND(wxID_ANY, wxEVT_ACCOUNTLIST_REFRESH, MainWindow::OnAccountListRefresh) EVT_COMMAND(wxID_ANY, wxEVT_SET_WINDOW_TITLE, MainWindow::OnSetWindowTitle) EVT_COMMAND(wxID_ANY, wxEVT_REQUEST_RECREATE_CANVAS, MainWindow::OnRequestRecreateCanvas) wxEND_EVENT_TABLE() class wxGameDropTarget : public wxFileDropTarget { public: wxGameDropTarget(MainWindow* window) : m_window(window) {} bool OnDropFiles(wxCoord x, wxCoord y, const wxArrayString& filenames) override { if(!m_window->IsGameLaunched() && filenames.GetCount() == 1) return m_window->FileLoad(_utf8ToPath(filenames[0].utf8_string()), wxLaunchGameEvent::INITIATED_BY::DRAG_AND_DROP); return false; } private: MainWindow* m_window; }; class wxAmiiboDropTarget : public wxFileDropTarget { public: wxAmiiboDropTarget(MainWindow* window) : m_window(window) {} bool OnDropFiles(wxCoord x, wxCoord y, const wxArrayString& filenames) override { if (!m_window->IsGameLaunched() || filenames.GetCount() != 1) return false; uint32 nfcError; std::string path = filenames[0].utf8_string(); if (nfc::TouchTagFromFile(_utf8ToPath(path), &nfcError)) { GetConfig().AddRecentNfcFile(path); m_window->UpdateNFCMenu(); return true; } else { if (nfcError == NFC_TOUCH_TAG_ERROR_NO_ACCESS) wxMessageBox(_("Cannot open file"), _("Error"), wxOK | wxCENTRE | wxICON_ERROR); else if (nfcError == NFC_TOUCH_TAG_ERROR_INVALID_FILE_FORMAT) wxMessageBox(_("Not a valid NFC file"), _("Error"), wxOK | wxCENTRE | wxICON_ERROR); return false; } } private: MainWindow* m_window; }; MainWindow::MainWindow() : wxFrame(nullptr, -1, GetInitialWindowTitle(), wxDefaultPosition, wxSize(1280, 720), wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxSYSTEM_MENU | wxCAPTION | wxCLOSE_BOX | wxCLIP_CHILDREN | wxRESIZE_BORDER) { gui_initHandleContextFromWxWidgetsWindow(g_window_info.window_main, this); g_mainFrame = this; CafeSystem::SetImplementation(this); RecreateMenu(); SetClientSize(1280, 720); SetIcon(wxICON(M_WND_ICON128)); #if BOOST_OS_MACOS this->EnableFullScreenView(true); #endif #if BOOST_OS_WINDOWS HICON hWindowIcon = (HICON)LoadImageA(NULL, "M_WND_ICON16", IMAGE_ICON, 16, 16, LR_LOADFROMFILE); SendMessage(this->GetHWND(), WM_SETICON, ICON_SMALL, (LPARAM)hWindowIcon); #endif auto* main_sizer = new wxBoxSizer(wxVERTICAL); auto load_file = LaunchSettings::GetLoadFile(); auto load_title_id = LaunchSettings::GetLoadTitleID(); bool quick_launch = false; if (load_file) { MainWindow::RequestLaunchGame(load_file.value(), wxLaunchGameEvent::INITIATED_BY::COMMAND_LINE); quick_launch = true; } else if (load_title_id) { TitleInfo info; TitleId baseId; if (CafeTitleList::FindBaseTitleId(load_title_id.value(), baseId) && CafeTitleList::GetFirstByTitleId(baseId, info)) { MainWindow::RequestLaunchGame(info.GetPath(), wxLaunchGameEvent::INITIATED_BY::COMMAND_LINE); quick_launch = true; } else { wxString errorMsg = fmt::format("Title ID {:016x} not found", load_title_id.value()); wxMessageBox(errorMsg, _("Error"), wxOK | wxCENTRE | wxICON_ERROR); } } SetSizer(main_sizer); if (!quick_launch) { CreateGameListAndStatusBar(); } else { // launching game via -g or -t option. Don't set up or load game list m_game_list = nullptr; m_info_bar = nullptr; } SetSizer(main_sizer); m_last_mouse_move_time = std::chrono::steady_clock::now(); m_timer = new wxTimer(this, MAINFRAME_ID_TIMER1); m_timer->Start(500); LoadSettings(); auto& config = GetConfig(); #ifdef ENABLE_DISCORD_RPC if (config.use_discord_presence) m_discord = std::make_unique<DiscordPresence>(); #endif Bind(wxEVT_OPEN_GRAPHIC_PACK, &MainWindow::OnGraphicWindowOpen, this); Bind(wxEVT_LAUNCH_GAME, &MainWindow::OnLaunchFromFile, this); if (LaunchSettings::GDBStubEnabled()) { g_gdbstub = std::make_unique<GDBServer>(config.gdb_port); } } MainWindow::~MainWindow() { if (m_padView) { m_padView->Destroy(); m_padView = nullptr; } m_timer->Stop(); std::unique_lock lock(g_mutex); g_mainFrame = nullptr; } void MainWindow::CreateGameListAndStatusBar() { if(m_main_panel) return; // already displayed m_main_panel = new wxPanel(this); auto* sizer = new wxBoxSizer(wxVERTICAL); // game list m_game_list = new wxGameList(m_main_panel, MAINFRAME_GAMELIST_ID); m_game_list->Bind(wxEVT_OPEN_SETTINGS, [this](auto&) {OpenSettings(); }); m_game_list->SetDropTarget(new wxGameDropTarget(this)); sizer->Add(m_game_list, 1, wxEXPAND); // info, warning bar m_info_bar = new wxInfoBar(m_main_panel); m_info_bar->SetShowHideEffects(wxSHOW_EFFECT_BLEND, wxSHOW_EFFECT_BLEND); m_info_bar->SetEffectDuration(500); sizer->Add(m_info_bar, 0, wxALL | wxEXPAND, 5); m_main_panel->SetSizer(sizer); auto* main_sizer = this->GetSizer(); main_sizer->Add(m_main_panel, 1, wxEXPAND, 0, nullptr); } void MainWindow::DestroyGameListAndStatusBar() { if(!m_main_panel) return; m_main_panel->Destroy(); m_main_panel = nullptr; m_game_list = nullptr; m_info_bar = nullptr; } wxString MainWindow::GetInitialWindowTitle() { return BUILD_VERSION_WITH_NAME_STRING; } void MainWindow::OnClose(wxCloseEvent& event) { wxTheClipboard->Flush(); if(m_game_list) m_game_list->OnClose(event); if (!IsMaximized() && !gui_isFullScreen()) m_restored_size = GetSize(); SaveSettings(); m_timer->Stop(); event.Skip(); CafeSystem::Shutdown(); DestroyCanvas(); } bool MainWindow::InstallUpdate(const fs::path& metaFilePath) { try { GameUpdateWindow frame(*this, metaFilePath); const int updateResult = frame.ShowModal(); if (updateResult == wxID_OK) { CafeTitleList::AddTitleFromPath(frame.GetTargetPath()); // this will also send a notification to the game list which will update the entry wxMessageBox(_("Title installed!"), _("Success")); return true; } else { if (frame.GetExceptionMessage().empty()) wxMessageBox(_("Title installation has been canceled!")); else { throw std::runtime_error(frame.GetExceptionMessage()); } } } catch(const AbortException&) { // ignored } catch (const std::exception& ex) { wxMessageBox(ex.what(), _("Update error")); } return false; } bool MainWindow::FileLoad(const fs::path launchPath, wxLaunchGameEvent::INITIATED_BY initiatedBy) { TitleInfo launchTitle{ launchPath }; if (launchTitle.IsValid()) { // the title might not be in the TitleList, so we add it as a temporary entry CafeTitleList::AddTitleFromPath(launchPath); // title is valid, launch from TitleId TitleId baseTitleId; if (!CafeTitleList::FindBaseTitleId(launchTitle.GetAppTitleId(), baseTitleId)) { wxString t = _("Unable to launch game because the base files were not found."); wxMessageBox(t, _("Error"), wxOK | wxCENTRE | wxICON_ERROR); return false; } CafeSystem::PREPARE_STATUS_CODE r = CafeSystem::PrepareForegroundTitle(baseTitleId); if (r == CafeSystem::PREPARE_STATUS_CODE::INVALID_RPX) { cemu_assert_debug(false); return false; } else if (r == CafeSystem::PREPARE_STATUS_CODE::UNABLE_TO_MOUNT) { wxString t = _("Unable to mount title.\nMake sure the configured game paths are still valid and refresh the game list.\n\nFile which failed to load:\n"); t.append(_pathToUtf8(launchPath)); wxMessageBox(t, _("Error"), wxOK | wxCENTRE | wxICON_ERROR); return false; } else if (r != CafeSystem::PREPARE_STATUS_CODE::SUCCESS) { wxString t = _("Failed to launch game."); t.append(_pathToUtf8(launchPath)); wxMessageBox(t, _("Error"), wxOK | wxCENTRE | wxICON_ERROR); return false; } } else //if (launchTitle.GetFormat() == TitleInfo::TitleDataFormat::INVALID_STRUCTURE ) { // title is invalid, if it's an RPX/ELF we can launch it directly // otherwise it's an error CafeTitleFileType fileType = DetermineCafeSystemFileType(launchPath); if (fileType == CafeTitleFileType::RPX || fileType == CafeTitleFileType::ELF) { CafeSystem::PREPARE_STATUS_CODE r = CafeSystem::PrepareForegroundTitleFromStandaloneRPX(launchPath); if (r != CafeSystem::PREPARE_STATUS_CODE::SUCCESS) { cemu_assert_debug(false); // todo wxString t = _("Failed to launch executable. Path: "); t.append(_pathToUtf8(launchPath)); wxMessageBox(t, _("Error"), wxOK | wxCENTRE | wxICON_ERROR); return false; } } else if (initiatedBy == wxLaunchGameEvent::INITIATED_BY::GAME_LIST) { wxString t = _("Unable to launch title.\nMake sure the configured game paths are still valid and refresh the game list.\n\nPath which failed to load:\n"); t.append(_pathToUtf8(launchPath)); wxMessageBox(t, _("Error"), wxOK | wxCENTRE | wxICON_ERROR); return false; } else if (initiatedBy == wxLaunchGameEvent::INITIATED_BY::MENU || initiatedBy == wxLaunchGameEvent::INITIATED_BY::COMMAND_LINE) { wxString t = _("Unable to launch game\nPath:\n"); t.append(_pathToUtf8(launchPath)); if(launchTitle.GetInvalidReason() == TitleInfo::InvalidReason::NO_DISC_KEY) { t.append("\n\n"); t.append(_("Could not decrypt title. Make sure that keys.txt contains the correct disc key for this title.")); } if(launchTitle.GetInvalidReason() == TitleInfo::InvalidReason::NO_TITLE_TIK) { t.append("\n\n"); t.append(_("Could not decrypt title because title.tik is missing.")); } wxMessageBox(t, _("Error"), wxOK | wxCENTRE | wxICON_ERROR); return false; } else { wxString t = _("Unable to launch game\nPath:\n"); t.append(_pathToUtf8(launchPath)); wxMessageBox(t, _("Error"), wxOK | wxCENTRE | wxICON_ERROR); return false; } } if(launchTitle.IsValid()) GetConfig().AddRecentlyLaunchedFile(_pathToUtf8(launchTitle.GetPath())); else GetConfig().AddRecentlyLaunchedFile(_pathToUtf8(launchPath)); wxWindowUpdateLocker lock(this); DestroyGameListAndStatusBar(); m_game_launched = true; m_loadMenuItem->Enable(false); m_installUpdateMenuItem->Enable(false); m_memorySearcherMenuItem->Enable(true); m_launched_game_name = CafeSystem::GetForegroundTitleName(); #ifdef ENABLE_DISCORD_RPC if (m_discord) m_discord->UpdatePresence(DiscordPresence::Playing, m_launched_game_name); #endif if (GetConfig().disable_screensaver) { ScreenSaver::SetInhibit(true); // TODO: disable when only the game, not Cemu, is closed (a feature not yet implemented) // currently unnecessary because this will happen automatically when Cemu closes // ScreenSaver::SetInhibit(false); } if (ActiveSettings::FullscreenEnabled()) SetFullScreen(true); //GameMode support #if BOOST_OS_LINUX && defined(ENABLE_FERAL_GAMEMODE) if(GetConfig().feral_gamemode) { // attempt to start gamemode if(gamemode_request_start() < 0) { // GameMode failed to start cemuLog_log(LogType::Force, "Could not start GameMode"); } else { cemuLog_log(LogType::Force, "GameMode has been started."); } } #endif CreateCanvas(); CafeSystem::LaunchForegroundTitle(); RecreateMenu(); UpdateChildWindowTitleRunningState(); return true; } void MainWindow::OnLaunchFromFile(wxLaunchGameEvent& event) { if (event.GetPath().empty()) return; FileLoad(event.GetPath(), event.GetInitiatedBy()); } void MainWindow::OnFileMenu(wxCommandEvent& event) { const auto menuId = event.GetId(); if (menuId == MAINFRAME_MENU_ID_FILE_LOAD) { const auto wildcard = formatWxString( "{}|*.wud;*.wux;*.wua;*.wuhb;*.iso;*.rpx;*.elf;title.tmd" "|{}|*.wud;*.wux;*.iso" "|{}|title.tmd" "|{}|*.wua" "|{}|*.wuhb" "|{}|*.rpx;*.elf" "|{}|*", _("All Wii U files (*.wud, *.wux, *.wua, *.wuhb, *.iso, *.rpx, *.elf)"), _("Wii U image (*.wud, *.wux, *.iso, *.wad)"), _("Wii U NUS content"), _("Wii U archive (*.wua)"), _("Wii U homebrew bundle (*.wuhb)"), _("Wii U executable (*.rpx, *.elf)"), _("All files (*.*)") ); wxFileDialog openFileDialog(this, _("Open file to launch"), wxEmptyString, wxEmptyString, wildcard, wxFD_OPEN | wxFD_FILE_MUST_EXIST); if (openFileDialog.ShowModal() == wxID_CANCEL || openFileDialog.GetPath().IsEmpty()) return; const wxString wxStrFilePath = openFileDialog.GetPath(); FileLoad(_utf8ToPath(wxStrFilePath.utf8_string()), wxLaunchGameEvent::INITIATED_BY::MENU); } else if (menuId >= MAINFRAME_MENU_ID_FILE_RECENT_0 && menuId <= MAINFRAME_MENU_ID_FILE_RECENT_LAST) { const auto& config = GetConfig(); const size_t index = menuId - MAINFRAME_MENU_ID_FILE_RECENT_0; if (index < config.recent_launch_files.size()) { fs::path path = _utf8ToPath(config.recent_launch_files[index]); if (!path.empty()) FileLoad(path, wxLaunchGameEvent::INITIATED_BY::MENU); } } else if (menuId == MAINFRAME_MENU_ID_FILE_END_EMULATION) { CafeSystem::ShutdownTitle(); DestroyCanvas(); m_game_launched = false; RecreateMenu(); CreateGameListAndStatusBar(); DoLayout(); UpdateChildWindowTitleRunningState(); } } void MainWindow::OnOpenFolder(wxCommandEvent& event) { if(event.GetId() == MAINFRAME_MENU_ID_FILE_OPEN_CEMU_FOLDER) wxLaunchDefaultApplication(wxHelper::FromPath(ActiveSettings::GetUserDataPath())); else if(event.GetId() == MAINFRAME_MENU_ID_FILE_OPEN_MLC_FOLDER) wxLaunchDefaultApplication(wxHelper::FromPath(ActiveSettings::GetMlcPath())); } void MainWindow::OnInstallUpdate(wxCommandEvent& event) { while (true) { wxDirDialog openDirDialog(nullptr, _("Select folder of title to install"), "", wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST, wxDefaultPosition, wxDefaultSize, _("Select the folder that stores your update, DLC or base game files")); int modalChoice = openDirDialog.ShowModal(); if (modalChoice == wxID_CANCEL || openDirDialog.GetPath().IsEmpty()) break; if (modalChoice == wxID_OK) { #if BOOST_OS_LINUX || BOOST_OS_MACOS fs::path dirPath((const char*)(openDirDialog.GetPath().fn_str())); #else fs::path dirPath(openDirDialog.GetPath().fn_str()); #endif if ((dirPath.filename() == "code" || dirPath.filename() == "content" || dirPath.filename() == "meta") && dirPath.has_parent_path()) { if (!fs::exists(dirPath.parent_path() / "code") || !fs::exists(dirPath.parent_path() / "content") || !fs::exists(dirPath.parent_path() / "meta")) { wxMessageBox(formatWxString(_("The (parent) folder of the title you selected is missing at least one of the required subfolders (\"code\", \"content\" and \"meta\")\nMake sure that the files are complete."), dirPath.filename().string())); continue; } else dirPath = dirPath.parent_path(); } if (!fs::exists(dirPath)) wxMessageBox(_("The folder you have selected cannot be found on your system.")); else if (!fs::exists(dirPath / "meta" / "meta.xml")) wxMessageBox(_("Unable to find the /meta/meta.xml file inside the selected folder.")); else { InstallUpdate(dirPath); return; } } } } void MainWindow::OnNFCMenu(wxCommandEvent& event) { if (event.GetId() == MAINFRAME_MENU_ID_NFC_TOUCH_NFC_FILE) { wxFileDialog openFileDialog(this, _("Open file to load"), "", "", "All NFC files (bin, dat, nfc)|*.bin;*.dat;*.nfc|All files (*.*)|*", wxFD_OPEN | wxFD_FILE_MUST_EXIST); // TRANSLATE if (openFileDialog.ShowModal() == wxID_CANCEL || openFileDialog.GetPath().IsEmpty()) return; wxString wxStrFilePath = openFileDialog.GetPath(); uint32 nfcError; if (nfc::TouchTagFromFile(_utf8ToPath(wxStrFilePath.utf8_string()), &nfcError) == false) { if (nfcError == NFC_TOUCH_TAG_ERROR_NO_ACCESS) wxMessageBox(_("Cannot open file")); else if (nfcError == NFC_TOUCH_TAG_ERROR_INVALID_FILE_FORMAT) wxMessageBox(_("Not a valid NFC file")); } else { GetConfig().AddRecentNfcFile(wxStrFilePath.utf8_string()); UpdateNFCMenu(); } } else if (event.GetId() >= MAINFRAME_MENU_ID_NFC_RECENT_0 && event.GetId() <= MAINFRAME_MENU_ID_NFC_RECENT_LAST) { const size_t index = event.GetId() - MAINFRAME_MENU_ID_NFC_RECENT_0; auto& config = GetConfig(); if (index < config.recent_nfc_files.size()) { const auto& path = config.recent_nfc_files[index]; if (!path.empty()) { uint32 nfcError = 0; if (nfc::TouchTagFromFile(_utf8ToPath(path), &nfcError) == false) { if (nfcError == NFC_TOUCH_TAG_ERROR_NO_ACCESS) wxMessageBox(_("Cannot open file")); else if (nfcError == NFC_TOUCH_TAG_ERROR_INVALID_FILE_FORMAT) wxMessageBox(_("Not a valid NFC file")); } else { config.AddRecentNfcFile(path); UpdateNFCMenu(); } } } } } void MainWindow::OnFileExit(wxCommandEvent& event) { // todo: Safely clean up everything SaveSettings(); exit(0); } void MainWindow::TogglePadView() { const auto& config = GetConfig(); if (config.pad_open) { if (m_padView) return; m_padView = new PadViewFrame(this); m_padView->Bind(wxEVT_CLOSE_WINDOW, &MainWindow::OnPadClose, this); m_padView->Show(true); #if BOOST_OS_LINUX && HAS_WAYLAND if (wxWlIsWaylandWindow(m_padView)) wxWlSetAppId(m_padView, "info.cemu.Cemu"); #endif m_padView->Initialize(); if (m_game_launched) m_padView->InitializeRenderCanvas(); } else if (m_padView) { m_padView->Destroy(); m_padView = nullptr; } } #if BOOST_OS_WINDOWS #ifndef DBT_DEVNODES_CHANGED #define DBT_DEVNODES_CHANGED (0x0007) #endif WXLRESULT MainWindow::MSWWindowProc(WXUINT nMsg, WXWPARAM wParam, WXLPARAM lParam) { if (nMsg == WM_DEVICECHANGE) { if (wParam == DBT_DEVNODES_CHANGED) { InputManager::instance().on_device_changed(); } } return wxFrame::MSWWindowProc(nMsg, wParam, lParam); } #endif void MainWindow::OpenSettings() { auto& config = GetConfig(); const auto language = config.language; GeneralSettings2 frame(this, m_game_launched); frame.ShowModal(); const bool paths_modified = frame.ShouldReloadGamelist(); const bool mlc_modified = frame.MLCModified(); if (paths_modified) m_game_list->ReloadGameEntries(false); else SaveSettings(); #ifdef ENABLE_DISCORD_RPC if (config.use_discord_presence) { if (!m_discord) { m_discord = std::make_unique<DiscordPresence>(); if (!m_launched_game_name.empty()) m_discord->UpdatePresence(DiscordPresence::Playing, m_launched_game_name); } } else m_discord.reset(); #endif if(config.check_update && !m_game_launched) m_update_available = CemuUpdateWindow::IsUpdateAvailableAsync(); if (mlc_modified) RecreateMenu(); if (!config.fullscreen_menubar && IsFullScreen()) SetMenuVisible(false); if (language != config.language) wxMessageBox(_("Cemu must be restarted to apply the selected UI language."), _("Information"), wxOK | wxCENTRE, this); // TODO: change language to newly selected one } void MainWindow::OnOptionsInput(wxCommandEvent& event) { switch (event.GetId()) { case MAINFRAME_MENU_ID_OPTIONS_FULLSCREEN: { const bool state = m_fullscreenMenuItem->IsChecked(); SetFullScreen(state); break; } case MAINFRAME_MENU_ID_OPTIONS_SECOND_WINDOW_PADVIEW: { GetConfig().pad_open = !GetConfig().pad_open; g_config.Save(); TogglePadView(); break; } case MAINFRAME_MENU_ID_OPTIONS_GRAPHIC_PACKS2: { if (m_graphic_pack_window) return; uint64 titleId = 0; if (CafeSystem::IsTitleRunning()) titleId = CafeSystem::GetForegroundTitleId(); m_graphic_pack_window = new GraphicPacksWindow2(this, titleId); m_graphic_pack_window->Bind(wxEVT_CLOSE_WINDOW, &MainWindow::OnGraphicWindowClose, this); m_graphic_pack_window->Show(true); break; } case MAINFRAME_MENU_ID_OPTIONS_GENERAL2: { OpenSettings(); break; } case MAINFRAME_MENU_ID_OPTIONS_INPUT: { auto* frame = new InputSettings2(this); frame->ShowModal(); frame->Destroy(); break; } } } void MainWindow::OnAccountSelect(wxCommandEvent& event) { const int index = event.GetId() - MAINFRAME_MENU_ID_OPTIONS_ACCOUNT_1; const auto& accounts = Account::GetAccounts(); wxASSERT(index >= 0 && index < (int)accounts.size()); auto& config = GetConfig(); config.account.m_persistent_id = accounts[index].GetPersistentId(); // config.account.online_enabled.value = false; // reset online for safety g_config.Save(); } void MainWindow::OnConsoleLanguage(wxCommandEvent& event) { switch (event.GetId()) { case MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_JAPANESE: GetConfig().console_language = CafeConsoleLanguage::JA; break; case MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_ENGLISH: GetConfig().console_language = CafeConsoleLanguage::EN; break; case MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_FRENCH: GetConfig().console_language = CafeConsoleLanguage::FR; break; case MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_GERMAN: GetConfig().console_language = CafeConsoleLanguage::DE; break; case MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_ITALIAN: GetConfig().console_language = CafeConsoleLanguage::IT; break; case MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_SPANISH: GetConfig().console_language = CafeConsoleLanguage::ES; break; case MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_CHINESE: GetConfig().console_language = CafeConsoleLanguage::ZH; break; case MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_KOREAN: GetConfig().console_language = CafeConsoleLanguage::KO; break; case MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_DUTCH: GetConfig().console_language = CafeConsoleLanguage::NL; break; case MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_PORTUGUESE: GetConfig().console_language = CafeConsoleLanguage::PT; break; case MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_RUSSIAN: GetConfig().console_language = CafeConsoleLanguage::RU; break; case MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_TAIWANESE: GetConfig().console_language = CafeConsoleLanguage::TW; break; default: cemu_assert_debug(false); } if (m_game_list) { m_game_list->DeleteCachedStrings(); m_game_list->ReloadGameEntries(false); } g_config.Save(); } //void MainWindow::OnCPUMode(wxCommandEvent& event) //{ // if (event.GetId() == MAINFRAME_MENU_ID_CPU_MODE_SINGLECORE_INTERPRETER) // GetConfig().cpu_mode = CPUMode::SinglecoreInterpreter; // else if (event.GetId() == MAINFRAME_MENU_ID_CPU_MODE_SINGLECORE_RECOMPILER) // GetConfig().cpu_mode = CPUMode::SinglecoreRecompiler; // else if (event.GetId() == MAINFRAME_MENU_ID_CPU_MODE_DUALCORE_RECOMPILER) // GetConfig().cpu_mode = CPUMode::DualcoreRecompiler; // else if (event.GetId() == MAINFRAME_MENU_ID_CPU_MODE_TRIPLECORE_RECOMPILER) // GetConfig().cpu_mode = CPUMode::TriplecoreRecompiler; // else // cemu_assert_debug(false); // // g_config.Save(); //} void MainWindow::OnDebugSetting(wxCommandEvent& event) { if (event.GetId() == MAINFRAME_MENU_ID_DEBUG_RENDER_UPSIDE_DOWN) GetConfig().render_upside_down = event.IsChecked(); else if (event.GetId() == MAINFRAME_MENU_ID_DEBUG_VK_ACCURATE_BARRIERS) { GetConfig().vk_accurate_barriers = event.IsChecked(); if(!GetConfig().vk_accurate_barriers) wxMessageBox(_("Warning: Disabling the accurate barriers option will lead to flickering graphics but may improve performance. It is highly recommended to leave it turned on."), _("Accurate barriers are off"), wxOK); } else if (event.GetId() == MAINFRAME_MENU_ID_DEBUG_AUDIO_AUX_ONLY) ActiveSettings::EnableAudioOnlyAux(event.IsChecked()); else if (event.GetId() == MAINFRAME_MENU_ID_DEBUG_DUMP_RAM) memory_createDump(); else if (event.GetId() == MAINFRAME_MENU_ID_DEBUG_DUMP_FST) { /* int msgBoxAnswer = wxMessageBox(_("All files from the currently running game will be dumped to /dump/<gamefolder>. This process can take a few minutes."), _("Dump WUD"), wxOK | wxCANCEL | wxICON_WARNING); if (msgBoxAnswer == wxOK) { volumeFST_dump(bootGame_getMountedWUD()); wxMessageBox(_("Dump complete")); }*/ } else if (event.GetId() == MAINFRAME_MENU_ID_DEBUG_DUMP_CURL_REQUESTS) { // toggle debug -> dump -> curl requests const bool state = event.IsChecked(); ActiveSettings::EnableDumpLibcurlRequests(state); if (state) { try { const fs::path path(ActiveSettings::GetUserDataPath()); fs::create_directories(path / "dump" / "curl"); } catch (const std::exception& ex) { SystemException sys(ex); cemuLog_log(LogType::Force, "error when creating dump curl folder: {}", sys.what()); ActiveSettings::EnableDumpLibcurlRequests(false); } } } else if (event.GetId() == MAINFRAME_MENU_ID_TIMER_SPEED_8X) ActiveSettings::SetTimerShiftFactor(0); else if (event.GetId() == MAINFRAME_MENU_ID_TIMER_SPEED_4X) ActiveSettings::SetTimerShiftFactor(1); else if (event.GetId() == MAINFRAME_MENU_ID_TIMER_SPEED_2X) ActiveSettings::SetTimerShiftFactor(2); else if (event.GetId() == MAINFRAME_MENU_ID_TIMER_SPEED_1X) ActiveSettings::SetTimerShiftFactor(3); else if (event.GetId() == MAINFRAME_MENU_ID_TIMER_SPEED_05X) ActiveSettings::SetTimerShiftFactor(4); else if (event.GetId() == MAINFRAME_MENU_ID_TIMER_SPEED_025X) ActiveSettings::SetTimerShiftFactor(5); else if (event.GetId() == MAINFRAME_MENU_ID_TIMER_SPEED_0125X) ActiveSettings::SetTimerShiftFactor(6); else cemu_assert_debug(false); g_config.Save(); } void MainWindow::OnDebugLoggingToggleFlagGeneric(wxCommandEvent& event) { sint32 loggingIdBase = MAINFRAME_MENU_ID_DEBUG_LOGGING0; sint32 id = event.GetId(); if (id >= loggingIdBase && id < (MAINFRAME_MENU_ID_DEBUG_LOGGING0 + 64)) { bool isEnable = event.IsChecked(); LogType loggingType = static_cast<LogType>(id - loggingIdBase); if (isEnable) GetConfig().log_flag = GetConfig().log_flag.GetValue() | cemuLog_getFlag(loggingType); else GetConfig().log_flag = GetConfig().log_flag.GetValue() & ~cemuLog_getFlag(loggingType); cemuLog_setActiveLoggingFlags(GetConfig().log_flag.GetValue()); g_config.Save(); } } void MainWindow::OnPPCInfoToggle(wxCommandEvent& event) { GetConfig().advanced_ppc_logging = !GetConfig().advanced_ppc_logging.GetValue(); g_config.Save(); } void MainWindow::OnDebugDumpUsedTextures(wxCommandEvent& event) { const bool value = event.IsChecked(); ActiveSettings::EnableDumpTextures(value); if (value) { try { // create directory const fs::path path(ActiveSettings::GetUserDataPath()); fs::create_directories(path / "dump" / "textures"); } catch (const std::exception& ex) { SystemException sys(ex); cemuLog_log(LogType::Force, "can't create texture dump folder: {}", ex.what()); ActiveSettings::EnableDumpTextures(false); } } } void MainWindow::OnDebugDumpUsedShaders(wxCommandEvent& event) { const bool value = event.IsChecked(); ActiveSettings::EnableDumpShaders(value); if (value) { try { // create directory const fs::path path(ActiveSettings::GetUserDataPath()); fs::create_directories(path / "dump" / "shaders"); } catch (const std::exception & ex) { SystemException sys(ex); cemuLog_log(LogType::Force, "can't create shaders dump folder: {}", ex.what()); ActiveSettings::EnableDumpShaders(false); } } } void MainWindow::OnLoggingWindow(wxCommandEvent& event) { if(m_logging_window) return; m_logging_window = new LoggingWindow(this); m_logging_window->Bind(wxEVT_CLOSE_WINDOW, [this](wxCloseEvent& event) { m_logging_window = nullptr; event.Skip(); }); m_logging_window->Show(true); } void MainWindow::OnGDBStubToggle(wxCommandEvent& event) { if (g_gdbstub) { g_gdbstub.release(); return; } const auto& config = GetConfig(); g_gdbstub = std::make_unique<GDBServer>(config.gdb_port); } void MainWindow::OnDebugViewPPCThreads(wxCommandEvent& event) { auto frame = new DebugPPCThreadsWindow(*this); frame->Show(true); } void MainWindow::OnDebugViewPPCDebugger(wxCommandEvent& event) { if (m_debugger_window && m_debugger_window->IsShown()) { m_debugger_window->Close(); m_debugger_window = nullptr; return; } auto rect = GetDesktopRect(); /* sint32 new_width = max(rect.GetWidth() * 0.70, rect.GetWidth() - 850); this->SetSize(new_width, 480);*/ this->SetSize(800, 450 + 50); this->CenterOnScreen(); auto pos = this->GetPosition(); pos.y = std::min(pos.y + 200, rect.GetHeight() - 400); this->SetPosition(pos); m_debugger_window = new DebuggerWindow2(*this, rect); m_debugger_window->Bind(wxEVT_CLOSE_WINDOW, &MainWindow::OnDebuggerClose, this); m_debugger_window->Show(true); } void MainWindow::OnDebugViewAudioDebugger(wxCommandEvent& event) { auto frame = new AudioDebuggerWindow(*this); frame->Show(true); } void MainWindow::OnDebugViewTextureRelations(wxCommandEvent& event) { openTextureViewer(*this); } void MainWindow::ShowCursor(bool state) { #if BOOST_OS_WINDOWS CURSORINFO info{}; info.cbSize = sizeof(CURSORINFO); GetCursorInfo(&info); const bool visible = info.flags == CURSOR_SHOWING; if (state == visible) return; int counter = 0; if(state) { do { counter = ::ShowCursor(TRUE); } while (counter < 0); } else { do { counter = ::ShowCursor(FALSE); } while (counter >= 0); } #else if (state) { wxSetCursor(wxNullCursor); // restore system default cursor } else { wxSetCursor(wxCursor(wxCURSOR_BLANK)); } #endif } uintptr_t MainWindow::GetRenderCanvasHWND() { // deprecated. We can use the global cross-platform window info structs now #if BOOST_OS_WINDOWS if (!m_render_canvas) return 0; return (uintptr_t)m_render_canvas->GetHWND(); #else return 0; #endif } wxRect MainWindow::GetDesktopRect() { const auto pos = GetPosition(); const auto middle = pos.x + GetSize().GetWidth() / 2; const auto displayCount = wxDisplay::GetCount(); for (uint32 i = 0; i < displayCount; ++i) { wxDisplay display(i); if (!display.IsOk()) continue; const auto geo = display.GetGeometry(); if (geo.x <= middle && middle <= geo.x + geo.width) return geo; } return { 0,0,800,600 }; } void MainWindow::LoadSettings() { g_config.Load(); const auto& config = GetConfig(); if(config.check_update) m_update_available = CemuUpdateWindow::IsUpdateAvailableAsync(); if (config.window_position != Vector2i{ -1,-1 }) this->SetPosition({ config.window_position.x, config.window_position.y }); if (config.window_size != Vector2i{ -1,-1 }) { this->SetSize({ config.window_size.x, config.window_size.y }); if (config.window_maximized) this->Maximize(); } if (config.pad_position != Vector2i{ -1,-1 }) { g_window_info.restored_pad_x = config.pad_position.x; g_window_info.restored_pad_y = config.pad_position.y; } if (config.pad_size != Vector2i{ -1,-1 }) { g_window_info.restored_pad_width = config.pad_size.x; g_window_info.restored_pad_height = config.pad_size.y; g_window_info.pad_maximized = config.pad_maximized; } this->TogglePadView(); if(m_game_list) m_game_list->LoadConfig(); } void MainWindow::SaveSettings() { auto lock = g_config.Lock(); auto& config = GetConfig(); if (config.window_position != Vector2i{ -1,-1 }) { config.window_position.x = m_restored_position.x; config.window_position.y = m_restored_position.y; } if (config.window_size != Vector2i{ -1,-1 }) { config.window_size.x = m_restored_size.x; config.window_size.y = m_restored_size.y; config.window_maximized = IsMaximized(); } else { config.window_maximized = false; } config.pad_open = m_padView != nullptr; if (config.pad_position != Vector2i{ -1,-1 } && g_window_info.restored_pad_x != -1) { config.pad_position.x = g_window_info.restored_pad_x; config.pad_position.y = g_window_info.restored_pad_y; } if (config.pad_size != Vector2i{ -1,-1 } && g_window_info.restored_pad_width != -1) { config.pad_size.x = g_window_info.restored_pad_width; config.pad_size.y = g_window_info.restored_pad_height; config.pad_maximized = g_window_info.pad_maximized; } else { config.pad_maximized = false; } if(m_game_list) m_game_list->SaveConfig(); g_config.Save(); } void MainWindow::OnMouseMove(wxMouseEvent& event) { event.Skip(); m_last_mouse_move_time = std::chrono::steady_clock::now(); m_mouse_position = wxGetMousePosition(); ShowCursor(true); auto& instance = InputManager::instance(); std::unique_lock lock(instance.m_main_mouse.m_mutex); auto physPos = ToPhys(event.GetPosition()); instance.m_main_mouse.position = { physPos.x, physPos.y }; lock.unlock(); if (!IsFullScreen()) return; const auto& config = GetConfig(); // if mouse goes to upper screen then show our menu in fullscreen mode if (config.fullscreen_menubar) SetMenuVisible(event.GetPosition().y < 50); } void MainWindow::OnMouseLeft(wxMouseEvent& event) { auto& instance = InputManager::instance(); std::scoped_lock lock(instance.m_main_mouse.m_mutex); instance.m_main_mouse.left_down = event.ButtonDown(wxMOUSE_BTN_LEFT); auto physPos = ToPhys(event.GetPosition()); instance.m_main_mouse.position = { physPos.x, physPos.y }; if (event.ButtonDown(wxMOUSE_BTN_LEFT)) instance.m_main_mouse.left_down_toggle = true; event.Skip(); } void MainWindow::OnMouseRight(wxMouseEvent& event) { auto& instance = InputManager::instance(); std::scoped_lock lock(instance.m_main_mouse.m_mutex); instance.m_main_mouse.right_down = event.ButtonDown(wxMOUSE_BTN_RIGHT); auto physPos = ToPhys(event.GetPosition()); instance.m_main_mouse.position = { physPos.x, physPos.y }; if(event.ButtonDown(wxMOUSE_BTN_RIGHT)) instance.m_main_mouse.right_down_toggle = true; event.Skip(); } void MainWindow::OnGameListBeginUpdate(wxCommandEvent& event) { if (m_game_list->IsShown()) m_info_bar->ShowMessage(_("Updating game list...")); } void MainWindow::OnGameListEndUpdate(wxCommandEvent& event) { m_info_bar->Dismiss(); } void MainWindow::OnAccountListRefresh(wxCommandEvent& event) { RecreateMenu(); } void MainWindow::OnRequestGameListRefresh(wxCommandEvent& event) { m_game_list->ReloadGameEntries(false); } void MainWindow::OnSetWindowTitle(wxCommandEvent& event) { this->SetTitle(event.GetString()); } void MainWindow::OnKeyUp(wxKeyEvent& event) { event.Skip(); if (swkbd_hasKeyboardInputHook()) return; const auto code = event.GetKeyCode(); if (code == WXK_ESCAPE) SetFullScreen(false); else if (code == WXK_RETURN && event.AltDown() || code == WXK_F11) SetFullScreen(!IsFullScreen()); else if (code == WXK_F12) g_window_info.has_screenshot_request = true; // async screenshot request } void MainWindow::OnKeyDown(wxKeyEvent& event) { if ((event.AltDown() && event.GetKeyCode() == WXK_F4) || (event.CmdDown() && event.GetKeyCode() == 'Q')) { Close(true); } else { event.Skip(); } } void MainWindow::OnChar(wxKeyEvent& event) { if (swkbd_hasKeyboardInputHook()) swkbd_keyInput(event.GetUnicodeKey()); // event.Skip(); } void MainWindow::OnToolsInput(wxCommandEvent& event) { const auto id = event.GetId(); switch (id) { case MAINFRAME_MENU_ID_TOOLS_MEMORY_SEARCHER: { if (m_toolWindow) m_toolWindow->SetFocus(); else { m_toolWindow = new MemorySearcherTool(this); m_toolWindow->Bind(wxEVT_CLOSE_WINDOW, &MainWindow::OnMemorySearcherClose, this); m_toolWindow->Show(true); } break; } case MAINFRAME_MENU_ID_TOOLS_TITLE_MANAGER: case MAINFRAME_MENU_ID_TOOLS_DOWNLOAD_MANAGER: { const auto default_tab = id == MAINFRAME_MENU_ID_TOOLS_TITLE_MANAGER ? TitleManagerPage::TitleManager : TitleManagerPage::DownloadManager; if (m_title_manager) m_title_manager->SetFocusAndTab(default_tab); else { m_title_manager = new TitleManager(this, default_tab); m_title_manager->Bind(wxEVT_CLOSE_WINDOW, [this](wxCloseEvent& event) { m_title_manager = nullptr; event.Skip(); }); m_title_manager->Show(); } break; } case MAINFRAME_MENU_ID_TOOLS_EMULATED_USB_DEVICES: { if (m_usb_devices) { m_usb_devices->Show(true); m_usb_devices->Raise(); m_usb_devices->SetFocus(); } else { m_usb_devices = new EmulatedUSBDeviceFrame(this); m_usb_devices->Bind(wxEVT_CLOSE_WINDOW, [this](wxCloseEvent& event) { if (event.CanVeto()) { m_usb_devices->Show(false); event.Veto(); } }); m_usb_devices->Show(true); } break; } break; } } void MainWindow::OnGesturePan(wxPanGestureEvent& event) { auto& instance = InputManager::instance(); std::scoped_lock lock(instance.m_main_touch.m_mutex); auto physPos = ToPhys(event.GetPosition()); instance.m_main_touch.position = { physPos.x, physPos.y }; instance.m_main_touch.left_down = event.IsGestureStart() || !event.IsGestureEnd(); if (event.IsGestureStart() || !event.IsGestureEnd()) instance.m_main_touch.left_down_toggle = true; event.Skip(); } void MainWindow::OnGameLoaded() { if (m_debugger_window) m_debugger_window->OnGameLoaded(); } void MainWindow::AsyncSetTitle(std::string_view windowTitle) { wxCommandEvent set_title_event(wxEVT_SET_WINDOW_TITLE); set_title_event.SetString(wxHelper::FromUtf8(windowTitle)); g_mainFrame->QueueEvent(set_title_event.Clone()); } void MainWindow::CreateCanvas() { // create panel for canvas m_game_panel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL | wxNO_BORDER | wxWANTS_CHARS); auto* sizer = new wxBoxSizer(wxVERTICAL); // shouldn't be needed, but who knows m_game_panel->Bind(wxEVT_KEY_UP, &MainWindow::OnKeyUp, this); m_game_panel->Bind(wxEVT_CHAR, &MainWindow::OnChar, this); m_game_panel->SetSizer(sizer); this->GetSizer()->Add(m_game_panel, 1, wxEXPAND, 0, nullptr); // create canvas if (ActiveSettings::GetGraphicsAPI() == kVulkan) m_render_canvas = new VulkanCanvas(m_game_panel, wxSize(1280, 720), true); else m_render_canvas = GLCanvas_Create(m_game_panel, wxSize(1280, 720), true); // mouse events m_render_canvas->Bind(wxEVT_MOTION, &MainWindow::OnMouseMove, this); m_render_canvas->Bind(wxEVT_MOUSEWHEEL, &MainWindow::OnMouseWheel, this); m_render_canvas->Bind(wxEVT_LEFT_DOWN, &MainWindow::OnMouseLeft, this); m_render_canvas->Bind(wxEVT_LEFT_UP, &MainWindow::OnMouseLeft, this); m_render_canvas->Bind(wxEVT_RIGHT_DOWN, &MainWindow::OnMouseRight, this); m_render_canvas->Bind(wxEVT_RIGHT_UP, &MainWindow::OnMouseRight, this); m_render_canvas->Bind(wxEVT_GESTURE_PAN, &MainWindow::OnGesturePan, this); // key events m_render_canvas->Bind(wxEVT_KEY_UP, &MainWindow::OnKeyUp, this); m_render_canvas->Bind(wxEVT_KEY_DOWN, &MainWindow::OnKeyDown, this); m_render_canvas->Bind(wxEVT_CHAR, &MainWindow::OnChar, this); m_render_canvas->SetDropTarget(new wxAmiiboDropTarget(this)); m_game_panel->GetSizer()->Add(m_render_canvas, 1, wxEXPAND, 0, nullptr); GetSizer()->Layout(); m_render_canvas->SetFocus(); if (m_padView) m_padView->InitializeRenderCanvas(); } void MainWindow::DestroyCanvas() { if (m_padView) { m_padView->DestroyCanvas(); } if (m_render_canvas) { m_render_canvas->Destroy(); m_render_canvas = nullptr; } if(m_game_panel) { m_game_panel->Destroy(); m_game_panel = nullptr; } } void MainWindow::OnSizeEvent(wxSizeEvent& event) { if (!IsMaximized() && !gui_isFullScreen()) m_restored_size = GetSize(); const wxSize client_size = GetClientSize(); g_window_info.width = client_size.GetWidth(); g_window_info.height = client_size.GetHeight(); g_window_info.phys_width = ToPhys(client_size.GetWidth()); g_window_info.phys_height = ToPhys(client_size.GetHeight()); g_window_info.dpi_scale = GetDPIScaleFactor(); if (m_debugger_window && m_debugger_window->IsShown()) m_debugger_window->OnParentMove(GetPosition(), event.GetSize()); event.Skip(); VsyncDriver_notifyWindowPosChanged(); } void MainWindow::OnDPIChangedEvent(wxDPIChangedEvent& event) { event.Skip(); const wxSize client_size = GetClientSize(); g_window_info.width = client_size.GetWidth(); g_window_info.height = client_size.GetHeight(); g_window_info.phys_width = ToPhys(client_size.GetWidth()); g_window_info.phys_height = ToPhys(client_size.GetHeight()); g_window_info.dpi_scale = GetDPIScaleFactor(); } void MainWindow::OnMove(wxMoveEvent& event) { if (!IsMaximized() && !gui_isFullScreen()) m_restored_position = GetPosition(); if (m_debugger_window && m_debugger_window->IsShown()) m_debugger_window->OnParentMove(GetPosition(), GetSize()); VsyncDriver_notifyWindowPosChanged(); } void MainWindow::OnDebuggerClose(wxCloseEvent& event) { m_debugger_window = nullptr; event.Skip(); } void MainWindow::OnPadClose(wxCloseEvent& event) { auto& config = GetConfig(); config.pad_open = false; if (config.pad_position != Vector2i{ -1,-1 }) m_padView->GetPosition(&config.pad_position.x, &config.pad_position.y); if (config.pad_size != Vector2i{ -1,-1 }) m_padView->GetSize(&config.pad_size.x, &config.pad_size.y); g_config.Save(); // already deleted by wxwidget m_padView = nullptr; if (m_padViewMenuItem) m_padViewMenuItem->Check(false); event.Skip(); } void MainWindow::OnMemorySearcherClose(wxCloseEvent& event) { m_toolWindow = nullptr; event.Skip(); } void MainWindow::OnMouseWheel(wxMouseEvent& event) { const float delta = event.GetWheelRotation(); // in 120 steps -> max reached ~480 (?) auto& instance = InputManager::instance(); instance.m_mouse_wheel = (delta / 120.0f); event.Skip(); } void MainWindow::SetFullScreen(bool state) { // only update config entry if we dont't have launch parameters if (!LaunchSettings::FullscreenEnabled().has_value()) { GetConfig().fullscreen = state; g_config.Save(); } if (state && !m_game_launched) return; g_window_info.is_fullscreen = state; m_fullscreenMenuItem->Check(state); this->ShowFullScreen(state); if (state) m_menu_visible = false; // menu gets always disabled by wxFULLSCREEN_NOMENUBAR else SetMenuVisible(true); } void MainWindow::SetMenuVisible(bool state) { if (m_menu_visible == state) return; SetMenuBar(state ? m_menuBar : nullptr); m_menu_visible = state; } void MainWindow::UpdateNFCMenu() { if (m_nfcMenuSeparator0) { m_nfcMenu->Remove(m_nfcMenuSeparator0->GetId()); m_nfcMenuSeparator0 = nullptr; } // remove recent files list for (sint32 i = 0; i < CemuConfig::kMaxRecentEntries; i++) { if (m_nfcMenu->FindChildItem(MAINFRAME_MENU_ID_NFC_RECENT_0 + i) == nullptr) continue; m_nfcMenu->Remove(MAINFRAME_MENU_ID_NFC_RECENT_0 + i); } // add entries const auto& config = GetConfig(); sint32 recentFileIndex = 0; for (size_t i = 0; i < config.recent_nfc_files.size(); i++) { const auto& entry = config.recent_nfc_files[i]; if (entry.empty()) continue; if (!fs::exists(_utf8ToPath(entry))) continue; if (recentFileIndex == 0) m_nfcMenuSeparator0 = m_nfcMenu->AppendSeparator(); m_nfcMenu->Append(MAINFRAME_MENU_ID_NFC_RECENT_0 + i, to_wxString(fmt::format("{}. {}", recentFileIndex, entry))); recentFileIndex++; if (recentFileIndex >= 12) break; } } bool MainWindow::IsMenuHidden() const { return m_menu_visible; } void MainWindow::OnTimer(wxTimerEvent& event) { if(m_update_available.valid() && future_is_ready(m_update_available)) { if(m_update_available.get()) { wxMessageDialog dialog(this, _("There's a new update available.\nDo you want to update?"), _("Update notification"), wxCENTRE | wxYES_NO); if(dialog.ShowModal() == wxID_YES) { CemuUpdateWindow update_window(this); update_window.ShowModal(); } } m_update_available = {}; } if (!IsFullScreen() || m_menu_visible) return; const auto mouse_position = wxGetMousePosition(); if(m_mouse_position != mouse_position) { m_last_mouse_move_time = std::chrono::steady_clock::now(); m_mouse_position = mouse_position; ShowCursor(true); return; } auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - m_last_mouse_move_time); if (diff.count() > 3000) { ShowCursor(false); } } #define BUILD_DATE __DATE__ " " __TIME__ class CemuAboutDialog : public wxDialog { public: CemuAboutDialog(wxWindow* parent = NULL) : wxDialog(NULL, wxID_ANY, _("About Cemu"), wxDefaultPosition, wxSize(500, 700)) { Create(parent); } void Create(wxWindow* parent = NULL) { SetIcon(wxICON(M_WND_ICON128)); wxScrolledWindow* scrolledWindow = new wxScrolledWindow(this); wxBoxSizer* mainSizer = new wxBoxSizer(wxVERTICAL); m_scrolledSizer = new wxBoxSizer(wxVERTICAL); AddHeaderInfo(scrolledWindow, m_scrolledSizer); m_scrolledSizer->AddSpacer(5); AddLibInfo(scrolledWindow, m_scrolledSizer); m_scrolledSizer->AddSpacer(5); AddThanks(scrolledWindow, m_scrolledSizer); scrolledWindow->SetSizer(m_scrolledSizer); scrolledWindow->FitInside(); scrolledWindow->SetScrollRate(25, 25); mainSizer->Add(scrolledWindow, wxSizerFlags(1).Expand().Border(wxLEFT | wxRIGHT, 10)); SetSizer(mainSizer); CentreOnParent(); } void AddHeaderInfo(wxWindow* parent, wxSizer* sizer) { auto versionString = formatWxString(_("Cemu\nVersion {0}\nCompiled on {1}\nOriginal authors: {2}"), BUILD_VERSION_STRING, BUILD_DATE, "Exzap, Petergov"); sizer->Add(new wxStaticText(parent, wxID_ANY, versionString), wxSizerFlags().Border(wxALL, 3).Border(wxTOP, 10)); sizer->Add(new wxHyperlinkCtrl(parent, -1, "https://cemu.info", "https://cemu.info"), wxSizerFlags().Expand().Border(wxTOP | wxBOTTOM, 3)); sizer->AddSpacer(3); sizer->Add(new wxStaticLine(parent), wxSizerFlags().Expand().Border(wxRIGHT, 4)); sizer->AddSpacer(5); wxString extraInfo(_("Cemu is a Wii U emulator.\n\nWii and Wii U are trademarks of Nintendo.\nCemu is not affiliated with Nintendo.")); sizer->Add(new wxStaticText(parent, wxID_ANY, extraInfo), wxSizerFlags()); } void AddLibInfo(wxWindow* parent, wxSizer* sizer) { sizer->AddSpacer(3); sizer->Add(new wxStaticLine(parent), wxSizerFlags().Expand().Border(wxRIGHT, 4)); sizer->AddSpacer(3); sizer->Add(new wxStaticText(parent, wxID_ANY, _("Used libraries and utilities:")), wxSizerFlags().Expand().Border(wxTOP | wxBOTTOM, 2)); // zLib { wxSizer* lineSizer = new wxBoxSizer(wxHORIZONTAL); lineSizer->Add(new wxStaticText(parent, -1, "zLib ("), 0); lineSizer->Add(new wxHyperlinkCtrl(parent, -1, "https://www.zlib.net", "https://www.zlib.net"), 0); lineSizer->Add(new wxStaticText(parent, -1, ")"), 0); sizer->Add(lineSizer); } // wxWidgets { wxSizer* lineSizer = new wxBoxSizer(wxHORIZONTAL); lineSizer->Add(new wxStaticText(parent, -1, "wxWidgets ("), 0); lineSizer->Add(new wxHyperlinkCtrl(parent, -1, "https://www.wxwidgets.org/", "https://www.wxwidgets.org/"), 0); lineSizer->Add(new wxStaticText(parent, -1, ")"), 0); sizer->Add(lineSizer); } // OpenSSL { wxSizer* lineSizer = new wxBoxSizer(wxHORIZONTAL); lineSizer->Add(new wxStaticText(parent, -1, "OpenSSL ("), 0); lineSizer->Add(new wxHyperlinkCtrl(parent, -1, "https://www.openssl.org/", "https://www.openssl.org/"), 0); lineSizer->Add(new wxStaticText(parent, -1, ")"), 0); sizer->Add(lineSizer); } // libcurl { wxSizer* lineSizer = new wxBoxSizer(wxHORIZONTAL); lineSizer->Add(new wxStaticText(parent, -1, "libcurl ("), 0); lineSizer->Add(new wxHyperlinkCtrl(parent, -1, "https://curl.haxx.se/libcurl/", "https://curl.haxx.se/libcurl/"), 0); lineSizer->Add(new wxStaticText(parent, -1, ")"), 0); sizer->Add(lineSizer); } // imgui { wxSizer* lineSizer = new wxBoxSizer(wxHORIZONTAL); lineSizer->Add(new wxStaticText(parent, -1, "imgui ("), 0); lineSizer->Add(new wxHyperlinkCtrl(parent, -1, "https://github.com/ocornut/imgui", "https://github.com/ocornut/imgui"), 0); lineSizer->Add(new wxStaticText(parent, -1, ")"), 0); sizer->Add(lineSizer); } // fontawesome { wxSizer* lineSizer = new wxBoxSizer(wxHORIZONTAL); lineSizer->Add(new wxStaticText(parent, -1, "fontawesome ("), 0); lineSizer->Add(new wxHyperlinkCtrl(parent, -1, "https://github.com/FortAwesome/Font-Awesome", "https://github.com/FortAwesome/Font-Awesome"), 0); lineSizer->Add(new wxStaticText(parent, -1, ")"), 0); sizer->Add(lineSizer); } // boost { wxSizer* lineSizer = new wxBoxSizer(wxHORIZONTAL); lineSizer->Add(new wxStaticText(parent, -1, "boost ("), 0); lineSizer->Add(new wxHyperlinkCtrl(parent, -1, "https://www.boost.org", "https://www.boost.org"), 0); lineSizer->Add(new wxStaticText(parent, -1, ")"), 0); sizer->Add(lineSizer); } // libusb { wxSizer* lineSizer = new wxBoxSizer(wxHORIZONTAL); lineSizer->Add(new wxStaticText(parent, -1, "libusb ("), 0); lineSizer->Add(new wxHyperlinkCtrl(parent, -1, "https://libusb.info", "https://libusb.info"), 0); lineSizer->Add(new wxStaticText(parent, -1, ")"), 0); sizer->Add(lineSizer); } // icons { wxSizer* lineSizer = new wxBoxSizer(wxHORIZONTAL); lineSizer->Add(new wxStaticText(parent, -1, "icons from "), 0); lineSizer->Add(new wxHyperlinkCtrl(parent, -1, "https://icons8.com", "https://icons8.com"), 0); sizer->Add(lineSizer); } // Lato font (are we still using it?) { wxSizer* lineSizer = new wxBoxSizer(wxHORIZONTAL); lineSizer->Add(new wxStaticText(parent, -1, "\"Lato\" font by tyPoland Lukasz Dziedzic (OFL, V1.1)"), 0); sizer->Add(lineSizer); } // SDL { wxSizer* lineSizer = new wxBoxSizer(wxHORIZONTAL); lineSizer->Add(new wxStaticText(parent, -1, "SDL ("), 0); lineSizer->Add(new wxHyperlinkCtrl(parent, -1, "https://github.com/libsdl-org/SDL", "https://github.com/libsdl-org/SDL"), 0); lineSizer->Add(new wxStaticText(parent, -1, ")"), 0); sizer->Add(lineSizer); } // IH264 { wxSizer* lineSizer = new wxBoxSizer(wxHORIZONTAL); lineSizer->Add(new wxStaticText(parent, -1, "Modified ih264 from Android project ("), 0); lineSizer->Add(new wxHyperlinkCtrl(parent, -1, "Source", "https://cemu.info/oss/ih264d.zip"), 0); lineSizer->Add(new wxStaticText(parent, -1, " "), 0); wxHyperlinkCtrl* noticeLink = new wxHyperlinkCtrl(parent, -1, "NOTICE", ""); noticeLink->Bind(wxEVT_LEFT_DOWN, [](wxMouseEvent& event) { fs::path tempPath = fs::temp_directory_path(); tempPath.append("NOTICE_IH264.txt"); FileStream* fs = FileStream::createFile2(tempPath); if (!fs) return; fs->writeString( "/******************************************************************************\r\n" " *\r\n" " * Copyright (C) 2015 The Android Open Source Project\r\n" " *\r\n" " * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n" " * you may not use this file except in compliance with the License.\r\n" " * You may obtain a copy of the License at:" " *\r\n" " * http://www.apache.org/licenses/LICENSE-2.0\r\n" " *\r\n" " * Unless required by applicable law or agreed to in writing, software\r\n" " * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n" " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n" " * See the License for the specific language governing permissions and\r\n" " * limitations under the License.\r\n" " *\r\n" " *****************************************************************************\r\n" " * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore\r\n" "*/\r\n" "/*****************************************************************************/\r\n" ); delete fs; wxLaunchDefaultBrowser(wxHelper::FromUtf8(fmt::format("file:{}", _pathToUtf8(tempPath)))); }); lineSizer->Add(noticeLink, 0); lineSizer->Add(new wxStaticText(parent, -1, ")"), 0); sizer->Add(lineSizer); } } void AddThanks(wxWindow* parent, wxSizer* sizer) { sizer->AddSpacer(3); sizer->Add(new wxStaticLine(parent), wxSizerFlags().Expand().Border(wxRIGHT, 4)); sizer->AddSpacer(3); wxGridSizer* gridSizer = new wxGridSizer(1, 2, 0, 0); sizer->AddSpacer(2); sizer->Add(new wxStaticText(parent, wxID_ANY, _("Thanks to our Patreon supporters:")), wxSizerFlags().Expand().Border(wxTOP | wxBOTTOM, 2)); std::vector<const char*> patreonSupporterNames{ "Maufeat", "lvlv", "F34R", "John Godgames", "Jameel Lewis", "skooks", "Cheesy", "Barrowsx", "Mored1984", "madmat007" , "Kuhnnl", "Owen M", "lucianobugalu", "KimoMaka", "nick palma aka renaissance18", "TheGiantBros", "SpiGAndromeda" , "Chimech0", "Nicol√°s Pino", "Pezzatti", "Barry Wallace", "REGNR8 Productions", "Lagia", "Freestyler316", "Dentora" , "tactics", "Merola.C", "Ceigyx", "Mata", "BobSchneeder45", "fenixDG", "jjalapeno55", "FissionMetroid101", "Jetta88" , "nesxdie", "Mikah", "PornfoxVR.com", "Hunter4everosa", "Bbzx", "Salim Sanehi", "FalloutpunkX", "NashOH-CL", "RaheemWala" , "Faris Leonhart", "MahvZero", "PlaguedGuardian", "Stuffie", "CaptainLester", "Qtech", "Zaurexus", "Leonidas", "Artifesto" , "Alca259", "SirWestofAsh", "Loli Co.", "The Technical Revolutionary", "MegaYama", "mitori", "Seymordius", "Adrian Josh Cruz", "Manuel Hoenings", "Just A Jabb" , "pgantonio", "CannonXIII", "Lonewolf00708", "AlexsDesign.com", "NoskLo", "MrSirHaku", "xElite_V AKA William H. Johnson", "Zalnor", "Pig", "James \"SE4LS\"", "DairyOrange", "Horoko Lawrence", "bloodmc", "Officer Jenny", "Quasar", "Postposterous", "Jake Jackson", "Kaydax", "CthePredatorG" , "Hengi", "Pyrochaser", "luma.x3"}; wxString nameListLeft, nameListRight; for (size_t i = 0; i < patreonSupporterNames.size(); i++) { const char* name = patreonSupporterNames[i]; wxString& nameList = ((i % 2) == 0) ? nameListLeft : nameListRight; if (i >= 2) nameList.append("\n"); nameList.append(name); } gridSizer->Add(new wxStaticText(parent, wxID_ANY, nameListLeft), wxSizerFlags()); gridSizer->Add(new wxStaticText(parent, wxID_ANY, nameListRight), wxSizerFlags()); sizer->AddSpacer(4); sizer->Add(gridSizer, 1, wxEXPAND); sizer->AddSpacer(2); sizer->Add(new wxStaticText(parent, wxID_ANY, _("Special thanks:")), wxSizerFlags().Expand().Border(wxTOP, 2)); sizer->Add(new wxStaticText(parent, wxID_ANY, "espes - Also try XQEMU!\nWaltzz92"), wxSizerFlags().Expand().Border(wxTOP, 1)); } protected: wxSizer* m_scrolledSizer; }; void MainWindow::OnHelpAbout(wxCommandEvent& event) { CemuAboutDialog dlgAbout(this); dlgAbout.ShowModal(); } void MainWindow::OnHelpUpdate(wxCommandEvent& event) { CemuUpdateWindow test(this); test.ShowModal(); } void MainWindow::RecreateMenu() { if (m_menuBar) { SetMenuBar(nullptr); m_menuBar->Destroy(); m_menuBar = nullptr; } auto& config = GetConfig(); m_menuBar = new wxMenuBar(); // file submenu m_fileMenu = new wxMenu(); if (!m_game_launched) { m_loadMenuItem = m_fileMenu->Append(MAINFRAME_MENU_ID_FILE_LOAD, _("&Load...")); m_installUpdateMenuItem = m_fileMenu->Append(MAINFRAME_MENU_ID_FILE_INSTALL_UPDATE, _("&Install game title, update or DLC...")); sint32 recentFileIndex = 0; m_fileMenuSeparator0 = nullptr; m_fileMenuSeparator1 = nullptr; for (size_t i = 0; i < config.recent_launch_files.size(); i++) { const std::string& pathStr = config.recent_launch_files[i]; if (pathStr.empty()) continue; if (recentFileIndex == 0) m_fileMenuSeparator0 = m_fileMenu->AppendSeparator(); m_fileMenu->Append(MAINFRAME_MENU_ID_FILE_RECENT_0 + i, to_wxString(fmt::format("{}. {}", recentFileIndex, pathStr))); recentFileIndex++; if (recentFileIndex >= 8) break; } m_fileMenuSeparator1 = m_fileMenu->AppendSeparator(); } else { // add 'Stop emulation' menu entry to file menu #ifdef CEMU_DEBUG_ASSERT m_fileMenu->Append(MAINFRAME_MENU_ID_FILE_END_EMULATION, _("Stop emulation")); #endif } m_fileMenu->Append(MAINFRAME_MENU_ID_FILE_OPEN_CEMU_FOLDER, _("&Open Cemu folder")); m_fileMenu->Append(MAINFRAME_MENU_ID_FILE_OPEN_MLC_FOLDER, _("&Open MLC folder")); m_fileMenu->AppendSeparator(); m_exitMenuItem = m_fileMenu->Append(MAINFRAME_MENU_ID_FILE_EXIT, _("&Exit")); m_menuBar->Append(m_fileMenu, _("&File")); // options->account submenu m_optionsAccountMenu = new wxMenu(); const auto account_id = ActiveSettings::GetPersistentId(); int index = 0; for(const auto& account : Account::GetAccounts()) { wxMenuItem* item = m_optionsAccountMenu->AppendRadioItem(MAINFRAME_MENU_ID_OPTIONS_ACCOUNT_1 + index, account.ToString()); item->Check(account_id == account.GetPersistentId()); if (m_game_launched || LaunchSettings::GetPersistentId().has_value()) item->Enable(false); ++index; } // options->console language submenu wxMenu* optionsConsoleLanguageMenu = new wxMenu(); optionsConsoleLanguageMenu->AppendRadioItem(MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_ENGLISH, _("&English"), wxEmptyString)->Check(config.console_language == CafeConsoleLanguage::EN); optionsConsoleLanguageMenu->AppendRadioItem(MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_JAPANESE, _("&Japanese"), wxEmptyString)->Check(config.console_language == CafeConsoleLanguage::JA); optionsConsoleLanguageMenu->AppendRadioItem(MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_FRENCH, _("&French"), wxEmptyString)->Check(config.console_language == CafeConsoleLanguage::FR); optionsConsoleLanguageMenu->AppendRadioItem(MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_GERMAN, _("&German"), wxEmptyString)->Check(config.console_language == CafeConsoleLanguage::DE); optionsConsoleLanguageMenu->AppendRadioItem(MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_ITALIAN, _("&Italian"), wxEmptyString)->Check(config.console_language == CafeConsoleLanguage::IT); optionsConsoleLanguageMenu->AppendRadioItem(MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_SPANISH, _("&Spanish"), wxEmptyString)->Check(config.console_language == CafeConsoleLanguage::ES); optionsConsoleLanguageMenu->AppendRadioItem(MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_CHINESE, _("&Chinese"), wxEmptyString)->Check(config.console_language == CafeConsoleLanguage::ZH); optionsConsoleLanguageMenu->AppendRadioItem(MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_KOREAN, _("&Korean"), wxEmptyString)->Check(config.console_language == CafeConsoleLanguage::KO); optionsConsoleLanguageMenu->AppendRadioItem(MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_DUTCH, _("&Dutch"), wxEmptyString)->Check(config.console_language == CafeConsoleLanguage::NL); optionsConsoleLanguageMenu->AppendRadioItem(MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_PORTUGUESE, _("&Portuguese"), wxEmptyString)->Check(config.console_language == CafeConsoleLanguage::PT); optionsConsoleLanguageMenu->AppendRadioItem(MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_RUSSIAN, _("&Russian"), wxEmptyString)->Check(config.console_language == CafeConsoleLanguage::RU); optionsConsoleLanguageMenu->AppendRadioItem(MAINFRAME_MENU_ID_OPTIONS_LANGUAGE_TAIWANESE, _("&Taiwanese"), wxEmptyString)->Check(config.console_language == CafeConsoleLanguage::TW); if(IsGameLaunched()) { auto items = optionsConsoleLanguageMenu->GetMenuItems(); for (auto& item : items) { item->Enable(false); } } // options submenu wxMenu* optionsMenu = new wxMenu(); m_fullscreenMenuItem = optionsMenu->AppendCheckItem(MAINFRAME_MENU_ID_OPTIONS_FULLSCREEN, _("&Fullscreen"), wxEmptyString); m_fullscreenMenuItem->Check(ActiveSettings::FullscreenEnabled()); optionsMenu->Append(MAINFRAME_MENU_ID_OPTIONS_GRAPHIC_PACKS2, _("&Graphic packs")); m_padViewMenuItem = optionsMenu->AppendCheckItem(MAINFRAME_MENU_ID_OPTIONS_SECOND_WINDOW_PADVIEW, _("&Separate GamePad view"), wxEmptyString); m_padViewMenuItem->Check(GetConfig().pad_open); optionsMenu->AppendSeparator(); optionsMenu->Append(MAINFRAME_MENU_ID_OPTIONS_GENERAL2, _("&General settings")); optionsMenu->Append(MAINFRAME_MENU_ID_OPTIONS_INPUT, _("&Input settings")); optionsMenu->AppendSeparator(); optionsMenu->AppendSubMenu(m_optionsAccountMenu, _("&Active account")); optionsMenu->AppendSubMenu(optionsConsoleLanguageMenu, _("&Console language")); m_menuBar->Append(optionsMenu, _("&Options")); // tools submenu wxMenu* toolsMenu = new wxMenu(); m_memorySearcherMenuItem = toolsMenu->Append(MAINFRAME_MENU_ID_TOOLS_MEMORY_SEARCHER, _("&Memory searcher")); m_memorySearcherMenuItem->Enable(false); toolsMenu->Append(MAINFRAME_MENU_ID_TOOLS_TITLE_MANAGER, _("&Title Manager")); toolsMenu->Append(MAINFRAME_MENU_ID_TOOLS_DOWNLOAD_MANAGER, _("&Download Manager")); toolsMenu->Append(MAINFRAME_MENU_ID_TOOLS_EMULATED_USB_DEVICES, _("&Emulated USB Devices")); m_menuBar->Append(toolsMenu, _("&Tools")); // cpu timer speed menu wxMenu* timerSpeedMenu = new wxMenu(); timerSpeedMenu->AppendRadioItem(MAINFRAME_MENU_ID_TIMER_SPEED_1X, _("&1x speed"), wxEmptyString)->Check(ActiveSettings::GetTimerShiftFactor() == 3); timerSpeedMenu->AppendRadioItem(MAINFRAME_MENU_ID_TIMER_SPEED_2X, _("&2x speed"), wxEmptyString)->Check(ActiveSettings::GetTimerShiftFactor() == 2); timerSpeedMenu->AppendRadioItem(MAINFRAME_MENU_ID_TIMER_SPEED_4X, _("&4x speed"), wxEmptyString)->Check(ActiveSettings::GetTimerShiftFactor() == 1); timerSpeedMenu->AppendRadioItem(MAINFRAME_MENU_ID_TIMER_SPEED_8X, _("&8x speed"), wxEmptyString)->Check(ActiveSettings::GetTimerShiftFactor() == 0); timerSpeedMenu->AppendRadioItem(MAINFRAME_MENU_ID_TIMER_SPEED_05X, _("&0.5x speed"), wxEmptyString)->Check(ActiveSettings::GetTimerShiftFactor() == 4); timerSpeedMenu->AppendRadioItem(MAINFRAME_MENU_ID_TIMER_SPEED_025X, _("&0.25x speed"), wxEmptyString)->Check(ActiveSettings::GetTimerShiftFactor() == 5); timerSpeedMenu->AppendRadioItem(MAINFRAME_MENU_ID_TIMER_SPEED_0125X, _("&0.125x speed"), wxEmptyString)->Check(ActiveSettings::GetTimerShiftFactor() == 6); // cpu submenu wxMenu* cpuMenu = new wxMenu(); cpuMenu->AppendSubMenu(timerSpeedMenu, _("&Timer speed")); m_menuBar->Append(cpuMenu, _("&CPU")); // nfc submenu wxMenu* nfcMenu = new wxMenu(); m_nfcMenu = nfcMenu; nfcMenu->Append(MAINFRAME_MENU_ID_NFC_TOUCH_NFC_FILE, _("&Scan NFC tag from file"))->Enable(false); m_menuBar->Append(nfcMenu, _("&NFC")); m_nfcMenuSeparator0 = nullptr; // debug->logging submenu wxMenu* debugLoggingMenu = new wxMenu(); debugLoggingMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::UnsupportedAPI), _("&Unsupported API calls"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::UnsupportedAPI)); debugLoggingMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::APIErrors), _("&Invalid API usage"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::APIErrors)); debugLoggingMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::CoreinitLogging), _("&Coreinit Logging (OSReport/OSConsole)"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::CoreinitLogging)); debugLoggingMenu->AppendSeparator(); wxMenu* logCosModulesMenu = new wxMenu(); logCosModulesMenu->AppendCheckItem(0, _("&Options below are for experts. Leave off if unsure"), wxEmptyString)->Enable(false); logCosModulesMenu->AppendSeparator(); logCosModulesMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::CoreinitFile), _("coreinit File-Access API"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::CoreinitFile)); logCosModulesMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::CoreinitThreadSync), _("coreinit Thread-Synchronization API"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::CoreinitThreadSync)); logCosModulesMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::CoreinitMem), _("coreinit Memory API"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::CoreinitMem)); logCosModulesMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::CoreinitMP), _("coreinit MP API"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::CoreinitMP)); logCosModulesMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::CoreinitThread), _("coreinit Thread API"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::CoreinitThread)); logCosModulesMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::Save), _("nn_save API"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::Save)); logCosModulesMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::NN_NFP), _("nn_nfp API"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::NN_NFP)); logCosModulesMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::NN_FP), _("nn_fp API"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::NN_FP)); logCosModulesMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::PRUDP), _("nn_fp PRUDP"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::PRUDP)); logCosModulesMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::NN_BOSS), _("nn_boss API"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::NN_BOSS)); logCosModulesMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::NFC), _("nfc API"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::NFC)); logCosModulesMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::NTAG), _("ntag API"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::NTAG)); logCosModulesMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::Socket), _("nsysnet API"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::Socket)); logCosModulesMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::H264), _("h264 API"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::H264)); logCosModulesMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::GX2), _("gx2 API"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::GX2)); logCosModulesMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::SoundAPI), _("Audio API"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::SoundAPI)); logCosModulesMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::InputAPI), _("Input API"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::InputAPI)); debugLoggingMenu->AppendSubMenu(logCosModulesMenu, _("&CafeOS modules logging")); debugLoggingMenu->AppendSeparator(); debugLoggingMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::Patches), _("&Graphic pack patches"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::Patches)); debugLoggingMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::TextureCache), _("&Texture cache warnings"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::TextureCache)); debugLoggingMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::TextureReadback), _("&Texture readback"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::TextureReadback)); debugLoggingMenu->AppendSeparator(); debugLoggingMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::OpenGLLogging), _("&OpenGL debug output"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::OpenGLLogging)); debugLoggingMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::VulkanValidation), _("&Vulkan validation layer (slow)"), wxEmptyString)->Check(cemuLog_isLoggingEnabled(LogType::VulkanValidation)); debugLoggingMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_ADVANCED_PPC_INFO, _("&Log PPC context for API"), wxEmptyString)->Check(cemuLog_advancedPPCLoggingEnabled()); m_loggingSubmenu = debugLoggingMenu; // debug->dump submenu wxMenu* debugDumpMenu = new wxMenu; debugDumpMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_DUMP_TEXTURES, _("&Textures"), wxEmptyString)->Check(ActiveSettings::DumpTexturesEnabled()); debugDumpMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_DUMP_SHADERS, _("&Shaders"), wxEmptyString)->Check(ActiveSettings::DumpShadersEnabled()); debugDumpMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_DUMP_CURL_REQUESTS, _("&nlibcurl HTTP/HTTPS requests"), wxEmptyString); // debug submenu wxMenu* debugMenu = new wxMenu(); m_debugMenu = debugMenu; debugMenu->AppendSubMenu(debugLoggingMenu, _("&Logging")); debugMenu->AppendSubMenu(debugDumpMenu, _("&Dump")); debugMenu->AppendSeparator(); auto upsidedownItem = debugMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_RENDER_UPSIDE_DOWN, _("&Render upside-down"), wxEmptyString); upsidedownItem->Check(ActiveSettings::RenderUpsideDownEnabled()); if(LaunchSettings::RenderUpsideDownEnabled().has_value()) upsidedownItem->Enable(false); auto accurateBarriers = debugMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_VK_ACCURATE_BARRIERS, _("&Accurate barriers (Vulkan)"), wxEmptyString); accurateBarriers->Check(GetConfig().vk_accurate_barriers); debugMenu->AppendSeparator(); #ifdef CEMU_DEBUG_ASSERT auto audioAuxOnly = debugMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_AUDIO_AUX_ONLY, _("&Audio AUX only"), wxEmptyString); audioAuxOnly->Check(ActiveSettings::AudioOutputOnlyAux()); #endif debugMenu->Append(MAINFRAME_MENU_ID_DEBUG_VIEW_LOGGING_WINDOW, _("&Open logging window")); m_gdbstub_toggle = debugMenu->AppendCheckItem(MAINFRAME_MENU_ID_DEBUG_TOGGLE_GDB_STUB, _("&Launch with GDB stub"), wxEmptyString); m_gdbstub_toggle->Check(g_gdbstub != nullptr); m_gdbstub_toggle->Enable(!m_game_launched); debugMenu->Append(MAINFRAME_MENU_ID_DEBUG_VIEW_PPC_THREADS, _("&View PPC threads")); debugMenu->Append(MAINFRAME_MENU_ID_DEBUG_VIEW_PPC_DEBUGGER, _("&View PPC debugger")); debugMenu->Append(MAINFRAME_MENU_ID_DEBUG_VIEW_AUDIO_DEBUGGER, _("&View audio debugger")); debugMenu->Append(MAINFRAME_MENU_ID_DEBUG_VIEW_TEXTURE_RELATIONS, _("&View texture cache info")); debugMenu->Append(MAINFRAME_MENU_ID_DEBUG_DUMP_RAM, _("&Dump current RAM")); // debugMenu->Append(MAINFRAME_MENU_ID_DEBUG_DUMP_FST, _("&Dump WUD filesystem"))->Enable(false); m_menuBar->Append(debugMenu, _("&Debug")); // help menu wxMenu* helpMenu = new wxMenu(); m_check_update_menu = helpMenu->Append(MAINFRAME_MENU_ID_HELP_UPDATE, _("&Check for updates")); #if BOOST_OS_LINUX if (!std::getenv("APPIMAGE")) { m_check_update_menu->Enable(false); } #endif helpMenu->AppendSeparator(); helpMenu->Append(MAINFRAME_MENU_ID_HELP_ABOUT, _("&About Cemu")); m_menuBar->Append(helpMenu, _("&Help")); SetMenuBar(m_menuBar); m_menu_visible = true; if (m_game_launched) { if (m_check_update_menu) m_check_update_menu->Enable(false); m_memorySearcherMenuItem->Enable(true); m_nfcMenu->Enable(MAINFRAME_MENU_ID_NFC_TOUCH_NFC_FILE, true); // these options cant be toggled after the renderer backend is initialized: m_loggingSubmenu->Enable(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::OpenGLLogging), false); m_loggingSubmenu->Enable(MAINFRAME_MENU_ID_DEBUG_LOGGING0 + stdx::to_underlying(LogType::VulkanValidation), false); UpdateNFCMenu(); } // hide new menu in fullscreen if (IsFullScreen()) SetMenuVisible(false); } void MainWindow::UpdateChildWindowTitleRunningState() { const bool running = CafeSystem::IsTitleRunning(); if(m_graphic_pack_window) m_graphic_pack_window->UpdateTitleRunning(running); } void MainWindow::RestoreSettingsAfterGameExited() { RecreateMenu(); } void MainWindow::UpdateSettingsAfterGameLaunch() { m_update_available = {}; RecreateMenu(); } void MainWindow::OnGraphicWindowClose(wxCloseEvent& event) { m_graphic_pack_window->Destroy(); m_graphic_pack_window = nullptr; } void MainWindow::OnGraphicWindowOpen(wxTitleIdEvent& event) { if (m_graphic_pack_window) return; m_graphic_pack_window = new GraphicPacksWindow2(this, event.GetTitleId()); m_graphic_pack_window->Bind(wxEVT_CLOSE_WINDOW, &MainWindow::OnGraphicWindowClose, this); m_graphic_pack_window->Show(true); } void MainWindow::RequestGameListRefresh() { auto* evt = new wxCommandEvent(wxEVT_REQUEST_GAMELIST_REFRESH); wxQueueEvent(g_mainFrame, evt); } void MainWindow::RequestLaunchGame(fs::path filePath, wxLaunchGameEvent::INITIATED_BY initiatedBy) { wxLaunchGameEvent evt(filePath, initiatedBy); wxPostEvent(g_mainFrame, evt); } void MainWindow::OnRequestRecreateCanvas(wxCommandEvent& event) { CounterSemaphore* sem = (CounterSemaphore*)event.GetClientData(); DestroyCanvas(); CreateCanvas(); sem->increment(); } void MainWindow::CafeRecreateCanvas() { CounterSemaphore sem; auto* evt = new wxCommandEvent(wxEVT_REQUEST_RECREATE_CANVAS); evt->SetClientData((void*)&sem); wxQueueEvent(g_mainFrame, evt); sem.decrementWithWait(); }
82,389
C++
.cpp
2,074
36.910318
292
0.736955
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,969
CemuUpdateWindow.cpp
cemu-project_Cemu/src/gui/CemuUpdateWindow.cpp
#include "gui/CemuUpdateWindow.h" #include "Common/version.h" #include "util/helpers/helpers.h" #include "util/helpers/SystemException.h" #include "config/ActiveSettings.h" #include "Common/FileStream.h" #include <wx/sizer.h> #include <wx/gauge.h> #include <wx/button.h> #include <wx/msgdlg.h> #include <wx/stdpaths.h> #ifndef BOOST_OS_WINDOWS #include <unistd.h> #include <sys/stat.h> #endif #include <curl/curl.h> #include <zip.h> #include <boost/tokenizer.hpp> wxDECLARE_EVENT(wxEVT_RESULT, wxCommandEvent); wxDEFINE_EVENT(wxEVT_RESULT, wxCommandEvent); wxDECLARE_EVENT(wxEVT_PROGRESS, wxCommandEvent); wxDEFINE_EVENT(wxEVT_PROGRESS, wxCommandEvent); CemuUpdateWindow::CemuUpdateWindow(wxWindow* parent) : wxDialog(parent, wxID_ANY, _("Cemu update"), wxDefaultPosition, wxDefaultSize, wxCAPTION | wxMINIMIZE_BOX | wxSYSTEM_MENU | wxTAB_TRAVERSAL | wxCLOSE_BOX) { auto* sizer = new wxBoxSizer(wxVERTICAL); m_gauge = new wxGauge(this, wxID_ANY, 100, wxDefaultPosition, wxSize(500, 20), wxGA_HORIZONTAL); m_gauge->SetValue(0); sizer->Add(m_gauge, 0, wxALL | wxEXPAND, 5); auto* rows = new wxFlexGridSizer(0, 2, 0, 0); rows->AddGrowableCol(1); m_text = new wxStaticText(this, wxID_ANY, _("Checking for latest version...")); rows->Add(m_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); { auto* right_side = new wxBoxSizer(wxHORIZONTAL); m_updateButton = new wxButton(this, wxID_ANY, _("Update")); m_updateButton->Bind(wxEVT_BUTTON, &CemuUpdateWindow::OnUpdateButton, this); right_side->Add(m_updateButton, 0, wxALL, 5); m_cancelButton = new wxButton(this, wxID_ANY, _("Cancel")); m_cancelButton->Bind(wxEVT_BUTTON, &CemuUpdateWindow::OnCancelButton, this); right_side->Add(m_cancelButton, 0, wxALL, 5); rows->Add(right_side, 1, wxALIGN_RIGHT, 5); } m_changelog = new wxHyperlinkCtrl(this, wxID_ANY, _("Changelog"), wxEmptyString); rows->Add(m_changelog, 0, wxLEFT | wxBOTTOM | wxRIGHT | wxEXPAND, 5); sizer->Add(rows, 0, wxALL | wxEXPAND, 5); SetSizerAndFit(sizer); Centre(wxBOTH); Bind(wxEVT_CLOSE_WINDOW, &CemuUpdateWindow::OnClose, this); Bind(wxEVT_RESULT, &CemuUpdateWindow::OnResult, this); Bind(wxEVT_PROGRESS, &CemuUpdateWindow::OnGaugeUpdate, this); m_thread = std::thread(&CemuUpdateWindow::WorkerThread, this); m_updateButton->Hide(); m_changelog->Hide(); } CemuUpdateWindow::~CemuUpdateWindow() { m_order = WorkerOrder::Exit; if (m_thread.joinable()) m_thread.join(); } size_t CemuUpdateWindow::WriteStringCallback(char* ptr, size_t size, size_t nmemb, void* userdata) { ((std::string*)userdata)->append(ptr, size * nmemb); return size * nmemb; }; std::string _curlUrlEscape(CURL* curl, const std::string& input) { char* escapedStr = curl_easy_escape(curl, input.c_str(), input.size()); std::string r(escapedStr); curl_free(escapedStr); return r; } std::string _curlUrlUnescape(CURL* curl, std::string_view input) { int decodedLen = 0; const char* decoded = curl_easy_unescape(curl, input.data(), input.size(), &decodedLen); return std::string(decoded, decodedLen); } // returns true if update is available and sets output parameters bool CemuUpdateWindow::QueryUpdateInfo(std::string& downloadUrlOut, std::string& changelogUrlOut) { std::string buffer; std::string urlStr("https://cemu.info/api2/version.php?v="); auto* curl = curl_easy_init(); urlStr.append(_curlUrlEscape(curl, BUILD_VERSION_STRING)); #if BOOST_OS_LINUX urlStr.append("&platform=linux_appimage_x86"); #elif BOOST_OS_WINDOWS urlStr.append("&platform=windows"); #elif BOOST_OS_MACOS urlStr.append("&platform=macos_bundle_x86"); #elif #error Name for current platform is missing #endif const auto& config = GetConfig(); if(config.receive_untested_updates) urlStr.append("&allowNewUpdates=1"); curl_easy_setopt(curl, CURLOPT_URL, urlStr.c_str()); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteStringCallback); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); bool result = false; CURLcode cr = curl_easy_perform(curl); if (cr == CURLE_OK) { long http_code = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code); if (http_code != 0 && http_code != 200) { cemuLog_log(LogType::Force, "Update check failed (http code: {})", http_code); cemu_assert_debug(false); return false; } std::vector<std::string> tokens; const boost::char_separator<char> sep{ "|" }; for (const auto& token : boost::tokenizer(buffer, sep)) tokens.emplace_back(token); if (tokens.size() >= 3 && tokens[0] == "UPDATE") { // first token: "UPDATE" // second token: Download URL // third token: Changelog URL // we allow more tokens in case we ever want to add extra information for future releases downloadUrlOut = _curlUrlUnescape(curl, tokens[1]); changelogUrlOut = _curlUrlUnescape(curl, tokens[2]); if (!downloadUrlOut.empty() && !changelogUrlOut.empty()) result = true; } } else { cemuLog_log(LogType::Force, "Update check failed with CURL error {}", (int)cr); cemu_assert_debug(false); } curl_easy_cleanup(curl); return result; } std::future<bool> CemuUpdateWindow::IsUpdateAvailableAsync() { return std::async(std::launch::async, CheckVersion); } bool CemuUpdateWindow::CheckVersion() { std::string downloadUrl, changelogUrl; return QueryUpdateInfo(downloadUrl, changelogUrl); } int CemuUpdateWindow::ProgressCallback(void* clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) { auto* thisptr = (CemuUpdateWindow*)clientp; auto* event = new wxCommandEvent(wxEVT_PROGRESS); event->SetInt((int)dlnow); wxQueueEvent(thisptr, event); return 0; } bool CemuUpdateWindow::DownloadCemuZip(const std::string& url, const fs::path& filename) { FileStream* fsUpdateFile = FileStream::createFile2(filename); if (!fsUpdateFile) return false; bool result = false; auto* curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_NOBODY, 1); curl_easy_setopt(curl, CURLOPT_USERAGENT, BUILD_VERSION_WITH_NAME_STRING); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); auto r = curl_easy_perform(curl); if (r == CURLE_OK) { long http_code = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code); if (http_code != 0 && http_code != 200) { cemuLog_log(LogType::Force, "Unable to download cemu update zip file from {} (http error: {})", url, http_code); curl_easy_cleanup(curl); return false; } curl_off_t update_size; if (curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &update_size) == CURLE_OK) m_gaugeMaxValue = (int)update_size; auto _curlWriteData = +[](void* ptr, size_t size, size_t nmemb, void* ctx) -> size_t { FileStream* fs = (FileStream*)ctx; const size_t writeSize = size * nmemb; fs->writeData(ptr, writeSize); return writeSize; }; curl_easy_setopt(curl, CURLOPT_NOBODY, 0); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, _curlWriteData); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fsUpdateFile); curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0); curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, ProgressCallback); curl_easy_setopt(curl, CURLOPT_XFERINFODATA, this); auto curl_result = std::async(std::launch::async, [](CURL* curl, long* http_code) { const auto r = curl_easy_perform(curl); curl_easy_cleanup(curl); return r; }, curl, &http_code); while (!curl_result.valid()) { if (m_order == WorkerOrder::Exit) return false; std::this_thread::sleep_for(std::chrono::milliseconds(1)); } result = curl_result.get() == CURLE_OK; delete fsUpdateFile; } else { cemuLog_log(LogType::Force, "Cemu zip download failed with error {}", r); curl_easy_cleanup(curl); } if (!result && fs::exists(filename)) { try { fs::remove(filename); } catch (const std::exception& ex) { cemuLog_log(LogType::Force, "can't remove update.zip on error: {}", ex.what()); } } return result; } bool CemuUpdateWindow::ExtractUpdate(const fs::path& zipname, const fs::path& targetpath, std::string& cemuFolderName) { cemuFolderName.clear(); // open downloaded zip int err; auto* za = zip_open(zipname.string().c_str(), ZIP_RDONLY, &err); if (za == nullptr) { cemuLog_log(LogType::Force, "Cannot open zip file: {}", zipname.string()); return false; } const auto count = zip_get_num_entries(za, 0); m_gaugeMaxValue = count; for (auto i = 0; i < count; i++) { if (m_order == WorkerOrder::Exit) return false; zip_stat_t sb{}; if (zip_stat_index(za, i, 0, &sb) == 0) { fs::path fname = targetpath; fname /= sb.name; const auto len = strlen(sb.name); if (strcmp(sb.name, ".") == 0 || strcmp(sb.name, "..") == 0) { // protection continue; } if (sb.name[len - 1] == '/' || sb.name[len - 1] == '\\') { // directory try { if (!exists(fname)) create_directory(fname); } catch (const std::exception& ex) { SystemException sys(ex); cemuLog_log(LogType::Force, "can't create folder \"{}\" for update: {}", sb.name, sys.what()); } // the root should have only one Cemu_... directory, we track it here if ((std::count(sb.name, sb.name + len, '/') + std::count(sb.name, sb.name + len, '\\')) == 1) { if (!cemuFolderName.empty()) cemuLog_log(LogType::Force, "update zip has multiple folders in root"); cemuFolderName.assign(sb.name, len - 1); } continue; } // file auto* zf = zip_fopen_index(za, i, 0); if (!zf) { cemuLog_log(LogType::Force, "can't open zip file \"{}\"", sb.name); zip_close(za); return false; } std::vector<char> buffer(sb.size); const auto read = zip_fread(zf, buffer.data(), sb.size); if (read != (sint64)sb.size) { cemuLog_log(LogType::Force, "could only read 0x{:x} of 0x{:x} bytes from zip file \"{}\"", read, sb.size, sb.name); zip_close(za); return false; } auto* file = fopen(fname.string().c_str(), "wb"); if (file == nullptr) { cemuLog_log(LogType::Force, "can't create update file \"{}\"", sb.name); zip_close(za); return false; } fwrite(buffer.data(), 1, buffer.size(), file); fflush(file); fclose(file); zip_fclose(zf); if ((i / 10) * 10 == i) { auto* event = new wxCommandEvent(wxEVT_PROGRESS); event->SetInt(i); wxQueueEvent(this, event); } } } auto* event = new wxCommandEvent(wxEVT_PROGRESS); event->SetInt(m_gaugeMaxValue); wxQueueEvent(this, event); zip_close(za); return true; } void CemuUpdateWindow::WorkerThread() { const auto tmppath = fs::temp_directory_path() / L"cemu_update"; std::error_code ec; // clean leftovers if (exists(tmppath)) remove_all(tmppath, ec); while (true) { std::unique_lock lock(m_mutex); while (m_order == WorkerOrder::Idle) m_condition.wait_for(lock, std::chrono::milliseconds(125)); if (m_order == WorkerOrder::Exit) break; try { if (m_order == WorkerOrder::CheckVersion) { auto* event = new wxCommandEvent(wxEVT_RESULT); if (QueryUpdateInfo(m_downloadUrl, m_changelogUrl)) event->SetInt((int)Result::UpdateAvailable); else event->SetInt((int)Result::NoUpdateAvailable); wxQueueEvent(this, event); } else if (m_order == WorkerOrder::UpdateVersion) { // download update const std::string url = m_downloadUrl; if (!exists(tmppath)) create_directory(tmppath); #if BOOST_OS_WINDOWS const auto update_file = tmppath / L"update.zip"; #elif BOOST_OS_LINUX const auto update_file = tmppath / L"Cemu.AppImage"; #elif BOOST_OS_MACOS const auto update_file = tmppath / L"cemu.dmg"; #endif if (DownloadCemuZip(url, update_file)) { auto* event = new wxCommandEvent(wxEVT_RESULT); event->SetInt((int)Result::UpdateDownloaded); wxQueueEvent(this, event); } else { auto* event = new wxCommandEvent(wxEVT_RESULT); event->SetInt((int)Result::UpdateDownloadError); wxQueueEvent(this, event); m_order = WorkerOrder::Idle; continue; } if (m_order == WorkerOrder::Exit) break; // extract std::string cemuFolderName; #if BOOST_OS_WINDOWS if (!ExtractUpdate(update_file, tmppath, cemuFolderName)) { cemuLog_log(LogType::Force, "Extracting Cemu zip failed"); break; } if (cemuFolderName.empty()) { cemuLog_log(LogType::Force, "Cemu folder not found in zip"); break; } #endif const auto expected_path = tmppath / cemuFolderName; if (exists(expected_path)) { auto* event = new wxCommandEvent(wxEVT_RESULT); event->SetInt((int)Result::ExtractSuccess); wxQueueEvent(this, event); } else { auto* event = new wxCommandEvent(wxEVT_RESULT); event->SetInt((int)Result::ExtractError); wxQueueEvent(this, event); if (exists(tmppath)) { try { fs::remove(tmppath); } catch (const std::exception& ex) { SystemException sys(ex); cemuLog_log(LogType::Force, "can't remove extracted tmp files: {}", sys.what()); } } continue; } if (m_order == WorkerOrder::Exit) break; // apply update fs::path exePath = ActiveSettings::GetExecutablePath(); #if BOOST_OS_WINDOWS std::wstring target_directory = exePath.parent_path().generic_wstring(); if (target_directory[target_directory.size() - 1] == '/') target_directory = target_directory.substr(0, target_directory.size() - 1); // remove trailing / // get exe name const auto exec = ActiveSettings::GetExecutablePath(); const auto target_exe = fs::path(exec).replace_extension("exe.backup"); fs::rename(exec, target_exe); m_restartFile = exec; #elif BOOST_OS_LINUX const char* appimage_path = std::getenv("APPIMAGE"); const auto target_exe = fs::path(appimage_path).replace_extension("AppImage.backup"); const char* filePath = update_file.c_str(); mode_t permissions = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH; fs::rename(appimage_path, target_exe); m_restartFile = appimage_path; chmod(filePath, permissions); wxString wxAppPath = wxString::FromUTF8(appimage_path); wxCopyFile (wxT("/tmp/cemu_update/Cemu.AppImage"), wxAppPath); #endif #if BOOST_OS_WINDOWS const auto index = expected_path.wstring().size(); int counter = 0; for (const auto& it : fs::recursive_directory_iterator(expected_path)) { const auto filename = it.path().wstring().substr(index); auto target_file = target_directory + filename; try { if (is_directory(it)) { if (!fs::exists(target_file)) fs::create_directory(target_file); } else { if (it.path().filename() == L"Cemu.exe") fs::rename(it.path(), fs::path(target_file).replace_filename(exec.filename())); else fs::rename(it.path(), target_file); } } catch (const std::exception& ex) { SystemException sys(ex); cemuLog_log(LogType::Force, "applying update error: {}", sys.what()); } if ((counter++ % 10) == 0) { auto* event = new wxCommandEvent(wxEVT_PROGRESS); event->SetInt(counter); wxQueueEvent(this, event); } } #endif auto* event = new wxCommandEvent(wxEVT_PROGRESS); event->SetInt(m_gaugeMaxValue); wxQueueEvent(this, event); auto* result_event = new wxCommandEvent(wxEVT_RESULT); result_event->SetInt((int)Result::Success); wxQueueEvent(this, result_event); } } catch (const std::exception& ex) { SystemException sys(ex); cemuLog_log(LogType::Force, "update error: {}", sys.what()); // clean leftovers if (exists(tmppath)) remove_all(tmppath, ec); auto* result_event = new wxCommandEvent(wxEVT_RESULT); result_event->SetInt((int)Result::Error); wxQueueEvent(this, result_event); } m_order = WorkerOrder::Idle; } } void CemuUpdateWindow::OnClose(wxCloseEvent& event) { event.Skip(); #if BOOST_OS_WINDOWS if (m_restartRequired && !m_restartFile.empty() && fs::exists(m_restartFile)) { PROCESS_INFORMATION pi{}; STARTUPINFO si{}; si.cb = sizeof(si); std::wstring cmdline = GetCommandLineW(); const auto index = cmdline.find('"', 1); cemu_assert_debug(index != std::wstring::npos); cmdline = L"\"" + m_restartFile.wstring() + L"\"" + cmdline.substr(index + 1); HANDLE lock = CreateMutex(nullptr, TRUE, L"Global\\cemu_update_lock"); CreateProcess(nullptr, (wchar_t*)cmdline.c_str(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi); exit(0); } #elif BOOST_OS_LINUX if (m_restartRequired && !m_restartFile.empty() && fs::exists(m_restartFile)) { const char* appimage_path = std::getenv("APPIMAGE"); execlp(appimage_path, appimage_path, (char *)NULL); exit(0); } #elif BOOST_OS_MACOS if (m_restartRequired) { const auto tmppath = fs::temp_directory_path() / L"cemu_update/Cemu.dmg"; fs::path exePath = ActiveSettings::GetExecutablePath().parent_path(); const auto apppath = exePath / L"update.sh"; execlp("sh", "sh", apppath.c_str(), NULL); exit(0); } #endif } void CemuUpdateWindow::OnResult(wxCommandEvent& event) { switch ((Result)event.GetInt()) { case Result::NoUpdateAvailable: m_cancelButton->SetLabel(_("Exit")); m_text->SetLabel(_("No update available!")); m_gauge->SetValue(100); break; case Result::UpdateAvailable: { if (!m_changelogUrl.empty()) { m_changelog->SetURL(m_changelogUrl); m_changelog->Show(); } else m_changelog->Hide(); m_updateButton->Show(); m_text->SetLabel(_("Update available!")); m_cancelButton->SetLabel(_("Exit")); break; } case Result::UpdateDownloaded: m_text->SetLabel(_("Extracting update...")); m_gauge->SetValue(0); break; case Result::UpdateDownloadError: m_updateButton->Enable(); m_text->SetLabel(_("Couldn't download the update!")); break; case Result::ExtractSuccess: m_text->SetLabel(_("Applying update...")); m_gauge->SetValue(0); m_cancelButton->Disable(); break; case Result::ExtractError: m_updateButton->Enable(); m_cancelButton->Enable(); m_text->SetLabel(_("Extracting failed!")); break; case Result::Success: m_cancelButton->Enable(); m_updateButton->Hide(); m_text->SetLabel(_("Success")); m_cancelButton->SetLabel(_("Restart")); m_restartRequired = true; break; default:; } } void CemuUpdateWindow::OnGaugeUpdate(wxCommandEvent& event) { const int total_size = m_gaugeMaxValue > 0 ? m_gaugeMaxValue : 10000000; m_gauge->SetValue((event.GetInt() * 100) / total_size); } void CemuUpdateWindow::OnUpdateButton(const wxCommandEvent& event) { std::unique_lock lock(m_mutex); m_order = WorkerOrder::UpdateVersion; m_condition.notify_all(); m_updateButton->Disable(); m_text->SetLabel(_("Downloading update...")); } void CemuUpdateWindow::OnCancelButton(const wxCommandEvent& event) { Close(); }
19,191
C++
.cpp
600
28.468333
119
0.688173
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,970
LoggingWindow.cpp
cemu-project_Cemu/src/gui/LoggingWindow.cpp
#include "gui/LoggingWindow.h" #include "gui/helpers/wxLogEvent.h" #include <wx/sizer.h> #include <wx/stattext.h> #include <wx/wupdlock.h> #include "gui/helpers/wxHelpers.h" wxDEFINE_EVENT(EVT_LOG, wxLogEvent); LoggingWindow* s_instance; LoggingWindow::LoggingWindow(wxFrame* parent) : wxFrame(parent, wxID_ANY, _("Logging window"), wxDefaultPosition, wxSize(800, 600), wxDEFAULT_FRAME_STYLE | wxTAB_TRAVERSAL) { auto* sizer = new wxBoxSizer( wxVERTICAL ); { auto filter_row = new wxBoxSizer( wxHORIZONTAL ); filter_row->Add(new wxStaticText( this, wxID_ANY, _("Filter")), 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); wxString choices[] = {"Unsupported APIs calls", "Coreinit Logging", "Coreinit File-Access", "Coreinit Thread-Synchronization", "Coreinit Memory", "Coreinit MP", "Coreinit Thread", "nn::nfp", "GX2", "Audio", "Input", "Socket", "Save", "H264", "Graphic pack patches", "Texture cache", "Texture readback", "OpenGL debug output", "Vulkan validation layer"}; m_filter = new wxComboBox( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, std::size(choices), choices, 0 ); m_filter->Bind(wxEVT_COMBOBOX, &LoggingWindow::OnFilterChange, this); m_filter->Bind(wxEVT_TEXT, &LoggingWindow::OnFilterChange, this); filter_row->Add(m_filter, 1, wxALL, 5 ); m_filter_message = new wxCheckBox(this, wxID_ANY, _("Filter messages")); m_filter_message->Bind(wxEVT_CHECKBOX, &LoggingWindow::OnFilterMessageChange, this); filter_row->Add(m_filter_message, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5 ); sizer->Add( filter_row, 0, wxEXPAND, 5 ); } m_log_list = new wxLogCtrl(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxScrolledWindowStyle|wxVSCROLL);//( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, NULL, wxLB_HSCROLL ); sizer->Add( m_log_list, 1, wxALL | wxEXPAND, 5 ); this->SetSizer( sizer ); this->Layout(); this->Bind(EVT_LOG, &LoggingWindow::OnLogMessage, this); std::unique_lock lock(s_mutex); cemu_assert_debug(s_instance == nullptr); s_instance = this; } LoggingWindow::~LoggingWindow() { this->Unbind(EVT_LOG, &LoggingWindow::OnLogMessage, this); std::unique_lock lock(s_mutex); s_instance = nullptr; } void LoggingWindow::Log(std::string_view filter, std::string_view message) { std::shared_lock lock(s_mutex); if(!s_instance) return; wxLogEvent event(std::string {filter}, std::string{ message }); s_instance->OnLogMessage(event); //const auto log_event = new wxLogEvent(filter, message); //wxQueueEvent(s_instance, log_event); } void LoggingWindow::Log(std::string_view filter, std::wstring_view message) { std::shared_lock lock(s_mutex); if(!s_instance) return; wxLogEvent event(std::string {filter}, std::wstring{ message }); s_instance->OnLogMessage(event); //const auto log_event = new wxLogEvent(filter, message); //wxQueueEvent(s_instance, log_event); } void LoggingWindow::OnLogMessage(wxLogEvent& event) { m_log_list->PushEntry(event.GetFilter(), event.GetMessage()); } void LoggingWindow::OnFilterChange(wxCommandEvent& event) { m_log_list->SetActiveFilter(m_filter->GetValue().utf8_string()); event.Skip(); } void LoggingWindow::OnFilterMessageChange(wxCommandEvent& event) { m_log_list->SetFilterMessage(m_filter_message->GetValue()); event.Skip(); }
3,274
C++
.cpp
74
42.081081
355
0.743541
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,971
GameProfileWindow.cpp
cemu-project_Cemu/src/gui/GameProfileWindow.cpp
#include "gui/GameProfileWindow.h" #include <wx/statbox.h> #include <wx/sizer.h> #include <wx/panel.h> #include <wx/notebook.h> #include <wx/stattext.h> #include <wx/wupdlock.h> #include <wx/slider.h> #include "gui/helpers/wxHelpers.h" #include "input/InputManager.h" #if BOOST_OS_LINUX || BOOST_OS_MACOS #include "resource/embedded/resources.h" #endif GameProfileWindow::GameProfileWindow(wxWindow* parent, uint64_t title_id) : wxFrame(parent, wxID_ANY, _("Edit game profile"), wxDefaultPosition, wxSize{ 390, 350 }, wxCLOSE_BOX | wxCLIP_CHILDREN | wxCAPTION | wxRESIZE_BORDER | wxTAB_TRAVERSAL | wxSYSTEM_MENU), m_title_id(title_id) { SetIcon(wxICON(X_GAME_PROFILE)); m_game_profile.Reset(); m_game_profile.Load(title_id); this->SetSizeHints(wxDefaultSize, wxDefaultSize); auto* main_sizer = new wxBoxSizer(wxVERTICAL); auto* m_notebook = new wxNotebook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0); // general { auto* panel = new wxPanel(m_notebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); auto* sizer = new wxBoxSizer(wxVERTICAL); { auto* box_sizer = new wxStaticBoxSizer(new wxStaticBox(panel, wxID_ANY, _("General")), wxVERTICAL); auto* box = box_sizer->GetStaticBox(); m_load_libs = new wxCheckBox(box, wxID_ANY, _("Load shared libraries")); m_load_libs->SetToolTip(_("EXPERT OPTION\nThis option will load libraries from the cafeLibs directory")); box_sizer->Add(m_load_libs, 0, wxALL, 5); m_start_with_padview = new wxCheckBox(box, wxID_ANY, _("Launch with gamepad view")); m_start_with_padview->SetToolTip(_("Games will be launched with gamepad view toggled as default. The view can be toggled with CTRL + TAB")); box_sizer->Add(m_start_with_padview, 0, wxALL, 5); sizer->Add(box_sizer, 0, wxEXPAND, 5); } // cpu { auto* box_sizer = new wxStaticBoxSizer(new wxStaticBox(panel, wxID_ANY, _("CPU")), wxVERTICAL); auto* box = box_sizer->GetStaticBox(); auto* first_row = new wxFlexGridSizer(0, 2, 0, 0); first_row->SetFlexibleDirection(wxBOTH); first_row->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); first_row->Add(new wxStaticText(box, wxID_ANY, _("Mode")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); wxString cpu_modes[] = { _("Single-core interpreter"), _("Single-core recompiler"), _("Multi-core recompiler"), _("Auto (recommended)") }; const sint32 m_cpu_modeNChoices = std::size(cpu_modes); m_cpu_mode = new wxChoice(box, wxID_ANY, wxDefaultPosition, wxDefaultSize, m_cpu_modeNChoices, cpu_modes, 0); m_cpu_mode->SetToolTip(_("Set the CPU emulation mode")); first_row->Add(m_cpu_mode, 0, wxALL, 5); first_row->Add(new wxStaticText(box, wxID_ANY, _("Thread quantum")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); auto* quantum_sizer = new wxFlexGridSizer(0, 2, 0, 0); quantum_sizer->SetFlexibleDirection(wxBOTH); quantum_sizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); wxString quantum_values[] = { "20000", "45000", "60000", "80000" ,"100000" }; m_thread_quantum = new wxChoice(box, wxID_ANY, wxDefaultPosition, wxDefaultSize, std::size(quantum_values), quantum_values); m_thread_quantum->SetMinSize(wxSize(85, -1)); m_thread_quantum->SetToolTip(_("EXPERT OPTION\nSet the maximum thread slice runtime (in virtual cycles)")); quantum_sizer->Add(m_thread_quantum, 0, wxALL, 5); quantum_sizer->Add(new wxStaticText(box, wxID_ANY, _("cycles")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); first_row->Add(quantum_sizer, 0, wxEXPAND, 5); box_sizer->Add(first_row, 0, wxEXPAND, 5); sizer->Add(box_sizer, 0, wxEXPAND, 5); } panel->SetSizer(sizer); panel->Layout(); sizer->Fit(panel); m_notebook->AddPage(panel, _("General"), true); } // graphic { auto* panel = new wxPanel(m_notebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); auto* sizer = new wxBoxSizer(wxVERTICAL); //m_extended_texture_readback = new wxCheckBox(panel, wxID_ANY, _("Extended texture readback")); //m_extended_texture_readback->SetToolTip(_("Improves emulation accuracy of CPU to GPU memory access at the cost of performance. Required for some games.")); //sizer->Add(m_extended_texture_readback, 0, wxALL, 5); auto* first_row = new wxFlexGridSizer(0, 2, 0, 0); first_row->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); /*first_row->Add(new wxStaticText(panel, wxID_ANY, _("Precompiled shaders")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); wxString precompiled_modes[] = { _("auto"), _("enable"), _("disable") }; const sint32 precompiled_count = std::size(precompiled_modes); m_precompiled = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, precompiled_count, precompiled_modes, 0); m_precompiled->SetToolTip(_("Precompiled shaders can speed up the load time on the shader loading screen.\nAuto will enable it for AMD/Intel but disable it for NVIDIA GPUs as a workaround for a driver bug.\n\nRecommended: Auto")); first_row->Add(m_precompiled, 0, wxALL, 5);*/ first_row->Add(new wxStaticText(panel, wxID_ANY, _("Graphics API")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); wxString gapi_values[] = { "", "OpenGL", "Vulkan" }; m_graphic_api = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, (int)std::size(gapi_values), gapi_values); first_row->Add(m_graphic_api, 0, wxALL, 5); first_row->Add(new wxStaticText(panel, wxID_ANY, _("Shader multiplication accuracy")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); wxString mul_values[] = { _("false"), _("true")}; m_shader_mul_accuracy = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, (int)std::size(mul_values), mul_values); m_shader_mul_accuracy->SetToolTip(_("EXPERT OPTION\nControls the accuracy of floating point multiplication in shaders.\n\nRecommended: true")); first_row->Add(m_shader_mul_accuracy, 0, wxALL, 5); /*first_row->Add(new wxStaticText(panel, wxID_ANY, _("GPU buffer cache accuracy")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); wxString accuarcy_values[] = { _("high"), _("medium"), _("low") }; m_cache_accuracy = new wxChoice(panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, (int)std::size(accuarcy_values), accuarcy_values); m_cache_accuracy->SetToolTip(_("Lower value results in higher performance, but may cause graphical issues")); first_row->Add(m_cache_accuracy, 0, wxALL, 5);*/ sizer->Add(first_row, 0, wxEXPAND, 5); panel->SetSizer(sizer); panel->Layout(); sizer->Fit(panel); m_notebook->AddPage(panel, _("Graphic"), false); } //// audio //{ // auto panel = new wxPanel(m_notebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); // wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL); // m_disable_audio = new wxCheckBox(panel, wxID_ANY, _("Disable Audio"), wxDefaultPosition, wxDefaultSize, wxCHK_3STATE | wxCHK_ALLOW_3RD_STATE_FOR_USER); // sizer->Add(m_disable_audio, 0, wxALL, 5); // panel->SetSizer(sizer); // panel->Layout(); // sizer->Fit(panel); // m_notebook->AddPage(panel, _("Audio"), false); //} // controller { auto panel = new wxPanel(m_notebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); wxBoxSizer* sizer; sizer = new wxBoxSizer(wxVERTICAL); wxFlexGridSizer* profile_sizer; profile_sizer = new wxFlexGridSizer(0, 2, 0, 0); profile_sizer->SetFlexibleDirection(wxBOTH); profile_sizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); for (int i = 0; i < 8; ++i) { profile_sizer->Add(new wxStaticText(panel, wxID_ANY, formatWxString(_("Controller {}"), i + 1)), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_controller_profile[i] = new wxComboBox(panel, wxID_ANY,"", wxDefaultPosition, wxDefaultSize, 0, nullptr, wxCB_DROPDOWN| wxCB_READONLY); m_controller_profile[i]->SetMinSize(wxSize(250, -1)); m_controller_profile[i]->Bind(wxEVT_COMBOBOX_DROPDOWN, &GameProfileWindow::OnControllerProfileDropdown, this); m_controller_profile[i]->SetToolTip(_("Forces a given controller profile")); profile_sizer->Add(m_controller_profile[i], 0, wxALL, 5); } sizer->Add(profile_sizer, 0, wxEXPAND, 5); panel->SetSizer(sizer); panel->Layout(); sizer->Fit(panel); m_notebook->AddPage(panel, _("Controller"), false); } main_sizer->Add(m_notebook, 1, wxEXPAND | wxALL, 5); this->SetSizer(main_sizer); this->Layout(); this->Centre(wxBOTH); ApplyProfile(); } GameProfileWindow::~GameProfileWindow() { SaveProfile(); } void GameProfileWindow::OnStreamoutSizeChange(wxCommandEvent& event) { wxSlider* slider = wxDynamicCast(event.GetEventObject(), wxSlider); wxASSERT(slider); wxStaticText* text = wxDynamicCast(slider->GetClientData(), wxStaticText); wxASSERT(text); text->SetLabelText(fmt::format("{} MB", slider->GetValue())); event.Skip(); } void GameProfileWindow::OnControllerProfileDropdown(wxCommandEvent& event) { wxComboBox* cb = wxDynamicCast(event.GetEventObject(), wxComboBox); wxASSERT(cb); wxWindowUpdateLocker lock(cb); const auto selected_value = cb->GetStringSelection(); cb->Clear(); cb->Append(wxEmptyString); auto profiles = InputManager::get_profiles(); for (const auto& profile : profiles) { cb->Append(to_wxString(profile)); } cb->SetStringSelection(selected_value); } void GameProfileWindow::SetProfileInt(gameProfileIntegerOption_t& option, wxCheckBox* checkbox, sint32 value) const { const auto state = checkbox->GetValue(); if (state) { option.isPresent = true; option.value = value; } else option.isPresent = false; } void GameProfileWindow::ApplyProfile() { if(m_game_profile.m_gameName) this->SetTitle(_("Edit game profile") + " - " + m_game_profile.m_gameName.value()); // general m_load_libs->SetValue(m_game_profile.m_loadSharedLibraries.value()); m_start_with_padview->SetValue(m_game_profile.m_startWithPadView); // cpu // wxString cpu_modes[] = { _("Singlecore-Interpreter"), _("Singlecore-Recompiler"), _("Triplecore-Recompiler"), _("Auto (recommended)") }; switch(m_game_profile.m_cpuMode.value()) { case CPUMode::SinglecoreInterpreter: m_cpu_mode->SetSelection(0); break; case CPUMode::SinglecoreRecompiler: m_cpu_mode->SetSelection(1); break; case CPUMode::DualcoreRecompiler: m_cpu_mode->SetSelection(2); break; case CPUMode::MulticoreRecompiler: m_cpu_mode->SetSelection(2); break; default: m_cpu_mode->SetSelection(3); } m_thread_quantum->SetStringSelection(fmt::format("{}", m_game_profile.m_threadQuantum)); // gpu if (!m_game_profile.m_graphics_api.has_value()) m_graphic_api->SetSelection(0); // selecting "" else m_graphic_api->SetSelection(1 + m_game_profile.m_graphics_api.value()); // "", OpenGL, Vulkan m_shader_mul_accuracy->SetSelection((int)m_game_profile.m_accurateShaderMul); //// audio //m_disable_audio->Set3StateValue(GetCheckboxState(m_game_profile.disableAudio)); // controller auto profiles = InputManager::get_profiles(); for (const auto& cb : m_controller_profile) { cb->Clear(); for (const auto& profile : profiles) { cb->Append(to_wxString(profile)); } } for (int i = 0; i < InputManager::kMaxController; ++i) { const bool has_value = m_game_profile.m_controllerProfile[i].has_value(); if (has_value) { const auto& v = m_game_profile.m_controllerProfile[i].value(); m_controller_profile[i]->SetStringSelection(wxString::FromUTF8(v)); } else m_controller_profile[i]->SetSelection(wxNOT_FOUND); } } void GameProfileWindow::SaveProfile() { // update game profile struct m_game_profile.Reset(); // general m_game_profile.m_loadSharedLibraries = m_load_libs->GetValue(); m_game_profile.m_startWithPadView = m_start_with_padview->GetValue(); // cpu switch(m_cpu_mode->GetSelection()) { case 0: m_game_profile.m_cpuMode = CPUMode::SinglecoreInterpreter; break; case 1: m_game_profile.m_cpuMode = CPUMode::SinglecoreRecompiler; break; case 2: m_game_profile.m_cpuMode = CPUMode::MulticoreRecompiler; break; default: m_game_profile.m_cpuMode = CPUMode::Auto; } const wxString thread_quantum = m_thread_quantum->GetStringSelection(); if (!thread_quantum.empty()) { m_game_profile.m_threadQuantum = ConvertString<uint32>(thread_quantum.ToStdString()); m_game_profile.m_threadQuantum = std::min<uint32>(m_game_profile.m_threadQuantum, 536870912); m_game_profile.m_threadQuantum = std::max<uint32>(m_game_profile.m_threadQuantum, 5000); } // gpu m_game_profile.m_accurateShaderMul = (AccurateShaderMulOption)m_shader_mul_accuracy->GetSelection(); if (m_game_profile.m_accurateShaderMul != AccurateShaderMulOption::False && m_game_profile.m_accurateShaderMul != AccurateShaderMulOption::True) m_game_profile.m_accurateShaderMul = AccurateShaderMulOption::True; // force a legal value if (m_graphic_api->GetSelection() == 0) m_game_profile.m_graphics_api = {}; else m_game_profile.m_graphics_api = (GraphicAPI)(m_graphic_api->GetSelection() - 1); // "", OpenGL, Vulkan // controller for (int i = 0; i < 8; ++i) { if(m_controller_profile[i]->GetSelection() == wxNOT_FOUND) { m_game_profile.m_controllerProfile[i].reset(); continue; } const wxString profile_name = m_controller_profile[i]->GetStringSelection(); if (profile_name.empty()) m_game_profile.m_controllerProfile[i].reset(); else m_game_profile.m_controllerProfile[i] = profile_name.ToUTF8(); } // update game profile file m_game_profile.Save(m_title_id); } void GameProfileWindow::SetSliderValue(wxSlider* slider, sint32 new_value) const { wxASSERT(slider); slider->SetValue(new_value); wxCommandEvent slider_event(wxEVT_SLIDER, slider->GetId()); slider_event.SetEventObject(slider); slider_event.SetClientData((void*)IsFrozen()); wxPostEvent(slider->GetEventHandler(), slider_event); }
13,688
C++
.cpp
289
44.550173
232
0.729322
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,972
PairingDialog.cpp
cemu-project_Cemu/src/gui/PairingDialog.cpp
#include "gui/wxgui.h" #include "gui/PairingDialog.h" #if BOOST_OS_WINDOWS #include <bluetoothapis.h> #endif wxDECLARE_EVENT(wxEVT_PROGRESS_PAIR, wxCommandEvent); wxDEFINE_EVENT(wxEVT_PROGRESS_PAIR, wxCommandEvent); PairingDialog::PairingDialog(wxWindow* parent) : wxDialog(parent, wxID_ANY, _("Pairing..."), wxDefaultPosition, wxDefaultSize, wxCAPTION | wxMINIMIZE_BOX | wxSYSTEM_MENU | wxTAB_TRAVERSAL | wxCLOSE_BOX) { auto* sizer = new wxBoxSizer(wxVERTICAL); m_gauge = new wxGauge(this, wxID_ANY, 100, wxDefaultPosition, wxSize(350, 20), wxGA_HORIZONTAL); m_gauge->SetValue(0); sizer->Add(m_gauge, 0, wxALL | wxEXPAND, 5); auto* rows = new wxFlexGridSizer(0, 2, 0, 0); rows->AddGrowableCol(1); m_text = new wxStaticText(this, wxID_ANY, _("Searching for controllers...")); rows->Add(m_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); { auto* right_side = new wxBoxSizer(wxHORIZONTAL); m_cancelButton = new wxButton(this, wxID_ANY, _("Cancel")); m_cancelButton->Bind(wxEVT_BUTTON, &PairingDialog::OnCancelButton, this); right_side->Add(m_cancelButton, 0, wxALL, 5); rows->Add(right_side, 1, wxALIGN_RIGHT, 5); } sizer->Add(rows, 0, wxALL | wxEXPAND, 5); SetSizerAndFit(sizer); Centre(wxBOTH); Bind(wxEVT_CLOSE_WINDOW, &PairingDialog::OnClose, this); Bind(wxEVT_PROGRESS_PAIR, &PairingDialog::OnGaugeUpdate, this); m_thread = std::thread(&PairingDialog::WorkerThread, this); } PairingDialog::~PairingDialog() { Unbind(wxEVT_CLOSE_WINDOW, &PairingDialog::OnClose, this); } void PairingDialog::OnClose(wxCloseEvent& event) { event.Skip(); m_threadShouldQuit = true; if (m_thread.joinable()) m_thread.join(); } void PairingDialog::OnCancelButton(const wxCommandEvent& event) { Close(); } void PairingDialog::OnGaugeUpdate(wxCommandEvent& event) { PairingState state = (PairingState)event.GetInt(); switch (state) { case PairingState::Pairing: { m_text->SetLabel(_("Found controller. Pairing...")); m_gauge->SetValue(50); break; } case PairingState::Finished: { m_text->SetLabel(_("Successfully paired the controller.")); m_gauge->SetValue(100); m_cancelButton->SetLabel(_("Close")); break; } case PairingState::NoBluetoothAvailable: { m_text->SetLabel(_("Failed to find a suitable Bluetooth radio.")); m_gauge->SetValue(0); m_cancelButton->SetLabel(_("Close")); break; } case PairingState::BluetoothFailed: { m_text->SetLabel(_("Failed to search for controllers.")); m_gauge->SetValue(0); m_cancelButton->SetLabel(_("Close")); break; } case PairingState::PairingFailed: { m_text->SetLabel(_("Failed to pair with the found controller.")); m_gauge->SetValue(0); m_cancelButton->SetLabel(_("Close")); break; } case PairingState::BluetoothUnusable: { m_text->SetLabel(_("Please use your system's Bluetooth manager instead.")); m_gauge->SetValue(0); m_cancelButton->SetLabel(_("Close")); break; } default: { break; } } } void PairingDialog::WorkerThread() { const std::wstring wiimoteName = L"Nintendo RVL-CNT-01"; const std::wstring wiiUProControllerName = L"Nintendo RVL-CNT-01-UC"; #if BOOST_OS_WINDOWS const GUID bthHidGuid = {0x00001124,0x0000,0x1000,{0x80,0x00,0x00,0x80,0x5F,0x9B,0x34,0xFB}}; const BLUETOOTH_FIND_RADIO_PARAMS radioFindParams = { .dwSize = sizeof(BLUETOOTH_FIND_RADIO_PARAMS) }; HANDLE radio = INVALID_HANDLE_VALUE; HBLUETOOTH_RADIO_FIND radioFind = BluetoothFindFirstRadio(&radioFindParams, &radio); if (radioFind == nullptr) { UpdateCallback(PairingState::NoBluetoothAvailable); return; } BluetoothFindRadioClose(radioFind); BLUETOOTH_RADIO_INFO radioInfo = { .dwSize = sizeof(BLUETOOTH_RADIO_INFO) }; DWORD result = BluetoothGetRadioInfo(radio, &radioInfo); if (result != ERROR_SUCCESS) { UpdateCallback(PairingState::NoBluetoothAvailable); return; } const BLUETOOTH_DEVICE_SEARCH_PARAMS searchParams = { .dwSize = sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS), .fReturnAuthenticated = FALSE, .fReturnRemembered = FALSE, .fReturnUnknown = TRUE, .fReturnConnected = FALSE, .fIssueInquiry = TRUE, .cTimeoutMultiplier = 5, .hRadio = radio }; BLUETOOTH_DEVICE_INFO info = { .dwSize = sizeof(BLUETOOTH_DEVICE_INFO) }; while (!m_threadShouldQuit) { HBLUETOOTH_DEVICE_FIND deviceFind = BluetoothFindFirstDevice(&searchParams, &info); if (deviceFind == nullptr) { UpdateCallback(PairingState::BluetoothFailed); return; } while (!m_threadShouldQuit) { if (info.szName == wiimoteName || info.szName == wiiUProControllerName) { BluetoothFindDeviceClose(deviceFind); UpdateCallback(PairingState::Pairing); wchar_t passwd[6] = { radioInfo.address.rgBytes[0], radioInfo.address.rgBytes[1], radioInfo.address.rgBytes[2], radioInfo.address.rgBytes[3], radioInfo.address.rgBytes[4], radioInfo.address.rgBytes[5] }; DWORD bthResult = BluetoothAuthenticateDevice(nullptr, radio, &info, passwd, 6); if (bthResult != ERROR_SUCCESS) { UpdateCallback(PairingState::PairingFailed); return; } bthResult = BluetoothSetServiceState(radio, &info, &bthHidGuid, BLUETOOTH_SERVICE_ENABLE); if (bthResult != ERROR_SUCCESS) { UpdateCallback(PairingState::PairingFailed); return; } UpdateCallback(PairingState::Finished); return; } BOOL nextDevResult = BluetoothFindNextDevice(deviceFind, &info); if (nextDevResult == FALSE) { break; } } BluetoothFindDeviceClose(deviceFind); } #else UpdateCallback(PairingState::BluetoothUnusable); #endif } void PairingDialog::UpdateCallback(PairingState state) { auto* event = new wxCommandEvent(wxEVT_PROGRESS_PAIR); event->SetInt((int)state); wxQueueEvent(this, event); }
6,633
C++
.cpp
190
27.610526
219
0.636136
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,973
PadViewFrame.cpp
cemu-project_Cemu/src/gui/PadViewFrame.cpp
#include "gui/wxgui.h" #include "gui/guiWrapper.h" #include "gui/PadViewFrame.h" #include <wx/display.h> #include "config/ActiveSettings.h" #include "Cafe/OS/libs/swkbd/swkbd.h" #include "gui/canvas/OpenGLCanvas.h" #include "gui/canvas/VulkanCanvas.h" #include "config/CemuConfig.h" #include "gui/MainWindow.h" #include "gui/helpers/wxHelpers.h" #include "input/InputManager.h" #if BOOST_OS_LINUX || BOOST_OS_MACOS #include "resource/embedded/resources.h" #endif #include "wxHelper.h" extern WindowInfo g_window_info; #define PAD_MIN_WIDTH 320 #define PAD_MIN_HEIGHT 180 PadViewFrame::PadViewFrame(wxFrame* parent) : wxFrame(nullptr, wxID_ANY, _("GamePad View"), wxDefaultPosition, wxDefaultSize, wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxSYSTEM_MENU | wxCAPTION | wxCLIP_CHILDREN | wxRESIZE_BORDER | wxCLOSE_BOX | wxWANTS_CHARS) { gui_initHandleContextFromWxWidgetsWindow(g_window_info.window_pad, this); SetIcon(wxICON(M_WND_ICON128)); wxWindow::EnableTouchEvents(wxTOUCH_PAN_GESTURES); SetMinClientSize({ PAD_MIN_WIDTH, PAD_MIN_HEIGHT }); SetPosition({ g_window_info.restored_pad_x, g_window_info.restored_pad_y }); if (g_window_info.restored_pad_width >= PAD_MIN_WIDTH && g_window_info.restored_pad_height >= PAD_MIN_HEIGHT) SetClientSize({ g_window_info.restored_pad_width, g_window_info.restored_pad_height }); else SetClientSize(wxSize(854, 480)); if (g_window_info.pad_maximized) Maximize(); Bind(wxEVT_SIZE, &PadViewFrame::OnSizeEvent, this); Bind(wxEVT_DPI_CHANGED, &PadViewFrame::OnDPIChangedEvent, this); Bind(wxEVT_MOVE, &PadViewFrame::OnMoveEvent, this); Bind(wxEVT_MOTION, &PadViewFrame::OnMouseMove, this); Bind(wxEVT_SET_WINDOW_TITLE, &PadViewFrame::OnSetWindowTitle, this); g_window_info.pad_open = true; } PadViewFrame::~PadViewFrame() { g_window_info.pad_open = false; } bool PadViewFrame::Initialize() { const wxSize client_size = GetClientSize(); g_window_info.pad_width = client_size.GetWidth(); g_window_info.pad_height = client_size.GetHeight(); g_window_info.phys_pad_width = ToPhys(client_size.GetWidth()); g_window_info.phys_pad_height = ToPhys(client_size.GetHeight()); return true; } void PadViewFrame::InitializeRenderCanvas() { auto sizer = new wxBoxSizer(wxVERTICAL); { if (ActiveSettings::GetGraphicsAPI() == kVulkan) m_render_canvas = new VulkanCanvas(this, wxSize(854, 480), false); else m_render_canvas = GLCanvas_Create(this, wxSize(854, 480), false); sizer->Add(m_render_canvas, 1, wxEXPAND, 0, nullptr); } SetSizer(sizer); Layout(); m_render_canvas->Bind(wxEVT_KEY_UP, &PadViewFrame::OnKeyUp, this); m_render_canvas->Bind(wxEVT_CHAR, &PadViewFrame::OnChar, this); m_render_canvas->Bind(wxEVT_MOTION, &PadViewFrame::OnMouseMove, this); m_render_canvas->Bind(wxEVT_LEFT_DOWN, &PadViewFrame::OnMouseLeft, this); m_render_canvas->Bind(wxEVT_LEFT_UP, &PadViewFrame::OnMouseLeft, this); m_render_canvas->Bind(wxEVT_RIGHT_DOWN, &PadViewFrame::OnMouseRight, this); m_render_canvas->Bind(wxEVT_RIGHT_UP, &PadViewFrame::OnMouseRight, this); m_render_canvas->Bind(wxEVT_GESTURE_PAN, &PadViewFrame::OnGesturePan, this); m_render_canvas->SetFocus(); SendSizeEvent(); } void PadViewFrame::DestroyCanvas() { if(!m_render_canvas) return; m_render_canvas->Destroy(); m_render_canvas = nullptr; } void PadViewFrame::OnSizeEvent(wxSizeEvent& event) { if (!IsMaximized() && !IsFullScreen()) { g_window_info.restored_pad_width = GetSize().x; g_window_info.restored_pad_height = GetSize().y; } g_window_info.pad_maximized = IsMaximized() && !IsFullScreen(); const wxSize client_size = GetClientSize(); g_window_info.pad_width = client_size.GetWidth(); g_window_info.pad_height = client_size.GetHeight(); g_window_info.phys_pad_width = ToPhys(client_size.GetWidth()); g_window_info.phys_pad_height = ToPhys(client_size.GetHeight()); g_window_info.pad_dpi_scale = GetDPIScaleFactor(); event.Skip(); } void PadViewFrame::OnDPIChangedEvent(wxDPIChangedEvent& event) { event.Skip(); const wxSize client_size = GetClientSize(); g_window_info.pad_width = client_size.GetWidth(); g_window_info.pad_height = client_size.GetHeight(); g_window_info.phys_pad_width = ToPhys(client_size.GetWidth()); g_window_info.phys_pad_height = ToPhys(client_size.GetHeight()); g_window_info.pad_dpi_scale = GetDPIScaleFactor(); } void PadViewFrame::OnMoveEvent(wxMoveEvent& event) { if (!IsMaximized() && !IsFullScreen()) { g_window_info.restored_pad_x = GetPosition().x; g_window_info.restored_pad_y = GetPosition().y; } } void PadViewFrame::OnKeyUp(wxKeyEvent& event) { event.Skip(); if (swkbd_hasKeyboardInputHook()) return; const auto code = event.GetKeyCode(); if (code == WXK_ESCAPE) ShowFullScreen(false); else if (code == WXK_RETURN && event.AltDown() || code == WXK_F11) ShowFullScreen(!IsFullScreen()); } void PadViewFrame::OnGesturePan(wxPanGestureEvent& event) { auto& instance = InputManager::instance(); std::scoped_lock lock(instance.m_pad_touch.m_mutex); auto physPos = ToPhys(event.GetPosition()); instance.m_pad_touch.position = { physPos.x, physPos.y }; instance.m_pad_touch.left_down = event.IsGestureStart() || !event.IsGestureEnd(); if (event.IsGestureStart() || !event.IsGestureEnd()) instance.m_pad_touch.left_down_toggle = true; } void PadViewFrame::OnChar(wxKeyEvent& event) { if (swkbd_hasKeyboardInputHook()) swkbd_keyInput(event.GetUnicodeKey()); event.Skip(); } void PadViewFrame::OnMouseMove(wxMouseEvent& event) { auto& instance = InputManager::instance(); std::scoped_lock lock(instance.m_pad_touch.m_mutex); auto physPos = ToPhys(event.GetPosition()); instance.m_pad_mouse.position = { physPos.x, physPos.y }; event.Skip(); } void PadViewFrame::OnMouseLeft(wxMouseEvent& event) { auto& instance = InputManager::instance(); std::scoped_lock lock(instance.m_pad_mouse.m_mutex); instance.m_pad_mouse.left_down = event.ButtonDown(wxMOUSE_BTN_LEFT); auto physPos = ToPhys(event.GetPosition()); instance.m_pad_mouse.position = { physPos.x, physPos.y }; if (event.ButtonDown(wxMOUSE_BTN_LEFT)) instance.m_pad_mouse.left_down_toggle = true; } void PadViewFrame::OnMouseRight(wxMouseEvent& event) { auto& instance = InputManager::instance(); std::scoped_lock lock(instance.m_pad_mouse.m_mutex); instance.m_pad_mouse.right_down = event.ButtonDown(wxMOUSE_BTN_LEFT); auto physPos = ToPhys(event.GetPosition()); instance.m_pad_mouse.position = { physPos.x, physPos.y }; if (event.ButtonDown(wxMOUSE_BTN_RIGHT)) instance.m_pad_mouse.right_down_toggle = true; } void PadViewFrame::OnSetWindowTitle(wxCommandEvent& event) { this->SetTitle(event.GetString()); } void PadViewFrame::AsyncSetTitle(std::string_view windowTitle) { wxCommandEvent set_title_event(wxEVT_SET_WINDOW_TITLE); set_title_event.SetString(wxHelper::FromUtf8(windowTitle)); QueueEvent(set_title_event.Clone()); }
6,871
C++
.cpp
182
35.747253
209
0.759145
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,974
TitleManager.cpp
cemu-project_Cemu/src/gui/TitleManager.cpp
#include "gui/TitleManager.h" #include "gui/helpers/wxCustomEvents.h" #include "gui/helpers/wxCustomData.h" #include "Cafe/TitleList/GameInfo.h" #include "util/helpers/helpers.h" #include "gui/helpers/wxHelpers.h" #include "gui/wxHelper.h" #include "gui/components/wxTitleManagerList.h" #include "gui/components/wxDownloadManagerList.h" #include "gui/GameUpdateWindow.h" #include "gui/dialogs/SaveImport/SaveTransfer.h" #include <wx/listbase.h> #include <wx/sizer.h> #include <wx/listctrl.h> #include <wx/statline.h> #include <wx/stattext.h> #include <wx/textctrl.h> #include <wx/statbmp.h> #include <wx/panel.h> #include <wx/bmpbuttn.h> #include <wx/choice.h> #include <wx/msgdlg.h> #include <wx/filedlg.h> #include <wx/combobox.h> #include <wx/checkbox.h> #include <pugixml.hpp> #include <zip.h> #include <wx/dirdlg.h> #include <wx/notebook.h> #include "Cafe/IOSU/legacy/iosu_crypto.h" #include "config/ActiveSettings.h" #include "gui/dialogs/SaveImport/SaveImportWindow.h" #include "Cafe/Account/Account.h" #include "Cemu/Tools/DownloadManager/DownloadManager.h" #include "gui/CemuApp.h" #include "Cafe/TitleList/TitleList.h" #include "Cafe/TitleList/SaveList.h" #include "resource/embedded/resources.h" wxDEFINE_EVENT(wxEVT_TITLE_FOUND, wxCommandEvent); wxDEFINE_EVENT(wxEVT_TITLE_SEARCH_COMPLETE, wxCommandEvent); wxDEFINE_EVENT(wxEVT_DL_TITLE_UPDATE, wxCommandEvent); wxDEFINE_EVENT(wxEVT_DL_DISCONNECT_COMPLETE, wxCommandEvent); wxPanel* TitleManager::CreateTitleManagerPage() { auto* panel = new wxPanel(m_notebook); auto* sizer = new wxBoxSizer(wxVERTICAL); { auto* row = new wxFlexGridSizer(0, 4, 0, 0); row->AddGrowableCol(1); row->Add(new wxStaticText(panel, wxID_ANY, _("Filter")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_filter = new wxTextCtrl(panel, wxID_ANY); m_filter->Bind(wxEVT_TEXT, &TitleManager::OnFilterChanged, this); row->Add(m_filter, 1, wxALL | wxEXPAND, 5); const wxImage refresh = wxBITMAP_PNG_FROM_DATA(PNG_REFRESH).ConvertToImage(); m_refresh_button = new wxBitmapButton(panel, wxID_ANY, refresh.Scale(16, 16)); m_refresh_button->Disable(); m_refresh_button->Bind(wxEVT_BUTTON, &TitleManager::OnRefreshButton, this); m_refresh_button->SetToolTip(_("Refresh")); row->Add(m_refresh_button, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); auto* help_button = new wxStaticBitmap(panel, wxID_ANY, wxBITMAP_PNG_FROM_DATA(PNG_HELP)); help_button->SetToolTip(formatWxString(_("The following prefixes are supported:\n{0}\n{1}\n{2}\n{3}\n{4}"), "titleid:", "name:", "type:", "version:", "region:")); row->Add(help_button, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); sizer->Add(row, 0, wxEXPAND, 5); } sizer->Add(new wxStaticLine(panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL), 0, wxEXPAND | wxALL, 5); m_title_list = new wxTitleManagerList(panel); m_title_list->SetSizeHints(800, 600); m_title_list->Bind(wxEVT_LIST_ITEM_SELECTED, &TitleManager::OnTitleSelected, this); sizer->Add(m_title_list, 1, wxALL | wxEXPAND, 5); sizer->Add(new wxStaticLine(panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL), 0, wxEXPAND | wxALL, 5); { auto* row = new wxFlexGridSizer(0, 3, 0, 0); row->AddGrowableCol(2); auto* install_button = new wxButton(panel, wxID_ANY, _("Install title")); install_button->Bind(wxEVT_BUTTON, &TitleManager::OnInstallTitle, this); row->Add(install_button, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); row->Add(new wxStaticLine(panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_VERTICAL), 0, wxEXPAND | wxALL, 5); { m_save_panel = new wxPanel(panel); auto* save_sizer = new wxFlexGridSizer(0, 7, 0, 0); save_sizer->Add(new wxStaticText(m_save_panel, wxID_ANY, _("Account")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_save_account_list = new wxChoice(m_save_panel, wxID_ANY); m_save_account_list->SetMinSize({ 170, -1 }); m_save_account_list->Bind(wxEVT_CHOICE, &TitleManager::OnSaveAccountSelected, this); save_sizer->Add(m_save_account_list, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); auto* save_open = new wxButton(m_save_panel, wxID_ANY, _("Open directory")); save_open->Bind(wxEVT_BUTTON, &TitleManager::OnSaveOpenDirectory, this); save_open->SetToolTip(_("Open the directory of the save entry")); save_open->Disable(); save_sizer->Add(save_open, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); auto* save_transfer = new wxButton(m_save_panel, wxID_ANY, _("Transfer")); save_transfer->Bind(wxEVT_BUTTON, &TitleManager::OnSaveTransfer, this); save_transfer->SetToolTip(_("Transfers the save entry to another persistent account id")); save_transfer->Disable(); save_sizer->Add(save_transfer, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); auto* save_delete = new wxButton(m_save_panel, wxID_ANY, _("Delete")); save_delete->Bind(wxEVT_BUTTON, &TitleManager::OnSaveDelete, this); save_delete->SetToolTip(_("Permanently delete the save entry")); save_delete->Disable(); save_sizer->Add(save_delete, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_save_import = new wxButton(m_save_panel, wxID_ANY, _("Import")); m_save_import->Bind(wxEVT_BUTTON, &TitleManager::OnSaveImport, this); m_save_import->SetToolTip(_("Imports a zipped save entry")); save_sizer->Add(m_save_import, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxTOP | wxBOTTOM, 5); auto* export_bttn = new wxButton(m_save_panel, wxID_ANY, _("Export")); export_bttn->Bind(wxEVT_BUTTON, &TitleManager::OnSaveExport, this); export_bttn->SetToolTip(_("Exports the selected save entry as zip file")); export_bttn->Disable(); save_sizer->Add(export_bttn, 0, wxALIGN_CENTER_VERTICAL | wxRIGHT | wxTOP | wxBOTTOM, 5); m_save_panel->SetSizerAndFit(save_sizer); row->Add(m_save_panel, 1, wxRESERVE_SPACE_EVEN_IF_HIDDEN | wxALIGN_CENTER_VERTICAL, 0); m_save_panel->Hide(); // hide by default } sizer->Add(row, 0, wxEXPAND, 5); } panel->SetSizerAndFit(sizer); return panel; } wxPanel* TitleManager::CreateDownloadManagerPage() { auto* panel = new wxPanel(m_notebook); auto* sizer = new wxBoxSizer(wxVERTICAL); { auto* row = new wxBoxSizer(wxHORIZONTAL); #if DOWNLOADMGR_HAS_ACCOUNT_DROPDOWN m_account = new wxChoice(panel, wxID_ANY); m_account->SetMinSize({ 250,-1 }); auto accounts = Account::GetAccounts(); if (!accounts.empty()) { const auto id = GetConfig().account.m_persistent_id.GetValue(); for (const auto& a : accounts) { m_account->Append(a.ToString(), (void*)static_cast<uintptr_t>(a.GetPersistentId())); if(a.GetPersistentId() == id) { m_account->SetSelection(m_account->GetCount() - 1); } } } row->Add(m_account, 0, wxALL, 5); #endif m_connect = new wxButton(panel, wxID_ANY, _("Connect")); m_connect->Bind(wxEVT_BUTTON, &TitleManager::OnConnect, this); row->Add(m_connect, 0, wxALL, 5); sizer->Add(row, 0, wxEXPAND, 5); } #if DOWNLOADMGR_HAS_ACCOUNT_DROPDOWN m_status_text = new wxStaticText(panel, wxID_ANY, _("Select an account and press Connect")); #else if(!NCrypto::HasDataForConsoleCert()) { m_status_text = new wxStaticText(panel, wxID_ANY, _("Valid online files are required to download eShop titles. For more information, go to the Account tab in the General Settings.")); m_connect->Enable(false); } else m_status_text = new wxStaticText(panel, wxID_ANY, _("Click on Connect to load the list of downloadable titles")); #endif this->Bind(wxEVT_SET_TEXT, &TitleManager::OnSetStatusText, this); sizer->Add(m_status_text, 0, wxALL, 5); sizer->Add(new wxStaticLine(panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL), 0, wxEXPAND | wxALL, 5); { auto* row = new wxFlexGridSizer(0, 3, 0, 0); m_show_titles = new wxCheckBox(panel, wxID_ANY, _("Show available titles")); m_show_titles->SetValue(true); m_show_titles->Enable(false); row->Add(m_show_titles, 0, wxALL, 5); m_show_titles->Bind(wxEVT_CHECKBOX, &TitleManager::OnDlFilterCheckbox, this); m_show_updates = new wxCheckBox(panel, wxID_ANY, _("Show available updates")); m_show_updates->SetValue(true); m_show_updates->Enable(false); row->Add(m_show_updates, 0, wxALL, 5); m_show_updates->Bind(wxEVT_CHECKBOX, &TitleManager::OnDlFilterCheckbox, this); m_show_installed = new wxCheckBox(panel, wxID_ANY, _("Show installed")); m_show_installed->SetValue(true); m_show_installed->Enable(false); row->Add(m_show_installed, 0, wxALL, 5); m_show_installed->Bind(wxEVT_CHECKBOX, &TitleManager::OnDlFilterCheckbox, this); sizer->Add(row, 0, wxEXPAND, 5); } m_download_list = new wxDownloadManagerList(panel); m_download_list->SetSizeHints(800, 600); m_download_list->Bind(wxEVT_LIST_ITEM_SELECTED, &TitleManager::OnTitleSelected, this); sizer->Add(m_download_list, 1, wxALL | wxEXPAND, 5); panel->SetSizerAndFit(sizer); return panel; } TitleManager::TitleManager(wxWindow* parent, TitleManagerPage default_page) : wxFrame(parent, wxID_ANY, _("Title Manager"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE | wxTAB_TRAVERSAL) { SetIcon(wxICON(X_BOX)); auto* sizer = new wxBoxSizer(wxVERTICAL); m_notebook = new wxNotebook(this, wxID_ANY); m_notebook->AddPage(CreateTitleManagerPage(), _("Title Manager"), default_page == TitleManagerPage::TitleManager); m_notebook->AddPage(CreateDownloadManagerPage(), _("Download Manager"), default_page == TitleManagerPage::DownloadManager); sizer->Add(m_notebook, 1, wxEXPAND); m_status_bar = CreateStatusBar(2, wxSTB_SIZEGRIP); m_status_bar->SetStatusText(_("Searching for titles...")); this->SetSizerAndFit(sizer); this->Centre(wxBOTH); this->Bind(wxEVT_SET_STATUS_BAR_TEXT, &TitleManager::OnSetStatusBarText, this); this->Bind(wxEVT_TITLE_FOUND, &TitleManager::OnTitleFound, this); this->Bind(wxEVT_TITLE_SEARCH_COMPLETE, &TitleManager::OnTitleSearchComplete, this); this->Bind(wxEVT_DL_TITLE_UPDATE, &TitleManager::OnDownloadableTitleUpdate, this); this->Bind(wxEVT_DL_DISCONNECT_COMPLETE, &TitleManager::OnDisconnect, this); // TODO typing on title list should change filter text and filter! // if download manager is already active then restore state DownloadManager* dlMgr = DownloadManager::GetInstance(false); if (dlMgr && dlMgr->IsConnected()) { dlMgr->setUserData(this); dlMgr->registerCallbacks( TitleManager::Callback_ConnectStatusUpdate, TitleManager::Callback_AddDownloadableTitle, TitleManager::Callback_RemoveDownloadableTitle); SetConnected(true); } m_callbackId = CafeTitleList::RegisterCallback([](CafeTitleListCallbackEvent* evt, void* ctx) { ((TitleManager*)ctx)->HandleTitleListCallback(evt); }, this); } TitleManager::~TitleManager() { CafeTitleList::UnregisterCallback(m_callbackId); // unregister callbacks for download manager DownloadManager* dlMgr = DownloadManager::GetInstance(false); if (dlMgr) { dlMgr->setUserData(nullptr); dlMgr->registerCallbacks( nullptr, nullptr, nullptr); // if download manager is still downloading / installing then show a warning if (dlMgr->hasActiveDownloads()) { static bool s_showedBGDownloadWarning = false; if (!s_showedBGDownloadWarning) { wxMessageBox(_("Currently active downloads will continue in the background."), _("Information"), wxOK | wxCENTRE, this); s_showedBGDownloadWarning = true; } } } m_running = false; } void TitleManager::SetFocusAndTab(TitleManagerPage page) { m_notebook->SetSelection((int)page); this->SetFocus(); } void TitleManager::SetDownloadStatusText(const wxString& text) { auto* evt = new wxCommandEvent(wxEVT_SET_TEXT); evt->SetEventObject(m_status_text); evt->SetString(text); wxQueueEvent(this, evt); } void TitleManager::HandleTitleListCallback(CafeTitleListCallbackEvent* evt) { if (evt->eventType == CafeTitleListCallbackEvent::TYPE::SCAN_FINISHED) { auto* evt = new wxCommandEvent(wxEVT_TITLE_SEARCH_COMPLETE); wxQueueEvent(this, evt); } } void TitleManager::OnTitleFound(wxCommandEvent& event) { auto* obj = dynamic_cast<wxTitleManagerList::TitleEntryData_t*>(event.GetClientObject()); wxASSERT(obj); m_title_list->AddTitle(obj); } void TitleManager::OnTitleSearchComplete(wxCommandEvent& event) { m_isScanning = false; if (m_connectRequested) { InitiateConnect(); m_connectRequested = false; } // update status bar text m_title_list->SortEntries(-1); m_status_bar->SetStatusText(formatWxString(_("Found {0} games, {1} updates, {2} DLCs and {3} save entries"), m_title_list->GetCountByType(wxTitleManagerList::EntryType::Base) + m_title_list->GetCountByType(wxTitleManagerList::EntryType::System), m_title_list->GetCountByType(wxTitleManagerList::EntryType::Update), m_title_list->GetCountByType(wxTitleManagerList::EntryType::Dlc), m_title_list->GetCountByType(wxTitleManagerList::EntryType::Save) )); // re-filter if any filter is set const auto filter = m_filter->GetValue(); if (!filter.IsEmpty()) m_title_list->Filter(m_filter->GetValue()); m_title_list->AutosizeColumns(); m_refresh_button->Enable(); } void TitleManager::OnSetStatusBarText(wxSetStatusBarTextEvent& event) { m_status_bar->SetStatusText(_(event.GetText()), event.GetNumber()); } void TitleManager::OnFilterChanged(wxCommandEvent& event) { event.Skip(); m_title_list->Filter(m_filter->GetValue()); } void TitleManager::OnRefreshButton(wxCommandEvent& event) { m_refresh_button->Disable(); m_isScanning = true; // m_title_list->ClearItems(); -> Dont clear. Refresh() triggers incremental updates via notifications m_status_bar->SetStatusText(_("Searching for titles...")); CafeTitleList::Refresh(); } void TitleManager::OnInstallTitle(wxCommandEvent& event) { wxFileDialog openFileDialog(this, _("Select title to install"), "", "", "meta.xml|meta.xml", wxFD_OPEN | wxFD_FILE_MUST_EXIST); if (openFileDialog.ShowModal() == wxID_CANCEL || openFileDialog.GetPath().IsEmpty()) return; fs::path filePath(openFileDialog.GetPath().wc_str()); try { filePath = filePath.parent_path(); filePath = filePath.parent_path(); GameUpdateWindow frame(*this, filePath); const int updateResult = frame.ShowModal(); if (updateResult == wxID_OK) { CafeTitleList::AddTitleFromPath(frame.GetTargetPath()); } else { if (frame.GetExceptionMessage().empty()) wxMessageBox(_("Update installation has been canceled!")); else { throw std::runtime_error(frame.GetExceptionMessage()); } } } catch (const AbortException&) { // ignored } catch (const std::exception& ex) { wxMessageBox(ex.what(), _("Update error")); } } static void PopulateSavePersistentIds(wxTitleManagerList::TitleEntry& entry) { if (!entry.persistent_ids.empty()) return; cemu_assert(entry.type == wxTitleManagerList::EntryType::Save); SaveInfo saveInfo = CafeSaveList::GetSaveByTitleId(entry.title_id); if (!saveInfo.IsValid()) return; fs::path savePath = saveInfo.GetPath(); savePath /= "user"; std::error_code ec; for (auto it : fs::directory_iterator(savePath, ec)) { if(!it.is_directory(ec)) continue; if(fs::is_empty(it.path())) continue; std::string dirName = it.path().filename().string(); if(!std::regex_match(dirName, std::regex("[0-9a-fA-F]{8}"))) continue; entry.persistent_ids.emplace_back(ConvertString<uint32>(dirName, 16)); } } void TitleManager::OnTitleSelected(wxListEvent& event) { event.Skip(); const auto entry = m_title_list->GetSelectedTitleEntry(); if(entry.has_value() && entry->type == wxTitleManagerList::EntryType::Save) { m_save_panel->Show(); m_save_account_list->Clear(); PopulateSavePersistentIds(*entry); // an account must be selected before any of the control buttons can be used for(auto&& v : m_save_panel->GetChildren()) { if (dynamic_cast<wxButton*>(v) && v->GetId() != m_save_import->GetId()) // import is always enabled v->Disable(); } const auto& accounts = Account::GetAccounts(); for (const auto& id : entry->persistent_ids) { const auto it = std::find_if(accounts.cbegin(), accounts.cend(), [id](const auto& acc) { return acc.GetPersistentId() == id; }); if(it != accounts.cend()) { m_save_account_list->Append(fmt::format("{:x} ({})", id, boost::nowide::narrow(it->GetMiiName().data(), it->GetMiiName().size())), (void*)(uintptr_t)id); } else m_save_account_list->Append(fmt::format("{:x}", id), (void*)(uintptr_t)id); } } else { m_save_panel->Hide(); } } void TitleManager::OnSaveOpenDirectory(wxCommandEvent& event) { const auto selection= m_save_account_list->GetSelection(); if (selection == wxNOT_FOUND) return; const auto entry = m_title_list->GetSelectedTitleEntry(); if (!entry.has_value()) return; const auto persistent_id = (uint32)(uintptr_t)m_save_account_list->GetClientData(selection); const fs::path target = ActiveSettings::GetMlcPath("usr/save/{:08x}/{:08x}/user/{:08x}", (uint32)(entry->title_id >> 32), (uint32)(entry->title_id & 0xFFFFFFFF), persistent_id); if (!fs::exists(target) || !fs::is_directory(target)) return; wxLaunchDefaultBrowser(wxHelper::FromUtf8(fmt::format("file:{}", _pathToUtf8(target)))); } void TitleManager::OnSaveDelete(wxCommandEvent& event) { const auto selection_index = m_save_account_list->GetSelection(); if (selection_index == wxNOT_FOUND) return; const auto selection = m_save_account_list->GetStringSelection(); if (selection.IsEmpty()) return; const auto msg = formatWxString(_("Are you really sure that you want to delete the save entry for {}"), selection); const auto result = wxMessageBox(msg, _("Warning"), wxYES_NO | wxCENTRE | wxICON_EXCLAMATION, this); if (result == wxNO) return; auto entry = m_title_list->GetSelectedTitleEntry(); if (!entry.has_value()) return; const auto persistent_id = (uint32)(uintptr_t)m_save_account_list->GetClientData(selection_index); const fs::path target = ActiveSettings::GetMlcPath("usr/save/{:08x}/{:08x}/user/{:08x}", (uint32)(entry->title_id >> 32), (uint32)(entry->title_id & 0xFFFFFFFF), persistent_id); if (!fs::exists(target) || !fs::is_directory(target)) return; // edit meta saveinfo.xml bool meta_file_edited = false; const fs::path saveinfo = ActiveSettings::GetMlcPath("usr/save/{:08x}/{:08x}/meta/saveinfo.xml", (uint32)(entry->title_id >> 32), (uint32)(entry->title_id & 0xFFFFFFFF)); if (fs::exists(saveinfo) || fs::is_regular_file(saveinfo)) { pugi::xml_document doc; if (doc.load_file(saveinfo.c_str())) { auto info_node = doc.child("info"); if(info_node) { auto persistend_id_string = fmt::format(L"{:08x}", persistent_id); const auto delete_entry = info_node.find_child([&persistend_id_string](const pugi::xml_node& node) { return boost::iequals(node.attribute("persistentId").as_string(), persistend_id_string); }); if (delete_entry) { info_node.remove_child(delete_entry); meta_file_edited = doc.save_file(saveinfo.c_str()); } } } } if (!meta_file_edited) cemuLog_log(LogType::Force, "TitleManager::OnSaveDelete: couldn't delete save entry in saveinfo.xml: {}", _pathToUtf8(saveinfo)); // remove from title entry auto& persistent_ids = entry->persistent_ids; persistent_ids.erase(std::remove(persistent_ids.begin(), persistent_ids.end(), persistent_id), persistent_ids.end()); std::error_code ec; fs::remove_all(target, ec); if (ec) { const auto error_msg = formatWxString(_("Error when trying to delete the save directory:\n{}"), GetSystemErrorMessage(ec)); wxMessageBox(error_msg, _("Error"), wxOK | wxCENTRE, this); return; } m_save_account_list->Delete(selection_index); } void TitleManager::OnSaveTransfer(wxCommandEvent& event) { const auto selection_index = m_save_account_list->GetSelection(); if (selection_index == wxNOT_FOUND) return; const auto selection = m_save_account_list->GetStringSelection(); if (selection.IsEmpty()) return; auto entry = m_title_list->GetSelectedTitleEntry(); if (!entry.has_value()) return; const auto persistent_id = (uint32)(uintptr_t)m_save_account_list->GetClientData(selection_index); SaveTransfer transfer(this, entry->title_id, selection, persistent_id); if (transfer.ShowModal() == wxCANCEL) return; // remove old id entry auto& persistent_ids = entry->persistent_ids; persistent_ids.erase(std::remove(persistent_ids.begin(), persistent_ids.end(), persistent_id), persistent_ids.end()); // add new id if not added yet const auto new_id = transfer.GetTargetPersistentId(); if (new_id != 0 && std::find(persistent_ids.cbegin(), persistent_ids.cend(), new_id) == persistent_ids.cend()) { persistent_ids.emplace_back(new_id); const auto& account = Account::GetAccount(new_id); if(account.GetPersistentId() == new_id) m_save_account_list->Append(fmt::format("{:x} ({})", new_id, boost::nowide::narrow(account.GetMiiName().data(), account.GetMiiName().size())), (void*)(uintptr_t)new_id); else m_save_account_list->Append(fmt::format("{:x}", new_id), (void*)(uintptr_t)new_id); } m_save_account_list->Delete(selection_index); } void TitleManager::OnSaveAccountSelected(wxCommandEvent& event) { event.Skip(); for (auto&& v : m_save_panel->GetChildren()) { if (!v->IsEnabled()) v->Enable(); } } void TitleManager::OnSaveExport(wxCommandEvent& event) { const auto selection_index = m_save_account_list->GetSelection(); if (selection_index == wxNOT_FOUND) return; const auto selection = m_save_account_list->GetStringSelection(); if (selection.IsEmpty()) return; const auto entry = m_title_list->GetSelectedTitleEntry(); if (!entry.has_value()) return; const auto persistent_id = (uint32)(uintptr_t)m_save_account_list->GetClientData(selection_index); wxFileDialog path_dialog(this, _("Select a target file to export the save entry"), entry->path.string(), wxEmptyString, fmt::format("{}|*.zip", _("Exported save entry (*.zip)")), wxFD_SAVE | wxFD_OVERWRITE_PROMPT); if (path_dialog.ShowModal() != wxID_OK || path_dialog.GetPath().IsEmpty()) return; const auto path = path_dialog.GetPath(); int ze; auto* zip = zip_open(path.ToUTF8().data(), ZIP_CREATE | ZIP_TRUNCATE, &ze); if (!zip) { zip_error_t ziperror; zip_error_init_with_code(&ziperror, ze); const auto error_msg = formatWxString(_("Error when creating the zip for the save entry:\n{}"), zip_error_strerror(&ziperror)); wxMessageBox(error_msg, _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } // grab all files to zip const auto savedir = fs::path(entry->path).append(fmt::format("user/{:08x}", persistent_id)); const auto savedir_str = savedir.generic_u8string(); for(const auto& it : fs::recursive_directory_iterator(savedir)) { if (it.path() == "." || it.path() == "..") continue; const auto entryname = it.path().generic_u8string(); if(fs::is_directory(it.path())) { if(zip_dir_add(zip, (const char*)entryname.substr(savedir_str.size() + 1).c_str(), ZIP_FL_ENC_UTF_8) < 0 ) { const auto error_msg = formatWxString(_("Error when trying to add a directory to the zip:\n{}"), zip_strerror(zip)); wxMessageBox(error_msg, _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); } } else { auto* source = zip_source_file(zip, (const char*)entryname.c_str(), 0, 0); if(!source) { const auto error_msg = formatWxString(_("Error when trying to add a file to the zip:\n{}"), zip_strerror(zip)); wxMessageBox(error_msg, _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); } if (zip_file_add(zip, (const char*)entryname.substr(savedir_str.size() + 1).c_str(), source, ZIP_FL_ENC_UTF_8) < 0) { const auto error_msg = formatWxString(_("Error when trying to add a file to the zip:\n{}"), zip_strerror(zip)); wxMessageBox(error_msg, _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); zip_source_free(source); } } } // add own metainfo like file and store title id for verification later std::string metacontent = fmt::format("titleId = {:#016x}", entry->title_id); auto* metabuff = zip_source_buffer(zip, metacontent.data(), metacontent.size(), 0); if(zip_file_add(zip, "cemu_meta", metabuff, ZIP_FL_ENC_UTF_8) < 0) { const auto error_msg = formatWxString(_("Error when trying to add cemu_meta file to the zip:\n{}"), zip_strerror(zip)); wxMessageBox(error_msg, _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); zip_source_free(metabuff); } zip_close(zip); } void TitleManager::OnSaveImport(wxCommandEvent& event) { auto entry = m_title_list->GetSelectedTitleEntry(); if (!entry.has_value()) return; SaveImportWindow save_import(this, entry->title_id); if (save_import.ShowModal() == wxCANCEL) return; // add new id if not added yet auto& persistent_ids = entry->persistent_ids; const auto new_id = save_import.GetTargetPersistentId(); if (new_id != 0 && std::find(persistent_ids.cbegin(), persistent_ids.cend(), new_id) == persistent_ids.cend()) { persistent_ids.emplace_back(new_id); const auto& account = Account::GetAccount(new_id); if (account.GetPersistentId() == new_id) m_save_account_list->Append(fmt::format("{:x} ({})", new_id, boost::nowide::narrow(account.GetMiiName().data(), account.GetMiiName().size())), (void*)(uintptr_t)new_id); else m_save_account_list->Append(fmt::format("{:x}", new_id), (void*)(uintptr_t)new_id); } } void TitleManager::InitiateConnect() { // init connection to download manager if queued #if DOWNLOADMGR_HAS_ACCOUNT_DROPDOWN uint32 persistentId = (uint32)(uintptr_t)m_account->GetClientData(m_account->GetSelection()); auto& account = Account::GetAccount(persistentId); #endif DownloadManager* dlMgr = DownloadManager::GetInstance(); dlMgr->reset(); m_download_list->SetCurrentDownloadMgr(dlMgr); std::string deviceCertBase64 = NCrypto::CertECC::GetDeviceCertificate().encodeToBase64(); if (!NCrypto::SEEPROM_IsPresent()) { SetDownloadStatusText(_("Dumped online files not found")); return; } SetDownloadStatusText(_("Connecting...")); // begin async connect dlMgr->setUserData(this); dlMgr->registerCallbacks( TitleManager::Callback_ConnectStatusUpdate, TitleManager::Callback_AddDownloadableTitle, TitleManager::Callback_RemoveDownloadableTitle); std::string accountName; std::array<uint8, 32> accountPassword; std::string accountCountry; #if DOWNLOADMGR_HAS_ACCOUNT_DROPDOWN accountName = account.GetAccountId(); accountPassword = account.GetAccountPasswordCache(); accountCountry.assign(NCrypto::GetCountryAsString(account.GetCountry())); #endif dlMgr->connect(accountName, accountPassword, NCrypto::SEEPROM_GetRegion(), accountCountry, NCrypto::GetDeviceId(), NCrypto::GetSerial(), deviceCertBase64); } void TitleManager::OnConnect(wxCommandEvent& event) { if (!m_isScanning) { InitiateConnect(); SetConnected(true); } else { SetDownloadStatusText(_("Getting installed title information...")); SetConnected(true); m_connectRequested = true; } } void TitleManager::OnDlFilterCheckbox(wxCommandEvent& event) { m_download_list->Filter2(m_show_titles->GetValue(), m_show_updates->GetValue(), m_show_installed->GetValue()); m_download_list->SortEntries(); } void TitleManager::OnSetStatusText(wxCommandEvent& event) { auto* text = wxDynamicCast(event.GetEventObject(), wxControl); wxASSERT(text); text->SetLabel(event.GetString()); } void TitleManager::OnDownloadableTitleUpdate(wxCommandEvent& event) { auto* obj = dynamic_cast<wxDownloadManagerList::TitleEntryData_t*>(event.GetClientObject()); auto entry = obj->GetData(); m_download_list->AddOrUpdateTitle(obj); } void TitleManager::OnDisconnect(wxCommandEvent& event) { SetConnected(false); } void TitleManager::SetConnected(bool state) { #if DOWNLOADMGR_HAS_ACCOUNT_DROPDOWN m_account->Enable(!state); #endif m_connect->Enable(!state); m_show_titles->Enable(state); m_show_updates->Enable(state); m_show_installed->Enable(state); m_download_list->Enable(state); } void TitleManager::Callback_ConnectStatusUpdate(std::string statusText, DLMGR_STATUS_CODE statusCode) { TitleManager* titleManager = static_cast<TitleManager*>(DownloadManager::GetInstance()->getUserData()); titleManager->SetDownloadStatusText(wxString::FromUTF8(statusText)); if (statusCode == DLMGR_STATUS_CODE::FAILED) { auto* evt = new wxCommandEvent(wxEVT_DL_DISCONNECT_COMPLETE); wxQueueEvent(titleManager, evt); // this will set SetConnected() to false return; } } void TitleManager::Callback_AddDownloadableTitle(const DlMgrTitleReport& titleInfo) { TitleManager* titleManager = static_cast<TitleManager*>(DownloadManager::GetInstance()->getUserData()); wxDownloadManagerList::EntryType type = wxDownloadManagerList::EntryType::Base; if (((titleInfo.titleId >> 32) & 0xF) == 0xE) type = wxDownloadManagerList::EntryType::Update; else if (((titleInfo.titleId >> 32) & 0xF) == 0xC) type = wxDownloadManagerList::EntryType::DLC; if (titleInfo.status == DlMgrTitleReport::STATUS::INSTALLABLE || titleInfo.status == DlMgrTitleReport::STATUS::INSTALLABLE_UNFINISHED || titleInfo.status == DlMgrTitleReport::STATUS::INSTALLABLE_UPDATE) { // installable title wxDownloadManagerList::TitleEntry titleEntry(type, false, titleInfo.titleId, titleInfo.version, titleInfo.isPaused); titleEntry.name = wxString::FromUTF8(titleInfo.name); titleEntry.status = wxDownloadManagerList::TitleDownloadStatus::Available; titleEntry.progress = 0; if (titleInfo.status == DlMgrTitleReport::STATUS::INSTALLABLE_UNFINISHED) titleEntry.progress = 1; if (titleInfo.status == DlMgrTitleReport::STATUS::INSTALLABLE_UPDATE) titleEntry.progress = 2; auto* evt = new wxCommandEvent(wxEVT_DL_TITLE_UPDATE); evt->SetClientObject(new wxCustomData(titleEntry)); wxQueueEvent(titleManager, evt); } else { // package wxDownloadManagerList::TitleEntry titleEntry(type, true, titleInfo.titleId, titleInfo.version, titleInfo.isPaused); titleEntry.name = wxString::FromUTF8(titleInfo.name); titleEntry.progress = titleInfo.progress; titleEntry.progressMax = titleInfo.progressMax; switch (titleInfo.status) { case DlMgrTitleReport::STATUS::INITIALIZING: titleEntry.status = wxDownloadManagerList::TitleDownloadStatus::Initializing; break; case DlMgrTitleReport::STATUS::QUEUED: titleEntry.status = wxDownloadManagerList::TitleDownloadStatus::Queued; break; case DlMgrTitleReport::STATUS::CHECKING: titleEntry.status = wxDownloadManagerList::TitleDownloadStatus::Checking; break; case DlMgrTitleReport::STATUS::DOWNLOADING: titleEntry.status = wxDownloadManagerList::TitleDownloadStatus::Downloading; titleEntry.progress = titleInfo.progress; break; case DlMgrTitleReport::STATUS::VERIFYING: titleEntry.status = wxDownloadManagerList::TitleDownloadStatus::Verifying; break; case DlMgrTitleReport::STATUS::INSTALLING: titleEntry.status = wxDownloadManagerList::TitleDownloadStatus::Installing; break; case DlMgrTitleReport::STATUS::INSTALLED: titleEntry.status = wxDownloadManagerList::TitleDownloadStatus::Installed; break; case DlMgrTitleReport::STATUS::HAS_ERROR: titleEntry.status = wxDownloadManagerList::TitleDownloadStatus::Error; titleEntry.errorMsg = titleInfo.errorMsg; break; default: titleEntry.status = wxDownloadManagerList::TitleDownloadStatus::None; break; } auto* evt = new wxCommandEvent(wxEVT_DL_TITLE_UPDATE); evt->SetClientObject(new wxCustomData(titleEntry)); wxQueueEvent(titleManager, evt); } } void TitleManager::Callback_RemoveDownloadableTitle(uint64 titleId, uint16 version) { TitleManager* titleManager = static_cast<TitleManager*>(DownloadManager::GetInstance()->getUserData()); assert_dbg(); }
31,614
C++
.cpp
772
38.264249
203
0.737441
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,975
DownloadGraphicPacksWindow.cpp
cemu-project_Cemu/src/gui/DownloadGraphicPacksWindow.cpp
#include "gui/wxgui.h" #include "gui/DownloadGraphicPacksWindow.h" #include <filesystem> #include <curl/curl.h> #include <zip.h> #include <rapidjson/document.h> #include <boost/algorithm/string.hpp> #include "config/ActiveSettings.h" #include "Common/FileStream.h" #include "Cafe/CafeSystem.h" struct DownloadGraphicPacksWindow::curlDownloadFileState_t { std::vector<uint8> fileData; double progress; }; size_t DownloadGraphicPacksWindow::curlDownloadFile_writeData(void *ptr, size_t size, size_t nmemb, curlDownloadFileState_t* downloadState) { const size_t writeSize = size * nmemb; const size_t currentSize = downloadState->fileData.size(); const size_t newSize = currentSize + writeSize; downloadState->fileData.resize(newSize); memcpy(downloadState->fileData.data() + currentSize, ptr, writeSize); return writeSize; } int DownloadGraphicPacksWindow::progress_callback(curlDownloadFileState_t* downloadState, double dltotal, double dlnow, double ultotal, double ulnow) { if (dltotal > 1.0) downloadState->progress = dlnow / dltotal; else downloadState->progress = 0.0; return 0; } bool DownloadGraphicPacksWindow::curlDownloadFile(const char *url, curlDownloadFileState_t* downloadState) { CURL* curl = curl_easy_init(); if (curl == nullptr) return false; downloadState->progress = 0.0; curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlDownloadFile_writeData); curl_easy_setopt(curl, CURLOPT_WRITEDATA, downloadState); curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_callback); curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, downloadState); curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, true); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0); curl_easy_setopt(curl, CURLOPT_USERAGENT, BUILD_VERSION_WITH_NAME_STRING); downloadState->fileData.resize(0); const CURLcode res = curl_easy_perform(curl); curl_easy_cleanup(curl); return res == CURLE_OK; } // returns true if the version matches bool checkGraphicPackDownloadedVersion(const char* nameVersion, bool& hasVersionFile) { hasVersionFile = false; const auto path = ActiveSettings::GetUserDataPath("graphicPacks/downloadedGraphicPacks/version.txt"); std::unique_ptr<FileStream> file(FileStream::openFile2(path)); std::string versionInFile; if (file && file->readLine(versionInFile)) { return boost::iequals(versionInFile, nameVersion); } return false; } void createGraphicPackDownloadedVersionFile(const char* nameVersion) { const auto path = ActiveSettings::GetUserDataPath("graphicPacks/downloadedGraphicPacks/version.txt"); std::unique_ptr<FileStream> file(FileStream::createFile2(path)); if (file) file->writeString(nameVersion); else { cemuLog_log(LogType::Force, "Failed to write graphic pack version.txt"); } } void deleteDownloadedGraphicPacks() { const auto path = ActiveSettings::GetUserDataPath("graphicPacks/downloadedGraphicPacks"); std::error_code er; if (!fs::exists(path, er)) return; try { for (auto& p : fs::directory_iterator(path)) { fs::remove_all(p.path(), er); } } catch (std::filesystem::filesystem_error& e) { cemuLog_log(LogType::Force, "Error in deleteDownloadedGraphicPacks():"); cemuLog_log(LogType::Force, e.what()); } } void DownloadGraphicPacksWindow::UpdateThread() { // get github url std::string githubAPIUrl; curlDownloadFileState_t tempDownloadState; std::string queryUrl("https://cemu.info/api2/query_graphicpack_url.php?"); char temp[64]; sprintf(temp, "version=%d.%d.%d", EMULATOR_VERSION_MAJOR, EMULATOR_VERSION_MINOR, EMULATOR_VERSION_PATCH); queryUrl.append(temp); queryUrl.append("&"); sprintf(temp, "t=%u", (uint32)std::chrono::seconds(std::time(NULL)).count()); // add a dynamic part to the url to bypass overly aggressive caching (like some proxies do) queryUrl.append(temp); if (curlDownloadFile(queryUrl.c_str(), &tempDownloadState) && boost::starts_with((const char*)tempDownloadState.fileData.data(), "http")) { // convert downloaded data to url string githubAPIUrl.assign(tempDownloadState.fileData.cbegin(), tempDownloadState.fileData.cend()); } else { // cemu api request failed, use hardcoded github url cemuLog_log(LogType::Force, "Graphic pack update request failed or returned invalid URL. Using default repository URL instead"); githubAPIUrl = "https://api.github.com/repos/cemu-project/cemu_graphic_packs/releases/latest"; } // github API request if (curlDownloadFile(githubAPIUrl.c_str(), &tempDownloadState) == false) { wxMessageBox( _("Error"), _(L"Failed to connect to server"), wxOK | wxCENTRE | wxICON_ERROR, this); m_threadState = ThreadError; return; } // parse json result rapidjson::Document d; d.Parse((const char*)tempDownloadState.fileData.data(), tempDownloadState.fileData.size()); if (d.HasParseError()) { m_threadState = ThreadError; return; } auto& jsonName = d["name"]; if (jsonName.IsString() == false) { m_threadState = ThreadError; return; } const char* assetName = jsonName.GetString(); // name includes version if( d.IsObject() == false) { m_threadState = ThreadError; return; } auto& jsonAssets = d["assets"]; if (jsonAssets.IsArray() == false || jsonAssets.GetArray().Size() == 0) { m_threadState = ThreadError; return; } auto& jsonAsset0 = jsonAssets.GetArray()[0]; if (jsonAsset0.IsObject() == false) { m_threadState = ThreadError; return; } auto& jsonDownloadUrl = jsonAsset0["browser_download_url"]; if (jsonDownloadUrl.IsString() == false) { m_threadState = ThreadError; return; } const char* browserDownloadUrl = jsonDownloadUrl.GetString(); // check version bool hasVersionFile = false; if (checkGraphicPackDownloadedVersion(assetName, hasVersionFile)) { // already up to date wxMessageBox(_("No updates available."), _("Graphic packs"), wxOK | wxCENTRE, this->GetParent()); m_threadState = ThreadFinished; return; } if (hasVersionFile) { // if a version file already exists (and graphic packs are installed) ask the user if he really wants to update if (wxMessageBox(_("Updated graphic packs are available. Do you want to download and install them?"), _("Graphic packs"), wxYES_NO, this->GetParent()) != wxYES) { // cancel update m_threadState = ThreadFinished; return; } } // download zip m_stage = StageDownloading; if (curlDownloadFile(browserDownloadUrl, m_downloadState.get()) == false) { wxMessageBox(_("Error"), _(L"Failed to connect to server"), wxOK | wxCENTRE | wxICON_ERROR, this); m_threadState = ThreadError; return; } m_extractionProgress = 0.0; m_stage = StageExtracting; zip_source_t *src; zip_t *za; zip_error_t error; // init zip source zip_error_init(&error); if ((src = zip_source_buffer_create(m_downloadState->fileData.data(), m_downloadState->fileData.size(), 1, &error)) == NULL) { zip_error_fini(&error); m_threadState = ThreadError; return; } // open zip from source if ((za = zip_open_from_source(src, 0, &error)) == NULL) { zip_source_free(src); zip_error_fini(&error); m_threadState = ThreadError; return; } auto path = ActiveSettings::GetUserDataPath("graphicPacks/downloadedGraphicPacks"); std::error_code er; //fs::remove_all(path, er); -> Don't delete the whole folder and recreate it immediately afterwards because sometimes it just fails deleteDownloadedGraphicPacks(); fs::create_directories(path, er); // make sure downloadedGraphicPacks folder exists sint32 numEntries = zip_get_num_entries(za, 0); for (sint32 i = 0; i < numEntries; i++) { m_extractionProgress = (double)i / (double)numEntries; zip_stat_t sb = { 0 }; if (zip_stat_index(za, i, 0, &sb) != 0) { assert_dbg(); } if(std::strstr(sb.name, "../") != nullptr || std::strstr(sb.name, "..\\") != nullptr) continue; // bad path path = ActiveSettings::GetUserDataPath("graphicPacks/downloadedGraphicPacks/{}", sb.name); size_t sbNameLen = strlen(sb.name); if(sbNameLen == 0) continue; if (sb.name[sbNameLen - 1] == '/') { fs::create_directories(path, er); continue; } if(sb.size == 0) continue; if (sb.size > (1024 * 1024 * 128)) continue; // skip unusually huge files zip_file_t* zipFile = zip_fopen_index(za, i, 0); if (zipFile == nullptr) continue; uint8* fileBuffer = new uint8[sb.size]; if (zip_fread(zipFile, fileBuffer, sb.size) == sb.size) { FileStream* fs = FileStream::createFile2(path); if (fs) { fs->writeData(fileBuffer, sb.size); delete fs; } } delete [] fileBuffer; zip_fclose(zipFile); } zip_error_fini(&error); createGraphicPackDownloadedVersionFile(assetName); m_threadState = ThreadFinished; } DownloadGraphicPacksWindow::DownloadGraphicPacksWindow(wxWindow* parent) : wxDialog(parent, wxID_ANY, _("Checking version..."), wxDefaultPosition, wxDefaultSize, wxCAPTION | wxMINIMIZE_BOX | wxSYSTEM_MENU | wxTAB_TRAVERSAL | wxCLOSE_BOX), m_threadState(ThreadRunning), m_stage(StageCheckVersion), m_currentStage(StageCheckVersion) { auto* sizer = new wxBoxSizer(wxVERTICAL); m_processBar = new wxGauge(this, wxID_ANY, 100, wxDefaultPosition, wxSize(500, 20), wxGA_HORIZONTAL); m_processBar->SetValue(0); m_processBar->SetRange(100); sizer->Add(m_processBar, 0, wxALL | wxEXPAND, 5); auto* m_cancelButton = new wxButton(this, wxID_ANY, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0); m_cancelButton->Bind(wxEVT_BUTTON, &DownloadGraphicPacksWindow::OnCancelButton, this); sizer->Add(m_cancelButton, 0, wxALIGN_RIGHT | wxALL, 5); this->SetSizer(sizer); this->Centre(wxBOTH); wxWindowBase::Layout(); wxWindowBase::Fit(); m_timer = new wxTimer(this); this->Bind(wxEVT_TIMER, &DownloadGraphicPacksWindow::OnUpdate, this); this->Bind(wxEVT_CLOSE_WINDOW, &DownloadGraphicPacksWindow::OnClose, this); m_timer->Start(250); m_downloadState = std::make_unique<curlDownloadFileState_t>(); } DownloadGraphicPacksWindow::~DownloadGraphicPacksWindow() { m_timer->Stop(); if (m_thread.joinable()) m_thread.join(); } const std::string& DownloadGraphicPacksWindow::GetException() const { return m_threadException; } int DownloadGraphicPacksWindow::ShowModal() { if(CafeSystem::IsTitleRunning()) { wxMessageBox(_("Graphic packs cannot be updated while a game is running."), _("Graphic packs"), 5, this->GetParent()); return wxID_CANCEL; } m_thread = std::thread(&DownloadGraphicPacksWindow::UpdateThread, this); wxDialog::ShowModal(); return m_threadState == ThreadCanceled ? wxID_CANCEL : wxID_OK; } void DownloadGraphicPacksWindow::OnClose(wxCloseEvent& event) { if (m_threadState == ThreadRunning) { //wxMessageDialog dialog(this, _("Do you really want to cancel the update process?\n\nCanceling the process will delete the applied update."), _("Info"), wxCENTRE | wxYES_NO); //if (dialog.ShowModal() != wxID_YES) // return; m_threadState = ThreadCanceled; } m_timer->Stop(); if (m_thread.joinable()) m_thread.join(); event.Skip(); } void DownloadGraphicPacksWindow::OnUpdate(const wxTimerEvent& event) { if (m_threadState != ThreadRunning) { Close(); return; } if (m_currentStage != m_stage) { if (m_stage == StageDownloading) { this->SetTitle(_("Downloading graphic packs...")); } else if (m_stage == StageExtracting) { this->SetTitle(_("Extracting...")); } m_currentStage = m_stage; } if (m_currentStage == StageDownloading) { const sint32 processedSize = (sint32)(m_downloadState->progress * 100.0f); if (m_processBar->GetValue() != processedSize) m_processBar->SetValue(processedSize); } else if (m_currentStage == StageExtracting) { const sint32 processedSize = (sint32)(m_extractionProgress * 100.0f); if (m_processBar->GetValue() != processedSize) m_processBar->SetValue(processedSize); } } void DownloadGraphicPacksWindow::OnCancelButton(const wxCommandEvent& event) { Close(); }
11,974
C++
.cpp
356
31.261236
177
0.743388
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,976
guiWrapper.cpp
cemu-project_Cemu/src/gui/guiWrapper.cpp
#if BOOST_OS_LINUX #include <gtk/gtk.h> #include <gdk/gdk.h> #include <gdk/gdkwindow.h> #include <gdk/gdkx.h> #ifdef HAS_WAYLAND #include <gdk/gdkwayland.h> #endif #endif #include "gui/wxgui.h" #include "gui/guiWrapper.h" #include "gui/CemuApp.h" #include "gui/MainWindow.h" #include "gui/debugger/DebuggerWindow2.h" #include "Cafe/HW/Latte/Core/Latte.h" #include "config/ActiveSettings.h" #include "config/NetworkSettings.h" #include "config/CemuConfig.h" #include "Cafe/HW/Latte/Renderer/Renderer.h" #include "Cafe/CafeSystem.h" #include "wxHelper.h" WindowInfo g_window_info {}; std::shared_mutex g_mutex; MainWindow* g_mainFrame = nullptr; #if BOOST_OS_WINDOWS void _wxLaunch() { SetThreadName("MainThread_UI"); wxEntry(); } #endif void gui_create() { SetThreadName("cemu"); #if BOOST_OS_WINDOWS // on Windows wxWidgets there is a bug where wxDirDialog->ShowModal will deadlock in Windows internals somehow // moving the UI thread off the main thread fixes this std::thread t = std::thread(_wxLaunch); t.join(); #else int argc = 0; char* argv[1]{}; wxEntry(argc, argv); #endif } WindowInfo& gui_getWindowInfo() { return g_window_info; } void gui_updateWindowTitles(bool isIdle, bool isLoading, double fps) { std::string windowText; windowText = BUILD_VERSION_WITH_NAME_STRING; if (isIdle) { if (g_mainFrame) g_mainFrame->AsyncSetTitle(windowText); return; } if (isLoading) { windowText.append(" - loading..."); if (g_mainFrame) g_mainFrame->AsyncSetTitle(windowText); return; } const char* renderer = ""; if(g_renderer) { switch(g_renderer->GetType()) { case RendererAPI::OpenGL: renderer = "[OpenGL]"; break; case RendererAPI::Vulkan: renderer = "[Vulkan]"; break; default: ; } } // get GPU vendor/mode const char* graphicMode = "[Generic]"; if (LatteGPUState.glVendor == GLVENDOR_AMD) graphicMode = "[AMD GPU]"; else if (LatteGPUState.glVendor == GLVENDOR_INTEL) graphicMode = "[Intel GPU]"; else if (LatteGPUState.glVendor == GLVENDOR_NVIDIA) graphicMode = "[NVIDIA GPU]"; else if (LatteGPUState.glVendor == GLVENDOR_APPLE) graphicMode = "[Apple GPU]"; const uint64 titleId = CafeSystem::GetForegroundTitleId(); windowText.append(fmt::format(" - FPS: {:.2f} {} {} [TitleId: {:08x}-{:08x}]", (double)fps, renderer, graphicMode, (uint32)(titleId >> 32), (uint32)(titleId & 0xFFFFFFFF))); if (ActiveSettings::IsOnlineEnabled()) { if (ActiveSettings::GetNetworkService() == NetworkService::Nintendo) windowText.append(" [Online]"); else if (ActiveSettings::GetNetworkService() == NetworkService::Pretendo) windowText.append(" [Online-Pretendo]"); else if (ActiveSettings::GetNetworkService() == NetworkService::Custom) windowText.append(" [Online-" + GetNetworkConfig().networkname.GetValue() + "]"); } windowText.append(" "); windowText.append(CafeSystem::GetForegroundTitleName()); // append region CafeConsoleRegion region = CafeSystem::GetForegroundTitleRegion(); uint16 titleVersion = CafeSystem::GetForegroundTitleVersion(); if (region == CafeConsoleRegion::JPN) windowText.append(fmt::format(" [JP v{}]", titleVersion)); else if (region == CafeConsoleRegion::USA) windowText.append(fmt::format(" [US v{}]", titleVersion)); else if (region == CafeConsoleRegion::EUR) windowText.append(fmt::format(" [EU v{}]", titleVersion)); else windowText.append(fmt::format(" [v{}]", titleVersion)); std::shared_lock lock(g_mutex); if (g_mainFrame) { g_mainFrame->AsyncSetTitle(windowText); auto* pad = g_mainFrame->GetPadView(); if (pad) pad->AsyncSetTitle(fmt::format("{} - FPS: {:.02f}", _("GamePad View").utf8_string(), fps)); } } void gui_getWindowSize(int& w, int& h) { w = g_window_info.width; h = g_window_info.height; } void gui_getPadWindowSize(int& w, int& h) { if (g_window_info.pad_open) { w = g_window_info.pad_width; h = g_window_info.pad_height; } else { w = 0; h = 0; } } void gui_getWindowPhysSize(int& w, int& h) { w = g_window_info.phys_width; h = g_window_info.phys_height; } void gui_getPadWindowPhysSize(int& w, int& h) { if (g_window_info.pad_open) { w = g_window_info.phys_pad_width; h = g_window_info.phys_pad_height; } else { w = 0; h = 0; } } double gui_getWindowDPIScale() { return g_window_info.dpi_scale; } double gui_getPadDPIScale() { return g_window_info.pad_open ? g_window_info.pad_dpi_scale.load() : 1.0; } bool gui_isPadWindowOpen() { return g_window_info.pad_open; } #if BOOST_OS_LINUX std::string gui_gtkRawKeyCodeToString(uint32 keyCode) { return gdk_keyval_name(keyCode); } #endif void gui_initHandleContextFromWxWidgetsWindow(WindowHandleInfo& handleInfoOut, class wxWindow* wxw) { #if BOOST_OS_WINDOWS handleInfoOut.hwnd = wxw->GetHWND(); #elif BOOST_OS_LINUX GtkWidget* gtkWidget = (GtkWidget*)wxw->GetHandle(); // returns GtkWidget gtk_widget_realize(gtkWidget); GdkWindow* gdkWindow = gtk_widget_get_window(gtkWidget); GdkDisplay* gdkDisplay = gdk_window_get_display(gdkWindow); if(GDK_IS_X11_WINDOW(gdkWindow)) { handleInfoOut.backend = WindowHandleInfo::Backend::X11; handleInfoOut.xlib_window = gdk_x11_window_get_xid(gdkWindow); handleInfoOut.xlib_display = gdk_x11_display_get_xdisplay(gdkDisplay); if(!handleInfoOut.xlib_display) { cemuLog_log(LogType::Force, "Unable to get xlib display"); } } else #ifdef HAS_WAYLAND if(GDK_IS_WAYLAND_WINDOW(gdkWindow)) { handleInfoOut.backend = WindowHandleInfo::Backend::WAYLAND; handleInfoOut.surface = gdk_wayland_window_get_wl_surface(gdkWindow); handleInfoOut.display = gdk_wayland_display_get_wl_display(gdkDisplay); } else #endif { cemuLog_log(LogType::Force, "Unsuported GTK backend"); } #else handleInfoOut.handle = wxw->GetHandle(); #endif } bool gui_isKeyDown(uint32 key) { return g_window_info.get_keystate(key); } bool gui_isKeyDown(PlatformKeyCodes key) { return gui_isKeyDown((std::underlying_type_t<PlatformKeyCodes>)key); } void gui_notifyGameLoaded() { std::shared_lock lock(g_mutex); if (g_mainFrame) { g_mainFrame->OnGameLoaded(); g_mainFrame->UpdateSettingsAfterGameLaunch(); } } void gui_notifyGameExited() { std::shared_lock lock(g_mutex); if(g_mainFrame) g_mainFrame->RestoreSettingsAfterGameExited(); } bool gui_isFullScreen() { return g_window_info.is_fullscreen; } bool gui_hasScreenshotRequest() { const bool result = g_window_info.has_screenshot_request; g_window_info.has_screenshot_request = false; return result; } extern DebuggerWindow2* g_debugger_window; void debuggerWindow_updateViewThreadsafe2() { if (g_debugger_window) { auto* evt = new wxCommandEvent(wxEVT_UPDATE_VIEW); wxQueueEvent(g_debugger_window, evt); } } void debuggerWindow_moveIP() { if (g_debugger_window) { auto* evt = new wxCommandEvent(wxEVT_MOVE_IP); wxQueueEvent(g_debugger_window, evt); } } void debuggerWindow_notifyDebugBreakpointHit2() { if (g_debugger_window) { auto* evt = new wxCommandEvent(wxEVT_BREAKPOINT_HIT); wxQueueEvent(g_debugger_window, evt); } } void debuggerWindow_notifyRun() { if (g_debugger_window) { auto* evt = new wxCommandEvent(wxEVT_RUN); wxQueueEvent(g_debugger_window, evt); } } void debuggerWindow_notifyModuleLoaded(void* module) { if (g_debugger_window) { auto* evt = new wxCommandEvent(wxEVT_NOTIFY_MODULE_LOADED); evt->SetClientData(module); wxQueueEvent(g_debugger_window, evt); } } void debuggerWindow_notifyModuleUnloaded(void* module) { if (g_debugger_window) { auto* evt = new wxCommandEvent(wxEVT_NOTIFY_MODULE_UNLOADED); evt->SetClientData(module); wxQueueEvent(g_debugger_window, evt); } }
7,663
C++
.cpp
297
23.6633
177
0.739872
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,977
GettingStartedDialog.cpp
cemu-project_Cemu/src/gui/GettingStartedDialog.cpp
#include "gui/GettingStartedDialog.h" #include <wx/sizer.h> #include <wx/filepicker.h> #include <wx/statbox.h> #include <wx/msgdlg.h> #include <wx/radiobox.h> #include "config/ActiveSettings.h" #include "gui/CemuApp.h" #include "gui/DownloadGraphicPacksWindow.h" #include "gui/GraphicPacksWindow2.h" #include "gui/input/InputSettings2.h" #include "config/CemuConfig.h" #include "Cafe/TitleList/TitleList.h" #if BOOST_OS_LINUX || BOOST_OS_MACOS #include "resource/embedded/resources.h" #endif #include "wxHelper.h" wxDEFINE_EVENT(EVT_REFRESH_FIRST_PAGE, wxCommandEvent); // used to refresh the first page after the language change wxPanel* GettingStartedDialog::CreatePage1() { auto* mainPanel = new wxPanel(m_notebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); auto* page1_sizer = new wxBoxSizer(wxVERTICAL); { auto* sizer = new wxBoxSizer(wxHORIZONTAL); sizer->Add(new wxStaticBitmap(mainPanel, wxID_ANY, wxICON(M_WND_ICON128)), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_page1.staticText11 = new wxStaticText(mainPanel, wxID_ANY, _("It looks like you're starting Cemu for the first time.\nThis quick setup assistant will help you get the best experience"), wxDefaultPosition, wxDefaultSize, 0); m_page1.staticText11->Wrap(-1); sizer->Add(m_page1.staticText11, 0, wxALL, 5); page1_sizer->Add(sizer, 0, wxALL | wxEXPAND, 5); } if(ActiveSettings::IsPortableMode()) { m_page1.portableModeInfoText = new wxStaticText(mainPanel, wxID_ANY, _("Cemu is running in portable mode")); m_page1.portableModeInfoText->Show(true); page1_sizer->Add(m_page1.portableModeInfoText, 0, wxALL, 5); } // language selection #if 0 { m_page1.languageBoxSizer = new wxStaticBoxSizer(wxVERTICAL, mainPanel, _("Language")); m_page1.languageText = new wxStaticText(m_page1.languageBoxSizer->GetStaticBox(), wxID_ANY, _("Select the language you want to use in Cemu")); m_page1.languageBoxSizer->Add(m_page1.languageText, 0, wxALL, 5); wxString language_choices[] = { _("Default") }; wxChoice* m_language = new wxChoice(m_page1.languageBoxSizer->GetStaticBox(), wxID_ANY, wxDefaultPosition, wxDefaultSize, std::size(language_choices), language_choices); m_language->SetSelection(0); for (const auto& language : wxGetApp().GetLanguages()) { m_language->Append(language->DescriptionNative); } m_language->SetSelection(0); m_page1.languageBoxSizer->Add(m_language, 0, wxALL | wxEXPAND, 5); page1_sizer->Add(m_page1.languageBoxSizer, 0, wxALL | wxEXPAND, 5); m_language->Bind(wxEVT_CHOICE, [this, m_language](const auto&) { const auto language = m_language->GetStringSelection(); auto selection = m_language->GetSelection(); if (selection == 0) GetConfig().language = wxLANGUAGE_DEFAULT; else { auto* app = (CemuApp*)wxTheApp; const auto language = m_language->GetStringSelection(); for (const auto& lang : app->GetLanguages()) { if (lang->DescriptionNative == language) { app->LocalizeUI(static_cast<wxLanguage>(lang->Language)); wxCommandEvent event(EVT_REFRESH_FIRST_PAGE); wxPostEvent(this, event); break; } } } }); } #endif { m_page1.gamePathBoxSizer = new wxStaticBoxSizer(wxVERTICAL, mainPanel, _("Game paths")); m_page1.gamePathText = new wxStaticText(m_page1.gamePathBoxSizer->GetStaticBox(), wxID_ANY, _("The game path is scanned by Cemu to automatically locate your games, game updates and DLCs. We recommend creating a dedicated directory in which\nyou place all your Wii U game files. Additional paths can be set later in Cemu's general settings. All common Wii U game formats are supported by Cemu.")); m_page1.gamePathBoxSizer->Add(m_page1.gamePathText, 0, wxALL, 5); auto* game_path_sizer = new wxBoxSizer(wxHORIZONTAL); m_page1.gamePathText2 = new wxStaticText(m_page1.gamePathBoxSizer->GetStaticBox(), wxID_ANY, _("Game path")); game_path_sizer->Add(m_page1.gamePathText2, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_page1.gamePathPicker = new wxDirPickerCtrl(m_page1.gamePathBoxSizer->GetStaticBox(), wxID_ANY, wxEmptyString, _("Select a folder")); game_path_sizer->Add(m_page1.gamePathPicker, 1, wxALL, 5); m_page1.gamePathBoxSizer->Add(game_path_sizer, 0, wxEXPAND, 5); page1_sizer->Add(m_page1.gamePathBoxSizer, 0, wxALL | wxEXPAND, 5); } { auto* sizer = new wxStaticBoxSizer(wxVERTICAL, mainPanel, _("Graphic packs && mods")); sizer->Add(new wxStaticText(sizer->GetStaticBox(), wxID_ANY, _("Graphic packs improve games by offering the ability to change resolution, increase FPS, tweak visuals or add gameplay modifications.\nGet started by opening the graphic packs configuration window.\n")), 0, wxALL, 5); auto* download_gp = new wxButton(sizer->GetStaticBox(), wxID_ANY, _("Download and configure graphic packs")); download_gp->Bind(wxEVT_BUTTON, &GettingStartedDialog::OnConfigureGPs, this); sizer->Add(download_gp, 0, wxALIGN_CENTER | wxALL, 5); page1_sizer->Add(sizer, 0, wxALL | wxEXPAND, 5); } { auto* sizer = new wxFlexGridSizer(0, 1, 0, 0); sizer->AddGrowableCol(0); sizer->AddGrowableRow(0); sizer->SetFlexibleDirection(wxBOTH); sizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_ALL); auto* next = new wxButton(mainPanel, wxID_ANY, _("Next"), wxDefaultPosition, wxDefaultSize, 0); next->Bind(wxEVT_BUTTON, [this](const auto&){m_notebook->SetSelection(1); }); sizer->Add(next, 0, wxALIGN_BOTTOM | wxALIGN_RIGHT | wxALL, 5); page1_sizer->Add(sizer, 1, wxEXPAND, 5); } mainPanel->SetSizer(page1_sizer); return mainPanel; } wxPanel* GettingStartedDialog::CreatePage2() { auto* result = new wxPanel(m_notebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); auto* page2_sizer = new wxBoxSizer(wxVERTICAL); { auto* sizer = new wxStaticBoxSizer(new wxStaticBox(result, wxID_ANY, _("Input settings")), wxVERTICAL); sizer->Add(new wxStaticText(sizer->GetStaticBox(), wxID_ANY, _("You can configure one controller for each player.\nWe advise you to always use GamePad as emulated input for the first player, since many games expect the GamePad to be present.\nIt is also required for touch functionality.\nThe default global hotkeys are:\nCTRL - show pad screen\nCTRL + TAB - toggle pad screen\nALT + ENTER - toggle fullscreen\nESC - leave fullscreen\n\nIf you're having trouble configuring your controller, make sure to have it in idle state and press calibrate.\nAlso don't set the axis deadzone too low.")), 0, wxALL, 5); auto* input_button = new wxButton(sizer->GetStaticBox(), wxID_ANY, _("Configure input")); input_button->Bind(wxEVT_BUTTON, &GettingStartedDialog::OnInputSettings, this); sizer->Add(input_button, 0, wxALIGN_CENTER | wxALL, 5); page2_sizer->Add(sizer, 0, wxALL | wxEXPAND, 5); } { auto* sizer = new wxStaticBoxSizer(new wxStaticBox(result, wxID_ANY, _("Additional options")), wxVERTICAL); auto* option_sizer = new wxFlexGridSizer(0, 2, 0, 0); option_sizer->SetFlexibleDirection(wxBOTH); option_sizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); m_page2.fullscreenCheckbox = new wxCheckBox(sizer->GetStaticBox(), wxID_ANY, _("Start games with fullscreen")); option_sizer->Add(m_page2.fullscreenCheckbox, 0, wxALL, 5); m_page2.separateCheckbox = new wxCheckBox(sizer->GetStaticBox(), wxID_ANY, _("Open separate pad screen")); option_sizer->Add(m_page2.separateCheckbox, 0, wxALL, 5); m_page2.updateCheckbox = new wxCheckBox(sizer->GetStaticBox(), wxID_ANY, _("Automatically check for updates")); option_sizer->Add(m_page2.updateCheckbox, 0, wxALL, 5); #if BOOST_OS_LINUX if (!std::getenv("APPIMAGE")) { m_page2.updateCheckbox->Disable(); } #endif sizer->Add(option_sizer, 1, wxEXPAND, 5); page2_sizer->Add(sizer, 0, wxALL | wxEXPAND, 5); } { auto* sizer = new wxFlexGridSizer(0, 3, 0, 0); sizer->AddGrowableCol(1); sizer->AddGrowableRow(0); sizer->SetFlexibleDirection(wxBOTH); sizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_ALL); auto* previous = new wxButton(result, wxID_ANY, _("Previous")); previous->Bind(wxEVT_BUTTON, [this](const auto&) {m_notebook->SetSelection(0); }); sizer->Add(previous, 0, wxALIGN_BOTTOM | wxALIGN_RIGHT | wxALL, 5); auto* close = new wxButton(result, wxID_ANY, _("Close")); close->Bind(wxEVT_BUTTON, [this](const auto&){ Close(); }); sizer->Add(close, 1, wxALIGN_BOTTOM | wxALIGN_RIGHT | wxALL, 5); page2_sizer->Add(sizer, 1, wxEXPAND | wxLEFT, 5); } result->SetSizer(page2_sizer); return result; } void GettingStartedDialog::ApplySettings() { auto& config = GetConfig(); m_page2.fullscreenCheckbox->SetValue(config.fullscreen.GetValue()); m_page2.updateCheckbox->SetValue(config.check_update.GetValue()); m_page2.separateCheckbox->SetValue(config.pad_open.GetValue()); } void GettingStartedDialog::UpdateWindowSize() { for (auto it = m_notebook->GetChildren().GetFirst(); it; it = it->GetNext()) { it->GetData()->Layout(); } m_notebook->Layout(); Layout(); Fit(); } void GettingStartedDialog::OnClose(wxCloseEvent& event) { event.Skip(); auto& config = GetConfig(); config.fullscreen = m_page2.fullscreenCheckbox->GetValue(); config.check_update = m_page2.updateCheckbox->GetValue(); config.pad_open = m_page2.separateCheckbox->GetValue(); const fs::path gamePath = wxHelper::MakeFSPath(m_page1.gamePathPicker->GetPath()); std::error_code ec; if (!gamePath.empty() && fs::exists(gamePath, ec)) { const auto it = std::find(config.game_paths.cbegin(), config.game_paths.cend(), gamePath); if (it == config.game_paths.cend()) { config.game_paths.emplace_back(_pathToUtf8(gamePath)); } } } GettingStartedDialog::GettingStartedDialog(wxWindow* parent) : wxDialog(parent, wxID_ANY, _("Getting started"), wxDefaultPosition, { 740,530 }, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER) { auto* sizer = new wxBoxSizer(wxVERTICAL); m_notebook = new wxSimplebook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0); auto* m_page1 = CreatePage1(); m_notebook->AddPage(m_page1, wxEmptyString, false); auto* m_page2 = CreatePage2(); m_notebook->AddPage(m_page2, wxEmptyString, false); sizer->Add(m_notebook, 1, wxEXPAND | wxALL, 5); this->SetSizer(sizer); this->Centre(wxBOTH); this->Bind(wxEVT_CLOSE_WINDOW, &GettingStartedDialog::OnClose, this); ApplySettings(); UpdateWindowSize(); } void GettingStartedDialog::OnConfigureGPs(wxCommandEvent& event) { DownloadGraphicPacksWindow dialog(this); dialog.ShowModal(); GraphicPacksWindow2::RefreshGraphicPacks(); GraphicPacksWindow2 window(this, 0); window.ShowModal(); } void GettingStartedDialog::OnInputSettings(wxCommandEvent& event) { InputSettings2 dialog(this); dialog.ShowModal(); }
10,685
C++
.cpp
222
45.369369
609
0.744041
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,978
GameUpdateWindow.cpp
cemu-project_Cemu/src/gui/GameUpdateWindow.cpp
#include "gui/wxgui.h" #include "gui/GameUpdateWindow.h" #include "util/helpers/helpers.h" #include <filesystem> #include <sstream> #include "util/helpers/SystemException.h" #include "gui/CemuApp.h" #include "Cafe/TitleList/GameInfo.h" #include "gui/helpers/wxHelpers.h" #include "wxHelper.h" wxString _GetTitleIdTypeStr(TitleId titleId) { TitleIdParser tip(titleId); switch (tip.GetType()) { case TitleIdParser::TITLE_TYPE::AOC: return _("DLC"); case TitleIdParser::TITLE_TYPE::BASE_TITLE: return _("Base game"); case TitleIdParser::TITLE_TYPE::BASE_TITLE_DEMO: return _("Demo"); case TitleIdParser::TITLE_TYPE::SYSTEM_TITLE: case TitleIdParser::TITLE_TYPE::SYSTEM_OVERLAY_TITLE: return _("System title"); case TitleIdParser::TITLE_TYPE::SYSTEM_DATA: return _("System data title"); case TitleIdParser::TITLE_TYPE::BASE_TITLE_UPDATE: return _("Update"); default: break; } return "Unknown"; } bool GameUpdateWindow::ParseUpdate(const fs::path& metaPath) { m_title_info = TitleInfo(metaPath); if (!m_title_info.IsValid()) return false; fs::path target_location = ActiveSettings::GetMlcPath(m_title_info.GetInstallPath()); std::error_code ec; if (fs::exists(target_location, ec)) { try { const TitleInfo tmp(target_location); if (!tmp.IsValid()) { // does not exist / is not valid. We allow to overwrite it } else { TitleIdParser tip(m_title_info.GetAppTitleId()); TitleIdParser tipOther(tmp.GetAppTitleId()); if (tip.GetType() != tipOther.GetType()) { auto typeStrToInstall = _GetTitleIdTypeStr(m_title_info.GetAppTitleId()); auto typeStrCurrentlyInstalled = _GetTitleIdTypeStr(tmp.GetAppTitleId()); auto wxMsg = _("It seems that there is already a title installed at the target location but it has a different type.\nCurrently installed: \'{}\' Installing: \'{}\'\n\nThis can happen for titles which were installed with very old Cemu versions.\nDo you still want to continue with the installation? It will replace the currently installed title."); wxMessageDialog dialog(this, formatWxString(wxMsg, typeStrCurrentlyInstalled, typeStrToInstall), _("Warning"), wxCENTRE | wxYES_NO | wxICON_EXCLAMATION); if (dialog.ShowModal() != wxID_YES) return false; } else if (tmp.GetAppTitleVersion() == m_title_info.GetAppTitleVersion()) { wxMessageDialog dialog(this, _("It seems that the selected title is already installed, do you want to reinstall it?"), _("Warning"), wxCENTRE | wxYES_NO); if (dialog.ShowModal() != wxID_YES) return false; } else if (tmp.GetAppTitleVersion() > m_title_info.GetAppTitleVersion()) { wxMessageDialog dialog(this, _("It seems that a newer version is already installed, do you still want to install the older version?"), _("Warning"), wxCENTRE | wxYES_NO); if (dialog.ShowModal() != wxID_YES) return false; } } // temp rename until done m_backup_folder = target_location; m_backup_folder.replace_extension(".backup"); std::error_code ec; while (fs::exists(m_backup_folder, ec) || ec) { fs::remove_all(m_backup_folder, ec); if (ec) { const auto error_msg = formatWxString(_("Error when trying to move former title installation:\n{}"), GetSystemErrorMessage(ec)); wxMessageBox(error_msg, _("Error"), wxOK | wxCENTRE, this); return false; } // wait so filesystem doesnt std::this_thread::sleep_for(std::chrono::milliseconds(100)); } fs::rename(target_location, m_backup_folder); } catch (const std::exception& ex) { cemuLog_log(LogType::Force, "GameUpdateWindow::ParseUpdate exist-error: {} at {}", ex.what(), _pathToUtf8(target_location)); } } m_target_path = target_location; fs::path source(metaPath); m_source_paths = { fs::path(source).append("content"), fs::path(source).append("code"), fs::path(source).append("meta") }; m_required_size = 0; for (auto& path : m_source_paths) { for (const fs::directory_entry& f : fs::recursive_directory_iterator(path)) { if (is_regular_file(f.path())) m_required_size += file_size(f.path()); } } const fs::space_info targetSpace = fs::space(ActiveSettings::GetMlcPath()); if (targetSpace.free <= m_required_size) { auto string = formatWxString(_("Not enough space available.\nRequired: {0} MB\nAvailable: {1} MB"), (m_required_size / 1024 / 1024), (targetSpace.free / 1024 / 1024)); throw std::runtime_error(string.utf8_string()); } return true; } GameUpdateWindow::GameUpdateWindow(wxWindow& parent, const fs::path& filePath) : wxDialog(&parent, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxCAPTION | wxMINIMIZE_BOX | wxSYSTEM_MENU | wxTAB_TRAVERSAL | wxCLOSE_BOX), m_thread_state(ThreadRunning) { try { #if BOOST_OS_WINDOWS SetLastError(0); #endif if(!ParseUpdate(filePath)) throw AbortException(); } catch (const std::runtime_error& ex) { throw SystemException(ex); } auto sizer = new wxBoxSizer(wxVERTICAL); TitleIdParser tip(GetTitleId()); if (tip.GetType() == TitleIdParser::TITLE_TYPE::AOC) SetTitle(_("Installing DLC...")); else if (tip.GetType() == TitleIdParser::TITLE_TYPE::BASE_TITLE_UPDATE) SetTitle(_("Installing update...")); else if (tip.IsSystemTitle()) SetTitle(_("Installing system title...")); else SetTitle(_("Installing title...")); m_processBar = new wxGauge(this, wxID_ANY, 100, wxDefaultPosition, wxSize(500, 20), wxGA_HORIZONTAL); m_processBar->SetValue(0); m_processBar->SetRange((sint32)(m_required_size / 1000)); sizer->Add(m_processBar, 0, wxALL | wxEXPAND, 5); wxButton* m_cancelButton = new wxButton(this, wxID_ANY, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0); m_cancelButton->Bind(wxEVT_BUTTON, &GameUpdateWindow::OnCancelButton, this); sizer->Add(m_cancelButton, 0, wxALIGN_RIGHT | wxALL, 5); this->SetSizer(sizer); this->Centre(wxBOTH); wxWindowBase::Layout(); wxWindowBase::Fit(); m_timer = new wxTimer(this); this->Bind(wxEVT_TIMER, &GameUpdateWindow::OnUpdate, this); this->Bind(wxEVT_CLOSE_WINDOW, &GameUpdateWindow::OnClose, this); m_timer->Start(250); m_thread_state = ThreadRunning; m_thread = std::thread(&GameUpdateWindow::ThreadWork, this); } void GameUpdateWindow::ThreadWork() { fs::directory_entry currentDirEntry; try { // create base directories for (auto& path : m_source_paths) { if (!path.has_stem()) continue; fs::path targetDir = fs::path(m_target_path) / path.stem(); create_directories(targetDir); } for (auto& path : m_source_paths) { if (m_thread_state == ThreadCanceled) break; if (!path.has_parent_path()) continue; const auto len = path.parent_path().string().size() + 1; for (const fs::directory_entry& f : fs::recursive_directory_iterator {path}) { if (m_thread_state == ThreadCanceled) break; currentDirEntry = f; fs::path relative(f.path().string().substr(len)); fs::path target = fs::path(m_target_path) / relative; if (is_directory(f)) { create_directories(target); continue; } copy(f, target, fs::copy_options::overwrite_existing); if (is_regular_file(f.path())) { m_processed_size += file_size(f.path()); } } } } catch (const std::exception& ex) { std::stringstream error_msg; error_msg << GetSystemErrorMessage(ex); if(currentDirEntry != fs::directory_entry{}) error_msg << fmt::format("\n{}\n{}",_("Current file:").utf8_string(), _pathToUtf8(currentDirEntry.path())); m_thread_exception = error_msg.str(); m_thread_state = ThreadCanceled; } if (m_thread_state == ThreadCanceled) { if(fs::exists(m_target_path)) fs::remove_all(m_target_path); } else m_thread_state = ThreadFinished; } GameUpdateWindow::~GameUpdateWindow() { m_timer->Stop(); if (m_thread.joinable()) m_thread.join(); } int GameUpdateWindow::ShowModal() { wxDialog::ShowModal(); return m_thread_state == ThreadCanceled ? wxID_CANCEL : wxID_OK; } void GameUpdateWindow::OnClose(wxCloseEvent& event) { if (m_thread_state == ThreadRunning) { wxMessageDialog dialog(this, _("Do you really want to cancel the installation process?\n\nCanceling the process will delete the applied files."), _("Info"), wxCENTRE | wxYES_NO); if (dialog.ShowModal() != wxID_YES) return; m_thread_state = ThreadCanceled; } m_timer->Stop(); if (m_thread.joinable()) m_thread.join(); if(!m_backup_folder.empty()) { if(m_thread_state == ThreadCanceled) { // restore backup try { if(fs::exists(m_target_path)) fs::remove_all(m_target_path); fs::rename(m_backup_folder, m_target_path); } catch (const std::exception& ex) { cemuLog_logDebug(LogType::Force, "can't restore update backup: {}",ex.what()); } } else { // delete backup try { if(fs::exists(m_backup_folder)) fs::remove_all(m_backup_folder); } catch (const std::exception& ex) { cemuLog_logDebug(LogType::Force, "can't delete update backup: {}",ex.what()); } } m_backup_folder.clear(); } event.Skip(); } void GameUpdateWindow::OnUpdate(const wxTimerEvent& event) { if (m_thread_state != ThreadRunning) { Close(); return; } const auto processedSize = (sint32)(m_processed_size / 1000); if (m_processBar->GetValue() != processedSize) m_processBar->SetValue(processedSize); } void GameUpdateWindow::OnCancelButton(const wxCommandEvent& event) { Close(); }
9,461
C++
.cpp
295
28.830508
353
0.70181
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,979
GraphicPacksWindow2.cpp
cemu-project_Cemu/src/gui/GraphicPacksWindow2.cpp
#include "gui/wxgui.h" #include "gui/GraphicPacksWindow2.h" #include "gui/DownloadGraphicPacksWindow.h" #include "Cafe/GraphicPack/GraphicPack2.h" #include "config/CemuConfig.h" #include "config/ActiveSettings.h" #include "Cafe/HW/Latte/Core/LatteAsyncCommands.h" #include "Cafe/CafeSystem.h" #include "Cafe/TitleList/TitleList.h" #include "wxHelper.h" #if BOOST_OS_LINUX || BOOST_OS_MACOS #include "resource/embedded/resources.h" #endif // main.cpp class wxGraphicPackData : public wxTreeItemData { public: wxGraphicPackData(GraphicPackPtr pack) : m_pack(std::move(pack)) { } const GraphicPackPtr& GetGraphicPack() const { return m_pack; } private: GraphicPackPtr m_pack; }; void GraphicPacksWindow2::FillGraphicPackList() const { wxWindowUpdateLocker lock(m_graphic_pack_tree); m_graphic_pack_tree->DeleteAllItems(); auto graphic_packs = GraphicPack2::GetGraphicPacks(); const auto root = m_graphic_pack_tree->AddRoot("Root"); const bool has_filter = !m_filter.empty(); for(auto& p : graphic_packs) { // filter graphic packs by given title id if (m_filter_installed_games && !m_installed_games.empty()) { bool found = false; for (uint64 titleId : p->GetTitleIds()) { if (std::find(m_installed_games.cbegin(), m_installed_games.cend(), titleId) != m_installed_games.cend()) { found = true; break; } } if (!found) continue; } // filter graphic packs by given title id if(has_filter) { bool found = false; if (boost::icontains(p->GetVirtualPath(), m_filter)) found = true; else { for (uint64 titleId : p->GetTitleIds()) { if (boost::icontains(fmt::format("{:x}", titleId), m_filter)) { found = true; break; } } } if (!found) continue; } const auto& path = p->GetVirtualPath(); auto tokens = TokenizeView(path, '/'); auto node = root; for(size_t i=0; i<tokens.size(); i++) { auto& token = tokens[i]; const auto parent_node = node; if (i < (tokens.size() - 1)) { node = FindTreeItem(parent_node, wxHelper::FromUtf8(token)); if (!node.IsOk()) { node = m_graphic_pack_tree->AppendItem(parent_node, wxHelper::FromUtf8(token)); } } else { // last token // if a node with same name already exists, add a number suffix for (sint32 s = 0; s < 999; s++) { wxString nodeName = wxHelper::FromUtf8(token); if (s > 0) nodeName.append(wxHelper::FromUtf8(fmt::format(" #{}", s + 1))); node = FindTreeItem(parent_node, nodeName); if (!node.IsOk()) { node = m_graphic_pack_tree->AppendItem(parent_node, nodeName); break; } } } } if(node.IsOk() && node != root) { m_graphic_pack_tree->SetItemData(node, new wxGraphicPackData(p)); bool canEnable = true; if (p->GetVersion() == 3) { auto tmp_text = m_graphic_pack_tree->GetItemText(node); m_graphic_pack_tree->SetItemText(node, tmp_text + " (may not be compatible with Vulkan)"); } else if (p->GetVersion() != 3 && p->GetVersion() != 4 && p->GetVersion() != 5 && p->GetVersion() != 6 && p->GetVersion() != GraphicPack2::GFXPACK_VERSION_7) { auto tmp_text = m_graphic_pack_tree->GetItemText(node); m_graphic_pack_tree->SetItemText(node, tmp_text + " (Unsupported version)"); m_graphic_pack_tree->SetItemTextColour(node, 0x0000CC); canEnable = false; } else if (p->IsActivated()) m_graphic_pack_tree->SetItemTextColour(node, 0x009900); m_graphic_pack_tree->MakeCheckable(node, p->IsEnabled()); if (!canEnable) m_graphic_pack_tree->DisableCheckBox(node); } } m_graphic_pack_tree->Sort(root, true); if (!m_filter.empty()) { size_t counter = 0; ExpandChildren({ root }, counter); } } void GraphicPacksWindow2::GetChildren(const wxTreeItemId& id, std::vector<wxTreeItemId>& children) const { wxTreeItemIdValue cookie; wxTreeItemId child = m_graphic_pack_tree->GetFirstChild(id, cookie); while (child.IsOk()) { children.emplace_back(child); child = m_graphic_pack_tree->GetNextChild(child, cookie); } } void GraphicPacksWindow2::ExpandChildren(const std::vector<wxTreeItemId>& ids, size_t& counter) const { std::vector<wxTreeItemId> children; for (const auto& id : ids) GetChildren(id, children); counter += children.size(); if (counter >= 30 || children.empty()) return; for (const auto& id : ids) { if(id != m_graphic_pack_tree->GetRootItem() && m_graphic_pack_tree->HasChildren(id)) m_graphic_pack_tree->Expand(id); } ExpandChildren(children, counter); } void GraphicPacksWindow2::RefreshGraphicPacks() { GraphicPack2::ClearGraphicPacks(); GraphicPack2::LoadAll(); } GraphicPacksWindow2::GraphicPacksWindow2(wxWindow* parent, uint64_t title_id_filter) : wxDialog(parent, wxID_ANY, _("Graphic packs"), wxDefaultPosition, wxSize(1000,670), wxCLOSE_BOX | wxCLIP_CHILDREN | wxCAPTION | wxRESIZE_BORDER), m_installed_games(CafeTitleList::GetAllTitleIds()) { if (title_id_filter != 0) m_filter = fmt::format("{:x}", title_id_filter); m_filter_installed_games = !m_installed_games.empty(); SetIcon(wxICON(X_BOX)); SetMinSize(wxSize(500, 400)); auto main_sizer = new wxBoxSizer(wxVERTICAL); m_splitter_window = new wxSplitterWindow(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxSP_3D); m_splitter_window->Bind(wxEVT_SIZE, &GraphicPacksWindow2::OnSizeChanged, this); m_splitter_window->Bind(wxEVT_SPLITTER_SASH_POS_CHANGED, &GraphicPacksWindow2::SashPositionChanged, this); // left side auto left_panel = new wxPanel(m_splitter_window); { auto sizer = new wxBoxSizer(wxVERTICAL); wxFlexGridSizer* filter_row = new wxFlexGridSizer(0, 3, 0, 0); filter_row->AddGrowableCol(1); filter_row->SetFlexibleDirection(wxBOTH); filter_row->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); const auto text = new wxStaticText(left_panel, wxID_ANY, _("Filter"), wxDefaultPosition, wxDefaultSize, 0); text->Wrap(-1); filter_row->Add(text, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_filter_text = new wxTextCtrl(left_panel, wxID_ANY, wxHelper::FromUtf8(m_filter), wxDefaultPosition, wxDefaultSize, 0); filter_row->Add(m_filter_text, 0, wxALL | wxEXPAND, 5); m_filter_text->Bind(wxEVT_COMMAND_TEXT_UPDATED, &GraphicPacksWindow2::OnFilterUpdate, this); m_installed_games_only = new wxCheckBox(left_panel, wxID_ANY, _("Installed games"), wxDefaultPosition, wxDefaultSize, 0); m_installed_games_only->SetValue(m_filter_installed_games); filter_row->Add(m_installed_games_only, 0, wxALL | wxEXPAND, 5); m_installed_games_only->Bind(wxEVT_CHECKBOX, &GraphicPacksWindow2::OnInstalledGamesChanged, this); if (m_installed_games.empty()) m_installed_games_only->Disable(); sizer->Add(filter_row, 0, wxEXPAND, 5); m_graphic_pack_tree = new wxCheckTree(left_panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTR_DEFAULT_STYLE | wxTR_HIDE_ROOT); m_graphic_pack_tree->Bind(wxEVT_TREE_SEL_CHANGED, &GraphicPacksWindow2::OnTreeSelectionChanged, this); m_graphic_pack_tree->Bind(wxEVT_CHECKTREE_CHOICE, &GraphicPacksWindow2::OnTreeChoiceChanged, this); //m_graphic_pack_tree->SetMinSize(wxSize(600, 400)); sizer->Add(m_graphic_pack_tree, 1, wxEXPAND | wxALL, 5); left_panel->SetSizerAndFit(sizer); } // right side m_right_panel = new wxPanel(m_splitter_window, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL | wxNO_BORDER | wxFULL_REPAINT_ON_RESIZE); { auto* sizer = new wxBoxSizer(wxVERTICAL); { m_gp_options = new wxScrolled<wxPanel>(m_right_panel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL | wxNO_BORDER | wxVSCROLL); m_gp_options->SetScrollRate(-1, 10); auto* inner_sizer = new wxBoxSizer(wxVERTICAL); { auto* box = new wxStaticBox(m_gp_options, wxID_ANY, _("Graphic pack")); auto* box_sizer = new wxStaticBoxSizer(box, wxVERTICAL); m_graphic_pack_name = new wxStaticText(box, wxID_ANY, wxEmptyString); box_sizer->Add(m_graphic_pack_name, 1, wxEXPAND | wxALL, 5); inner_sizer->Add(box_sizer, 0, wxEXPAND | wxALL, 5); } { auto* box = new wxStaticBox(m_gp_options, wxID_ANY, _("Description")); auto* box_sizer = new wxStaticBoxSizer(box, wxVERTICAL); m_graphic_pack_description = new wxStaticText(box, wxID_ANY, wxEmptyString); box_sizer->Add(m_graphic_pack_description, 1, wxEXPAND | wxALL, 5); inner_sizer->Add(box_sizer, 0, wxEXPAND | wxALL, 5); } m_preset_sizer = new wxBoxSizer(wxVERTICAL); inner_sizer->Add(m_preset_sizer, 0, wxEXPAND, 0); { auto* box = new wxStaticBox(m_gp_options, wxID_ANY, _("Control")); auto* box_sizer = new wxStaticBoxSizer(box, wxHORIZONTAL); m_reload_shaders = new wxButton(box, wxID_ANY, _("Reload edited shaders")); m_reload_shaders->Bind(wxEVT_BUTTON, &GraphicPacksWindow2::OnReloadShaders, this); m_reload_shaders->Disable(); box_sizer->Add(m_reload_shaders, 0, wxEXPAND | wxALL, 5); inner_sizer->Add(box_sizer, 0, wxEXPAND | wxALL, 5); } inner_sizer->Add(new wxStaticText(m_gp_options, wxID_ANY, wxEmptyString), 1, wxALL | wxEXPAND, 5); m_gp_options->SetSizerAndFit(inner_sizer); m_gp_options->Hide(); sizer->Add(m_gp_options, 1, wxEXPAND | wxRESERVE_SPACE_EVEN_IF_HIDDEN); } sizer->Add(new wxStaticLine(m_right_panel, wxID_ANY), 0, wxLEFT|wxRIGHT | wxEXPAND, 3); auto* row = new wxBoxSizer(wxHORIZONTAL); m_update_graphicPacks = new wxButton(m_right_panel, wxID_ANY, _("Download latest community graphic packs")); m_update_graphicPacks->Bind(wxEVT_BUTTON, &GraphicPacksWindow2::OnCheckForUpdates, this); row->Add(m_update_graphicPacks, 0, wxALL, 5); sizer->Add(row, 0, wxALL | wxEXPAND, 5); m_right_panel->SetSizerAndFit(sizer); } m_splitter_window->SetMinimumPaneSize(50); m_splitter_window->SplitVertically(left_panel, m_right_panel, (sint32)(m_ratio * m_splitter_window->GetParent()->GetSize().GetWidth())); main_sizer->Add(m_splitter_window, 1, wxEXPAND, 5); m_info_bar = new wxInfoBar(this); m_info_bar->SetShowHideEffects(wxSHOW_EFFECT_BLEND, wxSHOW_EFFECT_BLEND); m_info_bar->SetEffectDuration(500); main_sizer->Add(m_info_bar, 0, wxALL | wxEXPAND, 5); SetSizer(main_sizer); UpdateTitleRunning(CafeSystem::IsTitleRunning()); FillGraphicPackList(); } void GraphicPacksWindow2::SaveStateToConfig() { auto& data = g_config.data(); data.graphic_pack_entries.clear(); for (const auto& gp : GraphicPack2::GetGraphicPacks()) { auto filename = _utf8ToPath(gp->GetNormalizedPathString()); if (gp->IsEnabled()) { data.graphic_pack_entries.try_emplace(filename); auto& it = data.graphic_pack_entries[filename]; // otherwise store all selected presets for (const auto& preset : gp->GetActivePresets()) it.try_emplace(preset->category, preset->name); } else if(gp->IsDefaultEnabled()) { // save that its disabled data.graphic_pack_entries.try_emplace(filename); auto& it = data.graphic_pack_entries[filename]; it.try_emplace("_disabled", "false"); } } g_config.Save(); } GraphicPacksWindow2::~GraphicPacksWindow2() { m_graphic_pack_tree->Unbind(wxEVT_CHECKTREE_CHOICE, &GraphicPacksWindow2::OnTreeSelectionChanged, this); m_graphic_pack_tree->Unbind(wxEVT_CHECKTREE_CHOICE, &GraphicPacksWindow2::OnTreeChoiceChanged, this); // m_active_preset->Unbind(wxEVT_CHOICE, &GraphicPacksWindow2::OnActivePresetChanged, this); m_reload_shaders->Unbind(wxEVT_BUTTON, &GraphicPacksWindow2::OnReloadShaders, this); SaveStateToConfig(); } wxTreeItemId GraphicPacksWindow2::FindTreeItem(const wxTreeItemId& root, const wxString& text) const { wxTreeItemIdValue cookie; for(auto item = m_graphic_pack_tree->GetFirstChild(root, cookie); item.IsOk(); item = m_graphic_pack_tree->GetNextSibling(item)) { if (m_graphic_pack_tree->GetItemText(item) == text) return item; } return {}; } void GraphicPacksWindow2::LoadPresetSelections(const GraphicPackPtr& gp) { std::vector<std::string> order; auto presets = gp->GetCategorizedPresets(order); for(const auto& category : order) { const auto& entry = presets[category]; // test if any preset is visible and update its status if (std::none_of(entry.cbegin(), entry.cend(), [gp](const auto& p) { return p->visible; })) { continue; } wxString categoryWxStr = wxHelper::FromUtf8(category); wxString label(category.empty() ? _("Active preset") : categoryWxStr); auto* box = new wxStaticBox(m_preset_sizer->GetContainingWindow(), wxID_ANY, label); auto* box_sizer = new wxStaticBoxSizer(box, wxVERTICAL); auto* preset = new wxChoice(box, wxID_ANY); preset->SetClientObject(new wxStringClientData(categoryWxStr)); preset->Bind(wxEVT_CHOICE, &GraphicPacksWindow2::OnActivePresetChanged, this); std::optional<std::string> active_preset; for (auto& pentry : entry) { if (!pentry->visible) continue; preset->AppendString(wxHelper::FromUtf8(pentry->name)); if (pentry->active) active_preset = pentry->name; } if (active_preset) preset->SetStringSelection(wxHelper::FromUtf8(active_preset.value())); else if (preset->GetCount() > 0) preset->SetSelection(0); box_sizer->Add(preset, 1, wxEXPAND | wxALL, 5); m_preset_sizer->Add(box_sizer, 0, wxEXPAND | wxALL, 5); } } void GraphicPacksWindow2::OnTreeSelectionChanged(wxTreeEvent& event) { wxWindowUpdateLocker lock(this); bool item_deselected = m_graphic_pack_tree->GetSelection() == m_graphic_pack_tree->GetRootItem(); if (item_deselected) return; const auto selection = m_graphic_pack_tree->GetSelection(); if (selection.IsOk()) { const auto data = dynamic_cast<wxGraphicPackData*>(m_graphic_pack_tree->GetItemData(selection)); if (data) { if(!m_gp_options->IsShown()) m_gp_options->Show(); const auto& gp = data->GetGraphicPack(); if (gp != m_shown_graphic_pack) { m_preset_sizer->Clear(true); m_gp_name = gp->GetName(); m_graphic_pack_name->SetLabel(wxHelper::FromUtf8(m_gp_name)); if (gp->GetDescription().empty()) m_gp_description = _("This graphic pack has no description").utf8_string(); else m_gp_description = gp->GetDescription(); m_graphic_pack_description->SetLabel(wxHelper::FromUtf8(m_gp_description)); LoadPresetSelections(gp); m_reload_shaders->Enable(gp->HasShaders()); m_shown_graphic_pack = gp; m_graphic_pack_name->Wrap(m_graphic_pack_name->GetParent()->GetClientSize().GetWidth() - 20); m_graphic_pack_name->GetGrandParent()->Layout(); m_graphic_pack_description->Wrap(m_graphic_pack_description->GetParent()->GetClientSize().GetWidth() - 20); m_graphic_pack_description->GetGrandParent()->Layout(); m_right_panel->FitInside(); m_right_panel->Layout(); } return; } } m_preset_sizer->Clear(true); m_graphic_pack_name->SetLabel(wxEmptyString); m_graphic_pack_description->SetLabel(wxEmptyString); m_reload_shaders->Disable(); m_shown_graphic_pack.reset(); m_gp_options->Hide(); m_right_panel->FitInside(); m_right_panel->Layout(); } void GraphicPacksWindow2::OnTreeChoiceChanged(wxTreeEvent& event) { auto item = event.GetItem(); if (!item.IsOk()) return; const bool state = event.GetExtraLong() != 0; const auto data = dynamic_cast<wxGraphicPackData*>(m_graphic_pack_tree->GetItemData(item)); if (!data) return; auto& graphic_pack = data->GetGraphicPack(); graphic_pack->SetEnabled(state); bool requiresRestart = graphic_pack->RequiresRestart(true, false); bool isRunning = CafeSystem::IsTitleRunning() && graphic_pack->ContainsTitleId(CafeSystem::GetForegroundTitleId()); if (isRunning) { if (state) { GraphicPack2::ActivateGraphicPack(graphic_pack); if (!requiresRestart) { ReloadPack(graphic_pack); m_graphic_pack_tree->SetItemTextColour(item, 0x009900); } } else { if (!requiresRestart) { DeleteShadersFromRuntimeCache(graphic_pack); m_graphic_pack_tree->SetItemTextColour(item, *wxBLACK); } GraphicPack2::DeactivateGraphicPack(graphic_pack); } } if (!m_info_bar->IsShown() && (isRunning && requiresRestart)) m_info_bar->ShowMessage(_("Restart of Cemu required for changes to take effect")); // also change selection to activated gp m_graphic_pack_tree->SelectItem(item); } // In some environments with GTK (e.g. a flatpak app with org.freedesktop.Platform 22.08 runtime), // destroying the event source inside the handler crashes the app. // As a workaround to that, the wxWindow that needs to be destroyed is hidden and then // destroyed at a later time, outside the handler. void GraphicPacksWindow2::ClearPresets() { size_t item_count = m_preset_sizer->GetItemCount(); std::vector<wxSizer*> sizers; sizers.reserve(item_count); for (size_t i = 0; i < item_count; i++) sizers.push_back(m_preset_sizer->GetItem(i)->GetSizer()); for (auto&& sizer : sizers) { auto static_box_sizer = dynamic_cast<wxStaticBoxSizer*>(sizer); if (static_box_sizer) { wxStaticBox* parent_window = static_box_sizer->GetStaticBox(); if (parent_window) { m_preset_sizer->Detach(sizer); parent_window->Hide(); CallAfter([=]() { parent_window->DestroyChildren(); delete static_box_sizer; }); } } } } void GraphicPacksWindow2::OnActivePresetChanged(wxCommandEvent& event) { if (!m_shown_graphic_pack) return; const auto obj = wxDynamicCast(event.GetEventObject(), wxChoice); wxASSERT(obj); const auto string_data = dynamic_cast<wxStringClientData*>(obj->GetClientObject()); wxASSERT(string_data); const auto preset = obj->GetStringSelection().utf8_string(); if(m_shown_graphic_pack->SetActivePreset(string_data->GetData().utf8_string(), preset)) { wxWindowUpdateLocker lock(this); ClearPresets(); LoadPresetSelections(m_shown_graphic_pack); //m_preset_sizer->GetContainingWindow()->Layout(); //m_right_panel->FitInside(); m_right_panel->FitInside(); m_right_panel->Layout(); } if (!m_shown_graphic_pack->RequiresRestart(false, true)) ReloadPack(m_shown_graphic_pack); else if (!m_info_bar->IsShown()) m_info_bar->ShowMessage(_("Restart of Cemu required for changes to take effect")); } void GraphicPacksWindow2::OnReloadShaders(wxCommandEvent& event) { if (m_shown_graphic_pack) ReloadPack(m_shown_graphic_pack); } void GraphicPacksWindow2::OnCheckForUpdates(wxCommandEvent& event) { DownloadGraphicPacksWindow frame(this); SaveStateToConfig(); const int updateResult = frame.ShowModal(); if (updateResult == wxID_OK) { if (!CafeSystem::IsTitleRunning()) { // remember virtual paths of all the enabled packs std::map<std::string, std::string> previouslyEnabledPacks; for(auto& it : GraphicPack2::GetGraphicPacks()) { if(it->IsEnabled()) previouslyEnabledPacks.emplace(it->GetNormalizedPathString(), it->GetVirtualPath()); } // reload graphic packs RefreshGraphicPacks(); FillGraphicPackList(); // remove packs which are still present for(auto& it : GraphicPack2::GetGraphicPacks()) previouslyEnabledPacks.erase(it->GetNormalizedPathString()); if(!previouslyEnabledPacks.empty()) { std::string lost_packs; for(auto& it : previouslyEnabledPacks) { lost_packs.append(it.second); lost_packs.push_back('\n'); } wxString message = _("This update removed or renamed the following graphic packs:"); message << "\n \n" << wxString::FromUTF8(lost_packs) << " \n" << _("You may need to set them up again."); wxMessageBox(message, _("Warning"), wxOK | wxCENTRE | wxICON_INFORMATION, this); } } } } void GraphicPacksWindow2::OnSizeChanged(wxSizeEvent& event) { const auto obj = (wxSplitterWindow*)event.GetEventObject(); wxASSERT(obj); const auto width = std::max(obj->GetMinimumPaneSize(), obj->GetParent()->GetClientSize().GetWidth()); obj->SetSashPosition((sint32)(m_ratio * width)); if (!m_gp_name.empty()) m_graphic_pack_name->SetLabel(wxHelper::FromUtf8(m_gp_name)); if (!m_gp_description.empty()) m_graphic_pack_description->SetLabel(wxHelper::FromUtf8(m_gp_description)); m_graphic_pack_name->Wrap(m_graphic_pack_name->GetParent()->GetClientSize().GetWidth() - 10); m_graphic_pack_description->Wrap(m_graphic_pack_description->GetParent()->GetClientSize().GetWidth() - 10); event.Skip(); } void GraphicPacksWindow2::SashPositionChanged(wxEvent& event) { const auto obj = (wxSplitterWindow*)event.GetEventObject(); wxASSERT(obj); const auto width = std::max(obj->GetMinimumPaneSize(), obj->GetParent()->GetClientSize().GetWidth()); m_ratio = (float)obj->GetSashPosition() / width; event.Skip(); } void GraphicPacksWindow2::OnFilterUpdate(wxEvent& event) { m_filter = m_filter_text->GetValue().utf8_string(); FillGraphicPackList(); event.Skip(); } void GraphicPacksWindow2::OnInstalledGamesChanged(wxCommandEvent& event) { m_filter_installed_games = m_installed_games_only->GetValue(); FillGraphicPackList(); event.Skip(); } void GraphicPacksWindow2::UpdateTitleRunning(bool running) { m_update_graphicPacks->Enable(!running); if(running) m_update_graphicPacks->SetToolTip(_("Graphic packs cannot be updated while a game is running.")); else m_update_graphicPacks->SetToolTip(nullptr); } void GraphicPacksWindow2::ReloadPack(const GraphicPackPtr& graphic_pack) const { if (graphic_pack->HasShaders() || graphic_pack->HasPatches() || graphic_pack->HasCustomVSyncFrequency()) { if (graphic_pack->Reload()) { DeleteShadersFromRuntimeCache(graphic_pack); } } } void GraphicPacksWindow2::DeleteShadersFromRuntimeCache(const GraphicPackPtr& graphic_pack) const { for (const auto& shader : graphic_pack->GetCustomShaders()) { LatteConst::ShaderType shaderType; if (shader.type == GraphicPack2::GP_SHADER_TYPE::VERTEX) shaderType = LatteConst::ShaderType::Vertex; else if (shader.type == GraphicPack2::GP_SHADER_TYPE::GEOMETRY) shaderType = LatteConst::ShaderType::Geometry; else if (shader.type == GraphicPack2::GP_SHADER_TYPE::PIXEL) shaderType = LatteConst::ShaderType::Pixel; LatteAsyncCommands_queueDeleteShader(shader.shader_base_hash, shader.shader_aux_hash, shaderType); } }
22,109
C++
.cpp
588
34.345238
159
0.724967
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,980
InputAPIAddWindow.cpp
cemu-project_Cemu/src/gui/input/InputAPIAddWindow.cpp
#include "gui/input/InputAPIAddWindow.h" #include "input/InputManager.h" #include "gui/helpers/wxCustomData.h" #include "gui/helpers/wxHelpers.h" #include "input/api/Controller.h" #include <wx/sizer.h> #include <wx/stattext.h> #include <wx/choice.h> #include <wx/statline.h> #include <wx/button.h> #include <wx/combobox.h> #include <wx/msgdlg.h> #include <wx/wupdlock.h> #include "input/ControllerFactory.h" wxDEFINE_EVENT(wxControllersRefreshed, wxCommandEvent); using wxTypeData = wxCustomData<InputAPI::Type>; using wxControllerData = wxCustomData<ControllerPtr>; InputAPIAddWindow::InputAPIAddWindow(wxWindow* parent, const wxPoint& position, const std::vector<ControllerPtr>& controllers) : wxDialog(parent, wxID_ANY, "Add input API", position, wxDefaultSize, 0), m_controllers(controllers) { this->SetSizeHints(wxDefaultSize, wxDefaultSize); auto* sizer = new wxBoxSizer(wxVERTICAL); { auto* api_row = new wxFlexGridSizer(2); // API api_row->Add(new wxStaticText(this, wxID_ANY, _("API")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_input_api = new wxChoice(this, wxID_ANY); auto& providers = InputManager::instance().get_api_providers(); for (const auto& p : providers) { if (p.empty()) continue; const auto provider = *p.begin(); m_input_api->Append(to_wxString(provider->api_name()), new wxTypeData(provider->api())); } m_input_api->Bind(wxEVT_CHOICE, &InputAPIAddWindow::on_api_selected, this); api_row->Add(m_input_api, 1, wxALL | wxEXPAND, 5); // Controller api_row->Add(new wxStaticText(this, wxID_ANY, _("Controller")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_controller_list = new wxComboBox(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, nullptr, wxCB_READONLY); m_controller_list->Bind(wxEVT_COMBOBOX_DROPDOWN, &InputAPIAddWindow::on_controller_dropdown, this); m_controller_list->Bind(wxEVT_COMBOBOX, &InputAPIAddWindow::on_controller_selected, this); m_controller_list->SetMinSize(wxSize(240, -1)); m_controller_list->Disable(); api_row->Add(m_controller_list, 1, wxALL | wxEXPAND, 5); sizer->Add(api_row, 0, wxEXPAND, 5); } sizer->Add(new wxStaticLine(this), 0, wxEXPAND); { auto* end_row = new wxBoxSizer(wxHORIZONTAL); m_ok_button = new wxButton(this, wxID_ANY, _("Add")); m_ok_button->Bind(wxEVT_BUTTON, &InputAPIAddWindow::on_add_button, this); m_ok_button->Disable(); end_row->Add(m_ok_button, 0, wxALL, 5); auto* cancel_button = new wxButton(this, wxID_ANY, _("Cancel")); cancel_button->Bind(wxEVT_BUTTON, &InputAPIAddWindow::on_close_button, this); end_row->Add(cancel_button, 0, wxALL, 5); sizer->Add(end_row, 0, wxEXPAND, 5); } { // optional settings m_settings_panel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); auto* panel_sizer = new wxBoxSizer(wxVERTICAL); panel_sizer->Add(new wxStaticLine(m_settings_panel), 0, wxEXPAND, 0); { auto* row = new wxBoxSizer(wxHORIZONTAL); // we only have dsu settings atm, so add elements now row->Add(new wxStaticText(m_settings_panel, wxID_ANY, _("IP")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_ip = new wxTextCtrl(m_settings_panel, wxID_ANY, "127.0.0.1"); row->Add(m_ip, 0, wxALL, 5); row->Add(new wxStaticText(m_settings_panel, wxID_ANY, _("Port")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_port = new wxTextCtrl(m_settings_panel, wxID_ANY, "26760"); row->Add(m_port, 0, wxALL, 5); panel_sizer->Add(row, 0, wxEXPAND); } m_settings_panel->SetSizer(panel_sizer); m_settings_panel->Layout(); m_settings_panel->Hide(); sizer->Add(m_settings_panel, 1, wxEXPAND); } this->SetSizer(sizer); this->Layout(); sizer->Fit(this); this->Bind(wxControllersRefreshed, &InputAPIAddWindow::on_controllers_refreshed, this); } InputAPIAddWindow::~InputAPIAddWindow() { discard_thread_result(); } void InputAPIAddWindow::on_add_button(wxCommandEvent& event) { const auto selection = m_input_api->GetSelection(); if (selection == wxNOT_FOUND) { cemu_assert_debug(false); EndModal(wxID_CANCEL); return; } for (const auto& c : m_controllers) { if (*c == *m_controller) { wxMessageBox(_("The controller is already added!"), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } } m_type = static_cast<wxTypeData*>(m_input_api->GetClientObject(selection))->get(); EndModal(wxID_OK); } void InputAPIAddWindow::on_close_button(wxCommandEvent& event) { EndModal(wxID_CANCEL); } bool InputAPIAddWindow::has_custom_settings() const { const auto selection = m_input_api->GetStringSelection(); return selection == to_wxString(to_string(InputAPI::DSUClient)); } std::unique_ptr<ControllerProviderSettings> InputAPIAddWindow::get_settings() const { if (!has_custom_settings()) return {}; return std::make_unique<DSUProviderSettings>(m_ip->GetValue().ToStdString(), ConvertString<uint16>(m_port->GetValue().ToStdString())); } void InputAPIAddWindow::on_api_selected(wxCommandEvent& event) { discard_thread_result(); if (m_input_api->GetSelection() == wxNOT_FOUND) return; m_controller_list->Enable(); m_controller_list->SetSelection(wxNOT_FOUND); const auto selection = m_input_api->GetStringSelection(); // keyboard is a special case, as theres only one device supported atm if (selection == to_wxString(to_string(InputAPI::Keyboard))) { const auto controllers = InputManager::instance().get_api_provider(InputAPI::Keyboard)->get_controllers(); if (!controllers.empty()) { m_controller = controllers[0]; m_ok_button->Enable(); m_controller_list->Clear(); const auto display_name = controllers[0]->display_name(); const auto index = m_controller_list->Append(display_name, new wxCustomData(controllers[0])); m_controller_list->SetSelection(index); } } else { #if BOOST_OS_LINUX // We rely on the wxEVT_COMBOBOX_DROPDOWN event to trigger filling the controller list, // but on wxGTK the dropdown button cannot be clicked if the list is empty // so as a quick and dirty workaround we fill the list here wxCommandEvent tmpCmdEvt; on_controller_dropdown(tmpCmdEvt); #endif } const auto show_settings = has_custom_settings(); // dsu has special settings for ip/port if (show_settings != m_settings_panel->IsShown()) { wxWindowUpdateLocker locker(this); m_settings_panel->Show(show_settings); Layout(); Fit(); } } void InputAPIAddWindow::on_controller_dropdown(wxCommandEvent& event) { if (m_search_running) return; int selection = m_input_api->GetSelection(); if (selection == wxNOT_FOUND) return; const auto type = static_cast<wxAPIType*>(m_input_api->GetClientObject(selection))->get(); auto settings = get_settings(); ControllerProviderPtr provider; if (settings) provider = InputManager::instance().get_api_provider(type, *settings); else provider = InputManager::instance().get_api_provider(type); if (!provider) return; std::string selected_uuid; selection = m_controller_list->GetSelection(); if (selection != wxNOT_FOUND) { // TODO selected_uuid } m_search_running = true; wxWindowUpdateLocker lock(m_controller_list); m_controller_list->Clear(); m_controller_list->Append(_("Searching for controllers..."), (wxClientData*)nullptr); m_controller_list->SetSelection(wxNOT_FOUND); m_search_thread_data = std::make_unique<AsyncThreadData>(); std::thread([this, provider, selected_uuid](std::shared_ptr<AsyncThreadData> data) { auto available_controllers = provider->get_controllers(); { std::lock_guard lock{data->mutex}; if(!data->discardResult) { wxCommandEvent event(wxControllersRefreshed); event.SetEventObject(m_controller_list); event.SetClientObject(new wxCustomData(std::move(available_controllers))); event.SetInt(provider->api()); event.SetString(selected_uuid); wxPostEvent(this, event); m_search_running = false; } } }, m_search_thread_data).detach(); } void InputAPIAddWindow::on_controller_selected(wxCommandEvent& event) { if (m_search_running) { return; } const auto selection = m_controller_list->GetSelection(); if (selection == wxNOT_FOUND) { return; } if (auto* controller = (wxControllerData*)m_controller_list->GetClientObject(selection)) { m_controller = controller->ref(); m_ok_button->Enable(); } } void InputAPIAddWindow::on_controllers_refreshed(wxCommandEvent& event) { const auto type = event.GetInt(); wxASSERT(0 <= type && type < InputAPI::MAX); auto* controllers = dynamic_cast<wxComboBox*>(event.GetEventObject()); wxASSERT(controllers); const auto available_controllers = static_cast<wxCustomData<std::vector<std::shared_ptr<ControllerBase>>>*>(event. GetClientObject())->get(); const auto selected_uuid = event.GetString().ToStdString(); bool item_selected = false; wxWindowUpdateLocker lock(controllers); controllers->Clear(); for (const auto& c : available_controllers) { const auto display_name = c->display_name(); const auto uuid = c->uuid(); const auto index = controllers->Append(display_name, new wxCustomData(c)); if (!item_selected && selected_uuid == uuid) { controllers->SetSelection(index); item_selected = true; } } } void InputAPIAddWindow::discard_thread_result() { m_search_running = false; if(m_search_thread_data) { std::lock_guard lock{m_search_thread_data->mutex}; m_search_thread_data->discardResult = true; } }
9,562
C++
.cpp
265
32.856604
115
0.722282
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,981
InputSettings2.cpp
cemu-project_Cemu/src/gui/input/InputSettings2.cpp
#include "gui/input/InputSettings2.h" #include <wx/gbsizer.h> #include "input/InputManager.h" #include "gui/helpers/wxHelpers.h" #include "gui/helpers/wxControlObject.h" #include "gui/helpers/wxCustomData.h" #include <wx/sizer.h> #include <wx/notebook.h> #include <wx/wupdlock.h> #include <wx/stattext.h> #include <wx/combobox.h> #include <wx/button.h> #include <wx/statline.h> #include <wx/bmpbuttn.h> #include "config/ActiveSettings.h" #include "gui/input/InputAPIAddWindow.h" #include "input/ControllerFactory.h" #include "gui/input/panels/VPADInputPanel.h" #include "gui/input/panels/ProControllerInputPanel.h" #include "gui/input/settings/DefaultControllerSettings.h" #include "gui/input/panels/ClassicControllerInputPanel.h" #include "gui/input/panels/WiimoteInputPanel.h" #include "gui/input/settings/WiimoteControllerSettings.h" #include "util/EventService.h" #include "resource/embedded/resources.h" bool g_inputConfigWindowHasFocus = false; using wxTypeData = wxCustomData<EmulatedController::Type>; using wxControllerData = wxCustomData<ControllerPtr>; struct ControllerPage { EmulatedControllerPtr m_controller; // profiles wxComboBox* m_profiles; wxButton* m_profile_load, * m_profile_save, * m_profile_delete; wxStaticText* m_profile_status; // emulated controller wxComboBox* m_emulated_controller; // controller api wxComboBox* m_controllers; wxButton* m_controller_api_add, *m_controller_api_remove; wxButton* m_controller_settings, * m_controller_calibrate, *m_controller_clear; wxBitmapButton* m_controller_connected; // panel std::array<InputPanel*, EmulatedController::Type::MAX> m_panels{}; }; using wxControllerPageData = wxCustomData<ControllerPage>; InputSettings2::InputSettings2(wxWindow* parent) : wxDialog(parent, wxID_ANY, _("Input settings")) { this->SetSizeHints(wxDefaultSize, wxDefaultSize); g_inputConfigWindowHasFocus = true; m_connected = wxBITMAP_PNG_FROM_DATA(INPUT_CONNECTED); m_disconnected = wxBITMAP_PNG_FROM_DATA(INPUT_DISCONNECTED); m_low_battery = wxBITMAP_PNG_FROM_DATA(INPUT_LOW_BATTERY); auto* sizer = new wxBoxSizer(wxVERTICAL); m_notebook = new wxNotebook(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0); for(size_t i = 0; i < InputManager::kMaxController; ++i) { auto* page = new wxPanel(m_notebook, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); page->SetClientObject(nullptr); // force internal type to client object m_notebook->AddPage(page, formatWxString(_("Controller {}"), i + 1)); } m_notebook->Bind(wxEVT_NOTEBOOK_PAGE_CHANGED, &InputSettings2::on_controller_page_changed, this); sizer->Add(m_notebook, 1, wxEXPAND); m_notebook->SetSelection(0); auto* first_page = initialize_page(0); // init first/default page for fitting size auto* page_data = (wxControllerPageData*)first_page->GetClientObject(); auto* panel = new VPADInputPanel(first_page); page_data->ref().m_panels[EmulatedController::Type::VPAD] = panel; auto* first_page_sizer = dynamic_cast<wxGridBagSizer*>(first_page->GetSizer()); auto* panel_sizer = first_page_sizer->FindItemAtPosition(wxGBPosition(7, 0))->GetSizer(); panel_sizer->Add(panel, 0, wxEXPAND); panel->Show(); first_page->Layout(); SetSizer(sizer); Layout(); Fit(); panel->Hide(); update_state(); Bind(wxEVT_TIMER, &InputSettings2::on_timer, this); m_timer = new wxTimer(this); m_timer->Start(25); m_controller_changed = EventService::instance().connect<Events::ControllerChanged>(&InputSettings2::on_controller_changed, this); } InputSettings2::~InputSettings2() { m_controller_changed.disconnect(); g_inputConfigWindowHasFocus = false; m_timer->Stop(); InputManager::instance().save(); } wxWindow* InputSettings2::initialize_page(size_t index) { auto* page = m_notebook->GetPage(index); if (page->GetClientObject()) // already initialized return page; page->Bind(wxEVT_LEFT_UP, &InputSettings2::on_left_click, this); ControllerPage page_data{}; const auto emulated_controller = InputManager::instance().get_controller(index); page_data.m_controller = emulated_controller; wxWindowUpdateLocker lock(page); auto* sizer = new wxGridBagSizer(); { // profile sizer->Add(new wxStaticText(page, wxID_ANY, _("Profile"), wxDefaultPosition, wxDefaultSize, 0), wxGBPosition(0, 0), wxDefaultSpan, wxALIGN_CENTER_VERTICAL | wxALL, 5); auto* profiles = new wxComboBox(page, wxID_ANY, kDefaultProfileName); sizer->Add(profiles, wxGBPosition(0, 1), wxDefaultSpan, wxALIGN_CENTER_VERTICAL | wxALL | wxEXPAND, 5); #if BOOST_OS_LINUX // We rely on the wxEVT_COMBOBOX_DROPDOWN event to trigger filling the profile list, // but on wxGTK the dropdown button cannot be clicked if the list is empty // so as a quick and dirty workaround we fill the list here wxCommandEvent tmpCmdEvt; tmpCmdEvt.SetEventObject(profiles); on_profile_dropdown(tmpCmdEvt); #endif if (emulated_controller && emulated_controller->has_profile_name()) { profiles->SetValue(emulated_controller->get_profile_name()); } auto* load_bttn = new wxButton(page, wxID_ANY, _("Load")); load_bttn->Disable(); sizer->Add(load_bttn, wxGBPosition(0, 2), wxDefaultSpan, wxALIGN_CENTER_VERTICAL | wxALL, 5); auto* save_bttn = new wxButton(page, wxID_ANY, _("Save")); save_bttn->Disable(); sizer->Add(save_bttn, wxGBPosition(0, 3), wxDefaultSpan, wxALIGN_CENTER_VERTICAL | wxALL, 5); auto* delete_bttn = new wxButton(page, wxID_ANY, _("Delete")); delete_bttn->Disable(); sizer->Add(delete_bttn, wxGBPosition(0, 4), wxDefaultSpan, wxALIGN_CENTER_VERTICAL | wxALL, 5); auto* profile_status = new wxStaticText(page, wxID_ANY, _("controller set by gameprofile. changes won't be saved permanently!"), wxDefaultPosition, wxDefaultSize, 0); profile_status->SetMinSize(wxSize(200, -1)); profile_status->Wrap(200); sizer->Add(profile_status, wxGBPosition(0, 5), wxDefaultSpan, wxALIGN_CENTER_VERTICAL | wxALL | wxRESERVE_SPACE_EVEN_IF_HIDDEN, 5); if(InputManager::instance().is_gameprofile_set(index)) { profile_status->SetForegroundColour(wxTheColourDatabase->Find("ERROR")); } else { profile_status->Hide(); } load_bttn->Bind(wxEVT_BUTTON, &InputSettings2::on_profile_load, this); save_bttn->Bind(wxEVT_BUTTON, &InputSettings2::on_profile_save, this); delete_bttn->Bind(wxEVT_BUTTON, &InputSettings2::on_profile_delete, this); profiles->Bind(wxEVT_COMBOBOX_DROPDOWN, &InputSettings2::on_profile_dropdown, this); profiles->Bind(wxEVT_TEXT, &InputSettings2::on_profile_text_changed, this); page_data.m_profiles = profiles; page_data.m_profile_load = load_bttn; page_data.m_profile_save = save_bttn; page_data.m_profile_delete = delete_bttn; page_data.m_profile_status = profile_status; } sizer->Add(new wxStaticLine(page), wxGBPosition(1, 0), wxGBSpan(1, 6), wxEXPAND); { // emulated controller sizer->Add(new wxStaticText(page, wxID_ANY, _("Emulated controller")), wxGBPosition(2, 0), wxDefaultSpan, wxALIGN_CENTER_VERTICAL | wxALL, 5); auto* econtroller_box = new wxComboBox(page, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, nullptr, wxCB_READONLY); econtroller_box->SetMinSize(wxSize(200, -1)); econtroller_box->Bind(wxEVT_COMBOBOX_DROPDOWN, &InputSettings2::on_emulated_controller_dropdown, this); econtroller_box->Bind(wxEVT_COMBOBOX, &InputSettings2::on_emulated_controller_selected, this); econtroller_box->AppendString(_("Disabled")); econtroller_box->SetSelection(0); sizer->Add(econtroller_box, wxGBPosition(2, 1), wxDefaultSpan, wxALIGN_CENTER_VERTICAL | wxALL | wxEXPAND, 5); page_data.m_emulated_controller = econtroller_box; } sizer->Add(new wxStaticLine(page), wxGBPosition(3, 0), wxGBSpan(1, 6), wxEXPAND); { // controller api sizer->Add(new wxStaticText(page, wxID_ANY, _("Controller")), wxGBPosition(4, 0), wxDefaultSpan, wxALIGN_CENTER_VERTICAL | wxALL, 5); auto* controllers = new wxComboBox(page, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0, nullptr, wxCB_READONLY); controllers->Bind(wxEVT_COMBOBOX, &InputSettings2::on_controller_selected, this); controllers->Bind(wxEVT_COMBOBOX_DROPDOWN, &InputSettings2::on_controller_dropdown, this); controllers->SetMinSize(wxSize(300, -1)); page_data.m_controllers = controllers; sizer->Add(controllers, wxGBPosition(4, 1), wxDefaultSpan, wxALIGN_CENTER_VERTICAL | wxALL | wxEXPAND, 5); { // add/remove buttons auto* bttn_sizer = new wxBoxSizer(wxHORIZONTAL); auto* add_api = new wxButton(page, wxID_ANY, " + ", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); add_api->Bind(wxEVT_BUTTON, &InputSettings2::on_controller_add, this); bttn_sizer->Add(add_api, 0, wxALL, 5); auto* remove_api = new wxButton(page, wxID_ANY, " - ", wxDefaultPosition, wxDefaultSize, wxBU_EXACTFIT); remove_api->Bind(wxEVT_BUTTON, &InputSettings2::on_controller_remove, this); bttn_sizer->Add(remove_api, 0, wxALL, 5); sizer->Add(bttn_sizer, wxGBPosition(4, 2), wxDefaultSpan, wxEXPAND, 5); page_data.m_controller_api_add = add_api; page_data.m_controller_api_remove = remove_api; } // controller auto* controller_bttns = new wxBoxSizer(wxHORIZONTAL); auto* settings = new wxButton(page, wxID_ANY, _("Settings"), wxDefaultPosition, wxDefaultSize, 0); settings->Bind(wxEVT_BUTTON, &InputSettings2::on_controller_settings, this); settings->Disable(); controller_bttns->Add(settings, 0, wxALL, 5); auto* calibrate = new wxButton(page, wxID_ANY, _("Calibrate"), wxDefaultPosition, wxDefaultSize, 0); calibrate->Bind(wxEVT_BUTTON, &InputSettings2::on_controller_calibrate, this); calibrate->Disable(); controller_bttns->Add(calibrate, 0, wxALL, 5); auto* clear = new wxButton(page, wxID_ANY, _("Clear"), wxDefaultPosition, wxDefaultSize, 0); clear->Bind(wxEVT_BUTTON, &InputSettings2::on_controller_clear, this); controller_bttns->Add(clear, 0, wxALL, 5); sizer->Add(controller_bttns, wxGBPosition(5, 1), wxDefaultSpan, wxALIGN_CENTER_VERTICAL); auto* connected_button = new wxBitmapButton(page, wxID_ANY, m_disconnected); connected_button->Bind(wxEVT_BUTTON, &InputSettings2::on_controller_connect, this); connected_button->SetToolTip(_("Test if the controller is connected")); sizer->Add(connected_button, wxGBPosition(5, 2), wxDefaultSpan, wxALIGN_CENTER_VERTICAL | wxALL, 5); // TODO replace with icon page_data.m_controller_settings = settings; page_data.m_controller_calibrate = calibrate; page_data.m_controller_clear = clear; page_data.m_controller_connected = connected_button; } sizer->Add(new wxStaticLine(page), wxGBPosition(6, 0), wxGBSpan(1, 6), wxEXPAND); auto* panel_sizer = new wxBoxSizer(wxVERTICAL); sizer->Add(panel_sizer, wxGBPosition(7, 0), wxGBSpan(1, 6), wxEXPAND | wxALL, 5); page->SetSizer(sizer); page->Layout(); page->SetClientObject(new wxCustomData(page_data)); return page; } std::shared_ptr<ControllerBase> InputSettings2::get_active_controller() const { auto& page_data = get_current_page_data(); const auto selection = page_data.m_controllers->GetSelection(); if(selection != wxNOT_FOUND) { if(auto* controller = (wxControllerData*)page_data.m_controllers->GetClientObject(selection)) return controller->ref(); } return {}; } bool InputSettings2::has_settings(InputAPI::Type type) { switch(type) { case InputAPI::Keyboard: return false; default: return true; } } void InputSettings2::update_state() { auto* page = m_notebook->GetCurrentPage(); wxWindowUpdateLocker lock(page); auto* page_data_ptr = (wxControllerPageData*)page->GetClientObject(); wxASSERT(page_data_ptr); auto& page_data = page_data_ptr->ref(); page_data.m_profile_status->Hide(); EmulatedControllerPtr emulated_controller = page_data.m_controller; auto has_controllers = false; // update emulated if(emulated_controller) { has_controllers = !emulated_controller->get_controllers().empty(); const auto emulated_type = emulated_controller->type(); int index = page_data.m_emulated_controller->Append(to_wxString(emulated_controller->type_to_string(emulated_type))); page_data.m_emulated_controller->SetSelection(index); const auto controller_selection = page_data.m_controllers->GetStringSelection(); page_data.m_controllers->Clear(); if (has_controllers) { for (const auto& c : emulated_controller->get_controllers()) { page_data.m_controllers->Append(fmt::format("{} [{}]", c->display_name(), c->api_name()), new wxCustomData(c)); } if (page_data.m_controllers->GetCount() > 0) { page_data.m_controllers->SetSelection(0); if (!controller_selection.empty()) page_data.m_controllers->SetStringSelection(controller_selection); } } } else { page_data.m_emulated_controller->SetValue(_("Disabled")); } ControllerPtr controller; if (page_data.m_controllers->GetSelection() != wxNOT_FOUND) { if (const auto data = (wxControllerData*)page_data.m_controllers->GetClientObject(page_data.m_controllers->GetSelection())) controller = data->ref(); } if (controller && controller->is_connected()) page_data.m_controller_connected->SetBitmap(m_connected); else page_data.m_controller_connected->SetBitmap(m_disconnected); // update controller page_data.m_controller_calibrate->Enable(has_controllers); page_data.m_controller_api_remove->Enable(has_controllers); page_data.m_controller_settings->Enable(controller && has_settings(controller->api())); // update settings // update panel // test if we need to update to correct panel std::optional<EmulatedController::Type> active_api{}; for(auto i = 0; i < EmulatedController::Type::MAX; ++i) { if(page_data.m_panels[i] && page_data.m_panels[i]->IsShown()) { active_api = (EmulatedController::Type)i; break; } } // disabled and no emulated controller if (!active_api && !emulated_controller) return; // enabled correct panel for active controller if (active_api && emulated_controller && emulated_controller->type() == active_api.value()) { // same controller type panel already shown, refresh content of panels for (auto* panel : page_data.m_panels) { if (panel) panel->load_controller(page_data.m_controller); } return; } // hide all panels for (auto* panel : page_data.m_panels) { if (panel) panel->Hide(); } // show required panel if (emulated_controller) { auto* sizer = dynamic_cast<wxGridBagSizer*>(page->GetSizer()); wxASSERT(sizer); const auto type = page_data.m_controller->type(); InputPanel* panel = page_data.m_panels[type]; if (!panel) { switch (type) { case EmulatedController::Type::VPAD: panel = new VPADInputPanel(page); break; case EmulatedController::Pro: panel = new ProControllerInputPanel(page); break; case EmulatedController::Classic: panel = new ClassicControllerInputPanel(page); break; case EmulatedController::Wiimote: panel = new WiimoteInputPanel(page); break; default: cemu_assert_debug(false); return; } page_data.m_panels[type] = panel; auto* panel_sizer = sizer->FindItemAtPosition(wxGBPosition(7, 0))->GetSizer(); wxASSERT(panel_sizer); panel_sizer->Add(panel, 0, wxEXPAND); } panel->load_controller(page_data.m_controller); if (has_controllers) panel->set_selected_controller(emulated_controller, emulated_controller->get_controllers()[0]); panel->Show(); page->wxWindowBase::Layout(); page->wxWindow::Update(); } } void InputSettings2::on_controller_changed() { for(auto i = 0 ; i < m_notebook->GetPageCount(); ++i) { auto* page = m_notebook->GetPage(i); if (!page) continue; auto* page_data_ptr = (wxControllerPageData*)page->GetClientObject(); if (!page_data_ptr) continue; const auto& page_data = page_data_ptr->ref(); if (page_data.m_controllers->GetSelection() != wxNOT_FOUND) { if (const auto data = (wxControllerData*)page_data.m_controllers->GetClientObject(page_data.m_controllers->GetSelection())) { if (const auto controller = data->ref()) { if (controller->connect()) page_data.m_controller_connected->SetBitmap(m_connected); else page_data.m_controller_connected->SetBitmap(m_disconnected); } } } } } void InputSettings2::on_notebook_page_changed(wxBookCtrlEvent& event) { initialize_page(event.GetSelection()); update_state(); event.Skip(); } void InputSettings2::on_timer(wxTimerEvent&) { auto& page_data = get_current_page_data(); if (!page_data.m_controller) { return; } auto* panel = page_data.m_panels[page_data.m_controller->type()]; if (!panel) return; auto controller = get_active_controller(); if (controller) { panel->on_timer(page_data.m_controller, controller); } } void InputSettings2::on_left_click(wxMouseEvent& event) { event.Skip(); auto& page_data = get_current_page_data(); if (!page_data.m_controller) { return; } auto* panel = page_data.m_panels[page_data.m_controller->type()]; if (!panel) return; panel->on_left_click(event); } void InputSettings2::on_profile_dropdown(wxCommandEvent& event) { auto* profile_names = dynamic_cast<wxComboBox*>(event.GetEventObject()); wxASSERT(profile_names); wxWindowUpdateLocker lock(profile_names); const auto selected_value = profile_names->GetStringSelection(); profile_names->Clear(); for(const auto& profile : InputManager::get_profiles()) { profile_names->Append(wxString::FromUTF8(profile)); } profile_names->SetStringSelection(selected_value); } void InputSettings2::on_profile_text_changed(wxCommandEvent& event) { auto* profile_names = dynamic_cast<wxComboBox*>(event.GetEventObject()); wxASSERT(profile_names); auto& page_data = get_current_page_data(); // load_bttn, save_bttn, delete_bttn, profile_status const auto text = event.GetString(); const bool valid_name = InputManager::is_valid_profilename(text.utf8_string()); const bool name_exists = profile_names->FindString(text) != wxNOT_FOUND; page_data.m_profile_load->Enable(name_exists); page_data.m_profile_save->Enable(valid_name); page_data.m_profile_delete->Enable(name_exists); page_data.m_profile_status->Hide(); } void InputSettings2::on_profile_load(wxCommandEvent& event) { auto& page_data = get_current_page_data(); auto* profile_names = page_data.m_profiles; auto* text = page_data.m_profile_status; const auto selection = profile_names->GetValue().utf8_string(); text->Show(); if (selection.empty() || !InputManager::is_valid_profilename(selection)) { text->SetLabelText(_("invalid profile name")); text->SetForegroundColour(wxTheColourDatabase->Find("ERROR")); text->Refresh(); return; } const auto page_index = m_notebook->GetSelection(); if (InputManager::instance().load(page_index, selection)) { text->SetLabelText(_("profile loaded")); text->SetForegroundColour(wxTheColourDatabase->Find("SUCCESS")); } else { text->SetLabelText(_("couldn't load profile")); text->SetForegroundColour(wxTheColourDatabase->Find("ERROR")); } text->Refresh(); // update controller info page_data.m_controller = InputManager::instance().get_controller(page_index); update_state(); } void InputSettings2::on_profile_save(wxCommandEvent& event) { auto& page_data = get_current_page_data(); auto* profile_names = page_data.m_profiles; auto* text = page_data.m_profile_status; const auto selection = profile_names->GetValue().utf8_string(); text->Show(); if (selection.empty() || !InputManager::is_valid_profilename(selection)) { text->SetLabelText(_("invalid profile name")); text->SetForegroundColour(wxTheColourDatabase->Find("ERROR")); text->Refresh(); return; } if(InputManager::instance().save(m_notebook->GetSelection(), selection)) { text->SetLabelText(_("profile saved")); text->SetForegroundColour(wxTheColourDatabase->Find("SUCCESS")); } else { text->SetLabelText(_("couldn't save profile")); text->SetForegroundColour(wxTheColourDatabase->Find("ERROR")); } text->Refresh(); } void InputSettings2::on_profile_delete(wxCommandEvent& event) { auto& page_data = get_current_page_data(); auto* profile_names = page_data.m_profiles; auto* text = page_data.m_profile_status; const auto selection = profile_names->GetStringSelection().utf8_string(); text->Show(); if (selection.empty() || !InputManager::is_valid_profilename(selection)) { text->SetLabelText(_("invalid profile name")); text->SetForegroundColour(wxTheColourDatabase->Find("ERROR")); text->Refresh(); return; } try { const fs::path old_path = ActiveSettings::GetConfigPath("controllerProfiles/{}.txt", selection); fs::remove(old_path); const fs::path path = ActiveSettings::GetConfigPath("controllerProfiles/{}.xml", selection); fs::remove(path); profile_names->ChangeValue(kDefaultProfileName); text->SetLabelText(_("profile deleted")); text->SetForegroundColour(wxTheColourDatabase->Find("SUCCESS")); page_data.m_profile_load->Disable(); page_data.m_profile_save->Disable(); page_data.m_profile_delete->Disable(); } catch (const std::exception&) { text->SetLabelText(_("can't delete profile")); text->SetForegroundColour(wxTheColourDatabase->Find("ERROR")); } text->Refresh(); } void InputSettings2::on_controller_page_changed(wxBookCtrlEvent& event) { initialize_page(event.GetSelection()); update_state(); event.Skip(); } void InputSettings2::on_emulated_controller_selected(wxCommandEvent& event) { const auto page_index = m_notebook->GetSelection(); auto& page_data = get_current_page_data(); const auto selection = event.GetSelection(); if(selection == 0) // disabled selected { page_data.m_controller = {}; InputManager::instance().delete_controller(page_index, true); } else { try { const auto type = EmulatedController::type_from_string(event.GetString().utf8_string()); // same has already been selected if (page_data.m_controller && page_data.m_controller->type() == type) return; // set new controller const auto new_controller = InputManager::instance().set_controller(page_index, type); page_data.m_controller = new_controller; // append controllers if some were already added before if (new_controller->get_controllers().empty()) { // test if we had no emulated controller before but still assigned controllers we want to transfer now for (uint32 i = 0; i < page_data.m_controllers->GetCount(); ++i) { if (auto* controller = (wxControllerData*)page_data.m_controllers->GetClientObject(i)) { new_controller->add_controller(controller->ref()); } } } // set default mappings if any controllers available for(const auto& c: new_controller->get_controllers()) { new_controller->set_default_mapping(c); } } catch (const std::exception&) { cemu_assert_debug(false); } } update_state(); } void InputSettings2::on_emulated_controller_dropdown(wxCommandEvent& event) { auto* emulated_controllers = dynamic_cast<wxComboBox*>(event.GetEventObject()); wxASSERT(emulated_controllers); wxWindowUpdateLocker lock(emulated_controllers); bool is_gamepad_selected = false; bool is_wpad_selected = false; const auto selected = emulated_controllers->GetSelection(); const auto selected_value = emulated_controllers->GetStringSelection(); if(selected != wxNOT_FOUND) { is_gamepad_selected = selected_value == to_wxString(EmulatedController::type_to_string(EmulatedController::Type::VPAD)); is_wpad_selected = !is_gamepad_selected && selected != 0; } const auto [vpad_count, wpad_count] = InputManager::instance().get_controller_count(); emulated_controllers->Clear(); emulated_controllers->AppendString(_("Disabled")); if (vpad_count < InputManager::kMaxVPADControllers || is_gamepad_selected) emulated_controllers->Append(to_wxString(EmulatedController::type_to_string(EmulatedController::Type::VPAD))); if (wpad_count < InputManager::kMaxWPADControllers || is_wpad_selected) { emulated_controllers->AppendString(to_wxString(EmulatedController::type_to_string(EmulatedController::Type::Pro))); emulated_controllers->AppendString(to_wxString(EmulatedController::type_to_string(EmulatedController::Type::Classic))); emulated_controllers->AppendString(to_wxString(EmulatedController::type_to_string(EmulatedController::Type::Wiimote))); } emulated_controllers->SetStringSelection(selected_value); } void InputSettings2::on_controller_selected(wxCommandEvent& event) { auto& page_data = get_current_page_data(); const auto enabled = event.GetSelection() != wxNOT_FOUND; page_data.m_controller_api_remove->Enable(enabled); // page_data->ref().m_controller_list->Clear(); if(enabled) { // get selected controller if any todo if (auto* controller = (wxControllerData*)page_data.m_controllers->GetClientObject(event.GetSelection())) { page_data.m_controller_settings->Enable(has_settings(controller->ref()->api())); if(page_data.m_controller) { page_data.m_panels[page_data.m_controller->type()]->set_selected_controller(page_data.m_controller, controller->ref()); } } } } void InputSettings2::on_controller_dropdown(wxCommandEvent& event) { if(auto* controllers = dynamic_cast<wxComboBox*>(event.GetEventObject())) { if(controllers->GetCount()== 0) { on_controller_add(event); controllers->SetSelection(0); } } } ControllerPage& InputSettings2::get_current_page_data() const { auto* page = m_notebook->GetCurrentPage(); auto* page_data_ptr = (wxControllerPageData*)page->GetClientObject(); wxASSERT(page_data_ptr); return page_data_ptr->ref(); } void InputSettings2::on_controller_connect(wxCommandEvent& event) { auto& page_data = get_current_page_data(); if (page_data.m_controllers->GetSelection() != wxNOT_FOUND) { if (const auto data = (wxControllerData*)page_data.m_controllers->GetClientObject(page_data.m_controllers->GetSelection())) { if(const auto controller = data->ref()) { if(controller->connect()) page_data.m_controller_connected->SetBitmap(m_connected); else page_data.m_controller_connected->SetBitmap(m_disconnected); } } } } void InputSettings2::on_controller_add(wxCommandEvent& event) { auto& page_data = get_current_page_data(); std::vector<ControllerPtr> controllers; controllers.reserve(page_data.m_controllers->GetCount()); for(uint32 i = 0; i < page_data.m_controllers->GetCount(); ++i) { if (auto* controller = (wxControllerData*)page_data.m_controllers->GetClientObject(i)) controllers.emplace_back(controller->ref()); } InputAPIAddWindow wnd(this, wxGetMousePosition() + wxSize(5, 5), controllers); if (wnd.ShowModal() != wxID_OK) return; wxASSERT(wnd.is_valid()); const auto controller = wnd.get_controller(); const auto api_type = wnd.get_type(); controller->connect(); const int index = page_data.m_controllers->Append(fmt::format("{} [{}]", controller->display_name(), to_string(api_type)), new wxCustomData(controller)); page_data.m_controllers->Select(index); if(page_data.m_controller) { page_data.m_controller->add_controller(controller); const auto type = page_data.m_controller->type(); // if first controller and we got no mappings, add default mappings if(page_data.m_controller->set_default_mapping(controller)) page_data.m_panels[type]->load_controller(page_data.m_controller); page_data.m_panels[type]->set_selected_controller(page_data.m_controller, controller); } update_state(); } void InputSettings2::on_controller_remove(wxCommandEvent& event) { auto& page_data = get_current_page_data(); auto* api_box = page_data.m_controllers; int selection = api_box->GetSelection(); if (selection == wxNOT_FOUND) return; if (page_data.m_controller) { if (auto* controller = (wxControllerData*)page_data.m_controllers->GetClientObject(selection)) { page_data.m_controller->remove_controller(controller->ref()); page_data.m_panels[page_data.m_controller->type()]->load_controller(page_data.m_controller); } } page_data.m_panels[page_data.m_controller->type()]->reset_colours(); api_box->Delete(selection); api_box->Refresh(); update_state(); if (api_box->GetCount() > 0) { selection = selection > 0 ? (selection - 1) : 0; api_box->SetSelection(selection); } update_state(); } void InputSettings2::on_controller_calibrate(wxCommandEvent& event) { if(const auto controller = get_active_controller()) controller->calibrate(); } void InputSettings2::on_controller_clear(wxCommandEvent& event) { auto& page_data = get_current_page_data(); if (page_data.m_controller) { const auto type = page_data.m_controller->type(); page_data.m_panels[type]->reset_configuration(); page_data.m_controller->clear_mappings(); } } void InputSettings2::on_controller_settings(wxCommandEvent& event) { auto controller = get_active_controller(); if (!controller) return; switch(controller->api()) { case InputAPI::DirectInput: case InputAPI::XInput: case InputAPI::GameCube: case InputAPI::WGIGamepad: case InputAPI::WGIRawController: case InputAPI::SDLController: case InputAPI::DSUClient: { DefaultControllerSettings wnd(this, wxGetMousePosition() + wxSize(5, 5), controller); wnd.ShowModal(); break; } case InputAPI::Keyboard: break; #ifdef SUPPORTS_WIIMOTE case InputAPI::Wiimote: { const auto wiimote = std::dynamic_pointer_cast<NativeWiimoteController>(controller); wxASSERT(wiimote); WiimoteControllerSettings wnd(this, wxGetMousePosition() + wxSize(5, 5), wiimote); wnd.ShowModal(); break; } #endif } }
29,540
C++
.cpp
771
35.562905
169
0.744583
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,982
WiimoteInputPanel.cpp
cemu-project_Cemu/src/gui/input/panels/WiimoteInputPanel.cpp
#include "gui/input/panels/WiimoteInputPanel.h" #include <wx/button.h> #include <wx/gbsizer.h> #include <wx/stattext.h> #include <wx/statline.h> #include <wx/textctrl.h> #include <wx/slider.h> #include <wx/checkbox.h> #include "gui/helpers/wxControlObject.h" #include "input/emulated/WiimoteController.h" #include "gui/helpers/wxHelpers.h" #include "gui/components/wxInputDraw.h" #include "gui/PairingDialog.h" constexpr WiimoteController::ButtonId g_kFirstColumnItems[] = { WiimoteController::kButtonId_A, WiimoteController::kButtonId_B, WiimoteController::kButtonId_1, WiimoteController::kButtonId_2, WiimoteController::kButtonId_Plus, WiimoteController::kButtonId_Minus, WiimoteController::kButtonId_Home }; constexpr WiimoteController::ButtonId g_kSecondColumnItems[] = { WiimoteController::kButtonId_Up, WiimoteController::kButtonId_Down, WiimoteController::kButtonId_Left, WiimoteController::kButtonId_Right }; constexpr WiimoteController::ButtonId g_kThirdColumnItems[] = { WiimoteController::kButtonId_Nunchuck_C, WiimoteController::kButtonId_Nunchuck_Z, WiimoteController::kButtonId_None, WiimoteController::kButtonId_Nunchuck_Up,WiimoteController::kButtonId_Nunchuck_Down,WiimoteController::kButtonId_Nunchuck_Left,WiimoteController::kButtonId_Nunchuck_Right }; WiimoteInputPanel::WiimoteInputPanel(wxWindow* parent) : InputPanel(parent) { auto bold_font = GetFont(); bold_font.MakeBold(); auto* main_sizer = new wxBoxSizer(wxVERTICAL); auto* horiz_main_sizer = new wxBoxSizer(wxHORIZONTAL); auto* pair_button = new wxButton(this, wxID_ANY, _("Pair a Wii or Wii U controller")); pair_button->Bind(wxEVT_BUTTON, &WiimoteInputPanel::on_pair_button, this); horiz_main_sizer->Add(pair_button); horiz_main_sizer->AddSpacer(10); auto* extensions_sizer = new wxBoxSizer(wxHORIZONTAL); horiz_main_sizer->Add(extensions_sizer, wxSizerFlags(0).Align(wxALIGN_CENTER_VERTICAL)); extensions_sizer->Add(new wxStaticText(this, wxID_ANY, _("Extensions:"))); extensions_sizer->AddSpacer(10); m_motion_plus = new wxCheckBox(this, wxID_ANY, _("MotionPlus")); m_motion_plus->Bind(wxEVT_CHECKBOX, &WiimoteInputPanel::on_extension_change, this); extensions_sizer->Add(m_motion_plus); m_nunchuck = new wxCheckBox(this, wxID_ANY, _("Nunchuck")); m_nunchuck->Bind(wxEVT_CHECKBOX, &WiimoteInputPanel::on_extension_change, this); extensions_sizer->Add(m_nunchuck); m_classic = new wxCheckBox(this, wxID_ANY, _("Classic")); m_classic->Bind(wxEVT_CHECKBOX, &WiimoteInputPanel::on_extension_change, this); m_classic->Hide(); extensions_sizer->Add(m_classic); main_sizer->Add(horiz_main_sizer, 0, wxEXPAND | wxALL, 5); main_sizer->Add(new wxStaticLine(this), 0, wxLEFT | wxRIGHT | wxTOP | wxEXPAND, 5); m_item_sizer = new wxGridBagSizer(); sint32 row = 0; sint32 column = 0; for (const auto& id : g_kFirstColumnItems) { row++; add_button_row(row, column, id); } m_item_sizer->Add(new wxStaticLine(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVERTICAL), wxGBPosition(0, column + 2), wxGBSpan(11, 1), wxLEFT | wxRIGHT | wxBOTTOM | wxEXPAND, 5); ////////////////////////////////////////////////////////////////// row = 0; column += 3; auto text = new wxStaticText(this, wxID_ANY, _("D-pad")); text->SetFont(bold_font); m_item_sizer->Add(text, wxGBPosition(row, column), wxGBSpan(1, 3), wxALL | wxEXPAND, 5); for (const auto& id : g_kSecondColumnItems) { row++; add_button_row(row, column, id); } row = 8; // Volume text = new wxStaticText(this, wxID_ANY, _("Volume")); text->Disable(); m_item_sizer->Add(text, wxGBPosition(row, column), wxDefaultSpan, wxALL, 5); m_volume = new wxSlider(this, wxID_ANY, 0, 0, 100); m_volume->Disable(); m_item_sizer->Add(m_volume, wxGBPosition(row, column + 1), wxDefaultSpan, wxTOP | wxBOTTOM | wxEXPAND, 5); const auto volume_text = new wxStaticText(this, wxID_ANY, wxString::Format("%d%%", 0)); volume_text->Disable(); m_item_sizer->Add(volume_text, wxGBPosition(row, column + 2), wxDefaultSpan, wxALL, 5); m_volume->Bind(wxEVT_SLIDER, &WiimoteInputPanel::on_volume_change, this, wxID_ANY, wxID_ANY, new wxControlObject(volume_text)); row++; m_item_sizer->Add(new wxStaticLine(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVERTICAL), wxGBPosition(0, column + 3), wxGBSpan(11, 1), wxLEFT | wxRIGHT | wxBOTTOM | wxEXPAND, 5); ////////////////////////////////////////////////////////////////// row = 0; column += 4; text = new wxStaticText(this, wxID_ANY, _("Nunchuck")); text->SetFont(bold_font); m_item_sizer->Add(text, wxGBPosition(row, column), wxGBSpan(1, 3), wxALL | wxEXPAND, 5); for (const auto& id : g_kThirdColumnItems) { row++; if (id == WiimoteController::kButtonId_None) continue; m_item_sizer->Add( new wxStaticText(this, wxID_ANY, wxGetTranslation(to_wxString(WiimoteController::get_button_name(id)))), wxGBPosition(row, column), wxDefaultSpan, wxALL | wxALIGN_CENTER_VERTICAL, 5); auto* text_ctrl = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL | wxTE_PROCESS_ENTER | wxTE_PROCESS_TAB); text_ctrl->SetClientData((void*)id); text_ctrl->SetMinSize(wxSize(150, -1)); text_ctrl->SetEditable(false); text_ctrl->SetBackgroundColour(kKeyColourNormalMode); bind_hotkey_events(text_ctrl); text_ctrl->Enable(m_nunchuck->GetValue()); m_item_sizer->Add(text_ctrl, wxGBPosition(row, column + 1), wxDefaultSpan, wxALL | wxEXPAND, 5); m_nunchuck_items.push_back(text_ctrl); } // input drawer m_draw = new wxInputDraw(this, wxID_ANY, wxDefaultPosition, { 60, 60 }); m_draw->Enable(m_nunchuck->GetValue()); m_item_sizer->Add(5, 0, wxGBPosition(3, column + 3), wxDefaultSpan, wxTOP | wxBOTTOM | wxEXPAND | wxALIGN_CENTER, 5); m_item_sizer->Add(m_draw, wxGBPosition(3, column + 4), wxGBSpan(4, 1), wxTOP | wxBOTTOM | wxEXPAND | wxALIGN_CENTER, 5); m_nunchuck_items.push_back(m_draw); ////////////////////////////////////////////////////////////////// main_sizer->Add(m_item_sizer, 1, wxEXPAND | wxLEFT | wxRIGHT | wxTOP, 5); SetSizer(main_sizer); Layout(); } void WiimoteInputPanel::add_button_row(sint32 row, sint32 column, const WiimoteController::ButtonId &button_id) { m_item_sizer->Add( new wxStaticText(this, wxID_ANY, wxGetTranslation(to_wxString(WiimoteController::get_button_name(button_id)))), wxGBPosition(row, column), wxDefaultSpan, wxALL | wxALIGN_CENTER_VERTICAL, 5); auto* text_ctrl = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL | wxTE_PROCESS_ENTER | wxTE_PROCESS_TAB); text_ctrl->SetClientData((void*)button_id); text_ctrl->SetMinSize(wxSize(150, -1)); text_ctrl->SetEditable(false); text_ctrl->SetBackgroundColour(kKeyColourNormalMode); bind_hotkey_events(text_ctrl); m_item_sizer->Add(text_ctrl, wxGBPosition(row, column + 1), wxDefaultSpan, wxALL | wxEXPAND, 5); } void WiimoteInputPanel::set_active_device_type(WPADDeviceType type) { m_device_type = type; m_motion_plus->SetValue(type == kWAPDevMPLS || type == kWAPDevMPLSFreeStyle || type == kWAPDevMPLSClassic); switch(type) { case kWAPDevFreestyle: case kWAPDevMPLSFreeStyle: m_nunchuck->SetValue(true); m_classic->SetValue(false); for (const auto& item : m_nunchuck_items) { item->Enable(true); } break; case kWAPDevClassic: case kWAPDevMPLSClassic: m_nunchuck->SetValue(false); m_classic->SetValue(true); for (const auto& item : m_nunchuck_items) { item->Enable(false); } break; default: m_nunchuck->SetValue(false); m_classic->SetValue(false); for (const auto& item : m_nunchuck_items) { item->Enable(false); } } } void WiimoteInputPanel::on_volume_change(wxCommandEvent& event) { } void WiimoteInputPanel::on_extension_change(wxCommandEvent& event) { if(m_motion_plus->GetValue() && m_nunchuck->GetValue()) set_active_device_type(kWAPDevMPLSFreeStyle); else if(m_motion_plus->GetValue() && m_classic->GetValue()) set_active_device_type(kWAPDevMPLSClassic); else if (m_motion_plus->GetValue()) set_active_device_type(kWAPDevMPLS); else if (m_nunchuck->GetValue()) set_active_device_type(kWAPDevFreestyle); else if (m_classic->GetValue()) set_active_device_type(kWAPDevClassic); else set_active_device_type(kWAPDevCore); } void WiimoteInputPanel::on_timer(const EmulatedControllerPtr& emulated_controller, const ControllerPtr& controller) { if (emulated_controller) { const auto wiimote = std::dynamic_pointer_cast<WiimoteController>(emulated_controller); wxASSERT(wiimote); wiimote->set_device_type(m_device_type); } InputPanel::on_timer(emulated_controller, controller); if (emulated_controller) { const auto axis = emulated_controller->get_axis(); m_draw->SetAxisValue(axis); } } void WiimoteInputPanel::load_controller(const EmulatedControllerPtr& emulated_controller) { InputPanel::load_controller(emulated_controller); if (emulated_controller) { const auto wiimote = std::dynamic_pointer_cast<WiimoteController>(emulated_controller); wxASSERT(wiimote); set_active_device_type(wiimote->get_device_type()); } } void WiimoteInputPanel::on_pair_button(wxCommandEvent& event) { PairingDialog pairing_dialog(this); pairing_dialog.ShowModal(); }
9,274
C++
.cpp
219
39.835616
233
0.734474
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,983
VPADInputPanel.cpp
cemu-project_Cemu/src/gui/input/panels/VPADInputPanel.cpp
#include "gui/input/panels/VPADInputPanel.h" #include <wx/gbsizer.h> #include <wx/stattext.h> #include <wx/statline.h> #include <wx/textctrl.h> #include <wx/slider.h> #include <wx/checkbox.h> #include "gui/helpers/wxControlObject.h" #include "gui/helpers/wxHelpers.h" #include "gui/components/wxInputDraw.h" #include "input/emulated/VPADController.h" constexpr VPADController::ButtonId g_kFirstColumnItems[] = { VPADController::kButtonId_A, VPADController::kButtonId_B, VPADController::kButtonId_X, VPADController::kButtonId_Y, VPADController::kButtonId_L, VPADController::kButtonId_R, VPADController::kButtonId_ZL, VPADController::kButtonId_ZR, VPADController::kButtonId_Plus, VPADController::kButtonId_Minus }; constexpr VPADController::ButtonId g_kSecondColumnItems[] = { VPADController::kButtonId_StickL, VPADController::kButtonId_StickL_Up, VPADController::kButtonId_StickL_Down, VPADController::kButtonId_StickL_Left, VPADController::kButtonId_StickL_Right }; constexpr VPADController::ButtonId g_kThirdColumnItems[] = { VPADController::kButtonId_StickR, VPADController::kButtonId_StickR_Up, VPADController::kButtonId_StickR_Down, VPADController::kButtonId_StickR_Left, VPADController::kButtonId_StickR_Right }; constexpr VPADController::ButtonId g_kFourthRowItems[] = { VPADController::kButtonId_Up, VPADController::kButtonId_Down, VPADController::kButtonId_Left, VPADController::kButtonId_Right }; VPADInputPanel::VPADInputPanel(wxWindow* parent) : InputPanel(parent) { auto bold_font = GetFont(); bold_font.MakeBold(); auto* main_sizer = new wxGridBagSizer(); sint32 row = 0; sint32 column = 0; for (const auto& id : g_kFirstColumnItems) { row++; add_button_row(main_sizer, row, column, id); } ////////////////////////////////////////////////////////////////// main_sizer->Add(new wxStaticLine(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVERTICAL), wxGBPosition(0, column + 2), wxGBSpan(11, 1), wxALL | wxEXPAND, 5); row = 0; column += 3; auto text = new wxStaticText(this, wxID_ANY, _("Left Axis")); text->SetFont(bold_font); main_sizer->Add(text, wxGBPosition(row, column), wxGBSpan(1, 3), wxALL | wxEXPAND, 5); for (const auto& id : g_kSecondColumnItems) { row++; add_button_row(main_sizer, row, column, id); } row++; // input drawer m_left_draw = new wxInputDraw(this, wxID_ANY, wxDefaultPosition, { 60, 60 }); main_sizer->Add(m_left_draw, wxGBPosition(row, column + 1), wxGBSpan(2, 1), wxTOP | wxBOTTOM | wxEXPAND | wxALIGN_CENTER, 5); main_sizer->Add(new wxStaticLine(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVERTICAL), wxGBPosition(0, column + 3), wxGBSpan(11, 1), wxALL | wxEXPAND, 5); ////////////////////////////////////////////////////////////////// row = 0; column += 4; text = new wxStaticText(this, wxID_ANY, _("Right Axis")); text->SetFont(bold_font); main_sizer->Add(text, wxGBPosition(row, column), wxGBSpan(1, 3), wxALL | wxEXPAND, 5); for (const auto& id : g_kThirdColumnItems) { row++; add_button_row(main_sizer, row, column, id); } row++; // input drawer m_right_draw = new wxInputDraw(this, wxID_ANY, wxDefaultPosition, { 60, 60 }); main_sizer->Add(m_right_draw, wxGBPosition(row, column + 1), wxGBSpan(2, 1), wxTOP | wxBOTTOM | wxEXPAND | wxALIGN_CENTER, 5); // Volume row = 10; text = new wxStaticText(this, wxID_ANY, _("Volume")); text->Disable(); main_sizer->Add(text, wxGBPosition(row, column), wxDefaultSpan, wxALL, 5); auto*m_volume = new wxSlider(this, wxID_ANY, 0, 0, 100); m_volume->Disable(); main_sizer->Add(m_volume, wxGBPosition(row, column + 1), wxDefaultSpan, wxTOP | wxBOTTOM | wxEXPAND, 5); const auto volume_text = new wxStaticText(this, wxID_ANY, wxString::Format("%d%%", 0)); volume_text->Disable(); main_sizer->Add(volume_text, wxGBPosition(row, column + 2), wxDefaultSpan, wxALL, 5); m_volume->Bind(wxEVT_SLIDER, &VPADInputPanel::OnVolumeChange, this, wxID_ANY, wxID_ANY, new wxControlObject(volume_text)); main_sizer->Add(new wxStaticLine(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVERTICAL), wxGBPosition(0, column + 3), wxGBSpan(11, 1), wxALL | wxEXPAND, 5); ////////////////////////////////////////////////////////////////// row = 0; column += 4; text = new wxStaticText(this, wxID_ANY, _("D-pad")); text->SetFont(bold_font); main_sizer->Add(text, wxGBPosition(row, column), wxGBSpan(1, 3), wxALL | wxEXPAND, 5); for (const auto& id : g_kFourthRowItems) { row++; add_button_row(main_sizer, row, column, id); } // Blow Mic row = 8; add_button_row(main_sizer, row, column, VPADController::kButtonId_Mic, _("blow mic")); row++; add_button_row(main_sizer, row, column, VPADController::kButtonId_Screen, _("show screen")); row++; auto toggleScreenText = new wxStaticText(this, wxID_ANY, _("toggle screen")); main_sizer->Add(toggleScreenText, wxGBPosition(row, column), wxDefaultSpan, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_togglePadViewCheckBox = new wxCheckBox(this, wxID_ANY, {}, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL); wxString toggleScreenTT = _("Makes the \"show screen\" button toggle between the TV and gamepad screens"); m_togglePadViewCheckBox->SetToolTip(toggleScreenTT); toggleScreenText->SetToolTip(toggleScreenTT); main_sizer->Add(m_togglePadViewCheckBox, wxGBPosition(row,column+1), wxDefaultSpan, wxALL | wxEXPAND, 5); ////////////////////////////////////////////////////////////////// SetSizer(main_sizer); Layout(); } void VPADInputPanel::add_button_row(wxGridBagSizer *sizer, sint32 row, sint32 column, const VPADController::ButtonId &button_id) { add_button_row(sizer, row, column, button_id, wxGetTranslation(to_wxString(VPADController::get_button_name(button_id)))); } void VPADInputPanel::add_button_row(wxGridBagSizer *sizer, sint32 row, sint32 column, const VPADController::ButtonId &button_id, const wxString &label) { sizer->Add( new wxStaticText(this, wxID_ANY, label), wxGBPosition(row, column), wxDefaultSpan, wxALL | wxALIGN_CENTER_VERTICAL, 5); auto* text_ctrl = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL | wxTE_PROCESS_ENTER | wxTE_PROCESS_TAB); text_ctrl->SetClientData((void*)button_id); text_ctrl->SetMinSize(wxSize(150, -1)); text_ctrl->SetEditable(false); text_ctrl->SetBackgroundColour(kKeyColourNormalMode); bind_hotkey_events(text_ctrl); sizer->Add(text_ctrl, wxGBPosition(row, column + 1), wxDefaultSpan, wxALL | wxEXPAND, 5); } void VPADInputPanel::on_timer(const EmulatedControllerPtr& emulated_controller, const ControllerPtr& controller_base) { InputPanel::on_timer(emulated_controller, controller_base); static_cast<VPADController*>(emulated_controller.get())->set_screen_toggle(m_togglePadViewCheckBox->GetValue()); if(emulated_controller) { const auto axis = emulated_controller->get_axis(); const auto rotation = emulated_controller->get_rotation(); m_left_draw->SetAxisValue(axis); m_right_draw->SetAxisValue(rotation); } } void VPADInputPanel::OnVolumeChange(wxCommandEvent& event) { } void VPADInputPanel::load_controller(const EmulatedControllerPtr& controller) { InputPanel::load_controller(controller); const bool isToggle = static_cast<VPADController*>(controller.get())->is_screen_active_toggle(); m_togglePadViewCheckBox->SetValue(isToggle); }
7,371
C++
.cpp
157
44.535032
188
0.725014
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,984
ProControllerInputPanel.cpp
cemu-project_Cemu/src/gui/input/panels/ProControllerInputPanel.cpp
#include "gui/input/panels/ProControllerInputPanel.h" #include <wx/gbsizer.h> #include <wx/stattext.h> #include <wx/statline.h> #include <wx/textctrl.h> #include "input/emulated/ProController.h" #include "gui/helpers/wxHelpers.h" #include "gui/components/wxInputDraw.h" const ProController::ButtonId g_kFirstColumnItems[] = { ProController::kButtonId_A, ProController::kButtonId_B, ProController::kButtonId_X, ProController::kButtonId_Y, ProController::kButtonId_L, ProController::kButtonId_R, ProController::kButtonId_ZL, ProController::kButtonId_ZR, ProController::kButtonId_Plus, ProController::kButtonId_Minus }; const ProController::ButtonId g_kSecondColumnItems[] = { ProController::kButtonId_StickL, ProController::kButtonId_StickL_Up, ProController::kButtonId_StickL_Down, ProController::kButtonId_StickL_Left, ProController::kButtonId_StickL_Right }; const ProController::ButtonId g_kThirdColumnItems[] = { ProController::kButtonId_StickR, ProController::kButtonId_StickR_Up, ProController::kButtonId_StickR_Down, ProController::kButtonId_StickR_Left, ProController::kButtonId_StickR_Right }; const ProController::ButtonId g_kFourthRowItems[] = { ProController::kButtonId_Up, ProController::kButtonId_Down, ProController::kButtonId_Left, ProController::kButtonId_Right }; ProControllerInputPanel::ProControllerInputPanel(wxWindow* parent) : InputPanel(parent) { auto bold_font = GetFont(); bold_font.MakeBold(); auto main_sizer = new wxGridBagSizer(); sint32 row = 0; sint32 column = 0; for (auto id : g_kFirstColumnItems) { row++; add_button_row(main_sizer, row, column, id); } ////////////////////////////////////////////////////////////////// main_sizer->Add(new wxStaticLine(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVERTICAL), wxGBPosition(0, column + 2), wxGBSpan(11, 1), wxALL | wxEXPAND, 5); row = 0; column += 3; auto text = new wxStaticText(this, wxID_ANY, _("Left Axis")); text->SetFont(bold_font); main_sizer->Add(text, wxGBPosition(row, column), wxGBSpan(1, 3), wxALL | wxEXPAND, 5); for (auto id : g_kSecondColumnItems) { row++; add_button_row(main_sizer, row, column, id); } row++; // input drawer m_left_draw = new wxInputDraw(this, wxID_ANY, wxDefaultPosition, { 60, 60 }); main_sizer->Add(m_left_draw, wxGBPosition(row, column + 1), wxGBSpan(2, 1), wxTOP | wxBOTTOM | wxEXPAND | wxALIGN_CENTER, 5); main_sizer->Add(new wxStaticLine(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVERTICAL), wxGBPosition(0, column + 3), wxGBSpan(11, 1), wxALL | wxEXPAND, 5); ////////////////////////////////////////////////////////////////// row = 0; column += 4; text = new wxStaticText(this, wxID_ANY, _("Right Axis")); text->SetFont(bold_font); main_sizer->Add(text, wxGBPosition(row, column), wxGBSpan(1, 3), wxALL | wxEXPAND, 5); for (auto id : g_kThirdColumnItems) { row++; add_button_row(main_sizer, row, column, id); } row++; // input drawer m_right_draw = new wxInputDraw(this, wxID_ANY, wxDefaultPosition, { 60, 60 }); main_sizer->Add(m_right_draw, wxGBPosition(row, column + 1), wxGBSpan(2, 1), wxTOP | wxBOTTOM | wxEXPAND | wxALIGN_CENTER, 5); main_sizer->Add(new wxStaticLine(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVERTICAL), wxGBPosition(0, column + 3), wxGBSpan(11, 1), wxALL | wxEXPAND, 5); ////////////////////////////////////////////////////////////////// row = 0; column += 4; text = new wxStaticText(this, wxID_ANY, _("D-pad")); text->SetFont(bold_font); main_sizer->Add(text, wxGBPosition(row, column), wxGBSpan(1, 3), wxALL | wxEXPAND, 5); for (auto id : g_kFourthRowItems) { row++; add_button_row(main_sizer, row, column, id); } ////////////////////////////////////////////////////////////////// SetSizerAndFit(main_sizer); } void ProControllerInputPanel::add_button_row(wxGridBagSizer *sizer, sint32 row, sint32 column, const ProController::ButtonId &button_id) { sizer->Add( new wxStaticText(this, wxID_ANY, wxGetTranslation(to_wxString(ProController::get_button_name(button_id)))), wxGBPosition(row, column), wxDefaultSpan, wxALL | wxALIGN_CENTER_VERTICAL, 5); auto text_ctrl = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL | wxTE_PROCESS_ENTER | wxTE_PROCESS_TAB); text_ctrl->SetClientData((void*)button_id); text_ctrl->SetMinSize(wxSize(150, -1)); text_ctrl->SetEditable(false); text_ctrl->SetBackgroundColour(kKeyColourNormalMode); bind_hotkey_events(text_ctrl); sizer->Add(text_ctrl, wxGBPosition(row, column + 1), wxDefaultSpan, wxALL | wxEXPAND, 5); } void ProControllerInputPanel::on_timer(const EmulatedControllerPtr& emulated_controller, const ControllerPtr& controller_base) { InputPanel::on_timer(emulated_controller, controller_base); if (emulated_controller) { const auto axis = emulated_controller->get_axis(); const auto rotation = emulated_controller->get_rotation(); m_left_draw->SetAxisValue(axis); m_right_draw->SetAxisValue(rotation); } }
5,001
C++
.cpp
98
48.72449
346
0.713288
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,985
InputPanel.cpp
cemu-project_Cemu/src/gui/input/panels/InputPanel.cpp
#include "gui/guiWrapper.h" #include "gui/input/panels/InputPanel.h" #include <wx/textctrl.h> #include <wx/wupdlock.h> #include "gui/helpers/wxHelpers.h" InputPanel::InputPanel(wxWindow* parent) : wxPanel(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL | wxNO_BORDER | wxWANTS_CHARS) { Bind(wxEVT_LEFT_UP, &InputPanel::on_left_click, this); } void InputPanel::on_timer(const EmulatedControllerPtr& emulated_controller, const ControllerPtr& controller) { const auto& state = controller->update_state(); if(m_focused_element == wxID_NONE) { return; } const auto element = dynamic_cast<wxTextCtrl*>(FindWindow(m_focused_element)); wxASSERT(element); const auto mapping = reinterpret_cast<uint64>(element->GetClientData()); // reset mapping if(std::exchange(m_right_down, false) || gui_isKeyDown(PlatformKeyCodes::ESCAPE)) { element->SetBackgroundColour(kKeyColourNormalMode); m_color_backup[element->GetId()] = kKeyColourNormalMode; emulated_controller->delete_mapping(mapping); if(element->IsEmpty()) reset_focused_element(); else element->SetValue(wxEmptyString); return; } static bool s_was_idle = true; if (state.buttons.IsIdle()) { s_was_idle = true; return; } if (!s_was_idle) { return; } s_was_idle = false; for(const auto& id : state.buttons.GetButtonList()) { if (controller->has_axis()) { // test if one axis direction is pressed more than the other if ((id == kAxisXP || id == kAxisXN) && (state.buttons.GetButtonState(kAxisYP) || state.buttons.GetButtonState(kAxisYN))) { if (std::abs(state.axis.y) > std::abs(state.axis.x)) continue; } else if ((id == kAxisYP || id == kAxisYN) && (state.buttons.GetButtonState(kAxisXP) || state.buttons.GetButtonState(kAxisXN))) { if (std::abs(state.axis.x) > std::abs(state.axis.y)) continue; } else if ((id == kRotationXP || id == kRotationXN) && (state.buttons.GetButtonState(kRotationYP) || state.buttons.GetButtonState(kRotationYN))) { if (std::abs(state.rotation.y) > std::abs(state.rotation.x)) continue; } else if ((id == kRotationYP || id == kRotationYN) && (state.buttons.GetButtonState(kRotationXP) || state.buttons.GetButtonState(kRotationXN))) { if (std::abs(state.rotation.x) > std::abs(state.rotation.y)) continue; } else if ((id == kTriggerXP || id == kTriggerXN) && (state.buttons.GetButtonState(kTriggerYP) || state.buttons.GetButtonState(kTriggerYN))) { if (std::abs(state.trigger.y) > std::abs(state.trigger.x)) continue; } else if ((id == kTriggerYP || id == kTriggerYN) && (state.buttons.GetButtonState(kTriggerXP) || state.buttons.GetButtonState(kTriggerXN))) { if (std::abs(state.trigger.x) > std::abs(state.trigger.y)) continue; } // ignore too low button values on configuration if (id >= kButtonAxisStart) { if (controller->get_axis_value(id) < 0.33f) { cemuLog_logDebug(LogType::Force, "skipping since value too low {}", controller->get_axis_value(id)); s_was_idle = true; return; } } } emulated_controller->set_mapping(mapping, controller, id); element->SetValue(controller->get_button_name(id)); element->SetBackgroundColour(kKeyColourNormalMode); m_color_backup[element->GetId()] = kKeyColourNormalMode; break; } if (const auto sibling = get_next_sibling(element)) sibling->SetFocus(); else // last element reached { reset_focused_element(); this->SetFocusIgnoringChildren(); } } void InputPanel::reset_configuration() { m_color_backup.clear(); wxWindowUpdateLocker lock(this); for (const auto& c : GetChildren()) { if (auto* text = dynamic_cast<wxTextCtrl*>(c)) { text->SetValue(wxEmptyString); text->SetBackgroundColour(kKeyColourNormalMode); text->Refresh(); } } } void InputPanel::reset_colours() { m_color_backup.clear(); wxWindowUpdateLocker lock(this); for (const auto& c : GetChildren()) { if (auto* text = dynamic_cast<wxTextCtrl*>(c)) { text->SetBackgroundColour(kKeyColourNormalMode); text->Refresh(); } } } void InputPanel::load_controller(const EmulatedControllerPtr& controller) { reset_configuration(); if(!controller) { return; } if(controller->get_controllers().empty()) { return; } wxWindowUpdateLocker lock(this); for (auto* child : this->GetChildren()) { const auto text = dynamic_cast<wxTextCtrl*>(child); if (text == nullptr) continue; const auto mapping = reinterpret_cast<sint64>(text->GetClientData()); if (mapping <= 0) continue; auto button_name = controller->get_mapping_name(mapping); #if BOOST_OS_WINDOWS text->SetLabelText(button_name); #else // SetLabelText doesn't seem to work here for some reason on wxGTK text->ChangeValue(button_name); #endif } } void InputPanel::set_selected_controller(const EmulatedControllerPtr& emulated_controller, const ControllerPtr& controller) { wxWindowUpdateLocker lock(this); for (auto* child : this->GetChildren()) { const auto text = dynamic_cast<wxTextCtrl*>(child); if (text == nullptr) continue; if (text->GetId() == m_focused_element) continue; const auto mapping = reinterpret_cast<sint64>(text->GetClientData()); if (mapping <= 0) continue; const auto mapping_controller = emulated_controller->get_mapping_controller(mapping); if (!mapping_controller) continue; text->SetBackgroundColour(*mapping_controller == *controller ? kKeyColourNormalMode : kKeyColourActiveMode); text->Refresh(); } } void InputPanel::bind_hotkey_events(wxTextCtrl* text_ctrl) { text_ctrl->Bind(wxEVT_SET_FOCUS, &InputPanel::on_edit_key_focus, this); text_ctrl->Bind(wxEVT_KILL_FOCUS, &InputPanel::on_edit_key_kill_focus, this); text_ctrl->Bind(wxEVT_RIGHT_DOWN, &InputPanel::on_right_click, this); #if BOOST_OS_LINUX // Bind to a no-op lambda to disable arrow keys navigation text_ctrl->Bind(wxEVT_KEY_DOWN, [](wxKeyEvent &) {}); #endif } void InputPanel::on_left_click(wxMouseEvent& event) { if (m_focused_element == wxID_NONE) return; const auto focuses_element = FindWindow(m_focused_element); wxASSERT(focuses_element); wxFocusEvent focus(wxEVT_KILL_FOCUS, m_focused_element); focus.SetWindow(focuses_element); focuses_element->GetEventHandler()->ProcessEvent(focus); this->SetFocusIgnoringChildren(); } void InputPanel::on_edit_key_focus(wxFocusEvent& event) { auto* text = dynamic_cast<wxTextCtrl*>(event.GetEventObject()); wxASSERT(text); m_color_backup[text->GetId()] = text->GetBackgroundColour(); text->SetBackgroundColour(kKeyColourEditMode); #if BOOST_OS_WINDOWS text->HideNativeCaret(); #endif text->Refresh(); m_focused_element = text->GetId(); event.Skip(); } void InputPanel::on_edit_key_kill_focus(wxFocusEvent& event) { reset_focused_element(); event.Skip(); } void InputPanel::on_right_click(wxMouseEvent& event) { m_right_down = true; if(m_focused_element == wxID_NONE) { auto* text = dynamic_cast<wxTextCtrl*>(event.GetEventObject()); wxASSERT(text); text->SetFocus(); } } bool InputPanel::reset_focused_element() { if (m_focused_element == wxID_NONE) return false; auto* prev_element = dynamic_cast<wxTextCtrl*>(FindWindow(m_focused_element)); wxASSERT(prev_element); if(m_color_backup.find(prev_element->GetId()) != m_color_backup.cend()) prev_element->SetBackgroundColour(m_color_backup[prev_element->GetId()]); else prev_element->SetBackgroundColour(kKeyColourNormalMode); #if BOOST_OS_WINDOWS prev_element->HideNativeCaret(); #endif prev_element->Refresh(); m_focused_element = wxID_NONE; return true; }
7,619
C++
.cpp
244
28.405738
145
0.727173
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,986
ClassicControllerInputPanel.cpp
cemu-project_Cemu/src/gui/input/panels/ClassicControllerInputPanel.cpp
#include "gui/input/panels/ClassicControllerInputPanel.h" #include <wx/gbsizer.h> #include <wx/stattext.h> #include <wx/statline.h> #include <wx/textctrl.h> #include <wx/slider.h> #include "gui/helpers/wxControlObject.h" #include "input/emulated/ClassicController.h" #include "gui/helpers/wxHelpers.h" #include "gui/components/wxInputDraw.h" constexpr ClassicController::ButtonId g_kFirstColumnItems[] = { ClassicController::kButtonId_A, ClassicController::kButtonId_B, ClassicController::kButtonId_X, ClassicController::kButtonId_Y, ClassicController::kButtonId_L, ClassicController::kButtonId_R, ClassicController::kButtonId_ZL, ClassicController::kButtonId_ZR, ClassicController::kButtonId_Plus, ClassicController::kButtonId_Minus }; constexpr ClassicController::ButtonId g_kSecondColumnItems[] = { ClassicController::kButtonId_StickL_Up, ClassicController::kButtonId_StickL_Down, ClassicController::kButtonId_StickL_Left, ClassicController::kButtonId_StickL_Right }; constexpr ClassicController::ButtonId g_kThirdColumnItems[] = { ClassicController::kButtonId_StickR_Up, ClassicController::kButtonId_StickR_Down, ClassicController::kButtonId_StickR_Left, ClassicController::kButtonId_StickR_Right }; constexpr ClassicController::ButtonId g_kFourthRowItems[] = { ClassicController::kButtonId_Up, ClassicController::kButtonId_Down, ClassicController::kButtonId_Left, ClassicController::kButtonId_Right }; ClassicControllerInputPanel::ClassicControllerInputPanel(wxWindow* parent) : InputPanel(parent) { auto bold_font = GetFont(); bold_font.MakeBold(); auto* main_sizer = new wxGridBagSizer(); sint32 row = 0; sint32 column = 0; for (const auto& id : g_kFirstColumnItems) { row++; add_button_row(main_sizer, row, column, id); } ////////////////////////////////////////////////////////////////// main_sizer->Add(new wxStaticLine(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVERTICAL), wxGBPosition(0, column + 2), wxGBSpan(11, 1), wxALL | wxEXPAND, 5); row = 0; column += 3; auto text = new wxStaticText(this, wxID_ANY, _("Left Axis")); text->SetFont(bold_font); main_sizer->Add(text, wxGBPosition(row, column), wxGBSpan(1, 3), wxALL | wxEXPAND, 5); for (const auto& id : g_kSecondColumnItems) { row++; add_button_row(main_sizer, row, column, id); } row++; // input drawer m_left_draw = new wxInputDraw(this, wxID_ANY, wxDefaultPosition, { 60, 60 }); main_sizer->Add(m_left_draw, wxGBPosition(row, column + 1), wxGBSpan(2, 1), wxTOP | wxBOTTOM | wxEXPAND | wxALIGN_CENTER, 5); main_sizer->Add(new wxStaticLine(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVERTICAL), wxGBPosition(0, column + 3), wxGBSpan(11, 1), wxALL | wxEXPAND, 5); ////////////////////////////////////////////////////////////////// row = 0; column += 4; text = new wxStaticText(this, wxID_ANY, _("Right Axis")); text->SetFont(bold_font); main_sizer->Add(text, wxGBPosition(row, column), wxGBSpan(1, 3), wxALL | wxEXPAND, 5); for (const auto& id : g_kThirdColumnItems) { row++; add_button_row(main_sizer, row, column, id); } row++; // input drawer m_right_draw = new wxInputDraw(this, wxID_ANY, wxDefaultPosition, { 60, 60 }); main_sizer->Add(m_right_draw, wxGBPosition(row, column + 1), wxGBSpan(2, 1), wxTOP | wxBOTTOM | wxEXPAND | wxALIGN_CENTER, 5); main_sizer->Add(new wxStaticLine(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxVERTICAL), wxGBPosition(0, column + 3), wxGBSpan(11, 1), wxALL | wxEXPAND, 5); ////////////////////////////////////////////////////////////////// row = 0; column += 4; text = new wxStaticText(this, wxID_ANY, _("D-pad")); text->SetFont(bold_font); main_sizer->Add(text, wxGBPosition(row, column), wxGBSpan(1, 3), wxALL | wxEXPAND, 5); for (auto id : g_kFourthRowItems) { row++; add_button_row(main_sizer, row, column, id); } ////////////////////////////////////////////////////////////////// SetSizer(main_sizer); Layout(); } void ClassicControllerInputPanel::add_button_row(wxGridBagSizer *sizer, sint32 row, sint32 column, const ClassicController::ButtonId &button_id) { sizer->Add( new wxStaticText(this, wxID_ANY, wxGetTranslation(to_wxString(ClassicController::get_button_name(button_id)))), wxGBPosition(row, column), wxDefaultSpan, wxALL | wxALIGN_CENTER_VERTICAL, 5); auto* text_ctrl = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL | wxTE_PROCESS_ENTER | wxTE_PROCESS_TAB); text_ctrl->SetClientData(reinterpret_cast<void*>(button_id)); text_ctrl->SetMinSize(wxSize(150, -1)); text_ctrl->SetEditable(false); text_ctrl->SetBackgroundColour(kKeyColourNormalMode); bind_hotkey_events(text_ctrl); sizer->Add(text_ctrl, wxGBPosition(row, column + 1), wxDefaultSpan, wxALL | wxEXPAND, 5); }
4,775
C++
.cpp
89
51.393258
394
0.714347
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,987
DefaultControllerSettings.cpp
cemu-project_Cemu/src/gui/input/settings/DefaultControllerSettings.cpp
#include "gui/input/settings/DefaultControllerSettings.h" #include <wx/sizer.h> #include <wx/stattext.h> #include <wx/slider.h> #include <wx/button.h> #include <wx/gbsizer.h> #include <wx/statline.h> #include <wx/checkbox.h> #include <wx/statbox.h> #include "gui/helpers/wxControlObject.h" #include "gui/helpers/wxHelpers.h" #include "gui/components/wxInputDraw.h" #include "gui/input/InputAPIAddWindow.h" DefaultControllerSettings::DefaultControllerSettings(wxWindow* parent, const wxPoint& position, std::shared_ptr<ControllerBase> controller) : wxDialog(parent, wxID_ANY, _("Controller settings"), position, wxDefaultSize, wxDEFAULT_DIALOG_STYLE), m_controller(std::move(controller)) { m_settings = m_controller->get_settings(); m_rumble_backup = m_settings.rumble; this->SetSizeHints(wxDefaultSize, wxDefaultSize); auto* sizer = new wxBoxSizer(wxVERTICAL); // options { auto* box = new wxStaticBox(this, wxID_ANY, _("Options")); auto* box_sizer = new wxStaticBoxSizer(box, wxVERTICAL); // Motion m_use_motion = new wxCheckBox(box, wxID_ANY, _("Use motion")); m_use_motion->SetValue(m_settings.motion); m_use_motion->Enable(m_controller->has_motion()); box_sizer->Add(m_use_motion, 0, wxEXPAND | wxALL, 5); // Vibration auto* rumbleSizer = new wxBoxSizer(wxHORIZONTAL); const auto rumble = (int)(m_settings.rumble * 100); rumbleSizer->Add(new wxStaticText(box, wxID_ANY, _("Rumble")), 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_rumble = new wxSlider(box, wxID_ANY, rumble, 0, 100); rumbleSizer->Add(m_rumble, 1, wxALL | wxEXPAND, 5); const auto text = new wxStaticText(box, wxID_ANY, wxString::Format("%d%%", rumble)); rumbleSizer->Add(text, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_rumble->Bind(wxEVT_SLIDER, &DefaultControllerSettings::on_rumble_change, this, wxID_ANY, wxID_ANY, new wxControlObject(text)); box_sizer->Add(rumbleSizer); sizer->Add(box_sizer, 1, wxALL|wxEXPAND, 5); } auto* row_sizer = new wxBoxSizer(wxHORIZONTAL); // Axis { auto* box = new wxStaticBox(this, wxID_ANY, _("Axis")); auto* box_sizer = new wxStaticBoxSizer(box, wxVERTICAL); { auto* content_sizer = new wxFlexGridSizer(0, 3, 0, 0); // Deadzone const auto deadzone = (int)(m_settings.axis.deadzone * 100); content_sizer->Add(new wxStaticText(box, wxID_ANY, _("Deadzone")), 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_axis_deadzone = new wxSlider(box, wxID_ANY, deadzone, 0, 100); content_sizer->Add(m_axis_deadzone, 1, wxALL | wxEXPAND, 5); const auto deadzone_text = new wxStaticText(box, wxID_ANY, wxString::Format("%d%%", deadzone)); content_sizer->Add(deadzone_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_axis_deadzone->Bind(wxEVT_SLIDER, &DefaultControllerSettings::on_deadzone_change, this, wxID_ANY, wxID_ANY, new wxControlObject(deadzone_text)); // Range const auto range = (int)(m_settings.axis.range * 100); content_sizer->Add(new wxStaticText(box, wxID_ANY, _("Range")), 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_axis_range = new wxSlider(box, wxID_ANY, range, 50, 200); content_sizer->Add(m_axis_range, 1, wxALL | wxEXPAND, 5); const auto range_text = new wxStaticText(box, wxID_ANY, wxString::Format("%d%%", range)); content_sizer->Add(range_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_axis_range->Bind(wxEVT_SLIDER, &DefaultControllerSettings::on_range_change, this, wxID_ANY, wxID_ANY, new wxControlObject(range_text)); content_sizer->AddSpacer(1); m_axis_draw = new wxInputDraw(box, wxID_ANY, wxDefaultPosition, { 60, 60 }); content_sizer->Add(m_axis_draw, 0, wxTOP | wxBOTTOM | wxALIGN_CENTER, 5); box_sizer->Add(content_sizer, 1, wxEXPAND, 0); } row_sizer->Add(box_sizer, 0, wxALL | wxEXPAND, 5); } // Rotation { auto* box = new wxStaticBox(this, wxID_ANY, _("Rotation")); auto* box_sizer = new wxStaticBoxSizer(box, wxVERTICAL); { auto* content_sizer = new wxFlexGridSizer(0, 3, 0, 0); // Deadzone const auto deadzone = (int)(m_settings.rotation.deadzone * 100); content_sizer->Add(new wxStaticText(box, wxID_ANY, _("Deadzone")), 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_rotation_deadzone = new wxSlider(box, wxID_ANY, deadzone, 0, 100); content_sizer->Add(m_rotation_deadzone, 1, wxALL | wxEXPAND, 5); const auto deadzone_text = new wxStaticText(box, wxID_ANY, wxString::Format("%d%%", deadzone)); content_sizer->Add(deadzone_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_rotation_deadzone->Bind(wxEVT_SLIDER, &DefaultControllerSettings::on_deadzone_change, this, wxID_ANY, wxID_ANY, new wxControlObject(deadzone_text)); // Range const auto range = (int)(m_settings.rotation.range * 100); content_sizer->Add(new wxStaticText(box, wxID_ANY, _("Range")), 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_rotation_range = new wxSlider(box, wxID_ANY, range, 50, 200); content_sizer->Add(m_rotation_range, 1, wxALL | wxEXPAND, 5); const auto range_text = new wxStaticText(box, wxID_ANY, wxString::Format("%d%%", range)); content_sizer->Add(range_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_rotation_range->Bind(wxEVT_SLIDER, &DefaultControllerSettings::on_range_change, this, wxID_ANY, wxID_ANY, new wxControlObject(range_text)); content_sizer->AddSpacer(1); m_rotation_draw = new wxInputDraw(box, wxID_ANY, wxDefaultPosition, { 60, 60 }); content_sizer->Add(m_rotation_draw, 0, wxTOP | wxBOTTOM | wxALIGN_CENTER, 5); box_sizer->Add(content_sizer, 1, wxEXPAND, 0); } row_sizer->Add(box_sizer, 0, wxALL | wxEXPAND, 5); } // Trigger { auto* box = new wxStaticBox(this, wxID_ANY, _("Trigger")); auto* box_sizer = new wxStaticBoxSizer(box, wxVERTICAL); { auto* content_sizer = new wxFlexGridSizer(0, 3, 0, 0); // Deadzone const auto deadzone = (int)(m_settings.trigger.deadzone * 100); content_sizer->Add(new wxStaticText(box, wxID_ANY, _("Deadzone")), 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_trigger_deadzone = new wxSlider(box, wxID_ANY, deadzone, 0, 100); content_sizer->Add(m_trigger_deadzone, 1, wxALL | wxEXPAND, 5); const auto deadzone_text = new wxStaticText(box, wxID_ANY, wxString::Format("%d%%", deadzone)); content_sizer->Add(deadzone_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_trigger_deadzone->Bind(wxEVT_SLIDER, &DefaultControllerSettings::on_deadzone_change, this, wxID_ANY, wxID_ANY, new wxControlObject(deadzone_text)); // Range const auto range = (int)(m_settings.trigger.range * 100); content_sizer->Add(new wxStaticText(box, wxID_ANY, _("Range")), 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_trigger_range = new wxSlider(box, wxID_ANY, range, 50, 200); content_sizer->Add(m_trigger_range, 1, wxALL | wxEXPAND, 5); const auto range_text = new wxStaticText(box, wxID_ANY, wxString::Format("%d%%", range)); content_sizer->Add(range_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_trigger_range->Bind(wxEVT_SLIDER, &DefaultControllerSettings::on_range_change, this, wxID_ANY, wxID_ANY, new wxControlObject(range_text)); content_sizer->AddSpacer(1); m_trigger_draw = new wxInputDraw(box, wxID_ANY, wxDefaultPosition, { 60, 60 }); content_sizer->Add(m_trigger_draw, 0, wxTOP | wxBOTTOM | wxALIGN_CENTER, 5); box_sizer->Add(content_sizer, 1, wxEXPAND, 0); } row_sizer->Add(box_sizer, 0, wxALL | wxEXPAND, 5); } sizer->Add(row_sizer); { auto* control_sizer = new wxFlexGridSizer(0, 4, 0, 0); control_sizer->AddGrowableCol(3); auto* ok_button = new wxButton(this, wxID_ANY, _("OK")); ok_button->Bind(wxEVT_BUTTON, [this](auto&) { update_settings(); EndModal(wxID_OK); }); control_sizer->Add(ok_button, 0, wxALL, 5); control_sizer->Add(0, 0, 0, wxEXPAND, 5); auto* cancel_button = new wxButton(this, wxID_ANY, _("Cancel")); cancel_button->Bind(wxEVT_BUTTON, [this](auto&) { EndModal(wxID_CANCEL); }); control_sizer->Add(cancel_button, 0, wxALL, 5); auto* calibrate_button = new wxButton(this, wxID_ANY, _("Calibrate")); calibrate_button->Bind(wxEVT_BUTTON, [this](auto&) { m_controller->calibrate(); }); control_sizer->Add(calibrate_button, 0, wxALL | wxALIGN_RIGHT, 5); sizer->Add(control_sizer, 0, wxEXPAND, 5); } this->SetSizer(sizer); this->Layout(); this->Fit(); this->Bind(wxEVT_CLOSE_WINDOW, &DefaultControllerSettings::on_close, this); m_timer = new wxTimer(this); Bind(wxEVT_TIMER, &DefaultControllerSettings::on_timer, this); m_timer->Start(100); } DefaultControllerSettings::~DefaultControllerSettings() { m_controller->stop_rumble(); m_timer->Stop(); } void DefaultControllerSettings::update_settings() { // update settings m_controller->set_settings(m_settings); if (m_use_motion) m_controller->set_use_motion(m_use_motion->GetValue()); } void DefaultControllerSettings::on_timer(wxTimerEvent& event) { if (m_rumble_time.has_value() && std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - m_rumble_time.value()).count() > 500 ) { m_controller->stop_rumble(); m_rumble_time = {}; } const auto& default_state = m_controller->get_default_state(); auto state = m_controller->raw_state(); m_controller->apply_axis_setting(state.axis, default_state.axis, m_settings.axis); m_controller->apply_axis_setting(state.rotation, default_state.rotation, m_settings.rotation); m_controller->apply_axis_setting(state.trigger, default_state.trigger, m_settings.trigger); if (m_controller->api() == InputAPI::SDLController) { state.axis.y *= -1; state.rotation.y *= -1; } m_axis_draw->SetDeadzone(m_settings.axis.deadzone); m_axis_draw->SetAxisValue(state.axis); m_rotation_draw->SetDeadzone(m_settings.rotation.deadzone); m_rotation_draw->SetAxisValue(state.rotation); m_trigger_draw->SetDeadzone(m_settings.trigger.deadzone); m_trigger_draw->SetAxisValue(state.trigger); } void DefaultControllerSettings::on_close(wxCloseEvent& event) { if (this->GetReturnCode() == 0 || this->GetReturnCode() == wxID_OK) update_settings(); event.Skip(); } void DefaultControllerSettings::on_deadzone_change(wxCommandEvent& event) { update_slider_text(event); const auto new_value = (float)event.GetInt() / 100.0f; if (event.GetEventObject() == m_axis_deadzone) m_settings.axis.deadzone = new_value; else if (event.GetEventObject() == m_rotation_deadzone) m_settings.rotation.deadzone = new_value; else if (event.GetEventObject() == m_trigger_deadzone) m_settings.trigger.deadzone = new_value; } void DefaultControllerSettings::on_range_change(wxCommandEvent& event) { update_slider_text(event); const auto new_value = (float)event.GetInt() / 100.0f; if (event.GetEventObject() == m_axis_range) m_settings.axis.range = new_value; else if (event.GetEventObject() == m_rotation_range) m_settings.rotation.range = new_value; else if (event.GetEventObject() == m_trigger_range) m_settings.trigger.range = new_value; } void DefaultControllerSettings::on_rumble_change(wxCommandEvent& event) { update_slider_text(event); const auto rumble_value = event.GetInt(); m_settings.rumble = (float)rumble_value / 100.0f; m_controller->set_rumble(m_settings.rumble); if (rumble_value != 0) m_controller->start_rumble(); else m_controller->stop_rumble(); m_controller->set_rumble(m_rumble_backup); m_rumble_time = std::chrono::steady_clock::now(); }
11,365
C++
.cpp
237
44.852321
161
0.717972
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,988
WiimoteControllerSettings.cpp
cemu-project_Cemu/src/gui/input/settings/WiimoteControllerSettings.cpp
#include "gui/input/settings/WiimoteControllerSettings.h" #include <wx/sizer.h> #include <wx/stattext.h> #include <wx/slider.h> #include <wx/button.h> #include <wx/gbsizer.h> #include <wx/statline.h> #include <wx/checkbox.h> #include <wx/statbox.h> #include "gui/helpers/wxControlObject.h" #include "gui/helpers/wxHelpers.h" #include "gui/components/wxInputDraw.h" #include "gui/input/InputAPIAddWindow.h" #ifdef SUPPORTS_WIIMOTE WiimoteControllerSettings::WiimoteControllerSettings(wxWindow* parent, const wxPoint& position, std::shared_ptr<NativeWiimoteController> controller) : wxDialog(parent, wxID_ANY, _("Controller settings"), position, wxDefaultSize, wxDEFAULT_DIALOG_STYLE), m_controller(std::move(controller)) { m_settings = m_controller->get_settings(); m_rumble_backup = m_settings.rumble; m_packet_delay_backup = m_controller->get_packet_delay(); this->SetSizeHints(wxDefaultSize, wxDefaultSize); auto* sizer = new wxBoxSizer(wxVERTICAL); // extension info { auto* box = new wxStaticBox(this, wxID_ANY, _("Connected extension")); auto* box_sizer = new wxStaticBoxSizer(box, wxVERTICAL); m_extension_text = new wxStaticText(box, wxID_ANY, _("None")); box_sizer->Add(m_extension_text, 0, wxALL, 5); sizer->Add(box_sizer, 0, wxALL | wxEXPAND, 5); } // options { auto* box = new wxStaticBox(this, wxID_ANY, _("Options")); auto* box_sizer = new wxStaticBoxSizer(box, wxVERTICAL); { auto* row_sizer = new wxBoxSizer(wxHORIZONTAL); // Rumble m_rumble = new wxCheckBox(box, wxID_ANY, _("Rumble")); m_rumble->SetValue(m_settings.rumble > 0); row_sizer->Add(m_rumble, 0, wxALL, 5); m_rumble->Bind(wxEVT_CHECKBOX, &WiimoteControllerSettings::on_rumble_change, this); // Motion m_use_motion = new wxCheckBox(box, wxID_ANY, _("Use motion")); m_use_motion->SetValue(m_settings.motion); m_use_motion->Enable(m_controller->has_motion()); row_sizer->Add(m_use_motion, 0, wxALL, 5); box_sizer->Add(row_sizer); } { auto* row_sizer = new wxBoxSizer(wxHORIZONTAL); // Delay row_sizer->Add(new wxStaticText(box, wxID_ANY, _("Packet delay")), 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_package_delay = new wxSlider(box, wxID_ANY, m_packet_delay_backup, 1, 100); row_sizer->Add(m_package_delay, 1, wxALL | wxEXPAND, 5); const auto range_text = new wxStaticText(box, wxID_ANY, wxString::Format("%dms", m_packet_delay_backup)); row_sizer->Add(range_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_package_delay->Bind(wxEVT_SLIDER, &WiimoteControllerSettings::on_delay_change, this, wxID_ANY, wxID_ANY, new wxControlObject(range_text)); box_sizer->Add(row_sizer); } sizer->Add(box_sizer, 0, wxALL | wxEXPAND, 5); } // Nunchuck { m_nunchuck_settings = new wxStaticBox(this, wxID_ANY, _("Nunchuck")); auto* box_sizer = new wxStaticBoxSizer(m_nunchuck_settings, wxVERTICAL); { auto* content_sizer = new wxFlexGridSizer(0, 3, 0, 0); // Deadzone const auto deadzone = (int)(m_settings.axis.deadzone * 100); content_sizer->Add(new wxStaticText(m_nunchuck_settings, wxID_ANY, _("Deadzone")), 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_nunchuck_deadzone = new wxSlider(m_nunchuck_settings, wxID_ANY, deadzone, 0, 100); content_sizer->Add(m_nunchuck_deadzone, 1, wxALL | wxEXPAND, 5); const auto deadzone_text = new wxStaticText(m_nunchuck_settings, wxID_ANY, wxString::Format("%d%%", deadzone)); content_sizer->Add(deadzone_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_nunchuck_deadzone->Bind(wxEVT_SLIDER, &WiimoteControllerSettings::on_slider_change, this, wxID_ANY, wxID_ANY, new wxControlObject(deadzone_text)); // Range const auto range = (int)(m_settings.axis.range * 100); content_sizer->Add(new wxStaticText(m_nunchuck_settings, wxID_ANY, _("Range")), 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_nunchuck_range = new wxSlider(m_nunchuck_settings, wxID_ANY, range, 50, 200); content_sizer->Add(m_nunchuck_range, 1, wxALL | wxEXPAND, 5); const auto range_text = new wxStaticText(m_nunchuck_settings, wxID_ANY, wxString::Format("%d%%", range)); content_sizer->Add(range_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_nunchuck_range->Bind(wxEVT_SLIDER, &WiimoteControllerSettings::on_slider_change, this, wxID_ANY, wxID_ANY, new wxControlObject(range_text)); content_sizer->AddSpacer(1); m_nunchuck_draw = new wxInputDraw(m_nunchuck_settings, wxID_ANY, wxDefaultPosition, { 60, 60 }); content_sizer->Add(m_nunchuck_draw, 0, wxTOP | wxBOTTOM | wxALIGN_CENTER, 5); box_sizer->Add(content_sizer, 1, wxEXPAND, 0); } sizer->Add(box_sizer, 0, wxALL | wxEXPAND, 5); } // Classic { m_classic_settings = new wxStaticBox(this, wxID_ANY, _("Classic")); auto* box_sizer = new wxStaticBoxSizer(m_classic_settings, wxVERTICAL); { auto* content_sizer = new wxFlexGridSizer(0, 6, 0, 0); // Deadzone { // Axis const auto deadzone = (int)(m_settings.axis.deadzone * 100); content_sizer->Add(new wxStaticText(m_classic_settings, wxID_ANY, _("Deadzone")), 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_classic_axis_deadzone = new wxSlider(m_classic_settings, wxID_ANY, deadzone, 0, 100); content_sizer->Add(m_classic_axis_deadzone, 1, wxALL | wxEXPAND, 5); const auto deadzone_text = new wxStaticText(m_classic_settings, wxID_ANY, wxString::Format("%d%%", deadzone)); content_sizer->Add(deadzone_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_classic_axis_deadzone->Bind(wxEVT_SLIDER, &WiimoteControllerSettings::on_slider_change, this, wxID_ANY, wxID_ANY, new wxControlObject(deadzone_text)); } { // Range const auto deadzone = (int)(m_settings.rotation.deadzone * 100); content_sizer->Add(new wxStaticText(m_classic_settings, wxID_ANY, _("Deadzone")), 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_classic_rotation_deadzone = new wxSlider(m_classic_settings, wxID_ANY, deadzone, 0, 100); content_sizer->Add(m_classic_rotation_deadzone, 1, wxALL | wxEXPAND, 5); const auto deadzone_text = new wxStaticText(m_classic_settings, wxID_ANY, wxString::Format("%d%%", deadzone)); content_sizer->Add(deadzone_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_classic_rotation_deadzone->Bind(wxEVT_SLIDER, &WiimoteControllerSettings::on_slider_change, this, wxID_ANY, wxID_ANY, new wxControlObject(deadzone_text)); } // Range { // Axis const auto range = (int)(m_settings.axis.range * 100); content_sizer->Add(new wxStaticText(m_classic_settings, wxID_ANY, _("Range")), 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_classic_axis_range = new wxSlider(m_classic_settings, wxID_ANY, range, 50, 200); content_sizer->Add(m_classic_axis_range, 1, wxALL | wxEXPAND, 5); const auto range_text = new wxStaticText(m_classic_settings, wxID_ANY, wxString::Format("%d%%", range)); content_sizer->Add(range_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_classic_axis_range->Bind(wxEVT_SLIDER, &WiimoteControllerSettings::on_slider_change, this, wxID_ANY, wxID_ANY, new wxControlObject(range_text)); } { // Rotation const auto range = (int)(m_settings.rotation.range * 100); content_sizer->Add(new wxStaticText(m_classic_settings, wxID_ANY, _("Range")), 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_classic_rotation_range = new wxSlider(m_classic_settings, wxID_ANY, range, 50, 200); content_sizer->Add(m_classic_rotation_range, 1, wxALL | wxEXPAND, 5); const auto range_text = new wxStaticText(m_classic_settings, wxID_ANY, wxString::Format("%d%%", range)); content_sizer->Add(range_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); m_classic_rotation_range->Bind(wxEVT_SLIDER, &WiimoteControllerSettings::on_slider_change, this, wxID_ANY, wxID_ANY, new wxControlObject(range_text)); } content_sizer->AddSpacer(1); m_classic_axis_draw = new wxInputDraw(m_classic_settings, wxID_ANY, wxDefaultPosition, { 60, 60 }); content_sizer->Add(m_classic_axis_draw, 0, wxTOP | wxBOTTOM | wxALIGN_CENTER, 5); content_sizer->AddSpacer(1); content_sizer->AddSpacer(1); m_classic_rotation_draw = new wxInputDraw(m_classic_settings, wxID_ANY, wxDefaultPosition, { 60, 60 }); content_sizer->Add(m_classic_rotation_draw, 0, wxTOP | wxBOTTOM | wxALIGN_CENTER, 5); box_sizer->Add(content_sizer, 1, wxEXPAND, 0); } sizer->Add(box_sizer, 0, wxALL | wxEXPAND, 5); } { auto* control_sizer = new wxFlexGridSizer(0, 4, 0, 0); control_sizer->AddGrowableCol(3); auto* ok_button = new wxButton(this, wxID_ANY, _("OK")); ok_button->Bind(wxEVT_BUTTON, [this](auto&) { update_settings(); EndModal(wxID_OK); }); control_sizer->Add(ok_button, 0, wxALL, 5); control_sizer->Add(0, 0, 0, wxEXPAND, 5); auto* cancel_button = new wxButton(this, wxID_ANY, _("Cancel")); cancel_button->Bind(wxEVT_BUTTON, [this](auto&) { EndModal(wxID_CANCEL); }); control_sizer->Add(cancel_button, 0, wxALL, 5); auto* calibrate_button = new wxButton(this, wxID_ANY, _("Calibrate")); calibrate_button->Bind(wxEVT_BUTTON, [this](auto&) { m_controller->calibrate(); }); control_sizer->Add(calibrate_button, 0, wxALL | wxALIGN_RIGHT, 5); sizer->Add(control_sizer, 0, wxEXPAND, 5); } this->SetSizer(sizer); this->Layout(); this->Fit(); this->Bind(wxEVT_CLOSE_WINDOW, &WiimoteControllerSettings::on_close, this); m_timer = new wxTimer(this); Bind(wxEVT_TIMER, &WiimoteControllerSettings::on_timer, this); m_timer->Start(100); } WiimoteControllerSettings::~WiimoteControllerSettings() { m_controller->stop_rumble(); m_timer->Stop(); } void WiimoteControllerSettings::update_settings() { // update settings m_controller->set_settings(m_settings); if (m_use_motion) m_controller->set_use_motion(m_use_motion->GetValue()); m_controller->set_packet_delay(m_package_delay->GetValue()); } void WiimoteControllerSettings::on_timer(wxTimerEvent& event) { if (m_rumble_time.has_value() && std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - m_rumble_time.value()).count() > 500) { m_controller->stop_rumble(); m_rumble_time = {}; } const auto& default_state = m_controller->get_default_state(); auto state = m_controller->raw_state(); m_controller->apply_axis_setting(state.axis, default_state.axis, m_settings.axis); m_controller->apply_axis_setting(state.rotation, default_state.rotation, m_settings.rotation); m_controller->apply_axis_setting(state.trigger, default_state.trigger, m_settings.trigger); if (m_nunchuck_settings->IsEnabled()) { m_nunchuck_draw->SetDeadzone(m_settings.axis.deadzone); m_nunchuck_draw->SetAxisValue(state.axis); } if (m_classic_settings->IsEnabled()) { m_classic_axis_draw->SetDeadzone(m_settings.axis.deadzone); m_classic_axis_draw->SetAxisValue(state.axis); m_classic_rotation_draw->SetDeadzone(m_settings.rotation.deadzone); m_classic_rotation_draw->SetAxisValue(state.rotation); } wxString label; switch (m_controller->get_extension()) { case NativeWiimoteController::Nunchuck: label = _("Nunchuck"); m_nunchuck_settings->Enable(); m_classic_settings->Disable(); break; case NativeWiimoteController::Classic: label = _("Classic"); m_nunchuck_settings->Disable(); m_classic_settings->Enable(); break; default: m_nunchuck_settings->Disable(); m_classic_settings->Disable(); } if(m_controller->is_mpls_attached()) { const bool empty = label.empty(); if (!empty) label.Append(" ("); label.Append(_("MotionPlus")); if (!empty) label.Append(")"); } if(label.empty()) { label = _("None"); } m_extension_text->SetLabelText(label); } void WiimoteControllerSettings::on_close(wxCloseEvent& event) { if (this->GetReturnCode() == 0 || this->GetReturnCode() == wxID_OK) update_settings(); event.Skip(); } void WiimoteControllerSettings::on_slider_change(wxCommandEvent& event) { update_slider_text(event); const auto new_value = (float)event.GetInt() / 100.0f; auto* obj = event.GetEventObject(); if (obj == m_nunchuck_deadzone || obj == m_classic_axis_deadzone) m_settings.axis.deadzone = new_value; else if (obj == m_nunchuck_range || obj == m_classic_axis_range) m_settings.axis.range = new_value; else if (obj == m_classic_rotation_deadzone) m_settings.rotation.deadzone = new_value; else if (obj == m_classic_rotation_range) m_settings.rotation.range = new_value; } void WiimoteControllerSettings::on_rumble_change(wxCommandEvent& event) { const auto rumble_value = m_rumble->GetValue(); m_settings.rumble = rumble_value ? 1.0f : 0.0f; m_controller->set_rumble(m_settings.rumble); if (rumble_value) m_controller->start_rumble(); else m_controller->stop_rumble(); m_controller->set_rumble(m_rumble_backup); m_rumble_time = std::chrono::steady_clock::now(); } void WiimoteControllerSettings::on_delay_change(wxCommandEvent& event) { update_slider_text(event, "%dms"); } #endif
12,938
C++
.cpp
286
41.965035
160
0.716525
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,989
wxInputDraw.cpp
cemu-project_Cemu/src/gui/components/wxInputDraw.cpp
#include "gui/components/wxInputDraw.h" #include <wx/dcbuffer.h> wxInputDraw::wxInputDraw(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size) : wxWindow(parent, id, pos, size, 0, wxPanelNameStr) { SetBackgroundStyle(wxBG_STYLE_PAINT); Bind(wxEVT_PAINT, &wxInputDraw::OnPaintEvent, this); } wxInputDraw::~wxInputDraw() { Unbind(wxEVT_PAINT, &wxInputDraw::OnPaintEvent, this); } void wxInputDraw::OnPaintEvent(wxPaintEvent& event) { wxAutoBufferedPaintDC dc(this); OnRender(dc); } void wxInputDraw::OnRender(wxDC& dc) { dc.Clear(); glm::vec2 position; const wxPen *black, *red, *grey; const wxBrush *black_brush, *red_brush, *grey_brush; if(IsEnabled()) { position = m_position; black = wxBLACK_PEN; red = wxRED_PEN; grey = wxGREY_PEN; black_brush = wxBLACK_BRUSH; red_brush = wxRED_BRUSH; grey_brush = wxGREY_BRUSH; } else { position = {}; black = red = wxMEDIUM_GREY_PEN; grey = wxLIGHT_GREY_PEN; black_brush = red_brush = wxMEDIUM_GREY_BRUSH; grey_brush = wxLIGHT_GREY_BRUSH; } dc.SetBackgroundMode(wxSOLID); dc.SetBackground(*wxWHITE_BRUSH); const auto size = GetSize(); const auto min_size = (float)std::min(size.GetWidth(), size.GetHeight()) - 1.0f; const Vector2f middle{min_size / 2.0f, min_size / 2.0f}; // border const wxRect border{0, 0, (int)min_size, (int)min_size}; dc.SetPen(*black); dc.DrawRectangle(border); dc.SetPen(IsEnabled() ? wxPen(wxColour(0x336600)) : *grey); // dark green dc.DrawCircle((int)middle.x, (int)middle.y, (int)middle.x); if (m_deadzone > 0) { dc.SetPen(*grey); dc.SetBrush(*wxLIGHT_GREY_BRUSH); const auto deadzone_size = m_deadzone * min_size / 2.0f; dc.DrawCircle( static_cast<int>(middle.x), static_cast<int>(middle.x), (int)deadzone_size); if (length(position) >= m_deadzone) { dc.SetPen(*red); dc.SetBrush(*red_brush); if (std::abs(1.0f - length(position)) < 0.05f) { dc.SetPen(wxPen(wxColour(0x336600))); dc.SetBrush(wxColour(0x336600)); } } else { dc.SetPen(*black); dc.SetBrush(*black_brush); } } else { dc.SetPen(*red); dc.SetBrush(*red_brush); } // draw axis const wxPoint pos { static_cast<int>(middle.x + position.x * middle.x), static_cast<int>(middle.y - position.y * middle.y) }; dc.DrawCircle(pos.x, pos.y, 2); dc.SetBrush(*wxTRANSPARENT_BRUSH); } void wxInputDraw::SetAxisValue(const glm::vec2& position) { m_position = position; Refresh(); } void wxInputDraw::SetDeadzone(float deadzone) { m_deadzone = deadzone; Refresh(); }
2,553
C++
.cpp
98
23.5
97
0.705955
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,990
wxLogCtrl.cpp
cemu-project_Cemu/src/gui/components/wxLogCtrl.cpp
#include "gui/components/wxLogCtrl.h" #include <boost/algorithm/string.hpp> wxDEFINE_EVENT(EVT_ON_LIST_UPDATED, wxEvent); wxLogCtrl::wxLogCtrl(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style) : TextList(parent, id, pos, size, style) { m_timer = new wxTimer(this); this->Bind(wxEVT_TIMER, &wxLogCtrl::OnTimer, this); this->Bind(EVT_ON_LIST_UPDATED, &wxLogCtrl::OnActiveListUpdated, this); m_timer->Start(250); } wxLogCtrl::~wxLogCtrl() { this->Unbind(wxEVT_TIMER, &wxLogCtrl::OnTimer, this); this->Unbind(EVT_ON_LIST_UPDATED, &wxLogCtrl::OnActiveListUpdated, this); if(m_timer) m_timer->Stop(); if(m_update_worker.joinable()) m_update_worker.join(); } void wxLogCtrl::SetActiveFilter(const std::string& active_filter) { if(m_active_filter == active_filter) return; m_active_filter = active_filter; if(m_update_worker.joinable()) m_update_worker.join(); m_update_worker = std::thread(&wxLogCtrl::UpdateActiveEntries, this); } const std::string& wxLogCtrl::GetActiveFilter() const { return m_active_filter; } void wxLogCtrl::SetFilterMessage(bool state) { if(m_filter_messages == state) return; m_filter_messages = state; if(m_update_worker.joinable()) m_update_worker.join(); m_update_worker = std::thread(&wxLogCtrl::UpdateActiveEntries, this); } bool wxLogCtrl::GetFilterMessage() const { return m_filter_messages; } void wxLogCtrl::PushEntry(const wxString& filter, const wxString& message) { std::unique_lock lock(m_mutex); m_log_entries.emplace_back(filter, message); ListIt_t it = m_log_entries.back(); lock.unlock(); if(m_active_filter.empty() || filter == m_active_filter || (m_filter_messages && boost::icontains(message.ToStdString(), m_active_filter))) { std::unique_lock active_lock(m_active_mutex); m_active_entries.emplace_back(std::cref(it)); const auto entry_count = m_active_entries.size(); active_lock.unlock(); if(entry_count <= m_elements_visible) { RefreshLine(entry_count - 1); } } } void wxLogCtrl::OnDraw(wxDC& dc, sint32 start, sint32 count, const wxPoint& start_position) { wxPoint position = start_position; std::scoped_lock lock(m_active_mutex); auto it = std::next(m_active_entries.cbegin(), start); if(it == m_active_entries.cend()) return; for (sint32 i = 0; i <= count && it != m_active_entries.cend(); ++i, ++it) { wxColour background_colour; if((start + i) % 2 == 0) background_colour = COLOR_WHITE; else background_colour = 0xFFFDF9F2; DrawLineBackground(dc, position, background_colour); dc.SetTextForeground(COLOR_BLACK); dc.DrawText(it->get().second, position); NextLine(position, &start_position); } } void wxLogCtrl::OnTimer(wxTimerEvent& event) { std::unique_lock lock(m_active_mutex); const auto count = m_active_entries.size(); if(count == m_element_count) return; lock.unlock(); SetElementCount(count); if(m_scrolled_to_end) { Scroll(0, count); RefreshControl(); } } void wxLogCtrl::OnActiveListUpdated(wxEvent& event) { std::unique_lock lock(m_active_mutex); const auto count = m_active_entries.size(); lock.unlock(); SetElementCount(count); RefreshControl(); } void wxLogCtrl::UpdateActiveEntries() { { std::scoped_lock lock(m_mutex, m_active_mutex); m_active_entries.clear(); if(m_active_filter.empty()) { for (const auto& it : m_log_entries) m_active_entries.emplace_back(it); } else { for (const auto& it : m_log_entries) { if(it.first == m_active_filter || (m_filter_messages && boost::icontains(it.second.ToStdString(), m_active_filter)) ) m_active_entries.emplace_back(it); } } } wxQueueEvent(this, new wxCommandEvent(EVT_ON_LIST_UPDATED)); }
3,741
C++
.cpp
128
26.570313
140
0.721912
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,991
wxTitleManagerList.cpp
cemu-project_Cemu/src/gui/components/wxTitleManagerList.cpp
#include "gui/components/wxTitleManagerList.h" #include "gui/helpers/wxHelpers.h" #include "util/helpers/SystemException.h" #include "Cafe/TitleList/GameInfo.h" #include "Cafe/TitleList/TitleInfo.h" #include "Cafe/TitleList/TitleList.h" #include "gui/components/wxGameList.h" #include "gui/helpers/wxCustomEvents.h" #include "gui/helpers/wxHelpers.h" #include <wx/imaglist.h> #include <wx/wupdlock.h> #include <wx/menu.h> #include <wx/msgdlg.h> #include <wx/stattext.h> #include <wx/sizer.h> #include <wx/timer.h> #include <wx/panel.h> #include <wx/progdlg.h> #include "../wxHelper.h" #include <functional> #include "config/ActiveSettings.h" #include "gui/ChecksumTool.h" #include "gui/MainWindow.h" #include "Cafe/TitleList/TitleId.h" #include "Cafe/TitleList/SaveList.h" #include "Cafe/TitleList/TitleList.h" #include <zarchive/zarchivewriter.h> #include <zarchive/zarchivereader.h> #include "Common/FileStream.h" wxDEFINE_EVENT(wxEVT_TITLE_FOUND, wxCommandEvent); wxDEFINE_EVENT(wxEVT_TITLE_REMOVED, wxCommandEvent); wxDEFINE_EVENT(wxEVT_REMOVE_ENTRY, wxCommandEvent); wxTitleManagerList::wxTitleManagerList(wxWindow* parent, wxWindowID id) : wxListCtrl(parent, id, wxDefaultPosition, wxDefaultSize, wxLC_REPORT | wxLC_VIRTUAL) { AddColumns(); // tooltip TODO: extract class mb wxPanelTooltip m_tooltip_window = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxNO_BORDER); auto* tooltip_sizer = new wxBoxSizer(wxVERTICAL); m_tooltip_text = new wxStaticText(m_tooltip_window, wxID_ANY, wxEmptyString); tooltip_sizer->Add(m_tooltip_text , 0, wxALL, 5); m_tooltip_window->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_INFOBK)); m_tooltip_window->SetSizerAndFit(tooltip_sizer); m_tooltip_window->Hide(); m_tooltip_timer = new wxTimer(this); Bind(wxEVT_LIST_COL_CLICK, &wxTitleManagerList::OnColumnClick, this); Bind(wxEVT_CONTEXT_MENU, &wxTitleManagerList::OnContextMenu, this); Bind(wxEVT_LIST_ITEM_SELECTED, &wxTitleManagerList::OnItemSelected, this); Bind(wxEVT_TIMER, &wxTitleManagerList::OnTimer, this); Bind(wxEVT_REMOVE_ITEM, &wxTitleManagerList::OnRemoveItem, this); Bind(wxEVT_REMOVE_ENTRY, &wxTitleManagerList::OnRemoveEntry, this); Bind(wxEVT_TITLE_FOUND, &wxTitleManagerList::OnTitleDiscovered, this); Bind(wxEVT_TITLE_REMOVED, &wxTitleManagerList::OnTitleRemoved, this); Bind(wxEVT_CLOSE_WINDOW, &wxTitleManagerList::OnClose, this); m_callbackIdTitleList = CafeTitleList::RegisterCallback([](CafeTitleListCallbackEvent* evt, void* ctx) { ((wxTitleManagerList*)ctx)->HandleTitleListCallback(evt); }, this); m_callbackIdSaveList = CafeSaveList::RegisterCallback([](CafeSaveListCallbackEvent* evt, void* ctx) { ((wxTitleManagerList*)ctx)->HandleSaveListCallback(evt); }, this); } wxTitleManagerList::~wxTitleManagerList() { CafeSaveList::UnregisterCallback(m_callbackIdSaveList); CafeTitleList::UnregisterCallback(m_callbackIdTitleList); } boost::optional<const wxTitleManagerList::TitleEntry&> wxTitleManagerList::GetSelectedTitleEntry() const { const auto selection = GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED); if (selection != wxNOT_FOUND) { const auto tmp = GetTitleEntry(selection); if (tmp.has_value()) return tmp.value(); } return {}; } boost::optional<wxTitleManagerList::TitleEntry&> wxTitleManagerList::GetSelectedTitleEntry() { const auto selection = GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED); if (selection != wxNOT_FOUND) { const auto tmp = GetTitleEntry(selection); if (tmp.has_value()) return tmp.value(); } return {}; } //boost::optional<wxTitleManagerList::TitleEntry&> wxTitleManagerList::GetTitleEntry(EntryType type, uint64 titleid) //{ // for(const auto& v : m_data) // { // if (v->entry.title_id == titleid && v->entry.type == type) // return v->entry; // } // // return {}; //} boost::optional<wxTitleManagerList::TitleEntry&> wxTitleManagerList::GetTitleEntryByUID(uint64 uid) { for (const auto& v : m_data) { if (v->entry.location_uid == uid) return v->entry; } return {}; } void wxTitleManagerList::AddColumns() { wxListItem col0; col0.SetId(ColumnTitleId); col0.SetText(_("Title ID")); col0.SetWidth(120); InsertColumn(ColumnTitleId, col0); wxListItem col1; col1.SetId(ColumnName); col1.SetText(_("Name")); col1.SetWidth(435); InsertColumn(ColumnName, col1); wxListItem col2; col2.SetId(ColumnType); col2.SetText(_("Type")); col2.SetWidth(65); InsertColumn(ColumnType, col2); wxListItem col3; col3.SetId(ColumnVersion); col3.SetText(_("Version")); col3.SetWidth(40); InsertColumn(ColumnVersion, col3); wxListItem col4; col4.SetId(ColumnRegion); col4.SetText(_("Region")); col4.SetWidth(60); InsertColumn(ColumnRegion, col4); wxListItem col5; col5.SetId(ColumnFormat); col5.SetText(_("Format")); col5.SetWidth(63); InsertColumn(ColumnFormat, col5); wxListItem col6; col6.SetId(ColumnLocation); col6.SetText(_("Location")); col6.SetWidth(63); InsertColumn(ColumnLocation, col6); } wxString wxTitleManagerList::OnGetItemText(long item, long column) const { if (item >= GetItemCount()) return wxEmptyString; const auto entry = GetTitleEntry(item); if (entry.has_value()) return GetTitleEntryText(entry.value(), (ItemColumn)column); return wxEmptyString; } wxItemAttr* wxTitleManagerList::OnGetItemAttr(long item) const { static wxColour bgColourPrimary = GetBackgroundColour(); static wxColour bgColourSecondary = wxHelper::CalculateAccentColour(bgColourPrimary); static wxListItemAttr s_primary_attr(GetTextColour(), bgColourPrimary, GetFont()); static wxListItemAttr s_secondary_attr(GetTextColour(), bgColourSecondary, GetFont()); return item % 2 == 0 ? &s_primary_attr : &s_secondary_attr; } boost::optional<wxTitleManagerList::TitleEntry&> wxTitleManagerList::GetTitleEntry(long item) { long counter = 0; for (const auto& data : m_sorted_data) { if (!data.get().visible) continue; if (item != counter++) continue; return data.get().entry; } return {}; } boost::optional<const wxTitleManagerList::TitleEntry&> wxTitleManagerList::GetTitleEntry(const fs::path& path) const { const auto tmp = _pathToUtf8(path); for (const auto& data : m_data) { if (boost::iequals(_pathToUtf8(data->entry.path), tmp)) return data->entry; } return {}; } boost::optional<wxTitleManagerList::TitleEntry&> wxTitleManagerList::GetTitleEntry(const fs::path& path) { const auto tmp = _pathToUtf8(path); for (const auto& data : m_data) { if (boost::iequals(_pathToUtf8(data->entry.path), tmp)) return data->entry; } return {}; } boost::optional<const wxTitleManagerList::TitleEntry&> wxTitleManagerList::GetTitleEntry(long item) const { long counter = 0; for (const auto& data : m_sorted_data) { if (!data.get().visible) continue; if (item != counter++) continue; return data.get().entry; } return {}; } void wxTitleManagerList::OnConvertToCompressedFormat(uint64 titleId, uint64 rightClickedUID) { TitleInfo titleInfo_base; TitleInfo titleInfo_update; TitleInfo titleInfo_aoc; titleId = TitleIdParser::MakeBaseTitleId(titleId); // if the titleId of a separate update is selected, this converts it back to the base titleId TitleIdParser titleIdParser(titleId); bool hasBaseTitleId = titleIdParser.GetType() != TitleIdParser::TITLE_TYPE::AOC; bool hasUpdateTitleId = titleIdParser.CanHaveSeparateUpdateTitleId(); TitleId updateTitleId = hasUpdateTitleId ? titleIdParser.GetSeparateUpdateTitleId() : 0; // todo - AOC titleIds might differ from the base/update game in other bits than the type. We have to use the meta data from the base/update to match aoc to the base title id // for now we just assume they match TitleId aocTitleId; if (hasBaseTitleId) aocTitleId = (titleId & (uint64)~0xFF00000000) | (uint64)0xC00000000; else aocTitleId = titleId; // find base and update for (const auto& data : m_data) { if (hasBaseTitleId && data->entry.title_id == titleId) { if (!titleInfo_base.IsValid()) { titleInfo_base = CafeTitleList::GetTitleInfoByUID(data->entry.location_uid); if(data->entry.location_uid == rightClickedUID) break; // prefer the users selection } } } for (const auto& data : m_data) { if (hasUpdateTitleId && data->entry.title_id == updateTitleId) { if (!titleInfo_update.IsValid()) { titleInfo_update = CafeTitleList::GetTitleInfoByUID(data->entry.location_uid); if(data->entry.location_uid == rightClickedUID) break; } else { // if multiple updates are present use the newest one if (titleInfo_update.GetAppTitleVersion() < data->entry.version) titleInfo_update = CafeTitleList::GetTitleInfoByUID(data->entry.location_uid); if(data->entry.location_uid == rightClickedUID) break; } } } // find AOC for (const auto& data : m_data) { if (data->entry.title_id == aocTitleId) { titleInfo_aoc = CafeTitleList::GetTitleInfoByUID(data->entry.location_uid); if(data->entry.location_uid == rightClickedUID) break; } } wxString msg = _("The following content will be converted to a compressed Wii U archive file (.wua):"); msg.append("\n \n"); if (titleInfo_base.IsValid()) msg.append(formatWxString(_("Base game:\n{}"), titleInfo_base.GetPrintPath())); else msg.append(_("Base game:\nNot installed")); msg.append("\n\n"); if (titleInfo_update.IsValid()) msg.append(formatWxString(_("Update:\n{}"), titleInfo_update.GetPrintPath())); else msg.append(_("Update:\nNot installed")); msg.append("\n\n"); if (titleInfo_aoc.IsValid()) msg.append(formatWxString(_("DLC:\n{}"), titleInfo_aoc.GetPrintPath())); else msg.append(_("DLC:\nNot installed")); const int answer = wxMessageBox(msg, _("Confirmation"), wxOK | wxCANCEL | wxCENTRE | wxICON_QUESTION, this); if (answer != wxOK) return; std::vector<TitleInfo*> titlesToConvert; if (titleInfo_base.IsValid()) titlesToConvert.emplace_back(&titleInfo_base); if (titleInfo_update.IsValid()) titlesToConvert.emplace_back(&titleInfo_update); if (titleInfo_aoc.IsValid()) titlesToConvert.emplace_back(&titleInfo_aoc); if (titlesToConvert.empty()) return; // get short name CafeConsoleLanguage languageId = CafeConsoleLanguage::EN; // todo - use user's locale std::string shortName; if (titleInfo_base.IsValid()) shortName = titleInfo_base.GetMetaInfo()->GetShortName(languageId); else if (titleInfo_update.IsValid()) shortName = titleInfo_update.GetMetaInfo()->GetShortName(languageId); else if (titleInfo_aoc.IsValid()) shortName = titleInfo_aoc.GetMetaInfo()->GetShortName(languageId); if (!shortName.empty()) { boost::replace_all(shortName, ":", ""); } // for the default output directory we use the first game path configured by the user std::string defaultDir = ""; if (!GetConfig().game_paths.empty()) defaultDir = GetConfig().game_paths.front(); // get the short name, which we will use as a suggested default file name std::string defaultFileName = std::move(shortName); boost::replace_all(defaultFileName, "/", ""); boost::replace_all(defaultFileName, "\\", ""); CafeConsoleRegion region = CafeConsoleRegion::Auto; if (titleInfo_base.IsValid() && titleInfo_base.HasValidXmlInfo()) region = titleInfo_base.GetMetaInfo()->GetRegion(); else if (titleInfo_update.IsValid() && titleInfo_update.HasValidXmlInfo()) region = titleInfo_update.GetMetaInfo()->GetRegion(); if (region == CafeConsoleRegion::JPN) defaultFileName.append(" (JP)"); else if (region == CafeConsoleRegion::EUR) defaultFileName.append(" (EU)"); else if (region == CafeConsoleRegion::USA) defaultFileName.append(" (US)"); if (titleInfo_update.IsValid()) { defaultFileName.append(fmt::format(" (v{})", titleInfo_update.GetAppTitleVersion())); } defaultFileName.append(".wua"); // ask the user to provide a path for the output file wxFileDialog saveFileDialog(this, _("Save Wii U game archive file"), defaultDir, wxHelper::FromUtf8(defaultFileName), "WUA files (*.wua)|*.wua", wxFD_SAVE | wxFD_OVERWRITE_PROMPT); if (saveFileDialog.ShowModal() == wxID_CANCEL || saveFileDialog.GetPath().IsEmpty()) return; fs::path outputPath(wxHelper::MakeFSPath(saveFileDialog.GetPath())); fs::path outputPathTmp(wxHelper::MakeFSPath(saveFileDialog.GetPath().append("__tmp"))); struct ZArchiveWriterContext { static void NewOutputFile(const int32_t partIndex, void* _ctx) { ZArchiveWriterContext* ctx = (ZArchiveWriterContext*)_ctx; ctx->fs = FileStream::createFile2(ctx->outputPath); if (!ctx->fs) ctx->isValid = false; } static void WriteOutputData(const void* data, size_t length, void* _ctx) { ZArchiveWriterContext* ctx = (ZArchiveWriterContext*)_ctx; if (ctx->fs) ctx->fs->writeData(data, length); } bool RecursivelyCountFiles(const std::string& fscPath) { sint32 fscStatus; std::unique_ptr<FSCVirtualFile> vfDir(fsc_openDirIterator(fscPath.c_str(), &fscStatus)); if (!vfDir) return false; if (cancelled) return false; FSCDirEntry dirEntry; while (fsc_nextDir(vfDir.get(), &dirEntry)) { if (dirEntry.isFile) { totalInputFileSize += (uint64)dirEntry.fileSize; totalFileCount++; } else if (dirEntry.isDirectory) { if (!RecursivelyCountFiles(fmt::format("{}{}/", fscPath, dirEntry.path))) { return false; } } else cemu_assert_unimplemented(); } return true; } bool RecursivelyAddFiles(std::string archivePath, std::string fscPath) { sint32 fscStatus; std::unique_ptr<FSCVirtualFile> vfDir(fsc_openDirIterator(fscPath.c_str(), &fscStatus)); if (!vfDir) return false; if (cancelled) return false; zaWriter->MakeDir(archivePath.c_str(), false); FSCDirEntry dirEntry; while (fsc_nextDir(vfDir.get(), &dirEntry)) { if (dirEntry.isFile) { zaWriter->StartNewFile((archivePath + dirEntry.path).c_str()); std::unique_ptr<FSCVirtualFile> vFile(fsc_open((fscPath + dirEntry.path).c_str(), FSC_ACCESS_FLAG::OPEN_FILE | FSC_ACCESS_FLAG::READ_PERMISSION, &fscStatus)); if (!vFile) return false; transferBuffer.resize(32 * 1024); // 32KB uint32 readBytes; while (true) { readBytes = vFile->fscReadData(transferBuffer.data(), transferBuffer.size()); if(readBytes == 0) break; zaWriter->AppendData(transferBuffer.data(), readBytes); if (cancelled) return false; transferredInputBytes += readBytes; } currentFileIndex++; } else if (dirEntry.isDirectory) { if (!RecursivelyAddFiles(fmt::format("{}{}/", archivePath, dirEntry.path), fmt::format("{}{}/", fscPath, dirEntry.path))) return false; } else cemu_assert_unimplemented(); } return true; } bool LoadTitleMetaAndCountFiles(TitleInfo* titleInfo) { std::string temporaryMountPath = TitleInfo::GetUniqueTempMountingPath(); titleInfo->Mount(temporaryMountPath.c_str(), "", FSC_PRIORITY_BASE); bool r = RecursivelyCountFiles(temporaryMountPath); titleInfo->Unmount(temporaryMountPath.c_str()); return r; } bool StoreTitle(TitleInfo* titleInfo) { std::string temporaryMountPath = TitleInfo::GetUniqueTempMountingPath(); titleInfo->Mount(temporaryMountPath.c_str(), "", FSC_PRIORITY_BASE); bool r = RecursivelyAddFiles(fmt::format("{:016x}_v{}/", titleInfo->GetAppTitleId(), titleInfo->GetAppTitleVersion()), temporaryMountPath); titleInfo->Unmount(temporaryMountPath.c_str()); return r; } bool AddTitles(TitleInfo** titles, size_t count) { currentFileIndex = 0; totalFileCount = 0; // count files for (size_t i = 0; i < count; i++) { if (!LoadTitleMetaAndCountFiles(titles[i])) return false; if (cancelled) return false; } // store files for (size_t i = 0; i < count; i++) { if (!StoreTitle(titles[i])) return false; } return true; } ~ZArchiveWriterContext() { delete fs; delete zaWriter; }; fs::path outputPath; FileStream* fs; ZArchiveWriter* zaWriter{}; bool isValid{false}; std::vector<uint8> transferBuffer; std::atomic_bool cancelled{false}; // progress std::atomic_uint32_t totalFileCount{}; std::atomic_uint32_t currentFileIndex{}; std::atomic_uint64_t totalInputFileSize{}; std::atomic_uint64_t transferredInputBytes{}; }writerContext; // mount and store writerContext.isValid = true; writerContext.outputPath = outputPathTmp; writerContext.zaWriter = new ZArchiveWriter(&ZArchiveWriterContext::NewOutputFile, &ZArchiveWriterContext::WriteOutputData, &writerContext); if (!writerContext.isValid) { // failed to create file wxMessageBox(_("Unable to create file"), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } // open progress dialog wxGenericProgressDialog progressDialog("Converting to .wua", _("Counting files..."), 100, // range this, // parent wxPD_CAN_ABORT ); progressDialog.Show(); auto asyncWorker = std::async(std::launch::async, &ZArchiveWriterContext::AddTitles, &writerContext, titlesToConvert.data(), titlesToConvert.size()); while (!future_is_ready(asyncWorker)) { if (writerContext.cancelled) { progressDialog.Update(0, _("Stopping...")); } else if (writerContext.currentFileIndex != 0) { uint64 numSizeCompleted = writerContext.transferredInputBytes; uint64 numSizeTotal = writerContext.totalInputFileSize; uint32 pct = (uint32)(numSizeCompleted * (uint64)100 / numSizeTotal); pct = std::min(pct, (uint32)100); if (pct >= 100) pct = 99; // never set it to 100 as progress == total will make .Update() call ShowModal() and lock up this loop std::string textSuffix = fmt::format(" ({}MiB/{}MiB)", numSizeCompleted / 1024 / 1024, numSizeTotal / 1024 / 1024); progressDialog.Update(pct, _("Converting files...") + textSuffix); } else { progressDialog.Update(0, _("Collecting list of files..." + fmt::format(" ({})", writerContext.totalFileCount.load()))); } if (progressDialog.WasCancelled()) writerContext.cancelled.store(true); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } progressDialog.Update(100-1, _("Finalizing...")); bool r = asyncWorker.get(); if (!r) { delete writerContext.fs; writerContext.fs = nullptr; std::error_code ec; fs::remove(outputPathTmp, ec); return; } writerContext.zaWriter->Finalize(); delete writerContext.fs; writerContext.fs = nullptr; // verify the created WUA file ZArchiveReader* zreader = ZArchiveReader::OpenFromFile(outputPathTmp); if (!zreader) { wxMessageBox(_("Conversion failed\n"), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); std::error_code ec; fs::remove(outputPathTmp, ec); return; } // todo - do a quick verification here delete zreader; // finish progressDialog.Hide(); fs::rename(outputPathTmp, outputPath); // ask user if they want to delete the original titles // todo CafeTitleList::Refresh(); wxMessageBox(_("Conversion finished\n"), _("Complete"), wxOK | wxCENTRE | wxICON_INFORMATION, this); } void wxTitleManagerList::OnClose(wxCloseEvent& event) { event.Skip(); // wait until all tasks are complete if (m_context_worker.valid()) m_context_worker.get(); } void wxTitleManagerList::OnColumnClick(wxListEvent& event) { const int column = event.GetColumn(); SortEntries(column); event.Skip(); } void wxTitleManagerList::RemoveItem(long item) { const int item_count = GetItemCount(); const ItemData* ref = nullptr; long counter = 0; for(auto it = m_sorted_data.begin(); it != m_sorted_data.end(); ++it) { if (!it->get().visible) continue; if (item != counter++) continue; ref = &(it->get()); m_sorted_data.erase(it); break; } // shouldn't happen if (ref == nullptr) return; for(auto it = m_data.begin(); it != m_data.end(); ++it) { if (ref != (*it).get()) continue; m_data.erase(it); break; } SetItemCount(std::max(0, item_count - 1)); RefreshPage(); } void wxTitleManagerList::RemoveItem(const TitleEntry& entry) { const int item_count = GetItemCount(); const TitleEntry* ref = &entry; for (auto it = m_sorted_data.begin(); it != m_sorted_data.end(); ++it) { if (ref != &it->get().entry) continue; m_sorted_data.erase(it); break; } for (auto it = m_data.begin(); it != m_data.end(); ++it) { if (ref != &(*it).get()->entry) continue; m_data.erase(it); break; } SetItemCount(std::max(0, item_count - 1)); RefreshPage(); } void wxTitleManagerList::OnItemSelected(wxListEvent& event) { event.Skip(); m_tooltip_timer->Stop(); const auto selection = event.GetIndex(); if (selection == wxNOT_FOUND) { m_tooltip_window->Hide(); return; } const auto entry = GetTitleEntry(selection); if (!entry.has_value()) { m_tooltip_window->Hide(); return; } m_tooltip_window->Hide(); return; //const auto mouse_position = wxGetMousePosition() - GetScreenPosition(); //m_tooltip_window->SetPosition(wxPoint(mouse_position.x + 15, mouse_position.y + 15)); //wxString msg; //switch(entry->error) //{ //case TitleError::WrongBaseLocation: // msg = _("This base game is installed at the wrong location."); // break; //case TitleError::WrongUpdateLocation: // msg = _("This update is installed at the wrong location."); // break; //case TitleError::WrongDlcLocation: // msg = _("This DLC is installed at the wrong location."); // break; //default: // return;; //} //m_tooltip_text->SetLabel(formatWxString("{}\n{}", msg, _("You can use the context menu to fix it."))); //m_tooltip_window->Fit(); //m_tooltip_timer->StartOnce(250); } enum ContextMenuEntries { kContextMenuOpenDirectory = wxID_HIGHEST + 1, kContextMenuDelete, kContextMenuLaunch, kContextMenuVerifyGameFiles, kContextMenuConvertToWUA, }; void wxTitleManagerList::OnContextMenu(wxContextMenuEvent& event) { // still doing work if (m_context_worker.valid() && !future_is_ready(m_context_worker)) return; wxMenu menu; menu.Bind(wxEVT_COMMAND_MENU_SELECTED, &wxTitleManagerList::OnContextMenuSelected, this); const auto selection = GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED); if (selection == wxNOT_FOUND) return; const auto entry = GetTitleEntry(selection); if (!entry.has_value()) return; if(entry->type == EntryType::Base) menu.Append(kContextMenuLaunch, _("&Launch title")); menu.Append(kContextMenuOpenDirectory, _("&Open directory")); if (entry->type != EntryType::Save) menu.Append(kContextMenuVerifyGameFiles, _("&Verify integrity of game files")); menu.AppendSeparator(); if (entry->type != EntryType::Save && entry->format != EntryFormat::WUA) { menu.Append(kContextMenuConvertToWUA, _("Convert to compressed Wii U archive (.wua)")); menu.AppendSeparator(); } menu.Append(kContextMenuDelete, _("&Delete")); PopupMenu(&menu); // TODO: fix tooltip position } bool wxTitleManagerList::DeleteEntry(long index, const TitleEntry& entry) { wxDTorFunc reset_text(wxQueueEvent, this, new wxSetStatusBarTextEvent(wxEmptyString, 1)); wxQueueEvent(this, new wxSetStatusBarTextEvent("Deleting entry...", 1)); wxString msg; const bool is_directory = fs::is_directory(entry.path); if(is_directory) msg = formatWxString(_("Are you really sure that you want to delete the following folder:\n{}"), _pathToUtf8(entry.path)); else msg = formatWxString(_("Are you really sure that you want to delete the following file:\n{}"), _pathToUtf8(entry.path)); const auto result = wxMessageBox(msg, _("Warning"), wxYES_NO | wxCENTRE | wxICON_EXCLAMATION, this); if (result == wxNO) return false; std::error_code ec; if (is_directory) { if (entry.type != EntryType::Save) { // delete content, meta, code folders first const auto content = entry.path / "content"; fs::remove_all(content, ec); const auto meta = entry.path / "meta"; fs::remove_all(meta, ec); const auto code = entry.path / "code"; fs::remove_all(code, ec); } else { // delete meta, user folders first const auto meta = entry.path / "meta"; fs::remove_all(meta, ec); const auto user = entry.path / "user"; fs::remove_all(user, ec); } // check if folder is empty if(fs::is_empty(entry.path, ec)) fs::remove_all(entry.path, ec); } else // simply remove file fs::remove(entry.path, ec); if(ec) { const auto error_msg = formatWxString(_("Error when trying to delete the entry:\n{}"), GetSystemErrorMessage(ec)); wxMessageBox(error_msg, _("Error"), wxOK|wxCENTRE, this); return false; } // thread safe request to delete entry const auto evt = new wxCommandEvent(wxEVT_REMOVE_ITEM); evt->SetInt(index); wxQueueEvent(this, evt); return true; } void wxTitleManagerList::OnContextMenuSelected(wxCommandEvent& event) { // still doing work if (m_context_worker.valid() && !future_is_ready(m_context_worker)) return; const auto selection = GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED); if (selection == wxNOT_FOUND) return; const auto entry = GetTitleEntry(selection); if (!entry.has_value()) return; switch (event.GetId()) { case kContextMenuOpenDirectory: { const auto path = fs::is_directory(entry->path) ? entry->path : entry->path.parent_path(); wxLaunchDefaultBrowser(wxHelper::FromUtf8(fmt::format("file:{}", _pathToUtf8(path)))); } break; case kContextMenuDelete: m_context_worker = std::async(std::launch::async, &wxTitleManagerList::DeleteEntry, this, selection, entry.value()); break; case kContextMenuLaunch: { try { MainWindow::RequestLaunchGame(entry->path, wxLaunchGameEvent::INITIATED_BY::TITLE_MANAGER); Close(); } catch (const std::exception& ex) { cemuLog_log(LogType::Force, "wxTitleManagerList::OnContextMenuSelected: can't launch title: {}", ex.what()); } } break; case kContextMenuVerifyGameFiles: (new ChecksumTool(this, entry.value()))->Show(); break; case kContextMenuConvertToWUA: OnConvertToCompressedFormat(entry.value().title_id, entry.value().location_uid); break; } } void wxTitleManagerList::OnTimer(wxTimerEvent& event) { if(event.GetTimer().GetId() != m_tooltip_timer->GetId()) { event.Skip(); return; } m_tooltip_window->Show(); } void wxTitleManagerList::OnRemoveItem(wxCommandEvent& event) { RemoveItem(event.GetInt()); } void wxTitleManagerList::OnRemoveEntry(wxCommandEvent& event) { wxASSERT(event.GetClientData() != nullptr); RemoveItem(*(TitleEntry*)event.GetClientData()); } wxString wxTitleManagerList::GetTitleEntryText(const TitleEntry& entry, ItemColumn column) { switch (column) { case ColumnTitleId: return formatWxString("{:08x}-{:08x}", (uint32) (entry.title_id >> 32), (uint32) (entry.title_id & 0xFFFFFFFF)); case ColumnName: return entry.name; case ColumnType: return GetTranslatedTitleEntryType(entry.type); case ColumnVersion: return formatWxString("{}", entry.version); case ColumnRegion: return wxGetTranslation(fmt::format("{}", entry.region)); case ColumnFormat: { if (entry.type == EntryType::Save) return _("Save folder"); switch (entry.format) { case wxTitleManagerList::EntryFormat::Folder: return _("Folder"); case wxTitleManagerList::EntryFormat::WUD: return _("WUD"); case wxTitleManagerList::EntryFormat::NUS: return _("NUS"); case wxTitleManagerList::EntryFormat::WUA: return _("WUA"); case wxTitleManagerList::EntryFormat::WUHB: return _("WUHB"); } return ""; } case ColumnLocation: { const auto relative_mlc_path = _pathToUtf8(entry.path.lexically_relative(ActiveSettings::GetMlcPath())); if (relative_mlc_path.starts_with("usr") || relative_mlc_path.starts_with("sys")) return _("MLC"); else return _("Game Paths"); } default: UNREACHABLE; } return wxEmptyString; } wxString wxTitleManagerList::GetTranslatedTitleEntryType(EntryType type) { switch (type) { case EntryType::Base: return _("base"); case EntryType::Update: return _("update"); case EntryType::Dlc: return _("DLC"); case EntryType::Save: return _("save"); case EntryType::System: return _("system"); default: return std::to_string(static_cast<std::underlying_type_t<EntryType>>(type)); } } void wxTitleManagerList::HandleTitleListCallback(CafeTitleListCallbackEvent* evt) { if (evt->eventType != CafeTitleListCallbackEvent::TYPE::TITLE_DISCOVERED && evt->eventType != CafeTitleListCallbackEvent::TYPE::TITLE_REMOVED) return; auto& titleInfo = *evt->titleInfo; wxTitleManagerList::EntryType entryType; switch (titleInfo.GetTitleType()) { case TitleIdParser::TITLE_TYPE::BASE_TITLE_UPDATE: entryType = EntryType::Update; break; case TitleIdParser::TITLE_TYPE::AOC: entryType = EntryType::Dlc; break; case TitleIdParser::TITLE_TYPE::SYSTEM_DATA: case TitleIdParser::TITLE_TYPE::SYSTEM_OVERLAY_TITLE: case TitleIdParser::TITLE_TYPE::SYSTEM_TITLE: entryType = EntryType::System; break; default: entryType = EntryType::Base; } wxTitleManagerList::EntryFormat entryFormat; switch (titleInfo.GetFormat()) { case TitleInfo::TitleDataFormat::WUD: entryFormat = EntryFormat::WUD; break; case TitleInfo::TitleDataFormat::NUS: entryFormat = EntryFormat::NUS; break; case TitleInfo::TitleDataFormat::WIIU_ARCHIVE: entryFormat = EntryFormat::WUA; break; case TitleInfo::TitleDataFormat::WUHB: entryFormat = EntryFormat::WUHB; break; case TitleInfo::TitleDataFormat::HOST_FS: default: entryFormat = EntryFormat::Folder; break; } if (evt->eventType == CafeTitleListCallbackEvent::TYPE::TITLE_DISCOVERED) { if (titleInfo.IsCached()) return; // the title list only displays non-cached entries wxTitleManagerList::TitleEntry entry(entryType, entryFormat, titleInfo.GetPath()); ParsedMetaXml* metaInfo = titleInfo.GetMetaInfo(); if(titleInfo.IsSystemDataTitle()) return; // dont show system data titles for now entry.location_uid = titleInfo.GetUID(); entry.title_id = titleInfo.GetAppTitleId(); std::string name = metaInfo->GetLongName(GetConfig().console_language.GetValue()); const auto nl = name.find(L'\n'); if (nl != std::string::npos) name.replace(nl, 1, " - "); entry.name = wxString::FromUTF8(name); entry.version = titleInfo.GetAppTitleVersion(); entry.region = metaInfo->GetRegion(); auto* cmdEvt = new wxCommandEvent(wxEVT_TITLE_FOUND); cmdEvt->SetClientObject(new wxCustomData(entry)); wxQueueEvent(this, cmdEvt); } else if (evt->eventType == CafeTitleListCallbackEvent::TYPE::TITLE_REMOVED) { wxTitleManagerList::TitleEntry entry(entryType, entryFormat, titleInfo.GetPath()); entry.location_uid = titleInfo.GetUID(); entry.title_id = titleInfo.GetAppTitleId(); auto* cmdEvt = new wxCommandEvent(wxEVT_TITLE_REMOVED); cmdEvt->SetClientObject(new wxCustomData(entry)); wxQueueEvent(this, cmdEvt); } } void wxTitleManagerList::HandleSaveListCallback(struct CafeSaveListCallbackEvent* evt) { if (evt->eventType == CafeSaveListCallbackEvent::TYPE::SAVE_DISCOVERED) { ParsedMetaXml* metaInfo = evt->saveInfo->GetMetaInfo(); if (!metaInfo) return; auto& saveInfo = *evt->saveInfo; wxTitleManagerList::TitleEntry entry(EntryType::Save, EntryFormat::Folder, saveInfo.GetPath()); entry.location_uid = std::hash<uint64>() ( metaInfo->GetTitleId() ); entry.title_id = metaInfo->GetTitleId(); std::string name = metaInfo->GetLongName(GetConfig().console_language.GetValue()); const auto nl = name.find(L'\n'); if (nl != std::string::npos) name.replace(nl, 1, " - "); entry.name = wxString::FromUTF8(name); entry.version = metaInfo->GetTitleVersion(); entry.region = metaInfo->GetRegion(); auto* cmdEvt = new wxCommandEvent(wxEVT_TITLE_FOUND); cmdEvt->SetClientObject(new wxCustomData(entry)); wxQueueEvent(this, cmdEvt); } } void wxTitleManagerList::OnTitleDiscovered(wxCommandEvent& event) { auto* obj = dynamic_cast<wxTitleManagerList::TitleEntryData_t*>(event.GetClientObject()); wxASSERT(obj); AddTitle(obj); } void wxTitleManagerList::OnTitleRemoved(wxCommandEvent& event) { auto* obj = dynamic_cast<wxTitleManagerList::TitleEntryData_t*>(event.GetClientObject()); wxASSERT(obj); for (auto& itr : m_data) { if (itr.get()->entry.location_uid == obj->get().location_uid) { RemoveItem(itr.get()->entry); break; } } } void wxTitleManagerList::AddTitle(TitleEntryData_t* obj) { const auto& data = obj->GetData(); if (GetTitleEntryByUID(data.location_uid).has_value()) return; // already in list m_data.emplace_back(std::make_unique<ItemData>(true, data)); m_sorted_data.emplace_back(*m_data[m_data.size() - 1]); SetItemCount(m_data.size()); } int wxTitleManagerList::AddImage(const wxImage& image) const { return -1; // m_image_list->Add(image.Scale(kListIconWidth, kListIconWidth, wxIMAGE_QUALITY_BICUBIC)); } // return < bool wxTitleManagerList::SortFunc(int column, const Type_t& v1, const Type_t& v2) { // last sort option if (column == -1) return v1.get().entry.path.compare(v2.get().entry.path) < 0; // visible have always priority if (!v1.get().visible && v2.get().visible) return false; else if (v1.get().visible && !v2.get().visible) return true; const auto& entry1 = v1.get().entry; const auto& entry2 = v2.get().entry; // check column: title id -> type -> path if (column == ColumnTitleId) { // ensure strong ordering -> use type since only one entry should be now (should be changed if every save for every user is displayed separately?) if (entry1.title_id == entry2.title_id) return SortFunc(ColumnType, v1, v2); return entry1.title_id < entry2.title_id; } else if (column == ColumnName) { const int tmp = entry1.name.CmpNoCase(entry2.name); if(tmp == 0) return SortFunc(ColumnTitleId, v1, v2); return tmp < 0; } else if (column == ColumnType) { if(entry1.type == entry2.type) return SortFunc(-1, v1, v2); return std::underlying_type_t<EntryType>(entry1.type) < std::underlying_type_t<EntryType>(entry2.type); } else if (column == ColumnVersion) { if(entry1.version == entry2.version) return SortFunc(ColumnTitleId, v1, v2); return std::underlying_type_t<EntryType>(entry1.version) < std::underlying_type_t<EntryType>(entry2.version); } else if (column == ColumnRegion) { if(entry1.region == entry2.region) return SortFunc(ColumnTitleId, v1, v2); return std::underlying_type_t<EntryType>(entry1.region) < std::underlying_type_t<EntryType>(entry2.region); } else if (column == ColumnFormat) { if(entry1.format == entry2.format) return SortFunc(ColumnType, v1, v2); return std::underlying_type_t<EntryType>(entry1.format) < std::underlying_type_t<EntryType>(entry2.format); } return false; } void wxTitleManagerList::SortEntries(int column) { if(column == -1) { column = m_last_column_sorted; m_last_column_sorted = -1; if (column == -1) column = ColumnTitleId; } if (column != ColumnTitleId && column != ColumnName && column != ColumnType && column != ColumnVersion && column != ColumnRegion && column != ColumnFormat) return; if (m_last_column_sorted != column) { m_last_column_sorted = column; m_sort_less = true; } else m_sort_less = !m_sort_less; std::sort(m_sorted_data.begin(), m_sorted_data.end(), [this, column](const Type_t& v1, const Type_t& v2) -> bool { const bool result = SortFunc(column, v1, v2); return m_sort_less ? result : !result; }); RefreshPage(); } void wxTitleManagerList::RefreshPage() { long item_count = GetItemCount(); if (item_count > 0) RefreshItems(GetTopItem(), std::min(item_count - 1, GetTopItem() + GetCountPerPage() + 1)); } int wxTitleManagerList::Filter(const wxString& filter, const wxString& prefix, ItemColumn column) { if (prefix.empty()) return -1; if (!filter.StartsWith(prefix)) return -1; int counter = 0; const auto tmp_filter = filter.substr(prefix.size() - 1).Trim(false); for (auto&& data : m_data) { if (GetTitleEntryText(data->entry, column).Upper().Contains(tmp_filter)) { data->visible = true; ++counter; } else data->visible = false; } return counter; } void wxTitleManagerList::Filter(const wxString& filter) { if(filter.empty()) { std::for_each(m_data.begin(), m_data.end(), [](ItemDataPtr& data) { data->visible = true; }); SetItemCount(m_data.size()); RefreshPage(); return; } const auto filter_upper = filter.Upper().Trim(false).Trim(true); int counter = 0; if (const auto result = Filter(filter_upper, "TITLEID:", ColumnTitleId) != -1) counter = result; else if (const auto result = Filter(filter_upper, "NAME:", ColumnName) != -1) counter = result; else if (const auto result = Filter(filter_upper, "TYPE:", ColumnType) != -1) counter = result; else if (const auto result = Filter(filter_upper, "REGION:", ColumnRegion) != -1) counter = result; else if (const auto result = Filter(filter_upper, "VERSION:", ColumnVersion) != -1) counter = result; else if (const auto result = Filter(filter_upper, "FORMAT:", ColumnFormat) != -1) counter = result; else if(filter_upper == "ERROR") { for (auto&& data : m_data) { bool visible = true; data->visible = visible; if (visible) ++counter; } } else { for (auto&& data : m_data) { bool visible = false; if (data->entry.name.Upper().Contains(filter_upper)) visible = true; else if (GetTitleEntryText(data->entry, ColumnTitleId).Upper().Contains(filter_upper)) visible = true; else if (GetTitleEntryText(data->entry, ColumnType).Upper().Contains(filter_upper)) visible = true; data->visible = visible; if (visible) ++counter; } } SetItemCount(counter); RefreshPage(); } size_t wxTitleManagerList::GetCountByType(EntryType type) const { size_t result = 0; for(const auto& data : m_data) { if (data->entry.type == type) ++result; } return result; } void wxTitleManagerList::ClearItems() { m_sorted_data.clear(); m_data.clear(); SetItemCount(0); RefreshPage(); } void wxTitleManagerList::AutosizeColumns() { wxAutosizeColumns(this, ColumnTitleId, ColumnMAX - 1); }
38,145
C++
.cpp
1,172
29.71843
175
0.727246
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,992
wxGameList.cpp
cemu-project_Cemu/src/gui/components/wxGameList.cpp
#include "gui/components/wxGameList.h" #include "gui/helpers/wxCustomData.h" #include "util/helpers/helpers.h" #include "gui/GameProfileWindow.h" #include <numeric> #include <wx/wupdlock.h> #include <wx/menu.h> #include <wx/mstream.h> #include <wx/imaglist.h> #include <wx/textdlg.h> #include <wx/stattext.h> #include <wx/sizer.h> #include <wx/wfstream.h> #include <wx/imagpng.h> #include <wx/string.h> #include <wx/utils.h> #include <wx/clipbrd.h> #include <boost/algorithm/string.hpp> #include <boost/tokenizer.hpp> #include "config/ActiveSettings.h" #include "config/LaunchSettings.h" #include "Cafe/TitleList/GameInfo.h" #include "Cafe/TitleList/TitleList.h" #include "gui/CemuApp.h" #include "gui/helpers/wxHelpers.h" #include "gui/MainWindow.h" #include "../wxHelper.h" #include "Cafe/IOSU/PDM/iosu_pdm.h" // for last played and play time #if BOOST_OS_WINDOWS // for shortcut creation #include <windows.h> #include <winnls.h> #include <shobjidl.h> #include <objbase.h> #include <objidl.h> #include <shlguid.h> #include <shlobj.h> #endif // public events wxDEFINE_EVENT(wxEVT_OPEN_SETTINGS, wxCommandEvent); wxDEFINE_EVENT(wxEVT_GAMELIST_BEGIN_UPDATE, wxCommandEvent); wxDEFINE_EVENT(wxEVT_GAMELIST_END_UPDATE, wxCommandEvent); wxDEFINE_EVENT(wxEVT_OPEN_GRAPHIC_PACK, wxTitleIdEvent); // internal events wxDEFINE_EVENT(wxEVT_GAME_ENTRY_ADDED_OR_REMOVED, wxTitleIdEvent); constexpr uint64 kDefaultEntryData = 0x1337; void _stripPathFilename(fs::path& path) { if (path.has_extension()) path = path.parent_path(); } std::list<fs::path> _getCachesPaths(const TitleId& titleId) { std::list<fs::path> cachePaths{ ActiveSettings::GetCachePath(L"shaderCache/driver/vk/{:016x}.bin", titleId), ActiveSettings::GetCachePath(L"shaderCache/precompiled/{:016x}_spirv.bin", titleId), ActiveSettings::GetCachePath(L"shaderCache/precompiled/{:016x}_gl.bin", titleId), ActiveSettings::GetCachePath(L"shaderCache/transferable/{:016x}_shaders.bin", titleId), ActiveSettings::GetCachePath(L"shaderCache/transferable/{:016x}_vkpipeline.bin", titleId)}; cachePaths.remove_if( [](const fs::path& cachePath) { std::error_code ec; return !fs::exists(cachePath, ec); }); return cachePaths; } wxGameList::wxGameList(wxWindow* parent, wxWindowID id) : wxListCtrl(parent, id, wxDefaultPosition, wxDefaultSize, GetStyleFlags(Style::kList)), m_style(Style::kList) { const auto& config = GetConfig(); InsertColumn(ColumnHiddenName, "", wxLIST_FORMAT_LEFT, 0); if(config.show_icon_column) InsertColumn(ColumnIcon, _("Icon"), wxLIST_FORMAT_LEFT, kListIconWidth); else InsertColumn(ColumnIcon, _("Icon"), wxLIST_FORMAT_LEFT, 0); InsertColumn(ColumnName, _("Game"), wxLIST_FORMAT_LEFT, config.column_width.name); InsertColumn(ColumnVersion, _("Version"), wxLIST_FORMAT_RIGHT, config.column_width.version); InsertColumn(ColumnDLC, _("DLC"), wxLIST_FORMAT_RIGHT, config.column_width.dlc); InsertColumn(ColumnGameTime, _("You've played"), wxLIST_FORMAT_LEFT, config.column_width.game_time); InsertColumn(ColumnGameStarted, _("Last played"), wxLIST_FORMAT_LEFT, config.column_width.game_started); InsertColumn(ColumnRegion, _("Region"), wxLIST_FORMAT_LEFT, config.column_width.region); InsertColumn(ColumnTitleID, _("Title ID"), wxLIST_FORMAT_LEFT, config.column_width.title_id); const char transparent_bitmap[kIconWidth * kIconWidth * 4] = {0}; wxBitmap blank(transparent_bitmap, kIconWidth, kIconWidth); blank.UseAlpha(true); m_image_list = new wxImageList(kIconWidth, kIconWidth); m_image_list->Add(blank); wxListCtrl::SetImageList(m_image_list, wxIMAGE_LIST_NORMAL); m_image_list_small = new wxImageList(kListIconWidth, kListIconWidth); wxBitmap::Rescale(blank, {kListIconWidth, kListIconWidth}); m_image_list_small->Add(blank); wxListCtrl::SetImageList(m_image_list_small, wxIMAGE_LIST_SMALL); m_tooltip_window = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxNO_BORDER); auto* tooltip_sizer = new wxBoxSizer(wxVERTICAL); tooltip_sizer->Add(new wxStaticText(m_tooltip_window, wxID_ANY, _("This game entry seems to be either an update or the base game was merged with update data\nBroken game dumps cause various problems during emulation and may even stop working at all in future Cemu versions\nPlease make sure the base game is intact and install updates only with the File->Install Update/DLC option")), 0, wxALL, 5); m_tooltip_window->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_INFOBK)); m_tooltip_window->SetSizerAndFit(tooltip_sizer); m_tooltip_window->Hide(); m_tooltip_timer = new wxTimer(this); Bind(wxEVT_CLOSE_WINDOW, &wxGameList::OnClose, this); Bind(wxEVT_MOTION, &wxGameList::OnMouseMove, this); Bind(wxEVT_LIST_KEY_DOWN, &wxGameList::OnKeyDown, this); Bind(wxEVT_CONTEXT_MENU, &wxGameList::OnContextMenu, this); Bind(wxEVT_LIST_ITEM_ACTIVATED, &wxGameList::OnItemActivated, this); Bind(wxEVT_GAME_ENTRY_ADDED_OR_REMOVED, &wxGameList::OnGameEntryUpdatedByTitleId, this); Bind(wxEVT_TIMER, &wxGameList::OnTimer, this); Bind(wxEVT_LEAVE_WINDOW, &wxGameList::OnLeaveWindow, this); Bind(wxEVT_LIST_COL_CLICK, &wxGameList::OnColumnClick, this); Bind(wxEVT_LIST_COL_BEGIN_DRAG, &wxGameList::OnColumnBeginResize, this); Bind(wxEVT_LIST_COL_END_DRAG, &wxGameList::OnColumnResize, this); Bind(wxEVT_LIST_COL_RIGHT_CLICK, &wxGameList::OnColumnRightClick, this); Bind(wxEVT_SIZE, &wxGameList::OnGameListSize, this); m_callbackIdTitleList = CafeTitleList::RegisterCallback([](CafeTitleListCallbackEvent* evt, void* ctx) { ((wxGameList*)ctx)->HandleTitleListCallback(evt); }, this); // start async worker (for icon loading) m_async_worker_active = true; m_async_worker_thread = std::thread(&wxGameList::AsyncWorkerThread, this); } wxGameList::~wxGameList() { CafeTitleList::UnregisterCallback(m_callbackIdTitleList); m_tooltip_timer->Stop(); // shut down async worker m_async_worker_active.store(false); m_async_task_count.increment(); m_async_worker_thread.join(); // destroy image lists delete m_image_list; delete m_image_list_small; // clear image cache m_icon_cache_mtx.lock(); m_icon_cache.clear(); m_icon_cache_mtx.unlock(); } void wxGameList::LoadConfig() { const auto& config = GetConfig(); SetStyle((Style)config.game_list_style, false); if (!config.game_list_column_order.empty()) { wxArrayInt order; order.reserve(ColumnCounts); const auto order_string = std::string_view(config.game_list_column_order).substr(1); const boost::char_separator<char> sep(","); boost::tokenizer tokens(order_string.begin(), order_string.end(), sep); for(const auto& token : tokens) { order.push_back(ConvertString<int>(token, 10)); } #ifdef wxHAS_LISTCTRL_COLUMN_ORDER if(order.GetCount() == ColumnCounts) SetColumnsOrder(order); #endif } } void wxGameList::OnGameListSize(wxSizeEvent &event) { event.Skip(); // when using a sizer-based layout, do not change the size of the wxComponent in its own wxSizeEvent handler to avoid some UI issues. int last_col_index = 0; for(int i = GetColumnCount() - 1; i > 0; i--) { #ifdef wxHAS_LISTCTRL_COLUMN_ORDER if(GetColumnWidth(GetColumnIndexFromOrder(i)) > 0) { last_col_index = GetColumnIndexFromOrder(i); break; } #else if(GetColumnWidth(i) > 0) { last_col_index = i; break; } #endif } wxListEvent column_resize_event(wxEVT_LIST_COL_END_DRAG); column_resize_event.SetColumn(last_col_index); wxPostEvent(this, column_resize_event); } void wxGameList::AdjustLastColumnWidth() { wxWindowUpdateLocker windowlock(this); int last_col_index = 0; int last_col_width = GetClientSize().GetWidth(); for (int i = 1; i < GetColumnCount(); i++) { #ifdef wxHAS_LISTCTRL_COLUMN_ORDER if (GetColumnWidth(GetColumnIndexFromOrder(i)) > 0) { last_col_index = GetColumnIndexFromOrder(i); last_col_width -= GetColumnWidth(last_col_index); } #else if (GetColumnWidth(i) > 0) { last_col_index = i; last_col_width -= GetColumnWidth(i); } #endif } last_col_width += GetColumnWidth(last_col_index); if (last_col_width < GetColumnDefaultWidth(last_col_index)) // keep a minimum width last_col_width = GetColumnDefaultWidth(last_col_index); SetColumnWidth(last_col_index, last_col_width); } // todo: scale all columns using a ratio instead of hardcoding exact widths int wxGameList::GetColumnDefaultWidth(int column) { switch (column) { case ColumnIcon: return kListIconWidth; case ColumnName: return DefaultColumnSize::name; case ColumnVersion: return DefaultColumnSize::version; case ColumnDLC: return DefaultColumnSize::dlc; case ColumnGameTime: return DefaultColumnSize::game_time; case ColumnGameStarted: return DefaultColumnSize::game_started; case ColumnRegion: return DefaultColumnSize::region; case ColumnTitleID: return DefaultColumnSize::title_id; default: return 80; } } void wxGameList::SaveConfig(bool flush) { auto& config = GetConfig(); config.game_list_style = (int)m_style; #ifdef wxHAS_LISTCTRL_COLUMN_ORDER config.game_list_column_order = fmt::format("{}", GetColumnsOrder()); #endif if (flush) g_config.Save(); } bool wxGameList::IsVisible(long item) const { wxRect itemRect; GetItemRect(item, itemRect); const wxRect clientRect = GetClientRect(); bool visible = clientRect.Intersects(itemRect); return visible; } void wxGameList::ReloadGameEntries(bool cached) { wxWindowUpdateLocker windowlock(this); DeleteAllItems(); // tell the game list to rescan CafeTitleList::Refresh(); // resend notifications for all known titles by re-registering the callback CafeTitleList::UnregisterCallback(m_callbackIdTitleList); m_callbackIdTitleList = CafeTitleList::RegisterCallback([](CafeTitleListCallbackEvent* evt, void* ctx) { ((wxGameList*)ctx)->HandleTitleListCallback(evt); }, this); } long wxGameList::FindListItemByTitleId(uint64 title_id) const { for (int i = 0; i < GetItemCount(); ++i) { const auto id = (uint64)GetItemData(i); if (id == title_id) return i; } return wxNOT_FOUND; } // get title name with cache std::string wxGameList::GetNameByTitleId(uint64 titleId) { auto it = m_name_cache.find(titleId); if (it != m_name_cache.end()) return it->second; TitleInfo titleInfo; if (!CafeTitleList::GetFirstByTitleId(titleId, titleInfo)) return "Unknown title"; std::string name; if (!GetConfig().GetGameListCustomName(titleId, name)) name = titleInfo.GetMetaTitleName(); m_name_cache.emplace(titleId, name); return name; } void wxGameList::SetStyle(Style style, bool save) { if (m_style == style) return; wxWindowUpdateLocker updatelock(this); m_style = style; SetWindowStyleFlag(GetStyleFlags(m_style)); uint64 selected_title_id = 0; auto selection = GetNextItem(wxNOT_FOUND, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED); if (selection != wxNOT_FOUND) { selected_title_id = (uint64)GetItemData(selection); selection = wxNOT_FOUND; } switch(style) { case Style::kIcons: wxListCtrl::SetImageList(m_image_list, wxIMAGE_LIST_NORMAL); break; case Style::kSmallIcons: wxListCtrl::SetImageList(m_image_list_small, wxIMAGE_LIST_NORMAL); break; } ReloadGameEntries(); SortEntries(); UpdateItemColors(); if(selection != wxNOT_FOUND) { SetItemState(selection, wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED, wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED); EnsureVisible(selection); } if(save) { GetConfig().game_list_style = (int)m_style; g_config.Save(); } if (style == Style::kList) ApplyGameListColumnWidths(); } long wxGameList::GetStyleFlags(Style style) const { switch (style) { case Style::kList: return (wxLC_SINGLE_SEL | wxLC_REPORT); case Style::kIcons: return (wxLC_SINGLE_SEL | wxLC_ICON); case Style::kSmallIcons: return (wxLC_SINGLE_SEL | wxLC_ICON); default: wxASSERT(false); return (wxLC_SINGLE_SEL | wxLC_REPORT); } } void wxGameList::UpdateItemColors(sint32 startIndex) { wxWindowUpdateLocker lock(this); wxColour bgColourPrimary = GetBackgroundColour(); wxColour bgColourSecondary = wxHelper::CalculateAccentColour(bgColourPrimary); for (int i = startIndex; i < GetItemCount(); ++i) { const auto titleId = (uint64)GetItemData(i); if (GetConfig().IsGameListFavorite(titleId)) { SetItemBackgroundColour(i, kFavoriteColor); SetItemTextColour(i, 0x000000UL); } else if ((i&1) != 0) { SetItemBackgroundColour(i, bgColourPrimary); SetItemTextColour(i, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT)); } else { SetItemBackgroundColour(i, bgColourSecondary); SetItemTextColour(i, wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT)); } } } static inline int order_to_int(const std::weak_ordering &wo) { // no easy conversion seems to exists in C++20 if (wo == std::weak_ordering::less) return -1; else if (wo == std::weak_ordering::greater) return 1; return 0; } int wxGameList::SortComparator(uint64 titleId1, uint64 titleId2, SortData* sortData) { const auto isFavoriteA = GetConfig().IsGameListFavorite(titleId1); const auto isFavoriteB = GetConfig().IsGameListFavorite(titleId2); const auto& name1 = GetNameByTitleId(titleId1); const auto& name2 = GetNameByTitleId(titleId2); if(sortData->dir > 0) return order_to_int(std::tie(isFavoriteB, name1) <=> std::tie(isFavoriteA, name2)); else return order_to_int(std::tie(isFavoriteB, name2) <=> std::tie(isFavoriteA, name1)); } int wxGameList::SortFunction(wxIntPtr item1, wxIntPtr item2, wxIntPtr sortData) { const auto sort_data = (SortData*)sortData; const int dir = sort_data->dir; return sort_data->thisptr->SortComparator((uint64)item1, (uint64)item2, sort_data); } void wxGameList::SortEntries(int column) { if (column == -1) column = s_last_column; else { if (s_last_column == column) { s_last_column = 0; s_direction = -1; } else { s_last_column = column; s_direction = 1; } } switch (column) { case ColumnName: case ColumnGameTime: case ColumnGameStarted: case ColumnRegion: { SortData data{ this, column, s_direction }; SortItems(SortFunction, (wxIntPtr)&data); break; } } } void wxGameList::OnKeyDown(wxListEvent& event) { event.Skip(); if (m_style != Style::kList) return; const auto keycode = std::tolower(event.m_code); if (keycode == WXK_LEFT) { const auto item_count = GetItemCount(); if (item_count > 0) { auto selection = (int)GetNextItem(wxNOT_FOUND, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED); if (selection == wxNOT_FOUND) selection = 0; else selection = std::max(0, selection - GetCountPerPage()); SetItemState(wxNOT_FOUND, 0, wxLIST_STATE_SELECTED); SetItemState(selection, wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED, wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED); EnsureVisible(selection); } } else if (keycode == WXK_RIGHT) { const auto item_count = GetItemCount(); if (item_count > 0) { auto selection = (int)GetNextItem(wxNOT_FOUND, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED); if (selection == wxNOT_FOUND) selection = 0; selection = std::min(item_count - 1, selection + GetCountPerPage()); SetItemState(wxNOT_FOUND, 0, wxLIST_STATE_SELECTED); SetItemState(selection, wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED, wxLIST_STATE_SELECTED | wxLIST_STATE_FOCUSED); EnsureVisible(selection); } } } enum ContextMenuEntries { kContextMenuRefreshGames = wxID_HIGHEST + 1, kContextMenuStart, kWikiPage, kContextMenuFavorite, kContextMenuEditName, kContextMenuGameFolder, kContextMenuSaveFolder, kContextMenuUpdateFolder, kContextMenuDLCFolder, kContextMenuEditGraphicPacks, kContextMenuEditGameProfile, kContextMenuRemoveCache, kContextMenuStyleList, kContextMenuStyleIcon, kContextMenuStyleIconSmall, kContextMenuCreateShortcut, kContextMenuCopyTitleName, kContextMenuCopyTitleId, kContextMenuCopyTitleImage }; void wxGameList::OnContextMenu(wxContextMenuEvent& event) { auto& config = GetConfig(); wxMenu menu; menu.Bind(wxEVT_COMMAND_MENU_SELECTED, &wxGameList::OnContextMenuSelected, this); const auto selection = GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED); if (selection != wxNOT_FOUND) { const auto title_id = (uint64)GetItemData(selection); GameInfo2 gameInfo = CafeTitleList::GetGameInfo(title_id); if (gameInfo.IsValid()) { menu.SetClientData((void*)title_id); menu.Append(kContextMenuStart, _("&Start")); bool isFavorite = GetConfig().IsGameListFavorite(title_id); std::error_code ec; menu.AppendSeparator(); menu.AppendCheckItem(kContextMenuFavorite, _("&Favorite"))->Check(isFavorite); menu.Append(kContextMenuEditName, _("&Edit name")); menu.AppendSeparator(); menu.Append(kWikiPage, _("&Wiki page")); menu.Append(kContextMenuGameFolder, _("&Game directory")); menu.Append(kContextMenuSaveFolder, _("&Save directory"))->Enable(fs::is_directory(gameInfo.GetSaveFolder(), ec)); menu.Append(kContextMenuUpdateFolder, _("&Update directory"))->Enable(gameInfo.HasUpdate()); menu.Append(kContextMenuDLCFolder, _("&DLC directory"))->Enable(gameInfo.HasAOC()); menu.AppendSeparator(); menu.Append(kContextMenuRemoveCache, _("&Remove shader caches"))->Enable(!_getCachesPaths(gameInfo.GetBaseTitleId()).empty()); menu.AppendSeparator(); menu.Append(kContextMenuEditGraphicPacks, _("&Edit graphic packs")); menu.Append(kContextMenuEditGameProfile, _("&Edit game profile")); menu.AppendSeparator(); #if BOOST_OS_LINUX || BOOST_OS_WINDOWS menu.Append(kContextMenuCreateShortcut, _("&Create shortcut")); #endif menu.AppendSeparator(); menu.Append(kContextMenuCopyTitleName, _("&Copy Title Name")); menu.Append(kContextMenuCopyTitleId, _("&Copy Title ID")); menu.Append(kContextMenuCopyTitleImage, _("&Copy Title Image")); menu.AppendSeparator(); } } menu.Append(kContextMenuRefreshGames, _("&Refresh game list"))->Enable(!CafeTitleList::IsScanning()); menu.AppendSeparator(); menu.AppendRadioItem(kContextMenuStyleList, _("Style: &List"))->Check(m_style == Style::kList); menu.AppendRadioItem(kContextMenuStyleIcon, _("Style: &Icons"))->Check(m_style == Style::kIcons); menu.AppendRadioItem(kContextMenuStyleIconSmall, _("Style: &Small Icons"))->Check(m_style == Style::kSmallIcons); PopupMenu(&menu); } void wxGameList::OnContextMenuSelected(wxCommandEvent& event) { const auto title_id = (uint64)((wxMenu*)event.GetEventObject())->GetClientData(); if (title_id) { GameInfo2 gameInfo = CafeTitleList::GetGameInfo(title_id); if (gameInfo.IsValid()) { switch (event.GetId()) { case kContextMenuStart: { MainWindow::RequestLaunchGame(gameInfo.GetBase().GetPath(), wxLaunchGameEvent::INITIATED_BY::GAME_LIST); break; } case kContextMenuFavorite: GetConfig().SetGameListFavorite(title_id, !GetConfig().IsGameListFavorite(title_id)); SortEntries(); UpdateItemColors(); //SaveConfig(); break; case kContextMenuEditName: { std::string customName = ""; if (!GetConfig().GetGameListCustomName(title_id, customName)) customName.clear(); wxTextEntryDialog dialog(this, wxEmptyString, _("Enter a custom game title"), wxHelper::FromUtf8(customName)); if(dialog.ShowModal() == wxID_OK) { const auto custom_name = dialog.GetValue(); GetConfig().SetGameListCustomName(title_id, custom_name.utf8_string()); m_name_cache.clear(); g_config.Save(); // update list entry for (int i = 0; i < GetItemCount(); ++i) { const auto id = (uint64)GetItemData(i); if (id == title_id) { if (m_style == Style::kList) SetItem(i, ColumnName, wxHelper::FromUtf8(GetNameByTitleId(title_id))); break; } } SortEntries(); UpdateItemColors(); } break; } case kContextMenuGameFolder: { fs::path path(gameInfo.GetBase().GetPath()); _stripPathFilename(path); wxLaunchDefaultBrowser(wxHelper::FromUtf8(fmt::format("file:{}", _pathToUtf8(path)))); break; } case kWikiPage: { // https://wiki.cemu.info/wiki/GameIDs // WUP-P-ALZP if (gameInfo.GetBase().ParseXmlInfo()) { std::string productCode = gameInfo.GetBase().GetMetaInfo()->GetProductCode(); const auto tokens = TokenizeView(productCode, '-'); wxASSERT(!tokens.empty()); const std::string company_code = gameInfo.GetBase().GetMetaInfo()->GetCompanyCode(); wxASSERT(company_code.size() >= 2); wxLaunchDefaultBrowser(wxHelper::FromUtf8(fmt::format("https://wiki.cemu.info/wiki/{}{}", *tokens.rbegin(), company_code.substr(company_code.size() - 2).c_str()))); } break; } case kContextMenuSaveFolder: { wxLaunchDefaultBrowser(wxHelper::FromUtf8(fmt::format("file:{}", _pathToUtf8(gameInfo.GetSaveFolder())))); break; } case kContextMenuUpdateFolder: { fs::path path(gameInfo.GetUpdate().GetPath()); _stripPathFilename(path); wxLaunchDefaultBrowser(wxHelper::FromUtf8(fmt::format("file:{}", _pathToUtf8(path)))); break; } case kContextMenuDLCFolder: { fs::path path(gameInfo.GetAOC().front().GetPath()); _stripPathFilename(path); wxLaunchDefaultBrowser(wxHelper::FromUtf8(fmt::format("file:{}", _pathToUtf8(path)))); break; } case kContextMenuRemoveCache: { RemoveCache(_getCachesPaths(gameInfo.GetBaseTitleId()), gameInfo.GetTitleName()); break; } case kContextMenuEditGraphicPacks: { wxTitleIdEvent open_event(wxEVT_OPEN_GRAPHIC_PACK, title_id); ProcessWindowEvent(open_event); break; } case kContextMenuEditGameProfile: { (new GameProfileWindow(GetParent(), title_id))->Show(); break; } case kContextMenuCreateShortcut: { #if BOOST_OS_LINUX || BOOST_OS_WINDOWS CreateShortcut(gameInfo); #endif break; } case kContextMenuCopyTitleName: { if (wxTheClipboard->Open()) { wxTheClipboard->SetData(new wxTextDataObject(wxString::FromUTF8(gameInfo.GetTitleName()))); wxTheClipboard->Close(); } break; } case kContextMenuCopyTitleId: { if (wxTheClipboard->Open()) { wxTheClipboard->SetData(new wxTextDataObject(fmt::format("{:016x}", gameInfo.GetBaseTitleId()))); wxTheClipboard->Close(); } break; } case kContextMenuCopyTitleImage: { if (wxTheClipboard->Open()) { int icon_large; int icon_small; if (!QueryIconForTitle(title_id, icon_large, icon_small)) break; auto icon = m_image_list->GetBitmap(icon_large); wxTheClipboard->SetData(new wxBitmapDataObject(icon)); wxTheClipboard->Close(); } break; } } } } switch (event.GetId()) { case kContextMenuRefreshGames: ReloadGameEntries(false); break; case kContextMenuStyleList: SetStyle(Style::kList); break; case kContextMenuStyleIcon: SetStyle(Style::kIcons); break; case kContextMenuStyleIconSmall: SetStyle(Style::kSmallIcons); break; } } void wxGameList::OnColumnClick(wxListEvent& event) { const int column = event.GetColumn(); SortEntries(column); UpdateItemColors(); event.Skip(); } void wxGameList::OnColumnRightClick(wxListEvent& event) { enum ItemIds { ResetWidth = wxID_HIGHEST + 1, ResetOrder, ShowIcon, ShowName, ShowVersion, ShowDlc, ShowGameTime, ShowLastPlayed, ShowRegion, ShowTitleId }; const int column = event.GetColumn(); wxMenu menu; menu.SetClientObject(new wxCustomData(column)); menu.Append(ResetWidth, _("Reset &width")); menu.Append(ResetOrder, _("Reset &order")) ; menu.AppendSeparator(); menu.AppendCheckItem(ShowIcon, _("Show &icon"))->Check(GetColumnWidth(ColumnIcon) > 0); menu.AppendCheckItem(ShowName, _("Show &name"))->Check(GetColumnWidth(ColumnName) > 0); menu.AppendCheckItem(ShowVersion, _("Show &version"))->Check(GetColumnWidth(ColumnVersion) > 0); menu.AppendCheckItem(ShowDlc, _("Show &dlc"))->Check(GetColumnWidth(ColumnDLC) > 0); menu.AppendCheckItem(ShowGameTime, _("Show &game time"))->Check(GetColumnWidth(ColumnGameTime) > 0); menu.AppendCheckItem(ShowLastPlayed, _("Show &last played"))->Check(GetColumnWidth(ColumnGameStarted) > 0); menu.AppendCheckItem(ShowRegion, _("Show &region"))->Check(GetColumnWidth(ColumnRegion) > 0); menu.AppendCheckItem(ShowTitleId, _("Show &title ID"))->Check(GetColumnWidth(ColumnTitleID) > 0); menu.Bind(wxEVT_COMMAND_MENU_SELECTED, [this](wxCommandEvent& event) { event.Skip(); const auto menu = dynamic_cast<wxMenu*>(event.GetEventObject()); const int column = dynamic_cast<wxCustomData<int>*>(menu->GetClientObject())->GetData(); auto& config = GetConfig(); switch (event.GetId()) { case ShowIcon: config.show_icon_column = menu->IsChecked(ShowIcon); break; case ShowName: config.column_width.name = menu->IsChecked(ShowName) ? DefaultColumnSize::name : 0; break; case ShowVersion: config.column_width.version = menu->IsChecked(ShowVersion) ? DefaultColumnSize::version : 0; break; case ShowDlc: config.column_width.dlc = menu->IsChecked(ShowDlc) ? DefaultColumnSize::dlc : 0; break; case ShowGameTime: config.column_width.game_time = menu->IsChecked(ShowGameTime) ? DefaultColumnSize::game_time : 0; break; case ShowLastPlayed: config.column_width.game_started = menu->IsChecked(ShowLastPlayed) ? DefaultColumnSize::game_started : 0; break; case ShowRegion: config.column_width.region = menu->IsChecked(ShowRegion) ? DefaultColumnSize::region : 0; break; case ShowTitleId: config.column_width.title_id = menu->IsChecked(ShowTitleId) ? DefaultColumnSize::title_id : 0; break; case ResetWidth: { switch (column) { case ColumnIcon: break; case ColumnName: config.column_width.name = DefaultColumnSize::name; break; case ColumnVersion: config.column_width.version = DefaultColumnSize::version; break; case ColumnDLC: config.column_width.dlc = DefaultColumnSize::dlc; break; case ColumnGameTime: config.column_width.game_time = DefaultColumnSize::game_time; break; case ColumnGameStarted: config.column_width.game_started = DefaultColumnSize::game_started; break; case ColumnRegion: config.column_width.region = DefaultColumnSize::region; break; case ColumnTitleID: config.column_width.title_id = DefaultColumnSize::title_id; default: return; } break; } case ResetOrder: { config.game_list_column_order.clear(); wxArrayInt order(ColumnCounts); std::iota(order.begin(), order.end(), 0); #ifdef wxHAS_LISTCTRL_COLUMN_ORDER SetColumnsOrder(order); #endif //ApplyGameListColumnWidths(); //Refresh(); //return; } } g_config.Save(); ApplyGameListColumnWidths(); }); PopupMenu(&menu); event.Skip(); } void wxGameList::ApplyGameListColumnWidths() { const auto& config = GetConfig(); wxWindowUpdateLocker lock(this); if(config.show_icon_column) SetColumnWidth(ColumnIcon, kListIconWidth); else SetColumnWidth(ColumnIcon, 0); SetColumnWidth(ColumnName, config.column_width.name); SetColumnWidth(ColumnVersion, config.column_width.version); SetColumnWidth(ColumnDLC, config.column_width.dlc); SetColumnWidth(ColumnGameTime, config.column_width.game_time); SetColumnWidth(ColumnGameStarted, config.column_width.game_started); SetColumnWidth(ColumnRegion, config.column_width.region); SetColumnWidth(ColumnTitleID, config.column_width.title_id); AdjustLastColumnWidth(); } void wxGameList::OnColumnBeginResize(wxListEvent& event) { const int column = event.GetColumn(); const int width = GetColumnWidth(column); int last_col_index = 0; for(int i = GetColumnCount() - 1; i > 0; i--) { #ifdef wxHAS_LISTCTRL_COLUMN_ORDER if(GetColumnWidth(GetColumnIndexFromOrder(i)) > 0) { last_col_index = GetColumnIndexFromOrder(i); break; } #else if(GetColumnWidth(i) > 0) { last_col_index = i; break; } #endif } if (width == 0 || column == ColumnIcon || column == last_col_index) // dont resize hidden name, icon, and last column event.Veto(); else event.Skip(); } void wxGameList::OnColumnResize(wxListEvent& event) { event.Skip(); if(m_style != Style::kList) return; const int column = event.GetColumn(); const int width = GetColumnWidth(column); auto& config = GetConfig(); switch (column) { case ColumnName: config.column_width.name = width; break; case ColumnVersion: config.column_width.version = width; break; case ColumnDLC: config.column_width.dlc = width; break; case ColumnGameTime: config.column_width.game_time = width; break; case ColumnGameStarted: config.column_width.game_started = width; break; case ColumnRegion: config.column_width.region = width; break; default: break; } g_config.Save(); AdjustLastColumnWidth(); } void wxGameList::OnClose(wxCloseEvent& event) { event.Skip(); m_exit = true; } int wxGameList::FindInsertPosition(TitleId titleId) { SortData data{ this, s_last_column, s_direction }; const auto itemCount = GetItemCount(); if (itemCount == 0) return 0; // todo - optimize this with binary search for (int i = 0; i < itemCount; i++) { if (SortComparator(titleId, (uint64)GetItemData(i), &data) <= 0) return i; } return itemCount; } void wxGameList::OnGameEntryUpdatedByTitleId(wxTitleIdEvent& event) { const auto titleId = event.GetTitleId(); GameInfo2 gameInfo = CafeTitleList::GetGameInfo(titleId); if (!gameInfo.IsValid() || gameInfo.IsSystemDataTitle()) { // entry no longer exists or is not a valid game // we dont need to remove list entries here because all delete operations should trigger a full list refresh return; } TitleId baseTitleId = gameInfo.GetBaseTitleId(); bool isNewEntry = false; auto index = FindListItemByTitleId(baseTitleId); if(index == wxNOT_FOUND) { // entry doesn't exist index = InsertItem(FindInsertPosition(baseTitleId), wxHelper::FromUtf8(GetNameByTitleId(baseTitleId))); SetItemPtrData(index, baseTitleId); isNewEntry = true; } int icon = 0; /* 0 is the default empty icon */ int icon_small = 0; /* 0 is the default empty icon */ QueryIconForTitle(baseTitleId, icon, icon_small); if (m_style == Style::kList) { SetItemColumnImage(index, ColumnIcon, icon_small); SetItem(index, ColumnName, wxHelper::FromUtf8(GetNameByTitleId(baseTitleId))); SetItem(index, ColumnVersion, fmt::format("{}", gameInfo.GetVersion())); if(gameInfo.HasAOC()) SetItem(index, ColumnDLC, fmt::format("{}", gameInfo.GetAOCVersion())); else SetItem(index, ColumnDLC, wxString()); if (isNewEntry) { iosu::pdm::GameListStat playTimeStat; if (iosu::pdm::GetStatForGamelist(baseTitleId, playTimeStat)) { // time played uint32 minutesPlayed = playTimeStat.numMinutesPlayed; if (minutesPlayed == 0) SetItem(index, ColumnGameTime, wxEmptyString); else if (minutesPlayed < 60) SetItem(index, ColumnGameTime, formatWxString(wxPLURAL("{} minute", "{} minutes", minutesPlayed), minutesPlayed)); else { uint32 hours = minutesPlayed / 60; uint32 minutes = minutesPlayed % 60; wxString hoursText = formatWxString(wxPLURAL("{} hour", "{} hours", hours), hours); wxString minutesText = formatWxString(wxPLURAL("{} minute", "{} minutes", minutes), minutes); SetItem(index, ColumnGameTime, hoursText + " " + minutesText); } // last played if (playTimeStat.last_played.year != 0) { const wxDateTime tmp((wxDateTime::wxDateTime_t)playTimeStat.last_played.day, (wxDateTime::Month)playTimeStat.last_played.month, (wxDateTime::wxDateTime_t)playTimeStat.last_played.year, 0, 0, 0, 0); SetItem(index, ColumnGameStarted, tmp.FormatDate()); } else SetItem(index, ColumnGameStarted, _("never")); } else { SetItem(index, ColumnGameTime, wxEmptyString); SetItem(index, ColumnGameStarted, _("never")); } } const auto region_text = fmt::format("{}", gameInfo.GetRegion()); SetItem(index, ColumnRegion, wxGetTranslation(region_text)); SetItem(index, ColumnTitleID, fmt::format("{:016x}", baseTitleId)); } else if (m_style == Style::kIcons) { SetItemImage(index, icon); } else if (m_style == Style::kSmallIcons) { SetItemImage(index, icon_small); } if (isNewEntry) UpdateItemColors(index); } void wxGameList::OnItemActivated(wxListEvent& event) { event.Skip(); const auto selection = event.GetIndex(); if (selection == wxNOT_FOUND) return; const auto item_data = (uint64)GetItemData(selection); if(item_data == kDefaultEntryData) { const wxCommandEvent open_settings_event(wxEVT_OPEN_SETTINGS); wxPostEvent(this, open_settings_event); return; } TitleInfo titleInfo; if (!CafeTitleList::GetFirstByTitleId(item_data, titleInfo)) return; if (!titleInfo.IsValid()) return; MainWindow::RequestLaunchGame(titleInfo.GetPath(), wxLaunchGameEvent::INITIATED_BY::GAME_LIST); } void wxGameList::OnTimer(wxTimerEvent& event) { const auto& obj = event.GetTimer().GetId(); if(obj == m_tooltip_timer->GetId()) { m_tooltip_window->Hide(); auto flag = wxLIST_HITTEST_ONITEM; const auto item = this->HitTest(m_mouse_position, flag); if(item != wxNOT_FOUND ) { //const auto title_id = (uint64_t)GetItemData(item); //auto entry = GetGameEntry(title_id); //if (entry && entry->is_update) //{ // m_tooltip_window->SetPosition(wxPoint(m_mouse_position.x + 15, m_mouse_position.y + 15)); // m_tooltip_window->SendSizeEvent(); // m_tooltip_window->Show(); //} } } } void wxGameList::OnMouseMove(wxMouseEvent& event) { m_tooltip_timer->Stop(); m_tooltip_timer->StartOnce(250); m_mouse_position = event.GetPosition(); } void wxGameList::OnLeaveWindow(wxMouseEvent& event) { m_tooltip_timer->Stop(); m_tooltip_window->Hide(); } void wxGameList::HandleTitleListCallback(CafeTitleListCallbackEvent* evt) { if (evt->eventType == CafeTitleListCallbackEvent::TYPE::TITLE_DISCOVERED || evt->eventType == CafeTitleListCallbackEvent::TYPE::TITLE_REMOVED) { wxQueueEvent(this, new wxTitleIdEvent(wxEVT_GAME_ENTRY_ADDED_OR_REMOVED, evt->titleInfo->GetAppTitleId())); } } void wxGameList::RemoveCache(const std::list<fs::path>& cachePaths, const std::string& titleName) { wxMessageDialog dialog(this, formatWxString(_("Remove the shader caches for {}?"), titleName), _("Remove shader caches"), wxCENTRE | wxYES_NO | wxICON_EXCLAMATION); dialog.SetYesNoLabels(_("Yes"), _("No")); const auto dialogResult = dialog.ShowModal(); if (dialogResult != wxID_YES) return; std::list<std::string> errs; for (const fs::path& cachePath : cachePaths) { if (std::error_code ec; !fs::remove(cachePath, ec)) errs.emplace_back(fmt::format("{} : {}", cachePath.string(), ec.message())); } if (errs.empty()) wxMessageDialog(this, _("The shader caches were removed!"), _("Shader caches removed"), wxCENTRE | wxOK | wxICON_INFORMATION).ShowModal(); else wxMessageDialog(this, formatWxString(_("Failed to remove the shader caches:\n{}"), fmt::join(errs, "\n")), _("Error"), wxCENTRE | wxOK | wxICON_ERROR).ShowModal(); } void wxGameList::AsyncWorkerThread() { SetThreadName("GameListWorker"); while (m_async_worker_active) { m_async_task_count.decrementWithWait(); // get next titleId to load (if any) m_async_worker_mutex.lock(); bool hasJob = !m_icon_load_queue.empty(); TitleId titleId = 0; if (hasJob) { titleId = m_icon_load_queue.front(); m_icon_load_queue.erase(m_icon_load_queue.begin()); } m_async_worker_mutex.unlock(); if (!hasJob) continue; if(m_icon_loaded.find(titleId) != m_icon_loaded.end()) continue; m_icon_loaded.emplace(titleId); // load and process icon TitleInfo titleInfo; if( !CafeTitleList::GetFirstByTitleId(titleId, titleInfo) ) continue; std::string tempMountPath = TitleInfo::GetUniqueTempMountingPath(); if(!titleInfo.Mount(tempMountPath, "", FSC_PRIORITY_BASE)) continue; auto tgaData = fsc_extractFile((tempMountPath + "/meta/iconTex.tga").c_str()); // try iconTex.tga.gz if (!tgaData) { tgaData = fsc_extractFile((tempMountPath + "/meta/iconTex.tga.gz").c_str()); if (tgaData) { auto decompressed = zlibDecompress(*tgaData, 70*1024); std::swap(tgaData, decompressed); } } bool iconSuccessfullyLoaded = false; if (tgaData && tgaData->size() > 16) { wxMemoryInputStream tmp_stream(tgaData->data(), tgaData->size()); const wxImage image(tmp_stream); // todo - is wxImageList thread safe? int icon = m_image_list->Add(image.Scale(kIconWidth, kIconWidth, wxIMAGE_QUALITY_BICUBIC)); int icon_small = m_image_list_small->Add(image.Scale(kListIconWidth, kListIconWidth, wxIMAGE_QUALITY_BICUBIC)); // store in cache m_icon_cache_mtx.lock(); m_icon_cache.try_emplace(titleId, icon, icon_small); m_icon_cache_mtx.unlock(); iconSuccessfullyLoaded = true; } else { cemuLog_log(LogType::Force, "Failed to load icon for title {:016x}", titleId); } titleInfo.Unmount(tempMountPath); // notify UI about loaded icon if(iconSuccessfullyLoaded) wxQueueEvent(this, new wxTitleIdEvent(wxEVT_GAME_ENTRY_ADDED_OR_REMOVED, titleId)); } } void wxGameList::RequestLoadIconAsync(TitleId titleId) { m_async_worker_mutex.lock(); m_icon_load_queue.push_back(titleId); m_async_worker_mutex.unlock(); m_async_task_count.increment(); } // returns icons if cached, otherwise an async request to load them is made bool wxGameList::QueryIconForTitle(TitleId titleId, int& icon, int& iconSmall) { m_icon_cache_mtx.lock(); auto it = m_icon_cache.find(titleId); if (it == m_icon_cache.end()) { m_icon_cache_mtx.unlock(); RequestLoadIconAsync(titleId); return false; } icon = it->second.first; iconSmall = it->second.second; m_icon_cache_mtx.unlock(); return true; } void wxGameList::DeleteCachedStrings() { m_name_cache.clear(); } #if BOOST_OS_LINUX void wxGameList::CreateShortcut(GameInfo2& gameInfo) { const auto titleId = gameInfo.GetBaseTitleId(); const auto titleName = wxString::FromUTF8(gameInfo.GetTitleName()); auto exePath = ActiveSettings::GetExecutablePath(); const char* flatpakId = getenv("FLATPAK_ID"); const wxString desktopEntryName = wxString::Format("%s.desktop", titleName); wxFileDialog entryDialog(this, _("Choose desktop entry location"), "~/.local/share/applications", desktopEntryName, "Desktop file (*.desktop)|*.desktop", wxFD_SAVE | wxFD_CHANGE_DIR | wxFD_OVERWRITE_PROMPT); const auto result = entryDialog.ShowModal(); if (result == wxID_CANCEL) return; const auto output_path = entryDialog.GetPath(); std::optional<fs::path> iconPath; // Obtain and convert icon [&]() { int iconIndex, smallIconIndex; if (!QueryIconForTitle(titleId, iconIndex, smallIconIndex)) { cemuLog_log(LogType::Force, "Icon hasn't loaded"); return; } const fs::path outIconDir = ActiveSettings::GetUserDataPath("icons"); if (!fs::exists(outIconDir) && !fs::create_directories(outIconDir)) { cemuLog_log(LogType::Force, "Failed to create icon directory"); return; } iconPath = outIconDir / fmt::format("{:016x}.png", gameInfo.GetBaseTitleId()); wxFileOutputStream pngFileStream(_pathToUtf8(iconPath.value())); auto image = m_image_list->GetIcon(iconIndex).ConvertToImage(); wxPNGHandler pngHandler; if (!pngHandler.SaveFile(&image, pngFileStream, false)) { iconPath = std::nullopt; cemuLog_log(LogType::Force, "Icon failed to save"); } }(); std::string desktopExecEntry = flatpakId ? fmt::format("/usr/bin/flatpak run {0} --title-id {1:016x}", flatpakId, titleId) : fmt::format("{0:?} --title-id {1:016x}", _pathToUtf8(exePath), titleId); // 'Icon' accepts spaces in file name, does not accept quoted file paths // 'Exec' does not accept non-escaped spaces, and can accept quoted file paths auto desktopEntryString = fmt::format( "[Desktop Entry]\n" "Name={0}\n" "Comment=Play {0} on Cemu\n" "Exec={1}\n" "Icon={2}\n" "Terminal=false\n" "Type=Application\n" "Categories=Game;\n", titleName.utf8_string(), desktopExecEntry, _pathToUtf8(iconPath.value_or(""))); if (flatpakId) desktopEntryString += fmt::format("X-Flatpak={}\n", flatpakId); std::ofstream outputStream(output_path.utf8_string()); if (!outputStream.good()) { auto errorMsg = formatWxString(_("Failed to save desktop entry to {}"), output_path.utf8_string()); wxMessageBox(errorMsg, _("Error"), wxOK | wxCENTRE | wxICON_ERROR); return; } outputStream << desktopEntryString; } #elif BOOST_OS_WINDOWS void wxGameList::CreateShortcut(GameInfo2& gameInfo) { const auto titleId = gameInfo.GetBaseTitleId(); const auto titleName = wxString::FromUTF8(gameInfo.GetTitleName()); auto exePath = ActiveSettings::GetExecutablePath(); // Get '%APPDATA%\Microsoft\Windows\Start Menu\Programs' path PWSTR userShortcutFolder; SHGetKnownFolderPath(FOLDERID_Programs, 0, NULL, &userShortcutFolder); const wxString shortcutName = wxString::Format("%s.lnk", titleName); wxFileDialog shortcutDialog(this, _("Choose shortcut location"), _pathToUtf8(userShortcutFolder), shortcutName, "Shortcut (*.lnk)|*.lnk", wxFD_SAVE | wxFD_CHANGE_DIR | wxFD_OVERWRITE_PROMPT); const auto result = shortcutDialog.ShowModal(); if (result == wxID_CANCEL) return; const auto outputPath = shortcutDialog.GetPath(); std::optional<fs::path> icon_path = std::nullopt; { int iconIdx; int smallIconIdx; if (!QueryIconForTitle(titleId, iconIdx, smallIconIdx)) { cemuLog_log(LogType::Force, "Icon hasn't loaded"); return; } const auto icon = m_image_list->GetIcon(iconIdx); const auto folder = ActiveSettings::GetUserDataPath("icons"); if (!fs::exists(folder) && !fs::create_directories(folder)) { cemuLog_log(LogType::Force, "Failed to create icon directory"); return; } wxBitmap bitmap{}; if (!bitmap.CopyFromIcon(icon)) { cemuLog_log(LogType::Force, "Failed to copy icon"); return; } icon_path = folder / fmt::format("{:016x}.ico", titleId); auto stream = wxFileOutputStream(_pathToUtf8(*icon_path)); auto image = bitmap.ConvertToImage(); wxICOHandler icohandler{}; if (!icohandler.SaveFile(&image, stream, false)) { icon_path = std::nullopt; cemuLog_log(LogType::Force, "Icon failed to save"); } } IShellLinkW* shellLink; HRESULT hres = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_IShellLink, reinterpret_cast<LPVOID*>(&shellLink)); if (SUCCEEDED(hres)) { const auto description = wxString::Format("Play %s on Cemu", titleName); const auto args = wxString::Format("-t %016llx", titleId); shellLink->SetPath(exePath.wstring().c_str()); shellLink->SetDescription(description.wc_str()); shellLink->SetArguments(args.wc_str()); shellLink->SetWorkingDirectory(exePath.parent_path().wstring().c_str()); if (icon_path) shellLink->SetIconLocation(icon_path->wstring().c_str(), 0); else shellLink->SetIconLocation(exePath.wstring().c_str(), 0); IPersistFile* shellLinkFile; // save the shortcut hres = shellLink->QueryInterface(IID_IPersistFile, reinterpret_cast<LPVOID*>(&shellLinkFile)); if (SUCCEEDED(hres)) { hres = shellLinkFile->Save(outputPath.wc_str(), TRUE); shellLinkFile->Release(); } shellLink->Release(); } if (!SUCCEEDED(hres)) { auto errorMsg = formatWxString(_("Failed to save shortcut to {}"), outputPath); wxMessageBox(errorMsg, _("Error"), wxOK | wxCENTRE | wxICON_ERROR); } } #endif
44,109
C++
.cpp
1,297
30.525058
399
0.725109
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,993
wxDownloadManagerList.cpp
cemu-project_Cemu/src/gui/components/wxDownloadManagerList.cpp
#include "gui/components/wxDownloadManagerList.h" #include "gui/helpers/wxHelpers.h" #include "util/helpers/SystemException.h" #include "Cafe/TitleList/GameInfo.h" #include "gui/components/wxGameList.h" #include "gui/helpers/wxCustomEvents.h" #include <wx/imaglist.h> #include <wx/wupdlock.h> #include <wx/menu.h> #include <wx/msgdlg.h> #include <wx/stattext.h> #include <wx/sizer.h> #include <wx/timer.h> #include <wx/panel.h> #include <functional> #include "config/ActiveSettings.h" #include "gui/ChecksumTool.h" #include "Cemu/Tools/DownloadManager/DownloadManager.h" #include "Cafe/TitleList/TitleId.h" #include "gui/MainWindow.h" wxDEFINE_EVENT(wxEVT_REMOVE_ENTRY, wxCommandEvent); wxDownloadManagerList::wxDownloadManagerList(wxWindow* parent, wxWindowID id) : wxListCtrl(parent, id, wxDefaultPosition, wxDefaultSize, wxLC_REPORT | wxLC_VIRTUAL) { AddColumns(); // tooltip TODO: extract class mb wxPanelTooltip m_tooltip_window = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxNO_BORDER); auto* tooltip_sizer = new wxBoxSizer(wxVERTICAL); m_tooltip_text = new wxStaticText(m_tooltip_window, wxID_ANY, wxEmptyString); tooltip_sizer->Add(m_tooltip_text , 0, wxALL, 5); m_tooltip_window->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_INFOBK)); m_tooltip_window->SetSizerAndFit(tooltip_sizer); m_tooltip_window->Hide(); m_tooltip_timer = new wxTimer(this); Bind(wxEVT_LIST_COL_CLICK, &wxDownloadManagerList::OnColumnClick, this); Bind(wxEVT_CONTEXT_MENU, &wxDownloadManagerList::OnContextMenu, this); Bind(wxEVT_LIST_ITEM_SELECTED, &wxDownloadManagerList::OnItemSelected, this); Bind(wxEVT_TIMER, &wxDownloadManagerList::OnTimer, this); Bind(wxEVT_REMOVE_ITEM, &wxDownloadManagerList::OnRemoveItem, this); Bind(wxEVT_REMOVE_ENTRY, &wxDownloadManagerList::OnRemoveEntry, this); Bind(wxEVT_CLOSE_WINDOW, &wxDownloadManagerList::OnClose, this); } boost::optional<const wxDownloadManagerList::TitleEntry&> wxDownloadManagerList::GetSelectedTitleEntry() const { const auto selection = GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED); if (selection != wxNOT_FOUND) { const auto tmp = GetTitleEntry(selection); if (tmp.has_value()) return tmp.value(); } return {}; } boost::optional<wxDownloadManagerList::TitleEntry&> wxDownloadManagerList::GetSelectedTitleEntry() { const auto selection = GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED); if (selection != wxNOT_FOUND) { const auto tmp = GetTitleEntry(selection); if (tmp.has_value()) return tmp.value(); } return {}; } boost::optional<wxDownloadManagerList::TitleEntry&> wxDownloadManagerList::GetTitleEntry(uint64 titleId, uint16 titleVersion) { for(const auto& v : m_data) { if (v->entry.titleId == titleId && v->entry.version == titleVersion) return v->entry; } return {}; } void wxDownloadManagerList::AddColumns() { wxListItem col0; col0.SetId(ColumnTitleId); col0.SetText(_("Title ID")); col0.SetWidth(120); InsertColumn(ColumnTitleId, col0); wxListItem col1; col1.SetId(ColumnName); col1.SetText(_("Name")); col1.SetWidth(260); InsertColumn(ColumnName, col1); wxListItem col2; col2.SetId(ColumnVersion); col2.SetText(_("Version")); col2.SetWidth(55); InsertColumn(ColumnVersion, col2); wxListItem col3; col3.SetId(ColumnType); col3.SetText(_("Type")); col3.SetWidth(60); InsertColumn(ColumnType, col3); wxListItem col4; col4.SetId(ColumnProgress); col4.SetText(_("Progress")); col4.SetWidth(wxLIST_AUTOSIZE_USEHEADER); InsertColumn(ColumnProgress, col4); wxListItem col5; col5.SetId(ColumnStatus); col5.SetText(_("Status")); col5.SetWidth(240); InsertColumn(ColumnStatus, col5); } wxString wxDownloadManagerList::OnGetItemText(long item, long column) const { if (item >= GetItemCount()) return wxEmptyString; const auto entry = GetTitleEntry(item); if (entry.has_value()) return GetTitleEntryText(entry.value(), (ItemColumn)column); return wxEmptyString; } wxItemAttr* wxDownloadManagerList::OnGetItemAttr(long item) const { const auto entry = GetTitleEntry(item); if (entry.has_value()) { auto& entryData = entry.value(); if (entryData.status == TitleDownloadStatus::Downloading || entryData.status == TitleDownloadStatus::Verifying || entryData.status == TitleDownloadStatus::Installing) { const wxColour kActiveColor{ 0xFFE0E0 }; static wxListItemAttr s_error_attr(GetTextColour(), kActiveColor, GetFont()); return &s_error_attr; } else if (entryData.status == TitleDownloadStatus::Installed && entryData.isPackage) { const wxColour kActiveColor{ 0xE0FFE0 }; static wxListItemAttr s_error_attr(GetTextColour(), kActiveColor, GetFont()); return &s_error_attr; } else if (entryData.status == TitleDownloadStatus::Error) { const wxColour kActiveColor{ 0xCCCCF2 }; static wxListItemAttr s_error_attr(GetTextColour(), kActiveColor, GetFont()); return &s_error_attr; } } const wxColour kSecondColor{ 0xFDF9F2 }; static wxListItemAttr s_coloured_attr(GetTextColour(), kSecondColor, GetFont()); return item % 2 == 0 ? nullptr : &s_coloured_attr; } boost::optional<wxDownloadManagerList::TitleEntry&> wxDownloadManagerList::GetTitleEntry(long item) { long counter = 0; for (const auto& data : m_sorted_data) { if (!data.get().visible) continue; if (item != counter++) continue; return data.get().entry; } return {}; } boost::optional<const wxDownloadManagerList::TitleEntry&> wxDownloadManagerList::GetTitleEntry(long item) const { long counter = 0; for (const auto& data : m_sorted_data) { if (!data.get().visible) continue; if (item != counter++) continue; return data.get().entry; } return {}; } void wxDownloadManagerList::OnClose(wxCloseEvent& event) { event.Skip(); // wait until all tasks are complete if (m_context_worker.valid()) m_context_worker.get(); g_mainFrame->RequestGameListRefresh(); // todo: add games instead of fully refreshing game list if a game is downloaded } void wxDownloadManagerList::OnColumnClick(wxListEvent& event) { const int column = event.GetColumn(); if (column == m_sort_by_column) { m_sort_less = !m_sort_less; } else { m_sort_by_column = column; m_sort_less = true; } SortEntries(); event.Skip(); } void wxDownloadManagerList::RemoveItem(long item) { const int item_count = GetItemCount(); const ItemData* ref = nullptr; long counter = 0; for(auto it = m_sorted_data.begin(); it != m_sorted_data.end(); ++it) { if (!it->get().visible) continue; if (item != counter++) continue; ref = &(it->get()); m_sorted_data.erase(it); break; } // shouldn't happen if (ref == nullptr) return; for(auto it = m_data.begin(); it != m_data.end(); ++it) { if (ref != (*it).get()) continue; m_data.erase(it); break; } SetItemCount(std::max(0, item_count - 1)); RefreshPage(); } void wxDownloadManagerList::RemoveItem(const TitleEntry& entry) { const int item_count = GetItemCount(); const TitleEntry* ref = &entry; for (auto it = m_sorted_data.begin(); it != m_sorted_data.end(); ++it) { if (ref != &it->get().entry) continue; m_sorted_data.erase(it); break; } for (auto it = m_data.begin(); it != m_data.end(); ++it) { if (ref != &(*it).get()->entry) continue; m_data.erase(it); break; } SetItemCount(std::max(0, item_count - 1)); RefreshPage(); } void wxDownloadManagerList::OnItemSelected(wxListEvent& event) { event.Skip(); m_tooltip_timer->Stop(); const auto selection = event.GetIndex(); if (selection == wxNOT_FOUND) { m_tooltip_window->Hide(); return; } } enum ContextMenuEntries { kContextMenuRetry = wxID_HIGHEST + 1, kContextMenuDownload, kContextMenuPause, kContextMenuResume, }; void wxDownloadManagerList::OnContextMenu(wxContextMenuEvent& event) { // still doing work if (m_context_worker.valid() && !future_is_ready(m_context_worker)) return; wxMenu menu; menu.Bind(wxEVT_COMMAND_MENU_SELECTED, &wxDownloadManagerList::OnContextMenuSelected, this); const auto selection = GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED); if (selection == wxNOT_FOUND) return; const auto entry = GetTitleEntry(selection); if (!entry.has_value()) return; if (entry->isPaused) menu.Append(kContextMenuResume, _("&Resume")); else if (entry->status == TitleDownloadStatus::Error) menu.Append(kContextMenuRetry, _("&Retry")); else if(entry->status == TitleDownloadStatus::Available) menu.Append(kContextMenuDownload, _("&Download")); //else if(entry->status == TitleDownloadStatus::Downloading || entry->status == TitleDownloadStatus::Initializing) // menu.Append(kContextMenuPause, _("&Pause")); buggy! PopupMenu(&menu); // TODO: fix tooltip position } void wxDownloadManagerList::SetCurrentDownloadMgr(DownloadManager* dlMgr) { std::unique_lock<std::mutex> _l(m_dlMgrMutex); m_dlMgr = dlMgr; } bool wxDownloadManagerList::StartDownloadEntry(const TitleEntry& entry) { std::unique_lock<std::mutex> _l(m_dlMgrMutex); if (m_dlMgr) m_dlMgr->initiateDownload(entry.titleId, entry.version); return true; } bool wxDownloadManagerList::RetryDownloadEntry(const TitleEntry& entry) { StartDownloadEntry(entry); return true; } bool wxDownloadManagerList::PauseDownloadEntry(const TitleEntry& entry) { std::unique_lock<std::mutex> _l(m_dlMgrMutex); if (m_dlMgr) m_dlMgr->pauseDownload(entry.titleId, entry.version); return true; } void wxDownloadManagerList::OnContextMenuSelected(wxCommandEvent& event) { // still doing work if (m_context_worker.valid() && !future_is_ready(m_context_worker)) return; const auto selection = GetNextItem(-1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED); if (selection == wxNOT_FOUND) return; const auto entry = GetTitleEntry(selection); if (!entry.has_value()) return; switch (event.GetId()) { case kContextMenuDownload: StartDownloadEntry(entry.value()); break; case kContextMenuRetry: RetryDownloadEntry(entry.value()); break; case kContextMenuResume: StartDownloadEntry(entry.value()); break; case kContextMenuPause: PauseDownloadEntry(entry.value()); break; } } void wxDownloadManagerList::OnTimer(wxTimerEvent& event) { if(event.GetTimer().GetId() != m_tooltip_timer->GetId()) { event.Skip(); return; } m_tooltip_window->Show(); } void wxDownloadManagerList::OnRemoveItem(wxCommandEvent& event) { RemoveItem(event.GetInt()); } void wxDownloadManagerList::OnRemoveEntry(wxCommandEvent& event) { wxASSERT(event.GetClientData() != nullptr); RemoveItem(*(TitleEntry*)event.GetClientData()); } wxString wxDownloadManagerList::GetTitleEntryText(const TitleEntry& entry, ItemColumn column) { switch (column) { case ColumnTitleId: return formatWxString("{:08x}-{:08x}", (uint32) (entry.titleId >> 32), (uint32) (entry.titleId & 0xFFFFFFFF)); case ColumnName: return entry.name; case ColumnType: return GetTranslatedTitleEntryType(entry.type); case ColumnVersion: { // dont show version for base game unless it is not v0 if (entry.type == EntryType::Base && entry.version == 0) return ""; if (entry.type == EntryType::DLC && entry.version == 0) return ""; return formatWxString("v{}", entry.version); } case ColumnProgress: { if (entry.status == TitleDownloadStatus::Downloading) { if (entry.progress >= 1000) return "100%"; return formatWxString("{:.1f}%", (float) entry.progress / 10.0f); // one decimal } else if (entry.status == TitleDownloadStatus::Installing || entry.status == TitleDownloadStatus::Checking || entry.status == TitleDownloadStatus::Verifying) { return formatWxString("{0}/{1}", entry.progress, entry.progressMax); // number of processed files/content files } return ""; } case ColumnStatus: { if (entry.isPaused) return _("Paused"); else if (entry.status == TitleDownloadStatus::Available) { if (entry.progress == 1) return _("Not installed (Partially downloaded)"); if (entry.progress == 2) return _("Update available"); return _("Not installed"); } else if (entry.status == TitleDownloadStatus::Initializing) return _("Initializing"); else if (entry.status == TitleDownloadStatus::Checking) return _("Checking"); else if (entry.status == TitleDownloadStatus::Queued) return _("Queued"); else if (entry.status == TitleDownloadStatus::Downloading) return _("Downloading"); else if (entry.status == TitleDownloadStatus::Verifying) return _("Verifying"); else if (entry.status == TitleDownloadStatus::Installing) return _("Installing"); else if (entry.status == TitleDownloadStatus::Installed) return _("Installed"); else if (entry.status == TitleDownloadStatus::Error) { wxString errorStatusMsg = _("Error:"); errorStatusMsg.append(" "); errorStatusMsg.append(entry.errorMsg); return errorStatusMsg; } else return "Unknown status"; } } return wxEmptyString; } wxString wxDownloadManagerList::GetTranslatedTitleEntryType(EntryType type) { switch (type) { case EntryType::Base: return _("base"); case EntryType::Update: return _("update"); case EntryType::DLC: return _("DLC"); default: return std::to_string(static_cast<std::underlying_type_t<EntryType>>(type)); } } void wxDownloadManagerList::AddOrUpdateTitle(TitleEntryData_t* obj) { const auto& data = obj->GetData(); // if already in list only update auto entry = GetTitleEntry(data.titleId, data.version); if (entry.has_value()) { // update item entry.value() = data; RefreshPage(); // more efficient way to do this? return; } m_data.emplace_back(std::make_unique<ItemData>(true, data)); m_sorted_data.emplace_back(*m_data[m_data.size() - 1]); SetItemCount(m_data.size()); // reapply sort Filter2(m_filterShowTitles, m_filterShowUpdates, m_filterShowInstalled); SortEntries(); } void wxDownloadManagerList::UpdateTitleStatusDepr(TitleEntryData_t* obj, const wxString& text) { const auto& data = obj->GetData(); const auto entry = GetTitleEntry(data.titleId, data.version); // check if already added to list if (!entry.has_value()) return; // update gamelist text for(size_t i = 0; i < m_sorted_data.size(); ++i) { if (m_sorted_data[i].get().entry == data) { SetItem(i, ColumnStatus, text); return; } } cemuLog_logDebug(LogType::Force, "cant update title status of {:x}", data.titleId); } int wxDownloadManagerList::AddImage(const wxImage& image) const { return -1; // m_image_list->Add(image.Scale(kListIconWidth, kListIconWidth, wxIMAGE_QUALITY_BICUBIC)); } // return < bool wxDownloadManagerList::SortFunc(std::span<int> sortColumnOrder, const Type_t& v1, const Type_t& v2) { cemu_assert_debug(sortColumnOrder.size() == 5); // visible have always priority if (!v1.get().visible && v2.get().visible) return false; else if (v1.get().visible && !v2.get().visible) return true; const auto& entry1 = v1.get().entry; const auto& entry2 = v2.get().entry; for (size_t i = 0; i < sortColumnOrder.size(); i++) { int sortByColumn = sortColumnOrder[i]; if (sortByColumn == ColumnTitleId) { // ensure strong ordering -> use type since only one entry should be now (should be changed if every save for every user is displayed spearately?) if (entry1.titleId != entry2.titleId) return entry1.titleId < entry2.titleId; } else if (sortByColumn == ColumnName) { const int tmp = entry1.name.CmpNoCase(entry2.name); if (tmp != 0) return tmp < 0; } else if (sortByColumn == ColumnType) { if (std::underlying_type_t<EntryType>(entry1.type) != std::underlying_type_t<EntryType>(entry2.type)) return std::underlying_type_t<EntryType>(entry1.type) < std::underlying_type_t<EntryType>(entry2.type); } else if (sortByColumn == ColumnVersion) { if (entry1.version != entry2.version) return entry1.version < entry2.version; } else if (sortByColumn == ColumnProgress) { if (entry1.progress != entry2.progress) return entry1.progress < entry2.progress; } else { cemu_assert_debug(false); return (uintptr_t)&entry1 < (uintptr_t)&entry2; } } return false; } #include <boost/container/small_vector.hpp> void wxDownloadManagerList::SortEntries() { boost::container::small_vector<int, 12> s_SortColumnOrder{ ColumnName, ColumnType, ColumnVersion, ColumnTitleId, ColumnProgress }; if (m_sort_by_column != -1) { // prioritize column by moving it to first position in the column sort order list s_SortColumnOrder.erase(std::remove(s_SortColumnOrder.begin(), s_SortColumnOrder.end(), m_sort_by_column), s_SortColumnOrder.end()); s_SortColumnOrder.insert(s_SortColumnOrder.begin(), m_sort_by_column); } std::sort(m_sorted_data.begin(), m_sorted_data.end(), [this, &s_SortColumnOrder](const Type_t& v1, const Type_t& v2) -> bool { const bool result = SortFunc({ s_SortColumnOrder.data(), s_SortColumnOrder.size() }, v1, v2); return m_sort_less ? result : !result; }); RefreshPage(); } void wxDownloadManagerList::RefreshPage() { long item_count = GetItemCount(); if (item_count > 0) RefreshItems(GetTopItem(), std::min(item_count - 1, GetTopItem() + GetCountPerPage() + 1)); } int wxDownloadManagerList::Filter(const wxString& filter, const wxString& prefix, ItemColumn column) { if (prefix.empty()) return -1; if (!filter.StartsWith(prefix)) return -1; int counter = 0; const auto tmp_filter = filter.substr(prefix.size() - 1).Trim(false); for (auto&& data : m_data) { if (GetTitleEntryText(data->entry, column).Upper().Contains(tmp_filter)) { data->visible = true; ++counter; } else data->visible = false; } return counter; } void wxDownloadManagerList::Filter(const wxString& filter) { if(filter.empty()) { std::for_each(m_data.begin(), m_data.end(), [](ItemDataPtr& data) { data->visible = true; }); SetItemCount(m_data.size()); RefreshPage(); return; } const auto filter_upper = filter.Upper().Trim(false).Trim(true); int counter = 0; if (const auto result = Filter(filter_upper, "TITLEID:", ColumnTitleId) != -1) counter = result; else if (const auto result = Filter(filter_upper, "NAME:", ColumnName) != -1) counter = result; else if (const auto result = Filter(filter_upper, "TYPE:", ColumnType) != -1) counter = result; //else if (const auto result = Filter(filter_upper, "REGION:", ColumnRegion) != -1) // counter = result; else if (const auto result = Filter(filter_upper, "VERSION:", ColumnVersion) != -1) counter = result; else if(filter_upper == "ERROR") { for (auto&& data : m_data) { bool visible = false; //if (data->entry.error != TitleError::None) // visible = true; data->visible = visible; if (visible) ++counter; } } else { for (auto&& data : m_data) { bool visible = false; if (data->entry.name.Upper().Contains(filter_upper)) visible = true; else if (GetTitleEntryText(data->entry, ColumnTitleId).Upper().Contains(filter_upper)) visible = true; else if (GetTitleEntryText(data->entry, ColumnType).Upper().Contains(filter_upper)) visible = true; data->visible = visible; if (visible) ++counter; } } SetItemCount(counter); RefreshPage(); } void wxDownloadManagerList::Filter2(bool showTitles, bool showUpdates, bool showInstalled) { m_filterShowTitles = showTitles; m_filterShowUpdates = showUpdates; m_filterShowInstalled = showInstalled; if (showTitles && showUpdates && showInstalled) { std::for_each(m_data.begin(), m_data.end(), [](ItemDataPtr& data) { data->visible = true; }); SetItemCount(m_data.size()); RefreshPage(); return; } size_t counter = 0; for (auto&& data : m_data) { bool visible = false; TitleIdParser tParser(data->entry.titleId); bool isInstalled = data->entry.status == TitleDownloadStatus::Installed; if (tParser.IsBaseTitleUpdate()) { if (showUpdates && (showInstalled || !isInstalled)) visible = true; } else { if (showTitles && (showInstalled || !isInstalled)) visible = true; } data->visible = visible; if (visible) ++counter; } SetItemCount(counter); RefreshPage(); } size_t wxDownloadManagerList::GetCountByType(EntryType type) const { size_t result = 0; for(const auto& data : m_data) { if (data->entry.type == type) ++result; } return result; } void wxDownloadManagerList::ClearItems() { m_sorted_data.clear(); m_data.clear(); SetItemCount(0); RefreshPage(); } void wxDownloadManagerList::AutosizeColumns() { wxAutosizeColumns(this, ColumnTitleId, ColumnMAX - 1); }
20,537
C++
.cpp
683
27.532943
158
0.732089
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,994
TextList.cpp
cemu-project_Cemu/src/gui/components/TextList.cpp
#include "gui/wxgui.h" #include "TextList.h" #include <wx/setup.h> #include <wx/tooltip.h> TextList::~TextList() { m_tooltip_timer->Stop(); this->Unbind(wxEVT_MOTION, &TextList::OnMouseMoveEvent, this); this->Unbind(wxEVT_KEY_DOWN, &TextList::OnKeyDownEvent, this); this->Unbind(wxEVT_KEY_UP, &TextList::OnKeyUpEvent, this); this->Unbind(wxEVT_PAINT, &TextList::OnPaintEvent, this); this->Unbind(wxEVT_LEFT_DOWN, &TextList::OnMouseDownEvent, this); this->Unbind(wxEVT_LEFT_UP, &TextList::OnMouseUpEvent, this); this->Unbind(wxEVT_LEFT_DCLICK, &TextList::OnMouseDClickEvent, this); this->Unbind(wxEVT_CONTEXT_MENU, &TextList::OnContextMenu, this); this->Unbind(wxEVT_ERASE_BACKGROUND, &TextList::OnEraseBackground, this); } TextList::TextList(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style) : wxControl(parent, id, pos, size, style), wxScrollHelper(this) { m_font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT); wxWindowBase::SetBackgroundStyle(wxBG_STYLE_PAINT); wxClientDC dc(this); m_line_height = dc.GetCharHeight(); m_char_width = dc.GetCharWidth(); m_yScrollPixelsPerLine = m_line_height; this->ShowScrollbars(wxSHOW_SB_DEFAULT, wxSHOW_SB_DEFAULT); m_tooltip = new wxToolTip(wxEmptyString); this->Bind(wxEVT_MOTION, &TextList::OnMouseMoveEvent, this); this->Bind(wxEVT_KEY_DOWN, &TextList::OnKeyDownEvent, this); this->Bind(wxEVT_KEY_UP, &TextList::OnKeyUpEvent, this); this->Bind(wxEVT_PAINT, &TextList::OnPaintEvent, this); this->Bind(wxEVT_LEFT_DOWN, &TextList::OnMouseDownEvent, this); this->Bind(wxEVT_LEFT_UP, &TextList::OnMouseUpEvent, this); this->Bind(wxEVT_LEFT_DCLICK, &TextList::OnMouseDClickEvent, this); this->Bind(wxEVT_CONTEXT_MENU, &TextList::OnContextMenu, this); this->Bind(wxEVT_ERASE_BACKGROUND, &TextList::OnEraseBackground, this); m_tooltip_window = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxNO_BORDER); m_tooltip_window->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_INFOBK)); m_tooltip_window->Hide(); m_tooltip_timer = new wxTimer(this); this->Bind(wxEVT_TIMER, &TextList::OnTooltipTimer, this); } void TextList::RefreshControl(const wxRect* update_region) { if(update_region) Refresh(true, update_region); else { wxRect region = GetClientRect(); update_region = &region; Refresh(true, update_region); } } void TextList::RefreshLine(uint32 line) { wxRect update_region = GetClientRect(); update_region.y = (sint32)line * m_line_height; update_region.height = m_line_height; CalcScrolledPosition(0, update_region.y, nullptr, &update_region.y); // debug_printf("update: <%x, %x>\n", update_region.y, update_region.height); Refresh(true, &update_region); } wxSize TextList::DoGetVirtualSize() const { return {wxDefaultCoord, (int)(m_element_count + 1) * m_line_height}; } void TextList::DoSetSize(int x, int y, int width, int height, int sizeFlags) { wxControl::DoSetSize(x, y, width, height, sizeFlags); m_elements_visible = (height + m_line_height - 1) / m_line_height; Refresh(); } void TextList::SetScrollPos(int orient, int pos, bool refresh) { wxControl::SetScrollPos(orient, pos, refresh); } void TextList::DrawLineBackground(wxDC& dc, uint32 line, const wxColour& colour, uint32 lines) const { wxRect rect; rect.x = GetPosition().x; rect.y = line * m_line_height; rect.width = GetSize().x; rect.height = m_line_height * lines; dc.SetBrush(colour); dc.DrawRectangle(rect); } void TextList::DrawLineBackground(wxDC& dc, const wxPoint& position, const wxColour& colour, uint32 lines) const { wxRect rect; rect.x = position.x; rect.y = position.y; rect.width = this->GetSize().x; rect.height = m_line_height * lines; dc.SetBrush(colour); dc.DrawRectangle(rect); } bool TextList::SetElementCount(size_t element_count) { if (m_element_count == element_count) return false; if (element_count > 0x7FFFFFFF) element_count = 0x7FFFFFFF; m_element_count = element_count; this->AdjustScrollbars(); return true; } uint32 TextList::GetElementCount() const { return m_element_count; } bool TextList::IsKeyDown(sint32 keycode) { return m_key_states[keycode]; } void TextList::WriteText(wxDC& dc, const wxString& text, wxPoint& position) const { dc.ResetBoundingBox(); dc.DrawText(text, position); position.x += dc.MaxX() - dc.MinX(); } void TextList::WriteText(wxDC& dc, const wxString& text, wxPoint& position, const wxColour& color) const { dc.SetTextForeground(color); WriteText(dc, text, position); } void TextList::NextLine(wxPoint& position, const wxPoint* start_position) const { position.y += m_line_height; if (start_position) position.x = start_position->x; } void TextList::OnMouseDown() {} void TextList::OnMouseUp() {} bool TextList::OnShowTooltip(const wxPoint& position, uint32 line) { return false; } void TextList::OnMouseMoveEvent(wxMouseEvent& event) { m_tooltip_timer->Stop(); m_tooltip_timer->StartOnce(250); wxPoint position = event.GetPosition(); CalcUnscrolledPosition(position.x, position.y, &position.x, &position.y); m_mouse_position = position; if(m_mouse_down) m_selection.SetBottomRight(position); const sint32 line = position.y / m_line_height; OnMouseMove(position, line); } void TextList::OnKeyDownEvent(wxKeyEvent& event) { const auto key_code = event.GetKeyCode(); const auto it = m_key_states.find(key_code); if(it == m_key_states.end() || !it->second) { m_key_states[key_code] = true; OnKeyPressed(key_code, event.GetPosition()); } event.Skip(); } void TextList::OnKeyUpEvent(wxKeyEvent& event) { m_key_states[event.GetKeyCode()] = false; } void TextList::OnMouseDownEvent(wxMouseEvent& event) { m_mouse_down = true; wxPoint position = event.GetPosition(); CalcUnscrolledPosition(position.x, position.y, &position.x, &position.y); m_selection.SetPosition(position); m_selection.SetBottomRight(position); OnMouseDown(); event.Skip(); } void TextList::OnMouseUpEvent(wxMouseEvent& event) { m_mouse_down = false; OnMouseUp(); event.Skip(); } void TextList::OnMouseDClickEvent(wxMouseEvent& event) { wxPoint position = event.GetPosition(); CalcUnscrolledPosition(position.x, position.y, &position.x, &position.y); m_selection.SetPosition(position); m_selection.SetBottomRight(position); const uint32 line = position.y / m_line_height; OnMouseDClick(position, line); } void TextList::OnContextMenu(wxContextMenuEvent& event) { wxPoint position = event.GetPosition(); if (position == wxDefaultPosition) return; wxPoint clientPosition = ScreenToClient(position); CalcUnscrolledPosition(clientPosition.x, clientPosition.y, &clientPosition.x, &clientPosition.y); m_selection.SetPosition(clientPosition); m_selection.SetBottomRight(clientPosition); const uint32 line = clientPosition.y / m_line_height; OnContextMenu(clientPosition, line); } void TextList::OnTooltipTimer(wxTimerEvent& event) { m_tooltip_window->Hide(); const auto cursor_position = wxGetMousePosition(); const auto position = GetScreenPosition(); if (cursor_position.x < position.x || cursor_position.y < position.y) return; const auto size = GetSize(); if (position.x + size.x < cursor_position.x || position.y + size.y < cursor_position.y) return; const sint32 line = position.y / m_line_height; if(OnShowTooltip(m_mouse_position, line)) { m_tooltip_window->SetPosition(wxPoint(m_mouse_position.x + 15, m_mouse_position.y + 15)); m_tooltip_window->SendSizeEvent(); m_tooltip_window->Show(); } } void TextList::OnPaintEvent(wxPaintEvent& event) { wxBufferedPaintDC dc(m_targetWindow, wxBUFFER_VIRTUAL_AREA); dc.SetFont(m_font); // get window position auto position = GetPosition(); // get current real position wxRect rect_update = GetUpdateRegion().GetBox(); const auto count = (uint32)std::ceil((float)rect_update.GetHeight() / m_line_height); position.y = (rect_update.y / m_line_height) * m_line_height; // paint background const wxColour window_colour = COLOR_WHITE; dc.SetBrush(window_colour); dc.SetPen(window_colour); dc.DrawRectangle(rect_update); //// paint selection //if (!m_selected_text.eof()) //{ // dc.SetBrush(*wxBLUE_BRUSH); // dc.SetPen(*wxBLUE_PEN); // dc.DrawRectangle(m_selection); //} sint32 start; CalcUnscrolledPosition(rect_update.x, rect_update.y, nullptr, &start); start /= m_line_height; m_scrolled_to_end = (start + count) >= m_element_count; OnDraw(dc, start, count, position); this->Update(); }
8,474
C++
.cpp
249
32.02008
112
0.757754
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,995
wxCreateAccountDialog.cpp
cemu-project_Cemu/src/gui/dialogs/CreateAccount/wxCreateAccountDialog.cpp
#include "gui/dialogs/CreateAccount/wxCreateAccountDialog.h" #include "Cafe/Account/Account.h" #include <wx/sizer.h> #include <wx/stattext.h> #include <wx/choice.h> #include <wx/button.h> #include <wx/textctrl.h> #include <wx/msgdlg.h> #include <helpers/wxHelpers.h> #include "util/helpers/helpers.h" wxCreateAccountDialog::wxCreateAccountDialog(wxWindow* parent) : wxDialog(parent, wxID_ANY, _("Create new account")) { auto* main_sizer = new wxFlexGridSizer(0, 2, 0, 0); main_sizer->AddGrowableCol(1); main_sizer->SetFlexibleDirection(wxBOTH); main_sizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); main_sizer->Add(new wxStaticText(this, wxID_ANY, "PersistentId"), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_persistent_id = new wxTextCtrl(this, wxID_ANY, fmt::format("{:x}", Account::GetNextPersistentId())); m_persistent_id->SetToolTip(_("The persistent id is the internal folder name used for your saves. Only change this if you are importing saves from a Wii U with a specific id")); main_sizer->Add(m_persistent_id, 1, wxALL | wxEXPAND, 5); main_sizer->Add(new wxStaticText(this, wxID_ANY, _("Mii name")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_mii_name = new wxTextCtrl(this, wxID_ANY); m_mii_name->SetFocus(); m_mii_name->SetMaxLength(10); main_sizer->Add(m_mii_name, 1, wxALL | wxEXPAND, 5); main_sizer->Add(0, 0, 1, wxEXPAND, 5); { auto* button_sizer = new wxBoxSizer(wxHORIZONTAL); m_ok_button = new wxButton(this, wxID_ANY, _("OK")); m_ok_button->Bind(wxEVT_BUTTON, &wxCreateAccountDialog::OnOK, this); button_sizer->Add(m_ok_button, 0, wxALL, 5); m_cancel_buton = new wxButton(this, wxID_ANY, _("Cancel")); m_cancel_buton->Bind(wxEVT_BUTTON, &wxCreateAccountDialog::OnCancel, this); button_sizer->Add(m_cancel_buton, 0, wxALL, 5); main_sizer->Add(button_sizer, 1, wxALIGN_RIGHT, 5); } this->SetSizerAndFit(main_sizer); this->wxWindowBase::Layout(); } uint32 wxCreateAccountDialog::GetPersistentId() const { const std::string id_string = m_persistent_id->GetValue().c_str().AsChar(); return ConvertString<uint32>(id_string, 16); } wxString wxCreateAccountDialog::GetMiiName() const { return m_mii_name->GetValue(); } void wxCreateAccountDialog::OnOK(wxCommandEvent& event) { if(m_persistent_id->IsEmpty()) { wxMessageBox(_("No persistent id entered!"), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } const auto id = GetPersistentId(); if(id < Account::kMinPersistendId) { wxMessageBox(formatWxString(_("The persistent id must be greater than {:x}!"), Account::kMinPersistendId), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } const auto& account = Account::GetAccount(id); if(account.GetPersistentId() == id) { const std::wstring msg = fmt::format(fmt::runtime(_("The persistent id {:x} is already in use by account {}!").ToStdWstring()), account.GetPersistentId(), std::wstring{ account.GetMiiName() }); wxMessageBox(msg, _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } if(m_mii_name->IsEmpty()) { wxMessageBox(_("Account name may not be empty!"), _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } EndModal(wxID_OK); } void wxCreateAccountDialog::OnCancel(wxCommandEvent& event) { EndModal(wxID_CANCEL); }
3,281
C++
.cpp
82
37.780488
178
0.72836
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,996
SaveTransfer.cpp
cemu-project_Cemu/src/gui/dialogs/SaveImport/SaveTransfer.cpp
#include "SaveTransfer.h" #include "pugixml.hpp" #include <wx/sizer.h> #include <wx/choice.h> #include <wx/combobox.h> #include <wx/stattext.h> #include <wx/button.h> #include <wx/frame.h> #include <wx/msgdlg.h> #include "Cafe/Account/Account.h" #include "config/ActiveSettings.h" #include "util/helpers/helpers.h" #include "gui/helpers/wxHelpers.h" SaveTransfer::SaveTransfer(wxWindow* parent, uint64 title_id, const wxString& source_account, uint32 source_id) : wxDialog(parent, wxID_ANY, _("Save transfer"), wxDefaultPosition, wxDefaultSize, wxCAPTION | wxFRAME_TOOL_WINDOW | wxSYSTEM_MENU | wxTAB_TRAVERSAL | wxCLOSE_BOX), m_title_id(title_id), m_source_id(source_id) { auto* sizer = new wxBoxSizer(wxVERTICAL); { auto* row1 = new wxFlexGridSizer(0, 2, 0, 0); row1->AddGrowableCol(1); row1->Add(new wxStaticText(this, wxID_ANY, _("Source")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); auto* source_choice = new wxChoice(this, wxID_ANY); source_choice->SetMinSize({170, -1}); source_choice->Append(source_account); source_choice->SetSelection(0); row1->Add(source_choice, 1, wxALL | wxEXPAND, 5); row1->Add(new wxStaticText(this, wxID_ANY, _("Target")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); const auto& accounts = Account::GetAccounts(); m_target_selection = new wxComboBox(this, wxID_ANY); for (const auto& account : accounts) { if (account.GetPersistentId() == m_source_id) continue; m_target_selection->Append(fmt::format("{:x} ({})", account.GetPersistentId(), boost::nowide::narrow(account.GetMiiName().data(), account.GetMiiName().size())), (void*)(uintptr_t)account.GetPersistentId()); } row1->Add(m_target_selection, 1, wxALL | wxEXPAND, 5); sizer->Add(row1, 0, wxEXPAND, 5); } { auto* row2 = new wxFlexGridSizer(0, 2, 0, 0); row2->AddGrowableCol(1); row2->SetFlexibleDirection(wxBOTH); row2->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); auto* ok_button = new wxButton(this, wxID_ANY, _("OK"), wxDefaultPosition, wxDefaultSize, 0); ok_button->Bind(wxEVT_BUTTON, &SaveTransfer::OnTransfer, this); row2->Add(ok_button, 0, wxALL, 5); auto* cancel_button = new wxButton(this, wxID_ANY, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0); cancel_button->Bind(wxEVT_BUTTON, [this](auto&) { m_return_code = wxCANCEL; Close(); }); row2->Add(cancel_button, 0, wxALIGN_RIGHT | wxALL, 5); sizer->Add(row2, 1, wxEXPAND, 5); } this->SetSizerAndFit(sizer); this->Centre(wxBOTH); } void SaveTransfer::EndModal(int retCode) { wxDialog::EndModal(retCode); SetReturnCode(m_return_code); } void SaveTransfer::OnTransfer(wxCommandEvent& event) { uint32 target_id = 0; const auto selection = m_target_selection->GetCurrentSelection(); if(selection != wxNOT_FOUND) target_id = (uint32)(uintptr_t)m_target_selection->GetClientData(selection); if (target_id == 0) { target_id = ConvertString<uint32>(m_target_selection->GetValue().ToStdString(), 16); if(target_id < Account::kMinPersistendId) { const auto msg = formatWxString(_("The given account id is not valid!\nIt must be a hex number bigger or equal than {:08x}"), Account::kMinPersistendId); wxMessageBox(msg, _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } } const fs::path source_path = ActiveSettings::GetMlcPath("usr/save/{:08x}/{:08x}/user/{:08x}", (uint32)(m_title_id >> 32), (uint32)(m_title_id & 0xFFFFFFFF), m_source_id); if (!fs::exists(source_path) || !fs::is_directory(source_path)) return; const fs::path target_path = ActiveSettings::GetMlcPath("usr/save/{:08x}/{:08x}/user/{:08x}", (uint32)(m_title_id >> 32), (uint32)(m_title_id & 0xFFFFFFFF), target_id); if (fs::exists(target_path)) { if(!fs::is_directory(target_path)) { const auto msg = formatWxString(_("There's already a file at the target directory:\n{}"), _pathToUtf8(target_path)); wxMessageBox(msg, _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); m_return_code = wxCANCEL; Close(); return; } const auto msg = _("There's already a save game available for the target account, do you want to overwrite it?\nThis will delete the existing save files for the account and replace them."); const auto result = wxMessageBox(msg, _("Error"), wxYES_NO | wxCENTRE | wxICON_WARNING, this); if(result == wxNO) { m_return_code = wxCANCEL; Close(); return; } std::error_code ec; while (fs::exists(target_path, ec) || ec) { fs::remove_all(target_path, ec); if (ec) { const auto error_msg = formatWxString(_("Error when trying to delete the former save game:\n{}"), GetSystemErrorMessage(ec)); wxMessageBox(error_msg, _("Error"), wxOK | wxCENTRE, this); return; } // wait so filesystem doesnt std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } // edit meta saveinfo.xml bool meta_file_edited = false; const fs::path saveinfo = ActiveSettings::GetMlcPath("usr/save/{:08x}/{:08x}/meta/saveinfo.xml", (uint32)(m_title_id >> 32), (uint32)(m_title_id & 0xFFFFFFFF)); if (fs::exists(saveinfo) || fs::is_regular_file(saveinfo)) { pugi::xml_document doc; if (doc.load_file(saveinfo.c_str())) { auto info_node = doc.child("info"); if (info_node) { // delete old node if available auto old_persistend_id_string = fmt::format("{:08x}", target_id); const auto delete_entry = info_node.find_child([&old_persistend_id_string](const pugi::xml_node& node) { return boost::iequals(node.attribute("persistentId").as_string(), old_persistend_id_string); }); if (delete_entry) info_node.remove_child(delete_entry); // move new node auto new_persistend_id_string = fmt::format("{:08x}", m_source_id); auto move_entry = info_node.find_child([&new_persistend_id_string](const pugi::xml_node& node) { return boost::iequals(node.attribute("persistentId").as_string(), new_persistend_id_string); }); if(move_entry) move_entry.attribute("persistentId").set_value(old_persistend_id_string.c_str()); else { // TODO: create if not found! (shouldnt happen though) } meta_file_edited = doc.save_file(saveinfo.c_str()); } } } if (!meta_file_edited) cemuLog_log(LogType::Force, "SaveTransfer::OnTransfer: couldn't update save entry in saveinfo.xml: {}", _pathToUtf8(saveinfo)); std::error_code ec; fs::rename(source_path, target_path, ec); if (ec) { const auto error_msg = formatWxString(_("Error when trying to move the save game:\n{}"), GetSystemErrorMessage(ec)); wxMessageBox(error_msg, _("Error"), wxOK | wxCENTRE, this); return; } m_target_id = target_id; m_return_code = wxOK; Close(); }
6,728
C++
.cpp
167
36.712575
191
0.692355
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,997
SaveImportWindow.cpp
cemu-project_Cemu/src/gui/dialogs/SaveImport/SaveImportWindow.cpp
#include "SaveImportWindow.h" #include "pugixml.hpp" #include <wx/sizer.h> #include <wx/choice.h> #include <wx/combobox.h> #include <wx/stattext.h> #include <wx/button.h> #include <wx/frame.h> #include <wx/filepicker.h> #include <wx/msgdlg.h> #include "zip.h" #include "Cafe/Account/Account.h" #include "config/ActiveSettings.h" #include "Cafe/OS/libs/coreinit/coreinit_Time.h" #include "util/helpers/helpers.h" #include "Cafe/HW/Espresso/PPCState.h" #include "gui/helpers/wxHelpers.h" SaveImportWindow::SaveImportWindow(wxWindow* parent, uint64 title_id) : wxDialog(parent, wxID_ANY, _("Import save entry"), wxDefaultPosition, wxDefaultSize, wxCAPTION | wxFRAME_TOOL_WINDOW | wxSYSTEM_MENU | wxTAB_TRAVERSAL | wxCLOSE_BOX), m_title_id(title_id) { auto* sizer = new wxBoxSizer(wxVERTICAL); { auto* row1 = new wxFlexGridSizer(0, 2, 0, 0); row1->AddGrowableCol(1); row1->Add(new wxStaticText(this, wxID_ANY, _("Source")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); m_source_selection = new wxFilePickerCtrl(this, wxID_ANY, wxEmptyString, _("Select a zipped save file"), formatWxString("{}|*.zip", _("Save entry (*.zip)"))); m_source_selection->SetMinSize({ 270, -1 }); row1->Add(m_source_selection, 1, wxALL | wxEXPAND, 5); row1->Add(new wxStaticText(this, wxID_ANY, _("Target")), 0, wxALIGN_CENTER_VERTICAL | wxALL, 5); const auto& accounts = Account::GetAccounts(); m_target_selection = new wxComboBox(this, wxID_ANY); for (const auto& account : accounts) { m_target_selection->Append(fmt::format("{:x} ({})", account.GetPersistentId(), boost::nowide::narrow(account.GetMiiName().data(), account.GetMiiName().size())), (void*)(uintptr_t)account.GetPersistentId()); } row1->Add(m_target_selection, 1, wxALL | wxEXPAND, 5); sizer->Add(row1, 0, wxEXPAND, 5); } { auto* row2 = new wxFlexGridSizer(0, 2, 0, 0); row2->AddGrowableCol(1); row2->SetFlexibleDirection(wxBOTH); row2->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED); auto* ok_button = new wxButton(this, wxID_ANY, _("OK"), wxDefaultPosition, wxDefaultSize, 0); ok_button->Bind(wxEVT_BUTTON, &SaveImportWindow::OnImport, this); row2->Add(ok_button, 0, wxALL, 5); auto* cancel_button = new wxButton(this, wxID_ANY, _("Cancel"), wxDefaultPosition, wxDefaultSize, 0); cancel_button->Bind(wxEVT_BUTTON, [this](auto&) { m_return_code = wxCANCEL; Close(); }); row2->Add(cancel_button, 0, wxALIGN_RIGHT | wxALL, 5); sizer->Add(row2, 1, wxEXPAND, 5); } this->SetSizerAndFit(sizer); this->Centre(wxBOTH); } void SaveImportWindow::EndModal(int retCode) { wxDialog::EndModal(retCode); SetReturnCode(m_return_code); } void SaveImportWindow::OnImport(wxCommandEvent& event) { const auto source_path = m_source_selection->GetPath(); if (source_path.empty()) return; // try to find cemu_meta file to verify targetid const std::string zipfile = source_path.ToUTF8().data(); int ziperr; auto* zip = zip_open(zipfile.c_str(), ZIP_RDONLY, &ziperr); if (zip) { const sint32 numEntries = zip_get_num_entries(zip, 0); for (sint32 i = 0; i < numEntries; i++) { zip_stat_t sb{}; if (zip_stat_index(zip, i, 0, &sb) != 0) continue; if (!boost::equals(sb.name, "cemu_meta")) continue; auto* zip_file = zip_fopen_index(zip, i, 0); if (zip_file == nullptr) continue; auto buffer = std::make_unique<char[]>(sb.size); if (zip_fread(zip_file, buffer.get(), sb.size) == sb.size) { std::string_view str{ buffer.get(), sb.size }; // titleId = {:#016x} if(boost::starts_with(str, "titleId = ")) { const uint64_t titleId = ConvertString<uint64>(str.substr(sizeof("titleId = ") + 1), 16); if(titleId != 0 && titleId != m_title_id) { const auto msg = formatWxString(_("You are trying to import a savegame for a different title than your currently selected one: {:016x} vs {:016x}\nAre you sure that you want to continue?"), titleId, m_title_id); const auto res = wxMessageBox(msg, _("Error"), wxYES_NO | wxCENTRE | wxICON_WARNING, this); if(res == wxNO) { m_return_code = wxCANCEL; Close(); return; } } } } zip_fclose(zip_file); break; } zip_close(zip); } // unzip to tmp folder -> using target path directly now std::error_code ec; //auto tmp_source = fs::temp_directory_path(ec); //if(ec) //{ // const auto error_msg = formatWxString(_("Error when getting the temp directory path:\n{}"), GetSystemErrorMessage(ec)); // wxMessageBox(error_msg, _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); // return; //} uint32 target_id = 0; const auto selection = m_target_selection->GetCurrentSelection(); if (selection != wxNOT_FOUND) target_id = (uint32)(uintptr_t)m_target_selection->GetClientData(selection); if (target_id == 0) { target_id = ConvertString<uint32>(m_target_selection->GetValue().ToStdString(), 16); if (target_id < Account::kMinPersistendId) { const auto msg = formatWxString(_("The given account id is not valid!\nIt must be a hex number bigger or equal than {:08x}"), Account::kMinPersistendId); wxMessageBox(msg, _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } } fs::path target_path = ActiveSettings::GetMlcPath("usr/save/{:08x}/{:08x}/user/{:08x}", (uint32)(m_title_id >> 32), (uint32)(m_title_id & 0xFFFFFFFF), target_id); if (fs::exists(target_path)) { if (!fs::is_directory(target_path)) { const auto msg = formatWxString(_("There's already a file at the target directory:\n{}"), _pathToUtf8(target_path)); wxMessageBox(msg, _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); m_return_code = wxCANCEL; Close(); return; } const auto msg = _("There's already a save game available for the target account, do you want to overwrite it?\nThis will delete the existing save files for the account and replace them."); const auto result = wxMessageBox(msg, _("Error"), wxYES_NO | wxCENTRE | wxICON_WARNING, this); if (result == wxNO) { m_return_code = wxCANCEL; Close(); return; } std::error_code ec; while (fs::exists(target_path, ec) || ec) { fs::remove_all(target_path, ec); if (ec) { const auto error_msg = formatWxString(_("Error when trying to delete the former save game:\n{}"), GetSystemErrorMessage(ec)); wxMessageBox(error_msg, _("Error"), wxOK | wxCENTRE, this); return; } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } // extract zip file //tmp_source.append("Cemu").append(fmt::format("{}", rand())); //tmp_source = getMlcPath(L"usr/save"); //tmp_source /= fmt::format("{:08x}/{:08x}/user/{:08x}_tmp", (uint32)(m_title_id >> 32), (uint32)(m_title_id & 0xFFFFFFFF), target_id); auto tmp_source = target_path; fs::create_directories(tmp_source, ec); if (ec) { const auto error_msg = formatWxString(_("Error when creating the extraction path:\n{}"), GetSystemErrorMessage(ec)); wxMessageBox(error_msg, _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } zip = zip_open(zipfile.c_str(), ZIP_RDONLY, &ziperr); if (!zip) { const auto error_msg = formatWxString(_("Error when opening the import zip file:\n{}"), GetSystemErrorMessage(ec)); wxMessageBox(error_msg, _("Error"), wxOK | wxCENTRE | wxICON_ERROR, this); return; } sint32 numEntries = zip_get_num_entries(zip, 0); for (sint32 i = 0; i < numEntries; i++) { zip_stat_t sb{}; if (zip_stat_index(zip, i, 0, &sb) != 0) { cemuLog_log(LogType::Force, "zip stat index failed on {} entry", i); continue; } if (boost::starts_with(sb.name, "../") || boost::starts_with(sb.name, "..\\")) continue; // bad path if (boost::equals(sb.name, "cemu_meta")) continue; size_t sb_name_len = strlen(sb.name); if (sb_name_len == 0) continue; const auto path = fs::path(tmp_source).append(sb.name); if (sb.name[sb_name_len - 1] == '/') { fs::create_directories(path, ec); if (ec) cemuLog_log(LogType::Force, "can't create directory {}: {}", sb.name, ec.message()); continue; } if (sb.size == 0) continue; if (sb.size > (1024 * 1024 * 128)) continue; // skip unusually huge files auto* zip_file = zip_fopen_index(zip, i, 0); if (zip_file == nullptr) continue; auto buffer = std::make_unique<char[]>(sb.size); if (zip_fread(zip_file, buffer.get(), sb.size) == sb.size) { std::ofstream file(path, std::ios::out | std::ios::binary); if (file.is_open()) file.write(buffer.get(), sb.size); } zip_fclose(zip_file); } zip_close(zip); // extracted all files to tmp_source // edit meta saveinfo.xml fs::path saveinfo = ActiveSettings::GetMlcPath("usr/save/{:08x}/{:08x}/meta/saveinfo.xml", (uint32)(m_title_id >> 32), (uint32)(m_title_id & 0xFFFFFFFF)); if (fs::exists(saveinfo) || fs::is_regular_file(saveinfo)) { pugi::xml_document doc; if (doc.load_file(saveinfo.c_str())) { auto info_node = doc.child("info"); if (info_node) { // delete old node if available auto old_persistend_id_string = fmt::format("{:08x}", target_id); const auto node_entry = info_node.find_child([&old_persistend_id_string](const pugi::xml_node& node) { return boost::iequals(node.attribute("persistentId").as_string(), old_persistend_id_string); }); // add save-entry node if not available yet if (!node_entry) { // add new node auto new_persistend_id_string = fmt::format("{:08x}", target_id); auto new_node = info_node.append_child("account"); new_node.append_attribute("persistentId").set_value(new_persistend_id_string.c_str()); auto timestamp = new_node.append_child("timestamp"); timestamp.text().set(fmt::format("{:016x}", coreinit::coreinit_getOSTime() / ESPRESSO_TIMER_CLOCK).c_str()); // TODO time not initialized yet? if(!doc.save_file(saveinfo.c_str())) cemuLog_log(LogType::Force, "couldn't insert save entry in saveinfo.xml: {}", _pathToUtf8(saveinfo)); } } } } // todo create saveinfo if doesnt exist /*wxMessageBox(fmt::format("{}\n{}", tmp_source.generic_u8string(), target_path.generic_u8string()), _("Error"), wxOK | wxCENTRE, this); fs::rename(tmp_source, target_path, ec); if (ec) { const auto error_msg = formatWxString(_("Error when trying to move the extracted save game:\n{}"), GetSystemErrorMessage(ec)); wxMessageBox(error_msg, _("Error"), wxOK | wxCENTRE, this); return; }*/ m_target_id = target_id; m_return_code = wxOK; Close(); }
10,511
C++
.cpp
275
34.781818
217
0.673417
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,998
EmulatedUSBDeviceFrame.cpp
cemu-project_Cemu/src/gui/EmulatedUSBDevices/EmulatedUSBDeviceFrame.cpp
#include "EmulatedUSBDeviceFrame.h" #include <algorithm> #include "config/CemuConfig.h" #include "gui/helpers/wxHelpers.h" #include "gui/wxHelper.h" #include "util/helpers/helpers.h" #include "Cafe/OS/libs/nsyshid/nsyshid.h" #include "Cafe/OS/libs/nsyshid/Dimensions.h" #include "Common/FileStream.h" #include <wx/arrstr.h> #include <wx/button.h> #include <wx/combobox.h> #include <wx/checkbox.h> #include <wx/combobox.h> #include <wx/filedlg.h> #include <wx/log.h> #include <wx/msgdlg.h> #include <wx/notebook.h> #include <wx/panel.h> #include <wx/sizer.h> #include <wx/statbox.h> #include <wx/stattext.h> #include <wx/stream.h> #include <wx/textctrl.h> #include <wx/textentry.h> #include <wx/valnum.h> #include <wx/wfstream.h> #include "resource/embedded/resources.h" EmulatedUSBDeviceFrame::EmulatedUSBDeviceFrame(wxWindow* parent) : wxFrame(parent, wxID_ANY, _("Emulated USB Devices"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_FRAME_STYLE | wxTAB_TRAVERSAL) { SetIcon(wxICON(X_BOX)); auto& config = GetConfig(); auto* sizer = new wxBoxSizer(wxVERTICAL); auto* notebook = new wxNotebook(this, wxID_ANY); notebook->AddPage(AddSkylanderPage(notebook), _("Skylanders Portal")); notebook->AddPage(AddInfinityPage(notebook), _("Infinity Base")); notebook->AddPage(AddDimensionsPage(notebook), _("Dimensions Toypad")); sizer->Add(notebook, 1, wxEXPAND | wxALL, 2); SetSizerAndFit(sizer); Layout(); Centre(wxBOTH); } EmulatedUSBDeviceFrame::~EmulatedUSBDeviceFrame() {} wxPanel* EmulatedUSBDeviceFrame::AddSkylanderPage(wxNotebook* notebook) { auto* panel = new wxPanel(notebook); auto* panelSizer = new wxBoxSizer(wxVERTICAL); auto* box = new wxStaticBox(panel, wxID_ANY, _("Skylanders Manager")); auto* boxSizer = new wxStaticBoxSizer(box, wxVERTICAL); auto* row = new wxBoxSizer(wxHORIZONTAL); m_emulatePortal = new wxCheckBox(box, wxID_ANY, _("Emulate Skylander Portal")); m_emulatePortal->SetValue( GetConfig().emulated_usb_devices.emulate_skylander_portal); m_emulatePortal->Bind(wxEVT_CHECKBOX, [this](wxCommandEvent&) { GetConfig().emulated_usb_devices.emulate_skylander_portal = m_emulatePortal->IsChecked(); g_config.Save(); }); row->Add(m_emulatePortal, 1, wxEXPAND | wxALL, 2); boxSizer->Add(row, 1, wxEXPAND | wxALL, 2); for (int i = 0; i < nsyshid::MAX_SKYLANDERS; i++) { boxSizer->Add(AddSkylanderRow(i, box), 1, wxEXPAND | wxALL, 2); } panelSizer->Add(boxSizer, 1, wxEXPAND | wxALL, 2); panel->SetSizerAndFit(panelSizer); return panel; } wxPanel* EmulatedUSBDeviceFrame::AddInfinityPage(wxNotebook* notebook) { auto* panel = new wxPanel(notebook); auto* panelSizer = new wxBoxSizer(wxBOTH); auto* box = new wxStaticBox(panel, wxID_ANY, _("Infinity Manager")); auto* boxSizer = new wxStaticBoxSizer(box, wxBOTH); auto* row = new wxBoxSizer(wxHORIZONTAL); m_emulateBase = new wxCheckBox(box, wxID_ANY, _("Emulate Infinity Base")); m_emulateBase->SetValue( GetConfig().emulated_usb_devices.emulate_infinity_base); m_emulateBase->Bind(wxEVT_CHECKBOX, [this](wxCommandEvent&) { GetConfig().emulated_usb_devices.emulate_infinity_base = m_emulateBase->IsChecked(); g_config.Save(); }); row->Add(m_emulateBase, 1, wxEXPAND | wxALL, 2); boxSizer->Add(row, 1, wxEXPAND | wxALL, 2); boxSizer->Add(AddInfinityRow("Play Set/Power Disc", 0, box), 1, wxEXPAND | wxALL, 2); boxSizer->Add(AddInfinityRow("Power Disc Two", 1, box), 1, wxEXPAND | wxALL, 2); boxSizer->Add(AddInfinityRow("Power Disc Three", 2, box), 1, wxEXPAND | wxALL, 2); boxSizer->Add(AddInfinityRow("Player One", 3, box), 1, wxEXPAND | wxALL, 2); boxSizer->Add(AddInfinityRow("Player One Ability One", 4, box), 1, wxEXPAND | wxALL, 2); boxSizer->Add(AddInfinityRow("Player One Ability Two", 5, box), 1, wxEXPAND | wxALL, 2); boxSizer->Add(AddInfinityRow("Player Two", 6, box), 1, wxEXPAND | wxALL, 2); boxSizer->Add(AddInfinityRow("Player Two Ability One", 7, box), 1, wxEXPAND | wxALL, 2); boxSizer->Add(AddInfinityRow("Player Two Ability Two", 8, box), 1, wxEXPAND | wxALL, 2); panelSizer->Add(boxSizer, 1, wxEXPAND | wxALL, 2); panel->SetSizerAndFit(panelSizer); return panel; } wxPanel* EmulatedUSBDeviceFrame::AddDimensionsPage(wxNotebook* notebook) { auto* panel = new wxPanel(notebook); auto* panel_sizer = new wxBoxSizer(wxVERTICAL); auto* box = new wxStaticBox(panel, wxID_ANY, _("Dimensions Manager")); auto* box_sizer = new wxStaticBoxSizer(box, wxVERTICAL); auto* row = new wxBoxSizer(wxHORIZONTAL); m_emulateToypad = new wxCheckBox(box, wxID_ANY, _("Emulate Dimensions Toypad")); m_emulateToypad->SetValue( GetConfig().emulated_usb_devices.emulate_dimensions_toypad); m_emulateToypad->Bind(wxEVT_CHECKBOX, [this](wxCommandEvent&) { GetConfig().emulated_usb_devices.emulate_dimensions_toypad = m_emulateToypad->IsChecked(); g_config.Save(); }); row->Add(m_emulateToypad, 1, wxEXPAND | wxALL, 2); box_sizer->Add(row, 1, wxEXPAND | wxALL, 2); auto* top_row = new wxBoxSizer(wxHORIZONTAL); auto* bottom_row = new wxBoxSizer(wxHORIZONTAL); auto* dummy = new wxStaticText(box, wxID_ANY, ""); top_row->Add(AddDimensionPanel(2, 0, box), 1, wxEXPAND | wxALL, 2); top_row->Add(dummy, 1, wxEXPAND | wxLEFT | wxRIGHT, 2); top_row->Add(AddDimensionPanel(1, 1, box), 1, wxEXPAND | wxALL, 2); top_row->Add(dummy, 1, wxEXPAND | wxLEFT | wxRIGHT, 2); top_row->Add(AddDimensionPanel(3, 2, box), 1, wxEXPAND | wxALL, 2); bottom_row->Add(AddDimensionPanel(2, 3, box), 1, wxEXPAND | wxALL, 2); bottom_row->Add(AddDimensionPanel(2, 4, box), 1, wxEXPAND | wxALL, 2); bottom_row->Add(dummy, 1, wxEXPAND | wxLEFT | wxRIGHT, 0); bottom_row->Add(AddDimensionPanel(3, 5, box), 1, wxEXPAND | wxALL, 2); bottom_row->Add(AddDimensionPanel(3, 6, box), 1, wxEXPAND | wxALL, 2); box_sizer->Add(top_row, 1, wxEXPAND | wxALL, 2); box_sizer->Add(bottom_row, 1, wxEXPAND | wxALL, 2); panel_sizer->Add(box_sizer, 1, wxEXPAND | wxALL, 2); panel->SetSizerAndFit(panel_sizer); return panel; } wxBoxSizer* EmulatedUSBDeviceFrame::AddSkylanderRow(uint8 rowNumber, wxStaticBox* box) { auto* row = new wxBoxSizer(wxHORIZONTAL); row->Add(new wxStaticText(box, wxID_ANY, fmt::format("{} {}", _("Skylander").ToStdString(), (rowNumber + 1))), 1, wxEXPAND | wxALL, 2); m_skylanderSlots[rowNumber] = new wxTextCtrl(box, wxID_ANY, _("None"), wxDefaultPosition, wxDefaultSize, wxTE_READONLY); m_skylanderSlots[rowNumber]->SetMinSize(wxSize(150, -1)); m_skylanderSlots[rowNumber]->Disable(); row->Add(m_skylanderSlots[rowNumber], 1, wxEXPAND | wxALL, 2); auto* loadButton = new wxButton(box, wxID_ANY, _("Load")); loadButton->Bind(wxEVT_BUTTON, [rowNumber, this](wxCommandEvent&) { LoadSkylander(rowNumber); }); auto* createButton = new wxButton(box, wxID_ANY, _("Create")); createButton->Bind(wxEVT_BUTTON, [rowNumber, this](wxCommandEvent&) { CreateSkylander(rowNumber); }); auto* clearButton = new wxButton(box, wxID_ANY, _("Clear")); clearButton->Bind(wxEVT_BUTTON, [rowNumber, this](wxCommandEvent&) { ClearSkylander(rowNumber); }); row->Add(loadButton, 1, wxEXPAND | wxALL, 2); row->Add(createButton, 1, wxEXPAND | wxALL, 2); row->Add(clearButton, 1, wxEXPAND | wxALL, 2); return row; } wxBoxSizer* EmulatedUSBDeviceFrame::AddInfinityRow(wxString name, uint8 rowNumber, wxStaticBox* box) { auto* row = new wxBoxSizer(wxHORIZONTAL); row->Add(new wxStaticText(box, wxID_ANY, name), 1, wxEXPAND | wxALL, 2); m_infinitySlots[rowNumber] = new wxTextCtrl(box, wxID_ANY, _("None"), wxDefaultPosition, wxDefaultSize, wxTE_READONLY); m_infinitySlots[rowNumber]->SetMinSize(wxSize(150, -1)); m_infinitySlots[rowNumber]->Disable(); row->Add(m_infinitySlots[rowNumber], 1, wxALL | wxEXPAND, 5); auto* loadButton = new wxButton(box, wxID_ANY, _("Load")); loadButton->Bind(wxEVT_BUTTON, [rowNumber, this](wxCommandEvent&) { LoadFigure(rowNumber); }); auto* createButton = new wxButton(box, wxID_ANY, _("Create")); createButton->Bind(wxEVT_BUTTON, [rowNumber, this](wxCommandEvent&) { CreateFigure(rowNumber); }); auto* clearButton = new wxButton(box, wxID_ANY, _("Clear")); clearButton->Bind(wxEVT_BUTTON, [rowNumber, this](wxCommandEvent&) { ClearFigure(rowNumber); }); row->Add(loadButton, 1, wxEXPAND | wxALL, 2); row->Add(createButton, 1, wxEXPAND | wxALL, 2); row->Add(clearButton, 1, wxEXPAND | wxALL, 2); return row; } wxBoxSizer* EmulatedUSBDeviceFrame::AddDimensionPanel(uint8 pad, uint8 index, wxStaticBox* box) { auto* panel = new wxBoxSizer(wxVERTICAL); auto* combo_row = new wxBoxSizer(wxHORIZONTAL); m_dimensionSlots[index] = new wxTextCtrl(box, wxID_ANY, _("None"), wxDefaultPosition, wxDefaultSize, wxTE_READONLY); combo_row->Add(m_dimensionSlots[index], 1, wxEXPAND | wxALL, 2); auto* move_button = new wxButton(box, wxID_ANY, _("Move")); move_button->Bind(wxEVT_BUTTON, [pad, index, this](wxCommandEvent&) { MoveMinifig(pad, index); }); combo_row->Add(move_button, 1, wxEXPAND | wxALL, 2); auto* button_row = new wxBoxSizer(wxHORIZONTAL); auto* load_button = new wxButton(box, wxID_ANY, _("Load")); load_button->Bind(wxEVT_BUTTON, [pad, index, this](wxCommandEvent&) { LoadMinifig(pad, index); }); auto* clear_button = new wxButton(box, wxID_ANY, _("Clear")); clear_button->Bind(wxEVT_BUTTON, [pad, index, this](wxCommandEvent&) { ClearMinifig(pad, index); }); auto* create_button = new wxButton(box, wxID_ANY, _("Create")); create_button->Bind(wxEVT_BUTTON, [pad, index, this](wxCommandEvent&) { CreateMinifig(pad, index); }); button_row->Add(clear_button, 1, wxEXPAND | wxALL, 2); button_row->Add(create_button, 1, wxEXPAND | wxALL, 2); button_row->Add(load_button, 1, wxEXPAND | wxALL, 2); panel->Add(combo_row, 1, wxEXPAND | wxALL, 2); panel->Add(button_row, 1, wxEXPAND | wxALL, 2); return panel; } void EmulatedUSBDeviceFrame::LoadSkylander(uint8 slot) { wxFileDialog openFileDialog(this, _("Open Skylander dump"), "", "", "Skylander files (*.sky;*.bin;*.dump;*.dmp)|*.sky;*.bin;*.dump;*.dmp", wxFD_OPEN | wxFD_FILE_MUST_EXIST); if (openFileDialog.ShowModal() != wxID_OK || openFileDialog.GetPath().empty()) return; LoadSkylanderPath(slot, openFileDialog.GetPath()); } void EmulatedUSBDeviceFrame::LoadSkylanderPath(uint8 slot, wxString path) { std::unique_ptr<FileStream> skyFile(FileStream::openFile2(_utf8ToPath(path.utf8_string()), true)); if (!skyFile) { wxMessageDialog open_error(this, "Error Opening File: " + path.c_str()); open_error.ShowModal(); return; } std::array<uint8, nsyshid::SKY_FIGURE_SIZE> fileData; if (skyFile->readData(fileData.data(), fileData.size()) != fileData.size()) { wxMessageDialog open_error(this, "Failed to read file! File was too small"); open_error.ShowModal(); return; } ClearSkylander(slot); uint16 skyId = uint16(fileData[0x11]) << 8 | uint16(fileData[0x10]); uint16 skyVar = uint16(fileData[0x1D]) << 8 | uint16(fileData[0x1C]); uint8 portalSlot = nsyshid::g_skyportal.LoadSkylander(fileData.data(), std::move(skyFile)); m_skySlots[slot] = std::tuple(portalSlot, skyId, skyVar); UpdateSkylanderEdits(); } void EmulatedUSBDeviceFrame::CreateSkylander(uint8 slot) { CreateSkylanderDialog create_dlg(this, slot); create_dlg.ShowModal(); if (create_dlg.GetReturnCode() == 1) { LoadSkylanderPath(slot, create_dlg.GetFilePath()); } } void EmulatedUSBDeviceFrame::ClearSkylander(uint8 slot) { if (auto slotInfos = m_skySlots[slot]) { auto [curSlot, id, var] = slotInfos.value(); nsyshid::g_skyportal.RemoveSkylander(curSlot); m_skySlots[slot] = {}; UpdateSkylanderEdits(); } } CreateSkylanderDialog::CreateSkylanderDialog(wxWindow* parent, uint8 slot) : wxDialog(parent, wxID_ANY, _("Skylander Figure Creator"), wxDefaultPosition, wxSize(500, 150)) { auto* sizer = new wxBoxSizer(wxVERTICAL); auto* comboRow = new wxBoxSizer(wxHORIZONTAL); auto* comboBox = new wxComboBox(this, wxID_ANY); comboBox->Append("---Select---", reinterpret_cast<void*>(0xFFFFFFFF)); wxArrayString filterlist; for (const auto& it : nsyshid::g_skyportal.GetListSkylanders()) { const uint32 variant = uint32(uint32(it.first.first) << 16) | uint32(it.first.second); comboBox->Append(it.second, reinterpret_cast<void*>(variant)); filterlist.Add(it.second); } comboBox->SetSelection(0); bool enabled = comboBox->AutoComplete(filterlist); comboRow->Add(comboBox, 1, wxEXPAND | wxALL, 2); auto* idVarRow = new wxBoxSizer(wxHORIZONTAL); wxIntegerValidator<uint32> validator; auto* labelId = new wxStaticText(this, wxID_ANY, "ID:"); auto* labelVar = new wxStaticText(this, wxID_ANY, "Variant:"); auto* editId = new wxTextCtrl(this, wxID_ANY, _("0"), wxDefaultPosition, wxDefaultSize, 0, validator); auto* editVar = new wxTextCtrl(this, wxID_ANY, _("0"), wxDefaultPosition, wxDefaultSize, 0, validator); idVarRow->Add(labelId, 1, wxALL, 5); idVarRow->Add(editId, 1, wxALL, 5); idVarRow->Add(labelVar, 1, wxALL, 5); idVarRow->Add(editVar, 1, wxALL, 5); auto* buttonRow = new wxBoxSizer(wxHORIZONTAL); auto* createButton = new wxButton(this, wxID_ANY, _("Create")); createButton->Bind(wxEVT_BUTTON, [editId, editVar, this](wxCommandEvent&) { long longSkyId; if (!editId->GetValue().ToLong(&longSkyId) || longSkyId > 0xFFFF) { wxMessageDialog idError(this, "Error Converting ID!", "ID Entered is Invalid"); idError.ShowModal(); return; } long longSkyVar; if (!editVar->GetValue().ToLong(&longSkyVar) || longSkyVar > 0xFFFF) { wxMessageDialog idError(this, "Error Converting Variant!", "Variant Entered is Invalid"); idError.ShowModal(); return; } uint16 skyId = longSkyId & 0xFFFF; uint16 skyVar = longSkyVar & 0xFFFF; wxString predefName = nsyshid::g_skyportal.FindSkylander(skyId, skyVar) + ".sky"; wxFileDialog saveFileDialog(this, _("Create Skylander file"), "", predefName, "SKY files (*.sky)|*.sky", wxFD_SAVE | wxFD_OVERWRITE_PROMPT); if (saveFileDialog.ShowModal() == wxID_CANCEL) return; m_filePath = saveFileDialog.GetPath(); if (!nsyshid::g_skyportal.CreateSkylander(_utf8ToPath(m_filePath.utf8_string()), skyId, skyVar)) { wxMessageDialog errorMessage(this, "Failed to create file"); errorMessage.ShowModal(); this->EndModal(0); return; } this->EndModal(1); }); auto* cancelButton = new wxButton(this, wxID_ANY, _("Cancel")); cancelButton->Bind(wxEVT_BUTTON, [this](wxCommandEvent&) { this->EndModal(0); }); comboBox->Bind(wxEVT_COMBOBOX, [comboBox, editId, editVar, this](wxCommandEvent&) { const uint64 sky_info = reinterpret_cast<uint64>(comboBox->GetClientData(comboBox->GetSelection())); if (sky_info != 0xFFFFFFFF) { const uint16 skyId = sky_info >> 16; const uint16 skyVar = sky_info & 0xFFFF; editId->SetValue(wxString::Format(wxT("%i"), skyId)); editVar->SetValue(wxString::Format(wxT("%i"), skyVar)); } }); buttonRow->Add(createButton, 1, wxALL, 5); buttonRow->Add(cancelButton, 1, wxALL, 5); sizer->Add(comboRow, 1, wxEXPAND | wxALL, 2); sizer->Add(idVarRow, 1, wxEXPAND | wxALL, 2); sizer->Add(buttonRow, 1, wxEXPAND | wxALL, 2); this->SetSizer(sizer); this->Centre(wxBOTH); } wxString CreateSkylanderDialog::GetFilePath() const { return m_filePath; } void EmulatedUSBDeviceFrame::UpdateSkylanderEdits() { for (auto i = 0; i < nsyshid::MAX_SKYLANDERS; i++) { std::string displayString; if (auto sd = m_skySlots[i]) { auto [portalSlot, skyId, skyVar] = sd.value(); displayString = nsyshid::g_skyportal.FindSkylander(skyId, skyVar); } else { displayString = "None"; } m_skylanderSlots[i]->ChangeValue(displayString); } } void EmulatedUSBDeviceFrame::LoadFigure(uint8 slot) { wxFileDialog openFileDialog(this, _("Open Infinity Figure dump"), "", "", "BIN files (*.bin)|*.bin", wxFD_OPEN | wxFD_FILE_MUST_EXIST); if (openFileDialog.ShowModal() != wxID_OK || openFileDialog.GetPath().empty()) { wxMessageDialog errorMessage(this, "File Okay Error"); errorMessage.ShowModal(); return; } LoadFigurePath(slot, openFileDialog.GetPath()); } void EmulatedUSBDeviceFrame::LoadFigurePath(uint8 slot, wxString path) { std::unique_ptr<FileStream> infFile(FileStream::openFile2(_utf8ToPath(path.utf8_string()), true)); if (!infFile) { wxMessageDialog errorMessage(this, "File Open Error"); errorMessage.ShowModal(); return; } std::array<uint8, nsyshid::INF_FIGURE_SIZE> fileData; if (infFile->readData(fileData.data(), fileData.size()) != fileData.size()) { wxMessageDialog open_error(this, "Failed to read file! File was too small"); open_error.ShowModal(); return; } ClearFigure(slot); uint32 number = nsyshid::g_infinitybase.LoadFigure(fileData, std::move(infFile), slot); m_infinitySlots[slot]->ChangeValue(nsyshid::g_infinitybase.FindFigure(number).second); } void EmulatedUSBDeviceFrame::CreateFigure(uint8 slot) { cemuLog_log(LogType::Force, "Create Figure: {}", slot); CreateInfinityFigureDialog create_dlg(this, slot); create_dlg.ShowModal(); if (create_dlg.GetReturnCode() == 1) { LoadFigurePath(slot, create_dlg.GetFilePath()); } } void EmulatedUSBDeviceFrame::ClearFigure(uint8 slot) { m_infinitySlots[slot]->ChangeValue("None"); nsyshid::g_infinitybase.RemoveFigure(slot); } CreateInfinityFigureDialog::CreateInfinityFigureDialog(wxWindow* parent, uint8 slot) : wxDialog(parent, wxID_ANY, _("Infinity Figure Creator"), wxDefaultPosition, wxSize(500, 150)) { auto* sizer = new wxBoxSizer(wxVERTICAL); auto* comboRow = new wxBoxSizer(wxHORIZONTAL); auto* comboBox = new wxComboBox(this, wxID_ANY); comboBox->Append("---Select---", reinterpret_cast<void*>(0xFFFFFF)); wxArrayString filterlist; for (const auto& it : nsyshid::g_infinitybase.GetFigureList()) { const uint32 figure = it.first; if ((slot == 0 && ((figure > 0x1E8480 && figure < 0x2DC6BF) || (figure > 0x3D0900 && figure < 0x4C4B3F))) || ((slot == 1 || slot == 2) && (figure > 0x3D0900 && figure < 0x4C4B3F)) || ((slot == 3 || slot == 6) && figure < 0x1E847F) || ((slot == 4 || slot == 5 || slot == 7 || slot == 8) && (figure > 0x2DC6C0 && figure < 0x3D08FF))) { comboBox->Append(it.second.second, reinterpret_cast<void*>(figure)); filterlist.Add(it.second.second); } } comboBox->SetSelection(0); bool enabled = comboBox->AutoComplete(filterlist); comboRow->Add(comboBox, 1, wxEXPAND | wxALL, 2); auto* figNumRow = new wxBoxSizer(wxHORIZONTAL); wxIntegerValidator<uint32> validator; auto* labelFigNum = new wxStaticText(this, wxID_ANY, "Figure Number:"); auto* editFigNum = new wxTextCtrl(this, wxID_ANY, _("0"), wxDefaultPosition, wxDefaultSize, 0, validator); figNumRow->Add(labelFigNum, 1, wxALL, 5); figNumRow->Add(editFigNum, 1, wxALL, 5); auto* buttonRow = new wxBoxSizer(wxHORIZONTAL); auto* createButton = new wxButton(this, wxID_ANY, _("Create")); createButton->Bind(wxEVT_BUTTON, [editFigNum, this](wxCommandEvent&) { long longFigNum; if (!editFigNum->GetValue().ToLong(&longFigNum)) { wxMessageDialog idError(this, "Error Converting Figure Number!", "Number Entered is Invalid"); idError.ShowModal(); this->EndModal(0); } uint32 figNum = longFigNum & 0xFFFFFFFF; auto figure = nsyshid::g_infinitybase.FindFigure(figNum); wxString predefName = figure.second + ".bin"; wxFileDialog saveFileDialog(this, _("Create Infinity Figure file"), "", predefName, "BIN files (*.bin)|*.bin", wxFD_SAVE | wxFD_OVERWRITE_PROMPT); if (saveFileDialog.ShowModal() == wxID_CANCEL) this->EndModal(0); m_filePath = saveFileDialog.GetPath(); nsyshid::g_infinitybase.CreateFigure(_utf8ToPath(m_filePath.utf8_string()), figNum, figure.first); this->EndModal(1); }); auto* cancelButton = new wxButton(this, wxID_ANY, _("Cancel")); cancelButton->Bind(wxEVT_BUTTON, [this](wxCommandEvent&) { this->EndModal(0); }); comboBox->Bind(wxEVT_COMBOBOX, [comboBox, editFigNum, this](wxCommandEvent&) { const uint64 fig_info = reinterpret_cast<uint64>(comboBox->GetClientData(comboBox->GetSelection())); if (fig_info != 0xFFFFFF) { const uint32 figNum = fig_info & 0xFFFFFFFF; editFigNum->SetValue(wxString::Format(wxT("%i"), figNum)); } }); buttonRow->Add(createButton, 1, wxALL, 5); buttonRow->Add(cancelButton, 1, wxALL, 5); sizer->Add(comboRow, 1, wxEXPAND | wxALL, 2); sizer->Add(figNumRow, 1, wxEXPAND | wxALL, 2); sizer->Add(buttonRow, 1, wxEXPAND | wxALL, 2); this->SetSizer(sizer); this->Centre(wxBOTH); } wxString CreateInfinityFigureDialog::GetFilePath() const { return m_filePath; } void EmulatedUSBDeviceFrame::LoadMinifig(uint8 pad, uint8 index) { wxFileDialog openFileDialog(this, _("Load Dimensions Figure"), "", "", "Dimensions files (*.bin)|*.bin", wxFD_OPEN | wxFD_FILE_MUST_EXIST); if (openFileDialog.ShowModal() != wxID_OK || openFileDialog.GetPath().empty()) return; LoadMinifigPath(openFileDialog.GetPath(), pad, index); } void EmulatedUSBDeviceFrame::LoadMinifigPath(wxString path_name, uint8 pad, uint8 index) { std::unique_ptr<FileStream> dim_file(FileStream::openFile2(_utf8ToPath(path_name.utf8_string()), true)); if (!dim_file) { wxMessageDialog errorMessage(this, "Failed to open minifig file"); errorMessage.ShowModal(); return; } std::array<uint8, 0x2D * 0x04> file_data; if (dim_file->readData(file_data.data(), file_data.size()) != file_data.size()) { wxMessageDialog errorMessage(this, "Failed to read minifig file data"); errorMessage.ShowModal(); return; } ClearMinifig(pad, index); uint32 id = nsyshid::g_dimensionstoypad.LoadFigure(file_data, std::move(dim_file), pad, index); m_dimensionSlots[index]->ChangeValue(nsyshid::g_dimensionstoypad.FindFigure(id)); m_dimSlots[index] = id; } void EmulatedUSBDeviceFrame::ClearMinifig(uint8 pad, uint8 index) { nsyshid::g_dimensionstoypad.RemoveFigure(pad, index, true); m_dimensionSlots[index]->ChangeValue("None"); m_dimSlots[index] = std::nullopt; } void EmulatedUSBDeviceFrame::CreateMinifig(uint8 pad, uint8 index) { CreateDimensionFigureDialog create_dlg(this); create_dlg.ShowModal(); if (create_dlg.GetReturnCode() == 1) { LoadMinifigPath(create_dlg.GetFilePath(), pad, index); } } void EmulatedUSBDeviceFrame::MoveMinifig(uint8 pad, uint8 index) { if (!m_dimSlots[index]) return; MoveDimensionFigureDialog move_dlg(this, index); nsyshid::g_dimensionstoypad.TempRemove(index); move_dlg.ShowModal(); if (move_dlg.GetReturnCode() == 1) { nsyshid::g_dimensionstoypad.MoveFigure(move_dlg.GetNewPad(), move_dlg.GetNewIndex(), pad, index); if (index != move_dlg.GetNewIndex()) { m_dimSlots[move_dlg.GetNewIndex()] = m_dimSlots[index]; m_dimensionSlots[move_dlg.GetNewIndex()]->ChangeValue(m_dimensionSlots[index]->GetValue()); m_dimSlots[index] = std::nullopt; m_dimensionSlots[index]->ChangeValue("None"); } } else { nsyshid::g_dimensionstoypad.CancelRemove(index); } } CreateDimensionFigureDialog::CreateDimensionFigureDialog(wxWindow* parent) : wxDialog(parent, wxID_ANY, _("Dimensions Figure Creator"), wxDefaultPosition, wxSize(500, 200)) { auto* sizer = new wxBoxSizer(wxVERTICAL); auto* comboRow = new wxBoxSizer(wxHORIZONTAL); auto* comboBox = new wxComboBox(this, wxID_ANY); comboBox->Append("---Select---", reinterpret_cast<void*>(0xFFFFFFFF)); wxArrayString filterlist; for (const auto& it : nsyshid::g_dimensionstoypad.GetListMinifigs()) { const uint32 figure = it.first; comboBox->Append(it.second, reinterpret_cast<void*>(figure)); filterlist.Add(it.second); } comboBox->SetSelection(0); bool enabled = comboBox->AutoComplete(filterlist); comboRow->Add(comboBox, 1, wxEXPAND | wxALL, 2); auto* figNumRow = new wxBoxSizer(wxHORIZONTAL); wxIntegerValidator<uint32> validator; auto* labelFigNum = new wxStaticText(this, wxID_ANY, "Figure Number:"); auto* editFigNum = new wxTextCtrl(this, wxID_ANY, _("0"), wxDefaultPosition, wxDefaultSize, 0, validator); figNumRow->Add(labelFigNum, 1, wxALL, 5); figNumRow->Add(editFigNum, 1, wxALL, 5); auto* buttonRow = new wxBoxSizer(wxHORIZONTAL); auto* createButton = new wxButton(this, wxID_ANY, _("Create")); createButton->Bind(wxEVT_BUTTON, [editFigNum, this](wxCommandEvent&) { long longFigNum; if (!editFigNum->GetValue().ToLong(&longFigNum) || longFigNum > 0xFFFF) { wxMessageDialog idError(this, "Error Converting Figure Number!", "Number Entered is Invalid"); idError.ShowModal(); this->EndModal(0); } uint16 figNum = longFigNum & 0xFFFF; auto figure = nsyshid::g_dimensionstoypad.FindFigure(figNum); wxString predefName = figure + ".bin"; wxFileDialog saveFileDialog(this, _("Create Dimensions Figure file"), "", predefName, "BIN files (*.bin)|*.bin", wxFD_SAVE | wxFD_OVERWRITE_PROMPT); if (saveFileDialog.ShowModal() == wxID_CANCEL) this->EndModal(0); m_filePath = saveFileDialog.GetPath(); nsyshid::g_dimensionstoypad.CreateFigure(_utf8ToPath(m_filePath.utf8_string()), figNum); this->EndModal(1); }); auto* cancelButton = new wxButton(this, wxID_ANY, _("Cancel")); cancelButton->Bind(wxEVT_BUTTON, [this](wxCommandEvent&) { this->EndModal(0); }); comboBox->Bind(wxEVT_COMBOBOX, [comboBox, editFigNum, this](wxCommandEvent&) { const uint64 fig_info = reinterpret_cast<uint64>(comboBox->GetClientData(comboBox->GetSelection())); if (fig_info != 0xFFFF) { const uint16 figNum = fig_info & 0xFFFF; editFigNum->SetValue(wxString::Format(wxT("%i"), figNum)); } }); buttonRow->Add(createButton, 1, wxALL, 5); buttonRow->Add(cancelButton, 1, wxALL, 5); sizer->Add(comboRow, 1, wxEXPAND | wxALL, 2); sizer->Add(figNumRow, 1, wxEXPAND | wxALL, 2); sizer->Add(buttonRow, 1, wxEXPAND | wxALL, 2); this->SetSizer(sizer); this->Centre(wxBOTH); } wxString CreateDimensionFigureDialog::GetFilePath() const { return m_filePath; } MoveDimensionFigureDialog::MoveDimensionFigureDialog(EmulatedUSBDeviceFrame* parent, uint8 currentIndex) : wxDialog(parent, wxID_ANY, _("Dimensions Figure Mover"), wxDefaultPosition, wxSize(700, 300)) { auto* sizer = new wxGridSizer(2, 5, 10, 10); std::array<std::optional<uint32>, 7> ids = parent->GetCurrentMinifigs(); sizer->Add(AddMinifigSlot(2, 0, currentIndex, ids[0]), 1, wxALL, 5); sizer->Add(new wxStaticText(this, wxID_ANY, ""), 1, wxALL, 5); sizer->Add(AddMinifigSlot(1, 1, currentIndex, ids[1]), 1, wxALL, 5); sizer->Add(new wxStaticText(this, wxID_ANY, ""), 1, wxALL, 5); sizer->Add(AddMinifigSlot(3, 2, currentIndex, ids[2]), 1, wxALL, 5); sizer->Add(AddMinifigSlot(2, 3, currentIndex, ids[3]), 1, wxALL, 5); sizer->Add(AddMinifigSlot(2, 4, currentIndex, ids[4]), 1, wxALL, 5); sizer->Add(new wxStaticText(this, wxID_ANY, ""), 1, wxALL, 5); sizer->Add(AddMinifigSlot(3, 5, currentIndex, ids[5]), 1, wxALL, 5); sizer->Add(AddMinifigSlot(3, 6, currentIndex, ids[6]), 1, wxALL, 5); this->SetSizer(sizer); this->Centre(wxBOTH); } wxBoxSizer* MoveDimensionFigureDialog::AddMinifigSlot(uint8 pad, uint8 index, uint8 currentIndex, std::optional<uint32> currentId) { auto* panel = new wxBoxSizer(wxVERTICAL); auto* label = new wxStaticText(this, wxID_ANY, "None"); if (currentId) label->SetLabel(nsyshid::g_dimensionstoypad.FindFigure(currentId.value())); auto* moveButton = new wxButton(this, wxID_ANY, _("Move Here")); if (index == currentIndex) moveButton->SetLabelText("Pick up and Place"); moveButton->Bind(wxEVT_BUTTON, [pad, index, this](wxCommandEvent&) { m_newPad = pad; m_newIndex = index; this->EndModal(1); }); panel->Add(label, 1, wxALL, 5); panel->Add(moveButton, 1, wxALL, 5); return panel; } uint8 MoveDimensionFigureDialog::GetNewPad() const { return m_newPad; } uint8 MoveDimensionFigureDialog::GetNewIndex() const { return m_newIndex; } std::array<std::optional<uint32>, 7> EmulatedUSBDeviceFrame::GetCurrentMinifigs() { return m_dimSlots; }
27,899
C++
.cpp
695
37.589928
130
0.727498
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
22,999
VulkanCanvas.cpp
cemu-project_Cemu/src/gui/canvas/VulkanCanvas.cpp
#include "gui/canvas/VulkanCanvas.h" #include "Cafe/HW/Latte/Renderer/Vulkan/VulkanRenderer.h" #include "gui/guiWrapper.h" #if BOOST_OS_LINUX && HAS_WAYLAND #include "gui/helpers/wxWayland.h" #endif #include <wx/msgdlg.h> #include <helpers/wxHelpers.h> VulkanCanvas::VulkanCanvas(wxWindow* parent, const wxSize& size, bool is_main_window) : IRenderCanvas(is_main_window), wxWindow(parent, wxID_ANY, wxDefaultPosition, size, wxNO_FULL_REPAINT_ON_RESIZE | wxWANTS_CHARS) { Bind(wxEVT_PAINT, &VulkanCanvas::OnPaint, this); Bind(wxEVT_SIZE, &VulkanCanvas::OnResize, this); WindowHandleInfo& canvas = is_main_window ? gui_getWindowInfo().canvas_main : gui_getWindowInfo().canvas_pad; gui_initHandleContextFromWxWidgetsWindow(canvas, this); #if BOOST_OS_LINUX && HAS_WAYLAND if (canvas.backend == WindowHandleInfo::Backend::WAYLAND) { m_subsurface = std::make_unique<wxWlSubsurface>(this); canvas.surface = m_subsurface->getSurface(); } #endif cemu_assert(g_vulkan_available); try { if (is_main_window) g_renderer = std::make_unique<VulkanRenderer>(); auto vulkan_renderer = VulkanRenderer::GetInstance(); vulkan_renderer->InitializeSurface({size.x, size.y}, is_main_window); } catch(const std::exception& ex) { cemuLog_log(LogType::Force, "Error when initializing Vulkan renderer: {}", ex.what()); auto msg = formatWxString(_("Error when initializing Vulkan renderer:\n{}"), ex.what()); wxMessageDialog dialog(this, msg, _("Error"), wxOK | wxCENTRE | wxICON_ERROR); dialog.ShowModal(); exit(0); } wxWindow::EnableTouchEvents(wxTOUCH_PAN_GESTURES); } VulkanCanvas::~VulkanCanvas() { Unbind(wxEVT_PAINT, &VulkanCanvas::OnPaint, this); Unbind(wxEVT_SIZE, &VulkanCanvas::OnResize, this); if(!m_is_main_window) { VulkanRenderer* vkr = (VulkanRenderer*)g_renderer.get(); if(vkr) vkr->StopUsingPadAndWait(); } } void VulkanCanvas::OnPaint(wxPaintEvent& event) { } void VulkanCanvas::OnResize(wxSizeEvent& event) { const wxSize size = GetSize(); if (size.GetWidth() == 0 || size.GetHeight() == 0) return; #if BOOST_OS_LINUX && HAS_WAYLAND if(m_subsurface) { auto sRect = GetScreenRect(); m_subsurface->setSize(sRect.GetX(), sRect.GetY(), sRect.GetWidth(), sRect.GetHeight()); } #endif const wxRect refreshRect(size); RefreshRect(refreshRect, false); }
2,319
C++
.cpp
69
31.449275
130
0.746869
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
23,000
OpenGLCanvas.cpp
cemu-project_Cemu/src/gui/canvas/OpenGLCanvas.cpp
#include "gui/canvas/OpenGLCanvas.h" #include "Cafe/HW/Latte/Renderer/OpenGL/OpenGLRenderer.h" #include "config/CemuConfig.h" #include "Common/GLInclude/GLInclude.h" #include <wx/glcanvas.h> // this includes GL/gl.h, avoid using this in a header because it would contaminate our own OpenGL definitions (GLInclude) static const int g_gl_attribute_list[] = { WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_DEPTH_SIZE, 16, WX_GL_MIN_RED, 8, WX_GL_MIN_GREEN, 8, WX_GL_MIN_BLUE, 8, WX_GL_MIN_ALPHA, 8, WX_GL_STENCIL_SIZE, 8, //WX_GL_MAJOR_VERSION, 4, //WX_GL_MINOR_VERSION, 1, //wx_GL_COMPAT_PROFILE, 0, // end of list }; wxGLContext* sGLContext = nullptr; class OpenGLCanvas* sGLTVView = nullptr; class OpenGLCanvas* sGLPadView = nullptr; class OpenGLCanvas : public IRenderCanvas, public wxGLCanvas { public: OpenGLCanvas(wxWindow* parent, const wxSize& size, bool is_main_window) : IRenderCanvas(is_main_window), wxGLCanvas(parent, wxID_ANY, g_gl_attribute_list, wxDefaultPosition, size, wxFULL_REPAINT_ON_RESIZE | wxWANTS_CHARS) { if (m_is_main_window) { sGLTVView = this; sGLContext = new wxGLContext(this); g_renderer = std::make_unique<OpenGLRenderer>(); } else sGLPadView = this; wxWindow::EnableTouchEvents(wxTOUCH_PAN_GESTURES); } ~OpenGLCanvas() override { // todo - if this is the main window, make sure the renderer has been shut down if (m_is_main_window) sGLTVView = nullptr; else sGLPadView = nullptr; if (sGLTVView == nullptr && sGLPadView == nullptr && sGLContext) delete sGLContext; } void UpdateVSyncState() { int configValue = GetConfig().vsync.GetValue(); if(m_activeVSyncState != configValue) { #if BOOST_OS_WINDOWS if(wglSwapIntervalEXT) wglSwapIntervalEXT(configValue); // 1 = enabled, 0 = disabled #elif BOOST_OS_LINUX if (eglSwapInterval) { if (eglSwapInterval(eglGetCurrentDisplay(), configValue) == EGL_FALSE) { cemuLog_log(LogType::Force, "Failed to set vsync using EGL"); } } #else cemuLog_log(LogType::Force, "OpenGL vsync not implemented"); #endif m_activeVSyncState = configValue; } } private: int m_activeVSyncState = -1; //wxGLContext* m_context = nullptr; }; wxWindow* GLCanvas_Create(wxWindow* parent, const wxSize& size, bool is_main_window) { return new OpenGLCanvas(parent, size, is_main_window); } bool GLCanvas_HasPadViewOpen() { return sGLPadView != nullptr; } bool GLCanvas_MakeCurrent(bool padView) { OpenGLCanvas* canvas = padView ? sGLPadView : sGLTVView; if (!canvas) return false; sGLContext->SetCurrent(*canvas); return true; } void GLCanvas_SwapBuffers(bool swapTV, bool swapDRC) { if (swapTV && sGLTVView) { GLCanvas_MakeCurrent(false); sGLTVView->SwapBuffers(); sGLTVView->UpdateVSyncState(); } if (swapDRC && sGLPadView) { GLCanvas_MakeCurrent(true); sGLPadView->SwapBuffers(); sGLPadView->UpdateVSyncState(); } GLCanvas_MakeCurrent(false); }
2,943
C++
.cpp
107
25.018692
151
0.742806
cemu-project/Cemu
7,119
558
254
MPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false