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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5,002
|
stdafx.cpp
|
RPCS3_rpcs3/rpcs3/stdafx.cpp
|
#include "stdafx.h" // No BOM and only basic ASCII in this file, or a neko will die
static_assert(std::endian::native == std::endian::little || std::endian::native == std::endian::big);
CHECK_SIZE_ALIGN(u128, 16, 16);
CHECK_SIZE_ALIGN(s128, 16, 16);
CHECK_SIZE_ALIGN(f16, 2, 2);
static_assert(be_t<u16>(1) + be_t<u32>(2) + be_t<u64>(3) == 6);
static_assert(le_t<u16>(1) + le_t<u32>(2) + le_t<u64>(3) == 6);
static_assert(sizeof(nullptr) == sizeof(void*));
static_assert(__cpp_constexpr_dynamic_alloc >= 201907L);
namespace
{
struct A
{
int a;
};
struct B : A
{
int b;
};
struct Z
{
};
struct C
{
virtual ~C() = 0;
int C;
};
struct D : Z, B
{
int d;
};
struct E : C, B
{
int e;
};
struct F : C
{
virtual ~F() = 0;
};
static_assert(is_same_ptr<B, A>());
static_assert(is_same_ptr<A, B>());
static_assert(is_same_ptr<D, B>());
static_assert(is_same_ptr<B, D>());
static_assert(!is_same_ptr<E, B>());
static_assert(!is_same_ptr<B, E>());
static_assert(is_same_ptr<F, C>());
static_assert(is_same_ptr<C, F>());
}
| 1,065
|
C++
|
.cpp
| 48
| 20
| 101
| 0.622134
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
5,003
|
display_sleep_control.cpp
|
RPCS3_rpcs3/rpcs3/display_sleep_control.cpp
|
#include "display_sleep_control.h"
#ifdef _WIN32
#include <windows.h>
#elif defined(__APPLE__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#include <IOKit/pwr_mgt/IOPMLib.h>
#pragma GCC diagnostic pop
static IOPMAssertionID s_pm_assertion = kIOPMNullAssertionID;
#elif defined(HAVE_QTDBUS)
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusInterface>
#include <QtDBus/QDBusMessage>
#include <QDBusReply>
#include "util/types.hpp"
static u32 s_dbus_cookie = 0;
#endif
bool display_sleep_control_supported()
{
#if defined(_WIN32) || defined(__APPLE__)
return true;
#elif defined(HAVE_QTDBUS)
for (const char* service : { "org.freedesktop.ScreenSaver", "org.mate.ScreenSaver" })
{
QDBusInterface interface(service, "/ScreenSaver", service, QDBusConnection::sessionBus());
if (interface.isValid())
{
return true;
}
}
return false;
#else
return false;
#endif
}
void enable_display_sleep()
{
if (!display_sleep_control_supported())
{
return;
}
#ifdef _WIN32
SetThreadExecutionState(ES_CONTINUOUS);
#elif defined(__APPLE__)
if (s_pm_assertion != kIOPMNullAssertionID)
{
IOPMAssertionRelease(s_pm_assertion);
s_pm_assertion = kIOPMNullAssertionID;
}
#elif defined(HAVE_QTDBUS)
if (s_dbus_cookie != 0)
{
for (const char* service : { "org.freedesktop.ScreenSaver", "org.mate.ScreenSaver" })
{
QDBusInterface interface(service, "/ScreenSaver", service, QDBusConnection::sessionBus());
if (interface.isValid())
{
interface.call("UnInhibit", s_dbus_cookie);
break;
}
}
s_dbus_cookie = 0;
}
#endif
}
void disable_display_sleep()
{
if (!display_sleep_control_supported())
{
return;
}
#ifdef _WIN32
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED);
#elif defined(__APPLE__)
#pragma GCC diagnostic push
// Necessary as some of those values are macro using old casts
#pragma GCC diagnostic ignored "-Wold-style-cast"
IOPMAssertionCreateWithName(kIOPMAssertionTypePreventUserIdleDisplaySleep, kIOPMAssertionLevelOn, CFSTR("Game running"), &s_pm_assertion);
#pragma GCC diagnostic pop
#elif defined(HAVE_QTDBUS)
for (const char* service : { "org.freedesktop.ScreenSaver", "org.mate.ScreenSaver" })
{
QDBusInterface interface(service, "/ScreenSaver", service, QDBusConnection::sessionBus());
if (interface.isValid())
{
QDBusReply<u32> reply = interface.call("Inhibit", "rpcs3", "Game running");
if (reply.isValid())
{
s_dbus_cookie = reply.value();
}
break;
}
}
#endif
}
| 2,530
|
C++
|
.cpp
| 95
| 24.505263
| 139
| 0.748969
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
5,004
|
rpcs3_version.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3_version.cpp
|
#include "stdafx.h"
#include "rpcs3_version.h"
#include "git-version.h"
#include "Utilities/StrUtil.h"
namespace rpcs3
{
std::string_view get_branch()
{
return RPCS3_GIT_BRANCH;
}
std::string_view get_full_branch()
{
return RPCS3_GIT_FULL_BRANCH;
}
std::pair<std::string, std::string> get_commit_and_hash()
{
const auto commit_and_hash = fmt::split(RPCS3_GIT_VERSION, {"-"});
if (commit_and_hash.size() != 2)
return std::make_pair("0", "00000000");
return std::make_pair(commit_and_hash[0], commit_and_hash[1]);
}
// TODO: Make this accessible from cmake and keep in sync with MACOSX_BUNDLE_BUNDLE_VERSION.
// Currently accessible by Windows and Linux build scripts, see implementations when doing MACOSX
const utils::version& get_version()
{
static constexpr utils::version version{ 0, 0, 34, utils::version_type::alpha, 1, RPCS3_GIT_VERSION };
return version;
}
std::string get_version_and_branch()
{
// Add branch and commit hash to version on frame unless it's master.
if (rpcs3::get_branch() != "master"sv && rpcs3::get_branch() != "HEAD"sv)
{
return get_verbose_version();
}
// Get version by substringing VersionNumber-buildnumber-commithash to get just the part before the dash
std::string version = rpcs3::get_version().to_string();
const auto last_minus = version.find_last_of('-');
version = version.substr(0, last_minus);
return version;
}
std::string get_verbose_version()
{
std::string version = fmt::format("%s | %s", rpcs3::get_version().to_string(), get_branch());
if (is_local_build())
{
fmt::append(version, " | local_build");
}
return version;
}
bool is_release_build()
{
static constexpr bool is_release_build = std::string_view(RPCS3_GIT_FULL_BRANCH) == "RPCS3/rpcs3/master"sv;
return is_release_build;
}
bool is_local_build()
{
static constexpr bool is_local_build = std::string_view(RPCS3_GIT_FULL_BRANCH) == "local_build"sv;
return is_local_build;
}
}
| 1,974
|
C++
|
.cpp
| 61
| 29.770492
| 109
| 0.708048
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,005
|
skateboard_pad_handler.cpp
|
RPCS3_rpcs3/rpcs3/Input/skateboard_pad_handler.cpp
|
#include "stdafx.h"
#include "skateboard_pad_handler.h"
#include "Emu/Io/pad_config.h"
LOG_CHANNEL(skateboard_log, "Skateboard");
using namespace reports;
namespace
{
constexpr id_pair SKATEBOARD_ID_0 = {0x12BA, 0x0400}; // Tony Hawk RIDE Skateboard
constexpr id_pair SKATEBOARD_ID_1 = {0x1430, 0x0100}; // Tony Hawk SHRED Skateboard
enum button_flags : u16
{
square = 0x0001,
cross = 0x0002,
circle = 0x0004,
triangle = 0x0008,
select = 0x0100,
start = 0x0200,
ps = 0x1000,
};
enum dpad_states : u8
{
up = 0x00,
up_right = 0x01,
left = 0x02,
down_right = 0x03,
down = 0x04,
down_left = 0x05,
right = 0x06,
up_left = 0x07,
none = 0x0F,
};
// Default data if dongle is connected but the skateboard is turned off:
static constexpr std::array<u8, sizeof(skateboard_input_report)> not_connected_state = { 0x00, 0x00, 0x0F, 0x80, 0x80, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02 };
static constexpr std::array<u8, sizeof(skateboard_input_report)> disconnected_state = { 0x00, 0x00, 0x0F, 0x80, 0x80, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
}
skateboard_pad_handler::skateboard_pad_handler()
: hid_pad_handler<skateboard_device>(pad_handler::skateboard, {SKATEBOARD_ID_0, SKATEBOARD_ID_1})
{
// Unique names for the config files and our pad settings dialog
button_list =
{
{ skateboard_key_codes::none, "" },
{ skateboard_key_codes::left, "Left" },
{ skateboard_key_codes::right, "Right" },
{ skateboard_key_codes::up, "Up" },
{ skateboard_key_codes::down, "Down" },
{ skateboard_key_codes::cross, "Cross" },
{ skateboard_key_codes::square, "Square" },
{ skateboard_key_codes::circle, "Circle" },
{ skateboard_key_codes::triangle, "Triangle" },
{ skateboard_key_codes::start, "Start" },
{ skateboard_key_codes::select, "Select" },
{ skateboard_key_codes::ps, "PS" },
{ skateboard_key_codes::ir_left, "IR Left" },
{ skateboard_key_codes::ir_right, "IR Right" },
{ skateboard_key_codes::ir_nose, "IR Nose" },
{ skateboard_key_codes::ir_tail, "IR Tail" },
{ skateboard_key_codes::tilt_left, "Tilt Left" },
{ skateboard_key_codes::tilt_right, "Tilt Right" }
};
init_configs();
// Define border values
thumb_max = 255;
trigger_min = 0;
trigger_max = 255;
// Set capabilities
b_has_config = true;
b_has_rumble = false;
b_has_motion = true;
b_has_deadzones = false;
b_has_led = false;
b_has_rgb = false;
b_has_player_led = false;
b_has_battery = false;
b_has_battery_led = false;
b_has_pressure_intensity_button = false;
m_name_string = "Skateboard #";
m_max_devices = CELL_PAD_MAX_PORT_NUM;
m_trigger_threshold = trigger_max / 2;
m_thumb_threshold = thumb_max / 2;
}
skateboard_pad_handler::~skateboard_pad_handler()
{
}
void skateboard_pad_handler::init_config(cfg_pad* cfg)
{
if (!cfg) return;
// Set default button mapping
cfg->ls_left.def = ::at32(button_list, skateboard_key_codes::none);
cfg->ls_down.def = ::at32(button_list, skateboard_key_codes::none);
cfg->ls_right.def = ::at32(button_list, skateboard_key_codes::none);
cfg->ls_up.def = ::at32(button_list, skateboard_key_codes::none);
cfg->rs_left.def = ::at32(button_list, skateboard_key_codes::none);
cfg->rs_down.def = ::at32(button_list, skateboard_key_codes::none);
cfg->rs_right.def = ::at32(button_list, skateboard_key_codes::none);
cfg->rs_up.def = ::at32(button_list, skateboard_key_codes::none);
cfg->start.def = ::at32(button_list, skateboard_key_codes::start);
cfg->select.def = ::at32(button_list, skateboard_key_codes::select);
cfg->ps.def = ::at32(button_list, skateboard_key_codes::ps);
cfg->square.def = ::at32(button_list, skateboard_key_codes::square);
cfg->cross.def = ::at32(button_list, skateboard_key_codes::cross);
cfg->circle.def = ::at32(button_list, skateboard_key_codes::circle);
cfg->triangle.def = ::at32(button_list, skateboard_key_codes::triangle);
cfg->left.def = ::at32(button_list, skateboard_key_codes::left);
cfg->down.def = ::at32(button_list, skateboard_key_codes::down);
cfg->right.def = ::at32(button_list, skateboard_key_codes::right);
cfg->up.def = ::at32(button_list, skateboard_key_codes::up);
cfg->r1.def = ::at32(button_list, skateboard_key_codes::none);
cfg->r2.def = ::at32(button_list, skateboard_key_codes::none);
cfg->r3.def = ::at32(button_list, skateboard_key_codes::none);
cfg->l1.def = ::at32(button_list, skateboard_key_codes::none);
cfg->l2.def = ::at32(button_list, skateboard_key_codes::none);
cfg->l3.def = ::at32(button_list, skateboard_key_codes::none);
cfg->ir_nose.def = ::at32(button_list, skateboard_key_codes::ir_nose);
cfg->ir_tail.def = ::at32(button_list, skateboard_key_codes::ir_tail);
cfg->ir_left.def = ::at32(button_list, skateboard_key_codes::ir_left);
cfg->ir_right.def = ::at32(button_list, skateboard_key_codes::ir_right);
cfg->tilt_left.def = ::at32(button_list, skateboard_key_codes::tilt_left);
cfg->tilt_right.def = ::at32(button_list, skateboard_key_codes::tilt_right);
// Set default misc variables
cfg->lstick_anti_deadzone.def = 0;
cfg->rstick_anti_deadzone.def = 0;
cfg->lstickdeadzone.def = 40; // between 0 and 255
cfg->rstickdeadzone.def = 40; // between 0 and 255
cfg->ltriggerthreshold.def = 0; // between 0 and 255
cfg->rtriggerthreshold.def = 0; // between 0 and 255
// apply defaults
cfg->from_default();
}
void skateboard_pad_handler::check_add_device(hid_device* hidDevice, std::string_view path, std::wstring_view wide_serial)
{
if (!hidDevice)
{
return;
}
skateboard_device* device = nullptr;
for (auto& controller : m_controllers)
{
ensure(controller.second);
if (!controller.second->hidDevice)
{
device = controller.second.get();
break;
}
}
if (!device)
{
return;
}
if (hid_set_nonblocking(hidDevice, 1) == -1)
{
skateboard_log.error("check_add_device: hid_set_nonblocking failed! Reason: %s", hid_error(hidDevice));
hid_close(hidDevice);
return;
}
device->hidDevice = hidDevice;
device->path = path;
// Activate
if (send_output_report(device) == -1)
{
skateboard_log.error("check_add_device: send_output_report failed! Reason: %s", hid_error(hidDevice));
}
std::string serial;
for (wchar_t ch : wide_serial)
serial += static_cast<uchar>(ch);
skateboard_log.notice("Added device: serial='%s', path='%s'", serial, device->path);
}
skateboard_pad_handler::DataStatus skateboard_pad_handler::get_data(skateboard_device* device)
{
if (!device)
return DataStatus::ReadError;
std::array<u8, sizeof(skateboard_input_report)> buf{};
int res = hid_read(device->hidDevice, buf.data(), buf.size());
if (res == -1)
{
// looks like controller disconnected or read error
skateboard_log.error("get_data ReadError: %s", hid_error(device->hidDevice));
return DataStatus::ReadError;
}
if (res != static_cast<int>(sizeof(skateboard_input_report)))
return DataStatus::NoNewData;
if (std::memcmp(&device->report, buf.data(), sizeof(skateboard_input_report)) == 0)
return DataStatus::NoNewData;
// Get the new data
std::memcpy(&device->report, buf.data(), sizeof(skateboard_input_report));
// Check the skateboard's power state based on the input report
device->skateboard_is_on =
(std::memcmp(not_connected_state.data(), buf.data(), not_connected_state.size()) != 0 && // This usually means that the device hasn't been connected to the dongle yet.
std::memcmp(disconnected_state.data(), buf.data(), disconnected_state.size()) != 0); // This usually means that the device was disconnected from the dongle.
return DataStatus::NewData;
}
PadHandlerBase::connection skateboard_pad_handler::update_connection(const std::shared_ptr<PadDevice>& device)
{
skateboard_device* dev = static_cast<skateboard_device*>(device.get());
if (!dev || dev->path.empty())
return connection::disconnected;
if (dev->hidDevice == nullptr)
{
// try to reconnect
if (hid_device* hid_dev = hid_open_path(dev->path.c_str()))
{
if (hid_set_nonblocking(hid_dev, 1) == -1)
{
skateboard_log.error("Reconnecting Device %s: hid_set_nonblocking failed with error %s", dev->path, hid_error(hid_dev));
}
dev->hidDevice = hid_dev;
}
else
{
// nope, not there
skateboard_log.error("Device %s: disconnected", dev->path);
return connection::disconnected;
}
}
if (get_data(dev) == DataStatus::ReadError)
{
// this also can mean disconnected, either way deal with it on next loop and reconnect
dev->close();
return connection::no_data;
}
if (!dev->skateboard_is_on)
{
// This means that the dongle is still connected, but the skateboard is turned off.
// There is no need to reconnect the hid device again, we just have to check the input report for proper data.
// The game should get the proper disconnected state anyway.
return connection::disconnected;
}
return connection::connected;
}
std::unordered_map<u64, u16> skateboard_pad_handler::get_button_values(const std::shared_ptr<PadDevice>& device)
{
std::unordered_map<u64, u16> key_buf;
skateboard_device* dev = static_cast<skateboard_device*>(device.get());
if (!dev)
return key_buf;
const skateboard_input_report& input = dev->report;
// D-Pad
key_buf[skateboard_key_codes::left] = (input.d_pad == dpad_states::left || input.d_pad == dpad_states::up_left || input.d_pad == dpad_states::down_left) ? 255 : 0;
key_buf[skateboard_key_codes::right] = (input.d_pad == dpad_states::right || input.d_pad == dpad_states::up_right || input.d_pad == dpad_states::down_right) ? 255 : 0;
key_buf[skateboard_key_codes::up] = (input.d_pad == dpad_states::up || input.d_pad == dpad_states::up_left || input.d_pad == dpad_states::up_right) ? 255 : 0;
key_buf[skateboard_key_codes::down] = (input.d_pad == dpad_states::down || input.d_pad == dpad_states::down_left || input.d_pad == dpad_states::down_right) ? 255 : 0;
// Face buttons
key_buf[skateboard_key_codes::cross] = (input.buttons & button_flags::cross) ? 255 : 0;
key_buf[skateboard_key_codes::square] = (input.buttons & button_flags::square) ? 255 : 0;
key_buf[skateboard_key_codes::circle] = (input.buttons & button_flags::circle) ? 255 : 0;
key_buf[skateboard_key_codes::triangle] = (input.buttons & button_flags::triangle) ? 255 : 0;
key_buf[skateboard_key_codes::start] = (input.buttons & button_flags::start) ? 255 : 0;
key_buf[skateboard_key_codes::select] = (input.buttons & button_flags::select) ? 255 : 0;
key_buf[skateboard_key_codes::ps] = (input.buttons & button_flags::ps) ? 255 : 0;
// Infrared
key_buf[skateboard_key_codes::ir_nose] = input.pressure_triangle;
key_buf[skateboard_key_codes::ir_tail] = input.pressure_circle;
key_buf[skateboard_key_codes::ir_left] = input.pressure_cross;
key_buf[skateboard_key_codes::ir_right] = input.pressure_square;
key_buf[skateboard_key_codes::tilt_left] = input.pressure_l1;
key_buf[skateboard_key_codes::tilt_right] = input.pressure_r1;
// NOTE: Axes X, Y, Z and RZ are always 128, which is the default anyway, so setting the values is omitted.
return key_buf;
}
void skateboard_pad_handler::get_extended_info(const pad_ensemble& binding)
{
const auto& device = binding.device;
const auto& pad = binding.pad;
skateboard_device* dev = static_cast<skateboard_device*>(device.get());
if (!dev || !pad)
return;
const skateboard_input_report& input = dev->report;
pad->m_sensors[0].m_value = Clamp0To1023(input.large_axes[0]);
pad->m_sensors[1].m_value = Clamp0To1023(input.large_axes[1]);
pad->m_sensors[2].m_value = Clamp0To1023(input.large_axes[2]);
pad->m_sensors[3].m_value = Clamp0To1023(input.large_axes[3]);
}
pad_preview_values skateboard_pad_handler::get_preview_values(const std::unordered_map<u64, u16>& /*data*/)
{
// There is no proper user interface for skateboard values yet
return {};
}
int skateboard_pad_handler::send_output_report(skateboard_device* device)
{
if (!device || !device->hidDevice)
return -2;
const cfg_pad* config = device->config;
if (config == nullptr)
return -2; // hid_write returns -1 on error
// The output report contents are still unknown
skateboard_output_report report{};
return hid_write(device->hidDevice, report.data.data(), report.data.size());
}
void skateboard_pad_handler::apply_pad_data(const pad_ensemble& binding)
{
const auto& device = binding.device;
const auto& pad = binding.pad;
skateboard_device* dev = static_cast<skateboard_device*>(device.get());
if (!dev || !dev->hidDevice || !dev->config || !pad)
return;
dev->new_output_data = false;
// Disabled until needed
//const auto now = steady_clock::now();
//const auto elapsed = now - dev->last_output;
//if (dev->new_output_data || elapsed > min_output_interval)
//{
// if (const int res = send_output_report(dev); res >= 0)
// {
// dev->new_output_data = false;
// dev->last_output = now;
// }
// else if (res == -1)
// {
// skateboard_log.error("apply_pad_data: send_output_report failed! error=%s", hid_error(dev->hidDevice));
// }
//}
}
void skateboard_pad_handler::SetPadData(const std::string& padId, u8 player_id, u8 /*large_motor*/, u8 /*small_motor*/, s32 /*r*/, s32 /*g*/, s32 /*b*/, bool /*player_led*/, bool /*battery_led*/, u32 /*battery_led_brightness*/)
{
std::shared_ptr<skateboard_device> device = get_hid_device(padId);
if (device == nullptr || device->hidDevice == nullptr)
return;
device->player_id = player_id;
device->config = get_config(padId);
ensure(device->config);
// Disabled until needed
//if (send_output_report(device.get()) == -1)
//{
// skateboard_log.error("SetPadData: send_output_report failed! Reason: %s", hid_error(device->hidDevice));
//}
}
| 14,056
|
C++
|
.cpp
| 326
| 40.742331
| 253
| 0.690551
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,006
|
sdl_pad_handler.cpp
|
RPCS3_rpcs3/rpcs3/Input/sdl_pad_handler.cpp
|
#ifdef HAVE_SDL2
#include "stdafx.h"
#include "sdl_pad_handler.h"
#include "Emu/system_utils.hpp"
#include "Emu/system_config.h"
#include <mutex>
LOG_CHANNEL(sdl_log, "SDL");
struct sdl_instance
{
public:
sdl_instance() = default;
~sdl_instance()
{
// Only quit SDL once on exit. SDL uses a global state internally...
if (m_initialized)
{
sdl_log.notice("Quitting SDL ...");
SDL_Quit();
}
}
static sdl_instance& get_instance()
{
static sdl_instance instance {};
return instance;
}
bool initialize()
{
// Only init SDL once. SDL uses a global state internally...
if (m_initialized)
{
return true;
}
sdl_log.notice("Initializing SDL ...");
// Set non-dynamic hints before SDL_Init
if (!SDL_SetHint(SDL_HINT_JOYSTICK_THREAD, "1"))
{
sdl_log.error("Could not set SDL_HINT_JOYSTICK_THREAD: %s", SDL_GetError());
}
if (SDL_Init(SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC | SDL_INIT_GAMECONTROLLER) < 0)
{
sdl_log.error("Could not initialize! SDL Error: %s", SDL_GetError());
return false;
}
SDL_LogSetAllPriority(SDL_LOG_PRIORITY_VERBOSE);
SDL_LogSetOutputFunction([](void*, int category, SDL_LogPriority priority, const char* message)
{
std::string category_name;
switch (category)
{
case SDL_LOG_CATEGORY_APPLICATION:
category_name = "app";
break;
case SDL_LOG_CATEGORY_ERROR:
category_name = "error";
break;
case SDL_LOG_CATEGORY_ASSERT:
category_name = "assert";
break;
case SDL_LOG_CATEGORY_SYSTEM:
category_name = "system";
break;
case SDL_LOG_CATEGORY_AUDIO:
category_name = "audio";
break;
case SDL_LOG_CATEGORY_VIDEO:
category_name = "video";
break;
case SDL_LOG_CATEGORY_RENDER:
category_name = "render";
break;
case SDL_LOG_CATEGORY_INPUT:
category_name = "input";
break;
case SDL_LOG_CATEGORY_TEST:
category_name = "test";
break;
default:
category_name = fmt::format("unknown(%d)", category);
break;
}
switch (priority)
{
case SDL_LOG_PRIORITY_VERBOSE:
case SDL_LOG_PRIORITY_DEBUG:
sdl_log.trace("%s: %s", category_name, message);
break;
case SDL_LOG_PRIORITY_INFO:
sdl_log.notice("%s: %s", category_name, message);
break;
case SDL_LOG_PRIORITY_WARN:
sdl_log.warning("%s: %s", category_name, message);
break;
case SDL_LOG_PRIORITY_ERROR:
sdl_log.error("%s: %s", category_name, message);
break;
case SDL_LOG_PRIORITY_CRITICAL:
sdl_log.error("%s: %s", category_name, message);
break;
default:
break;
}
}, nullptr);
m_initialized = true;
return true;
}
private:
bool m_initialized = false;
};
sdl_pad_handler::sdl_pad_handler() : PadHandlerBase(pad_handler::sdl)
{
button_list =
{
{ SDLKeyCodes::None, "" },
{ SDLKeyCodes::A, "A" },
{ SDLKeyCodes::B, "B" },
{ SDLKeyCodes::X, "X" },
{ SDLKeyCodes::Y, "Y" },
{ SDLKeyCodes::Left, "Left" },
{ SDLKeyCodes::Right, "Right" },
{ SDLKeyCodes::Up, "Up" },
{ SDLKeyCodes::Down, "Down" },
{ SDLKeyCodes::LB, "LB" },
{ SDLKeyCodes::RB, "RB" },
{ SDLKeyCodes::Back, "Back" },
{ SDLKeyCodes::Start, "Start" },
{ SDLKeyCodes::LS, "LS" },
{ SDLKeyCodes::RS, "RS" },
{ SDLKeyCodes::Guide, "Guide" },
{ SDLKeyCodes::Misc1, "Misc 1" },
{ SDLKeyCodes::Paddle1, "Paddle 1" },
{ SDLKeyCodes::Paddle2, "Paddle 2" },
{ SDLKeyCodes::Paddle3, "Paddle 3" },
{ SDLKeyCodes::Paddle4, "Paddle 4" },
{ SDLKeyCodes::Touchpad, "Touchpad" },
{ SDLKeyCodes::Touch_L, "Touch Left" },
{ SDLKeyCodes::Touch_R, "Touch Right" },
{ SDLKeyCodes::Touch_U, "Touch Up" },
{ SDLKeyCodes::Touch_D, "Touch Down" },
{ SDLKeyCodes::LT, "LT" },
{ SDLKeyCodes::RT, "RT" },
{ SDLKeyCodes::LSXNeg, "LS X-" },
{ SDLKeyCodes::LSXPos, "LS X+" },
{ SDLKeyCodes::LSYPos, "LS Y+" },
{ SDLKeyCodes::LSYNeg, "LS Y-" },
{ SDLKeyCodes::RSXNeg, "RS X-" },
{ SDLKeyCodes::RSXPos, "RS X+" },
{ SDLKeyCodes::RSYPos, "RS Y+" },
{ SDLKeyCodes::RSYNeg, "RS Y-" },
};
init_configs();
// Define border values
thumb_max = SDL_JOYSTICK_AXIS_MAX;
trigger_min = 0;
trigger_max = SDL_JOYSTICK_AXIS_MAX;
// set capabilities
b_has_config = true;
b_has_deadzones = true;
b_has_rumble = true;
b_has_motion = true;
b_has_led = true;
b_has_rgb = true;
b_has_battery = true;
b_has_battery_led = true;
m_trigger_threshold = trigger_max / 2;
m_thumb_threshold = thumb_max / 2;
}
sdl_pad_handler::~sdl_pad_handler()
{
if (!m_is_init)
return;
for (auto& controller : m_controllers)
{
if (controller.second && controller.second->sdl.game_controller)
{
set_rumble(controller.second.get(), 0, 0);
SDL_GameControllerClose(controller.second->sdl.game_controller);
controller.second->sdl.game_controller = nullptr;
}
}
}
void sdl_pad_handler::init_config(cfg_pad* cfg)
{
if (!cfg) return;
// Set default button mapping
cfg->ls_left.def = ::at32(button_list, SDLKeyCodes::LSXNeg);
cfg->ls_down.def = ::at32(button_list, SDLKeyCodes::LSYNeg);
cfg->ls_right.def = ::at32(button_list, SDLKeyCodes::LSXPos);
cfg->ls_up.def = ::at32(button_list, SDLKeyCodes::LSYPos);
cfg->rs_left.def = ::at32(button_list, SDLKeyCodes::RSXNeg);
cfg->rs_down.def = ::at32(button_list, SDLKeyCodes::RSYNeg);
cfg->rs_right.def = ::at32(button_list, SDLKeyCodes::RSXPos);
cfg->rs_up.def = ::at32(button_list, SDLKeyCodes::RSYPos);
cfg->start.def = ::at32(button_list, SDLKeyCodes::Start);
cfg->select.def = ::at32(button_list, SDLKeyCodes::Back);
cfg->ps.def = ::at32(button_list, SDLKeyCodes::Guide);
cfg->square.def = ::at32(button_list, SDLKeyCodes::X);
cfg->cross.def = ::at32(button_list, SDLKeyCodes::A);
cfg->circle.def = ::at32(button_list, SDLKeyCodes::B);
cfg->triangle.def = ::at32(button_list, SDLKeyCodes::Y);
cfg->left.def = ::at32(button_list, SDLKeyCodes::Left);
cfg->down.def = ::at32(button_list, SDLKeyCodes::Down);
cfg->right.def = ::at32(button_list, SDLKeyCodes::Right);
cfg->up.def = ::at32(button_list, SDLKeyCodes::Up);
cfg->r1.def = ::at32(button_list, SDLKeyCodes::RB);
cfg->r2.def = ::at32(button_list, SDLKeyCodes::RT);
cfg->r3.def = ::at32(button_list, SDLKeyCodes::RS);
cfg->l1.def = ::at32(button_list, SDLKeyCodes::LB);
cfg->l2.def = ::at32(button_list, SDLKeyCodes::LT);
cfg->l3.def = ::at32(button_list, SDLKeyCodes::LS);
cfg->pressure_intensity_button.def = ::at32(button_list, SDLKeyCodes::None);
cfg->analog_limiter_button.def = ::at32(button_list, SDLKeyCodes::None);
// Set default misc variables
cfg->lstick_anti_deadzone.def = static_cast<u32>(0.13 * thumb_max); // 13%
cfg->rstick_anti_deadzone.def = static_cast<u32>(0.13 * thumb_max); // 13%
cfg->lstickdeadzone.def = 8000; // between 0 and SDL_JOYSTICK_AXIS_MAX
cfg->rstickdeadzone.def = 8000; // between 0 and SDL_JOYSTICK_AXIS_MAX
cfg->ltriggerthreshold.def = 0; // between 0 and SDL_JOYSTICK_AXIS_MAX
cfg->rtriggerthreshold.def = 0; // between 0 and SDL_JOYSTICK_AXIS_MAX
cfg->lpadsquircling.def = 8000;
cfg->rpadsquircling.def = 8000;
// Set default color value
cfg->colorR.def = 0;
cfg->colorG.def = 0;
cfg->colorB.def = 20;
// Set default LED options
cfg->led_battery_indicator.def = false;
cfg->led_battery_indicator_brightness.def = 10;
cfg->led_low_battery_blink.def = true;
// apply defaults
cfg->from_default();
}
bool sdl_pad_handler::Init()
{
if (m_is_init)
return true;
if (!sdl_instance::get_instance().initialize())
return false;
if (g_cfg.io.load_sdl_mappings)
{
const std::string db_path = rpcs3::utils::get_input_config_root() + "gamecontrollerdb.txt";
sdl_log.notice("Adding mappings from file '%s'", db_path);
if (fs::is_file(db_path))
{
if (SDL_GameControllerAddMappingsFromFile(db_path.c_str()) < 0)
{
sdl_log.error("Could not add mappings from file '%s'! SDL Error: %s", db_path, SDL_GetError());
}
}
else
{
sdl_log.warning("Could not add mappings from file '%s'! File does not exist!", db_path);
}
}
SDL_version version{};
SDL_GetVersion(&version);
if (const char* revision = SDL_GetRevision(); revision && strlen(revision) > 0)
{
sdl_log.notice("Using version: %d.%d.%d (revision='%s')", version.major, version.minor, version.patch, revision);
}
else
{
sdl_log.notice("Using version: %d.%d.%d", version.major, version.minor, version.patch);
}
m_is_init = true;
enumerate_devices();
return true;
}
void sdl_pad_handler::process()
{
if (!m_is_init)
return;
SDL_PumpEvents();
PadHandlerBase::process();
}
SDLDevice::sdl_info sdl_pad_handler::get_sdl_info(int i)
{
SDLDevice::sdl_info info{};
info.game_controller = SDL_GameControllerOpen(i);
if (!info.game_controller)
{
sdl_log.error("Could not open device %d! SDL Error: %s", i, SDL_GetError());
return {};
}
if (const char* name = SDL_GameControllerName(info.game_controller))
{
info.name = name;
}
if (const char* path = SDL_GameControllerPath(info.game_controller))
{
info.path = path;
}
if (const char* serial = SDL_GameControllerGetSerial(info.game_controller))
{
info.serial = serial;
}
info.joystick = SDL_GameControllerGetJoystick(info.game_controller);
info.type = SDL_GameControllerGetType(info.game_controller);
info.vid = SDL_GameControllerGetVendor(info.game_controller);
info.pid = SDL_GameControllerGetProduct(info.game_controller);
info.product_version= SDL_GameControllerGetProductVersion(info.game_controller);
info.firmware_version = SDL_GameControllerGetFirmwareVersion(info.game_controller);
info.has_led = SDL_GameControllerHasLED(info.game_controller);
info.has_rumble = SDL_GameControllerHasRumble(info.game_controller);
info.has_rumble_triggers = SDL_GameControllerHasRumbleTriggers(info.game_controller);
info.has_accel = SDL_GameControllerHasSensor(info.game_controller, SDL_SENSOR_ACCEL);
info.has_gyro = SDL_GameControllerHasSensor(info.game_controller, SDL_SENSOR_GYRO);
if (const int num_touchpads = SDL_GameControllerGetNumTouchpads(info.game_controller); num_touchpads > 0)
{
info.touchpads.resize(num_touchpads);
for (int i = 0; i < num_touchpads; i++)
{
SDLDevice::touchpad& touchpad = ::at32(info.touchpads, i);
touchpad.index = i;
if (const int num_fingers = SDL_GameControllerGetNumTouchpadFingers(info.game_controller, touchpad.index); num_fingers > 0)
{
touchpad.fingers.resize(num_fingers);
for (int f = 0; f < num_fingers; f++)
{
::at32(touchpad.fingers, f).index = f;
}
}
}
}
sdl_log.notice("Found game controller %d: type=%d, name='%s', path='%s', serial='%s', vid=0x%x, pid=0x%x, product_version=0x%x, firmware_version=0x%x, has_led=%d, has_rumble=%d, has_rumble_triggers=%d, has_accel=%d, has_gyro=%d",
i, static_cast<int>(info.type), info.name, info.path, info.serial, info.vid, info.pid, info.product_version, info.firmware_version, info.has_led, info.has_rumble, info.has_rumble_triggers, info.has_accel, info.has_gyro);
if (info.has_accel)
{
if (SDL_GameControllerSetSensorEnabled(info.game_controller, SDL_SENSOR_ACCEL, SDL_TRUE) != 0 ||
!SDL_GameControllerIsSensorEnabled(info.game_controller, SDL_SENSOR_ACCEL))
{
sdl_log.error("Could not activate acceleration sensor of device %d! SDL Error: %s", i, SDL_GetError());
info.has_accel = false;
}
else
{
info.data_rate_accel = SDL_GameControllerGetSensorDataRate(info.game_controller, SDL_SENSOR_ACCEL);
sdl_log.notice("Acceleration sensor data rate of device %d = %.2f/s", i, info.data_rate_accel);
}
}
if (info.has_gyro)
{
if (SDL_GameControllerSetSensorEnabled(info.game_controller, SDL_SENSOR_GYRO, SDL_TRUE) != 0 ||
!SDL_GameControllerIsSensorEnabled(info.game_controller, SDL_SENSOR_GYRO))
{
sdl_log.error("Could not activate gyro sensor of device %d! SDL Error: %s", i, SDL_GetError());
info.has_gyro = false;
}
else
{
info.data_rate_gyro = SDL_GameControllerGetSensorDataRate(info.game_controller, SDL_SENSOR_GYRO);
sdl_log.notice("Gyro sensor data rate of device %d = %.2f/s", i, info.data_rate_accel);
}
}
for (int i = 0; i < SDL_CONTROLLER_BUTTON_MAX; i++)
{
const SDL_GameControllerButton button_id = static_cast<SDL_GameControllerButton>(i);
if (SDL_GameControllerHasButton(info.game_controller, button_id))
{
info.button_ids.insert(button_id);
}
}
for (int i = 0; i < SDL_CONTROLLER_AXIS_MAX; i++)
{
const SDL_GameControllerAxis axis_id = static_cast<SDL_GameControllerAxis>(i);
if (SDL_GameControllerHasAxis(info.game_controller, axis_id))
{
info.axis_ids.insert(axis_id);
}
}
return info;
}
std::vector<pad_list_entry> sdl_pad_handler::list_devices()
{
std::vector<pad_list_entry> pads_list;
if (!Init())
return pads_list;
for (const auto& controller : m_controllers)
{
pads_list.emplace_back(controller.first, false);
}
return pads_list;
}
void sdl_pad_handler::enumerate_devices()
{
if (!m_is_init)
return;
for (int i = 0; i < SDL_NumJoysticks(); i++)
{
if (!SDL_IsGameController(i))
{
sdl_log.error("Joystick %d is not game controller interface compatible! SDL Error: %s", i, SDL_GetError());
continue;
}
if (SDLDevice::sdl_info info = get_sdl_info(i); info.game_controller)
{
std::shared_ptr<SDLDevice> dev = std::make_shared<SDLDevice>();
dev->sdl = std::move(info);
// Count existing real devices with the same name
u32 device_count = 1; // This device also counts
for (const auto& controller : m_controllers)
{
if (controller.second && !controller.second->sdl.is_virtual_device && controller.second->sdl.name == dev->sdl.name)
{
device_count++;
}
}
// Add real device
const std::string device_name = fmt::format("%s %d", dev->sdl.name, device_count);
m_controllers[device_name] = std::move(dev);
}
}
}
std::shared_ptr<SDLDevice> sdl_pad_handler::get_device_by_game_controller(SDL_GameController* game_controller) const
{
if (!game_controller)
return nullptr;
const char* name = SDL_GameControllerName(game_controller);
const char* path = SDL_GameControllerPath(game_controller);
const char* serial = SDL_GameControllerGetSerial(game_controller);
// Try to find a real device
for (const auto& controller : m_controllers)
{
if (!controller.second || controller.second->sdl.is_virtual_device)
continue;
const auto is_same = [](const char* c, std::string_view s) -> bool
{
return c ? c == s : s.empty();
};
if (is_same(name, controller.second->sdl.name) &&
is_same(path, controller.second->sdl.path) &&
is_same(serial, controller.second->sdl.serial))
{
return controller.second;
}
}
// Try to find a virtual device if we can't find a real device
for (const auto& controller : m_controllers)
{
if (!controller.second || !controller.second->sdl.is_virtual_device)
continue;
if (name && controller.second->sdl.name.starts_with(name))
{
return controller.second;
}
}
return nullptr;
}
std::shared_ptr<PadDevice> sdl_pad_handler::get_device(const std::string& device)
{
if (!Init() || device.empty())
return nullptr;
if (auto it = m_controllers.find(device); it != m_controllers.end())
{
return it->second;
}
// Add a virtual controller until it is actually attached
std::shared_ptr<SDLDevice> dev = std::make_unique<SDLDevice>();
dev->sdl.name = device;
dev->sdl.is_virtual_device = true;
m_controllers.emplace(device, dev);
sdl_log.warning("Adding empty device: %s", device);
return dev;
}
PadHandlerBase::connection sdl_pad_handler::update_connection(const std::shared_ptr<PadDevice>& device)
{
if (SDLDevice* dev = static_cast<SDLDevice*>(device.get()))
{
if (dev->sdl.game_controller)
{
if (SDL_GameControllerGetAttached(dev->sdl.game_controller))
{
if (SDL_HasEvent(SDL_EventType::SDL_CONTROLLERBUTTONDOWN) ||
SDL_HasEvent(SDL_EventType::SDL_CONTROLLERBUTTONUP) ||
SDL_HasEvent(SDL_EventType::SDL_CONTROLLERAXISMOTION) ||
SDL_HasEvent(SDL_EventType::SDL_CONTROLLERSENSORUPDATE) ||
SDL_HasEvent(SDL_EventType::SDL_CONTROLLERTOUCHPADUP) ||
SDL_HasEvent(SDL_EventType::SDL_CONTROLLERTOUCHPADDOWN) ||
SDL_HasEvent(SDL_EventType::SDL_JOYBATTERYUPDATED))
{
return connection::connected;
}
return connection::no_data;
}
SDL_GameControllerClose(dev->sdl.game_controller);
dev->sdl.game_controller = nullptr;
dev->sdl.joystick = nullptr;
}
// Try to reconnect
for (int i = 0; i < SDL_NumJoysticks(); i++)
{
if (!SDL_IsGameController(i))
{
continue;
}
// Get game controller
SDL_GameController* game_controller = SDL_GameControllerOpen(i);
if (!game_controller)
{
continue;
}
// Find out if we already know this controller
std::shared_ptr<SDLDevice> sdl_device = get_device_by_game_controller(game_controller);
if (!sdl_device)
{
// Close the game controller if we don't know it.
SDL_GameControllerClose(game_controller);
continue;
}
// Re-attach the controller if the device matches the current one
if (sdl_device.get() == dev)
{
if (SDLDevice::sdl_info info = get_sdl_info(i); info.game_controller)
{
dev->sdl = std::move(info);
}
break;
}
}
}
return connection::disconnected;
}
void sdl_pad_handler::SetPadData(const std::string& padId, u8 player_id, u8 large_motor, u8 small_motor, s32 r, s32 g, s32 b, bool /*player_led*/, bool battery_led, u32 battery_led_brightness)
{
std::shared_ptr<PadDevice> device = get_device(padId);
SDLDevice* dev = static_cast<SDLDevice*>(device.get());
if (!dev)
return;
dev->player_id = player_id;
dev->config = get_config(padId);
ensure(dev->config);
set_rumble(dev, large_motor, small_motor);
if (battery_led)
{
const u32 combined_color = get_battery_color(dev->sdl.power_level, battery_led_brightness);
dev->config->colorR.set(combined_color >> 8);
dev->config->colorG.set(combined_color & 0xff);
dev->config->colorB.set(0);
}
else if (r >= 0 && g >= 0 && b >= 0 && r <= 255 && g <= 255 && b <= 255)
{
dev->config->colorR.set(r);
dev->config->colorG.set(g);
dev->config->colorB.set(b);
}
if (dev->sdl.has_led && SDL_GameControllerSetLED(dev->sdl.game_controller, r, g, b) != 0)
{
sdl_log.error("Could not set LED of device %d! SDL Error: %s", player_id, SDL_GetError());
}
}
u32 sdl_pad_handler::get_battery_color(SDL_JoystickPowerLevel power_level, u32 brightness) const
{
u32 combined_color{};
switch (power_level)
{
default: combined_color = 0xFF00; break;
case SDL_JOYSTICK_POWER_UNKNOWN: combined_color = 0xFF00; break;
case SDL_JOYSTICK_POWER_EMPTY: combined_color = 0xFF33; break;
case SDL_JOYSTICK_POWER_LOW: combined_color = 0xFFCC; break;
case SDL_JOYSTICK_POWER_MEDIUM: combined_color = 0x66FF; break;
case SDL_JOYSTICK_POWER_FULL: combined_color = 0x00FF; break;
case SDL_JOYSTICK_POWER_WIRED: combined_color = 0x00FF; break;
case SDL_JOYSTICK_POWER_MAX: combined_color = 0x00FF; break;
}
const u32 red = (combined_color >> 8) * brightness / 100;
const u32 green = (combined_color & 0xff) * brightness / 100;
return ((red << 8) | green);
}
u32 sdl_pad_handler::get_battery_level(const std::string& padId)
{
std::shared_ptr<PadDevice> device = get_device(padId);
SDLDevice* dev = static_cast<SDLDevice*>(device.get());
if (!dev)
return 0;
if (dev->sdl.joystick)
{
dev->sdl.power_level = SDL_JoystickCurrentPowerLevel(dev->sdl.joystick);
switch (dev->sdl.power_level)
{
case SDL_JOYSTICK_POWER_UNKNOWN: return 0;
case SDL_JOYSTICK_POWER_EMPTY: return 5;
case SDL_JOYSTICK_POWER_LOW: return 20;
case SDL_JOYSTICK_POWER_MEDIUM: return 70;
case SDL_JOYSTICK_POWER_FULL: return 100;
case SDL_JOYSTICK_POWER_WIRED: return 100;
case SDL_JOYSTICK_POWER_MAX: return 100;
default: return 0;
}
}
return 0;
}
void sdl_pad_handler::get_extended_info(const pad_ensemble& binding)
{
const auto& pad = binding.pad;
SDLDevice* dev = static_cast<SDLDevice*>(binding.device.get());
if (!dev || !dev->sdl.game_controller || !pad)
return;
if (dev->sdl.joystick)
{
dev->sdl.power_level = SDL_JoystickCurrentPowerLevel(dev->sdl.joystick);
pad->m_cable_state = dev->sdl.power_level == SDL_JOYSTICK_POWER_WIRED;
switch (dev->sdl.power_level)
{
case SDL_JOYSTICK_POWER_UNKNOWN: pad->m_battery_level = 0; break;
case SDL_JOYSTICK_POWER_EMPTY: pad->m_battery_level = 5; break;
case SDL_JOYSTICK_POWER_LOW: pad->m_battery_level = 20; break;
case SDL_JOYSTICK_POWER_MEDIUM: pad->m_battery_level = 70; break;
case SDL_JOYSTICK_POWER_FULL: pad->m_battery_level = 100; break;
case SDL_JOYSTICK_POWER_WIRED: pad->m_battery_level = 100; break;
case SDL_JOYSTICK_POWER_MAX: pad->m_battery_level = 100; break;
default: pad->m_battery_level = 0; break;
}
}
else
{
pad->m_cable_state = 1;
pad->m_battery_level = 100;
}
if (dev->sdl.has_accel)
{
if (SDL_GameControllerGetSensorData(dev->sdl.game_controller, SDL_SENSOR_ACCEL, dev->values_accel.data(), 3) != 0)
{
sdl_log.error("Could not get acceleration sensor data of device %d! SDL Error: %s", dev->player_id, SDL_GetError());
}
else
{
const float& accel_x = dev->values_accel[0]; // Angular speed around the x axis (pitch)
const float& accel_y = dev->values_accel[1]; // Angular speed around the y axis (yaw)
const float& accel_z = dev->values_accel[2]; // Angular speed around the z axis (roll
// Convert to ds3. The ds3 resolution is 113/G.
pad->m_sensors[0].m_value = Clamp0To1023((accel_x / SDL_STANDARD_GRAVITY) * -1 * 113 + 512);
pad->m_sensors[1].m_value = Clamp0To1023((accel_y / SDL_STANDARD_GRAVITY) * -1 * 113 + 512);
pad->m_sensors[2].m_value = Clamp0To1023((accel_z / SDL_STANDARD_GRAVITY) * -1 * 113 + 512);
}
}
if (dev->sdl.has_gyro)
{
if (SDL_GameControllerGetSensorData(dev->sdl.game_controller, SDL_SENSOR_GYRO, dev->values_gyro.data(), 3) != 0)
{
sdl_log.error("Could not get gyro sensor data of device %d! SDL Error: %s", dev->player_id, SDL_GetError());
}
else
{
//const float& gyro_x = dev->values_gyro[0]; // Angular speed around the x axis (pitch)
const float& gyro_y = dev->values_gyro[1]; // Angular speed around the y axis (yaw)
//const float& gyro_z = dev->values_gyro[2]; // Angular speed around the z axis (roll)
// Convert to ds3. The ds3 resolution is 123/90°/sec. The SDL gyro is measured in rad/sec.
static constexpr f32 PI = 3.14159265f;
const float degree = (gyro_y * 180.0f / PI);
pad->m_sensors[3].m_value = Clamp0To1023(degree * (123.f / 90.f) + 512);
}
}
}
void sdl_pad_handler::get_motion_sensors(const std::string& pad_id, const motion_callback& callback, const motion_fail_callback& fail_callback, motion_preview_values preview_values, const std::array<AnalogSensor, 4>& sensors)
{
if (!m_is_init)
return;
SDL_PumpEvents();
PadHandlerBase::get_motion_sensors(pad_id, callback, fail_callback, preview_values, sensors);
}
PadHandlerBase::connection sdl_pad_handler::get_next_button_press(const std::string& padId, const pad_callback& callback, const pad_fail_callback& fail_callback, gui_call_type call_type, const std::vector<std::string>& buttons)
{
if (!m_is_init)
return connection::disconnected;
SDL_PumpEvents();
return PadHandlerBase::get_next_button_press(padId, callback, fail_callback, call_type, buttons);
}
void sdl_pad_handler::apply_pad_data(const pad_ensemble& binding)
{
const auto& pad = binding.pad;
SDLDevice* dev = static_cast<SDLDevice*>(binding.device.get());
if (!dev || !pad)
return;
cfg_pad* cfg = dev->config;
// The left motor is the low-frequency rumble motor. The right motor is the high-frequency rumble motor.
// The two motors are not the same, and they create different vibration effects. Values range between 0 to 65535.
const usz idx_l = cfg->switch_vibration_motors ? 1 : 0;
const usz idx_s = cfg->switch_vibration_motors ? 0 : 1;
if (dev->sdl.has_rumble || dev->sdl.has_rumble_triggers)
{
const u8 speed_large = cfg->enable_vibration_motor_large ? pad->m_vibrateMotors[idx_l].m_value : 0;
const u8 speed_small = cfg->enable_vibration_motor_small ? pad->m_vibrateMotors[idx_s].m_value : 0;
dev->new_output_data |= dev->large_motor != speed_large || dev->small_motor != speed_small;
dev->large_motor = speed_large;
dev->small_motor = speed_small;
const auto now = steady_clock::now();
const auto elapsed = now - dev->last_output;
// XBox One Controller can't handle faster vibration updates than ~10ms. Elite is even worse. So I'll use 20ms to be on the safe side. No lag was noticable.
if ((dev->new_output_data && elapsed > 20ms) || elapsed > min_output_interval)
{
set_rumble(dev, speed_large, speed_small);
dev->new_output_data = false;
dev->last_output = now;
}
}
if (dev->sdl.has_led)
{
// Use LEDs to indicate battery level
if (cfg->led_battery_indicator)
{
// This makes sure that the LED color doesn't update every 1ms. DS4 only reports battery level in 10% increments
if (dev->sdl.last_power_level != dev->sdl.power_level)
{
const u32 combined_color = get_battery_color(dev->sdl.power_level, cfg->led_battery_indicator_brightness);
cfg->colorR.set(combined_color >> 8);
cfg->colorG.set(combined_color & 0xff);
cfg->colorB.set(0);
dev->sdl.last_power_level = dev->sdl.power_level;
dev->led_needs_update = true;
}
}
// Blink LED when battery is low
if (cfg->led_low_battery_blink)
{
const bool low_battery = pad->m_battery_level <= 20;
if (dev->led_is_blinking && !low_battery)
{
dev->led_is_blinking = false;
dev->led_needs_update = true;
}
else if (!dev->led_is_blinking && low_battery)
{
dev->led_is_blinking = true;
dev->led_needs_update = true;
}
if (dev->led_is_blinking)
{
if (const steady_clock::time_point now = steady_clock::now(); (now - dev->led_timestamp) > 500ms)
{
dev->led_is_on = !dev->led_is_on;
dev->led_timestamp = now;
dev->led_needs_update = true;
}
}
}
else if (!dev->led_is_on)
{
dev->led_is_on = true;
dev->led_needs_update = true;
}
if (dev->led_needs_update)
{
const u8 r = dev->led_is_on ? cfg->colorR : 0;
const u8 g = dev->led_is_on ? cfg->colorG : 0;
const u8 b = dev->led_is_on ? cfg->colorB : 0;
if (SDL_GameControllerSetLED(dev->sdl.game_controller, r, g, b) != 0)
{
sdl_log.error("Could not set LED of device %d! SDL Error: %s", dev->player_id, SDL_GetError());
}
dev->led_needs_update = false;
}
}
}
void sdl_pad_handler::set_rumble(SDLDevice* dev, u8 speed_large, u8 speed_small)
{
if (!dev || !dev->sdl.game_controller) return;
constexpr u32 rumble_duration_ms = static_cast<u32>((min_output_interval + 100ms).count()); // Some number higher than the min_output_interval.
if (dev->sdl.has_rumble)
{
if (SDL_GameControllerRumble(dev->sdl.game_controller, speed_large * 257, speed_small * 257, rumble_duration_ms) != 0)
{
sdl_log.error("Unable to play game controller rumble of player %d! SDL Error: %s", dev->player_id, SDL_GetError());
}
}
// NOTE: Disabled for now. The triggers do not seem to be implemented correctly in SDL in the current version.
// The rumble is way too intensive and has a high frequency. It is very displeasing at the moment.
// In the future we could use additional trigger rumble to enhance the existing rumble.
if (false && dev->sdl.has_rumble_triggers)
{
// Only the large motor shall control both triggers. It wouldn't make sense to differentiate here.
if (SDL_GameControllerRumbleTriggers(dev->sdl.game_controller, speed_large * 257, speed_large * 257, rumble_duration_ms) != 0)
{
sdl_log.error("Unable to play game controller trigger rumble of player %d! SDL Error: %s", dev->player_id, SDL_GetError());
}
}
}
bool sdl_pad_handler::get_is_left_trigger(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
return keyCode == SDLKeyCodes::LT;
}
bool sdl_pad_handler::get_is_right_trigger(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
return keyCode == SDLKeyCodes::RT;
}
bool sdl_pad_handler::get_is_left_stick(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
switch (keyCode)
{
case SDLKeyCodes::LSXNeg:
case SDLKeyCodes::LSXPos:
case SDLKeyCodes::LSYPos:
case SDLKeyCodes::LSYNeg:
return true;
default:
return false;
}
}
bool sdl_pad_handler::get_is_right_stick(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
switch (keyCode)
{
case SDLKeyCodes::RSXNeg:
case SDLKeyCodes::RSXPos:
case SDLKeyCodes::RSYPos:
case SDLKeyCodes::RSYNeg:
return true;
default:
return false;
}
}
bool sdl_pad_handler::get_is_touch_pad_motion(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
switch (keyCode)
{
case SDLKeyCodes::Touch_L:
case SDLKeyCodes::Touch_R:
case SDLKeyCodes::Touch_U:
case SDLKeyCodes::Touch_D:
return true;
default:
return false;
}
}
std::unordered_map<u64, u16> sdl_pad_handler::get_button_values(const std::shared_ptr<PadDevice>& device)
{
std::unordered_map<u64, u16> values;
SDLDevice* dev = static_cast<SDLDevice*>(device.get());
if (!dev || !dev->sdl.game_controller)
return values;
for (SDL_GameControllerButton button_id : dev->sdl.button_ids)
{
const u8 value = SDL_GameControllerGetButton(dev->sdl.game_controller, button_id);
const SDLKeyCodes key_code = get_button_code(button_id);
// TODO: SDL does not support DS3 button intensity in the current version
values[key_code] = value ? 255 : 0;
}
for (SDL_GameControllerAxis axis_id : dev->sdl.axis_ids)
{
const s16 value = SDL_GameControllerGetAxis(dev->sdl.game_controller, axis_id);
switch (axis_id)
{
case SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_TRIGGERLEFT:
values[SDLKeyCodes::LT] = std::max<u16>(0, value);
break;
case SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_TRIGGERRIGHT:
values[SDLKeyCodes::RT] = std::max<u16>(0, value);
break;
case SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_LEFTX:
values[SDLKeyCodes::LSXNeg] = value < 0 ? std::abs(value) - 1 : 0;
values[SDLKeyCodes::LSXPos] = value > 0 ? value : 0;
break;
case SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_LEFTY:
values[SDLKeyCodes::LSYNeg] = value > 0 ? value : 0;
values[SDLKeyCodes::LSYPos] = value < 0 ? std::abs(value) - 1 : 0;
break;
case SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_RIGHTX:
values[SDLKeyCodes::RSXNeg] = value < 0 ? std::abs(value) - 1 : 0;
values[SDLKeyCodes::RSXPos] = value > 0 ? value : 0;
break;
case SDL_GameControllerAxis::SDL_CONTROLLER_AXIS_RIGHTY:
values[SDLKeyCodes::RSYNeg] = value > 0 ? value : 0;
values[SDLKeyCodes::RSYPos] = value < 0 ? std::abs(value) - 1 : 0;
break;
default:
break;
}
}
for (const SDLDevice::touchpad& touchpad : dev->sdl.touchpads)
{
for (const SDLDevice::touch_point& finger : touchpad.fingers)
{
u8 state = 0; // 1 means the finger is touching the pad
f32 x = 0.0f; // 0 = left, 1 = right
f32 y = 0.0f; // 0 = top, 1 = bottom
f32 pressure = 0.0f; // In the current SDL version the pressure is always 1 if the state is 1
if (SDL_GameControllerGetTouchpadFinger(dev->sdl.game_controller, touchpad.index, finger.index, &state, &x, &y, &pressure) != 0)
{
sdl_log.error("Could not get touchpad %d finger %d data of device %d! SDL Error: %s", touchpad.index, finger.index, dev->player_id, SDL_GetError());
}
else
{
sdl_log.trace("touchpad=%d, finger=%d, state=%d, x=%f, y=%f, pressure=%f", touchpad.index, finger.index, state, x, y, pressure);
if (state == 0)
{
continue;
}
const f32 x_scaled = ScaledInput(x, 0.0f, 1.0f, 0.0f, 255.0f);
const f32 y_scaled = ScaledInput(y, 0.0f, 1.0f, 0.0f, 255.0f);
values[SDLKeyCodes::Touch_L] = Clamp0To255((127.5f - x_scaled) * 2.0f);
values[SDLKeyCodes::Touch_R] = Clamp0To255((x_scaled - 127.5f) * 2.0f);
values[SDLKeyCodes::Touch_U] = Clamp0To255((127.5f - y_scaled) * 2.0f);
values[SDLKeyCodes::Touch_D] = Clamp0To255((y_scaled - 127.5f) * 2.0f);
}
}
}
return values;
}
pad_preview_values sdl_pad_handler::get_preview_values(const std::unordered_map<u64, u16>& data)
{
return {
::at32(data, LT),
::at32(data, RT),
::at32(data, LSXPos) - ::at32(data, LSXNeg),
::at32(data, LSYPos) - ::at32(data, LSYNeg),
::at32(data, RSXPos) - ::at32(data, RSXNeg),
::at32(data, RSYPos) - ::at32(data, RSYNeg)
};
}
std::string sdl_pad_handler::button_to_string(SDL_GameControllerButton button)
{
if (const char* name = SDL_GameControllerGetStringForButton(button))
{
return name;
}
return {};
}
std::string sdl_pad_handler::axis_to_string(SDL_GameControllerAxis axis)
{
if (const char* name = SDL_GameControllerGetStringForAxis(axis))
{
return name;
}
return {};
}
sdl_pad_handler::SDLKeyCodes sdl_pad_handler::get_button_code(SDL_GameControllerButton button)
{
switch (button)
{
default:
case SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_INVALID: return SDLKeyCodes::None;
case SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_A: return SDLKeyCodes::A;
case SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_B: return SDLKeyCodes::B;
case SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_X: return SDLKeyCodes::X;
case SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_Y: return SDLKeyCodes::Y;
case SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_DPAD_LEFT: return SDLKeyCodes::Left;
case SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_DPAD_RIGHT: return SDLKeyCodes::Right;
case SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_DPAD_UP: return SDLKeyCodes::Up;
case SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_DPAD_DOWN: return SDLKeyCodes::Down;
case SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_LEFTSHOULDER: return SDLKeyCodes::LB;
case SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_RIGHTSHOULDER: return SDLKeyCodes::RB;
case SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_BACK: return SDLKeyCodes::Back;
case SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_START: return SDLKeyCodes::Start;
case SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_LEFTSTICK: return SDLKeyCodes::LS;
case SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_RIGHTSTICK: return SDLKeyCodes::RS;
case SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_GUIDE: return SDLKeyCodes::Guide;
case SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_MISC1: return SDLKeyCodes::Misc1;
case SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_PADDLE1: return SDLKeyCodes::Paddle1;
case SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_PADDLE2: return SDLKeyCodes::Paddle2;
case SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_PADDLE3: return SDLKeyCodes::Paddle3;
case SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_PADDLE4: return SDLKeyCodes::Paddle4;
case SDL_GameControllerButton::SDL_CONTROLLER_BUTTON_TOUCHPAD: return SDLKeyCodes::Touchpad;
}
}
#endif
| 35,299
|
C++
|
.cpp
| 953
| 34.06191
| 230
| 0.695124
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,007
|
evdev_gun_handler.cpp
|
RPCS3_rpcs3/rpcs3/Input/evdev_gun_handler.cpp
|
// This makes debugging on windows less painful
//#define HAVE_LIBEVDEV
#ifdef HAVE_LIBEVDEV
#include "stdafx.h"
#include "evdev_gun_handler.h"
#include "util/logs.hpp"
#include <libudev.h>
#include <libevdev/libevdev.h>
#include <fcntl.h>
#include <unistd.h>
LOG_CHANNEL(evdev_log, "evdev");
constexpr usz max_devices = 8;
const std::map<gun_button, int> button_map
{
{gun_button::btn_left, BTN_LEFT},
{gun_button::btn_right, BTN_RIGHT},
{gun_button::btn_middle, BTN_MIDDLE},
{gun_button::btn_1, BTN_1},
{gun_button::btn_2, BTN_2},
{gun_button::btn_3, BTN_3},
{gun_button::btn_4, BTN_4},
{gun_button::btn_5, BTN_5},
{gun_button::btn_6, BTN_6},
{gun_button::btn_7, BTN_7},
{gun_button::btn_8, BTN_8}
};
struct event_udev_entry
{
const char* devnode = nullptr;
struct udev_list_entry* item = nullptr;
};
bool event_is_number(const char* s)
{
if (!s)
return false;
const usz len = strlen(s);
if (len == 0)
return false;
for (usz n = 0; n < len; n++)
{
if (s[n] < '0' || s[n] > '9')
return false;
}
return true;
}
// compare /dev/input/eventX and /dev/input/eventY where X and Y are numbers
int event_strcmp_events(const char* x, const char* y)
{
// find a common string
int n = 0;
while (x && y && x[n] == y[n] && x[n] != '\0' && y[n] != '\0')
{
n++;
}
// check if remaining string is a number
if (event_is_number(x + n) && event_is_number(y + n))
{
const int a = atoi(x + n);
const int b = atoi(y + n);
if (a == b)
return 0;
if (a < b)
return -1;
return 1;
}
return strcmp(x, y);
}
evdev_gun_handler::evdev_gun_handler()
{
}
evdev_gun_handler::~evdev_gun_handler()
{
for (evdev_gun& gun : m_devices)
{
if (gun.device)
{
const int fd = libevdev_get_fd(gun.device);
libevdev_free(gun.device);
close(fd);
}
}
if (m_udev != nullptr)
udev_unref(m_udev);
evdev_log.notice("Lightgun: Shutdown udev initialization");
}
int evdev_gun_handler::get_button(u32 gunno, gun_button button) const
{
const auto& buttons = ::at32(m_devices, gunno).buttons;
if (const auto it = buttons.find(::at32(button_map, button)); it != buttons.end())
{
return it->second;
}
return 0;
}
int evdev_gun_handler::get_axis_x(u32 gunno) const
{
const evdev_axis& axis = ::at32(::at32(m_devices, gunno).axis, ABS_X);
return axis.value - axis.min;
}
int evdev_gun_handler::get_axis_y(u32 gunno) const
{
const evdev_axis& axis = ::at32(::at32(m_devices, gunno).axis, ABS_Y);
return axis.value - axis.min;
}
int evdev_gun_handler::get_axis_x_max(u32 gunno) const
{
const evdev_axis& axis = ::at32(::at32(m_devices, gunno).axis, ABS_X);
return axis.max - axis.min;
}
int evdev_gun_handler::get_axis_y_max(u32 gunno) const
{
const evdev_axis& axis = ::at32(::at32(m_devices, gunno).axis, ABS_Y);
return axis.max - axis.min;
}
void evdev_gun_handler::poll(u32 index)
{
if (!m_is_init || index >= m_devices.size())
return;
evdev_gun& gun = ::at32(m_devices, index);
if (!gun.device)
return;
// Try to fetch all new events from the joystick.
input_event evt;
int ret = LIBEVDEV_READ_STATUS_SUCCESS;
while (ret >= 0)
{
if (ret == LIBEVDEV_READ_STATUS_SYNC)
{
// Grab any pending sync event.
ret = libevdev_next_event(gun.device, LIBEVDEV_READ_FLAG_NORMAL | LIBEVDEV_READ_FLAG_SYNC, &evt);
}
else
{
ret = libevdev_next_event(gun.device, LIBEVDEV_READ_FLAG_NORMAL, &evt);
}
if (ret == LIBEVDEV_READ_STATUS_SUCCESS)
{
switch (evt.type)
{
case EV_KEY:
gun.buttons[evt.code] = evt.value;
break;
case EV_ABS:
gun.axis[evt.code].value = evt.value;
break;
default:
break;
}
}
}
if (ret < 0)
{
// -EAGAIN signifies no available events, not an actual *error*.
if (ret != -EAGAIN)
evdev_log.error("Failed to read latest event from lightgun device: %s [errno %d]", strerror(-ret), -ret);
}
}
bool evdev_gun_handler::is_init() const
{
return m_is_init;
}
u32 evdev_gun_handler::get_num_guns() const
{
return ::narrow<u32>(m_devices.size());
}
bool evdev_gun_handler::init()
{
if (m_is_init)
return true;
m_devices.clear();
evdev_log.notice("Lightgun: Begin udev initialization");
m_udev = udev_new();
if (m_udev == nullptr)
{
evdev_log.error("Lightgun: Failed udev initialization");
return false;
}
if (udev_enumerate* enumerate = udev_enumerate_new(m_udev))
{
udev_enumerate_add_match_property(enumerate, "ID_INPUT_MOUSE", "1");
udev_enumerate_add_match_subsystem(enumerate, "input");
udev_enumerate_scan_devices(enumerate);
udev_list_entry* devs = udev_enumerate_get_list_entry(enumerate);
std::vector<event_udev_entry> sorted_devices;
for (udev_list_entry* item = devs; item && sorted_devices.size() < max_devices; item = udev_list_entry_get_next(item))
{
const char* name = udev_list_entry_get_name(item);
udev_device* dev = udev_device_new_from_syspath(m_udev, name);
const char* devnode = udev_device_get_devnode(dev);
if (devnode != nullptr)
{
event_udev_entry new_device{};
new_device.devnode = devnode;
new_device.item = item;
sorted_devices.push_back(std::move(new_device));
}
else
{
udev_device_unref(dev);
}
}
// Sort the udev entries by devnode name so that they are created in the proper order
std::sort(sorted_devices.begin(), sorted_devices.end(), [](const event_udev_entry& a, const event_udev_entry& b)
{
return event_strcmp_events(a.devnode, b.devnode);
});
for (const event_udev_entry& entry : sorted_devices)
{
// Get the filename of the /sys entry for the device and create a udev_device object (dev) representing it.
const char* name = udev_list_entry_get_name(entry.item);
evdev_log.notice("Lightgun: found device %s", name);
udev_device* dev = udev_device_new_from_syspath(m_udev, name);
const char* devnode = udev_device_get_devnode(dev);
const int fd = open(devnode, O_RDONLY | O_NONBLOCK);
struct libevdev* device = nullptr;
const int rc = libevdev_new_from_fd(fd, &device);
if (rc < 0)
{
// If it's just a bad file descriptor, don't bother logging, but otherwise, log it.
if (rc != -9)
evdev_log.warning("Failed to connect to lightgun device at %s, the error was: %s", devnode, strerror(-rc));
libevdev_free(device);
close(fd);
continue;
}
if (libevdev_has_event_type(device, EV_KEY) &&
libevdev_has_event_type(device, EV_ABS))
{
bool is_valid = true;
evdev_gun gun{};
gun.device = device;
for (int code : { ABS_X, ABS_Y })
{
if (const input_absinfo* info = libevdev_get_abs_info(device, code))
{
gun.axis[code].min = info->minimum;
gun.axis[code].max = info->maximum;
}
else
{
evdev_log.notice("Lightgun: device %s not valid. axis %d not found", name, code);
is_valid = false;
break;
}
}
if (is_valid)
{
evdev_log.notice("Lightgun: Adding device %d: %s, ABS_X(%i, %i), ABS_Y(%i, %i)", m_devices.size(), name, gun.axis[ABS_X].min, gun.axis[ABS_X].max, gun.axis[ABS_Y].min, gun.axis[ABS_Y].max);
m_devices.push_back(gun);
}
else
{
close(fd);
}
if (m_devices.size() >= max_devices)
break;
}
else
{
evdev_log.notice("Lightgun: device %s not valid. No axis or key events found", name);
close(fd);
}
}
udev_enumerate_unref(enumerate);
}
else
{
evdev_log.error("Lightgun: Failed udev enumeration");
}
m_is_init = true;
return true;
}
#endif
| 7,464
|
C++
|
.cpp
| 273
| 24.29304
| 194
| 0.664333
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,008
|
gui_pad_thread.cpp
|
RPCS3_rpcs3/rpcs3/Input/gui_pad_thread.cpp
|
#include "stdafx.h"
#include "gui_pad_thread.h"
#include "ds3_pad_handler.h"
#include "ds4_pad_handler.h"
#include "dualsense_pad_handler.h"
#include "skateboard_pad_handler.h"
#ifdef _WIN32
#include "xinput_pad_handler.h"
#include "mm_joystick_handler.h"
#elif HAVE_LIBEVDEV
#include "evdev_joystick_handler.h"
#endif
#ifdef HAVE_SDL2
#include "sdl_pad_handler.h"
#endif
#include "Emu/Io/PadHandler.h"
#include "Emu/System.h"
#include "Emu/system_config.h"
#include "Utilities/Thread.h"
#include "rpcs3qt/gui_settings.h"
#ifdef __linux__
#include <linux/uinput.h>
#include <fcntl.h>
#include <unistd.h>
#define CHECK_IOCTRL_RET(res) if (res == -1) { gui_log.error("gui_pad_thread: ioctl failed (errno=%d=%s)", res, strerror(errno)); }
#elif defined(__APPLE__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#include <ApplicationServices/ApplicationServices.h>
#include <Carbon/Carbon.h>
#pragma GCC diagnostic pop
#endif
#include <QApplication>
LOG_CHANNEL(gui_log, "GUI");
gui_pad_thread::gui_pad_thread()
{
m_thread = std::make_unique<std::thread>(&gui_pad_thread::run, this);
}
gui_pad_thread::~gui_pad_thread()
{
m_terminate = true;
if (m_thread && m_thread->joinable())
{
m_thread->join();
m_thread.reset();
}
#ifdef __linux__
if (m_uinput_fd != 1)
{
gui_log.notice("gui_pad_thread: closing /dev/uinput");
CHECK_IOCTRL_RET(ioctl(m_uinput_fd, UI_DEV_DESTROY));
int res = close(m_uinput_fd);
if (res == -1)
{
gui_log.error("gui_pad_thread: Failed to close /dev/uinput (errno=%d=%s)", res, strerror(errno));
}
m_uinput_fd = -1;
}
#endif
}
void gui_pad_thread::update_settings(const std::shared_ptr<gui_settings>& settings)
{
ensure(!!settings);
m_allow_global_input = settings->GetValue(gui::nav_global).toBool();
}
bool gui_pad_thread::init()
{
m_handler.reset();
m_pad.reset();
// Initialize last button states as pressed to avoid unwanted button presses when starting the thread.
m_last_button_state.fill(true);
m_timestamp = steady_clock::now();
m_initial_timestamp = steady_clock::now();
m_last_auto_repeat_button = pad_button::pad_button_max_enum;
g_cfg_input_configs.load();
std::string active_config = g_cfg_input_configs.active_configs.get_value("");
if (active_config.empty())
{
active_config = g_cfg_input_configs.active_configs.get_value(g_cfg_input_configs.global_key);
}
gui_log.notice("gui_pad_thread: Using input configuration: '%s'", active_config);
// Load in order to get the pad handlers
if (!g_cfg_input.load("", active_config))
{
gui_log.notice("gui_pad_thread: Loaded empty pad config");
}
// Adjust to the different pad handlers
for (usz i = 0; i < g_cfg_input.player.size(); i++)
{
std::shared_ptr<PadHandlerBase> handler;
gui_pad_thread::InitPadConfig(g_cfg_input.player[i]->config, g_cfg_input.player[i]->handler, handler);
}
// Reload with proper defaults
if (!g_cfg_input.load("", active_config))
{
gui_log.notice("gui_pad_thread: Reloaded empty pad config");
}
gui_log.trace("gui_pad_thread: Using pad config:\n%s", g_cfg_input);
for (u32 i = 0; i < CELL_PAD_MAX_PORT_NUM; i++) // max 7 pads
{
cfg_player* cfg = g_cfg_input.player[i];
const pad_handler handler_type = cfg->handler.get();
std::shared_ptr<PadHandlerBase> cur_pad_handler = GetHandler(handler_type);
if (!cur_pad_handler)
{
continue;
}
cur_pad_handler->Init();
m_handler = cur_pad_handler;
m_pad = std::make_shared<Pad>(handler_type, i, CELL_PAD_STATUS_DISCONNECTED, CELL_PAD_CAPABILITY_PS3_CONFORMITY | CELL_PAD_CAPABILITY_PRESS_MODE | CELL_PAD_CAPABILITY_ACTUATOR, CELL_PAD_DEV_TYPE_STANDARD);
if (!cur_pad_handler->bindPadToDevice(m_pad))
{
gui_log.error("gui_pad_thread: Failed to bind device '%s' to handler %s.", cfg->device.to_string(), handler_type);
}
gui_log.notice("gui_pad_thread: Pad %d: device='%s', handler=%s, VID=0x%x, PID=0x%x, class_type=0x%x, class_profile=0x%x",
i, cfg->device.to_string(), m_pad->m_pad_handler, m_pad->m_vendor_id, m_pad->m_product_id, m_pad->m_class_type, m_pad->m_class_profile);
// We only use one pad
break;
}
if (!m_handler || !m_pad)
{
gui_log.notice("gui_pad_thread: No devices configured.");
return false;
}
#ifdef __linux__
gui_log.notice("gui_pad_thread: opening /dev/uinput");
m_uinput_fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK);
if (m_uinput_fd == -1)
{
gui_log.error("gui_pad_thread: Failed to open /dev/uinput (errno=%d=%s)", m_uinput_fd, strerror(errno));
return false;
}
struct uinput_setup usetup{};
usetup.id.bustype = BUS_USB;
usetup.id.vendor = 0x1234;
usetup.id.product = 0x1234;
std::strcpy(usetup.name, "RPCS3 GUI Input Device");
// The ioctls below will enable the device that is about to be created to pass events.
CHECK_IOCTRL_RET(ioctl(m_uinput_fd, UI_SET_EVBIT, EV_KEY));
CHECK_IOCTRL_RET(ioctl(m_uinput_fd, UI_SET_KEYBIT, KEY_ESC));
CHECK_IOCTRL_RET(ioctl(m_uinput_fd, UI_SET_KEYBIT, KEY_ENTER));
CHECK_IOCTRL_RET(ioctl(m_uinput_fd, UI_SET_KEYBIT, KEY_BACKSPACE));
CHECK_IOCTRL_RET(ioctl(m_uinput_fd, UI_SET_KEYBIT, KEY_TAB));
CHECK_IOCTRL_RET(ioctl(m_uinput_fd, UI_SET_KEYBIT, KEY_LEFT));
CHECK_IOCTRL_RET(ioctl(m_uinput_fd, UI_SET_KEYBIT, KEY_RIGHT));
CHECK_IOCTRL_RET(ioctl(m_uinput_fd, UI_SET_KEYBIT, KEY_UP));
CHECK_IOCTRL_RET(ioctl(m_uinput_fd, UI_SET_KEYBIT, KEY_DOWN));
CHECK_IOCTRL_RET(ioctl(m_uinput_fd, UI_SET_KEYBIT, BTN_LEFT));
CHECK_IOCTRL_RET(ioctl(m_uinput_fd, UI_SET_KEYBIT, BTN_RIGHT));
CHECK_IOCTRL_RET(ioctl(m_uinput_fd, UI_SET_KEYBIT, BTN_MIDDLE));
CHECK_IOCTRL_RET(ioctl(m_uinput_fd, UI_SET_EVBIT, EV_REL));
CHECK_IOCTRL_RET(ioctl(m_uinput_fd, UI_SET_RELBIT, REL_X));
CHECK_IOCTRL_RET(ioctl(m_uinput_fd, UI_SET_RELBIT, REL_Y));
CHECK_IOCTRL_RET(ioctl(m_uinput_fd, UI_SET_RELBIT, REL_WHEEL));
CHECK_IOCTRL_RET(ioctl(m_uinput_fd, UI_SET_RELBIT, REL_HWHEEL));
CHECK_IOCTRL_RET(ioctl(m_uinput_fd, UI_DEV_SETUP, &usetup));
CHECK_IOCTRL_RET(ioctl(m_uinput_fd, UI_DEV_CREATE));
#endif
return true;
}
std::shared_ptr<PadHandlerBase> gui_pad_thread::GetHandler(pad_handler type)
{
switch (type)
{
case pad_handler::null:
case pad_handler::keyboard:
// Makes no sense to use this if we are in the GUI anyway
return nullptr;
case pad_handler::ds3:
return std::make_shared<ds3_pad_handler>();
case pad_handler::ds4:
return std::make_shared<ds4_pad_handler>();
case pad_handler::dualsense:
return std::make_shared<dualsense_pad_handler>();
case pad_handler::skateboard:
return std::make_shared<skateboard_pad_handler>();
#ifdef _WIN32
case pad_handler::xinput:
return std::make_shared<xinput_pad_handler>();
case pad_handler::mm:
return std::make_shared<mm_joystick_handler>();
#endif
#ifdef HAVE_SDL2
case pad_handler::sdl:
return std::make_shared<sdl_pad_handler>();
#endif
#ifdef HAVE_LIBEVDEV
case pad_handler::evdev:
return std::make_shared<evdev_joystick_handler>();
#endif
}
return nullptr;
}
void gui_pad_thread::InitPadConfig(cfg_pad& cfg, pad_handler type, std::shared_ptr<PadHandlerBase>& handler)
{
if (!handler)
{
handler = GetHandler(type);
if (handler)
{
handler->init_config(&cfg);
}
}
}
void gui_pad_thread::run()
{
thread_base::set_name("Gui Pad Thread");
gui_log.notice("gui_pad_thread: Pad thread started");
if (!init())
{
gui_log.warning("gui_pad_thread: Pad thread stopped (init failed)");
return;
}
while (!m_terminate)
{
// Only process input if there is an active window
if (m_handler && m_pad && (m_allow_global_input || QApplication::activeWindow()))
{
m_handler->process();
if (m_terminate)
{
break;
}
process_input();
}
if (m_terminate)
{
break;
}
std::this_thread::sleep_for(10ms);
}
gui_log.notice("gui_pad_thread: Pad thread stopped");
}
void gui_pad_thread::process_input()
{
if (!m_pad || !(m_pad->m_port_status & CELL_PAD_STATUS_CONNECTED))
{
return;
}
constexpr u64 ms_threshold = 500;
const auto on_button_pressed = [this](pad_button button_id, bool pressed, u16 value)
{
if (button_id == m_mouse_boost_button)
{
m_boost_mouse = pressed;
return;
}
u16 key = 0;
mouse_button btn = mouse_button::none;
mouse_wheel wheel = mouse_wheel::none;
float wheel_delta = 0.0f;
const float wheel_multiplier = pressed ? (m_boost_mouse ? 10.0f : 1.0f) : 0.0f;
const float move_multiplier = pressed ? (m_boost_mouse ? 40.0f : 20.0f) : 0.0f;
switch (button_id)
{
#ifdef _WIN32
case pad_button::dpad_up: key = VK_UP; break;
case pad_button::dpad_down: key = VK_DOWN; break;
case pad_button::dpad_left: key = VK_LEFT; break;
case pad_button::dpad_right: key = VK_RIGHT; break;
case pad_button::circle: key = VK_ESCAPE; break;
case pad_button::cross: key = VK_RETURN; break;
case pad_button::square: key = VK_BACK; break;
case pad_button::triangle: key = VK_TAB; break;
#elif defined(__linux__)
case pad_button::dpad_up: key = KEY_UP; break;
case pad_button::dpad_down: key = KEY_DOWN; break;
case pad_button::dpad_left: key = KEY_LEFT; break;
case pad_button::dpad_right: key = KEY_RIGHT; break;
case pad_button::circle: key = KEY_ESC; break;
case pad_button::cross: key = KEY_ENTER; break;
case pad_button::square: key = KEY_BACKSPACE; break;
case pad_button::triangle: key = KEY_TAB; break;
#elif defined (__APPLE__)
case pad_button::dpad_up: key = kVK_UpArrow; break;
case pad_button::dpad_down: key = kVK_DownArrow; break;
case pad_button::dpad_left: key = kVK_LeftArrow; break;
case pad_button::dpad_right: key = kVK_RightArrow; break;
case pad_button::circle: key = kVK_Escape; break;
case pad_button::cross: key = kVK_Return; break;
case pad_button::square: key = kVK_Delete; break;
case pad_button::triangle: key = kVK_Tab; break;
#endif
case pad_button::L1: btn = mouse_button::left; break;
case pad_button::R1: btn = mouse_button::right; break;
case pad_button::rs_up: wheel = mouse_wheel::vertical; wheel_delta = 10.0f * wheel_multiplier; break;
case pad_button::rs_down: wheel = mouse_wheel::vertical; wheel_delta = -10.0f * wheel_multiplier; break;
case pad_button::rs_left: wheel = mouse_wheel::horizontal; wheel_delta = -10.0f * wheel_multiplier; break;
case pad_button::rs_right: wheel = mouse_wheel::horizontal; wheel_delta = 10.0f * wheel_multiplier; break;
case pad_button::ls_up: m_mouse_delta_y -= (abs(value - 128) / 255.f) * move_multiplier; break;
case pad_button::ls_down: m_mouse_delta_y += (abs(value - 128) / 255.f) * move_multiplier; break;
case pad_button::ls_left: m_mouse_delta_x -= (abs(value - 128) / 255.f) * move_multiplier; break;
case pad_button::ls_right: m_mouse_delta_x += (abs(value - 128) / 255.f) * move_multiplier; break;
default: return;
}
if (key)
{
send_key_event(key, pressed);
}
else if (btn != mouse_button::none)
{
send_mouse_button_event(btn, pressed);
}
else if (wheel != mouse_wheel::none && pressed)
{
send_mouse_wheel_event(wheel, wheel_delta);
}
};
const auto handle_button_press = [&](pad_button button_id, bool pressed, u16 value)
{
if (button_id >= pad_button::pad_button_max_enum)
{
return;
}
bool& last_state = m_last_button_state[static_cast<u32>(button_id)];
if (pressed)
{
const bool is_auto_repeat_button = m_auto_repeat_buttons.contains(button_id);
const bool is_mouse_move_button = m_mouse_move_buttons.contains(button_id);
if (!last_state)
{
if (button_id != m_mouse_boost_button && !is_mouse_move_button)
{
// The button was not pressed before, so this is a new button press. Reset auto-repeat.
m_timestamp = steady_clock::now();
m_initial_timestamp = m_timestamp;
m_last_auto_repeat_button = is_auto_repeat_button ? button_id : pad_button::pad_button_max_enum;
}
on_button_pressed(static_cast<pad_button>(button_id), true, value);
}
else if (is_auto_repeat_button)
{
if (m_last_auto_repeat_button == button_id
&& m_input_timer.GetMsSince(m_initial_timestamp) > ms_threshold
&& m_input_timer.GetMsSince(m_timestamp) > m_auto_repeat_buttons.at(button_id))
{
// The auto-repeat button was pressed for at least the given threshold in ms and will trigger at an interval.
m_timestamp = steady_clock::now();
on_button_pressed(static_cast<pad_button>(button_id), true, value);
}
else if (m_last_auto_repeat_button == pad_button::pad_button_max_enum)
{
// An auto-repeat button was already pressed before and will now start triggering again after the next threshold.
m_last_auto_repeat_button = button_id;
}
}
else if (is_mouse_move_button)
{
on_button_pressed(static_cast<pad_button>(button_id), pressed, value);
}
}
else if (last_state)
{
if (m_last_auto_repeat_button == button_id)
{
// We stopped pressing an auto-repeat button, so re-enable auto-repeat for other buttons.
m_last_auto_repeat_button = pad_button::pad_button_max_enum;
}
on_button_pressed(static_cast<pad_button>(button_id), false, value);
}
last_state = pressed;
};
for (const auto& button : m_pad->m_buttons)
{
pad_button button_id = pad_button::pad_button_max_enum;
if (button.m_offset == CELL_PAD_BTN_OFFSET_DIGITAL1)
{
switch (button.m_outKeyCode)
{
case CELL_PAD_CTRL_LEFT:
button_id = pad_button::dpad_left;
break;
case CELL_PAD_CTRL_RIGHT:
button_id = pad_button::dpad_right;
break;
case CELL_PAD_CTRL_DOWN:
button_id = pad_button::dpad_down;
break;
case CELL_PAD_CTRL_UP:
button_id = pad_button::dpad_up;
break;
case CELL_PAD_CTRL_L3:
button_id = pad_button::L3;
break;
case CELL_PAD_CTRL_R3:
button_id = pad_button::R3;
break;
case CELL_PAD_CTRL_SELECT:
button_id = pad_button::select;
break;
case CELL_PAD_CTRL_START:
button_id = pad_button::start;
break;
default:
break;
}
}
else if (button.m_offset == CELL_PAD_BTN_OFFSET_DIGITAL2)
{
switch (button.m_outKeyCode)
{
case CELL_PAD_CTRL_TRIANGLE:
button_id = pad_button::triangle;
break;
case CELL_PAD_CTRL_CIRCLE:
button_id = g_cfg.sys.enter_button_assignment == enter_button_assign::circle ? pad_button::cross : pad_button::circle;
break;
case CELL_PAD_CTRL_SQUARE:
button_id = pad_button::square;
break;
case CELL_PAD_CTRL_CROSS:
button_id = g_cfg.sys.enter_button_assignment == enter_button_assign::circle ? pad_button::circle : pad_button::cross;
break;
case CELL_PAD_CTRL_L1:
button_id = pad_button::L1;
break;
case CELL_PAD_CTRL_R1:
button_id = pad_button::R1;
break;
case CELL_PAD_CTRL_L2:
button_id = pad_button::L2;
break;
case CELL_PAD_CTRL_R2:
button_id = pad_button::R2;
break;
case CELL_PAD_CTRL_PS:
button_id = pad_button::ps;
break;
default:
break;
}
}
handle_button_press(button_id, button.m_pressed, button.m_value);
}
for (const AnalogStick& stick : m_pad->m_sticks)
{
pad_button button_id = pad_button::pad_button_max_enum;
pad_button release_id = pad_button::pad_button_max_enum;
switch (stick.m_offset)
{
case CELL_PAD_BTN_OFFSET_ANALOG_LEFT_X:
button_id = (stick.m_value <= 128) ? pad_button::ls_left : pad_button::ls_right;
release_id = (stick.m_value > 128) ? pad_button::ls_left : pad_button::ls_right;
break;
case CELL_PAD_BTN_OFFSET_ANALOG_LEFT_Y:
button_id = (stick.m_value <= 128) ? pad_button::ls_up : pad_button::ls_down;
release_id = (stick.m_value > 128) ? pad_button::ls_up : pad_button::ls_down;
break;
case CELL_PAD_BTN_OFFSET_ANALOG_RIGHT_X:
button_id = (stick.m_value <= 128) ? pad_button::rs_left : pad_button::rs_right;
release_id = (stick.m_value > 128) ? pad_button::rs_left : pad_button::rs_right;
break;
case CELL_PAD_BTN_OFFSET_ANALOG_RIGHT_Y:
button_id = (stick.m_value <= 128) ? pad_button::rs_up : pad_button::rs_down;
release_id = (stick.m_value > 128) ? pad_button::rs_up : pad_button::rs_down;
break;
default:
break;
}
bool pressed;
if (m_mouse_move_buttons.contains(button_id))
{
// Mouse move sticks are always pressed if they surpass a tiny deadzone.
constexpr int deadzone = 5;
pressed = std::abs(stick.m_value - 128) > deadzone;
}
else
{
// Let's say other sticks are only pressed if they are almost completely tilted. Otherwise navigation feels really wacky.
pressed = stick.m_value < 30 || stick.m_value > 225;
}
// Release other direction on the same axis first
handle_button_press(release_id, false, stick.m_value);
// Handle currently pressed stick direction
handle_button_press(button_id, pressed, stick.m_value);
}
// Send mouse move event at the end to prevent redundant calls
// Round to lower integer
const int delta_x = m_mouse_delta_x;
const int delta_y = m_mouse_delta_y;
if (delta_x || delta_y)
{
// Remove integer part
m_mouse_delta_x -= delta_x;
m_mouse_delta_y -= delta_y;
// Send event
send_mouse_move_event(delta_x, delta_y);
}
}
#ifdef __linux__
void gui_pad_thread::emit_event(int type, int code, int val)
{
struct input_event ie{};
ie.type = type;
ie.code = code;
ie.value = val;
int res = write(m_uinput_fd, &ie, sizeof(ie));
if (res == -1)
{
gui_log.error("gui_pad_thread::emit_event: write failed (errno=%d=%s)", res, strerror(errno));
}
}
#endif
void gui_pad_thread::send_key_event(u32 key, bool pressed)
{
gui_log.trace("gui_pad_thread::send_key_event: key=%d, pressed=%d", key, pressed);
#ifdef _WIN32
INPUT input{};
input.type = INPUT_KEYBOARD;
input.ki.wVk = key;
if (!pressed)
{
input.ki.dwFlags = KEYEVENTF_KEYUP;
}
if (SendInput(1, &input, sizeof(INPUT)) != 1)
{
gui_log.error("gui_pad_thread: SendInput() failed: %s", fmt::win_error{GetLastError(), nullptr});
}
#elif defined(__linux__)
emit_event(EV_KEY, key, pressed ? 1 : 0);
emit_event(EV_SYN, SYN_REPORT, 0);
#elif defined(__APPLE__)
CGEventRef ev = CGEventCreateKeyboardEvent(NULL, static_cast<CGKeyCode>(key), pressed);
if (!ev)
{
gui_log.error("gui_pad_thread: CGEventCreateKeyboardEvent() failed");
return;
}
CGEventPost(kCGHIDEventTap, ev);
CFRelease(ev);
#endif
}
void gui_pad_thread::send_mouse_button_event(mouse_button btn, bool pressed)
{
gui_log.trace("gui_pad_thread::send_mouse_button_event: btn=%d, pressed=%d", static_cast<int>(btn), pressed);
#ifdef _WIN32
INPUT input{};
input.type = INPUT_MOUSE;
switch (btn)
{
case mouse_button::none: return;
case mouse_button::left: input.mi.dwFlags = pressed ? MOUSEEVENTF_LEFTDOWN : MOUSEEVENTF_LEFTUP; break;
case mouse_button::right: input.mi.dwFlags = pressed ? MOUSEEVENTF_RIGHTDOWN : MOUSEEVENTF_RIGHTUP; break;
case mouse_button::middle: input.mi.dwFlags = pressed ? MOUSEEVENTF_MIDDLEDOWN : MOUSEEVENTF_MIDDLEUP; break;
}
if (SendInput(1, &input, sizeof(INPUT)) != 1)
{
gui_log.error("gui_pad_thread: SendInput() failed: %s", fmt::win_error{GetLastError(), nullptr});
}
#elif defined(__linux__)
int key = 0;
switch (btn)
{
case mouse_button::none: return;
case mouse_button::left: key = BTN_LEFT; break;
case mouse_button::right: key = BTN_RIGHT; break;
case mouse_button::middle: key = BTN_MIDDLE; break;
}
emit_event(EV_KEY, key, pressed ? 1 : 0);
emit_event(EV_SYN, SYN_REPORT, 0);
#elif defined(__APPLE__)
CGEventType type{};
CGMouseButton mouse_btn{};
switch (btn)
{
case mouse_button::none: return;
case mouse_button::left:
type = pressed ? kCGEventLeftMouseDown : kCGEventLeftMouseUp;
mouse_btn = kCGMouseButtonLeft;
break;
case mouse_button::right:
type = pressed ? kCGEventRightMouseDown : kCGEventRightMouseUp;
mouse_btn = kCGMouseButtonRight;
break;
case mouse_button::middle:
type = pressed ? kCGEventOtherMouseDown : kCGEventOtherMouseUp;
mouse_btn = kCGMouseButtonCenter;
break;
}
CGEventRef ev = CGEventCreateMouseEvent(NULL, type, CGPointMake(m_mouse_abs_x, m_mouse_abs_y), mouse_btn);
if (!ev)
{
gui_log.error("gui_pad_thread: CGEventCreateMouseEvent() failed");
return;
}
CGEventPost(kCGHIDEventTap, ev);
CFRelease(ev);
#endif
}
void gui_pad_thread::send_mouse_wheel_event(mouse_wheel wheel, int delta)
{
gui_log.trace("gui_pad_thread::send_mouse_wheel_event: wheel=%d, delta=%d", static_cast<int>(wheel), delta);
if (!delta)
{
return;
}
#ifdef _WIN32
INPUT input{};
input.type = INPUT_MOUSE;
input.mi.mouseData = delta;
switch (wheel)
{
case mouse_wheel::none: return;
case mouse_wheel::vertical: input.mi.dwFlags = MOUSEEVENTF_WHEEL; break;
case mouse_wheel::horizontal: input.mi.dwFlags = MOUSEEVENTF_HWHEEL; break;
}
if (SendInput(1, &input, sizeof(INPUT)) != 1)
{
gui_log.error("gui_pad_thread: SendInput() failed: %s", fmt::win_error{GetLastError(), nullptr});
}
#elif defined(__linux__)
int axis = 0;
switch (wheel)
{
case mouse_wheel::none: return;
case mouse_wheel::vertical: axis = REL_WHEEL; break;
case mouse_wheel::horizontal: axis = REL_HWHEEL; break;
}
emit_event(EV_REL, axis, delta);
emit_event(EV_SYN, SYN_REPORT, 0);
#elif defined(__APPLE__)
int v_delta = 0;
int h_delta = 0;
switch (wheel)
{
case mouse_wheel::none: return;
case mouse_wheel::vertical: v_delta = delta; break;
case mouse_wheel::horizontal: h_delta = delta; break;
}
constexpr u32 wheel_count = 2;
CGEventRef ev = CGEventCreateScrollWheelEvent(NULL, kCGScrollEventUnitPixel, wheel_count, v_delta, h_delta);
if (!ev)
{
gui_log.error("gui_pad_thread: CGEventCreateScrollWheelEvent() failed");
return;
}
CGEventPost(kCGHIDEventTap, ev);
CFRelease(ev);
#endif
}
void gui_pad_thread::send_mouse_move_event(int delta_x, int delta_y)
{
gui_log.trace("gui_pad_thread::send_mouse_move_event: delta_x=%d, delta_y=%d", delta_x, delta_y);
if (!delta_x && !delta_y)
{
return;
}
#ifdef _WIN32
INPUT input{};
input.type = INPUT_MOUSE;
input.mi.dwFlags = MOUSEEVENTF_MOVE;
input.mi.dx = delta_x;
input.mi.dy = delta_y;
if (SendInput(1, &input, sizeof(INPUT)) != 1)
{
gui_log.error("gui_pad_thread: SendInput() failed: %s", fmt::win_error{GetLastError(), nullptr});
}
#elif defined(__linux__)
if (delta_x) emit_event(EV_REL, REL_X, delta_x);
if (delta_y) emit_event(EV_REL, REL_Y, delta_y);
emit_event(EV_SYN, SYN_REPORT, 0);
#elif defined(__APPLE__)
CGDirectDisplayID display = CGMainDisplayID();
const usz width = CGDisplayPixelsWide(display);
const usz height = CGDisplayPixelsHigh(display);
const float mouse_abs_x = std::clamp(m_mouse_abs_x + delta_x, 0.0f, width - 1.0f);
const float mouse_abs_y = std::clamp(m_mouse_abs_y + delta_y, 0.0f, height - 1.0f);
if (m_mouse_abs_x == mouse_abs_x && m_mouse_abs_y == mouse_abs_y)
{
return;
}
m_mouse_abs_x = mouse_abs_x;
m_mouse_abs_y = mouse_abs_y;
CGEventRef ev = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, CGPointMake(m_mouse_abs_x, m_mouse_abs_y), {});
if (!ev)
{
gui_log.error("gui_pad_thread: CGEventCreateMouseEvent() failed");
return;
}
CGEventPost(kCGHIDEventTap, ev);
CFRelease(ev);
#endif
}
| 22,990
|
C++
|
.cpp
| 683
| 30.877013
| 207
| 0.699847
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,009
|
evdev_joystick_handler.cpp
|
RPCS3_rpcs3/rpcs3/Input/evdev_joystick_handler.cpp
|
// This makes debugging on windows less painful
//#define HAVE_LIBEVDEV
#ifdef HAVE_LIBEVDEV
#include "Input/product_info.h"
#include "Emu/Io/pad_config.h"
#include "evdev_joystick_handler.h"
#include "util/logs.hpp"
#include <functional>
#include <algorithm>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <cstring>
#include <cstdio>
#include <cmath>
LOG_CHANNEL(evdev_log, "evdev");
evdev_joystick_handler::evdev_joystick_handler()
: PadHandlerBase(pad_handler::evdev)
{
init_configs();
// Define border values
thumb_max = 255;
trigger_min = 0;
trigger_max = 255;
// set capabilities
b_has_config = true;
b_has_rumble = true;
b_has_motion = true;
b_has_deadzones = true;
m_trigger_threshold = trigger_max / 2;
m_thumb_threshold = thumb_max / 2;
m_dev = std::make_shared<EvdevDevice>();
}
evdev_joystick_handler::~evdev_joystick_handler()
{
close_devices();
}
void evdev_joystick_handler::init_config(cfg_pad* cfg)
{
if (!cfg) return;
// Set default button mapping
cfg->ls_left.def = ::at32(rev_axis_list, ABS_X);
cfg->ls_down.def = ::at32(axis_list, ABS_Y);
cfg->ls_right.def = ::at32(axis_list, ABS_X);
cfg->ls_up.def = ::at32(rev_axis_list, ABS_Y);
cfg->rs_left.def = ::at32(rev_axis_list, ABS_RX);
cfg->rs_down.def = ::at32(axis_list, ABS_RY);
cfg->rs_right.def = ::at32(axis_list, ABS_RX);
cfg->rs_up.def = ::at32(rev_axis_list, ABS_RY);
cfg->start.def = ::at32(button_list, BTN_START);
cfg->select.def = ::at32(button_list, BTN_SELECT);
cfg->ps.def = ::at32(button_list, BTN_MODE);
cfg->square.def = ::at32(button_list, BTN_X);
cfg->cross.def = ::at32(button_list, BTN_A);
cfg->circle.def = ::at32(button_list, BTN_B);
cfg->triangle.def = ::at32(button_list, BTN_Y);
cfg->left.def = ::at32(rev_axis_list, ABS_HAT0X);
cfg->down.def = ::at32(axis_list, ABS_HAT0Y);
cfg->right.def = ::at32(axis_list, ABS_HAT0X);
cfg->up.def = ::at32(rev_axis_list, ABS_HAT0Y);
cfg->r1.def = ::at32(button_list, BTN_TR);
cfg->r2.def = ::at32(axis_list, ABS_RZ);
cfg->r3.def = ::at32(button_list, BTN_THUMBR);
cfg->l1.def = ::at32(button_list, BTN_TL);
cfg->l2.def = ::at32(axis_list, ABS_Z);
cfg->l3.def = ::at32(button_list, BTN_THUMBL);
cfg->motion_sensor_x.axis.def = ::at32(motion_axis_list, ABS_X);
cfg->motion_sensor_y.axis.def = ::at32(motion_axis_list, ABS_Y);
cfg->motion_sensor_z.axis.def = ::at32(motion_axis_list, ABS_Z);
cfg->motion_sensor_g.axis.def = ::at32(motion_axis_list, ABS_RY); // DS3 uses the yaw axis for gyros
cfg->pressure_intensity_button.def = ::at32(button_list, NO_BUTTON);
cfg->analog_limiter_button.def = ::at32(button_list, NO_BUTTON);
// Set default misc variables
cfg->lstick_anti_deadzone.def = static_cast<u32>(0.13 * thumb_max); // 13%
cfg->rstick_anti_deadzone.def = static_cast<u32>(0.13 * thumb_max); // 13%
cfg->lstickdeadzone.def = 30; // between 0 and 255
cfg->rstickdeadzone.def = 30; // between 0 and 255
cfg->ltriggerthreshold.def = 0; // between 0 and 255
cfg->rtriggerthreshold.def = 0; // between 0 and 255
cfg->lpadsquircling.def = 8000;
cfg->rpadsquircling.def = 8000;
// apply defaults
cfg->from_default();
}
std::unordered_map<u32, std::string> evdev_joystick_handler::get_motion_axis_list() const
{
return motion_axis_list;
}
bool evdev_joystick_handler::Init()
{
if (m_is_init)
return true;
m_pos_axis_config.load();
if (!m_pos_axis_config.exist())
m_pos_axis_config.save();
for (const auto& node : m_pos_axis_config.get_nodes())
{
if (node && *static_cast<cfg::_bool*>(node))
{
const std::string& name = node->get_name();
const int code = libevdev_event_code_from_name(EV_ABS, name.c_str());
if (code < 0)
evdev_log.error("Failed to read axis name from %s. [code = %d] [name = %s]", m_pos_axis_config.cfg_name, code, name);
else
m_positive_axis.insert(code);
}
}
m_is_init = true;
return true;
}
std::string evdev_joystick_handler::get_device_name(const libevdev* dev)
{
std::string name;
if (const char* raw_name = libevdev_get_name(dev))
name = raw_name;
if (name.empty())
{
if (const char* unique = libevdev_get_uniq(dev))
name = unique;
if (name.empty())
name = "Unknown Device";
}
return name;
}
bool evdev_joystick_handler::update_device(const std::shared_ptr<PadDevice>& device)
{
EvdevDevice* evdev_device = static_cast<EvdevDevice*>(device.get());
if (!evdev_device)
return false;
const std::string& path = evdev_device->path;
libevdev*& dev = evdev_device->device;
const bool was_connected = dev != nullptr;
if (access(path.c_str(), R_OK) == -1)
{
if (was_connected)
{
const int fd = libevdev_get_fd(dev);
libevdev_free(dev);
close(fd);
dev = nullptr;
}
evdev_log.error("Joystick %s is not present or accessible [previous status: %d]", path.c_str(), was_connected ? 1 : 0);
return false;
}
if (was_connected)
return true; // It's already been connected, and the js is still present.
const int fd = open(path.c_str(), O_RDWR | O_NONBLOCK);
if (fd == -1)
{
const int err = errno;
evdev_log.error("Failed to open joystick: %s [errno %d]", strerror(err), err);
return false;
}
const int ret = libevdev_new_from_fd(fd, &dev);
if (ret < 0)
{
evdev_log.error("Failed to initialize libevdev for joystick: %s [errno %d]", strerror(-ret), -ret);
return false;
}
evdev_log.notice("Opened joystick: '%s' at %s (fd %d)", get_device_name(dev), path, fd);
return true;
}
void evdev_joystick_handler::close_devices()
{
const auto free_device = [](EvdevDevice* evdev_device)
{
if (evdev_device && evdev_device->device)
{
const int fd = libevdev_get_fd(evdev_device->device);
if (evdev_device->effect_id != -1)
ioctl(fd, EVIOCRMFF, evdev_device->effect_id);
libevdev_free(evdev_device->device);
close(fd);
}
};
for (pad_ensemble& binding : m_bindings)
{
free_device(static_cast<EvdevDevice*>(binding.device.get()));
free_device(static_cast<EvdevDevice*>(binding.buddy_device.get()));
}
for (auto& [name, device] : m_settings_added)
{
free_device(static_cast<EvdevDevice*>(device.get()));
}
for (auto& [name, device] : m_motion_settings_added)
{
free_device(static_cast<EvdevDevice*>(device.get()));
}
}
std::unordered_map<u64, std::pair<u16, bool>> evdev_joystick_handler::GetButtonValues(const std::shared_ptr<EvdevDevice>& device)
{
std::unordered_map<u64, std::pair<u16, bool>> button_values;
if (!device)
return button_values;
libevdev* dev = device->device;
if (!Init())
return button_values;
for (const auto& [code, name] : button_list)
{
if (code == NO_BUTTON)
continue;
int val = 0;
if (libevdev_fetch_event_value(dev, EV_KEY, code, &val) == 0)
continue;
button_values.emplace(code, std::make_pair<u16, bool>(static_cast<u16>(val > 0 ? 255 : 0), false));
}
for (const auto& [code, name] : axis_list)
{
int val = 0;
if (libevdev_fetch_event_value(dev, EV_ABS, code, &val) == 0)
continue;
const int min = libevdev_get_abs_minimum(dev, code);
const int max = libevdev_get_abs_maximum(dev, code);
const int flat = libevdev_get_abs_flat(dev, code);
// Triggers do not need handling of negative values
if (min >= 0 && !m_positive_axis.contains(code))
{
const float fvalue = ScaledInput(val, min, max, flat);
button_values.emplace(code, std::make_pair<u16, bool>(static_cast<u16>(fvalue), false));
continue;
}
const float fvalue = ScaledAxisInput(val, min, max, flat);
if (fvalue < 0)
button_values.emplace(code, std::make_pair<u16, bool>(static_cast<u16>(std::abs(fvalue)), true));
else
button_values.emplace(code, std::make_pair<u16, bool>(static_cast<u16>(fvalue), false));
}
return button_values;
}
std::shared_ptr<evdev_joystick_handler::EvdevDevice> evdev_joystick_handler::get_evdev_device(const std::string& device)
{
// Add device if not yet present
std::shared_ptr<EvdevDevice> evdev_device = add_device(device, true);
if (!evdev_device)
return nullptr;
// Check if our device is connected
if (!update_device(evdev_device))
return nullptr;
return evdev_device;
}
PadHandlerBase::connection evdev_joystick_handler::get_next_button_press(const std::string& padId, const pad_callback& callback, const pad_fail_callback& fail_callback, gui_call_type call_type, const std::vector<std::string>& buttons)
{
if (call_type == gui_call_type::blacklist)
m_blacklist.clear();
if (call_type == gui_call_type::reset_input || call_type == gui_call_type::blacklist)
m_min_button_values.clear();
// Get our evdev device
std::shared_ptr<EvdevDevice> device = get_evdev_device(padId);
if (!device || !device->device)
{
if (fail_callback)
fail_callback(padId);
return connection::disconnected;
}
libevdev* dev = device->device;
// Try to fetch all new events from the joystick.
input_event evt;
bool has_new_event = false;
int ret = LIBEVDEV_READ_STATUS_SUCCESS;
while (ret >= 0)
{
if (ret == LIBEVDEV_READ_STATUS_SYNC)
{
// Grab any pending sync event.
ret = libevdev_next_event(dev, LIBEVDEV_READ_FLAG_SYNC, &evt);
}
else
{
ret = libevdev_next_event(dev, LIBEVDEV_READ_FLAG_NORMAL, &evt);
}
has_new_event |= ret == LIBEVDEV_READ_STATUS_SUCCESS;
}
if (call_type == gui_call_type::get_connection)
{
return has_new_event ? connection::connected : connection::no_data;
}
const auto data = GetButtonValues(device);
const auto find_value = [&, this](const std::string& str)
{
const std::vector<std::string> names = cfg_pad::get_buttons(str);
u16 value{};
const auto set_value = [&value, &data](u32 code, bool dir)
{
if (const auto it = data.find(static_cast<u64>(code)); it != data.cend() && dir == it->second.second)
{
value = std::max(value, it->second.first);
}
};
for (const u32 code : FindKeyCodes<u32, u32>(rev_axis_list, names))
{
set_value(code, true);
}
for (const u32 code : FindKeyCodes<u32, u32>(axis_list, names))
{
set_value(code, false);
}
for (const u32 code : FindKeyCodes<u32, u32>(button_list, names))
{
set_value(code, false);
}
return value;
};
pad_preview_values preview_values{};
if (buttons.size() == 10)
{
preview_values[0] = find_value(buttons[0]); // Left Trigger
preview_values[1] = find_value(buttons[1]); // Right Trigger
preview_values[2] = find_value(buttons[3]) - find_value(buttons[2]); // Left Stick X
preview_values[3] = find_value(buttons[5]) - find_value(buttons[4]); // Left Stick Y
preview_values[4] = find_value(buttons[7]) - find_value(buttons[6]); // Right Stick X
preview_values[5] = find_value(buttons[9]) - find_value(buttons[8]); // Right Stick Y
}
// return if nothing new has happened. ignore this to get the current state for blacklist or reset_input
if (call_type != gui_call_type::blacklist && call_type != gui_call_type::reset_input && !has_new_event)
{
if (callback)
callback(0, "", padId, 0, preview_values);
return connection::no_data;
}
struct
{
u16 value = 0;
std::string name;
} pressed_button{};
const auto set_button_press = [&](const u32 code, const std::string& name, std::string_view type, u16 threshold, int ev_type, bool is_rev_axis)
{
if (call_type != gui_call_type::blacklist && m_blacklist.contains(name))
return;
// Ignore codes that aren't part of the latest events. Otherwise we will get value 0 which will reset our min_value.
const auto it = data.find(static_cast<u64>(code));
if (it == data.cend())
{
if (call_type == gui_call_type::reset_input)
{
// Set to max. We won't have all the events for all the buttons or axis at this point.
m_min_button_values[name] = 65535;
if (ev_type == EV_ABS)
{
// Also set the other direction to max if it wasn't already found.
const auto it_other_axis = is_rev_axis ? axis_list.find(code) : rev_axis_list.find(code);
ensure(it_other_axis != (is_rev_axis ? axis_list.cend() : rev_axis_list.cend()));
if (const std::string& other_name = it_other_axis->second; !m_min_button_values.contains(other_name))
{
m_min_button_values[other_name] = 65535;
}
}
}
return;
}
const auto& [value, is_rev_ax] = it->second;
// If we want the value for an axis, its direction has to match the direction of the data.
if (ev_type == EV_ABS && is_rev_axis != is_rev_ax)
return;
u16& min_value = m_min_button_values[name];
if (call_type == gui_call_type::reset_input || value < min_value)
{
min_value = value;
return;
}
if (value <= threshold)
return;
if (call_type == gui_call_type::blacklist)
{
m_blacklist.insert(name);
if (ev_type == EV_ABS)
{
const int min = libevdev_get_abs_minimum(dev, code);
const int max = libevdev_get_abs_maximum(dev, code);
evdev_log.error("Evdev Calibration: Added %s [ %d = %s = %s ] to blacklist. [ Value = %d ] [ Min = %d ] [ Max = %d ]", type, code, libevdev_event_code_get_name(ev_type, code), name, value, min, max);
}
else
{
evdev_log.error("Evdev Calibration: Added %s [ %d = %s = %s ] to blacklist. Value = %d", type, code, libevdev_event_code_get_name(ev_type, code), name, value);
}
return;
}
const u16 diff = value > min_value ? value - min_value : 0;
if (diff > button_press_threshold && value > pressed_button.value)
{
pressed_button = { .value = value, .name = name };
}
};
const bool is_xbox_360_controller = padId.find("Xbox 360") != umax;
const bool is_sony_controller = !is_xbox_360_controller && padId.find("Sony") != umax;
const bool is_sony_guitar = is_sony_controller && padId.find("Guitar") != umax;
for (const auto& [code, name] : button_list)
{
// Handle annoying useless buttons
if (code == NO_BUTTON)
continue;
if (is_xbox_360_controller && code >= BTN_TRIGGER_HAPPY)
continue;
if (is_sony_controller && !is_sony_guitar && (code == BTN_TL2 || code == BTN_TR2))
continue;
set_button_press(code, name, "button"sv, 0, EV_KEY, false);
}
for (const auto& [code, name] : axis_list)
{
set_button_press(code, name, "axis"sv, m_thumb_threshold, EV_ABS, false);
}
for (const auto& [code, name] : rev_axis_list)
{
set_button_press(code, name, "rev axis"sv, m_thumb_threshold, EV_ABS, true);
}
if (call_type == gui_call_type::reset_input)
{
return connection::no_data;
}
if (call_type == gui_call_type::blacklist)
{
if (m_blacklist.empty())
evdev_log.success("Evdev Calibration: Blacklist is clear. No input spam detected");
return connection::connected;
}
if (callback)
{
if (pressed_button.value > 0)
callback(pressed_button.value, pressed_button.name, padId, 0, std::move(preview_values));
else
callback(0, "", padId, 0, std::move(preview_values));
}
return connection::connected;
}
void evdev_joystick_handler::get_motion_sensors(const std::string& padId, const motion_callback& callback, const motion_fail_callback& fail_callback, motion_preview_values preview_values, const std::array<AnalogSensor, 4>& sensors)
{
// Add device if not yet present
std::shared_ptr<EvdevDevice> device = add_motion_device(padId, true);
if (!device || !update_device(device) || !device->device)
{
if (fail_callback)
fail_callback(padId, std::move(preview_values));
return;
}
libevdev* dev = device->device;
// Try to fetch all new events from the joystick.
bool is_dirty = false;
int ret = LIBEVDEV_READ_STATUS_SUCCESS;
while (ret >= 0)
{
input_event evt;
if (ret == LIBEVDEV_READ_STATUS_SYNC)
{
// Grab any pending sync event.
ret = libevdev_next_event(dev, LIBEVDEV_READ_FLAG_NORMAL | LIBEVDEV_READ_FLAG_SYNC, &evt);
}
else
{
ret = libevdev_next_event(dev, LIBEVDEV_READ_FLAG_NORMAL, &evt);
}
if (ret == LIBEVDEV_READ_STATUS_SUCCESS && evt.type == EV_ABS)
{
for (usz i = 0; i < sensors.size(); i++)
{
const AnalogSensor& sensor = sensors[i];
if (sensor.m_keyCode != evt.code)
continue;
preview_values[i] = get_sensor_value(dev, sensor, evt);;
is_dirty = true;
}
}
}
if (ret < 0)
{
// -EAGAIN signifies no available events, not an actual *error*.
if (ret != -EAGAIN)
evdev_log.error("Failed to read latest event from motion device: %s [errno %d]", strerror(-ret), -ret);
}
if (callback && is_dirty)
callback(padId, std::move(preview_values));
}
// https://github.com/dolphin-emu/dolphin/blob/master/Source/Core/InputCommon/ControllerInterface/evdev/evdev.cpp
// https://github.com/reicast/reicast-emulator/blob/master/core/linux-dist/evdev.cpp
// http://www.infradead.org/~mchehab/kernel_docs_pdf/linux-input.pdf
void evdev_joystick_handler::SetRumble(EvdevDevice* device, u8 large, u8 small)
{
if (!device || !device->has_rumble || device->effect_id == -2)
return;
const int fd = libevdev_get_fd(device->device);
if (fd < 0)
return;
device->new_output_data = large != device->large_motor || small != device->small_motor;
const auto now = steady_clock::now();
const auto elapsed = now - device->last_output;
// XBox One Controller can't handle faster vibration updates than ~10ms. Elite is even worse.
// So I'll use 20ms to be on the safe side. No lag was noticable.
if ((!device->new_output_data || elapsed <= 20ms) && elapsed <= min_output_interval)
return;
device->new_output_data = false;
device->last_output = now;
// delete the previous effect (which also stops it)
if (device->effect_id != -1)
{
ioctl(fd, EVIOCRMFF, device->effect_id);
device->effect_id = -1;
}
if (large == 0 && small == 0)
{
device->large_motor = large;
device->small_motor = small;
return;
}
ff_effect effect;
if (libevdev_has_event_code(device->device, EV_FF, FF_RUMBLE))
{
effect.type = FF_RUMBLE;
effect.id = device->effect_id;
effect.direction = 0;
effect.u.rumble.strong_magnitude = large * 257;
effect.u.rumble.weak_magnitude = small * 257;
effect.replay.length = 0;
effect.replay.delay = 0;
effect.trigger.button = 0;
effect.trigger.interval = 0;
}
else
{
// TODO: handle other Rumble effects
device->effect_id = -2;
return;
}
if (ioctl(fd, EVIOCSFF, &effect) == -1)
{
evdev_log.error("evdev SetRumble ioctl failed! [large = %d] [small = %d] [fd = %d]", large, small, fd);
device->effect_id = -2;
}
device->effect_id = effect.id;
input_event play;
play.type = EV_FF;
play.code = device->effect_id;
play.value = 1;
if (write(fd, &play, sizeof(play)) == -1)
{
evdev_log.error("evdev SetRumble write failed! [large = %d] [small = %d] [fd = %d] [effect_id = %d]", large, small, fd, device->effect_id);
device->effect_id = -2;
}
device->large_motor = large;
device->small_motor = small;
}
void evdev_joystick_handler::SetPadData(const std::string& padId, u8 /*player_id*/, u8 large_motor, u8 small_motor, s32 /* r*/, s32 /* g*/, s32 /* b*/, bool /*player_led*/, bool /*battery_led*/, u32 /*battery_led_brightness*/)
{
// Get our evdev device
std::shared_ptr<EvdevDevice> dev = get_evdev_device(padId);
if (!dev)
{
evdev_log.error("evdev TestVibration: Device [%s] not found! [large_motor = %d] [small_motor = %d]", padId, large_motor, small_motor);
return;
}
if (!dev->has_rumble)
{
evdev_log.error("evdev TestVibration: Device [%s] does not support rumble features! [large_motor = %d] [small_motor = %d]", padId, large_motor, small_motor);
return;
}
SetRumble(static_cast<EvdevDevice*>(dev.get()), large_motor, small_motor);
}
std::vector<pad_list_entry> evdev_joystick_handler::list_devices()
{
Init();
std::unordered_map<std::string, u32> unique_names;
std::vector<pad_list_entry> evdev_joystick_list;
for (auto&& et : fs::dir{"/dev/input/"})
{
// Check if the entry starts with event (a 5-letter word)
if (et.name.size() > 5 && et.name.starts_with("event"))
{
const int fd = open(("/dev/input/" + et.name).c_str(), O_RDONLY | O_NONBLOCK);
struct libevdev* dev = NULL;
const int rc = libevdev_new_from_fd(fd, &dev);
if (rc < 0)
{
// If it's just a bad file descriptor, don't bother logging, but otherwise, log it.
if (rc != -9)
evdev_log.warning("Failed to connect to device at %s, the error was: %s", "/dev/input/" + et.name, strerror(-rc));
libevdev_free(dev);
close(fd);
continue;
}
if (libevdev_has_event_type(dev, EV_ABS))
{
bool is_motion_device = false;
bool is_pad_device = libevdev_has_event_type(dev, EV_KEY);
if (!is_pad_device)
{
// Check if it's a motion device.
is_motion_device = libevdev_has_property(dev, INPUT_PROP_ACCELEROMETER);
}
if (is_pad_device || is_motion_device)
{
// It's a joystick or motion device.
std::string name = get_device_name(dev);
if (unique_names.find(name) == unique_names.end())
unique_names.emplace(name, 1);
else
name = fmt::format("%d. %s", ++unique_names[name], name);
evdev_joystick_list.emplace_back(name, is_motion_device);
}
}
libevdev_free(dev);
close(fd);
}
}
return evdev_joystick_list;
}
std::shared_ptr<evdev_joystick_handler::EvdevDevice> evdev_joystick_handler::add_device(const std::string& device, bool in_settings)
{
if (in_settings && m_settings_added.count(device))
return ::at32(m_settings_added, device);
// Now we need to find the device with the same name, and make sure not to grab any duplicates.
std::unordered_map<std::string, u32> unique_names;
for (auto&& et : fs::dir{"/dev/input/"})
{
// Check if the entry starts with event (a 5-letter word)
if (et.name.size() > 5 && et.name.starts_with("event"))
{
const std::string path = "/dev/input/" + et.name;
const int fd = open(path.c_str(), O_RDWR | O_NONBLOCK);
struct libevdev* dev = NULL;
const int rc = libevdev_new_from_fd(fd, &dev);
if (rc < 0)
{
// If it's just a bad file descriptor, don't bother logging, but otherwise, log it.
if (rc != -9)
evdev_log.warning("Failed to connect to device at %s, the error was: %s", path, strerror(-rc));
libevdev_free(dev);
close(fd);
continue;
}
std::string name = get_device_name(dev);
if (unique_names.find(name) == unique_names.end())
unique_names.emplace(name, 1);
else
name = fmt::format("%d. %s", ++unique_names[name], name);
if (name == device &&
libevdev_has_event_type(dev, EV_KEY) &&
libevdev_has_event_type(dev, EV_ABS))
{
// It's a joystick.
if (in_settings)
{
m_dev = std::make_shared<EvdevDevice>();
m_settings_added[device] = m_dev;
// Let's log axis information while we are in the settings in order to identify problems more easily.
for (const auto& [code, axis_name] : axis_list)
{
if (const input_absinfo *info = libevdev_get_abs_info(dev, code))
{
const char* code_name = libevdev_event_code_get_name(EV_ABS, code);
evdev_log.notice("Axis info for %s: %s (%s) => minimum=%d, maximum=%d, fuzz=%d, flat=%d, resolution=%d",
name, code_name, axis_name, info->minimum, info->maximum, info->fuzz, info->flat, info->resolution);
}
}
}
// Alright, now that we've confirmed we haven't added this joystick yet, les do dis.
m_dev->device = dev;
m_dev->path = path;
m_dev->has_rumble = libevdev_has_event_type(dev, EV_FF);
m_dev->has_motion = libevdev_has_property(dev, INPUT_PROP_ACCELEROMETER);
evdev_log.notice("Capability info for %s: rumble=%d, motion=%d", name, m_dev->has_rumble, m_dev->has_motion);
return m_dev;
}
libevdev_free(dev);
close(fd);
}
}
return nullptr;
}
std::shared_ptr<evdev_joystick_handler::EvdevDevice> evdev_joystick_handler::add_motion_device(const std::string& device, bool in_settings)
{
if (device.empty())
return nullptr;
if (in_settings && m_motion_settings_added.count(device))
return ::at32(m_motion_settings_added, device);
// Now we need to find the device with the same name, and make sure not to grab any duplicates.
std::unordered_map<std::string, u32> unique_names;
for (auto&& et : fs::dir{"/dev/input/"})
{
// Check if the entry starts with event (a 5-letter word)
if (et.name.size() > 5 && et.name.starts_with("event"))
{
const std::string path = "/dev/input/" + et.name;
const int fd = open(path.c_str(), O_RDWR | O_NONBLOCK);
struct libevdev* dev = NULL;
const int rc = libevdev_new_from_fd(fd, &dev);
if (rc < 0)
{
// If it's just a bad file descriptor, don't bother logging, but otherwise, log it.
if (rc != -9)
evdev_log.warning("Failed to connect to device at %s, the error was: %s", path, strerror(-rc));
libevdev_free(dev);
close(fd);
continue;
}
std::string name = get_device_name(dev);
if (unique_names.find(name) == unique_names.end())
unique_names.emplace(name, 1);
else
name = fmt::format("%d. %s", ++unique_names[name], name);
if (name == device &&
libevdev_has_property(dev, INPUT_PROP_ACCELEROMETER) &&
libevdev_has_event_type(dev, EV_ABS))
{
// Let's log axis information while we are in the settings in order to identify problems more easily.
// Directional axes on this device (absolute and/or relative x, y, z) represent accelerometer data.
// Some devices also report gyroscope data, which devices can report through the rotational axes (absolute and/or relative rx, ry, rz).
// All other axes retain their meaning.
// A device must not mix regular directional axes and accelerometer axes on the same event node.
for (const auto& [code, axis_name] : axis_list)
{
if (const input_absinfo *info = libevdev_get_abs_info(dev, code))
{
const bool is_accel = code == ABS_X || code == ABS_Y || code == ABS_Z;
const char* code_name = libevdev_event_code_get_name(EV_ABS, code);
evdev_log.notice("Axis info for %s: %s (%s, %s) => minimum=%d, maximum=%d, fuzz=%d, flat=%d, resolution=%d",
name, code_name, axis_name, is_accel ? "accelerometer" : "gyro", info->minimum, info->maximum, info->fuzz, info->flat, info->resolution);
}
}
std::shared_ptr<EvdevDevice> motion_device = std::make_shared<EvdevDevice>();
motion_device->device = dev;
motion_device->path = path;
motion_device->has_motion = true;
if (in_settings)
{
m_motion_settings_added[device] = motion_device;
}
return motion_device;
}
libevdev_free(dev);
close(fd);
}
}
return nullptr;
}
PadHandlerBase::connection evdev_joystick_handler::update_connection(const std::shared_ptr<PadDevice>& device)
{
if (!update_device(device))
return connection::disconnected;
EvdevDevice* evdev_device = static_cast<EvdevDevice*>(device.get());
if (!evdev_device || !evdev_device->device)
return connection::disconnected;
return connection::connected;
}
void evdev_joystick_handler::get_mapping(const pad_ensemble& binding)
{
m_dev = std::static_pointer_cast<EvdevDevice>(binding.device);
const auto& pad = binding.pad;
if (!m_dev || !pad)
return;
libevdev* dev = m_dev->device;
if (!dev)
return;
// Try to fetch all new events from the joystick.
bool got_changes = false;
input_event evt;
int ret = LIBEVDEV_READ_STATUS_SUCCESS;
while (ret >= 0)
{
if (ret == LIBEVDEV_READ_STATUS_SYNC)
{
// Grab any pending sync event.
ret = libevdev_next_event(dev, LIBEVDEV_READ_FLAG_NORMAL | LIBEVDEV_READ_FLAG_SYNC, &evt);
}
else
{
ret = libevdev_next_event(dev, LIBEVDEV_READ_FLAG_NORMAL, &evt);
}
if (ret == LIBEVDEV_READ_STATUS_SUCCESS)
{
switch (evt.type)
{
case EV_KEY:
{
auto& wrapper = m_dev->events_by_code[evt.code];
if (!wrapper)
{
wrapper.reset(new key_event_wrapper());
}
key_event_wrapper* key_wrapper = static_cast<key_event_wrapper*>(wrapper.get());
if (!key_wrapper->is_initialized)
{
if (!button_list.contains(evt.code))
{
evdev_log.error("Evdev button %s (%d) is unknown. Please add it to the button list.", libevdev_event_code_get_name(EV_KEY, evt.code), evt.code);
}
key_wrapper->is_initialized = true;
}
const u16 new_value = evt.value > 0 ? 255 : 0;
if (key_wrapper->value != new_value)
{
key_wrapper->value = new_value;
got_changes = true;
}
break;
}
case EV_ABS:
{
auto& wrapper = m_dev->events_by_code[evt.code];
if (!wrapper)
{
wrapper.reset(new axis_event_wrapper());
}
axis_event_wrapper* axis_wrapper = static_cast<axis_event_wrapper*>(wrapper.get());
if (!axis_wrapper->is_initialized)
{
axis_wrapper->min = libevdev_get_abs_minimum(dev, evt.code);
axis_wrapper->max = libevdev_get_abs_maximum(dev, evt.code);
axis_wrapper->flat = libevdev_get_abs_flat(dev, evt.code);
axis_wrapper->is_initialized = true;
// Triggers do not need handling of negative values
if (axis_wrapper->min >= 0 && !m_positive_axis.contains(evt.code))
{
axis_wrapper->is_trigger = true;
}
}
// Triggers do not need handling of negative values
if (axis_wrapper->is_trigger)
{
const u16 new_value = static_cast<u16>(ScaledInput(evt.value, axis_wrapper->min, axis_wrapper->max, axis_wrapper->flat));
u16& key_value = axis_wrapper->values[false];
if (key_value != new_value)
{
key_value = new_value;
got_changes = true;
}
}
else
{
const float fvalue = ScaledAxisInput(evt.value, axis_wrapper->min, axis_wrapper->max, axis_wrapper->flat);
const bool is_negative = fvalue < 0;
const u16 new_value_0 = static_cast<u16>(std::abs(fvalue));
const u16 new_value_1 = 0; // We need to reset the other direction of this axis
u16& key_value_0 = axis_wrapper->values[is_negative];
u16& key_value_1 = axis_wrapper->values[!is_negative];
if (key_value_0 != new_value_0 || key_value_1 != new_value_1)
{
key_value_0 = new_value_0;
key_value_1 = new_value_1;
got_changes = true;
}
}
break;
}
default:
break;
}
}
}
if (ret < 0)
{
// -EAGAIN signifies no available events, not an actual *error*.
if (ret != -EAGAIN)
evdev_log.error("Failed to read latest event from joystick: %s [errno %d]", strerror(-ret), -ret);
}
// Apply all events
if (got_changes)
{
apply_input_events(pad);
}
}
void evdev_joystick_handler::get_extended_info(const pad_ensemble& binding)
{
// We use this to get motion controls from our buddy device
const auto& device = std::static_pointer_cast<EvdevDevice>(binding.buddy_device);
const auto& pad = binding.pad;
if (!pad || !device || !update_device(device))
return;
libevdev* dev = device->device;
if (!dev)
return;
// Try to fetch all new events from the joystick.
input_event evt;
int ret = LIBEVDEV_READ_STATUS_SUCCESS;
while (ret >= 0)
{
if (ret == LIBEVDEV_READ_STATUS_SYNC)
{
// Grab any pending sync event.
ret = libevdev_next_event(dev, LIBEVDEV_READ_FLAG_NORMAL | LIBEVDEV_READ_FLAG_SYNC, &evt);
}
else
{
ret = libevdev_next_event(dev, LIBEVDEV_READ_FLAG_NORMAL, &evt);
}
if (ret == LIBEVDEV_READ_STATUS_SUCCESS && evt.type == EV_ABS)
{
for (AnalogSensor& sensor : pad->m_sensors)
{
if (sensor.m_keyCode != evt.code)
continue;
sensor.m_value = get_sensor_value(dev, sensor, evt);
}
}
}
if (ret < 0)
{
// -EAGAIN signifies no available events, not an actual *error*.
if (ret != -EAGAIN)
evdev_log.error("Failed to read latest event from buddy device: %s [errno %d]", strerror(-ret), -ret);
}
}
u16 evdev_joystick_handler::get_sensor_value(const libevdev* dev, const AnalogSensor& sensor, const input_event& evt) const
{
if (dev)
{
const int min = libevdev_get_abs_minimum(dev, evt.code);
const int max = libevdev_get_abs_maximum(dev, evt.code);
const int flat = libevdev_get_abs_flat(dev, evt.code);
s16 value = ScaledInput(evt.value, min, max, flat, 1023.0f);
if (sensor.m_mirrored)
{
value = 1023 - value;
}
return Clamp0To1023(value + sensor.m_shift);
}
return 0;
}
void evdev_joystick_handler::apply_input_events(const std::shared_ptr<Pad>& pad)
{
if (!pad)
return;
const cfg_pad* cfg = m_dev->config;
if (!cfg)
return;
// Find out if special buttons are pressed (introduced by RPCS3).
// These buttons will have a delay of one cycle, but whatever.
const bool analog_limiter_enabled = pad->get_analog_limiter_button_active(cfg->analog_limiter_toggle_mode.get(), pad->m_player_id);
const bool adjust_pressure = pad->get_pressure_intensity_button_active(cfg->pressure_intensity_toggle_mode.get(), pad->m_player_id);
const u32 pressure_intensity_deadzone = cfg->pressure_intensity_deadzone.get();
const auto update_values = [&](bool& pressed, u16& final_value, bool is_stick_value, u32 code, u16 val)
{
bool press{};
TranslateButtonPress(m_dev, code, press, val, analog_limiter_enabled, is_stick_value);
if (press)
{
if (!is_stick_value)
{
// Modify pressure if necessary if the button was pressed
if (adjust_pressure)
{
val = pad->m_pressure_intensity;
}
else if (pressure_intensity_deadzone > 0)
{
// Ignore triggers, since they have their own deadzones
if (!get_is_left_trigger(m_dev, code) && !get_is_right_trigger(m_dev, code))
{
val = NormalizeDirectedInput(val, pressure_intensity_deadzone, 255);
}
}
}
final_value = std::max(final_value, val);
pressed = final_value > 0;
}
};
const auto process_mapped_button = [&](u32 index, bool& pressed, u16& final_value, bool is_stick_value)
{
const EvdevButton& evdev_button = ::at32(m_dev->all_buttons, index);
auto& wrapper = m_dev->events_by_code[evdev_button.code];
if (!wrapper || !wrapper->is_initialized)
{
return;
}
// We need to set the current direction and type for TranslateButtonPress
m_dev->cur_type = wrapper->type;
m_dev->cur_dir = evdev_button.dir;
switch (wrapper->type)
{
case EV_KEY:
{
key_event_wrapper* key_wrapper = static_cast<key_event_wrapper*>(wrapper.get());
update_values(pressed, final_value, is_stick_value, evdev_button.code, key_wrapper->value);
break;
}
case EV_ABS: // Be careful to handle mapped axis specially
{
if (evdev_button.dir < 0)
{
evdev_log.error("Invalid axis direction = %d, Button Nr.%d", evdev_button.dir, index);
break;
}
axis_event_wrapper* axis_wrapper = static_cast<axis_event_wrapper*>(wrapper.get());
if (is_stick_value && axis_wrapper->is_trigger)
{
update_values(pressed, final_value, is_stick_value, evdev_button.code, axis_wrapper->values[false]);
break;
}
for (const auto& [is_negative, value] : axis_wrapper->values)
{
// Only set value if the stick / hat is actually pointing to the correct direction.
if (is_negative == (evdev_button.dir == 1))
{
update_values(pressed, final_value, is_stick_value, evdev_button.code, value);
}
}
break;
}
default:
fmt::throw_exception("Unknown evdev input_event_wrapper type: %d", wrapper->type);
}
};
// Translate any corresponding keycodes to our normal DS3 buttons and triggers
for (Button& button : pad->m_buttons)
{
bool pressed{};
u16 final_value{};
for (u32 index : button.m_key_codes)
{
process_mapped_button(index, pressed, final_value, false);
}
button.m_value = final_value;
button.m_pressed = pressed;
}
// used to get the absolute value of an axis
s32 stick_val[4]{};
// Translate any corresponding keycodes to our two sticks. (ignoring thresholds for now)
for (usz i = 0; i < pad->m_sticks.size(); i++)
{
bool pressed{}; // unused
u16 val_min{};
u16 val_max{};
// m_key_codes_min are the mapped keys for left or down
for (u32 index : pad->m_sticks[i].m_key_codes_min)
{
process_mapped_button(index, pressed, val_min, true);
}
// m_key_codes_max are the mapped keys for right or up
for (u32 index : pad->m_sticks[i].m_key_codes_max)
{
process_mapped_button(index, pressed, val_max, true);
}
// cancel out opposing values and get the resulting difference. if there was no change, use the old value.
stick_val[i] = val_max - val_min;
}
u16 lx, ly, rx, ry;
// Normalize and apply pad squircling
convert_stick_values(lx, ly, stick_val[0], stick_val[1], cfg->lstickdeadzone, cfg->lstick_anti_deadzone, cfg->lpadsquircling);
convert_stick_values(rx, ry, stick_val[2], stick_val[3], cfg->rstickdeadzone, cfg->rstick_anti_deadzone, cfg->rpadsquircling);
pad->m_sticks[0].m_value = lx;
pad->m_sticks[1].m_value = 255 - ly;
pad->m_sticks[2].m_value = rx;
pad->m_sticks[3].m_value = 255 - ry;
}
void evdev_joystick_handler::apply_pad_data(const pad_ensemble& binding)
{
const auto& device = binding.device;
const auto& pad = binding.pad;
EvdevDevice* evdev_device = static_cast<EvdevDevice*>(device.get());
if (!evdev_device)
return;
cfg_pad* cfg = device->config;
if (!cfg)
return;
// Handle vibration
const int idx_l = cfg->switch_vibration_motors ? 1 : 0;
const int idx_s = cfg->switch_vibration_motors ? 0 : 1;
const u8 force_large = cfg->enable_vibration_motor_large ? pad->m_vibrateMotors[idx_l].m_value * 257 : 0;
const u8 force_small = cfg->enable_vibration_motor_small ? pad->m_vibrateMotors[idx_s].m_value * 257 : 0;
SetRumble(evdev_device, force_large, force_small);
}
bool evdev_joystick_handler::bindPadToDevice(std::shared_ptr<Pad> pad)
{
if (!pad || pad->m_player_id >= g_cfg_input.player.size())
return false;
const cfg_player* player_config = g_cfg_input.player[pad->m_player_id];
if (!pad)
return false;
Init();
m_dev = std::make_shared<EvdevDevice>();
m_pad_configs[pad->m_player_id].from_string(player_config->config.to_string());
m_dev->config = &m_pad_configs[pad->m_player_id];
m_dev->player_id = pad->m_player_id;
cfg_pad* cfg = m_dev->config;
if (!cfg)
return false;
// We need to register EvdevButtons due to their axis directions.
const auto register_evdevbutton = [this](u32 code, bool is_axis, bool is_reverse) -> u32
{
const u32 index = ::narrow<u32>(m_dev->all_buttons.size());
if (is_axis)
{
m_dev->all_buttons.push_back(EvdevButton{ code, is_reverse ? 1 : 0, EV_ABS });
}
else
{
m_dev->all_buttons.push_back(EvdevButton{ code, -1, EV_KEY });
}
return index;
};
const auto find_buttons = [&](const cfg::string& name) -> std::set<u32>
{
const std::vector<std::string> names = cfg_pad::get_buttons(name);
// In evdev we store indices to an EvdevButton vector in our pad objects instead of the usual key codes.
std::set<u32> indices;
for (const u32 code : FindKeyCodes<u32, u32>(axis_list, names))
{
indices.insert(register_evdevbutton(code, true, false));
}
for (const u32 code : FindKeyCodes<u32, u32>(rev_axis_list, names))
{
indices.insert(register_evdevbutton(code, true, true));
}
for (const u32 code : FindKeyCodes<u32, u32>(button_list, names))
{
indices.insert(register_evdevbutton(code, false, false));
}
return indices;
};
const auto find_motion_button = [&](const cfg_sensor& sensor) -> evdev_sensor
{
evdev_sensor e_sensor{};
e_sensor.type = EV_ABS;
e_sensor.mirrored = sensor.mirrored.get();
e_sensor.shift = sensor.shift.get();
const std::set<u32> keys = FindKeyCodes<u32, u32>(motion_axis_list, sensor.axis);
if (!keys.empty()) e_sensor.code = *keys.begin(); // We should only have one key for each of our sensors
return e_sensor;
};
u32 pclass_profile = 0x0;
for (const input::product_info& product : input::get_products_by_class(cfg->device_class_type))
{
if (product.vendor_id == cfg->vendor_id && product.product_id == cfg->product_id)
{
pclass_profile = product.pclass_profile;
}
}
pad->Init
(
CELL_PAD_STATUS_DISCONNECTED,
CELL_PAD_CAPABILITY_PS3_CONFORMITY | CELL_PAD_CAPABILITY_PRESS_MODE | CELL_PAD_CAPABILITY_HP_ANALOG_STICK | CELL_PAD_CAPABILITY_ACTUATOR | CELL_PAD_CAPABILITY_SENSOR_MODE,
CELL_PAD_DEV_TYPE_STANDARD,
cfg->device_class_type,
pclass_profile,
cfg->vendor_id,
cfg->product_id,
cfg->pressure_intensity
);
if (b_has_pressure_intensity_button)
{
pad->m_buttons.emplace_back(special_button_offset, find_buttons(cfg->pressure_intensity_button), special_button_value::pressure_intensity);
pad->m_pressure_intensity_button_index = static_cast<s32>(pad->m_buttons.size()) - 1;
}
if (b_has_analog_limiter_button)
{
pad->m_buttons.emplace_back(special_button_offset, find_buttons(cfg->analog_limiter_button), special_button_value::analog_limiter);
pad->m_analog_limiter_button_index = static_cast<s32>(pad->m_buttons.size()) - 1;
}
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL2,find_buttons(cfg->triangle), CELL_PAD_CTRL_TRIANGLE);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL2,find_buttons(cfg->circle), CELL_PAD_CTRL_CIRCLE);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL2,find_buttons(cfg->cross), CELL_PAD_CTRL_CROSS);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL2,find_buttons(cfg->square), CELL_PAD_CTRL_SQUARE);
m_dev->trigger_left = find_buttons(cfg->l2);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL2, m_dev->trigger_left, CELL_PAD_CTRL_L2);
m_dev->trigger_right = find_buttons(cfg->r2);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL2, m_dev->trigger_right, CELL_PAD_CTRL_R2);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL2, find_buttons(cfg->l1), CELL_PAD_CTRL_L1);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL2, find_buttons(cfg->r1), CELL_PAD_CTRL_R1);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL1, find_buttons(cfg->start), CELL_PAD_CTRL_START);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL1, find_buttons(cfg->select), CELL_PAD_CTRL_SELECT);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL1, find_buttons(cfg->l3), CELL_PAD_CTRL_L3);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL1, find_buttons(cfg->r3), CELL_PAD_CTRL_R3);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL1, find_buttons(cfg->ps), CELL_PAD_CTRL_PS);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL1, find_buttons(cfg->up), CELL_PAD_CTRL_UP);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL1, find_buttons(cfg->down), CELL_PAD_CTRL_DOWN);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL1, find_buttons(cfg->left), CELL_PAD_CTRL_LEFT);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL1, find_buttons(cfg->right), CELL_PAD_CTRL_RIGHT);
if (pad->m_class_type == CELL_PAD_PCLASS_TYPE_SKATEBOARD)
{
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_PRESS_PIGGYBACK, find_buttons(cfg->ir_nose), CELL_PAD_CTRL_PRESS_TRIANGLE);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_PRESS_PIGGYBACK, find_buttons(cfg->ir_tail), CELL_PAD_CTRL_PRESS_CIRCLE);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_PRESS_PIGGYBACK, find_buttons(cfg->ir_left), CELL_PAD_CTRL_PRESS_CROSS);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_PRESS_PIGGYBACK, find_buttons(cfg->ir_right), CELL_PAD_CTRL_PRESS_SQUARE);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_PRESS_PIGGYBACK, find_buttons(cfg->tilt_left), CELL_PAD_CTRL_PRESS_L1);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_PRESS_PIGGYBACK, find_buttons(cfg->tilt_right), CELL_PAD_CTRL_PRESS_R1);
}
m_dev->axis_left[0] = find_buttons(cfg->ls_right);
m_dev->axis_left[1] = find_buttons(cfg->ls_left);
m_dev->axis_left[2] = find_buttons(cfg->ls_up);
m_dev->axis_left[3] = find_buttons(cfg->ls_down);
m_dev->axis_right[0] = find_buttons(cfg->rs_right);
m_dev->axis_right[1] = find_buttons(cfg->rs_left);
m_dev->axis_right[2] = find_buttons(cfg->rs_up);
m_dev->axis_right[3] = find_buttons(cfg->rs_down);
pad->m_sticks[0] = AnalogStick(CELL_PAD_BTN_OFFSET_ANALOG_LEFT_X, m_dev->axis_left[1], m_dev->axis_left[0]);
pad->m_sticks[1] = AnalogStick(CELL_PAD_BTN_OFFSET_ANALOG_LEFT_Y, m_dev->axis_left[3], m_dev->axis_left[2]);
pad->m_sticks[2] = AnalogStick(CELL_PAD_BTN_OFFSET_ANALOG_RIGHT_X, m_dev->axis_right[1], m_dev->axis_right[0]);
pad->m_sticks[3] = AnalogStick(CELL_PAD_BTN_OFFSET_ANALOG_RIGHT_Y, m_dev->axis_right[3], m_dev->axis_right[2]);
m_dev->axis_motion[0] = find_motion_button(cfg->motion_sensor_x);
m_dev->axis_motion[1] = find_motion_button(cfg->motion_sensor_y);
m_dev->axis_motion[2] = find_motion_button(cfg->motion_sensor_z);
m_dev->axis_motion[3] = find_motion_button(cfg->motion_sensor_g);
pad->m_sensors[0] = AnalogSensor(CELL_PAD_BTN_OFFSET_SENSOR_X, m_dev->axis_motion[0].code, m_dev->axis_motion[0].mirrored, m_dev->axis_motion[0].shift, DEFAULT_MOTION_X);
pad->m_sensors[1] = AnalogSensor(CELL_PAD_BTN_OFFSET_SENSOR_Y, m_dev->axis_motion[1].code, m_dev->axis_motion[1].mirrored, m_dev->axis_motion[1].shift, DEFAULT_MOTION_Y);
pad->m_sensors[2] = AnalogSensor(CELL_PAD_BTN_OFFSET_SENSOR_Z, m_dev->axis_motion[2].code, m_dev->axis_motion[2].mirrored, m_dev->axis_motion[2].shift, DEFAULT_MOTION_Z);
pad->m_sensors[3] = AnalogSensor(CELL_PAD_BTN_OFFSET_SENSOR_G, m_dev->axis_motion[3].code, m_dev->axis_motion[3].mirrored, m_dev->axis_motion[3].shift, DEFAULT_MOTION_G);
pad->m_vibrateMotors[0] = VibrateMotor(true, 0);
pad->m_vibrateMotors[1] = VibrateMotor(false, 0);
if (std::shared_ptr<EvdevDevice> evdev_device = add_device(player_config->device, false))
{
if (std::shared_ptr<EvdevDevice> motion_device = add_motion_device(player_config->buddy_device, false))
{
m_bindings.emplace_back(pad, evdev_device, motion_device);
}
else
{
m_bindings.emplace_back(pad, evdev_device, nullptr);
if (const std::string buddy_device_name = player_config->buddy_device.to_string(); buddy_device_name != "Null")
{
evdev_log.warning("evdev add_motion_device in bindPadToDevice failed for device %s", buddy_device_name);
}
}
}
else
{
evdev_log.warning("evdev add_device in bindPadToDevice failed for device %s", player_config->device.to_string());
}
for (pad_ensemble& binding : m_bindings)
{
update_device(binding.device);
update_device(binding.buddy_device);
}
return true;
}
bool evdev_joystick_handler::check_button_set(const std::set<u32>& indices, const u32 code)
{
if (!m_dev)
return false;
for (u32 index : indices)
{
const EvdevButton& button = ::at32(m_dev->all_buttons, index);
if (button.code == code && button.type == m_dev->cur_type && button.dir == m_dev->cur_dir)
{
return true;
}
}
return false;
}
bool evdev_joystick_handler::check_button_sets(const std::array<std::set<u32>, 4>& sets, const u32 code)
{
return std::any_of(sets.begin(), sets.end(), [this, code](const std::set<u32>& indices) { return check_button_set(indices, code); });
};
bool evdev_joystick_handler::get_is_left_trigger(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
return check_button_set(m_dev->trigger_left, static_cast<u32>(keyCode));
}
bool evdev_joystick_handler::get_is_right_trigger(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
return check_button_set(m_dev->trigger_right, static_cast<u32>(keyCode));
}
bool evdev_joystick_handler::get_is_left_stick(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
return check_button_sets(m_dev->axis_left, static_cast<u32>(keyCode));
}
bool evdev_joystick_handler::get_is_right_stick(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
return check_button_sets(m_dev->axis_right, static_cast<u32>(keyCode));
}
#endif
| 47,751
|
C++
|
.cpp
| 1,255
| 34.819124
| 234
| 0.679911
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,010
|
xinput_pad_handler.cpp
|
RPCS3_rpcs3/rpcs3/Input/xinput_pad_handler.cpp
|
#ifdef _WIN32
#include "stdafx.h"
#include "xinput_pad_handler.h"
#include "Emu/Io/pad_config.h"
namespace XINPUT_INFO
{
const DWORD GUIDE_BUTTON = 0x0400;
const LPCWSTR LIBRARY_FILENAMES[] = {
L"xinput1_3.dll", // Prioritizing 1_3 because of SCP
L"xinput1_4.dll",
L"xinput9_1_0.dll"
};
} // namespace XINPUT_INFO
xinput_pad_handler::xinput_pad_handler() : PadHandlerBase(pad_handler::xinput)
{
// Unique names for the config files and our pad settings dialog
button_list =
{
{ XInputKeyCodes::None, "" },
{ XInputKeyCodes::A, "A" },
{ XInputKeyCodes::B, "B" },
{ XInputKeyCodes::X, "X" },
{ XInputKeyCodes::Y, "Y" },
{ XInputKeyCodes::Left, "Left" },
{ XInputKeyCodes::Right, "Right" },
{ XInputKeyCodes::Up, "Up" },
{ XInputKeyCodes::Down, "Down" },
{ XInputKeyCodes::LB, "LB" },
{ XInputKeyCodes::RB, "RB" },
{ XInputKeyCodes::Back, "Back" },
{ XInputKeyCodes::Start, "Start" },
{ XInputKeyCodes::LS, "LS" },
{ XInputKeyCodes::RS, "RS" },
{ XInputKeyCodes::Guide, "Guide" },
{ XInputKeyCodes::LT, "LT" },
{ XInputKeyCodes::RT, "RT" },
{ XInputKeyCodes::LT_Pos, "LT+" },
{ XInputKeyCodes::LT_Neg, "LT-" },
{ XInputKeyCodes::RT_Pos, "RT+" },
{ XInputKeyCodes::RT_Neg, "RT-" },
{ XInputKeyCodes::LSXNeg, "LS X-" },
{ XInputKeyCodes::LSXPos, "LS X+" },
{ XInputKeyCodes::LSYPos, "LS Y+" },
{ XInputKeyCodes::LSYNeg, "LS Y-" },
{ XInputKeyCodes::RSXNeg, "RS X-" },
{ XInputKeyCodes::RSXPos, "RS X+" },
{ XInputKeyCodes::RSYPos, "RS Y+" },
{ XInputKeyCodes::RSYNeg, "RS Y-" }
};
init_configs();
// Define border values
thumb_max = 32767;
trigger_min = 0;
trigger_max = 255;
// set capabilities
b_has_config = true;
b_has_rumble = true;
b_has_deadzones = true;
b_has_battery = true;
b_has_battery_led = false;
m_name_string = "XInput Pad #";
m_max_devices = XUSER_MAX_COUNT;
m_trigger_threshold = trigger_max / 2;
m_thumb_threshold = thumb_max / 2;
}
xinput_pad_handler::~xinput_pad_handler()
{
if (library)
{
FreeLibrary(library);
library = nullptr;
xinputGetExtended = nullptr;
xinputGetCustomData = nullptr;
xinputGetState = nullptr;
xinputSetState = nullptr;
xinputGetBatteryInformation = nullptr;
}
}
void xinput_pad_handler::init_config(cfg_pad* cfg)
{
if (!cfg) return;
// Set default button mapping
cfg->ls_left.def = ::at32(button_list, XInputKeyCodes::LSXNeg);
cfg->ls_down.def = ::at32(button_list, XInputKeyCodes::LSYNeg);
cfg->ls_right.def = ::at32(button_list, XInputKeyCodes::LSXPos);
cfg->ls_up.def = ::at32(button_list, XInputKeyCodes::LSYPos);
cfg->rs_left.def = ::at32(button_list, XInputKeyCodes::RSXNeg);
cfg->rs_down.def = ::at32(button_list, XInputKeyCodes::RSYNeg);
cfg->rs_right.def = ::at32(button_list, XInputKeyCodes::RSXPos);
cfg->rs_up.def = ::at32(button_list, XInputKeyCodes::RSYPos);
cfg->start.def = ::at32(button_list, XInputKeyCodes::Start);
cfg->select.def = ::at32(button_list, XInputKeyCodes::Back);
cfg->ps.def = ::at32(button_list, XInputKeyCodes::Guide);
cfg->square.def = ::at32(button_list, XInputKeyCodes::X);
cfg->cross.def = ::at32(button_list, XInputKeyCodes::A);
cfg->circle.def = ::at32(button_list, XInputKeyCodes::B);
cfg->triangle.def = ::at32(button_list, XInputKeyCodes::Y);
cfg->left.def = ::at32(button_list, XInputKeyCodes::Left);
cfg->down.def = ::at32(button_list, XInputKeyCodes::Down);
cfg->right.def = ::at32(button_list, XInputKeyCodes::Right);
cfg->up.def = ::at32(button_list, XInputKeyCodes::Up);
cfg->r1.def = ::at32(button_list, XInputKeyCodes::RB);
cfg->r2.def = ::at32(button_list, XInputKeyCodes::RT);
cfg->r3.def = ::at32(button_list, XInputKeyCodes::RS);
cfg->l1.def = ::at32(button_list, XInputKeyCodes::LB);
cfg->l2.def = ::at32(button_list, XInputKeyCodes::LT);
cfg->l3.def = ::at32(button_list, XInputKeyCodes::LS);
cfg->pressure_intensity_button.def = ::at32(button_list, XInputKeyCodes::None);
cfg->analog_limiter_button.def = ::at32(button_list, XInputKeyCodes::None);
// Set default misc variables
cfg->lstick_anti_deadzone.def = static_cast<u32>(0.13 * thumb_max); // 13%
cfg->rstick_anti_deadzone.def = static_cast<u32>(0.13 * thumb_max); // 13%
cfg->lstickdeadzone.def = XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE; // between 0 and 32767
cfg->rstickdeadzone.def = XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE; // between 0 and 32767
cfg->ltriggerthreshold.def = XINPUT_GAMEPAD_TRIGGER_THRESHOLD; // between 0 and 255
cfg->rtriggerthreshold.def = XINPUT_GAMEPAD_TRIGGER_THRESHOLD; // between 0 and 255
cfg->lpadsquircling.def = 8000;
cfg->rpadsquircling.def = 8000;
// apply defaults
cfg->from_default();
}
void xinput_pad_handler::SetPadData(const std::string& padId, u8 /*player_id*/, u8 large_motor, u8 small_motor, s32/* r*/, s32/* g*/, s32/* b*/, bool /*player_led*/, bool /*battery_led*/, u32 /*battery_led_brightness*/)
{
const int device_number = GetDeviceNumber(padId);
if (device_number < 0)
return;
// The left motor is the low-frequency rumble motor. The right motor is the high-frequency rumble motor.
// The two motors are not the same, and they create different vibration effects.
XINPUT_VIBRATION vibrate
{
.wLeftMotorSpeed = static_cast<u16>(large_motor * 257), // between 0 to 65535
.wRightMotorSpeed = static_cast<u16>(small_motor * 257) // between 0 to 65535
};
xinputSetState(static_cast<u32>(device_number), &vibrate);
}
u32 xinput_pad_handler::get_battery_level(const std::string& padId)
{
const int device_number = GetDeviceNumber(padId);
if (device_number < 0)
return 0;
// Receive Battery Info. If device is not on cable, get battery level, else assume full.
XINPUT_BATTERY_INFORMATION battery_info;
xinputGetBatteryInformation(device_number, BATTERY_DEVTYPE_GAMEPAD, &battery_info);
switch (battery_info.BatteryType)
{
case BATTERY_TYPE_DISCONNECTED:
return 0;
case BATTERY_TYPE_WIRED:
return 100;
default:
break;
}
switch (battery_info.BatteryLevel)
{
case BATTERY_LEVEL_EMPTY:
return 0;
case BATTERY_LEVEL_LOW:
return 33;
case BATTERY_LEVEL_MEDIUM:
return 66;
case BATTERY_LEVEL_FULL:
return 100;
default:
return 0;
}
}
int xinput_pad_handler::GetDeviceNumber(const std::string& padId)
{
if (!Init())
return -1;
const usz pos = padId.find(m_name_string);
if (pos == umax)
return -1;
const int device_number = std::stoul(padId.substr(pos + 12)) - 1; // Controllers 1-n in GUI
if (device_number >= XUSER_MAX_COUNT)
return -1;
return device_number;
}
std::unordered_map<u64, u16> xinput_pad_handler::get_button_values(const std::shared_ptr<PadDevice>& device)
{
PadButtonValues values;
XInputDevice* dev = static_cast<XInputDevice*>(device.get());
if (!dev || dev->state != ERROR_SUCCESS) // the state has to be aquired with update_connection before calling this function
return values;
// Try SCP first, if it fails for that pad then try normal XInput
if (dev->is_scp_device)
{
return get_button_values_scp(dev->state_scp, m_trigger_recognition_mode);
}
return get_button_values_base(dev->state_base, m_trigger_recognition_mode);
}
xinput_pad_handler::PadButtonValues xinput_pad_handler::get_button_values_base(const XINPUT_STATE& state, trigger_recognition_mode trigger_mode)
{
PadButtonValues values;
// Triggers
if (trigger_mode == trigger_recognition_mode::any || trigger_mode == trigger_recognition_mode::one_directional)
{
values[XInputKeyCodes::LT] = state.Gamepad.bLeftTrigger;
values[XInputKeyCodes::RT] = state.Gamepad.bRightTrigger;
}
if (trigger_mode == trigger_recognition_mode::any || trigger_mode == trigger_recognition_mode::two_directional)
{
const float lTrigger = state.Gamepad.bLeftTrigger / 255.0f;
const float rTrigger = state.Gamepad.bRightTrigger / 255.0f;
values[XInputKeyCodes::LT_Pos] = static_cast<u16>(lTrigger > 0.5f ? std::clamp((lTrigger - 0.5f) * 2.0f * 255.0f, 0.0f, 255.0f) : 0.0f);
values[XInputKeyCodes::LT_Neg] = static_cast<u16>(lTrigger < 0.5f ? std::clamp((0.5f - lTrigger) * 2.0f * 255.0f, 0.0f, 255.0f) : 0.0f);
values[XInputKeyCodes::RT_Pos] = static_cast<u16>(rTrigger > 0.5f ? std::clamp((rTrigger - 0.5f) * 2.0f * 255.0f, 0.0f, 255.0f) : 0.0f);
values[XInputKeyCodes::RT_Neg] = static_cast<u16>(rTrigger < 0.5f ? std::clamp((0.5f - rTrigger) * 2.0f * 255.0f, 0.0f, 255.0f) : 0.0f);
}
// Sticks
const int lx = state.Gamepad.sThumbLX;
const int ly = state.Gamepad.sThumbLY;
const int rx = state.Gamepad.sThumbRX;
const int ry = state.Gamepad.sThumbRY;
// Left Stick X Axis
values[XInputKeyCodes::LSXNeg] = lx < 0 ? abs(lx) - 1 : 0;
values[XInputKeyCodes::LSXPos] = lx > 0 ? lx : 0;
// Left Stick Y Axis
values[XInputKeyCodes::LSYNeg] = ly < 0 ? abs(ly) - 1 : 0;
values[XInputKeyCodes::LSYPos] = ly > 0 ? ly : 0;
// Right Stick X Axis
values[XInputKeyCodes::RSXNeg] = rx < 0 ? abs(rx) - 1 : 0;
values[XInputKeyCodes::RSXPos] = rx > 0 ? rx : 0;
// Right Stick Y Axis
values[XInputKeyCodes::RSYNeg] = ry < 0 ? abs(ry) - 1 : 0;
values[XInputKeyCodes::RSYPos] = ry > 0 ? ry : 0;
// Buttons
const WORD buttons = state.Gamepad.wButtons;
// A, B, X, Y
values[XInputKeyCodes::A] = buttons & XINPUT_GAMEPAD_A ? 255 : 0;
values[XInputKeyCodes::B] = buttons & XINPUT_GAMEPAD_B ? 255 : 0;
values[XInputKeyCodes::X] = buttons & XINPUT_GAMEPAD_X ? 255 : 0;
values[XInputKeyCodes::Y] = buttons & XINPUT_GAMEPAD_Y ? 255 : 0;
// D-Pad
values[XInputKeyCodes::Left] = buttons & XINPUT_GAMEPAD_DPAD_LEFT ? 255 : 0;
values[XInputKeyCodes::Right] = buttons & XINPUT_GAMEPAD_DPAD_RIGHT ? 255 : 0;
values[XInputKeyCodes::Up] = buttons & XINPUT_GAMEPAD_DPAD_UP ? 255 : 0;
values[XInputKeyCodes::Down] = buttons & XINPUT_GAMEPAD_DPAD_DOWN ? 255 : 0;
// LB, RB, LS, RS
values[XInputKeyCodes::LB] = buttons & XINPUT_GAMEPAD_LEFT_SHOULDER ? 255 : 0;
values[XInputKeyCodes::RB] = buttons & XINPUT_GAMEPAD_RIGHT_SHOULDER ? 255 : 0;
values[XInputKeyCodes::LS] = buttons & XINPUT_GAMEPAD_LEFT_THUMB ? 255 : 0;
values[XInputKeyCodes::RS] = buttons & XINPUT_GAMEPAD_RIGHT_THUMB ? 255 : 0;
// Start, Back, Guide
values[XInputKeyCodes::Start] = buttons & XINPUT_GAMEPAD_START ? 255 : 0;
values[XInputKeyCodes::Back] = buttons & XINPUT_GAMEPAD_BACK ? 255 : 0;
values[XInputKeyCodes::Guide] = buttons & XINPUT_INFO::GUIDE_BUTTON ? 255 : 0;
return values;
}
xinput_pad_handler::PadButtonValues xinput_pad_handler::get_button_values_scp(const SCP_EXTN& state, trigger_recognition_mode trigger_mode)
{
PadButtonValues values;
// Triggers
if (trigger_mode == trigger_recognition_mode::any || trigger_mode == trigger_recognition_mode::one_directional)
{
values[xinput_pad_handler::XInputKeyCodes::LT] = static_cast<u16>(state.SCP_L2 * 255.0f);
values[xinput_pad_handler::XInputKeyCodes::RT] = static_cast<u16>(state.SCP_R2 * 255.0f);
}
if (trigger_mode == trigger_recognition_mode::any || trigger_mode == trigger_recognition_mode::two_directional)
{
values[XInputKeyCodes::LT_Pos] = static_cast<u16>(state.SCP_L2 > 0.5f ? std::clamp((state.SCP_L2 - 0.5f) * 2.0f * 255.0f, 0.0f, 255.0f) : 0.0f);
values[XInputKeyCodes::LT_Neg] = static_cast<u16>(state.SCP_L2 < 0.5f ? std::clamp((0.5f - state.SCP_L2) * 2.0f * 255.0f, 0.0f, 255.0f) : 0.0f);
values[XInputKeyCodes::RT_Pos] = static_cast<u16>(state.SCP_R2 > 0.5f ? std::clamp((state.SCP_R2 - 0.5f) * 2.0f * 255.0f, 0.0f, 255.0f) : 0.0f);
values[XInputKeyCodes::RT_Neg] = static_cast<u16>(state.SCP_R2 < 0.5f ? std::clamp((0.5f - state.SCP_R2) * 2.0f * 255.0f, 0.0f, 255.0f) : 0.0f);
}
// Sticks
const float lx = state.SCP_LX;
const float ly = state.SCP_LY;
const float rx = state.SCP_RX;
const float ry = state.SCP_RY;
// Left Stick X Axis
values[xinput_pad_handler::XInputKeyCodes::LSXNeg] = lx < 0.0f ? static_cast<u16>(lx * -32768.0f) : 0;
values[xinput_pad_handler::XInputKeyCodes::LSXPos] = lx > 0.0f ? static_cast<u16>(lx * 32767.0f) : 0;
// Left Stick Y Axis
values[xinput_pad_handler::XInputKeyCodes::LSYNeg] = ly < 0.0f ? static_cast<u16>(ly * -32768.0f) : 0;
values[xinput_pad_handler::XInputKeyCodes::LSYPos] = ly > 0.0f ? static_cast<u16>(ly * 32767.0f) : 0;
// Right Stick X Axis
values[xinput_pad_handler::XInputKeyCodes::RSXNeg] = rx < 0.0f ? static_cast<u16>(rx * -32768.0f) : 0;
values[xinput_pad_handler::XInputKeyCodes::RSXPos] = rx > 0.0f ? static_cast<u16>(rx * 32767.0f) : 0;
// Right Stick Y Axis
values[xinput_pad_handler::XInputKeyCodes::RSYNeg] = ry < 0.0f ? static_cast<u16>(ry * -32768.0f) : 0;
values[xinput_pad_handler::XInputKeyCodes::RSYPos] = ry > 0.0f ? static_cast<u16>(ry * 32767.0f) : 0;
// A, B, X, Y
values[xinput_pad_handler::XInputKeyCodes::A] = static_cast<u16>(state.SCP_X * 255.0f);
values[xinput_pad_handler::XInputKeyCodes::B] = static_cast<u16>(state.SCP_C * 255.0f);
values[xinput_pad_handler::XInputKeyCodes::X] = static_cast<u16>(state.SCP_S * 255.0f);
values[xinput_pad_handler::XInputKeyCodes::Y] = static_cast<u16>(state.SCP_T * 255.0f);
// D-Pad
values[xinput_pad_handler::XInputKeyCodes::Left] = static_cast<u16>(state.SCP_LEFT * 255.0f);
values[xinput_pad_handler::XInputKeyCodes::Right] = static_cast<u16>(state.SCP_RIGHT * 255.0f);
values[xinput_pad_handler::XInputKeyCodes::Up] = static_cast<u16>(state.SCP_UP * 255.0f);
values[xinput_pad_handler::XInputKeyCodes::Down] = static_cast<u16>(state.SCP_DOWN * 255.0f);
// LB, RB, LS, RS
values[xinput_pad_handler::XInputKeyCodes::LB] = static_cast<u16>(state.SCP_L1 * 255.0f);
values[xinput_pad_handler::XInputKeyCodes::RB] = static_cast<u16>(state.SCP_R1 * 255.0f);
values[xinput_pad_handler::XInputKeyCodes::LS] = static_cast<u16>(state.SCP_L3 * 255.0f);
values[xinput_pad_handler::XInputKeyCodes::RS] = static_cast<u16>(state.SCP_R3 * 255.0f);
// Start, Back, Guide
values[xinput_pad_handler::XInputKeyCodes::Start] = static_cast<u16>(state.SCP_START * 255.0f);
values[xinput_pad_handler::XInputKeyCodes::Back] = static_cast<u16>(state.SCP_SELECT * 255.0f);
values[xinput_pad_handler::XInputKeyCodes::Guide] = static_cast<u16>(state.SCP_PS * 255.0f);
return values;
}
pad_preview_values xinput_pad_handler::get_preview_values(const std::unordered_map<u64, u16>& data)
{
return {
::at32(data, LT),
::at32(data, RT),
::at32(data, LSXPos) - ::at32(data, LSXNeg),
::at32(data, LSYPos) - ::at32(data, LSYNeg),
::at32(data, RSXPos) - ::at32(data, RSXNeg),
::at32(data, RSYPos) - ::at32(data, RSYNeg)
};
}
template<class T>
T getProc(HMODULE hModule, LPCSTR lpProcName)
{
return reinterpret_cast<T>(GetProcAddress(hModule, lpProcName));
}
bool xinput_pad_handler::Init()
{
if (m_is_init)
return true;
for (auto it : XINPUT_INFO::LIBRARY_FILENAMES)
{
library = LoadLibrary(it);
if (library)
{
xinputGetExtended = getProc<PFN_XINPUTGETEXTENDED>(library, "XInputGetExtended"); // Optional
xinputGetCustomData = getProc<PFN_XINPUTGETCUSTOMDATA>(library, "XInputGetCustomData"); // Optional
xinputGetState = getProc<PFN_XINPUTGETSTATE>(library, reinterpret_cast<LPCSTR>(100));
if (!xinputGetState)
xinputGetState = getProc<PFN_XINPUTGETSTATE>(library, "XInputGetState");
xinputSetState = getProc<PFN_XINPUTSETSTATE>(library, "XInputSetState");
xinputGetBatteryInformation = getProc<PFN_XINPUTGETBATTERYINFORMATION>(library, "XInputGetBatteryInformation");
if (xinputGetState && xinputSetState && xinputGetBatteryInformation)
{
m_is_init = true;
break;
}
FreeLibrary(library);
library = nullptr;
xinputGetExtended = nullptr;
xinputGetCustomData = nullptr;
xinputGetState = nullptr;
xinputSetState = nullptr;
xinputGetBatteryInformation = nullptr;
}
}
if (!m_is_init)
return false;
return true;
}
std::vector<pad_list_entry> xinput_pad_handler::list_devices()
{
std::vector<pad_list_entry> xinput_pads_list;
if (!Init())
return xinput_pads_list;
for (DWORD i = 0; i < XUSER_MAX_COUNT; i++)
{
DWORD result = ERROR_NOT_CONNECTED;
// Try SCP first, if it fails for that pad then try normal XInput
if (xinputGetExtended)
{
SCP_EXTN state;
result = xinputGetExtended(i, &state);
}
if (result != ERROR_SUCCESS)
{
XINPUT_STATE state;
result = xinputGetState(i, &state);
}
if (result == ERROR_SUCCESS)
xinput_pads_list.emplace_back(m_name_string + std::to_string(i + 1), false); // Controllers 1-n in GUI
}
return xinput_pads_list;
}
std::shared_ptr<PadDevice> xinput_pad_handler::get_device(const std::string& device)
{
// Convert device string to u32 representing xinput device number
const int device_number = GetDeviceNumber(device);
if (device_number < 0)
return nullptr;
std::shared_ptr<XInputDevice> dev = std::make_shared<XInputDevice>();
dev->deviceNumber = static_cast<u32>(device_number);
return dev;
}
bool xinput_pad_handler::get_is_left_trigger(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
return keyCode == XInputKeyCodes::LT;
}
bool xinput_pad_handler::get_is_right_trigger(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
return keyCode == XInputKeyCodes::RT;
}
bool xinput_pad_handler::get_is_left_stick(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
switch (keyCode)
{
case XInputKeyCodes::LSXNeg:
case XInputKeyCodes::LSXPos:
case XInputKeyCodes::LSYPos:
case XInputKeyCodes::LSYNeg:
return true;
default:
return false;
}
}
bool xinput_pad_handler::get_is_right_stick(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
switch (keyCode)
{
case XInputKeyCodes::RSXNeg:
case XInputKeyCodes::RSXPos:
case XInputKeyCodes::RSYPos:
case XInputKeyCodes::RSYNeg:
return true;
default:
return false;
}
}
PadHandlerBase::connection xinput_pad_handler::update_connection(const std::shared_ptr<PadDevice>& device)
{
XInputDevice* dev = static_cast<XInputDevice*>(device.get());
if (!dev)
return connection::disconnected;
dev->state = ERROR_NOT_CONNECTED;
dev->state_scp = {};
dev->state_base = {};
// Try SCP first, if it fails for that pad then try normal XInput
if (xinputGetExtended)
dev->state = xinputGetExtended(dev->deviceNumber, &dev->state_scp);
dev->is_scp_device = dev->state == ERROR_SUCCESS;
if (!dev->is_scp_device)
dev->state = xinputGetState(dev->deviceNumber, &dev->state_base);
if (dev->state == ERROR_SUCCESS)
return connection::connected;
return connection::disconnected;
}
void xinput_pad_handler::get_extended_info(const pad_ensemble& binding)
{
const auto& device = binding.device;
const auto& pad = binding.pad;
XInputDevice* dev = static_cast<XInputDevice*>(device.get());
if (!dev || !pad)
return;
const auto padnum = dev->deviceNumber;
// Receive Battery Info. If device is not on cable, get battery level, else assume full
XINPUT_BATTERY_INFORMATION battery_info;
xinputGetBatteryInformation(padnum, BATTERY_DEVTYPE_GAMEPAD, &battery_info);
pad->m_cable_state = battery_info.BatteryType == BATTERY_TYPE_WIRED ? 1 : 0;
pad->m_battery_level = pad->m_cable_state ? BATTERY_LEVEL_FULL : battery_info.BatteryLevel;
if (xinputGetCustomData)
{
SCP_DS3_ACCEL sensors;
if (xinputGetCustomData(dev->deviceNumber, 0, &sensors) == ERROR_SUCCESS)
{
pad->m_sensors[0].m_value = sensors.SCP_ACCEL_X;
pad->m_sensors[1].m_value = sensors.SCP_ACCEL_Y;
pad->m_sensors[2].m_value = sensors.SCP_ACCEL_Z;
pad->m_sensors[3].m_value = sensors.SCP_GYRO;
}
}
}
void xinput_pad_handler::apply_pad_data(const pad_ensemble& binding)
{
const auto& device = binding.device;
const auto& pad = binding.pad;
XInputDevice* dev = static_cast<XInputDevice*>(device.get());
if (!dev || !pad)
return;
const auto padnum = dev->deviceNumber;
const auto cfg = dev->config;
// The left motor is the low-frequency rumble motor. The right motor is the high-frequency rumble motor.
// The two motors are not the same, and they create different vibration effects. Values range between 0 to 65535.
const usz idx_l = cfg->switch_vibration_motors ? 1 : 0;
const usz idx_s = cfg->switch_vibration_motors ? 0 : 1;
const u8 speed_large = cfg->enable_vibration_motor_large ? pad->m_vibrateMotors[idx_l].m_value : 0;
const u8 speed_small = cfg->enable_vibration_motor_small ? pad->m_vibrateMotors[idx_s].m_value : 0;
dev->new_output_data |= dev->large_motor != speed_large || dev->small_motor != speed_small;
dev->large_motor = speed_large;
dev->small_motor = speed_small;
const auto now = steady_clock::now();
const auto elapsed = now - dev->last_output;
// XBox One Controller can't handle faster vibration updates than ~10ms. Elite is even worse. So I'll use 20ms to be on the safe side. No lag was noticable.
if ((dev->new_output_data && elapsed > 20ms) || elapsed > min_output_interval)
{
XINPUT_VIBRATION vibrate
{
.wLeftMotorSpeed = static_cast<u16>(speed_large * 257), // between 0 to 65535
.wRightMotorSpeed = static_cast<u16>(speed_small * 257) // between 0 to 65535
};
if (xinputSetState(padnum, &vibrate) == ERROR_SUCCESS)
{
dev->new_output_data = false;
dev->last_output = now;
}
}
}
#endif
| 21,143
|
C++
|
.cpp
| 500
| 39.862
| 219
| 0.708617
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,011
|
ds4_pad_handler.cpp
|
RPCS3_rpcs3/rpcs3/Input/ds4_pad_handler.cpp
|
#include "stdafx.h"
#include "ds4_pad_handler.h"
#include "Emu/Io/pad_config.h"
#include <limits>
LOG_CHANNEL(ds4_log, "DS4");
using namespace reports;
constexpr id_pair SONY_DS4_ID_0 = {0x054C, 0x0BA0}; // Dongle
constexpr id_pair SONY_DS4_ID_1 = {0x054C, 0x05C4}; // CUH-ZCT1x
constexpr id_pair SONY_DS4_ID_2 = {0x054C, 0x09CC}; // CUH-ZCT2x
constexpr id_pair ZEROPLUS_ID_0 = {0x0C12, 0x0E20};
namespace
{
// This tries to convert axis to give us the max even in the corners,
// this actually might work 'too' well, we end up actually getting diagonals of actual max/min, we need the corners still a bit rounded to match ds3
// im leaving it here for now, and future reference as it probably can be used later
//taken from http://theinstructionlimit.com/squaring-the-thumbsticks
/*std::tuple<u16, u16> ConvertToSquarePoint(u16 inX, u16 inY, u32 innerRoundness = 0) {
// convert inX and Y to a (-1, 1) vector;
const f32 x = (inX - 127) / 127.f;
const f32 y = ((inY - 127) / 127.f) * -1;
f32 outX, outY;
const f32 piOver4 = M_PI / 4;
const f32 angle = std::atan2(y, x) + M_PI;
// x+ wall
if (angle <= piOver4 || angle > 7 * piOver4) {
outX = x * (f32)(1 / std::cos(angle));
outY = y * (f32)(1 / std::cos(angle));
}
// y+ wall
else if (angle > piOver4 && angle <= 3 * piOver4) {
outX = x * (f32)(1 / std::sin(angle));
outY = y * (f32)(1 / std::sin(angle));
}
// x- wall
else if (angle > 3 * piOver4 && angle <= 5 * piOver4) {
outX = x * (f32)(-1 / std::cos(angle));
outY = y * (f32)(-1 / std::cos(angle));
}
// y- wall
else if (angle > 5 * piOver4 && angle <= 7 * piOver4) {
outX = x * (f32)(-1 / std::sin(angle));
outY = y * (f32)(-1 / std::sin(angle));
}
else fmt::throw_exception("invalid angle in convertToSquarePoint");
if (innerRoundness == 0)
return std::tuple<u16, u16>(Clamp0To255((outX + 1) * 127.f), Clamp0To255(((outY * -1) + 1) * 127.f));
const f32 len = std::sqrt(std::pow(x, 2) + std::pow(y, 2));
const f32 factor = std::pow(len, innerRoundness);
outX = (1 - factor) * x + factor * outX;
outY = (1 - factor) * y + factor * outY;
return std::tuple<u16, u16>(Clamp0To255((outX + 1) * 127.f), Clamp0To255(((outY * -1) + 1) * 127.f));
}*/
}
ds4_pad_handler::ds4_pad_handler()
: hid_pad_handler<DS4Device>(pad_handler::ds4, {SONY_DS4_ID_0, SONY_DS4_ID_1, SONY_DS4_ID_2, ZEROPLUS_ID_0})
{
// Unique names for the config files and our pad settings dialog
button_list =
{
{ DS4KeyCodes::None, "" },
{ DS4KeyCodes::Triangle, "Triangle" },
{ DS4KeyCodes::Circle, "Circle" },
{ DS4KeyCodes::Cross, "Cross" },
{ DS4KeyCodes::Square, "Square" },
{ DS4KeyCodes::Left, "Left" },
{ DS4KeyCodes::Right, "Right" },
{ DS4KeyCodes::Up, "Up" },
{ DS4KeyCodes::Down, "Down" },
{ DS4KeyCodes::R1, "R1" },
{ DS4KeyCodes::R2, "R2" },
{ DS4KeyCodes::R3, "R3" },
{ DS4KeyCodes::Options, "Options" },
{ DS4KeyCodes::Share, "Share" },
{ DS4KeyCodes::PSButton, "PS Button" },
{ DS4KeyCodes::TouchPad, "Touch Pad" },
{ DS4KeyCodes::Touch_L, "Touch Left" },
{ DS4KeyCodes::Touch_R, "Touch Right" },
{ DS4KeyCodes::Touch_U, "Touch Up" },
{ DS4KeyCodes::Touch_D, "Touch Down" },
{ DS4KeyCodes::L1, "L1" },
{ DS4KeyCodes::L2, "L2" },
{ DS4KeyCodes::L3, "L3" },
{ DS4KeyCodes::LSXNeg, "LS X-" },
{ DS4KeyCodes::LSXPos, "LS X+" },
{ DS4KeyCodes::LSYPos, "LS Y+" },
{ DS4KeyCodes::LSYNeg, "LS Y-" },
{ DS4KeyCodes::RSXNeg, "RS X-" },
{ DS4KeyCodes::RSXPos, "RS X+" },
{ DS4KeyCodes::RSYPos, "RS Y+" },
{ DS4KeyCodes::RSYNeg, "RS Y-" }
};
init_configs();
// Define border values
thumb_max = 255;
trigger_min = 0;
trigger_max = 255;
// set capabilities
b_has_config = true;
b_has_rumble = true;
b_has_motion = true;
b_has_deadzones = true;
b_has_led = true;
b_has_rgb = true;
b_has_battery = true;
b_has_battery_led = true;
m_name_string = "DS4 Pad #";
m_max_devices = CELL_PAD_MAX_PORT_NUM;
m_trigger_threshold = trigger_max / 2;
m_thumb_threshold = thumb_max / 2;
}
ds4_pad_handler::~ds4_pad_handler()
{
for (auto& controller : m_controllers)
{
if (controller.second && controller.second->hidDevice)
{
// Disable blinking and vibration
controller.second->small_motor = 0;
controller.second->large_motor = 0;
controller.second->led_delay_on = 0;
controller.second->led_delay_off = 0;
if (send_output_report(controller.second.get()) == -1)
{
ds4_log.error("~ds4_pad_handler: send_output_report failed! error=%s", hid_error(controller.second->hidDevice));
}
}
}
}
void ds4_pad_handler::init_config(cfg_pad* cfg)
{
if (!cfg) return;
// Set default button mapping
cfg->ls_left.def = ::at32(button_list, DS4KeyCodes::LSXNeg);
cfg->ls_down.def = ::at32(button_list, DS4KeyCodes::LSYNeg);
cfg->ls_right.def = ::at32(button_list, DS4KeyCodes::LSXPos);
cfg->ls_up.def = ::at32(button_list, DS4KeyCodes::LSYPos);
cfg->rs_left.def = ::at32(button_list, DS4KeyCodes::RSXNeg);
cfg->rs_down.def = ::at32(button_list, DS4KeyCodes::RSYNeg);
cfg->rs_right.def = ::at32(button_list, DS4KeyCodes::RSXPos);
cfg->rs_up.def = ::at32(button_list, DS4KeyCodes::RSYPos);
cfg->start.def = ::at32(button_list, DS4KeyCodes::Options);
cfg->select.def = ::at32(button_list, DS4KeyCodes::Share);
cfg->ps.def = ::at32(button_list, DS4KeyCodes::PSButton);
cfg->square.def = ::at32(button_list, DS4KeyCodes::Square);
cfg->cross.def = ::at32(button_list, DS4KeyCodes::Cross);
cfg->circle.def = ::at32(button_list, DS4KeyCodes::Circle);
cfg->triangle.def = ::at32(button_list, DS4KeyCodes::Triangle);
cfg->left.def = ::at32(button_list, DS4KeyCodes::Left);
cfg->down.def = ::at32(button_list, DS4KeyCodes::Down);
cfg->right.def = ::at32(button_list, DS4KeyCodes::Right);
cfg->up.def = ::at32(button_list, DS4KeyCodes::Up);
cfg->r1.def = ::at32(button_list, DS4KeyCodes::R1);
cfg->r2.def = ::at32(button_list, DS4KeyCodes::R2);
cfg->r3.def = ::at32(button_list, DS4KeyCodes::R3);
cfg->l1.def = ::at32(button_list, DS4KeyCodes::L1);
cfg->l2.def = ::at32(button_list, DS4KeyCodes::L2);
cfg->l3.def = ::at32(button_list, DS4KeyCodes::L3);
cfg->pressure_intensity_button.def = ::at32(button_list, DS4KeyCodes::None);
cfg->analog_limiter_button.def = ::at32(button_list, DS4KeyCodes::None);
// Set default misc variables
cfg->lstick_anti_deadzone.def = static_cast<u32>(0.13 * thumb_max); // 13%
cfg->rstick_anti_deadzone.def = static_cast<u32>(0.13 * thumb_max); // 13%
cfg->lstickdeadzone.def = 40; // between 0 and 255
cfg->rstickdeadzone.def = 40; // between 0 and 255
cfg->ltriggerthreshold.def = 0; // between 0 and 255
cfg->rtriggerthreshold.def = 0; // between 0 and 255
cfg->lpadsquircling.def = 8000;
cfg->rpadsquircling.def = 8000;
// Set default color value
cfg->colorR.def = 0;
cfg->colorG.def = 0;
cfg->colorB.def = 20;
// Set default LED options
cfg->led_battery_indicator.def = false;
cfg->led_battery_indicator_brightness.def = 10;
cfg->led_low_battery_blink.def = true;
// apply defaults
cfg->from_default();
}
u32 ds4_pad_handler::get_battery_level(const std::string& padId)
{
const std::shared_ptr<DS4Device> device = get_hid_device(padId);
if (device == nullptr || device->hidDevice == nullptr)
{
return 0;
}
return std::min<u32>(device->battery_level * 10, 100);
}
void ds4_pad_handler::SetPadData(const std::string& padId, u8 player_id, u8 large_motor, u8 small_motor, s32 r, s32 g, s32 b, bool /*player_led*/, bool battery_led, u32 battery_led_brightness)
{
std::shared_ptr<DS4Device> device = get_hid_device(padId);
if (!device || !device->hidDevice)
return;
// Set the device's motor speeds to our requested values 0-255
device->large_motor = large_motor;
device->small_motor = small_motor;
device->player_id = player_id;
device->config = get_config(padId);
ensure(device->config);
// Set new LED color
if (battery_led)
{
const u32 combined_color = get_battery_color(device->battery_level, battery_led_brightness);
device->config->colorR.set(combined_color >> 8);
device->config->colorG.set(combined_color & 0xff);
device->config->colorB.set(0);
}
else if (r >= 0 && g >= 0 && b >= 0 && r <= 255 && g <= 255 && b <= 255)
{
device->config->colorR.set(r);
device->config->colorG.set(g);
device->config->colorB.set(b);
}
// Start/Stop the engines :)
if (send_output_report(device.get()) == -1)
{
ds4_log.error("SetPadData: send_output_report failed! error=%s", hid_error(device->hidDevice));
}
}
std::unordered_map<u64, u16> ds4_pad_handler::get_button_values(const std::shared_ptr<PadDevice>& device)
{
std::unordered_map<u64, u16> keyBuffer;
DS4Device* dev = static_cast<DS4Device*>(device.get());
if (!dev)
return keyBuffer;
const ds4_input_report_common& input = dev->bt_controller ? dev->report_bt.common : dev->report_usb.common;
// Left Stick X Axis
keyBuffer[DS4KeyCodes::LSXNeg] = Clamp0To255((127.5f - input.x) * 2.0f);
keyBuffer[DS4KeyCodes::LSXPos] = Clamp0To255((input.x - 127.5f) * 2.0f);
// Left Stick Y Axis (Up is the negative for some reason)
keyBuffer[DS4KeyCodes::LSYNeg] = Clamp0To255((input.y - 127.5f) * 2.0f);
keyBuffer[DS4KeyCodes::LSYPos] = Clamp0To255((127.5f - input.y) * 2.0f);
// Right Stick X Axis
keyBuffer[DS4KeyCodes::RSXNeg] = Clamp0To255((127.5f - input.rx) * 2.0f);
keyBuffer[DS4KeyCodes::RSXPos] = Clamp0To255((input.rx - 127.5f) * 2.0f);
// Right Stick Y Axis (Up is the negative for some reason)
keyBuffer[DS4KeyCodes::RSYNeg] = Clamp0To255((input.ry - 127.5f) * 2.0f);
keyBuffer[DS4KeyCodes::RSYPos] = Clamp0To255((127.5f - input.ry) * 2.0f);
// bleh, dpad in buffer is stored in a different state
const u8 dpadState = input.buttons[0] & 0xf;
switch (dpadState)
{
case 0x08: // none pressed
keyBuffer[DS4KeyCodes::Up] = 0;
keyBuffer[DS4KeyCodes::Down] = 0;
keyBuffer[DS4KeyCodes::Left] = 0;
keyBuffer[DS4KeyCodes::Right] = 0;
break;
case 0x07: // NW...left and up
keyBuffer[DS4KeyCodes::Up] = 255;
keyBuffer[DS4KeyCodes::Down] = 0;
keyBuffer[DS4KeyCodes::Left] = 255;
keyBuffer[DS4KeyCodes::Right] = 0;
break;
case 0x06: // W..left
keyBuffer[DS4KeyCodes::Up] = 0;
keyBuffer[DS4KeyCodes::Down] = 0;
keyBuffer[DS4KeyCodes::Left] = 255;
keyBuffer[DS4KeyCodes::Right] = 0;
break;
case 0x05: // SW..left down
keyBuffer[DS4KeyCodes::Up] = 0;
keyBuffer[DS4KeyCodes::Down] = 255;
keyBuffer[DS4KeyCodes::Left] = 255;
keyBuffer[DS4KeyCodes::Right] = 0;
break;
case 0x04: // S..down
keyBuffer[DS4KeyCodes::Up] = 0;
keyBuffer[DS4KeyCodes::Down] = 255;
keyBuffer[DS4KeyCodes::Left] = 0;
keyBuffer[DS4KeyCodes::Right] = 0;
break;
case 0x03: // SE..down and right
keyBuffer[DS4KeyCodes::Up] = 0;
keyBuffer[DS4KeyCodes::Down] = 255;
keyBuffer[DS4KeyCodes::Left] = 0;
keyBuffer[DS4KeyCodes::Right] = 255;
break;
case 0x02: // E... right
keyBuffer[DS4KeyCodes::Up] = 0;
keyBuffer[DS4KeyCodes::Down] = 0;
keyBuffer[DS4KeyCodes::Left] = 0;
keyBuffer[DS4KeyCodes::Right] = 255;
break;
case 0x01: // NE.. up right
keyBuffer[DS4KeyCodes::Up] = 255;
keyBuffer[DS4KeyCodes::Down] = 0;
keyBuffer[DS4KeyCodes::Left] = 0;
keyBuffer[DS4KeyCodes::Right] = 255;
break;
case 0x00: // n.. up
keyBuffer[DS4KeyCodes::Up] = 255;
keyBuffer[DS4KeyCodes::Down] = 0;
keyBuffer[DS4KeyCodes::Left] = 0;
keyBuffer[DS4KeyCodes::Right] = 0;
break;
default:
fmt::throw_exception("ds4 dpad state encountered unexpected input");
}
// square, cross, circle, triangle
keyBuffer[DS4KeyCodes::Square] = ((input.buttons[0] & (1 << 4)) != 0) ? 255 : 0;
keyBuffer[DS4KeyCodes::Cross] = ((input.buttons[0] & (1 << 5)) != 0) ? 255 : 0;
keyBuffer[DS4KeyCodes::Circle] = ((input.buttons[0] & (1 << 6)) != 0) ? 255 : 0;
keyBuffer[DS4KeyCodes::Triangle] = ((input.buttons[0] & (1 << 7)) != 0) ? 255 : 0;
// L1, R1, L2, L3, select, start, L3, L3
keyBuffer[DS4KeyCodes::L1] = ((input.buttons[1] & (1 << 0)) != 0) ? 255 : 0;
keyBuffer[DS4KeyCodes::R1] = ((input.buttons[1] & (1 << 1)) != 0) ? 255 : 0;
//keyBuffer[DS4KeyCodes::L2But] = ((input.buttons[1] & (1 << 2)) != 0) ? 255 : 0;
//keyBuffer[DS4KeyCodes::R2But] = ((input.buttons[1] & (1 << 3)) != 0) ? 255 : 0;
keyBuffer[DS4KeyCodes::Share] = ((input.buttons[1] & (1 << 4)) != 0) ? 255 : 0;
keyBuffer[DS4KeyCodes::Options] = ((input.buttons[1] & (1 << 5)) != 0) ? 255 : 0;
keyBuffer[DS4KeyCodes::L3] = ((input.buttons[1] & (1 << 6)) != 0) ? 255 : 0;
keyBuffer[DS4KeyCodes::R3] = ((input.buttons[1] & (1 << 7)) != 0) ? 255 : 0;
// PS Button, Touch Button
keyBuffer[DS4KeyCodes::PSButton] = ((input.buttons[2] & (1 << 0)) != 0) ? 255 : 0;
keyBuffer[DS4KeyCodes::TouchPad] = ((input.buttons[2] & (1 << 1)) != 0) ? 255 : 0;
// L2, R2
keyBuffer[DS4KeyCodes::L2] = input.z;
keyBuffer[DS4KeyCodes::R2] = input.rz;
// Touch Pad
const auto apply_touch = [&keyBuffer](const ds4_touch_report& touch)
{
for (const ds4_touch_point& point : touch.points)
{
if (!(point.contact & DS4_TOUCH_POINT_INACTIVE))
{
const s32 x = (point.x_hi << 8) | point.x_lo;
const s32 y = (point.y_hi << 4) | point.y_lo;
const f32 x_scaled = ScaledInput(static_cast<float>(x), 0.0f, static_cast<float>(DS4_TOUCHPAD_WIDTH), 0.0f, 255.0f);
const f32 y_scaled = ScaledInput(static_cast<float>(y), 0.0f, static_cast<float>(DS4_TOUCHPAD_HEIGHT), 0.0f, 255.0f);
keyBuffer[DS4KeyCodes::Touch_L] = Clamp0To255((127.5f - x_scaled) * 2.0f);
keyBuffer[DS4KeyCodes::Touch_R] = Clamp0To255((x_scaled - 127.5f) * 2.0f);
keyBuffer[DS4KeyCodes::Touch_U] = Clamp0To255((127.5f - y_scaled) * 2.0f);
keyBuffer[DS4KeyCodes::Touch_D] = Clamp0To255((y_scaled - 127.5f) * 2.0f);
}
}
};
if (dev->bt_controller)
{
const ds4_input_report_bt& report = dev->report_bt;
for (u32 i = 0; i < std::min<u32>(report.num_touch_reports, ::size32(report.touch_reports)); i++)
{
apply_touch(report.touch_reports[i]);
}
}
else
{
const ds4_input_report_usb& report = dev->report_usb;
for (u32 i = 0; i < std::min<u32>(report.num_touch_reports, ::size32(report.touch_reports)); i++)
{
apply_touch(report.touch_reports[i]);
}
}
return keyBuffer;
}
pad_preview_values ds4_pad_handler::get_preview_values(const std::unordered_map<u64, u16>& data)
{
return {
::at32(data, L2),
::at32(data, R2),
::at32(data, LSXPos) - ::at32(data, LSXNeg),
::at32(data, LSYPos) - ::at32(data, LSYNeg),
::at32(data, RSXPos) - ::at32(data, RSXNeg),
::at32(data, RSYPos) - ::at32(data, RSYNeg)
};
}
bool ds4_pad_handler::GetCalibrationData(DS4Device* ds4Dev) const
{
if (!ds4Dev || !ds4Dev->hidDevice)
{
ds4_log.error("GetCalibrationData called with null device");
return false;
}
std::array<u8, 64> buf{};
if (ds4Dev->bt_controller)
{
for (int tries = 0; tries < 3; ++tries)
{
buf = {};
buf[0] = 0x05; // Calibration feature report id
if (int res = hid_get_feature_report(ds4Dev->hidDevice, buf.data(), DS4_FEATURE_REPORT_BLUETOOTH_CALIBRATION_SIZE); res != DS4_FEATURE_REPORT_BLUETOOTH_CALIBRATION_SIZE || buf[0] != 0x05)
{
ds4_log.error("GetCalibrationData: hid_get_feature_report 0x05 for bluetooth controller failed! result=%d, error=%s", res, hid_error(ds4Dev->hidDevice));
return false;
}
const u8 btHdr = 0xA3;
const u32 crcHdr = CRCPP::CRC::Calculate(&btHdr, 1, crcTable);
const u32 crcCalc = CRCPP::CRC::Calculate(buf.data(), DS4_FEATURE_REPORT_BLUETOOTH_CALIBRATION_SIZE - 4, crcTable, crcHdr);
const u32 crcReported = read_u32(&buf[DS4_FEATURE_REPORT_BLUETOOTH_CALIBRATION_SIZE - 4]);
if (crcCalc == crcReported)
break;
ds4_log.warning("Calibration CRC check failed! Will retry up to 3 times. Received 0x%x, Expected 0x%x", crcReported, crcCalc);
if (tries == 2)
{
ds4_log.error("Calibration CRC check failed too many times!");
return false;
}
}
}
else
{
buf[0] = 0x02;
if (int res = hid_get_feature_report(ds4Dev->hidDevice, buf.data(), DS4_FEATURE_REPORT_USB_CALIBRATION_SIZE); res != DS4_FEATURE_REPORT_USB_CALIBRATION_SIZE || buf[0] != 0x02)
{
ds4_log.error("GetCalibrationData: hid_get_feature_report 0x02 for wired controller failed! result=%d, error=%s", res, hid_error(ds4Dev->hidDevice));
return false;
}
}
ds4Dev->calib_data[CalibIndex::PITCH].bias = read_s16(&buf[1]);
ds4Dev->calib_data[CalibIndex::YAW].bias = read_s16(&buf[3]);
ds4Dev->calib_data[CalibIndex::ROLL].bias = read_s16(&buf[5]);
s16 pitchPlus, pitchNeg, rollPlus, rollNeg, yawPlus, yawNeg;
// Check for calibration data format
// It's going to be either alternating +/- or +++---
if (read_s16(&buf[9]) < 0 && read_s16(&buf[7]) > 0)
{
// Wired mode for OEM controllers
pitchPlus = read_s16(&buf[7]);
pitchNeg = read_s16(&buf[9]);
yawPlus = read_s16(&buf[11]);
yawNeg = read_s16(&buf[13]);
rollPlus = read_s16(&buf[15]);
rollNeg = read_s16(&buf[17]);
}
else
{
// Bluetooth mode and wired mode for some 3rd party controllers
pitchPlus = read_s16(&buf[7]);
yawPlus = read_s16(&buf[9]);
rollPlus = read_s16(&buf[11]);
pitchNeg = read_s16(&buf[13]);
yawNeg = read_s16(&buf[15]);
rollNeg = read_s16(&buf[17]);
}
// Confirm correctness. Need confirmation with dongle with no active controller
if (pitchPlus <= 0 || yawPlus <= 0 || rollPlus <= 0 ||
pitchNeg >= 0 || yawNeg >= 0 || rollNeg >= 0)
{
ds4_log.error("GetCalibrationData: calibration data check failed! pitchPlus=%d, pitchNeg=%d, rollPlus=%d, rollNeg=%d, yawPlus=%d, yawNeg=%d", pitchPlus, pitchNeg, rollPlus, rollNeg, yawPlus, yawNeg);
}
const s32 gyroSpeedScale = read_s16(&buf[19]) + read_s16(&buf[21]);
ds4Dev->calib_data[CalibIndex::PITCH].sens_numer = gyroSpeedScale * DS4_GYRO_RES_PER_DEG_S;
ds4Dev->calib_data[CalibIndex::PITCH].sens_denom = pitchPlus - pitchNeg;
ds4Dev->calib_data[CalibIndex::YAW].sens_numer = gyroSpeedScale * DS4_GYRO_RES_PER_DEG_S;
ds4Dev->calib_data[CalibIndex::YAW].sens_denom = yawPlus - yawNeg;
ds4Dev->calib_data[CalibIndex::ROLL].sens_numer = gyroSpeedScale * DS4_GYRO_RES_PER_DEG_S;
ds4Dev->calib_data[CalibIndex::ROLL].sens_denom = rollPlus - rollNeg;
const s16 accelXPlus = read_s16(&buf[23]);
const s16 accelXNeg = read_s16(&buf[25]);
const s16 accelYPlus = read_s16(&buf[27]);
const s16 accelYNeg = read_s16(&buf[29]);
const s16 accelZPlus = read_s16(&buf[31]);
const s16 accelZNeg = read_s16(&buf[33]);
const s32 accelXRange = accelXPlus - accelXNeg;
ds4Dev->calib_data[CalibIndex::X].bias = accelXPlus - accelXRange / 2;
ds4Dev->calib_data[CalibIndex::X].sens_numer = 2 * DS4_ACC_RES_PER_G;
ds4Dev->calib_data[CalibIndex::X].sens_denom = accelXRange;
const s32 accelYRange = accelYPlus - accelYNeg;
ds4Dev->calib_data[CalibIndex::Y].bias = accelYPlus - accelYRange / 2;
ds4Dev->calib_data[CalibIndex::Y].sens_numer = 2 * DS4_ACC_RES_PER_G;
ds4Dev->calib_data[CalibIndex::Y].sens_denom = accelYRange;
const s32 accelZRange = accelZPlus - accelZNeg;
ds4Dev->calib_data[CalibIndex::Z].bias = accelZPlus - accelZRange / 2;
ds4Dev->calib_data[CalibIndex::Z].sens_numer = 2 * DS4_ACC_RES_PER_G;
ds4Dev->calib_data[CalibIndex::Z].sens_denom = accelZRange;
// Make sure data 'looks' valid, dongle will report invalid calibration data with no controller connected
for (usz i = 0; i < ds4Dev->calib_data.size(); i++)
{
CalibData& data = ds4Dev->calib_data[i];
if (data.sens_denom == 0)
{
ds4_log.error("GetCalibrationData: Invalid accelerometer calibration data for axis %d, disabling calibration.", i);
data.bias = 0;
data.sens_numer = 4 * DS4_ACC_RES_PER_G;
data.sens_denom = std::numeric_limits<s16>::max();
}
}
return true;
}
void ds4_pad_handler::check_add_device(hid_device* hidDevice, std::string_view path, std::wstring_view wide_serial)
{
if (!hidDevice)
{
return;
}
DS4Device* device = nullptr;
for (auto& controller : m_controllers)
{
ensure(controller.second);
if (!controller.second->hidDevice)
{
device = controller.second.get();
break;
}
}
if (!device)
{
return;
}
std::string serial;
for (wchar_t ch : wide_serial)
serial += static_cast<uchar>(ch);
const hid_device_info* devinfo = hid_get_device_info(hidDevice);
if (!devinfo)
{
ds4_log.error("check_add_device: hid_get_device_info failed! error=%s", hid_error(hidDevice));
hid_close(hidDevice);
return;
}
device->bt_controller = (devinfo->bus_type == HID_API_BUS_BLUETOOTH);
device->hidDevice = hidDevice;
if (!GetCalibrationData(device))
{
ds4_log.error("check_add_device: GetCalibrationData failed!");
device->close();
return;
}
u32 hw_version{};
u32 fw_version{};
std::array<u8, 64> buf{};
buf[0] = 0xA3;
int res = hid_get_feature_report(hidDevice, buf.data(), DS4_FEATURE_REPORT_FIRMWARE_INFO_SIZE);
if (res != DS4_FEATURE_REPORT_FIRMWARE_INFO_SIZE || buf[0] != 0xA3)
{
ds4_log.error("check_add_device: hid_get_feature_report 0xA3 failed! Could not retrieve firmware version! result=%d, buf[0]=0x%x, error=%s", res, buf[0], hid_error(hidDevice));
}
else
{
hw_version = read_u32(&buf[35]);
fw_version = read_u32(&buf[41]);
ds4_log.notice("check_add_device: Got firmware version: hw_version: 0x%x, fw_version: 0x%x", hw_version, fw_version);
}
if (hid_set_nonblocking(hidDevice, 1) == -1)
{
ds4_log.error("check_add_device: hid_set_nonblocking failed! Reason: %s", hid_error(hidDevice));
device->close();
return;
}
device->has_calib_data = true;
device->path = path;
if (send_output_report(device) == -1)
{
ds4_log.error("check_add_device: send_output_report failed! Reason: %s", hid_error(hidDevice));
}
ds4_log.notice("Added device: bluetooth=%d, serial='%s', hw_version: 0x%x, fw_version: 0x%x, path='%s'", device->bt_controller, serial, hw_version, fw_version, device->path);
}
int ds4_pad_handler::send_output_report(DS4Device* device)
{
if (!device || !device->hidDevice)
return -2;
const auto config = device->config;
if (config == nullptr)
return -2; // hid_write and hid_write_control return -1 on error
// write rumble state
ds4_output_report_common common{};
common.valid_flag0 = 0x07;
common.motor_right = device->small_motor;
common.motor_left = device->large_motor;
// write LED color
common.lightbar_red = config->colorR;
common.lightbar_green = config->colorG;
common.lightbar_blue = config->colorB;
// alternating blink states with values 0-255: only setting both to zero disables blinking
// 255 is roughly 2 seconds, so setting both values to 255 results in a 4 second interval
// using something like (0,10) will heavily blink, while using (0, 255) will be slow. you catch the drift
common.lightbar_blink_on = device->led_delay_on;
common.lightbar_blink_off = device->led_delay_off;
if (device->bt_controller)
{
ds4_output_report_bt output{};
output.report_id = 0x11;
output.hw_control = 0xC4;
output.common = std::move(common);
const u8 btHdr = 0xA2;
const u32 crcHdr = CRCPP::CRC::Calculate(&btHdr, 1, crcTable);
const u32 crcCalc = CRCPP::CRC::Calculate(&output.report_id, offsetof(ds4_output_report_bt, crc32), crcTable, crcHdr);
write_to_ptr(output.crc32, crcCalc);
return hid_write_control(device->hidDevice, &output.report_id, sizeof(ds4_output_report_bt));
}
ds4_output_report_usb output{};
output.report_id = 0x05;
output.common = std::move(common);
return hid_write(device->hidDevice, &output.report_id, sizeof(ds4_output_report_usb));
}
ds4_pad_handler::DataStatus ds4_pad_handler::get_data(DS4Device* device)
{
if (!device || !device->hidDevice)
return DataStatus::ReadError;
std::array<u8, std::max(sizeof(ds4_input_report_bt), sizeof(ds4_input_report_usb))> buf{};
const int res = hid_read(device->hidDevice, buf.data(), device->bt_controller ? sizeof(ds4_input_report_bt) : sizeof(ds4_input_report_usb));
if (res == -1)
{
// looks like controller disconnected or read error
return DataStatus::ReadError;
}
// no data? keep going
if (res == 0)
return DataStatus::NoNewData;
// bt controller sends this until 0x02 feature report is sent back (happens on controller init/restart)
if (device->bt_controller && buf[0] == 0x1)
{
// tells controller to send 0x11 reports
std::array<u8, 64> buf_error{};
buf_error[0] = 0x2;
if (int res = hid_get_feature_report(device->hidDevice, buf_error.data(), buf_error.size()); res != static_cast<int>(buf_error.size()) || buf_error[0] != 0x2)
{
ds4_log.error("GetRawData: hid_get_feature_report 0x2 failed! result=%d, buf[0]=0x%x, error=%s", res, buf[0], hid_error(device->hidDevice));
}
return DataStatus::NoNewData;
}
int offset = 0;
// check report and set offset
if (device->bt_controller && buf[0] == 0x11 && res == sizeof(ds4_input_report_bt))
{
offset = offsetof(ds4_input_report_bt, common);
const u8 btHdr = 0xA1;
const u32 crcHdr = CRCPP::CRC::Calculate(&btHdr, 1, crcTable);
const u32 crcCalc = CRCPP::CRC::Calculate(buf.data(), offsetof(ds4_input_report_bt, crc32), crcTable, crcHdr);
const u32 crcReported = read_u32(&buf[offsetof(ds4_input_report_bt, crc32)]);
if (crcCalc != crcReported)
{
ds4_log.warning("Data packet CRC check failed, ignoring! Received 0x%x, Expected 0x%x", crcReported, crcCalc);
return DataStatus::NoNewData;
}
}
else if (!device->bt_controller && buf[0] == 0x01 && res == sizeof(ds4_input_report_usb))
{
// Ds4 Dongle uses this bit to actually report whether a controller is connected
const bool connected = !(buf[31] & 0x04);
if (connected && !device->has_calib_data)
device->has_calib_data = GetCalibrationData(device);
offset = offsetof(ds4_input_report_usb, common);
}
else
return DataStatus::NoNewData;
const int battery_offset = offset + offsetof(ds4_input_report_common, status);
device->cable_state = (buf[battery_offset] >> 4) & 0x01;
device->battery_level = buf[battery_offset] & 0x0F; // 0 - 9 while unplugged, 0 - 10 while plugged in, 11 charge complete
if (device->has_calib_data)
{
int calib_offset = offset + offsetof(ds4_input_report_common, gyro);
for (int i = 0; i < CalibIndex::COUNT; ++i)
{
const s16 raw_value = read_s16(&buf[calib_offset]);
const s16 cal_value = apply_calibration(raw_value, device->calib_data[i]);
buf[calib_offset++] = (static_cast<u16>(cal_value) >> 0) & 0xFF;
buf[calib_offset++] = (static_cast<u16>(cal_value) >> 8) & 0xFF;
}
}
if (device->bt_controller)
{
std::memcpy(&device->report_bt, buf.data(), sizeof(ds4_input_report_bt));
}
else
{
std::memcpy(&device->report_usb, buf.data(), sizeof(ds4_input_report_usb));
}
return DataStatus::NewData;
}
bool ds4_pad_handler::get_is_left_trigger(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
return keyCode == DS4KeyCodes::L2;
}
bool ds4_pad_handler::get_is_right_trigger(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
return keyCode == DS4KeyCodes::R2;
}
bool ds4_pad_handler::get_is_left_stick(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
switch (keyCode)
{
case DS4KeyCodes::LSXNeg:
case DS4KeyCodes::LSXPos:
case DS4KeyCodes::LSYPos:
case DS4KeyCodes::LSYNeg:
return true;
default:
return false;
}
}
bool ds4_pad_handler::get_is_right_stick(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
switch (keyCode)
{
case DS4KeyCodes::RSXNeg:
case DS4KeyCodes::RSXPos:
case DS4KeyCodes::RSYPos:
case DS4KeyCodes::RSYNeg:
return true;
default:
return false;
}
}
bool ds4_pad_handler::get_is_touch_pad_motion(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
switch (keyCode)
{
case DS4KeyCodes::Touch_L:
case DS4KeyCodes::Touch_R:
case DS4KeyCodes::Touch_U:
case DS4KeyCodes::Touch_D:
return true;
default:
return false;
}
}
PadHandlerBase::connection ds4_pad_handler::update_connection(const std::shared_ptr<PadDevice>& device)
{
DS4Device* dev = static_cast<DS4Device*>(device.get());
if (!dev || dev->path.empty())
return connection::disconnected;
if (dev->hidDevice == nullptr)
{
// try to reconnect
if (hid_device* hid_dev = hid_open_path(dev->path.c_str()))
{
if (hid_set_nonblocking(hid_dev, 1) == -1)
{
ds4_log.error("Reconnecting Device %s: hid_set_nonblocking failed with error %s", dev->path, hid_error(hid_dev));
}
dev->hidDevice = hid_dev;
if (!dev->has_calib_data)
{
dev->has_calib_data = GetCalibrationData(dev);
}
}
else
{
// nope, not there
return connection::disconnected;
}
}
if (get_data(dev) == DataStatus::ReadError)
{
// this also can mean disconnected, either way deal with it on next loop and reconnect
dev->close();
return connection::no_data;
}
return connection::connected;
}
void ds4_pad_handler::get_extended_info(const pad_ensemble& binding)
{
const auto& device = binding.device;
const auto& pad = binding.pad;
DS4Device* dev = static_cast<DS4Device*>(device.get());
if (!dev || !pad)
return;
const ds4_input_report_common& input = dev->bt_controller ? dev->report_bt.common : dev->report_usb.common;
pad->m_battery_level = dev->battery_level;
pad->m_cable_state = dev->cable_state;
// these values come already calibrated, all we need to do is convert to ds3 range
// accel
f32 accelX = static_cast<s16>(input.accel[0]) / static_cast<f32>(DS4_ACC_RES_PER_G) * -1;
f32 accelY = static_cast<s16>(input.accel[1]) / static_cast<f32>(DS4_ACC_RES_PER_G) * -1;
f32 accelZ = static_cast<s16>(input.accel[2]) / static_cast<f32>(DS4_ACC_RES_PER_G) * -1;
// now just use formula from ds3
accelX = accelX * 113 + 512;
accelY = accelY * 113 + 512;
accelZ = accelZ * 113 + 512;
pad->m_sensors[0].m_value = Clamp0To1023(accelX);
pad->m_sensors[1].m_value = Clamp0To1023(accelY);
pad->m_sensors[2].m_value = Clamp0To1023(accelZ);
// gyroY is yaw, which is all that we need
//f32 gyroX = static_cast<s16>(input.gyro[0]) / static_cast<f32>(DS4_GYRO_RES_PER_DEG_S) * -1;
f32 gyroY = static_cast<s16>(input.gyro[1]) / static_cast<f32>(DS4_GYRO_RES_PER_DEG_S) * -1;
//f32 gyroZ = static_cast<s16>(input.gyro[2]) / static_cast<f32>(DS4_GYRO_RES_PER_DEG_S) * -1;
// Convert to ds3. The ds3 resolution is 123/90°/sec.
gyroY = gyroY * (123.f / 90.f) + 512;
pad->m_sensors[3].m_value = Clamp0To1023(gyroY);
}
void ds4_pad_handler::apply_pad_data(const pad_ensemble& binding)
{
const auto& device = binding.device;
const auto& pad = binding.pad;
DS4Device* dev = static_cast<DS4Device*>(device.get());
if (!dev || !dev->hidDevice || !dev->config || !pad)
return;
cfg_pad* config = dev->config;
// Attempt to send rumble no matter what
const int idx_l = config->switch_vibration_motors ? 1 : 0;
const int idx_s = config->switch_vibration_motors ? 0 : 1;
const u8 speed_large = config->enable_vibration_motor_large ? pad->m_vibrateMotors[idx_l].m_value : 0;
const u8 speed_small = config->enable_vibration_motor_small ? pad->m_vibrateMotors[idx_s].m_value : 0;
const bool wireless = dev->cable_state == 0;
const bool low_battery = dev->battery_level < 2;
const bool is_blinking = dev->led_delay_on > 0 || dev->led_delay_off > 0;
// Blink LED when battery is low
if (config->led_low_battery_blink)
{
// we are now wired or have okay battery level -> stop blinking
if (is_blinking && !(wireless && low_battery))
{
dev->led_delay_on = 0;
dev->led_delay_off = 0;
dev->new_output_data = true;
}
// we are now wireless and low on battery -> blink
else if (!is_blinking && wireless && low_battery)
{
dev->led_delay_on = 100;
dev->led_delay_off = 100;
dev->new_output_data = true;
}
}
// Use LEDs to indicate battery level
if (config->led_battery_indicator)
{
// This makes sure that the LED color doesn't update every 1ms. DS4 only reports battery level in 10% increments
if (dev->last_battery_level != dev->battery_level)
{
const u32 combined_color = get_battery_color(dev->battery_level, config->led_battery_indicator_brightness);
config->colorR.set(combined_color >> 8);
config->colorG.set(combined_color & 0xff);
config->colorB.set(0);
dev->new_output_data = true;
dev->last_battery_level = dev->battery_level;
}
}
dev->new_output_data |= dev->large_motor != speed_large || dev->small_motor != speed_small;
dev->large_motor = speed_large;
dev->small_motor = speed_small;
const auto now = steady_clock::now();
const auto elapsed = now - dev->last_output;
if (dev->new_output_data || elapsed > min_output_interval)
{
if (const int res = send_output_report(dev); res >= 0)
{
dev->new_output_data = false;
dev->last_output = now;
}
else if (res == -1)
{
ds4_log.error("apply_pad_data: send_output_report failed! error=%s", hid_error(dev->hidDevice));
}
}
}
| 32,895
|
C++
|
.cpp
| 836
| 36.696172
| 201
| 0.680801
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,012
|
basic_mouse_handler.cpp
|
RPCS3_rpcs3/rpcs3/Input/basic_mouse_handler.cpp
|
#include <QApplication>
#include <QCursor>
#include "util/types.hpp"
#include "util/logs.hpp"
#include "basic_mouse_handler.h"
#include "keyboard_pad_handler.h"
#include "rpcs3qt/gs_frame.h"
#include "Emu/Io/interception.h"
#include "Emu/Io/mouse_config.h"
mouse_config g_cfg_mouse;
void basic_mouse_handler::Init(const u32 max_connect)
{
if (m_info.max_connect > 0)
{
// Already initialized
return;
}
if (!g_cfg_mouse.load())
{
input_log.notice("basic_mouse_handler: Could not load basic mouse config. Using defaults.");
}
reload_config();
m_mice.clear();
m_mice.emplace_back(Mouse());
m_info = {};
m_info.max_connect = max_connect;
m_info.now_connect = std::min(::size32(m_mice), max_connect);
m_info.info = input::g_mice_intercepted ? CELL_MOUSE_INFO_INTERCEPTED : 0; // Ownership of mouse data: 0=Application, 1=System
for (u32 i = 1; i < max_connect; i++)
{
m_info.status[i] = CELL_MOUSE_STATUS_DISCONNECTED;
m_info.mode[i] = CELL_MOUSE_INFO_TABLET_MOUSE_MODE;
m_info.tablet_is_supported[i] = CELL_MOUSE_INFO_TABLET_NOT_SUPPORTED;
}
m_info.status[0] = CELL_MOUSE_STATUS_CONNECTED; // (TODO: Support for more mice)
m_info.vendor_id[0] = 0x1234;
m_info.product_id[0] = 0x1234;
type = mouse_handler::basic;
}
void basic_mouse_handler::reload_config()
{
input_log.notice("Basic mouse config=\n%s", g_cfg_mouse.to_string());
m_buttons[CELL_MOUSE_BUTTON_1] = get_mouse_button(g_cfg_mouse.mouse_button_1);
m_buttons[CELL_MOUSE_BUTTON_2] = get_mouse_button(g_cfg_mouse.mouse_button_2);
m_buttons[CELL_MOUSE_BUTTON_3] = get_mouse_button(g_cfg_mouse.mouse_button_3);
m_buttons[CELL_MOUSE_BUTTON_4] = get_mouse_button(g_cfg_mouse.mouse_button_4);
m_buttons[CELL_MOUSE_BUTTON_5] = get_mouse_button(g_cfg_mouse.mouse_button_5);
m_buttons[CELL_MOUSE_BUTTON_6] = get_mouse_button(g_cfg_mouse.mouse_button_6);
m_buttons[CELL_MOUSE_BUTTON_7] = get_mouse_button(g_cfg_mouse.mouse_button_7);
m_buttons[CELL_MOUSE_BUTTON_8] = get_mouse_button(g_cfg_mouse.mouse_button_8);
}
/* Sets the target window for the event handler, and also installs an event filter on the target. */
void basic_mouse_handler::SetTargetWindow(QWindow* target)
{
if (target)
{
m_target = target;
target->installEventFilter(this);
}
else
{
// If this is hit, it probably means that some refactoring occurs because currently a gsframe is created in Load.
// We still want events so filter from application instead since target is null.
QApplication::instance()->installEventFilter(this);
input_log.error("Trying to set mouse handler to a null target window.");
}
}
bool basic_mouse_handler::eventFilter(QObject* target, QEvent* ev)
{
if (m_info.max_connect == 0)
{
// Not initialized
return false;
}
if (!ev) [[unlikely]]
{
return false;
}
if (input::g_active_mouse_and_keyboard != input::active_mouse_and_keyboard::emulated)
{
return false;
}
// !m_target is for future proofing when gsrender isn't automatically initialized on load to ensure events still occur
// !m_target->isVisible() is a hack since currently a guiless application will STILL inititialize a gsrender (providing a valid target)
if (!m_target || !m_target->isVisible() || target == m_target)
{
if (g_cfg_mouse.reload_requested.exchange(false))
{
reload_config();
}
switch (ev->type())
{
case QEvent::MouseButtonPress:
MouseButtonDown(static_cast<QMouseEvent*>(ev));
break;
case QEvent::MouseButtonRelease:
MouseButtonUp(static_cast<QMouseEvent*>(ev));
break;
case QEvent::MouseMove:
MouseMove(static_cast<QMouseEvent*>(ev));
break;
case QEvent::Wheel:
MouseScroll(static_cast<QWheelEvent*>(ev));
break;
default:
return false;
}
}
return false;
}
void basic_mouse_handler::MouseButtonDown(QMouseEvent* event)
{
if (!event) [[unlikely]]
{
return;
}
const int button = event->button();
if (const auto it = std::find_if(m_buttons.cbegin(), m_buttons.cend(), [button](const auto& entry){ return entry.second == button; });
it != m_buttons.cend())
{
MouseHandlerBase::Button(0, it->first, true);
}
}
void basic_mouse_handler::MouseButtonUp(QMouseEvent* event)
{
if (!event) [[unlikely]]
{
return;
}
const int button = event->button();
if (const auto it = std::find_if(m_buttons.cbegin(), m_buttons.cend(), [button](const auto& entry){ return entry.second == button; });
it != m_buttons.cend())
{
MouseHandlerBase::Button(0, it->first, false);
}
}
void basic_mouse_handler::MouseScroll(QWheelEvent* event)
{
if (!event) [[unlikely]]
{
return;
}
const QPoint delta = event->angleDelta();
const s8 x = std::clamp(delta.x() / 120, -128, 127);
const s8 y = std::clamp(delta.y() / 120, -128, 127);
MouseHandlerBase::Scroll(0, x, y);
}
bool basic_mouse_handler::get_mouse_lock_state() const
{
if (auto game_frame = dynamic_cast<gs_frame*>(m_target))
return game_frame->get_mouse_lock_state();
return false;
}
int basic_mouse_handler::get_mouse_button(const cfg::string& button)
{
const std::string name = button.to_string();
const auto it = std::find_if(mouse_list.cbegin(), mouse_list.cend(), [&name](const auto& entry){ return entry.second == name; });
if (it != mouse_list.cend())
{
return it->first;
}
return Qt::MouseButton::NoButton;
}
void basic_mouse_handler::MouseMove(QMouseEvent* event)
{
if (!event) [[unlikely]]
{
return;
}
if (is_time_for_update())
{
// get the screen dimensions
const QSize screen = m_target->size();
const QPoint e_pos = event->pos();
if (m_target && m_target->isActive() && get_mouse_lock_state())
{
// get the center of the screen in global coordinates
QPoint p_center = m_target->geometry().topLeft() + QPoint(screen.width() / 2, screen.height() / 2);
// reset the mouse to the center for consistent results since edge movement won't be registered
QCursor::setPos(m_target->screen(), p_center);
// convert the center into screen coordinates
p_center = m_target->mapFromGlobal(p_center);
// current mouse position, starting at the center
static QPoint p_real(p_center);
// get the delta of the mouse position to the screen center
const QPoint p_delta = e_pos - p_center;
// update the current position without leaving the screen borders
p_real.setX(std::clamp(p_real.x() + p_delta.x(), 0, screen.width()));
p_real.setY(std::clamp(p_real.y() + p_delta.y(), 0, screen.height()));
// pass the 'real' position and the current delta to the screen center
MouseHandlerBase::Move(0, p_real.x(), p_real.y(), screen.width(), screen.height(), true, p_delta.x(), p_delta.y());
}
else
{
// pass the absolute position
MouseHandlerBase::Move(0, e_pos.x(), e_pos.y(), screen.width(), screen.height());
}
}
}
| 6,734
|
C++
|
.cpp
| 199
| 31.361809
| 136
| 0.70934
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,013
|
dualsense_pad_handler.cpp
|
RPCS3_rpcs3/rpcs3/Input/dualsense_pad_handler.cpp
|
#include "stdafx.h"
#include "dualsense_pad_handler.h"
#include "Emu/Io/pad_config.h"
#include <limits>
LOG_CHANNEL(dualsense_log, "DualSense");
using namespace reports;
template <>
void fmt_class_string<DualSenseDevice::DualSenseDataMode>::format(std::string& out, u64 arg)
{
format_enum(out, arg, [](DualSenseDevice::DualSenseDataMode mode)
{
switch (mode)
{
case DualSenseDevice::DualSenseDataMode::Simple: return "Simple";
case DualSenseDevice::DualSenseDataMode::Enhanced: return "Enhanced";
}
return unknown;
});
}
namespace
{
constexpr id_pair SONY_DUALSENSE_ID_0 = {0x054C, 0x0CE6}; // DualSense
constexpr id_pair SONY_DUALSENSE_ID_1 = {0x054C, 0x0DF2}; // DualSense Edge
}
dualsense_pad_handler::dualsense_pad_handler()
: hid_pad_handler<DualSenseDevice>(pad_handler::dualsense, {SONY_DUALSENSE_ID_0, SONY_DUALSENSE_ID_1})
{
// Unique names for the config files and our pad settings dialog
button_list =
{
{ DualSenseKeyCodes::None, "" },
{ DualSenseKeyCodes::Triangle, "Triangle" },
{ DualSenseKeyCodes::Circle, "Circle" },
{ DualSenseKeyCodes::Cross, "Cross" },
{ DualSenseKeyCodes::Square, "Square" },
{ DualSenseKeyCodes::Left, "Left" },
{ DualSenseKeyCodes::Right, "Right" },
{ DualSenseKeyCodes::Up, "Up" },
{ DualSenseKeyCodes::Down, "Down" },
{ DualSenseKeyCodes::R1, "R1" },
{ DualSenseKeyCodes::R2, "R2" },
{ DualSenseKeyCodes::R3, "R3" },
{ DualSenseKeyCodes::Options, "Options" },
{ DualSenseKeyCodes::Share, "Share" },
{ DualSenseKeyCodes::PSButton, "PS Button" },
{ DualSenseKeyCodes::Mic, "Mic" },
{ DualSenseKeyCodes::TouchPad, "Touch Pad" },
{ DualSenseKeyCodes::Touch_L, "Touch Left" },
{ DualSenseKeyCodes::Touch_R, "Touch Right" },
{ DualSenseKeyCodes::Touch_U, "Touch Up" },
{ DualSenseKeyCodes::Touch_D, "Touch Down" },
{ DualSenseKeyCodes::L1, "L1" },
{ DualSenseKeyCodes::L2, "L2" },
{ DualSenseKeyCodes::L3, "L3" },
{ DualSenseKeyCodes::LSXNeg, "LS X-" },
{ DualSenseKeyCodes::LSXPos, "LS X+" },
{ DualSenseKeyCodes::LSYPos, "LS Y+" },
{ DualSenseKeyCodes::LSYNeg, "LS Y-" },
{ DualSenseKeyCodes::RSXNeg, "RS X-" },
{ DualSenseKeyCodes::RSXPos, "RS X+" },
{ DualSenseKeyCodes::RSYPos, "RS Y+" },
{ DualSenseKeyCodes::RSYNeg, "RS Y-" },
{ DualSenseKeyCodes::EdgeFnL, "FN L" },
{ DualSenseKeyCodes::EdgeFnR, "FN R" },
{ DualSenseKeyCodes::EdgeLB, "LB" },
{ DualSenseKeyCodes::EdgeRB, "RB" },
};
init_configs();
// Define border values
thumb_max = 255;
trigger_min = 0;
trigger_max = 255;
// Set capabilities
b_has_config = true;
b_has_rumble = true;
b_has_motion = true;
b_has_deadzones = true;
b_has_led = true;
b_has_rgb = true;
b_has_player_led = true;
b_has_battery = true;
b_has_battery_led = true;
m_name_string = "DualSense Pad #";
m_max_devices = CELL_PAD_MAX_PORT_NUM;
m_trigger_threshold = trigger_max / 2;
m_thumb_threshold = thumb_max / 2;
}
void dualsense_pad_handler::check_add_device(hid_device* hidDevice, std::string_view path, std::wstring_view wide_serial)
{
if (!hidDevice)
{
return;
}
DualSenseDevice* device = nullptr;
for (auto& controller : m_controllers)
{
ensure(controller.second);
if (!controller.second->hidDevice)
{
device = controller.second.get();
break;
}
}
if (!device)
{
return;
}
std::array<u8, std::max(DUALSENSE_FIRMWARE_REPORT_SIZE, DUALSENSE_PAIRING_REPORT_SIZE)> buf{};
buf[0] = 0x09;
// This will give us the bluetooth mac address of the device, regardless if we are on wired or bluetooth.
// So we can't use this to determine if it is a bluetooth device or not.
// Will also enable enhanced feature reports for bluetooth.
int res = hid_get_feature_report(hidDevice, buf.data(), buf.size());
if (res < 0 || buf[0] != 0x09)
{
dualsense_log.error("check_add_device: hid_get_feature_report 0x09 failed! result=%d, buf[0]=0x%x, error=%s", res, buf[0], hid_error(hidDevice));
hid_close(hidDevice);
return;
}
std::string serial;
if (res == 21)
{
serial = fmt::format("%x%x%x%x%x%x", buf[6], buf[5], buf[4], buf[3], buf[2], buf[1]);
device->data_mode = DualSenseDevice::DualSenseDataMode::Enhanced;
}
else
{
// We're probably on Bluetooth in this case, but for whatever reason the feature report failed.
// This will give us a less capable fallback.
dualsense_log.warning("check_add_device: hid_get_feature_report returned wrong size! Falling back to simple mode. (result=%d)", res);
device->data_mode = DualSenseDevice::DualSenseDataMode::Simple;
for (wchar_t ch : wide_serial)
serial += static_cast<uchar>(ch);
}
device->hidDevice = hidDevice;
if (!get_calibration_data(device))
{
dualsense_log.error("check_add_device: get_calibration_data failed!");
device->close();
return;
}
u32 hw_version{};
u16 fw_version{};
u32 fw_version2{};
buf = {};
buf[0] = 0x20;
res = hid_get_feature_report(hidDevice, buf.data(), DUALSENSE_FIRMWARE_REPORT_SIZE);
if (res != DUALSENSE_FIRMWARE_REPORT_SIZE || buf[0] != 0x20) // Old versions return 65, newer versions return 64
{
dualsense_log.error("check_add_device: hid_get_feature_report 0x20 failed! Could not retrieve firmware version! result=%d, buf[0]=0x%x, error=%s", res, buf[0], hid_error(hidDevice));
}
else
{
hw_version = read_u32(&buf[24]);
fw_version2 = read_u32(&buf[28]);
fw_version = static_cast<u16>(buf[44]) | (static_cast<u16>(buf[45]) << 8);
}
if (hid_set_nonblocking(hidDevice, 1) == -1)
{
dualsense_log.error("check_add_device: hid_set_nonblocking failed! Reason: %s", hid_error(hidDevice));
device->close();
return;
}
device->has_calib_data = true;
device->path = path;
// Get feature set
if (const hid_device_info* info = hid_get_device_info(device->hidDevice))
{
if (info->product_id == SONY_DUALSENSE_ID_1.m_pid)
{
device->feature_set = DualSenseDevice::DualSenseFeatureSet::Edge;
dualsense_log.notice("check_add_device: device is DualSense Edge: vid=0x%x, pid=0x%x, path='%s'", info->vendor_id, info->product_id, path);
}
}
else
{
dualsense_log.warning("check_add_device: hid_get_device_info failed for determining feature set! Reason: %s", hid_error(hidDevice));
}
// Activate
if (send_output_report(device) == -1)
{
dualsense_log.error("check_add_device: send_output_report failed! Reason: %s", hid_error(hidDevice));
}
// Get bluetooth information
get_data(device);
dualsense_log.notice("Added device: bluetooth=%d, data_mode=%s, serial='%s', hw_version: 0x%x, fw_version: 0x%x (0x%x), path='%s'", device->bt_controller, device->data_mode, serial, hw_version, fw_version, fw_version2, device->path);
}
void dualsense_pad_handler::init_config(cfg_pad* cfg)
{
if (!cfg) return;
// Set default button mapping
cfg->ls_left.def = ::at32(button_list, DualSenseKeyCodes::LSXNeg);
cfg->ls_down.def = ::at32(button_list, DualSenseKeyCodes::LSYNeg);
cfg->ls_right.def = ::at32(button_list, DualSenseKeyCodes::LSXPos);
cfg->ls_up.def = ::at32(button_list, DualSenseKeyCodes::LSYPos);
cfg->rs_left.def = ::at32(button_list, DualSenseKeyCodes::RSXNeg);
cfg->rs_down.def = ::at32(button_list, DualSenseKeyCodes::RSYNeg);
cfg->rs_right.def = ::at32(button_list, DualSenseKeyCodes::RSXPos);
cfg->rs_up.def = ::at32(button_list, DualSenseKeyCodes::RSYPos);
cfg->start.def = ::at32(button_list, DualSenseKeyCodes::Options);
cfg->select.def = ::at32(button_list, DualSenseKeyCodes::Share);
cfg->ps.def = ::at32(button_list, DualSenseKeyCodes::PSButton);
cfg->square.def = ::at32(button_list, DualSenseKeyCodes::Square);
cfg->cross.def = ::at32(button_list, DualSenseKeyCodes::Cross);
cfg->circle.def = ::at32(button_list, DualSenseKeyCodes::Circle);
cfg->triangle.def = ::at32(button_list, DualSenseKeyCodes::Triangle);
cfg->left.def = ::at32(button_list, DualSenseKeyCodes::Left);
cfg->down.def = ::at32(button_list, DualSenseKeyCodes::Down);
cfg->right.def = ::at32(button_list, DualSenseKeyCodes::Right);
cfg->up.def = ::at32(button_list, DualSenseKeyCodes::Up);
cfg->r1.def = ::at32(button_list, DualSenseKeyCodes::R1);
cfg->r2.def = ::at32(button_list, DualSenseKeyCodes::R2);
cfg->r3.def = ::at32(button_list, DualSenseKeyCodes::R3);
cfg->l1.def = ::at32(button_list, DualSenseKeyCodes::L1);
cfg->l2.def = ::at32(button_list, DualSenseKeyCodes::L2);
cfg->l3.def = ::at32(button_list, DualSenseKeyCodes::L3);
cfg->pressure_intensity_button.def = ::at32(button_list, DualSenseKeyCodes::None);
cfg->analog_limiter_button.def = ::at32(button_list, DualSenseKeyCodes::None);
// Set default misc variables
cfg->lstick_anti_deadzone.def = static_cast<u32>(0.13 * thumb_max); // 13%
cfg->rstick_anti_deadzone.def = static_cast<u32>(0.13 * thumb_max); // 13%
cfg->lstickdeadzone.def = 40; // between 0 and 255
cfg->rstickdeadzone.def = 40; // between 0 and 255
cfg->ltriggerthreshold.def = 0; // between 0 and 255
cfg->rtriggerthreshold.def = 0; // between 0 and 255
cfg->lpadsquircling.def = 8000;
cfg->rpadsquircling.def = 8000;
// Set default color value
cfg->colorR.def = 0;
cfg->colorG.def = 0;
cfg->colorB.def = 20;
// Set default LED options
cfg->led_battery_indicator.def = false;
cfg->led_battery_indicator_brightness.def = 10;
cfg->led_low_battery_blink.def = true;
// apply defaults
cfg->from_default();
}
dualsense_pad_handler::DataStatus dualsense_pad_handler::get_data(DualSenseDevice* device)
{
if (!device)
return DataStatus::ReadError;
std::array<u8, 128> buf{};
const int res = hid_read(device->hidDevice, buf.data(), buf.size());
if (res == -1)
{
// looks like controller disconnected or read error
return DataStatus::ReadError;
}
if (res == 0)
return DataStatus::NoNewData;
u8 offset = 0;
switch (buf[0])
{
case 0x01:
{
if (res == sizeof(dualsense_input_report_bt))
{
device->data_mode = DualSenseDevice::DualSenseDataMode::Simple;
device->bt_controller = true;
}
else
{
device->data_mode = DualSenseDevice::DualSenseDataMode::Enhanced;
device->bt_controller = false;
}
offset = offsetof(dualsense_input_report_usb, common);
break;
}
case 0x31:
{
device->data_mode = DualSenseDevice::DualSenseDataMode::Enhanced;
device->bt_controller = true;
offset = offsetof(dualsense_input_report_bt, common);
const u8 btHdr = 0xA1;
const u32 crcHdr = CRCPP::CRC::Calculate(&btHdr, 1, crcTable);
const u32 crcCalc = CRCPP::CRC::Calculate(buf.data(), offsetof(dualsense_input_report_bt, crc32), crcTable, crcHdr);
const u32 crcReported = read_u32(&buf[offsetof(dualsense_input_report_bt, crc32)]);
if (crcCalc != crcReported)
{
dualsense_log.warning("Data packet CRC check failed, ignoring! Received 0x%x, Expected 0x%x", crcReported, crcCalc);
return DataStatus::NoNewData;
}
break;
}
default:
return DataStatus::NoNewData;
}
if (device->has_calib_data)
{
int calib_offset = offset + offsetof(dualsense_input_report_common, gyro);
for (int i = 0; i < CalibIndex::COUNT; ++i)
{
const s16 raw_value = read_s16(&buf[calib_offset]);
const s16 cal_value = apply_calibration(raw_value, device->calib_data[i]);
buf[calib_offset++] = (static_cast<u16>(cal_value) >> 0) & 0xFF;
buf[calib_offset++] = (static_cast<u16>(cal_value) >> 8) & 0xFF;
}
}
std::memcpy(&device->report, &buf[offset], sizeof(dualsense_input_report_common));
// For now let's only get battery info in enhanced mode
if (device->data_mode == DualSenseDevice::DualSenseDataMode::Enhanced)
{
const u8 battery_state = device->report.status;
const u8 battery_value = battery_state & 0x0F; // 10% per unit, starting with 0-9%. So 100% equals unit 10
const u8 charge_info = (battery_state & 0xF0) >> 4;
switch (charge_info)
{
case 0x0:
device->battery_level = battery_value;
device->cable_state = 0;
break;
case 0x1:
device->battery_level = battery_value;
device->cable_state = 1;
break;
case 0x2:
device->battery_level = 10;
device->cable_state = 1;
break;
default:
// We don't care about the other values. Just set battery to 0.
device->battery_level = 0;
device->cable_state = 0;
break;
}
}
return DataStatus::NewData;
}
bool dualsense_pad_handler::get_calibration_data(DualSenseDevice* dev) const
{
if (!dev || !dev->hidDevice)
{
dualsense_log.error("get_calibration_data called with null device");
return false;
}
std::array<u8, 64> buf{};
if (dev->bt_controller)
{
for (int tries = 0; tries < 3; ++tries)
{
buf = {};
buf[0] = 0x05;
if (int res = hid_get_feature_report(dev->hidDevice, buf.data(), DUALSENSE_CALIBRATION_REPORT_SIZE); res != DUALSENSE_CALIBRATION_REPORT_SIZE || buf[0] != 0x05)
{
dualsense_log.error("get_calibration_data: hid_get_feature_report 0x05 for bluetooth controller failed! result=%d, buf[0]=0x%x, error=%s", res, buf[0], hid_error(dev->hidDevice));
return false;
}
const u8 btHdr = 0xA3;
const u32 crcHdr = CRCPP::CRC::Calculate(&btHdr, 1, crcTable);
const u32 crcCalc = CRCPP::CRC::Calculate(buf.data(), (DUALSENSE_CALIBRATION_REPORT_SIZE - 4), crcTable, crcHdr);
const u32 crcReported = read_u32(&buf[DUALSENSE_CALIBRATION_REPORT_SIZE - 4]);
if (crcCalc == crcReported)
break;
dualsense_log.warning("Calibration CRC check failed! Will retry up to 3 times. Received 0x%x, Expected 0x%x", crcReported, crcCalc);
if (tries == 2)
{
dualsense_log.error("Calibration CRC check failed too many times!");
return false;
}
}
}
else
{
buf[0] = 0x05;
if (int res = hid_get_feature_report(dev->hidDevice, buf.data(), DUALSENSE_CALIBRATION_REPORT_SIZE); res != DUALSENSE_CALIBRATION_REPORT_SIZE || buf[0] != 0x05)
{
dualsense_log.error("get_calibration_data: hid_get_feature_report 0x05 for wired controller failed! result=%d, buf[0]=0x%x, error=%s", res, buf[0], hid_error(dev->hidDevice));
return false;
}
}
dev->calib_data[CalibIndex::PITCH].bias = read_s16(&buf[1]);
dev->calib_data[CalibIndex::YAW].bias = read_s16(&buf[3]);
dev->calib_data[CalibIndex::ROLL].bias = read_s16(&buf[5]);
const s16 pitch_plus = read_s16(&buf[7]);
const s16 pitch_minus = read_s16(&buf[9]);
const s16 yaw_plus = read_s16(&buf[11]);
const s16 yaw_minus = read_s16(&buf[13]);
const s16 roll_plus = read_s16(&buf[15]);
const s16 roll_minus = read_s16(&buf[17]);
// Confirm correctness. Need confirmation with dongle with no active controller
if (pitch_plus <= 0 || yaw_plus <= 0 || roll_plus <= 0 ||
pitch_minus >= 0 || yaw_minus >= 0 || roll_minus >= 0)
{
dualsense_log.error("get_calibration_data: calibration data check failed! pitch_plus=%d, pitch_minus=%d, roll_plus=%d, roll_minus=%d, yaw_plus=%d, yaw_minus=%d",
pitch_plus, pitch_minus, roll_plus, roll_minus, yaw_plus, yaw_minus);
}
const s32 gyro_speed_scale = read_s16(&buf[19]) + read_s16(&buf[21]);
dev->calib_data[CalibIndex::PITCH].sens_numer = gyro_speed_scale * DUALSENSE_GYRO_RES_PER_DEG_S;
dev->calib_data[CalibIndex::PITCH].sens_denom = pitch_plus - pitch_minus;
dev->calib_data[CalibIndex::YAW].sens_numer = gyro_speed_scale * DUALSENSE_GYRO_RES_PER_DEG_S;
dev->calib_data[CalibIndex::YAW].sens_denom = yaw_plus - yaw_minus;
dev->calib_data[CalibIndex::ROLL].sens_numer = gyro_speed_scale * DUALSENSE_GYRO_RES_PER_DEG_S;
dev->calib_data[CalibIndex::ROLL].sens_denom = roll_plus - roll_minus;
const s16 accel_x_plus = read_s16(&buf[23]);
const s16 accel_x_minus = read_s16(&buf[25]);
const s16 accel_y_plus = read_s16(&buf[27]);
const s16 accel_y_minus = read_s16(&buf[29]);
const s16 accel_z_plus = read_s16(&buf[31]);
const s16 accel_z_minus = read_s16(&buf[33]);
const s32 accel_x_range = accel_x_plus - accel_x_minus;
const s32 accel_y_range = accel_y_plus - accel_y_minus;
const s32 accel_z_range = accel_z_plus - accel_z_minus;
dev->calib_data[CalibIndex::X].bias = accel_x_plus - accel_x_range / 2;
dev->calib_data[CalibIndex::X].sens_numer = 2 * DUALSENSE_ACC_RES_PER_G;
dev->calib_data[CalibIndex::X].sens_denom = accel_x_range;
dev->calib_data[CalibIndex::Y].bias = accel_y_plus - accel_y_range / 2;
dev->calib_data[CalibIndex::Y].sens_numer = 2 * DUALSENSE_ACC_RES_PER_G;
dev->calib_data[CalibIndex::Y].sens_denom = accel_y_range;
dev->calib_data[CalibIndex::Z].bias = accel_z_plus - accel_z_range / 2;
dev->calib_data[CalibIndex::Z].sens_numer = 2 * DUALSENSE_ACC_RES_PER_G;
dev->calib_data[CalibIndex::Z].sens_denom = accel_z_range;
// Make sure data 'looks' valid, dongle will report invalid calibration data with no controller connected
for (usz i = 0; i < dev->calib_data.size(); i++)
{
CalibData& data = dev->calib_data[i];
if (data.sens_denom == 0)
{
dualsense_log.error("GetCalibrationData: Invalid accelerometer calibration data for axis %d, disabling calibration.", i);
data.bias = 0;
data.sens_numer = 4 * DUALSENSE_ACC_RES_PER_G;
data.sens_denom = std::numeric_limits<s16>::max();
}
}
return true;
}
bool dualsense_pad_handler::get_is_left_trigger(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
return keyCode == DualSenseKeyCodes::L2;
}
bool dualsense_pad_handler::get_is_right_trigger(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
return keyCode == DualSenseKeyCodes::R2;
}
bool dualsense_pad_handler::get_is_left_stick(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
switch (keyCode)
{
case DualSenseKeyCodes::LSXNeg:
case DualSenseKeyCodes::LSXPos:
case DualSenseKeyCodes::LSYPos:
case DualSenseKeyCodes::LSYNeg:
return true;
default:
return false;
}
}
bool dualsense_pad_handler::get_is_right_stick(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
switch (keyCode)
{
case DualSenseKeyCodes::RSXNeg:
case DualSenseKeyCodes::RSXPos:
case DualSenseKeyCodes::RSYPos:
case DualSenseKeyCodes::RSYNeg:
return true;
default:
return false;
}
}
bool dualsense_pad_handler::get_is_touch_pad_motion(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
switch (keyCode)
{
case DualSenseKeyCodes::Touch_L:
case DualSenseKeyCodes::Touch_R:
case DualSenseKeyCodes::Touch_U:
case DualSenseKeyCodes::Touch_D:
return true;
default:
return false;
}
}
PadHandlerBase::connection dualsense_pad_handler::update_connection(const std::shared_ptr<PadDevice>& device)
{
DualSenseDevice* dev = static_cast<DualSenseDevice*>(device.get());
if (!dev || dev->path.empty())
return connection::disconnected;
if (dev->hidDevice == nullptr)
{
// try to reconnect
if (hid_device* hid_dev = hid_open_path(dev->path.c_str()))
{
if (hid_set_nonblocking(hid_dev, 1) == -1)
{
dualsense_log.error("Reconnecting Device %s: hid_set_nonblocking failed with error %s", dev->path, hid_error(hid_dev));
}
dev->hidDevice = hid_dev;
if (!dev->has_calib_data)
{
dev->has_calib_data = get_calibration_data(dev);
}
}
else
{
// nope, not there
return connection::disconnected;
}
}
if (get_data(dev) == DataStatus::ReadError)
{
// this also can mean disconnected, either way deal with it on next loop and reconnect
dev->close();
return connection::no_data;
}
return connection::connected;
}
void dualsense_pad_handler::get_extended_info(const pad_ensemble& binding)
{
const auto& device = binding.device;
const auto& pad = binding.pad;
DualSenseDevice* dev = static_cast<DualSenseDevice*>(device.get());
if (!dev || !pad)
return;
pad->m_battery_level = dev->battery_level;
pad->m_cable_state = dev->cable_state;
const dualsense_input_report_common& input = dev->report;
// these values come already calibrated, all we need to do is convert to ds3 range
// gyroY is yaw, which is all that we need
//f32 gyroX = static_cast<s16>(input.gyro[0]) / static_cast<f32>(DUALSENSE_GYRO_RES_PER_DEG_S) * -1.f;
f32 gyroY = static_cast<s16>(input.gyro[1]) / static_cast<f32>(DUALSENSE_GYRO_RES_PER_DEG_S) * -1.f;
//f32 gyroZ = static_cast<s16>(input.gyro[2]) / static_cast<f32>(DUALSENSE_GYRO_RES_PER_DEG_S) * -1.f;
// accel
f32 accelX = static_cast<s16>(input.accel[0]) / static_cast<f32>(DUALSENSE_ACC_RES_PER_G) * -1;
f32 accelY = static_cast<s16>(input.accel[1]) / static_cast<f32>(DUALSENSE_ACC_RES_PER_G) * -1;
f32 accelZ = static_cast<s16>(input.accel[2]) / static_cast<f32>(DUALSENSE_ACC_RES_PER_G) * -1;
// now just use formula from ds3
accelX = accelX * 113 + 512;
accelY = accelY * 113 + 512;
accelZ = accelZ * 113 + 512;
// Convert to ds3. The ds3 resolution is 123/90°/sec.
gyroY = gyroY * (123.f / 90.f) + 512;
pad->m_sensors[0].m_value = Clamp0To1023(accelX);
pad->m_sensors[1].m_value = Clamp0To1023(accelY);
pad->m_sensors[2].m_value = Clamp0To1023(accelZ);
pad->m_sensors[3].m_value = Clamp0To1023(gyroY);
}
std::unordered_map<u64, u16> dualsense_pad_handler::get_button_values(const std::shared_ptr<PadDevice>& device)
{
std::unordered_map<u64, u16> keyBuffer;
DualSenseDevice* dev = static_cast<DualSenseDevice*>(device.get());
if (!dev)
return keyBuffer;
const dualsense_input_report_common& input = dev->report;
const bool is_simple_mode = dev->data_mode == DualSenseDevice::DualSenseDataMode::Simple;
// Left Stick X Axis
keyBuffer[DualSenseKeyCodes::LSXNeg] = Clamp0To255((127.5f - input.x) * 2.0f);
keyBuffer[DualSenseKeyCodes::LSXPos] = Clamp0To255((input.x - 127.5f) * 2.0f);
// Left Stick Y Axis (Up is the negative for some reason)
keyBuffer[DualSenseKeyCodes::LSYNeg] = Clamp0To255((input.y - 127.5f) * 2.0f);
keyBuffer[DualSenseKeyCodes::LSYPos] = Clamp0To255((127.5f - input.y) * 2.0f);
// Right Stick X Axis
keyBuffer[DualSenseKeyCodes::RSXNeg] = Clamp0To255((127.5f - input.rx) * 2.0f);
keyBuffer[DualSenseKeyCodes::RSXPos] = Clamp0To255((input.rx - 127.5f) * 2.0f);
// Right Stick Y Axis (Up is the negative for some reason)
keyBuffer[DualSenseKeyCodes::RSYNeg] = Clamp0To255((input.ry - 127.5f) * 2.0f);
keyBuffer[DualSenseKeyCodes::RSYPos] = Clamp0To255((127.5f - input.ry) * 2.0f);
keyBuffer[DualSenseKeyCodes::L2] = is_simple_mode ? input.buttons[0] : input.z;
keyBuffer[DualSenseKeyCodes::R2] = is_simple_mode ? input.buttons[1] : input.rz;
u8 data = (is_simple_mode ? input.z : input.buttons[0]) & 0xf;
switch (data)
{
case 0x08: // none pressed
keyBuffer[DualSenseKeyCodes::Up] = 0;
keyBuffer[DualSenseKeyCodes::Down] = 0;
keyBuffer[DualSenseKeyCodes::Left] = 0;
keyBuffer[DualSenseKeyCodes::Right] = 0;
break;
case 0x07: // NW...left and up
keyBuffer[DualSenseKeyCodes::Up] = 255;
keyBuffer[DualSenseKeyCodes::Down] = 0;
keyBuffer[DualSenseKeyCodes::Left] = 255;
keyBuffer[DualSenseKeyCodes::Right] = 0;
break;
case 0x06: // W..left
keyBuffer[DualSenseKeyCodes::Up] = 0;
keyBuffer[DualSenseKeyCodes::Down] = 0;
keyBuffer[DualSenseKeyCodes::Left] = 255;
keyBuffer[DualSenseKeyCodes::Right] = 0;
break;
case 0x05: // SW..left down
keyBuffer[DualSenseKeyCodes::Up] = 0;
keyBuffer[DualSenseKeyCodes::Down] = 255;
keyBuffer[DualSenseKeyCodes::Left] = 255;
keyBuffer[DualSenseKeyCodes::Right] = 0;
break;
case 0x04: // S..down
keyBuffer[DualSenseKeyCodes::Up] = 0;
keyBuffer[DualSenseKeyCodes::Down] = 255;
keyBuffer[DualSenseKeyCodes::Left] = 0;
keyBuffer[DualSenseKeyCodes::Right] = 0;
break;
case 0x03: // SE..down and right
keyBuffer[DualSenseKeyCodes::Up] = 0;
keyBuffer[DualSenseKeyCodes::Down] = 255;
keyBuffer[DualSenseKeyCodes::Left] = 0;
keyBuffer[DualSenseKeyCodes::Right] = 255;
break;
case 0x02: // E... right
keyBuffer[DualSenseKeyCodes::Up] = 0;
keyBuffer[DualSenseKeyCodes::Down] = 0;
keyBuffer[DualSenseKeyCodes::Left] = 0;
keyBuffer[DualSenseKeyCodes::Right] = 255;
break;
case 0x01: // NE.. up right
keyBuffer[DualSenseKeyCodes::Up] = 255;
keyBuffer[DualSenseKeyCodes::Down] = 0;
keyBuffer[DualSenseKeyCodes::Left] = 0;
keyBuffer[DualSenseKeyCodes::Right] = 255;
break;
case 0x00: // n.. up
keyBuffer[DualSenseKeyCodes::Up] = 255;
keyBuffer[DualSenseKeyCodes::Down] = 0;
keyBuffer[DualSenseKeyCodes::Left] = 0;
keyBuffer[DualSenseKeyCodes::Right] = 0;
break;
default:
fmt::throw_exception("dualsense dpad state encountered unexpected input");
}
data = (is_simple_mode ? input.z : input.buttons[0]) >> 4;
keyBuffer[DualSenseKeyCodes::Square] = ((data & 0x01) != 0) ? 255 : 0;
keyBuffer[DualSenseKeyCodes::Cross] = ((data & 0x02) != 0) ? 255 : 0;
keyBuffer[DualSenseKeyCodes::Circle] = ((data & 0x04) != 0) ? 255 : 0;
keyBuffer[DualSenseKeyCodes::Triangle] = ((data & 0x08) != 0) ? 255 : 0;
data = (is_simple_mode ? input.rz : input.buttons[1]);
keyBuffer[DualSenseKeyCodes::L1] = ((data & 0x01) != 0) ? 255 : 0;
keyBuffer[DualSenseKeyCodes::R1] = ((data & 0x02) != 0) ? 255 : 0;
//keyBuffer[DualSenseKeyCodes::L2] = ((data & 0x04) != 0) ? 255 : 0; // active when L2 is pressed
//keyBuffer[DualSenseKeyCodes::R2] = ((data & 0x08) != 0) ? 255 : 0; // active when R2 is pressed
keyBuffer[DualSenseKeyCodes::Share] = ((data & 0x10) != 0) ? 255 : 0;
keyBuffer[DualSenseKeyCodes::Options] = ((data & 0x20) != 0) ? 255 : 0;
keyBuffer[DualSenseKeyCodes::L3] = ((data & 0x40) != 0) ? 255 : 0;
keyBuffer[DualSenseKeyCodes::R3] = ((data & 0x80) != 0) ? 255 : 0;
data = (is_simple_mode ? input.seq_number : input.buttons[2]);
keyBuffer[DualSenseKeyCodes::PSButton] = ((data & 0x01) != 0) ? 255 : 0;
keyBuffer[DualSenseKeyCodes::TouchPad] = ((data & 0x02) != 0) ? 255 : 0;
keyBuffer[DualSenseKeyCodes::Mic] = ((data & 0x04) != 0) ? 255 : 0;
// Touch Pad
for (const dualsense_touch_point& point : input.points)
{
if (!(point.contact & DUALSENSE_TOUCH_POINT_INACTIVE))
{
const s32 x = (point.x_hi << 8) | point.x_lo;
const s32 y = (point.y_hi << 4) | point.y_lo;
const f32 x_scaled = ScaledInput(static_cast<float>(x), 0.0f, static_cast<float>(DUALSENSE_TOUCHPAD_WIDTH), 0.0f, 255.0f);
const f32 y_scaled = ScaledInput(static_cast<float>(y), 0.0f, static_cast<float>(DUALSENSE_TOUCHPAD_HEIGHT), 0.0f, 255.0f);
keyBuffer[DualSenseKeyCodes::Touch_L] = Clamp0To255((127.5f - x_scaled) * 2.0f);
keyBuffer[DualSenseKeyCodes::Touch_R] = Clamp0To255((x_scaled - 127.5f) * 2.0f);
keyBuffer[DualSenseKeyCodes::Touch_U] = Clamp0To255((127.5f - y_scaled) * 2.0f);
keyBuffer[DualSenseKeyCodes::Touch_D] = Clamp0To255((y_scaled - 127.5f) * 2.0f);
}
}
if (dev->feature_set == DualSenseDevice::DualSenseFeatureSet::Edge)
{
keyBuffer[DualSenseKeyCodes::EdgeFnL] = ((data & 0x10) != 0) ? 255 : 0;
keyBuffer[DualSenseKeyCodes::EdgeFnR] = ((data & 0x20) != 0) ? 255 : 0;
keyBuffer[DualSenseKeyCodes::EdgeLB] = ((data & 0x40) != 0) ? 255 : 0;
keyBuffer[DualSenseKeyCodes::EdgeRB] = ((data & 0x80) != 0) ? 255 : 0;
}
return keyBuffer;
}
pad_preview_values dualsense_pad_handler::get_preview_values(const std::unordered_map<u64, u16>& data)
{
return {
::at32(data, L2),
::at32(data, R2),
::at32(data, LSXPos) - ::at32(data, LSXNeg),
::at32(data, LSYPos) - ::at32(data, LSYNeg),
::at32(data, RSXPos) - ::at32(data, RSXNeg),
::at32(data, RSYPos) - ::at32(data, RSYNeg)
};
}
dualsense_pad_handler::~dualsense_pad_handler()
{
for (auto& controller : m_controllers)
{
if (controller.second && controller.second->hidDevice)
{
// Disable vibration
controller.second->small_motor = 0;
controller.second->large_motor = 0;
// Turns off the lights (disabled due to user complaints)
//controller.second->release_leds = true;
if (send_output_report(controller.second.get()) == -1)
{
dualsense_log.error("~dualsense_pad_handler: send_output_report failed! Reason: %s", hid_error(controller.second->hidDevice));
}
}
}
}
int dualsense_pad_handler::send_output_report(DualSenseDevice* device)
{
if (!device || !device->hidDevice)
return -2;
const cfg_pad* config = device->config;
if (config == nullptr)
return -2; // hid_write returns -1 on error
dualsense_output_report_common common{};
// Only initialize lightbar in the first output report. The controller didn't seem to update the player LEDs correctly otherwise. (Might be placebo)
if (device->init_lightbar)
{
device->init_lightbar = false;
device->lightbar_on = true;
device->lightbar_on_old = true;
common.valid_flag_2 |= VALID_FLAG_2_LIGHTBAR_SETUP_CONTROL_ENABLE;
common.lightbar_setup = LIGHTBAR_SETUP_LIGHT_OFF; // Fade light out.
}
else if (device->release_leds)
{
common.valid_flag_1 |= VALID_FLAG_1_RELEASE_LEDS;
device->release_leds = false;
}
else
{
common.valid_flag_0 |= VALID_FLAG_0_COMPATIBLE_VIBRATION;
common.valid_flag_0 |= VALID_FLAG_0_HAPTICS_SELECT;
common.valid_flag_1 |= VALID_FLAG_1_POWER_SAVE_CONTROL_ENABLE;
common.valid_flag_2 |= VALID_FLAG_2_IMPROVED_RUMBLE_EMULATION;
common.motor_left = device->large_motor;
common.motor_right = device->small_motor;
if (device->update_lightbar)
{
device->update_lightbar = false;
common.valid_flag_1 |= VALID_FLAG_1_LIGHTBAR_CONTROL_ENABLE;
if (device->lightbar_on)
{
common.lightbar_r = config->colorR; // red
common.lightbar_g = config->colorG; // green
common.lightbar_b = config->colorB; // blue
}
else
{
common.lightbar_r = 0;
common.lightbar_g = 0;
common.lightbar_b = 0;
}
device->lightbar_on_old = device->lightbar_on;
}
if (device->update_player_leds)
{
device->update_player_leds = false;
// The dualsense controller uses 5 LEDs to indicate the player ID.
// Use OR with 0x1, 0x2, 0x4, 0x8 and 0x10 to enable the LEDs (from leftmost to rightmost).
common.valid_flag_1 |= VALID_FLAG_1_PLAYER_INDICATOR_CONTROL_ENABLE;
if (config->player_led_enabled)
{
switch (device->player_id)
{
case 0: common.player_leds = 0b00100; break;
case 1: common.player_leds = 0b01010; break;
case 2: common.player_leds = 0b10101; break;
case 3: common.player_leds = 0b11011; break;
case 4: common.player_leds = 0b11111; break;
case 5: common.player_leds = 0b10111; break;
case 6: common.player_leds = 0b11101; break;
default:
fmt::throw_exception("Dualsense is using forbidden player id %d", device->player_id);
}
}
else
{
common.player_leds = 0;
}
}
}
if (device->bt_controller)
{
const u8 seq_tag = (device->bt_sequence << 4) | 0x0;
if (++device->bt_sequence >= 16) device->bt_sequence = 0;
dualsense_output_report_bt report{};
report.report_id = 0x31; // report id for bluetooth
report.seq_tag = seq_tag;
report.tag = 0x10; // magic number
report.common = std::move(common);
const u8 btHdr = 0xA2;
const u32 crcHdr = CRCPP::CRC::Calculate(&btHdr, 1, crcTable);
const u32 crcCalc = CRCPP::CRC::Calculate(&report.report_id, (sizeof(dualsense_output_report_bt) - 4), crcTable, crcHdr);
write_to_ptr(report.crc32, crcCalc);
return hid_write(device->hidDevice, &report.report_id, sizeof(dualsense_output_report_bt));
}
dualsense_output_report_usb report{};
report.report_id = 0x02; // report id for usb
report.common = std::move(common);
return hid_write(device->hidDevice, &report.report_id, DUALSENSE_USB_REPORT_SIZE);
}
void dualsense_pad_handler::apply_pad_data(const pad_ensemble& binding)
{
const auto& device = binding.device;
const auto& pad = binding.pad;
DualSenseDevice* dev = static_cast<DualSenseDevice*>(device.get());
if (!dev || !dev->hidDevice || !dev->config || !pad)
return;
cfg_pad* config = dev->config;
// Attempt to send rumble no matter what
const int idx_l = config->switch_vibration_motors ? 1 : 0;
const int idx_s = config->switch_vibration_motors ? 0 : 1;
const u8 speed_large = config->enable_vibration_motor_large ? pad->m_vibrateMotors[idx_l].m_value : 0;
const u8 speed_small = config->enable_vibration_motor_small ? pad->m_vibrateMotors[idx_s].m_value : 0;
const bool wireless = dev->cable_state == 0;
const bool low_battery = dev->battery_level <= 1;
const bool is_blinking = dev->led_delay_on > 0 || dev->led_delay_off > 0;
// Blink LED when battery is low
if (config->led_low_battery_blink)
{
// we are now wired or have okay battery level -> stop blinking
if (is_blinking && !(wireless && low_battery))
{
dev->lightbar_on = true;
dev->led_delay_on = 0;
dev->led_delay_off = 0;
dev->update_lightbar = true;
}
// we are now wireless and low on battery -> blink
else if (!is_blinking && wireless && low_battery)
{
dev->led_delay_on = 100;
dev->led_delay_off = 100;
dev->update_lightbar = true;
}
// Turn lightbar on and off in an interval. I wanted to do an automatic pulse, but I haven't found out how to do that yet.
if (dev->led_delay_on > 0)
{
if (const steady_clock::time_point now = steady_clock::now(); (now - dev->last_lightbar_time) > 500ms)
{
dev->lightbar_on = !dev->lightbar_on;
dev->last_lightbar_time = now;
dev->update_lightbar = true;
}
}
}
else if (!dev->lightbar_on)
{
dev->lightbar_on = true;
dev->update_lightbar = true;
}
// Use LEDs to indicate battery level
if (config->led_battery_indicator)
{
// This makes sure that the LED color doesn't update every 1ms. DS4 only reports battery level in 10% increments
if (dev->last_battery_level != dev->battery_level)
{
const u32 combined_color = get_battery_color(dev->battery_level, config->led_battery_indicator_brightness);
config->colorR.set(combined_color >> 8);
config->colorG.set(combined_color & 0xff);
config->colorB.set(0);
dev->update_lightbar = true;
dev->last_battery_level = dev->battery_level;
}
}
if (dev->enable_player_leds != config->player_led_enabled.get())
{
dev->enable_player_leds = config->player_led_enabled.get();
dev->update_player_leds = true;
}
dev->new_output_data |= dev->release_leds || dev->update_player_leds || dev->update_lightbar || dev->large_motor != speed_large || dev->small_motor != speed_small;
dev->large_motor = speed_large;
dev->small_motor = speed_small;
const auto now = steady_clock::now();
const auto elapsed = now - dev->last_output;
if (dev->new_output_data || elapsed > min_output_interval)
{
if (const int res = send_output_report(dev); res >= 0)
{
dev->new_output_data = false;
dev->last_output = now;
}
else if (res == -1)
{
dualsense_log.error("apply_pad_data: send_output_report failed! error=%s", hid_error(dev->hidDevice));
}
}
}
void dualsense_pad_handler::SetPadData(const std::string& padId, u8 player_id, u8 large_motor, u8 small_motor, s32 r, s32 g, s32 b, bool player_led, bool battery_led, u32 battery_led_brightness)
{
std::shared_ptr<DualSenseDevice> device = get_hid_device(padId);
if (device == nullptr || device->hidDevice == nullptr)
return;
// Set the device's motor speeds to our requested values 0-255
device->large_motor = large_motor;
device->small_motor = small_motor;
device->player_id = player_id;
device->config = get_config(padId);
ensure(device->config);
device->update_lightbar = true;
device->update_player_leds = true;
device->config->player_led_enabled.set(player_led);
// Set new LED color (see ds4_pad_handler)
if (battery_led)
{
const u32 combined_color = get_battery_color(device->battery_level, battery_led_brightness);
device->config->colorR.set(combined_color >> 8);
device->config->colorG.set(combined_color & 0xff);
device->config->colorB.set(0);
}
else if (r >= 0 && g >= 0 && b >= 0 && r <= 255 && g <= 255 && b <= 255)
{
device->config->colorR.set(r);
device->config->colorG.set(g);
device->config->colorB.set(b);
}
if (device->init_lightbar)
{
// Initialize first
if (send_output_report(device.get()) == -1)
{
dualsense_log.error("SetPadData: send_output_report failed! Reason: %s", hid_error(device->hidDevice));
}
}
// Start/Stop the engines :)
if (send_output_report(device.get()) == -1)
{
dualsense_log.error("SetPadData: send_output_report failed! Reason: %s", hid_error(device->hidDevice));
}
}
u32 dualsense_pad_handler::get_battery_level(const std::string& padId)
{
const std::shared_ptr<DualSenseDevice> device = get_hid_device(padId);
if (device == nullptr || device->hidDevice == nullptr)
{
return 0;
}
return std::min<u32>(device->battery_level * 10 + 5, 100); // 10% per unit, starting with 0-9%. So 100% equals unit 10
}
| 36,533
|
C++
|
.cpp
| 923
| 36.820152
| 234
| 0.693977
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,014
|
product_info.cpp
|
RPCS3_rpcs3/rpcs3/Input/product_info.cpp
|
#include "Input/product_info.h"
namespace input
{
static const std::map<product_type, product_info> input_products = {
{
product_type::playstation_3_controller,
{
.type = product_type::playstation_3_controller,
.class_id = CELL_PAD_PCLASS_TYPE_STANDARD,
.vendor_id = vendor_id::sony_corp,
.product_id = product_id::playstation_3_controller,
.pclass_profile = 0x0,
.capabilites = CELL_PAD_CAPABILITY_PS3_CONFORMITY | CELL_PAD_CAPABILITY_PRESS_MODE | CELL_PAD_CAPABILITY_HP_ANALOG_STICK | CELL_PAD_CAPABILITY_ACTUATOR | CELL_PAD_CAPABILITY_SENSOR_MODE
}
},
{
product_type::red_octane_gh_guitar,
{
.type = product_type::red_octane_gh_guitar,
.class_id = CELL_PAD_PCLASS_TYPE_GUITAR,
.vendor_id = vendor_id::sony_cea,
.product_id = product_id::red_octane_gh_guitar,
.pclass_profile =
CELL_PAD_PCLASS_PROFILE_GUITAR_FRET_1 |
CELL_PAD_PCLASS_PROFILE_GUITAR_FRET_2 |
CELL_PAD_PCLASS_PROFILE_GUITAR_FRET_3 |
CELL_PAD_PCLASS_PROFILE_GUITAR_FRET_4 |
CELL_PAD_PCLASS_PROFILE_GUITAR_FRET_5 |
CELL_PAD_PCLASS_PROFILE_GUITAR_STRUM_UP |
CELL_PAD_PCLASS_PROFILE_GUITAR_STRUM_DOWN |
CELL_PAD_PCLASS_PROFILE_GUITAR_WHAMMYBAR,
.capabilites = CELL_PAD_CAPABILITY_PS3_CONFORMITY | CELL_PAD_CAPABILITY_PRESS_MODE | CELL_PAD_CAPABILITY_HP_ANALOG_STICK | CELL_PAD_CAPABILITY_ACTUATOR | CELL_PAD_CAPABILITY_SENSOR_MODE
}
},
{
product_type::harmonix_rockband_guitar,
{
.type = product_type::harmonix_rockband_guitar,
.class_id = CELL_PAD_PCLASS_TYPE_GUITAR,
.vendor_id = vendor_id::sony_cea,
.product_id = product_id::harmonix_rockband_guitar,
.pclass_profile =
CELL_PAD_PCLASS_PROFILE_GUITAR_FRET_1 |
CELL_PAD_PCLASS_PROFILE_GUITAR_FRET_2 |
CELL_PAD_PCLASS_PROFILE_GUITAR_FRET_3 |
CELL_PAD_PCLASS_PROFILE_GUITAR_FRET_4 |
CELL_PAD_PCLASS_PROFILE_GUITAR_FRET_5 |
CELL_PAD_PCLASS_PROFILE_GUITAR_STRUM_UP |
CELL_PAD_PCLASS_PROFILE_GUITAR_STRUM_DOWN |
CELL_PAD_PCLASS_PROFILE_GUITAR_WHAMMYBAR |
CELL_PAD_PCLASS_PROFILE_GUITAR_FRET_H1 |
CELL_PAD_PCLASS_PROFILE_GUITAR_FRET_H2 |
CELL_PAD_PCLASS_PROFILE_GUITAR_FRET_H3 |
CELL_PAD_PCLASS_PROFILE_GUITAR_FRET_H4 |
CELL_PAD_PCLASS_PROFILE_GUITAR_FRET_H5 |
CELL_PAD_PCLASS_PROFILE_GUITAR_5WAY_EFFECT |
CELL_PAD_PCLASS_PROFILE_GUITAR_TILT_SENS,
.capabilites = CELL_PAD_CAPABILITY_PS3_CONFORMITY | CELL_PAD_CAPABILITY_PRESS_MODE | CELL_PAD_CAPABILITY_HP_ANALOG_STICK | CELL_PAD_CAPABILITY_ACTUATOR | CELL_PAD_CAPABILITY_SENSOR_MODE
}
},
{
product_type::red_octane_gh_drum_kit,
{
.type = product_type::red_octane_gh_drum_kit,
.class_id = CELL_PAD_PCLASS_TYPE_DRUM,
.vendor_id = vendor_id::sony_cea,
.product_id = product_id::red_octane_gh_drum_kit,
.pclass_profile =
CELL_PAD_PCLASS_PROFILE_DRUM_SNARE |
CELL_PAD_PCLASS_PROFILE_DRUM_TOM |
CELL_PAD_PCLASS_PROFILE_DRUM_TOM_FLOOR |
CELL_PAD_PCLASS_PROFILE_DRUM_KICK |
CELL_PAD_PCLASS_PROFILE_DRUM_CYM_HiHAT |
CELL_PAD_PCLASS_PROFILE_DRUM_CYM_RIDE,
.capabilites = CELL_PAD_CAPABILITY_PS3_CONFORMITY | CELL_PAD_CAPABILITY_PRESS_MODE | CELL_PAD_CAPABILITY_HP_ANALOG_STICK | CELL_PAD_CAPABILITY_ACTUATOR | CELL_PAD_CAPABILITY_SENSOR_MODE
}
},
{
product_type::harmonix_rockband_drum_kit,
{
.type = product_type::harmonix_rockband_drum_kit,
.class_id = CELL_PAD_PCLASS_TYPE_DRUM,
.vendor_id = vendor_id::sony_cea,
.product_id = product_id::harmonix_rockband_drum_kit,
.pclass_profile =
CELL_PAD_PCLASS_PROFILE_DRUM_SNARE |
CELL_PAD_PCLASS_PROFILE_DRUM_TOM |
CELL_PAD_PCLASS_PROFILE_DRUM_TOM2 |
CELL_PAD_PCLASS_PROFILE_DRUM_TOM_FLOOR |
CELL_PAD_PCLASS_PROFILE_DRUM_KICK |
CELL_PAD_PCLASS_PROFILE_DRUM_CYM_HiHAT |
CELL_PAD_PCLASS_PROFILE_DRUM_CYM_CRASH |
CELL_PAD_PCLASS_PROFILE_DRUM_CYM_RIDE,
.capabilites = CELL_PAD_CAPABILITY_PS3_CONFORMITY | CELL_PAD_CAPABILITY_PRESS_MODE | CELL_PAD_CAPABILITY_HP_ANALOG_STICK | CELL_PAD_CAPABILITY_ACTUATOR | CELL_PAD_CAPABILITY_SENSOR_MODE
}
},
{
product_type::harmonix_rockband_drum_kit_2,
{
.type = product_type::harmonix_rockband_drum_kit_2,
.class_id = CELL_PAD_PCLASS_TYPE_DRUM,
.vendor_id = vendor_id::sony_cea,
.product_id = product_id::harmonix_rockband_drum_kit_2,
.pclass_profile =
CELL_PAD_PCLASS_PROFILE_DRUM_SNARE |
CELL_PAD_PCLASS_PROFILE_DRUM_TOM |
CELL_PAD_PCLASS_PROFILE_DRUM_TOM2 |
CELL_PAD_PCLASS_PROFILE_DRUM_TOM_FLOOR |
CELL_PAD_PCLASS_PROFILE_DRUM_KICK |
CELL_PAD_PCLASS_PROFILE_DRUM_CYM_HiHAT |
CELL_PAD_PCLASS_PROFILE_DRUM_CYM_RIDE,
.capabilites = CELL_PAD_CAPABILITY_PS3_CONFORMITY | CELL_PAD_CAPABILITY_PRESS_MODE | CELL_PAD_CAPABILITY_HP_ANALOG_STICK | CELL_PAD_CAPABILITY_ACTUATOR | CELL_PAD_CAPABILITY_SENSOR_MODE
}
},
{
product_type::rock_revolution_drum_kit,
{
.type = product_type::rock_revolution_drum_kit,
.class_id = CELL_PAD_PCLASS_TYPE_DRUM,
.vendor_id = vendor_id::sony_cea,
.product_id = product_id::rock_revolution_drum_kit,
.pclass_profile =
CELL_PAD_PCLASS_PROFILE_DRUM_SNARE |
CELL_PAD_PCLASS_PROFILE_DRUM_TOM |
CELL_PAD_PCLASS_PROFILE_DRUM_TOM_FLOOR |
CELL_PAD_PCLASS_PROFILE_DRUM_KICK |
CELL_PAD_PCLASS_PROFILE_DRUM_CYM_HiHAT |
CELL_PAD_PCLASS_PROFILE_DRUM_CYM_CRASH |
CELL_PAD_PCLASS_PROFILE_DRUM_CYM_RIDE,
.capabilites = CELL_PAD_CAPABILITY_PS3_CONFORMITY | CELL_PAD_CAPABILITY_PRESS_MODE | CELL_PAD_CAPABILITY_HP_ANALOG_STICK | CELL_PAD_CAPABILITY_ACTUATOR | CELL_PAD_CAPABILITY_SENSOR_MODE
}
},
{
product_type::dj_hero_turntable,
{
.type = product_type::dj_hero_turntable,
.class_id = CELL_PAD_PCLASS_TYPE_DJ,
.vendor_id = vendor_id::sony_cea,
.product_id = product_id::dj_hero_turntable,
.pclass_profile =
CELL_PAD_PCLASS_PROFILE_DJ_MIXER_ATTACK |
CELL_PAD_PCLASS_PROFILE_DJ_MIXER_CROSSFADER |
CELL_PAD_PCLASS_PROFILE_DJ_MIXER_DSP_DIAL |
CELL_PAD_PCLASS_PROFILE_DJ_DECK1_STREAM1 |
CELL_PAD_PCLASS_PROFILE_DJ_DECK1_STREAM2 |
CELL_PAD_PCLASS_PROFILE_DJ_DECK1_STREAM3 |
CELL_PAD_PCLASS_PROFILE_DJ_DECK1_PLATTER |
CELL_PAD_PCLASS_PROFILE_DJ_DECK2_STREAM1 |
CELL_PAD_PCLASS_PROFILE_DJ_DECK2_STREAM2 |
CELL_PAD_PCLASS_PROFILE_DJ_DECK2_STREAM3 |
CELL_PAD_PCLASS_PROFILE_DJ_DECK2_PLATTER,
.capabilites = CELL_PAD_CAPABILITY_PS3_CONFORMITY | CELL_PAD_CAPABILITY_PRESS_MODE | CELL_PAD_CAPABILITY_HP_ANALOG_STICK | CELL_PAD_CAPABILITY_ACTUATOR | CELL_PAD_CAPABILITY_SENSOR_MODE
}
},
{
product_type::dance_dance_revolution_mat,
{
.type = product_type::dance_dance_revolution_mat,
.class_id = CELL_PAD_PCLASS_TYPE_DANCEMAT,
.vendor_id = vendor_id::konami_de,
.product_id = product_id::dance_dance_revolution_mat,
.pclass_profile =
CELL_PAD_PCLASS_PROFILE_DANCEMAT_CIRCLE |
CELL_PAD_PCLASS_PROFILE_DANCEMAT_CROSS |
CELL_PAD_PCLASS_PROFILE_DANCEMAT_TRIANGLE |
CELL_PAD_PCLASS_PROFILE_DANCEMAT_SQUARE |
CELL_PAD_PCLASS_PROFILE_DANCEMAT_RIGHT |
CELL_PAD_PCLASS_PROFILE_DANCEMAT_LEFT |
CELL_PAD_PCLASS_PROFILE_DANCEMAT_UP |
CELL_PAD_PCLASS_PROFILE_DANCEMAT_DOWN,
.capabilites = CELL_PAD_CAPABILITY_PS3_CONFORMITY | CELL_PAD_CAPABILITY_PRESS_MODE | CELL_PAD_CAPABILITY_HP_ANALOG_STICK | CELL_PAD_CAPABILITY_ACTUATOR | CELL_PAD_CAPABILITY_SENSOR_MODE
}
},
{
product_type::ps_move_navigation,
{
.type = product_type::ps_move_navigation,
.class_id = CELL_PAD_PCLASS_TYPE_NAVIGATION,
.vendor_id = vendor_id::sony_corp,
.product_id = product_id::ps_move_navigation,
.pclass_profile = 0x0,
.capabilites = CELL_PAD_CAPABILITY_PS3_CONFORMITY | CELL_PAD_CAPABILITY_PRESS_MODE | CELL_PAD_CAPABILITY_HP_ANALOG_STICK | CELL_PAD_CAPABILITY_ACTUATOR | CELL_PAD_CAPABILITY_SENSOR_MODE
}
},
{
product_type::ride_skateboard,
{
.type = product_type::ride_skateboard,
.class_id = CELL_PAD_PCLASS_TYPE_SKATEBOARD,
.vendor_id = vendor_id::sony_cea,
.product_id = product_id::ride_skateboard,
.pclass_profile = 0x0,
.capabilites = CELL_PAD_CAPABILITY_PS3_CONFORMITY | CELL_PAD_CAPABILITY_PRESS_MODE | CELL_PAD_CAPABILITY_SENSOR_MODE
}
},
{
product_type::guncon_3,
{
.type = product_type::guncon_3,
.class_id = CELL_PAD_FAKE_TYPE_GUNCON3,
.vendor_id = vendor_id::namco,
.product_id = product_id::guncon_3,
.pclass_profile = 0x0,
.capabilites = 0x0
}
},
{
product_type::top_shot_elite,
{
.type = product_type::top_shot_elite,
.class_id = CELL_PAD_FAKE_TYPE_TOP_SHOT_ELITE,
.vendor_id = vendor_id::sony_cea,
.product_id = product_id::top_shot_elite,
.pclass_profile = 0x0,
.capabilites = 0x0
}
},
{
product_type::top_shot_fearmaster,
{
.type = product_type::top_shot_fearmaster,
.class_id = CELL_PAD_FAKE_TYPE_TOP_SHOT_FEARMASTER,
.vendor_id = vendor_id::sony_cea,
.product_id = product_id::top_shot_fearmaster,
.pclass_profile = 0x0,
.capabilites = 0x0
}
},
{
product_type::udraw_gametablet,
{
.type = product_type::udraw_gametablet,
.class_id = CELL_PAD_FAKE_TYPE_GAMETABLET,
.vendor_id = vendor_id::bda,
.product_id = product_id::udraw_gametablet,
.pclass_profile = 0x0,
.capabilites = 0x0
}
}
};
product_info get_product_info(product_type type)
{
return input_products.at(type);
}
product_type get_product_by_vid_pid(u16 vendor_id, u16 product_id)
{
for (const auto& [type, product] : input_products)
{
if (product.vendor_id == vendor_id && product.product_id == product_id)
return type;
}
return product_type::playstation_3_controller;
}
std::vector<product_info> get_products_by_class(int class_id)
{
std::vector<product_info> ret;
for (const auto& [type, product] : input_products)
{
if (product.class_id == class_id)
ret.push_back(product);
}
return ret;
}
}
| 9,783
|
C++
|
.cpp
| 264
| 33.329545
| 188
| 0.71897
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,015
|
keyboard_pad_handler.cpp
|
RPCS3_rpcs3/rpcs3/Input/keyboard_pad_handler.cpp
|
#include "keyboard_pad_handler.h"
#include "pad_thread.h"
#include "Emu/Io/pad_config.h"
#include "Emu/Io/KeyboardHandler.h"
#include "Emu/Io/interception.h"
#include "Input/product_info.h"
#include "rpcs3qt/gs_frame.h"
#include <QApplication>
bool keyboard_pad_handler::Init()
{
const steady_clock::time_point now = steady_clock::now();
m_last_mouse_move_left = now;
m_last_mouse_move_right = now;
m_last_mouse_move_up = now;
m_last_mouse_move_down = now;
return true;
}
keyboard_pad_handler::keyboard_pad_handler()
: QObject()
, PadHandlerBase(pad_handler::keyboard)
{
init_configs();
// set capabilities
b_has_config = true;
}
void keyboard_pad_handler::init_config(cfg_pad* cfg)
{
if (!cfg) return;
// Set default button mapping
cfg->ls_left.def = GetKeyName(Qt::Key_A);
cfg->ls_down.def = GetKeyName(Qt::Key_S);
cfg->ls_right.def = GetKeyName(Qt::Key_D);
cfg->ls_up.def = GetKeyName(Qt::Key_W);
cfg->rs_left.def = GetKeyName(Qt::Key_Delete);
cfg->rs_down.def = GetKeyName(Qt::Key_End);
cfg->rs_right.def = GetKeyName(Qt::Key_PageDown);
cfg->rs_up.def = GetKeyName(Qt::Key_Home);
cfg->start.def = GetKeyName(Qt::Key_Return);
cfg->select.def = GetKeyName(Qt::Key_Space);
cfg->ps.def = GetKeyName(Qt::Key_Backspace);
cfg->square.def = GetKeyName(Qt::Key_Z);
cfg->cross.def = GetKeyName(Qt::Key_X);
cfg->circle.def = GetKeyName(Qt::Key_C);
cfg->triangle.def = GetKeyName(Qt::Key_V);
cfg->left.def = GetKeyName(Qt::Key_Left);
cfg->down.def = GetKeyName(Qt::Key_Down);
cfg->right.def = GetKeyName(Qt::Key_Right);
cfg->up.def = GetKeyName(Qt::Key_Up);
cfg->r1.def = GetKeyName(Qt::Key_E);
cfg->r2.def = GetKeyName(Qt::Key_T);
cfg->r3.def = GetKeyName(Qt::Key_G);
cfg->l1.def = GetKeyName(Qt::Key_Q);
cfg->l2.def = GetKeyName(Qt::Key_R);
cfg->l3.def = GetKeyName(Qt::Key_F);
cfg->pressure_intensity_button.def = GetKeyName(Qt::NoButton);
cfg->analog_limiter_button.def = GetKeyName(Qt::NoButton);
cfg->lstick_anti_deadzone.def = 0;
cfg->rstick_anti_deadzone.def = 0;
cfg->lstickdeadzone.def = 0;
cfg->rstickdeadzone.def = 0;
cfg->ltriggerthreshold.def = 0;
cfg->rtriggerthreshold.def = 0;
cfg->lpadsquircling.def = 8000;
cfg->rpadsquircling.def = 8000;
// apply defaults
cfg->from_default();
}
void keyboard_pad_handler::Key(const u32 code, bool pressed, u16 value)
{
if (!pad::g_enabled)
{
return;
}
value = Clamp0To255(value);
for (auto& pad : m_pads_internal)
{
const auto register_new_button_value = [&](std::map<u32, u16>& pressed_keys) -> u16
{
u16 actual_value = 0;
// Make sure we keep this button pressed until all related keys are released.
if (pressed)
{
pressed_keys[code] = value;
}
else
{
pressed_keys.erase(code);
}
// Get the max value of all pressed keys for this button
for (const auto& [key, val] : pressed_keys)
{
actual_value = std::max(actual_value, val);
}
return actual_value;
};
// Find out if special buttons are pressed (introduced by RPCS3).
// Activate the buttons here if possible since keys don't auto-repeat. This ensures that they are already pressed in the following loop.
if (pad.m_pressure_intensity_button_index >= 0)
{
Button& pressure_intensity_button = pad.m_buttons[pad.m_pressure_intensity_button_index];
if (pressure_intensity_button.m_key_codes.contains(code))
{
const u16 actual_value = register_new_button_value(pressure_intensity_button.m_pressed_keys);
pressure_intensity_button.m_pressed = actual_value > 0;
pressure_intensity_button.m_value = actual_value;
}
}
const bool adjust_pressure = pad.get_pressure_intensity_button_active(m_pressure_intensity_toggle_mode, pad.m_player_id);
const bool adjust_pressure_changed = pad.m_adjust_pressure_last != adjust_pressure;
if (adjust_pressure_changed)
{
pad.m_adjust_pressure_last = adjust_pressure;
}
if (pad.m_analog_limiter_button_index >= 0)
{
Button& analog_limiter_button = pad.m_buttons[pad.m_analog_limiter_button_index];
if (analog_limiter_button.m_key_codes.contains(code))
{
const u16 actual_value = register_new_button_value(analog_limiter_button.m_pressed_keys);
analog_limiter_button.m_pressed = actual_value > 0;
analog_limiter_button.m_value = actual_value;
}
}
const bool analog_limiter_enabled = pad.get_analog_limiter_button_active(m_analog_limiter_toggle_mode, pad.m_player_id);
const bool analog_limiter_changed = pad.m_analog_limiter_enabled_last != analog_limiter_enabled;
const u32 l_stick_multiplier = analog_limiter_enabled ? m_l_stick_multiplier : 100;
const u32 r_stick_multiplier = analog_limiter_enabled ? m_r_stick_multiplier : 100;
if (analog_limiter_changed)
{
pad.m_analog_limiter_enabled_last = analog_limiter_enabled;
}
// Handle buttons
for (usz i = 0; i < pad.m_buttons.size(); i++)
{
// Ignore special buttons
if (static_cast<s32>(i) == pad.m_pressure_intensity_button_index ||
static_cast<s32>(i) == pad.m_analog_limiter_button_index)
continue;
Button& button = pad.m_buttons[i];
bool update_button = true;
if (!button.m_key_codes.contains(code))
{
// Handle pressure changes anyway
update_button = adjust_pressure_changed;
}
else
{
button.m_actual_value = register_new_button_value(button.m_pressed_keys);
// to get the fastest response time possible we don't wanna use any lerp with factor 1
if (button.m_analog)
{
update_button = m_analog_lerp_factor >= 1.0f;
}
else if (button.m_trigger)
{
update_button = m_trigger_lerp_factor >= 1.0f;
}
}
if (!update_button)
continue;
if (button.m_actual_value > 0)
{
// Modify pressure if necessary if the button was pressed
if (adjust_pressure)
{
button.m_value = pad.m_pressure_intensity;
}
else if (m_pressure_intensity_deadzone > 0)
{
button.m_value = NormalizeDirectedInput(button.m_actual_value, m_pressure_intensity_deadzone, 255);
}
else
{
button.m_value = button.m_actual_value;
}
button.m_pressed = button.m_value > 0;
}
else
{
button.m_value = 0;
button.m_pressed = false;
}
}
// Handle sticks
for (usz i = 0; i < pad.m_sticks.size(); i++)
{
AnalogStick& stick = pad.m_sticks[i];
const bool is_left_stick = i < 2;
const bool is_max = stick.m_key_codes_max.contains(code);
const bool is_min = stick.m_key_codes_min.contains(code);
if (!is_max && !is_min)
{
if (!analog_limiter_changed)
continue;
// Update already pressed sticks
const bool is_min_pressed = !stick.m_pressed_keys_min.empty();
const bool is_max_pressed = !stick.m_pressed_keys_max.empty();
const u32 stick_multiplier = is_left_stick ? l_stick_multiplier : r_stick_multiplier;
const u16 actual_min_value = is_min_pressed ? MultipliedInput(255, stick_multiplier) : 255;
const u16 normalized_min_value = std::ceil(actual_min_value / 2.0);
const u16 actual_max_value = is_max_pressed ? MultipliedInput(255, stick_multiplier) : 255;
const u16 normalized_max_value = std::ceil(actual_max_value / 2.0);
m_stick_min[i] = is_min_pressed ? std::min<u8>(normalized_min_value, 128) : 0;
m_stick_max[i] = is_max_pressed ? std::min<int>(128 + normalized_max_value, 255) : 128;
}
else
{
const u16 actual_value = pressed ? MultipliedInput(value, is_left_stick ? l_stick_multiplier : r_stick_multiplier) : value;
u16 normalized_value = std::ceil(actual_value / 2.0);
const auto register_new_stick_value = [&](std::map<u32, u16>& pressed_keys, bool is_max)
{
// Make sure we keep this stick pressed until all related keys are released.
if (pressed)
{
pressed_keys[code] = normalized_value;
}
else
{
pressed_keys.erase(code);
}
// Get the min/max value of all pressed keys for this stick
for (const auto& [key, val] : pressed_keys)
{
normalized_value = is_max ? std::max(normalized_value, val) : std::min(normalized_value, val);
}
};
if (is_max)
{
register_new_stick_value(stick.m_pressed_keys_max, true);
const bool is_max_pressed = !stick.m_pressed_keys_max.empty();
m_stick_max[i] = is_max_pressed ? std::min<int>(128 + normalized_value, 255) : 128;
}
if (is_min)
{
register_new_stick_value(stick.m_pressed_keys_min, false);
const bool is_min_pressed = !stick.m_pressed_keys_min.empty();
m_stick_min[i] = is_min_pressed ? std::min<u8>(normalized_value, 128) : 0;
}
}
m_stick_val[i] = m_stick_max[i] - m_stick_min[i];
const f32 stick_lerp_factor = is_left_stick ? m_l_stick_lerp_factor : m_r_stick_lerp_factor;
// to get the fastest response time possible we don't wanna use any lerp with factor 1
if (stick_lerp_factor >= 1.0f)
{
stick.m_value = m_stick_val[i];
}
}
}
}
void keyboard_pad_handler::release_all_keys()
{
for (auto& pad : m_pads_internal)
{
for (Button& button : pad.m_buttons)
{
button.m_pressed = false;
button.m_value = 0;
button.m_actual_value = 0;
}
for (usz i = 0; i < pad.m_sticks.size(); i++)
{
m_stick_min[i] = 0;
m_stick_max[i] = 128;
m_stick_val[i] = 128;
pad.m_sticks[i].m_value = 128;
}
}
m_keys_released = true;
}
bool keyboard_pad_handler::eventFilter(QObject* target, QEvent* ev)
{
if (!ev) [[unlikely]]
{
return false;
}
if (input::g_active_mouse_and_keyboard != input::active_mouse_and_keyboard::pad)
{
if (!m_keys_released)
{
release_all_keys();
}
return false;
}
m_keys_released = false;
// !m_target is for future proofing when gsrender isn't automatically initialized on load.
// !m_target->isVisible() is a hack since currently a guiless application will STILL inititialize a gsrender (providing a valid target)
if (!m_target || !m_target->isVisible()|| target == m_target)
{
switch (ev->type())
{
case QEvent::KeyPress:
keyPressEvent(static_cast<QKeyEvent*>(ev));
break;
case QEvent::KeyRelease:
keyReleaseEvent(static_cast<QKeyEvent*>(ev));
break;
case QEvent::MouseButtonPress:
mousePressEvent(static_cast<QMouseEvent*>(ev));
break;
case QEvent::MouseButtonRelease:
mouseReleaseEvent(static_cast<QMouseEvent*>(ev));
break;
case QEvent::MouseMove:
mouseMoveEvent(static_cast<QMouseEvent*>(ev));
break;
case QEvent::Wheel:
mouseWheelEvent(static_cast<QWheelEvent*>(ev));
break;
case QEvent::FocusOut:
release_all_keys();
break;
default:
break;
}
}
return false;
}
/* Sets the target window for the event handler, and also installs an event filter on the target. */
void keyboard_pad_handler::SetTargetWindow(QWindow* target)
{
if (target != nullptr)
{
m_target = target;
target->installEventFilter(this);
}
else
{
QApplication::instance()->installEventFilter(this);
// If this is hit, it probably means that some refactoring occurs because currently a gsframe is created in Load.
// We still want events so filter from application instead since target is null.
input_log.error("Trying to set pad handler to a null target window.");
}
}
void keyboard_pad_handler::processKeyEvent(QKeyEvent* event, bool pressed)
{
if (!event) [[unlikely]]
{
return;
}
if (event->isAutoRepeat())
{
event->ignore();
return;
}
const auto handle_key = [this, pressed, event]()
{
QStringList list = GetKeyNames(event);
if (list.isEmpty())
return;
const bool is_num_key = list.removeAll("Num") > 0;
const QString name = QString::fromStdString(GetKeyName(event, true));
// TODO: Edge case: switching numlock keeps numpad keys pressed due to now different modifier
// Handle every possible key combination, for example: ctrl+A -> {ctrl, A, ctrl+A}
for (const QString& keyname : list)
{
// skip the 'original keys' when handling numpad keys
if (is_num_key && !keyname.contains("Num"))
continue;
// skip held modifiers when handling another key
if (keyname != name && list.count() > 1 && (keyname == "Alt" || keyname == "AltGr" || keyname == "Ctrl" || keyname == "Meta" || keyname == "Shift"))
continue;
Key(GetKeyCode(keyname), pressed);
}
};
handle_key();
event->ignore();
}
void keyboard_pad_handler::keyPressEvent(QKeyEvent* event)
{
if (!event) [[unlikely]]
{
return;
}
if (event->modifiers() & Qt::AltModifier)
{
switch (event->key())
{
case Qt::Key_I:
m_deadzone_y = std::min(m_deadzone_y + 1, 255);
input_log.success("mouse move adjustment: deadzone y = %d", m_deadzone_y);
event->ignore();
return;
case Qt::Key_U:
m_deadzone_y = std::max(0, m_deadzone_y - 1);
input_log.success("mouse move adjustment: deadzone y = %d", m_deadzone_y);
event->ignore();
return;
case Qt::Key_Y:
m_deadzone_x = std::min(m_deadzone_x + 1, 255);
input_log.success("mouse move adjustment: deadzone x = %d", m_deadzone_x);
event->ignore();
return;
case Qt::Key_T:
m_deadzone_x = std::max(0, m_deadzone_x - 1);
input_log.success("mouse move adjustment: deadzone x = %d", m_deadzone_x);
event->ignore();
return;
case Qt::Key_K:
m_multi_y = std::min(m_multi_y + 0.1, 5.0);
input_log.success("mouse move adjustment: multiplier y = %d", static_cast<int>(m_multi_y * 100));
event->ignore();
return;
case Qt::Key_J:
m_multi_y = std::max(0.0, m_multi_y - 0.1);
input_log.success("mouse move adjustment: multiplier y = %d", static_cast<int>(m_multi_y * 100));
event->ignore();
return;
case Qt::Key_H:
m_multi_x = std::min(m_multi_x + 0.1, 5.0);
input_log.success("mouse move adjustment: multiplier x = %d", static_cast<int>(m_multi_x * 100));
event->ignore();
return;
case Qt::Key_G:
m_multi_x = std::max(0.0, m_multi_x - 0.1);
input_log.success("mouse move adjustment: multiplier x = %d", static_cast<int>(m_multi_x * 100));
event->ignore();
return;
default:
break;
}
}
processKeyEvent(event, true);
}
void keyboard_pad_handler::keyReleaseEvent(QKeyEvent* event)
{
processKeyEvent(event, false);
}
void keyboard_pad_handler::mousePressEvent(QMouseEvent* event)
{
if (!event) [[unlikely]]
{
return;
}
Key(event->button(), true);
event->ignore();
}
void keyboard_pad_handler::mouseReleaseEvent(QMouseEvent* event)
{
if (!event) [[unlikely]]
{
return;
}
Key(event->button(), false, 0);
event->ignore();
}
bool keyboard_pad_handler::get_mouse_lock_state() const
{
if (gs_frame* game_frame = dynamic_cast<gs_frame*>(m_target))
return game_frame->get_mouse_lock_state();
return false;
}
void keyboard_pad_handler::mouseMoveEvent(QMouseEvent* event)
{
if (!m_mouse_move_used || !event)
{
event->ignore();
return;
}
static int movement_x = 0;
static int movement_y = 0;
if (m_target && m_target->isActive() && get_mouse_lock_state())
{
// get the screen dimensions
const QSize screen = m_target->size();
// get the center of the screen in global coordinates
QPoint p_center = m_target->geometry().topLeft() + QPoint(screen.width() / 2, screen.height() / 2);
// reset the mouse to the center for consistent results since edge movement won't be registered
QCursor::setPos(m_target->screen(), p_center);
// convert the center into screen coordinates
p_center = m_target->mapFromGlobal(p_center);
// get the delta of the mouse position to the screen center
const QPoint p_delta = event->pos() - p_center;
if (m_mouse_movement_mode == mouse_movement_mode::relative)
{
movement_x = p_delta.x();
movement_y = p_delta.y();
}
else
{
// current mouse position, starting at the center
static QPoint p_real(p_center);
// update the current position without leaving the screen borders
p_real.setX(std::clamp(p_real.x() + p_delta.x(), 0, screen.width()));
p_real.setY(std::clamp(p_real.y() + p_delta.y(), 0, screen.height()));
// get the delta of the real mouse position to the screen center
const QPoint p_real_delta = p_real - p_center;
movement_x = p_real_delta.x();
movement_y = p_real_delta.y();
}
}
else if (m_mouse_movement_mode == mouse_movement_mode::relative)
{
static int last_pos_x = 0;
static int last_pos_y = 0;
const QPoint e_pos = event->pos();
movement_x = e_pos.x() - last_pos_x;
movement_y = e_pos.y() - last_pos_y;
last_pos_x = e_pos.x();
last_pos_y = e_pos.y();
}
else if (m_target && m_target->isActive())
{
// get the screen dimensions
const QSize screen = m_target->size();
// get the center of the screen in global coordinates
QPoint p_center = m_target->geometry().topLeft() + QPoint(screen.width() / 2, screen.height() / 2);
// convert the center into screen coordinates
p_center = m_target->mapFromGlobal(p_center);
// get the delta of the mouse position to the screen center
const QPoint p_delta = event->pos() - p_center;
movement_x = p_delta.x();
movement_y = p_delta.y();
}
movement_x *= m_multi_x;
movement_y *= m_multi_y;
int deadzone_x = 0;
int deadzone_y = 0;
if (movement_x == 0 && movement_y != 0)
{
deadzone_y = m_deadzone_y;
}
else if (movement_y == 0 && movement_x != 0)
{
deadzone_x = m_deadzone_x;
}
else if (movement_x != 0 && movement_y != 0 && m_deadzone_x != 0 && m_deadzone_y != 0)
{
// Calculate the point on our deadzone ellipsis intersected with the line (0, 0)(movement_x, movement_y)
// Ellipsis: 1 = (x²/a²) + (y²/b²) ; where: a = m_deadzone_x and b = m_deadzone_y
// Line: y = mx + t ; where: t = 0 and m = (movement_y / movement_x)
// Combined: x = +-(a*b)/sqrt(a²m²+b²) ; where +- is always +, since we only want the magnitude
const double a = m_deadzone_x;
const double b = m_deadzone_y;
const double m = static_cast<double>(movement_y) / static_cast<double>(movement_x);
deadzone_x = a * b / std::sqrt(std::pow(a, 2) * std::pow(m, 2) + std::pow(b, 2));
deadzone_y = std::abs(m * deadzone_x);
}
if (movement_x < 0)
{
Key(mouse::move_right, false);
Key(mouse::move_left, true, std::min(deadzone_x + std::abs(movement_x), 255));
m_last_mouse_move_left = steady_clock::now();
}
else if (movement_x > 0)
{
Key(mouse::move_left, false);
Key(mouse::move_right, true, std::min(deadzone_x + movement_x, 255));
m_last_mouse_move_right = steady_clock::now();
}
// in Qt mouse up is equivalent to movement_y < 0
if (movement_y < 0)
{
Key(mouse::move_down, false);
Key(mouse::move_up, true, std::min(deadzone_y + std::abs(movement_y), 255));
m_last_mouse_move_up = steady_clock::now();
}
else if (movement_y > 0)
{
Key(mouse::move_up, false);
Key(mouse::move_down, true, std::min(deadzone_y + movement_y, 255));
m_last_mouse_move_down = steady_clock::now();
}
event->ignore();
}
void keyboard_pad_handler::mouseWheelEvent(QWheelEvent* event)
{
if (!m_mouse_wheel_used || !event)
{
return;
}
const QPoint direction = event->angleDelta();
if (direction.isNull())
{
// Scrolling started/ended event, no direction given
return;
}
if (const int x = direction.x())
{
const bool to_left = event->inverted() ? x < 0 : x > 0;
if (to_left)
{
Key(mouse::wheel_left, true);
m_last_wheel_move_left = steady_clock::now();
}
else
{
Key(mouse::wheel_right, true);
m_last_wheel_move_right = steady_clock::now();
}
}
if (const int y = direction.y())
{
const bool to_up = event->inverted() ? y < 0 : y > 0;
if (to_up)
{
Key(mouse::wheel_up, true);
m_last_wheel_move_up = steady_clock::now();
}
else
{
Key(mouse::wheel_down, true);
m_last_wheel_move_down = steady_clock::now();
}
}
}
std::vector<pad_list_entry> keyboard_pad_handler::list_devices()
{
std::vector<pad_list_entry> list_devices;
list_devices.emplace_back(std::string(pad::keyboard_device_name), false);
return list_devices;
}
std::string keyboard_pad_handler::GetMouseName(const QMouseEvent* event)
{
return GetMouseName(event->button());
}
std::string keyboard_pad_handler::GetMouseName(u32 button)
{
if (const auto it = mouse_list.find(button); it != mouse_list.cend())
return it->second;
return "FAIL";
}
QStringList keyboard_pad_handler::GetKeyNames(const QKeyEvent* keyEvent)
{
QStringList list;
if (keyEvent->modifiers() & Qt::ShiftModifier)
{
list.append("Shift");
list.append(QKeySequence(keyEvent->key() | Qt::ShiftModifier).toString(QKeySequence::NativeText));
}
if (keyEvent->modifiers() & Qt::AltModifier)
{
list.append("Alt");
list.append(QKeySequence(keyEvent->key() | Qt::AltModifier).toString(QKeySequence::NativeText));
}
if (keyEvent->modifiers() & Qt::ControlModifier)
{
list.append("Ctrl");
list.append(QKeySequence(keyEvent->key() | Qt::ControlModifier).toString(QKeySequence::NativeText));
}
if (keyEvent->modifiers() & Qt::MetaModifier)
{
list.append("Meta");
list.append(QKeySequence(keyEvent->key() | Qt::MetaModifier).toString(QKeySequence::NativeText));
}
if (keyEvent->modifiers() & Qt::KeypadModifier)
{
list.append("Num"); // helper object, not used as actual key
list.append(QKeySequence(keyEvent->key() | Qt::KeypadModifier).toString(QKeySequence::NativeText));
}
// Handle special cases
if (const std::string name = native_scan_code_to_string(keyEvent->nativeScanCode()); !name.empty())
{
list.append(QString::fromStdString(name));
}
switch (keyEvent->key())
{
case Qt::Key_Alt:
list.append("Alt");
break;
case Qt::Key_AltGr:
list.append("AltGr");
break;
case Qt::Key_Shift:
list.append("Shift");
break;
case Qt::Key_Control:
list.append("Ctrl");
break;
case Qt::Key_Meta:
list.append("Meta");
break;
default:
list.append(QKeySequence(keyEvent->key()).toString(QKeySequence::NativeText));
break;
}
list.removeDuplicates();
return list;
}
std::string keyboard_pad_handler::GetKeyName(const QKeyEvent* keyEvent, bool with_modifiers)
{
// Handle special cases first
if (std::string name = native_scan_code_to_string(keyEvent->nativeScanCode()); !name.empty())
{
return name;
}
switch (keyEvent->key())
{
case Qt::Key_Alt: return "Alt";
case Qt::Key_AltGr: return "AltGr";
case Qt::Key_Shift: return "Shift";
case Qt::Key_Control: return "Ctrl";
case Qt::Key_Meta: return "Meta";
case Qt::Key_NumLock: return QKeySequence(keyEvent->key()).toString(QKeySequence::NativeText).toStdString();
#ifdef __APPLE__
// On macOS, the arrow keys are considered to be part of the keypad;
// since most Mac keyboards lack a keypad to begin with,
// we change them to regular arrows to avoid confusion
case Qt::Key_Left: return "←";
case Qt::Key_Up: return "↑";
case Qt::Key_Right: return "→";
case Qt::Key_Down: return "↓";
#endif
default:
break;
}
if (with_modifiers)
{
return QKeySequence(keyEvent->key() | keyEvent->modifiers()).toString(QKeySequence::NativeText).toStdString();
}
return QKeySequence(keyEvent->key()).toString(QKeySequence::NativeText).toStdString();
}
std::string keyboard_pad_handler::GetKeyName(const u32& keyCode)
{
return QKeySequence(keyCode).toString(QKeySequence::NativeText).toStdString();
}
std::set<u32> keyboard_pad_handler::GetKeyCodes(const cfg::string& cfg_string)
{
std::set<u32> key_codes;
for (const std::string& key_name : cfg_pad::get_buttons(cfg_string))
{
if (u32 code = GetKeyCode(QString::fromStdString(key_name)); code != Qt::NoButton)
{
key_codes.insert(code);
}
}
return key_codes;
}
u32 keyboard_pad_handler::GetKeyCode(const QString& keyName)
{
if (keyName.isEmpty()) return Qt::NoButton;
if (const int native_scan_code = native_scan_code_from_string(keyName.toStdString()); native_scan_code >= 0)
return Qt::Key_unknown + native_scan_code; // Special cases that can't be expressed with Qt::Key
if (keyName == "Alt") return Qt::Key_Alt;
if (keyName == "AltGr") return Qt::Key_AltGr;
if (keyName == "Shift") return Qt::Key_Shift;
if (keyName == "Ctrl") return Qt::Key_Control;
if (keyName == "Meta") return Qt::Key_Meta;
#ifdef __APPLE__
// QKeySequence doesn't work properly for the arrow keys on macOS
if (keyName == "Num←") return Qt::Key_Left;
if (keyName == "Num↑") return Qt::Key_Up;
if (keyName == "Num→") return Qt::Key_Right;
if (keyName == "Num↓") return Qt::Key_Down;
#endif
const QKeySequence seq(keyName);
u32 key_code = Qt::NoButton;
if (seq.count() == 1 && seq[0].key() != Qt::Key_unknown)
key_code = seq[0].key();
else
input_log.notice("GetKeyCode(%s): seq.count() = %d", keyName, seq.count());
return key_code;
}
int keyboard_pad_handler::native_scan_code_from_string([[maybe_unused]] const std::string& key)
{
// NOTE: Qt throws a Ctrl key at us when using Alt Gr first, so right Alt does not work at the moment
if (key == "Shift Left") return native_key::shift_l;
if (key == "Shift Right") return native_key::shift_r;
if (key == "Ctrl Left") return native_key::ctrl_l;
if (key == "Ctrl Right") return native_key::ctrl_r;
if (key == "Alt Left") return native_key::alt_l;
if (key == "Alt Right") return native_key::alt_r;
if (key == "Meta Left") return native_key::meta_l;
if (key == "Meta Right") return native_key::meta_r;
#ifdef _WIN32
if (key == "Num+0" || key == "Num+Ins") return 82;
if (key == "Num+1" || key == "Num+End") return 79;
if (key == "Num+2" || key == "Num+Down") return 80;
if (key == "Num+3" || key == "Num+PgDown") return 81;
if (key == "Num+4" || key == "Num+Left") return 75;
if (key == "Num+5" || key == "Num+Clear") return 76;
if (key == "Num+6" || key == "Num+Right") return 77;
if (key == "Num+7" || key == "Num+Home") return 71;
if (key == "Num+8" || key == "Num+Up") return 72;
if (key == "Num+9" || key == "Num+PgUp") return 73;
if (key == "Num+," || key == "Num+Del") return 83;
if (key == "Num+/") return 309;
if (key == "Num+*") return 55;
if (key == "Num+-") return 74;
if (key == "Num++") return 78;
if (key == "Num+Enter") return 284;
#else
// TODO
#endif
return -1;
}
std::string keyboard_pad_handler::native_scan_code_to_string(int native_scan_code)
{
// NOTE: the other Qt function "nativeVirtualKey" does not distinguish between VK_SHIFT and VK_RSHIFT key in Qt at the moment
// NOTE: Qt throws a Ctrl key at us when using Alt Gr first, so right Alt does not work at the moment
// NOTE: for MacOs: nativeScanCode may not work
switch (native_scan_code)
{
case native_key::shift_l: return "Shift Left";
case native_key::shift_r: return "Shift Right";
case native_key::ctrl_l: return "Ctrl Left";
case native_key::ctrl_r: return "Ctrl Right";
case native_key::alt_l: return "Alt Left";
case native_key::alt_r: return "Alt Right";
case native_key::meta_l: return "Meta Left";
case native_key::meta_r: return "Meta Right";
#ifdef _WIN32
case 82: return "Num+0"; // Also "Num+Ins" depending on numlock
case 79: return "Num+1"; // Also "Num+End" depending on numlock
case 80: return "Num+2"; // Also "Num+Down" depending on numlock
case 81: return "Num+3"; // Also "Num+PgDown" depending on numlock
case 75: return "Num+4"; // Also "Num+Left" depending on numlock
case 76: return "Num+5"; // Also "Num+Clear" depending on numlock
case 77: return "Num+6"; // Also "Num+Right" depending on numlock
case 71: return "Num+7"; // Also "Num+Home" depending on numlock
case 72: return "Num+8"; // Also "Num+Up" depending on numlock
case 73: return "Num+9"; // Also "Num+PgUp" depending on numlock
case 83: return "Num+,"; // Also "Num+Del" depending on numlock
case 309: return "Num+/";
case 55: return "Num+*";
case 74: return "Num+-";
case 78: return "Num++";
case 284: return "Num+Enter";
#else
// TODO
#endif
default: return "";
}
}
bool keyboard_pad_handler::bindPadToDevice(std::shared_ptr<Pad> pad)
{
if (!pad || pad->m_player_id >= g_cfg_input.player.size())
return false;
const cfg_player* player_config = g_cfg_input.player[pad->m_player_id];
if (!player_config || player_config->device.to_string() != pad::keyboard_device_name)
return false;
m_pad_configs[pad->m_player_id].from_string(player_config->config.to_string());
const cfg_pad* cfg = &m_pad_configs[pad->m_player_id];
if (cfg == nullptr)
return false;
m_mouse_movement_mode = cfg->mouse_move_mode;
m_mouse_move_used = false;
m_mouse_wheel_used = false;
m_deadzone_x = cfg->mouse_deadzone_x;
m_deadzone_y = cfg->mouse_deadzone_y;
m_multi_x = cfg->mouse_acceleration_x / 100.0;
m_multi_y = cfg->mouse_acceleration_y / 100.0;
m_l_stick_lerp_factor = cfg->l_stick_lerp_factor / 100.0f;
m_r_stick_lerp_factor = cfg->r_stick_lerp_factor / 100.0f;
m_analog_lerp_factor = cfg->analog_lerp_factor / 100.0f;
m_trigger_lerp_factor = cfg->trigger_lerp_factor / 100.0f;
m_l_stick_multiplier = cfg->lstickmultiplier;
m_r_stick_multiplier = cfg->rstickmultiplier;
m_analog_limiter_toggle_mode = cfg->analog_limiter_toggle_mode.get();
m_pressure_intensity_toggle_mode = cfg->pressure_intensity_toggle_mode.get();
m_pressure_intensity_deadzone = cfg->pressure_intensity_deadzone.get();
const auto find_keys = [this](const cfg::string& name)
{
std::set<u32> keys = FindKeyCodes<u32, u32>(mouse_list, name, false);
for (const u32& key : GetKeyCodes(name)) keys.insert(key);
if (!keys.empty())
{
if (!m_mouse_move_used && (keys.contains(mouse::move_left) || keys.contains(mouse::move_right) || keys.contains(mouse::move_up) || keys.contains(mouse::move_down)))
{
m_mouse_move_used = true;
}
else if (!m_mouse_wheel_used && (keys.contains(mouse::wheel_left) || keys.contains(mouse::wheel_right) || keys.contains(mouse::wheel_up) || keys.contains(mouse::wheel_down)))
{
m_mouse_wheel_used = true;
}
}
return keys;
};
u32 pclass_profile = 0x0;
for (const input::product_info& product : input::get_products_by_class(cfg->device_class_type))
{
if (product.vendor_id == cfg->vendor_id && product.product_id == cfg->product_id)
{
pclass_profile = product.pclass_profile;
}
}
// Fixed assign change, default is both sensor and press off
pad->Init
(
CELL_PAD_STATUS_DISCONNECTED,
CELL_PAD_CAPABILITY_PS3_CONFORMITY | CELL_PAD_CAPABILITY_PRESS_MODE | CELL_PAD_CAPABILITY_HP_ANALOG_STICK | CELL_PAD_CAPABILITY_ACTUATOR | CELL_PAD_CAPABILITY_SENSOR_MODE,
CELL_PAD_DEV_TYPE_STANDARD,
cfg->device_class_type,
pclass_profile,
cfg->vendor_id,
cfg->product_id,
cfg->pressure_intensity
);
if (b_has_pressure_intensity_button)
{
pad->m_buttons.emplace_back(special_button_offset, find_keys(cfg->pressure_intensity_button), special_button_value::pressure_intensity);
pad->m_pressure_intensity_button_index = static_cast<s32>(pad->m_buttons.size()) - 1;
}
if (b_has_analog_limiter_button)
{
pad->m_buttons.emplace_back(special_button_offset, find_keys(cfg->analog_limiter_button), special_button_value::analog_limiter);
pad->m_analog_limiter_button_index = static_cast<s32>(pad->m_buttons.size()) - 1;
}
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL1, find_keys(cfg->left), CELL_PAD_CTRL_LEFT);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL1, find_keys(cfg->down), CELL_PAD_CTRL_DOWN);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL1, find_keys(cfg->right), CELL_PAD_CTRL_RIGHT);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL1, find_keys(cfg->up), CELL_PAD_CTRL_UP);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL1, find_keys(cfg->start), CELL_PAD_CTRL_START);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL1, find_keys(cfg->r3), CELL_PAD_CTRL_R3);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL1, find_keys(cfg->l3), CELL_PAD_CTRL_L3);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL1, find_keys(cfg->select), CELL_PAD_CTRL_SELECT);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL1, find_keys(cfg->ps), CELL_PAD_CTRL_PS);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL2, find_keys(cfg->square), CELL_PAD_CTRL_SQUARE);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL2, find_keys(cfg->cross), CELL_PAD_CTRL_CROSS);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL2, find_keys(cfg->circle), CELL_PAD_CTRL_CIRCLE);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL2, find_keys(cfg->triangle), CELL_PAD_CTRL_TRIANGLE);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL2, find_keys(cfg->r1), CELL_PAD_CTRL_R1);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL2, find_keys(cfg->l1), CELL_PAD_CTRL_L1);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL2, find_keys(cfg->r2), CELL_PAD_CTRL_R2);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_DIGITAL2, find_keys(cfg->l2), CELL_PAD_CTRL_L2);
if (pad->m_class_type == CELL_PAD_PCLASS_TYPE_SKATEBOARD)
{
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_PRESS_PIGGYBACK, find_keys(cfg->ir_nose), CELL_PAD_CTRL_PRESS_TRIANGLE);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_PRESS_PIGGYBACK, find_keys(cfg->ir_tail), CELL_PAD_CTRL_PRESS_CIRCLE);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_PRESS_PIGGYBACK, find_keys(cfg->ir_left), CELL_PAD_CTRL_PRESS_CROSS);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_PRESS_PIGGYBACK, find_keys(cfg->ir_right), CELL_PAD_CTRL_PRESS_SQUARE);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_PRESS_PIGGYBACK, find_keys(cfg->tilt_left), CELL_PAD_CTRL_PRESS_L1);
pad->m_buttons.emplace_back(CELL_PAD_BTN_OFFSET_PRESS_PIGGYBACK, find_keys(cfg->tilt_right), CELL_PAD_CTRL_PRESS_R1);
}
pad->m_sticks[0] = AnalogStick(CELL_PAD_BTN_OFFSET_ANALOG_LEFT_X, find_keys(cfg->ls_left), find_keys(cfg->ls_right));
pad->m_sticks[1] = AnalogStick(CELL_PAD_BTN_OFFSET_ANALOG_LEFT_Y, find_keys(cfg->ls_up), find_keys(cfg->ls_down));
pad->m_sticks[2] = AnalogStick(CELL_PAD_BTN_OFFSET_ANALOG_RIGHT_X, find_keys(cfg->rs_left), find_keys(cfg->rs_right));
pad->m_sticks[3] = AnalogStick(CELL_PAD_BTN_OFFSET_ANALOG_RIGHT_Y, find_keys(cfg->rs_up), find_keys(cfg->rs_down));
pad->m_sensors[0] = AnalogSensor(CELL_PAD_BTN_OFFSET_SENSOR_X, 0, 0, 0, DEFAULT_MOTION_X);
pad->m_sensors[1] = AnalogSensor(CELL_PAD_BTN_OFFSET_SENSOR_Y, 0, 0, 0, DEFAULT_MOTION_Y);
pad->m_sensors[2] = AnalogSensor(CELL_PAD_BTN_OFFSET_SENSOR_Z, 0, 0, 0, DEFAULT_MOTION_Z);
pad->m_sensors[3] = AnalogSensor(CELL_PAD_BTN_OFFSET_SENSOR_G, 0, 0, 0, DEFAULT_MOTION_G);
pad->m_vibrateMotors[0] = VibrateMotor(true, 0);
pad->m_vibrateMotors[1] = VibrateMotor(false, 0);
m_bindings.emplace_back(pad, nullptr, nullptr);
m_pads_internal.push_back(*pad);
return true;
}
void keyboard_pad_handler::process()
{
constexpr double stick_interval = 10.0;
constexpr double button_interval = 10.0;
const auto now = steady_clock::now();
const double elapsed_stick = std::chrono::duration_cast<std::chrono::microseconds>(now - m_stick_time).count() / 1000.0;
const double elapsed_button = std::chrono::duration_cast<std::chrono::microseconds>(now - m_button_time).count() / 1000.0;
const bool update_sticks = elapsed_stick > stick_interval;
const bool update_buttons = elapsed_button > button_interval;
if (update_sticks)
{
m_stick_time = now;
}
if (update_buttons)
{
m_button_time = now;
}
if (m_mouse_move_used && m_mouse_movement_mode == mouse_movement_mode::relative)
{
constexpr double mouse_interval = 30.0;
const double elapsed_left = std::chrono::duration_cast<std::chrono::microseconds>(now - m_last_mouse_move_left).count() / 1000.0;
const double elapsed_right = std::chrono::duration_cast<std::chrono::microseconds>(now - m_last_mouse_move_right).count() / 1000.0;
const double elapsed_up = std::chrono::duration_cast<std::chrono::microseconds>(now - m_last_mouse_move_up).count() / 1000.0;
const double elapsed_down = std::chrono::duration_cast<std::chrono::microseconds>(now - m_last_mouse_move_down).count() / 1000.0;
// roughly 1-2 frames to process the next mouse move
if (elapsed_left > mouse_interval)
{
Key(mouse::move_left, false);
m_last_mouse_move_left = now;
}
if (elapsed_right > mouse_interval)
{
Key(mouse::move_right, false);
m_last_mouse_move_right = now;
}
if (elapsed_up > mouse_interval)
{
Key(mouse::move_up, false);
m_last_mouse_move_up = now;
}
if (elapsed_down > mouse_interval)
{
Key(mouse::move_down, false);
m_last_mouse_move_down = now;
}
}
const auto get_lerped = [](f32 v0, f32 v1, f32 lerp_factor)
{
// linear interpolation from the current value v0 to the desired value v1
const f32 res = std::lerp(v0, v1, lerp_factor);
// round to the correct direction to prevent sticky values on small factors
return (v0 <= v1) ? std::ceil(res) : std::floor(res);
};
for (uint i = 0; i < m_pads_internal.size(); i++)
{
auto& pad = m_pads_internal[i];
if (last_connection_status[i] == false)
{
ensure(m_bindings[i].pad);
m_bindings[i].pad->m_port_status |= CELL_PAD_STATUS_CONNECTED;
m_bindings[i].pad->m_port_status |= CELL_PAD_STATUS_ASSIGN_CHANGES;
last_connection_status[i] = true;
connected_devices++;
}
else
{
if (update_sticks)
{
for (usz j = 0; j < pad.m_sticks.size(); j++)
{
const f32 stick_lerp_factor = (j < 2) ? m_l_stick_lerp_factor : m_r_stick_lerp_factor;
// we already applied the following values on keypress if we used factor 1
if (stick_lerp_factor < 1.0f)
{
const f32 v0 = static_cast<f32>(pad.m_sticks[j].m_value);
const f32 v1 = static_cast<f32>(m_stick_val[j]);
const f32 res = get_lerped(v0, v1, stick_lerp_factor);
pad.m_sticks[j].m_value = static_cast<u16>(res);
}
}
}
if (update_buttons)
{
for (Button& button : pad.m_buttons)
{
if (button.m_analog)
{
// we already applied the following values on keypress if we used factor 1
if (m_analog_lerp_factor < 1.0f)
{
const f32 v0 = static_cast<f32>(button.m_value);
const f32 v1 = static_cast<f32>(button.m_actual_value);
const f32 res = get_lerped(v0, v1, m_analog_lerp_factor);
button.m_value = static_cast<u16>(res);
button.m_pressed = button.m_value > 0;
}
}
else if (button.m_trigger)
{
// we already applied the following values on keypress if we used factor 1
if (m_trigger_lerp_factor < 1.0f)
{
const f32 v0 = static_cast<f32>(button.m_value);
const f32 v1 = static_cast<f32>(button.m_actual_value);
const f32 res = get_lerped(v0, v1, m_trigger_lerp_factor);
button.m_value = static_cast<u16>(res);
button.m_pressed = button.m_value > 0;
}
}
}
}
}
}
if (m_mouse_wheel_used)
{
// Releases the wheel buttons 0,1 sec after they've been triggered
// Next activation is set to distant future to avoid activating this on every proc
const auto update_threshold = now - std::chrono::milliseconds(100);
const auto distant_future = now + std::chrono::hours(24);
if (update_threshold >= m_last_wheel_move_up)
{
Key(mouse::wheel_up, false);
m_last_wheel_move_up = distant_future;
}
if (update_threshold >= m_last_wheel_move_down)
{
Key(mouse::wheel_down, false);
m_last_wheel_move_down = distant_future;
}
if (update_threshold >= m_last_wheel_move_left)
{
Key(mouse::wheel_left, false);
m_last_wheel_move_left = distant_future;
}
if (update_threshold >= m_last_wheel_move_right)
{
Key(mouse::wheel_right, false);
m_last_wheel_move_right = distant_future;
}
}
for (uint i = 0; i < m_bindings.size(); i++)
{
auto& pad = m_bindings[i].pad;
ensure(pad);
const cfg_pad* cfg = &m_pad_configs[pad->m_player_id];
ensure(cfg);
const Pad& pad_internal = m_pads_internal[i];
// Normalize and apply pad squircling
// Copy sticks first. We don't want to modify the raw internal values
std::array<AnalogStick, 4> squircled_sticks = pad_internal.m_sticks;
// Apply squircling
if (cfg->lpadsquircling != 0)
{
u16& lx = squircled_sticks[0].m_value;
u16& ly = squircled_sticks[1].m_value;
ConvertToSquirclePoint(lx, ly, cfg->lpadsquircling);
}
if (cfg->rpadsquircling != 0)
{
u16& rx = squircled_sticks[2].m_value;
u16& ry = squircled_sticks[3].m_value;
ConvertToSquirclePoint(rx, ry, cfg->rpadsquircling);
}
pad->m_buttons = pad_internal.m_buttons;
pad->m_sticks = squircled_sticks; // Don't use std::move here. We assign values lockless, so std::move can lead to segfaults.
}
}
| 40,460
|
C++
|
.cpp
| 1,104
| 33.54529
| 177
| 0.684389
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,016
|
hid_pad_handler.cpp
|
RPCS3_rpcs3/rpcs3/Input/hid_pad_handler.cpp
|
#include "hid_pad_handler.h"
#include "ds3_pad_handler.h"
#include "ds4_pad_handler.h"
#include "dualsense_pad_handler.h"
#include "skateboard_pad_handler.h"
#include "util/logs.hpp"
#include "Utilities/Timer.h"
#include "Emu/System.h"
#include "pad_thread.h"
#if defined(__APPLE__)
#include "3rdparty/hidapi/hidapi/mac/hidapi_darwin.h"
#endif
#include <algorithm>
#include <memory>
LOG_CHANNEL(hid_log, "HID");
struct hid_instance
{
public:
hid_instance() = default;
~hid_instance()
{
std::lock_guard lock(m_hid_mutex);
// Only exit HIDAPI once on exit. HIDAPI uses a global state internally...
if (m_initialized)
{
hid_log.notice("Exiting HIDAPI...");
if (hid_exit() != 0)
{
hid_log.error("hid_exit failed!");
}
}
}
static hid_instance& get_instance()
{
static hid_instance instance {};
return instance;
}
bool initialize()
{
std::lock_guard lock(m_hid_mutex);
// Only init HIDAPI once. HIDAPI uses a global state internally...
if (m_initialized)
{
return true;
}
hid_log.notice("Initializing HIDAPI ...");
if (hid_init() != 0)
{
hid_log.fatal("hid_init error");
return false;
}
m_initialized = true;
return true;
}
private:
bool m_initialized = false;
std::mutex m_hid_mutex;
};
void HidDevice::close()
{
if (hidDevice)
{
hid_close(hidDevice);
hidDevice = nullptr;
}
}
template <class Device>
hid_pad_handler<Device>::hid_pad_handler(pad_handler type, std::vector<id_pair> ids)
: PadHandlerBase(type), m_ids(std::move(ids))
{
};
template <class Device>
hid_pad_handler<Device>::~hid_pad_handler()
{
if (m_enumeration_thread)
{
auto& enumeration_thread = *m_enumeration_thread;
enumeration_thread = thread_state::aborting;
enumeration_thread();
}
for (auto& controller : m_controllers)
{
if (controller.second)
{
controller.second->close();
}
}
}
template <class Device>
bool hid_pad_handler<Device>::Init()
{
if (m_is_init)
return true;
if (!hid_instance::get_instance().initialize())
return false;
#if defined(__APPLE__)
hid_darwin_set_open_exclusive(0);
#endif
for (usz i = 1; i <= MAX_GAMEPADS; i++) // Controllers 1-n in GUI
{
m_controllers.emplace(m_name_string + std::to_string(i), std::make_shared<Device>());
}
enumerate_devices();
update_devices();
m_is_init = true;
m_enumeration_thread = std::make_unique<named_thread<std::function<void()>>>(fmt::format("%s Enumerator", m_type), [this]()
{
while (thread_ctrl::state() != thread_state::aborting)
{
if (pad::g_enabled && Emu.IsRunning())
{
enumerate_devices();
}
thread_ctrl::wait_for(2'000'000);
}
});
return true;
}
template <class Device>
void hid_pad_handler<Device>::process()
{
update_devices();
PadHandlerBase::process();
}
template <class Device>
std::vector<pad_list_entry> hid_pad_handler<Device>::list_devices()
{
std::vector<pad_list_entry> pads_list;
if (!Init())
return pads_list;
for (const auto& controller : m_controllers) // Controllers 1-n in GUI
{
pads_list.emplace_back(controller.first, false);
}
return pads_list;
}
template <class Device>
void hid_pad_handler<Device>::enumerate_devices()
{
Timer timer;
std::set<std::string> device_paths;
std::map<std::string, std::wstring> serials;
for (const auto& [vid, pid] : m_ids)
{
hid_device_info* dev_info = hid_enumerate(vid, pid);
hid_device_info* head = dev_info;
while (dev_info)
{
if (!dev_info->path)
{
hid_log.error("Skipping enumeration of device with empty path.");
continue;
}
device_paths.insert(dev_info->path);
serials[dev_info->path] = dev_info->serial_number ? std::wstring(dev_info->serial_number) : std::wstring();
dev_info = dev_info->next;
}
hid_free_enumeration(head);
}
hid_log.notice("%s enumeration found %d devices (%f ms)", m_type, device_paths.size(), timer.GetElapsedTimeInMilliSec());
std::lock_guard lock(m_enumeration_mutex);
m_new_enumerated_devices = device_paths;
m_enumerated_serials = std::move(serials);
}
template <class Device>
void hid_pad_handler<Device>::update_devices()
{
std::lock_guard lock(m_enumeration_mutex);
if (m_last_enumerated_devices == m_new_enumerated_devices)
{
return;
}
m_last_enumerated_devices = m_new_enumerated_devices;
// Scrap devices that are not in the new list
for (auto& controller : m_controllers)
{
if (controller.second && !controller.second->path.empty() && !m_new_enumerated_devices.contains(controller.second->path))
{
controller.second->close();
cfg_pad* config = controller.second->config;
controller.second.reset(new Device());
controller.second->config = config;
}
}
bool warn_about_drivers = false;
// Find and add new devices
for (const auto& path : m_new_enumerated_devices)
{
// Check if we have at least one virtual controller left
if (std::none_of(m_controllers.cbegin(), m_controllers.cend(), [](const auto& c) { return !c.second || !c.second->hidDevice; }))
break;
// Check if we already have this controller
if (std::any_of(m_controllers.cbegin(), m_controllers.cend(), [&path](const auto& c) { return c.second && c.second->path == path; }))
continue;
hid_device* dev = hid_open_path(path.c_str());
if (dev)
{
if (const hid_device_info* info = hid_get_device_info(dev))
{
hid_log.notice("%s adding device: vid=0x%x, pid=0x%x, path='%s'", m_type, info->vendor_id, info->product_id, path);
}
else
{
hid_log.warning("%s adding device: vid=N/A, pid=N/A, path='%s', error='%s'", m_type, path, hid_error(dev));
}
check_add_device(dev, path, m_enumerated_serials[path]);
}
else
{
hid_log.error("%s hid_open_path failed! error='%s', path='%s'", m_type, hid_error(dev), path);
warn_about_drivers = true;
}
}
if (warn_about_drivers)
{
hid_log.error("One or more %s pads were detected but couldn't be interacted with directly", m_type);
#if defined(_WIN32) || defined(__linux__)
hid_log.error("Check https://wiki.rpcs3.net/index.php?title=Help:Controller_Configuration for instructions on how to solve this issue");
#endif
}
else
{
const usz count = std::count_if(m_controllers.cbegin(), m_controllers.cend(), [](const auto& c) { return c.second && c.second->hidDevice; });
if (count > 0)
{
hid_log.success("%s Controllers found: %d", m_type, count);
}
else
{
hid_log.warning("No %s controllers found!", m_type);
}
}
}
template <class Device>
std::shared_ptr<Device> hid_pad_handler<Device>::get_hid_device(const std::string& padId)
{
if (!Init())
return nullptr;
// Controllers 1-n in GUI
if (auto it = m_controllers.find(padId); it != m_controllers.end())
{
return it->second;
}
return nullptr;
}
template <class Device>
std::shared_ptr<PadDevice> hid_pad_handler<Device>::get_device(const std::string& device)
{
return get_hid_device(device);
}
template <class Device>
u32 hid_pad_handler<Device>::get_battery_color(u8 battery_level, u32 brightness)
{
static constexpr std::array<u32, 12> battery_level_clr = {0xff00, 0xff33, 0xff66, 0xff99, 0xffcc, 0xffff, 0xccff, 0x99ff, 0x66ff, 0x33ff, 0x00ff, 0x00ff};
const u32 combined_color = battery_level_clr[battery_level < battery_level_clr.size() ? battery_level : 0];
const u32 red = (combined_color >> 8) * brightness / 100;
const u32 green = (combined_color & 0xff) * brightness / 100;
return ((red << 8) | green);
}
template class hid_pad_handler<ds3_device>;
template class hid_pad_handler<DS4Device>;
template class hid_pad_handler<DualSenseDevice>;
template class hid_pad_handler<skateboard_device>;
| 7,585
|
C++
|
.cpp
| 263
| 26.311787
| 155
| 0.697895
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,017
|
pad_thread.cpp
|
RPCS3_rpcs3/rpcs3/Input/pad_thread.cpp
|
#include "stdafx.h"
#include "pad_thread.h"
#include "product_info.h"
#include "ds3_pad_handler.h"
#include "ds4_pad_handler.h"
#include "dualsense_pad_handler.h"
#include "skateboard_pad_handler.h"
#ifdef _WIN32
#include "xinput_pad_handler.h"
#include "mm_joystick_handler.h"
#elif HAVE_LIBEVDEV
#include "evdev_joystick_handler.h"
#endif
#ifdef HAVE_SDL2
#include "sdl_pad_handler.h"
#endif
#include "keyboard_pad_handler.h"
#include "Emu/Io/Null/NullPadHandler.h"
#include "Emu/Io/interception.h"
#include "Emu/Io/PadHandler.h"
#include "Emu/Io/pad_config.h"
#include "Emu/System.h"
#include "Emu/system_config.h"
#include "Emu/RSX/Overlays/HomeMenu/overlay_home_menu.h"
#include "Emu/RSX/Overlays/overlay_message.h"
#include "Emu/Cell/lv2/sys_usbd.h"
#include "Emu/Cell/Modules/cellGem.h"
#include "Utilities/Thread.h"
#include "util/atomic.hpp"
LOG_CHANNEL(sys_log, "SYS");
extern void pad_state_notify_state_change(usz index, u32 state);
extern bool is_input_allowed();
extern std::string g_input_config_override;
namespace pad
{
atomic_t<pad_thread*> g_current = nullptr;
shared_mutex g_pad_mutex;
std::string g_title_id;
atomic_t<bool> g_started{false};
atomic_t<bool> g_reset{false};
atomic_t<bool> g_enabled{true};
atomic_t<bool> g_home_menu_requested{false};
}
namespace rsx
{
void set_native_ui_flip();
}
struct pad_setting
{
u32 port_status = 0;
u32 device_capability = 0;
u32 device_type = 0;
bool is_ldd_pad = false;
};
pad_thread::pad_thread(void* curthread, void* curwindow, std::string_view title_id) : m_curthread(curthread), m_curwindow(curwindow)
{
pad::g_title_id = title_id;
pad::g_current = this;
pad::g_started = false;
}
pad_thread::~pad_thread()
{
pad::g_current = nullptr;
}
void pad_thread::Init()
{
std::lock_guard lock(pad::g_pad_mutex);
// Cache old settings if possible
std::array<pad_setting, CELL_PAD_MAX_PORT_NUM> pad_settings;
for (u32 i = 0; i < CELL_PAD_MAX_PORT_NUM; i++) // max 7 pads
{
if (m_pads[i])
{
pad_settings[i] =
{
m_pads[i]->m_port_status,
m_pads[i]->m_device_capability,
m_pads[i]->m_device_type,
m_pads[i]->ldd
};
}
else
{
pad_settings[i] =
{
CELL_PAD_STATUS_DISCONNECTED,
CELL_PAD_CAPABILITY_PS3_CONFORMITY | CELL_PAD_CAPABILITY_PRESS_MODE | CELL_PAD_CAPABILITY_ACTUATOR,
CELL_PAD_DEV_TYPE_STANDARD,
false
};
}
}
num_ldd_pad = 0;
m_info.now_connect = 0;
m_handlers.clear();
g_cfg_input_configs.load();
std::string active_config = g_cfg_input_configs.active_configs.get_value(pad::g_title_id);
if (active_config.empty())
{
active_config = g_cfg_input_configs.active_configs.get_value(g_cfg_input_configs.global_key);
}
input_log.notice("Using input configuration: '%s' (override='%s')", active_config, g_input_config_override);
// Load in order to get the pad handlers
if (!g_cfg_input.load(pad::g_title_id, active_config))
{
input_log.notice("Loaded empty pad config");
}
// Adjust to the different pad handlers
for (usz i = 0; i < g_cfg_input.player.size(); i++)
{
std::shared_ptr<PadHandlerBase> handler;
pad_thread::InitPadConfig(g_cfg_input.player[i]->config, g_cfg_input.player[i]->handler, handler);
}
// Reload with proper defaults
if (!g_cfg_input.load(pad::g_title_id, active_config))
{
input_log.notice("Reloaded empty pad config");
}
input_log.trace("Using pad config:\n%s", g_cfg_input);
std::shared_ptr<keyboard_pad_handler> keyptr;
// Always have a Null Pad Handler
std::shared_ptr<NullPadHandler> nullpad = std::make_shared<NullPadHandler>();
m_handlers.emplace(pad_handler::null, nullpad);
for (u32 i = 0; i < CELL_PAD_MAX_PORT_NUM; i++) // max 7 pads
{
cfg_player* cfg = g_cfg_input.player[i];
std::shared_ptr<PadHandlerBase> cur_pad_handler;
const pad_handler handler_type = pad_settings[i].is_ldd_pad ? pad_handler::null : cfg->handler.get();
if (m_handlers.contains(handler_type))
{
cur_pad_handler = m_handlers[handler_type];
}
else
{
if (handler_type == pad_handler::keyboard)
{
keyptr = std::make_shared<keyboard_pad_handler>();
keyptr->moveToThread(static_cast<QThread*>(m_curthread));
keyptr->SetTargetWindow(static_cast<QWindow*>(m_curwindow));
cur_pad_handler = keyptr;
}
else
{
cur_pad_handler = GetHandler(handler_type);
}
m_handlers.emplace(handler_type, cur_pad_handler);
}
cur_pad_handler->Init();
std::shared_ptr<Pad> pad = std::make_shared<Pad>(handler_type, i, CELL_PAD_STATUS_DISCONNECTED, pad_settings[i].device_capability, pad_settings[i].device_type);
m_pads[i] = pad;
if (pad_settings[i].is_ldd_pad)
{
InitLddPad(i, &pad_settings[i].port_status);
}
else
{
if (!cur_pad_handler->bindPadToDevice(pad))
{
// Failed to bind the device to cur_pad_handler so binds to NullPadHandler
input_log.error("Failed to bind device '%s' to handler %s. Falling back to NullPadHandler.", cfg->device.to_string(), handler_type);
nullpad->bindPadToDevice(pad);
}
input_log.notice("Pad %d: device='%s', handler=%s, VID=0x%x, PID=0x%x, class_type=0x%x, class_profile=0x%x",
i, cfg->device.to_string(), pad->m_pad_handler, pad->m_vendor_id, pad->m_product_id, pad->m_class_type, pad->m_class_profile);
if (pad->m_pad_handler != pad_handler::null)
{
input_log.notice("Pad %d: config=\n%s", i, cfg->to_string());
}
}
pad->is_fake_pad = (g_cfg.io.move == move_handler::fake && i >= (static_cast<u32>(CELL_PAD_MAX_PORT_NUM) - static_cast<u32>(CELL_GEM_MAX_NUM)))
|| (pad->m_class_type >= CELL_PAD_FAKE_TYPE_FIRST && pad->m_class_type < CELL_PAD_FAKE_TYPE_LAST);
connect_usb_controller(i, input::get_product_by_vid_pid(pad->m_vendor_id, pad->m_product_id));
}
// Initialize active mouse and keyboard. Activate pad handler if one exists.
input::set_mouse_and_keyboard(m_handlers.contains(pad_handler::keyboard) ? input::active_mouse_and_keyboard::pad : input::active_mouse_and_keyboard::emulated);
}
void pad_thread::SetRumble(const u32 pad, u8 large_motor, bool small_motor)
{
if (pad >= m_pads.size())
return;
m_pads[pad]->m_vibrateMotors[0].m_value = large_motor;
m_pads[pad]->m_vibrateMotors[1].m_value = small_motor ? 255 : 0;
}
void pad_thread::SetIntercepted(bool intercepted)
{
if (intercepted)
{
m_info.system_info |= CELL_PAD_INFO_INTERCEPTED;
m_info.ignore_input = true;
}
else
{
m_info.system_info &= ~CELL_PAD_INFO_INTERCEPTED;
}
}
void pad_thread::update_pad_states()
{
for (usz i = 0; i < m_pads.size(); i++)
{
const auto& pad = m_pads[i];
const bool connected = pad && !pad->is_fake_pad && !!(pad->m_port_status & CELL_PAD_STATUS_CONNECTED);
if (m_pads_connected[i] == connected)
continue;
pad_state_notify_state_change(i, connected ? CELL_PAD_STATUS_CONNECTED : CELL_PAD_STATUS_DISCONNECTED);
m_pads_connected[i] = connected;
}
}
void pad_thread::operator()()
{
Init();
const bool is_vsh = Emu.IsVsh();
pad::g_reset = false;
pad::g_started = true;
bool mode_changed = true;
atomic_t<pad_handler_mode> pad_mode{g_cfg.io.pad_mode.get()};
std::vector<std::unique_ptr<named_thread<std::function<void()>>>> threads;
const auto stop_threads = [&threads]()
{
input_log.notice("Stopping pad threads...");
for (auto& thread : threads)
{
if (thread)
{
auto& enumeration_thread = *thread;
enumeration_thread = thread_state::aborting;
enumeration_thread();
}
}
threads.clear();
input_log.notice("Pad threads stopped");
};
const auto start_threads = [this, &threads, &pad_mode]()
{
if (pad_mode == pad_handler_mode::single_threaded)
{
return;
}
input_log.notice("Starting pad threads...");
for (const auto& handler : m_handlers)
{
if (handler.first == pad_handler::null)
{
continue;
}
threads.push_back(std::make_unique<named_thread<std::function<void()>>>(fmt::format("%s Thread", handler.second->m_type), [&handler = handler.second, &pad_mode]()
{
while (thread_ctrl::state() != thread_state::aborting)
{
if (!pad::g_enabled || !is_input_allowed())
{
thread_ctrl::wait_for(30'000);
continue;
}
handler->process();
u64 pad_sleep = g_cfg.io.pad_sleep;
if (Emu.IsPaused())
{
pad_sleep = std::max<u64>(pad_sleep, 30'000);
}
thread_ctrl::wait_for(pad_sleep);
}
}));
}
input_log.notice("Pad threads started");
};
while (thread_ctrl::state() != thread_state::aborting)
{
if (!pad::g_enabled || !is_input_allowed())
{
m_resume_emulation_flag = false;
m_mask_start_press_to_resume = 0;
thread_ctrl::wait_for(30'000);
continue;
}
// Update variables
const bool needs_reset = pad::g_reset && pad::g_reset.exchange(false);
const pad_handler_mode new_pad_mode = g_cfg.io.pad_mode.get();
mode_changed |= new_pad_mode != pad_mode.exchange(new_pad_mode);
// Reset pad handlers if necessary
if (needs_reset || mode_changed)
{
mode_changed = false;
stop_threads();
if (needs_reset)
{
Init();
}
else
{
input_log.success("The pad mode was changed to %s", pad_mode.load());
}
start_threads();
}
u32 connected_devices = 0;
if (pad_mode == pad_handler_mode::single_threaded)
{
for (auto& handler : m_handlers)
{
handler.second->process();
connected_devices += handler.second->connected_devices;
}
}
else
{
for (auto& handler : m_handlers)
{
connected_devices += handler.second->connected_devices;
}
}
if (Emu.IsRunning())
{
update_pad_states();
}
m_info.now_connect = connected_devices + num_ldd_pad;
// The ignore_input section is only reached when a dialog was closed and the pads are still intercepted.
// As long as any of the listed buttons is pressed, cellPadGetData will ignore all input (needed for Hotline Miami).
// ignore_input was added because if we keep the pads intercepted, then some games will enter the menu due to unexpected system interception (tested with Ninja Gaiden Sigma).
if (m_info.ignore_input && !(m_info.system_info & CELL_PAD_INFO_INTERCEPTED))
{
bool any_button_pressed = false;
for (usz i = 0; i < m_pads.size() && !any_button_pressed; i++)
{
const auto& pad = m_pads[i];
if (!(pad->m_port_status & CELL_PAD_STATUS_CONNECTED))
continue;
for (const auto& button : pad->m_buttons)
{
if (button.m_pressed && (
button.m_outKeyCode == CELL_PAD_CTRL_CROSS ||
button.m_outKeyCode == CELL_PAD_CTRL_CIRCLE ||
button.m_outKeyCode == CELL_PAD_CTRL_TRIANGLE ||
button.m_outKeyCode == CELL_PAD_CTRL_SQUARE ||
button.m_outKeyCode == CELL_PAD_CTRL_START ||
button.m_outKeyCode == CELL_PAD_CTRL_SELECT))
{
any_button_pressed = true;
break;
}
}
}
if (!any_button_pressed)
{
m_info.ignore_input = false;
}
}
// Handle home menu if requested
if (!is_vsh && !m_home_menu_open && Emu.IsRunning())
{
bool ps_button_pressed = false;
for (usz i = 0; i < m_pads.size() && !ps_button_pressed; i++)
{
if (i > 0 && g_cfg.io.lock_overlay_input_to_player_one)
break;
const auto& pad = m_pads[i];
if (!(pad->m_port_status & CELL_PAD_STATUS_CONNECTED))
continue;
// Check if an LDD pad pressed the PS button (bit 0 of the first button)
// NOTE: Rock Band 3 doesn't seem to care about the len. It's always 0.
if (pad->ldd /*&& pad->ldd_data.len >= 1 */&& !!(pad->ldd_data.button[0] & CELL_PAD_CTRL_LDD_PS))
{
ps_button_pressed = true;
break;
}
for (const auto& button : pad->m_buttons)
{
if (button.m_offset == CELL_PAD_BTN_OFFSET_DIGITAL1 && button.m_outKeyCode == CELL_PAD_CTRL_PS && button.m_pressed)
{
ps_button_pressed = true;
break;
}
}
}
// Make sure we call this function only once per button press
if ((ps_button_pressed && !m_ps_button_pressed) || pad::g_home_menu_requested.exchange(false))
{
open_home_menu();
}
m_ps_button_pressed = ps_button_pressed;
}
// Handle paused emulation (if triggered by home menu).
if (m_home_menu_open && g_cfg.misc.pause_during_home_menu)
{
// Reset resume control if the home menu is open
m_resume_emulation_flag = false;
m_mask_start_press_to_resume = 0;
m_track_start_press_begin_timestamp = 0;
// Update UI
rsx::set_native_ui_flip();
thread_ctrl::wait_for(33'000);
continue;
}
if (m_resume_emulation_flag)
{
m_resume_emulation_flag = false;
Emu.BlockingCallFromMainThread([]()
{
Emu.Resume();
});
}
u64 pad_sleep = g_cfg.io.pad_sleep;
if (Emu.GetStatus(false) == system_state::paused)
{
pad_sleep = std::max<u64>(pad_sleep, 30'000);
u64 timestamp = get_system_time();
u32 pressed_mask = 0;
for (usz i = 0; i < m_pads.size(); i++)
{
const auto& pad = m_pads[i];
if (!(pad->m_port_status & CELL_PAD_STATUS_CONNECTED))
continue;
for (const auto& button : pad->m_buttons)
{
if (button.m_offset == CELL_PAD_BTN_OFFSET_DIGITAL1 && button.m_outKeyCode == CELL_PAD_CTRL_START && button.m_pressed)
{
pressed_mask |= 1u << i;
break;
}
}
}
m_mask_start_press_to_resume &= pressed_mask;
if (!pressed_mask || timestamp - m_track_start_press_begin_timestamp >= 700'000)
{
m_track_start_press_begin_timestamp = timestamp;
if (std::exchange(m_mask_start_press_to_resume, u32{umax}))
{
m_mask_start_press_to_resume = 0;
m_track_start_press_begin_timestamp = 0;
sys_log.success("Resuming emulation using the START button in a few seconds...");
auto msg_ref = std::make_shared<atomic_t<u32>>(1);
rsx::overlays::queue_message(localized_string_id::EMULATION_RESUMING, 2'000'000, msg_ref);
m_resume_emulation_flag = true;
for (u32 i = 0; i < 40; i++)
{
if (Emu.GetStatus(false) != system_state::paused)
{
// Abort if emulation has been resumed by other means
m_resume_emulation_flag = false;
msg_ref->release(0);
break;
}
thread_ctrl::wait_for(50'000);
rsx::set_native_ui_flip();
}
}
}
}
else
{
// Reset resume control if caught a state of unpaused emulation
m_mask_start_press_to_resume = 0;
m_track_start_press_begin_timestamp = 0;
}
thread_ctrl::wait_for(pad_sleep);
}
stop_threads();
}
void pad_thread::InitLddPad(u32 handle, const u32* port_status)
{
if (handle >= m_pads.size())
{
return;
}
static const input::product_info product = input::get_product_info(input::product_type::playstation_3_controller);
m_pads[handle]->ldd = true;
m_pads[handle]->Init
(
port_status ? *port_status : CELL_PAD_STATUS_CONNECTED | CELL_PAD_STATUS_ASSIGN_CHANGES | CELL_PAD_STATUS_CUSTOM_CONTROLLER,
CELL_PAD_CAPABILITY_PS3_CONFORMITY,
CELL_PAD_DEV_TYPE_LDD,
CELL_PAD_PCLASS_TYPE_STANDARD,
product.pclass_profile,
product.vendor_id,
product.product_id,
50
);
input_log.notice("Pad %d: LDD, VID=0x%x, PID=0x%x, class_type=0x%x, class_profile=0x%x",
handle, m_pads[handle]->m_vendor_id, m_pads[handle]->m_product_id, m_pads[handle]->m_class_type, m_pads[handle]->m_class_profile);
num_ldd_pad++;
}
s32 pad_thread::AddLddPad()
{
// Look for first null pad
for (u32 i = 0; i < CELL_PAD_MAX_PORT_NUM; i++)
{
if (g_cfg_input.player[i]->handler == pad_handler::null && !m_pads[i]->ldd)
{
InitLddPad(i, nullptr);
return i;
}
}
return -1;
}
void pad_thread::UnregisterLddPad(u32 handle)
{
ensure(handle < m_pads.size());
m_pads[handle]->ldd = false;
num_ldd_pad--;
}
std::shared_ptr<PadHandlerBase> pad_thread::GetHandler(pad_handler type)
{
switch (type)
{
case pad_handler::null:
return std::make_shared<NullPadHandler>();
case pad_handler::keyboard:
return std::make_shared<keyboard_pad_handler>();
case pad_handler::ds3:
return std::make_shared<ds3_pad_handler>();
case pad_handler::ds4:
return std::make_shared<ds4_pad_handler>();
case pad_handler::dualsense:
return std::make_shared<dualsense_pad_handler>();
case pad_handler::skateboard:
return std::make_shared<skateboard_pad_handler>();
#ifdef _WIN32
case pad_handler::xinput:
return std::make_shared<xinput_pad_handler>();
case pad_handler::mm:
return std::make_shared<mm_joystick_handler>();
#endif
#ifdef HAVE_SDL2
case pad_handler::sdl:
return std::make_shared<sdl_pad_handler>();
#endif
#ifdef HAVE_LIBEVDEV
case pad_handler::evdev:
return std::make_shared<evdev_joystick_handler>();
#endif
}
return nullptr;
}
void pad_thread::InitPadConfig(cfg_pad& cfg, pad_handler type, std::shared_ptr<PadHandlerBase>& handler)
{
if (!handler)
{
handler = GetHandler(type);
}
ensure(!!handler);
handler->init_config(&cfg);
}
extern bool send_open_home_menu_cmds();
extern void send_close_home_menu_cmds();
extern bool close_osk_from_ps_button();
void pad_thread::open_home_menu()
{
// Check if the OSK is open and can be closed
if (!close_osk_from_ps_button())
{
rsx::overlays::queue_message(get_localized_string(localized_string_id::CELL_OSK_DIALOG_BUSY));
return;
}
if (auto manager = g_fxo->try_get<rsx::overlays::display_manager>())
{
if (m_home_menu_open.exchange(true))
{
return;
}
if (!send_open_home_menu_cmds())
{
m_home_menu_open = false;
return;
}
input_log.notice("opening home menu...");
const error_code result = manager->create<rsx::overlays::home_menu_dialog>()->show([this](s32 status)
{
input_log.notice("closing home menu with status %d", status);
m_home_menu_open = false;
send_close_home_menu_cmds();
});
(result ? input_log.error : input_log.notice)("opened home menu with result %d", s32{result});
}
}
| 17,708
|
C++
|
.cpp
| 572
| 27.548951
| 176
| 0.677795
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,018
|
raw_mouse_config.cpp
|
RPCS3_rpcs3/rpcs3/Input/raw_mouse_config.cpp
|
#include "stdafx.h"
#include "raw_mouse_config.h"
#include "Emu/Io/MouseHandler.h"
std::string mouse_button_id(int code)
{
switch (code)
{
case CELL_MOUSE_BUTTON_1: return "Button 1";
case CELL_MOUSE_BUTTON_2: return "Button 2";
case CELL_MOUSE_BUTTON_3: return "Button 3";
case CELL_MOUSE_BUTTON_4: return "Button 4";
case CELL_MOUSE_BUTTON_5: return "Button 5";
case CELL_MOUSE_BUTTON_6: return "Button 6";
case CELL_MOUSE_BUTTON_7: return "Button 7";
case CELL_MOUSE_BUTTON_8: return "Button 8";
}
return "";
}
cfg::string& raw_mouse_config::get_button_by_index(int index)
{
switch (index)
{
case 0: return mouse_button_1;
case 1: return mouse_button_2;
case 2: return mouse_button_3;
case 3: return mouse_button_4;
case 4: return mouse_button_5;
case 5: return mouse_button_6;
case 6: return mouse_button_7;
case 7: return mouse_button_8;
default: fmt::throw_exception("Invalid index %d", index);
}
}
cfg::string& raw_mouse_config::get_button(int code)
{
switch (code)
{
case CELL_MOUSE_BUTTON_1: return mouse_button_1;
case CELL_MOUSE_BUTTON_2: return mouse_button_2;
case CELL_MOUSE_BUTTON_3: return mouse_button_3;
case CELL_MOUSE_BUTTON_4: return mouse_button_4;
case CELL_MOUSE_BUTTON_5: return mouse_button_5;
case CELL_MOUSE_BUTTON_6: return mouse_button_6;
case CELL_MOUSE_BUTTON_7: return mouse_button_7;
case CELL_MOUSE_BUTTON_8: return mouse_button_8;
default: fmt::throw_exception("Invalid code %d", code);
}
}
raw_mice_config::raw_mice_config()
{
for (u32 i = 0; i < ::size32(players); i++)
{
players.at(i) = std::make_shared<raw_mouse_config>(this, fmt::format("Player %d", i + 1));
}
}
bool raw_mice_config::load()
{
m_mutex.lock();
bool result = false;
const std::string cfg_name = fmt::format("%sconfig/%s.yml", fs::get_config_dir(), cfg_id);
cfg_log.notice("Loading %s config: %s", cfg_id, cfg_name);
from_default();
if (fs::file cfg_file{ cfg_name, fs::read })
{
if (const std::string content = cfg_file.to_string(); !content.empty())
{
result = from_string(content);
}
m_mutex.unlock();
}
else
{
m_mutex.unlock();
save();
}
return result;
}
void raw_mice_config::save()
{
std::lock_guard lock(m_mutex);
const std::string cfg_name = fmt::format("%sconfig/%s.yml", fs::get_config_dir(), cfg_id);
cfg_log.notice("Saving %s config to '%s'", cfg_id, cfg_name);
if (!fs::create_path(fs::get_parent_dir(cfg_name)))
{
cfg_log.fatal("Failed to create path: %s (%s)", cfg_name, fs::g_tls_error);
}
if (!cfg::node::save(cfg_name))
{
cfg_log.error("Failed to save %s config to '%s' (error=%s)", cfg_id, cfg_name, fs::g_tls_error);
}
reload_requested = true;
}
| 2,669
|
C++
|
.cpp
| 92
| 26.956522
| 98
| 0.696331
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,019
|
ds3_pad_handler.cpp
|
RPCS3_rpcs3/rpcs3/Input/ds3_pad_handler.cpp
|
#include "stdafx.h"
#include "ds3_pad_handler.h"
#include "Emu/Io/pad_config.h"
#include "util/asm.hpp"
LOG_CHANNEL(ds3_log, "DS3");
using namespace reports;
constexpr std::array<u8, 6> battery_capacity = {0, 1, 25, 50, 75, 100};
constexpr id_pair SONY_DS3_ID_0 = {0x054C, 0x0268};
ds3_pad_handler::ds3_pad_handler()
: hid_pad_handler(pad_handler::ds3, {SONY_DS3_ID_0})
{
button_list =
{
{ DS3KeyCodes::None, "" },
{ DS3KeyCodes::Triangle, "Triangle" },
{ DS3KeyCodes::Circle, "Circle" },
{ DS3KeyCodes::Cross, "Cross" },
{ DS3KeyCodes::Square, "Square" },
{ DS3KeyCodes::Left, "Left" },
{ DS3KeyCodes::Right, "Right" },
{ DS3KeyCodes::Up, "Up" },
{ DS3KeyCodes::Down, "Down" },
{ DS3KeyCodes::R1, "R1" },
{ DS3KeyCodes::R2, "R2" },
{ DS3KeyCodes::R3, "R3" },
{ DS3KeyCodes::Start, "Start" },
{ DS3KeyCodes::Select, "Select" },
{ DS3KeyCodes::PSButton, "PS Button" },
{ DS3KeyCodes::L1, "L1" },
{ DS3KeyCodes::L2, "L2" },
{ DS3KeyCodes::L3, "L3" },
{ DS3KeyCodes::LSXNeg, "LS X-" },
{ DS3KeyCodes::LSXPos, "LS X+" },
{ DS3KeyCodes::LSYPos, "LS Y+" },
{ DS3KeyCodes::LSYNeg, "LS Y-" },
{ DS3KeyCodes::RSXNeg, "RS X-" },
{ DS3KeyCodes::RSXPos, "RS X+" },
{ DS3KeyCodes::RSYPos, "RS Y+" },
{ DS3KeyCodes::RSYNeg, "RS Y-" }
};
init_configs();
// set capabilities
b_has_config = true;
b_has_rumble = true;
b_has_motion = true;
b_has_deadzones = true;
b_has_battery = true;
b_has_battery_led = true;
b_has_led = true;
b_has_rgb = false;
b_has_player_led = true;
b_has_pressure_intensity_button = false; // The DS3 obviously already has this feature natively.
m_name_string = "DS3 Pad #";
m_max_devices = CELL_PAD_MAX_PORT_NUM;
m_trigger_threshold = trigger_max / 2;
m_thumb_threshold = thumb_max / 2;
}
ds3_pad_handler::~ds3_pad_handler()
{
for (auto& controller : m_controllers)
{
if (controller.second && controller.second->hidDevice)
{
// Disable blinking and vibration
controller.second->large_motor = 0;
controller.second->small_motor = 0;
if (send_output_report(controller.second.get()) == -1)
{
ds3_log.error("~ds3_pad_handler: send_output_report failed! error=%s", hid_error(controller.second->hidDevice));
}
}
}
}
u32 ds3_pad_handler::get_battery_level(const std::string& padId)
{
const std::shared_ptr<ds3_device> device = get_hid_device(padId);
if (!device || !device->hidDevice)
{
return 0;
}
return std::clamp<u32>(device->battery_level, 0, 100);
}
void ds3_pad_handler::SetPadData(const std::string& padId, u8 player_id, u8 large_motor, u8 small_motor, s32/* r*/, s32/* g*/, s32 /* b*/, bool player_led, bool /*battery_led*/, u32 /*battery_led_brightness*/)
{
std::shared_ptr<ds3_device> device = get_hid_device(padId);
if (device == nullptr || device->hidDevice == nullptr)
return;
// Set the device's motor speeds to our requested values 0-255
device->large_motor = large_motor;
device->small_motor = small_motor;
device->player_id = player_id;
device->config = get_config(padId);
ensure(device->config);
device->config->player_led_enabled.set(player_led);
// Start/Stop the engines :)
if (send_output_report(device.get()) == -1)
{
ds3_log.error("SetPadData: send_output_report failed! error=%s", hid_error(device->hidDevice));
}
}
int ds3_pad_handler::send_output_report(ds3_device* ds3dev)
{
if (!ds3dev || !ds3dev->hidDevice || !ds3dev->config)
return -2;
ds3_output_report output_report{};
output_report.rumble.small_motor_on = ds3dev->small_motor;
output_report.rumble.large_motor_force = ds3dev->large_motor;
if (ds3dev->config->led_battery_indicator)
{
if (ds3dev->battery_level >= 75)
output_report.led_enabled = 0b00011110;
else if (ds3dev->battery_level >= 50)
output_report.led_enabled = 0b00001110;
else if (ds3dev->battery_level >= 25)
output_report.led_enabled = 0b00000110;
else
output_report.led_enabled = 0b00000010;
}
else if (ds3dev->config->player_led_enabled)
{
switch (ds3dev->player_id)
{
case 0: output_report.led_enabled = 0b00000010; break;
case 1: output_report.led_enabled = 0b00000100; break;
case 2: output_report.led_enabled = 0b00001000; break;
case 3: output_report.led_enabled = 0b00010000; break;
case 4: output_report.led_enabled = 0b00010010; break;
case 5: output_report.led_enabled = 0b00010100; break;
case 6: output_report.led_enabled = 0b00011000; break;
default:
fmt::throw_exception("DS3 is using forbidden player id %d", ds3dev->player_id);
}
}
else
{
output_report.led_enabled = 0;
}
if (ds3dev->config->led_low_battery_blink && ds3dev->battery_level < 25)
{
output_report.led[3].interval_duration = 0x14; // 2 seconds
output_report.led[3].interval_portion_on = ds3dev->led_delay_on;
output_report.led[3].interval_portion_off = ds3dev->led_delay_off;
}
return hid_write(ds3dev->hidDevice, &output_report.report_id, sizeof(ds3_output_report));
}
void ds3_pad_handler::init_config(cfg_pad* cfg)
{
if (!cfg) return;
// Set default button mapping
cfg->ls_left.def = ::at32(button_list, DS3KeyCodes::LSXNeg);
cfg->ls_down.def = ::at32(button_list, DS3KeyCodes::LSYNeg);
cfg->ls_right.def = ::at32(button_list, DS3KeyCodes::LSXPos);
cfg->ls_up.def = ::at32(button_list, DS3KeyCodes::LSYPos);
cfg->rs_left.def = ::at32(button_list, DS3KeyCodes::RSXNeg);
cfg->rs_down.def = ::at32(button_list, DS3KeyCodes::RSYNeg);
cfg->rs_right.def = ::at32(button_list, DS3KeyCodes::RSXPos);
cfg->rs_up.def = ::at32(button_list, DS3KeyCodes::RSYPos);
cfg->start.def = ::at32(button_list, DS3KeyCodes::Start);
cfg->select.def = ::at32(button_list, DS3KeyCodes::Select);
cfg->ps.def = ::at32(button_list, DS3KeyCodes::PSButton);
cfg->square.def = ::at32(button_list, DS3KeyCodes::Square);
cfg->cross.def = ::at32(button_list, DS3KeyCodes::Cross);
cfg->circle.def = ::at32(button_list, DS3KeyCodes::Circle);
cfg->triangle.def = ::at32(button_list, DS3KeyCodes::Triangle);
cfg->left.def = ::at32(button_list, DS3KeyCodes::Left);
cfg->down.def = ::at32(button_list, DS3KeyCodes::Down);
cfg->right.def = ::at32(button_list, DS3KeyCodes::Right);
cfg->up.def = ::at32(button_list, DS3KeyCodes::Up);
cfg->r1.def = ::at32(button_list, DS3KeyCodes::R1);
cfg->r2.def = ::at32(button_list, DS3KeyCodes::R2);
cfg->r3.def = ::at32(button_list, DS3KeyCodes::R3);
cfg->l1.def = ::at32(button_list, DS3KeyCodes::L1);
cfg->l2.def = ::at32(button_list, DS3KeyCodes::L2);
cfg->l3.def = ::at32(button_list, DS3KeyCodes::L3);
cfg->pressure_intensity_button.def = ::at32(button_list, DS3KeyCodes::None);
cfg->analog_limiter_button.def = ::at32(button_list, DS3KeyCodes::None);
// Set default misc variables
cfg->lstick_anti_deadzone.def = 0;
cfg->rstick_anti_deadzone.def = 0;
cfg->lstickdeadzone.def = 40; // between 0 and 255
cfg->rstickdeadzone.def = 40; // between 0 and 255
cfg->ltriggerthreshold.def = 0; // between 0 and 255
cfg->rtriggerthreshold.def = 0; // between 0 and 255
cfg->lpadsquircling.def = 0;
cfg->rpadsquircling.def = 0;
// Set default LED options
cfg->led_battery_indicator.def = false;
cfg->led_low_battery_blink.def = true;
// apply defaults
cfg->from_default();
}
void ds3_pad_handler::check_add_device(hid_device* hidDevice, std::string_view path, std::wstring_view wide_serial)
{
if (!hidDevice)
{
return;
}
ds3_device* device = nullptr;
for (auto& controller : m_controllers)
{
ensure(controller.second);
if (!controller.second->hidDevice)
{
device = controller.second.get();
break;
}
}
if (!device)
{
return;
}
std::string serial;
#ifdef _WIN32
std::array<u8, 0xFF> buf{};
buf[0] = 0xF2;
int res = hid_get_feature_report(hidDevice, buf.data(), buf.size());
if (res <= 0 || buf[0] != 0xF2)
{
ds3_log.warning("check_add_device: hid_get_feature_report 0xF2 failed! Trying again with 0x0. (result=%d, buf[0]=0x%x, error=%s)", res, buf[0], hid_error(hidDevice));
buf = {};
buf[0] = 0x0;
res = hid_get_feature_report(hidDevice, buf.data(), buf.size());
if (res <= 0 || buf[0] != 0x0)
{
ds3_log.error("check_add_device: hid_get_feature_report 0x0 failed! result=%d, buf[0]=0x%x, error=%s", res, buf[0], hid_error(hidDevice));
hid_close(hidDevice);
return;
}
}
device->report_id = buf[0];
#elif defined (__APPLE__)
int res = hid_init_sixaxis_usb(hidDevice);
if (res < 0)
{
ds3_log.error("check_add_device: hid_init_sixaxis_usb failed! (result=%d, error=%s)", res, hid_error(hidDevice));
hid_close(hidDevice);
return;
}
#endif
for (wchar_t ch : wide_serial)
serial += static_cast<uchar>(ch);
if (hid_set_nonblocking(hidDevice, 1) == -1)
{
ds3_log.error("check_add_device: hid_set_nonblocking failed! Reason: %s", hid_error(hidDevice));
hid_close(hidDevice);
return;
}
device->path = path;
device->hidDevice = hidDevice;
if (send_output_report(device) == -1)
{
ds3_log.error("check_add_device: send_output_report failed! Reason: %s", hid_error(hidDevice));
}
#ifdef _WIN32
ds3_log.notice("Added device: report_id=%d, serial='%s', path='%s'", device->report_id, serial, device->path);
#else
ds3_log.notice("Added device: serial='%s', path='%s'", serial, device->path);
#endif
}
ds3_pad_handler::DataStatus ds3_pad_handler::get_data(ds3_device* ds3dev)
{
if (!ds3dev)
return DataStatus::ReadError;
std::array<u8, 64> buf{};
#ifdef _WIN32
buf[0] = ds3dev->report_id;
const int result = hid_get_feature_report(ds3dev->hidDevice, buf.data(), buf.size());
if (result < 0)
{
ds3_log.error("get_data: hid_get_feature_report 0x%02x failed! result=%d, buf[0]=0x%x, error=%s", ds3dev->report_id, result, buf[0], hid_error(ds3dev->hidDevice));
return DataStatus::ReadError;
}
#else
const int result = hid_read(ds3dev->hidDevice, buf.data(), buf.size());
if (result < 0)
{
ds3_log.error("get_data: hid_read failed! result=%d, error=%s", result, hid_error(ds3dev->hidDevice));
return DataStatus::ReadError;
}
#endif
if (result > 0)
{
#ifdef _WIN32
if (buf[0] == ds3dev->report_id)
#else
if (buf[0] == 0x01 && buf[1] != 0xFF)
#endif
{
std::memcpy(&ds3dev->report, &buf[DS3_HID_OFFSET], sizeof(ds3_input_report));
if (ds3dev->report.battery_status >= 0xEE)
{
// Charging (0xEE) or full (0xEF). Let's set the level to 100%.
ds3dev->battery_level = 100;
ds3dev->cable_state = 1;
}
else
{
ds3dev->battery_level = ::at32(battery_capacity, std::min<usz>(ds3dev->report.battery_status, battery_capacity.size() - 1));
ds3dev->cable_state = 0;
}
return DataStatus::NewData;
}
ds3_log.warning("get_data: Unknown packet received: 0x%02x", buf[0]);
}
return DataStatus::NoNewData;
}
std::unordered_map<u64, u16> ds3_pad_handler::get_button_values(const std::shared_ptr<PadDevice>& device)
{
std::unordered_map<u64, u16> key_buf;
ds3_device* dev = static_cast<ds3_device*>(device.get());
if (!dev)
return key_buf;
const ds3_input_report& report = dev->report;
// Left Stick X Axis
key_buf[DS3KeyCodes::LSXNeg] = Clamp0To255((127.5f - report.lsx) * 2.0f);
key_buf[DS3KeyCodes::LSXPos] = Clamp0To255((report.lsx - 127.5f) * 2.0f);
// Left Stick Y Axis (Up is the negative for some reason)
key_buf[DS3KeyCodes::LSYNeg] = Clamp0To255((report.lsy - 127.5f) * 2.0f);
key_buf[DS3KeyCodes::LSYPos] = Clamp0To255((127.5f - report.lsy) * 2.0f);
// Right Stick X Axis
key_buf[DS3KeyCodes::RSXNeg] = Clamp0To255((127.5f - report.rsx) * 2.0f);
key_buf[DS3KeyCodes::RSXPos] = Clamp0To255((report.rsx - 127.5f) * 2.0f);
// Right Stick Y Axis (Up is the negative for some reason)
key_buf[DS3KeyCodes::RSYNeg] = Clamp0To255((report.rsy - 127.5f) * 2.0f);
key_buf[DS3KeyCodes::RSYPos] = Clamp0To255((127.5f - report.rsy) * 2.0f);
// Buttons or triggers with pressure sensitivity
key_buf[DS3KeyCodes::Up] = (report.buttons[0] & 0x10) ? report.button_values[0] : 0;
key_buf[DS3KeyCodes::Right] = (report.buttons[0] & 0x20) ? report.button_values[1] : 0;
key_buf[DS3KeyCodes::Down] = (report.buttons[0] & 0x40) ? report.button_values[2] : 0;
key_buf[DS3KeyCodes::Left] = (report.buttons[0] & 0x80) ? report.button_values[3] : 0;
key_buf[DS3KeyCodes::L2] = (report.buttons[1] & 0x01) ? report.button_values[4] : 0;
key_buf[DS3KeyCodes::R2] = (report.buttons[1] & 0x02) ? report.button_values[5] : 0;
key_buf[DS3KeyCodes::L1] = (report.buttons[1] & 0x04) ? report.button_values[6] : 0;
key_buf[DS3KeyCodes::R1] = (report.buttons[1] & 0x08) ? report.button_values[7] : 0;
key_buf[DS3KeyCodes::Triangle] = (report.buttons[1] & 0x10) ? report.button_values[8] : 0;
key_buf[DS3KeyCodes::Circle] = (report.buttons[1] & 0x20) ? report.button_values[9] : 0;
key_buf[DS3KeyCodes::Cross] = (report.buttons[1] & 0x40) ? report.button_values[10] : 0;
key_buf[DS3KeyCodes::Square] = (report.buttons[1] & 0x80) ? report.button_values[11] : 0;
// Buttons without pressure sensitivity
key_buf[DS3KeyCodes::Select] = (report.buttons[0] & 0x01) ? 255 : 0;
key_buf[DS3KeyCodes::L3] = (report.buttons[0] & 0x02) ? 255 : 0;
key_buf[DS3KeyCodes::R3] = (report.buttons[0] & 0x04) ? 255 : 0;
key_buf[DS3KeyCodes::Start] = (report.buttons[0] & 0x08) ? 255 : 0;
key_buf[DS3KeyCodes::PSButton] = (report.buttons[2] & 0x01) ? 255 : 0;
return key_buf;
}
pad_preview_values ds3_pad_handler::get_preview_values(const std::unordered_map<u64, u16>& data)
{
return {
::at32(data, L2),
::at32(data, R2),
::at32(data, LSXPos) - ::at32(data, LSXNeg),
::at32(data, LSYPos) - ::at32(data, LSYNeg),
::at32(data, RSXPos) - ::at32(data, RSXNeg),
::at32(data, RSYPos) - ::at32(data, RSYNeg)
};
}
void ds3_pad_handler::get_extended_info(const pad_ensemble& binding)
{
const auto& device = binding.device;
const auto& pad = binding.pad;
ds3_device* dev = static_cast<ds3_device*>(device.get());
if (!dev || !pad)
return;
const ds3_input_report& report = dev->report;
pad->m_battery_level = dev->battery_level;
pad->m_cable_state = dev->cable_state;
// For unknown reasons the sixaxis values seem to be in little endian on linux
#ifdef _WIN32
// Official Sony Windows DS3 driver seems to do the same modification of this value as the ps3
pad->m_sensors[0].m_value = report.accel_x;
#else
// When getting raw values from the device this adjustement is needed
pad->m_sensors[0].m_value = 512 - (static_cast<u16>(report.accel_x) - 512);
#endif
pad->m_sensors[1].m_value = report.accel_y;
pad->m_sensors[2].m_value = report.accel_z;
pad->m_sensors[3].m_value = report.gyro;
// Those are formulas used to adjust sensor values in sys_hid code but I couldn't find all the vars.
//auto polish_value = [](s32 value, s32 dword_0x0, s32 dword_0x4, s32 dword_0x8, s32 dword_0xC, s32 dword_0x18, s32 dword_0x1C) -> u16
//{
// value -= dword_0xC;
// value *= dword_0x4;
// value <<= 10;
// value /= dword_0x0;
// value >>= 10;
// value += dword_0x8;
// if (value < dword_0x18) return dword_0x18;
// if (value > dword_0x1C) return dword_0x1C;
// return static_cast<u16>(value);
//};
// dword_0x0 and dword_0xC are unknown
//pad->m_sensors[0].m_value = polish_value(pad->m_sensors[0].m_value, 226, -226, 512, 512, 0, 1023);
//pad->m_sensors[1].m_value = polish_value(pad->m_sensors[1].m_value, 226, 226, 512, 512, 0, 1023);
//pad->m_sensors[2].m_value = polish_value(pad->m_sensors[2].m_value, 113, 113, 512, 512, 0, 1023);
//pad->m_sensors[3].m_value = polish_value(pad->m_sensors[3].m_value, 1, 1, 512, 512, 0, 1023);
}
bool ds3_pad_handler::get_is_left_trigger(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
return keyCode == DS3KeyCodes::L2;
}
bool ds3_pad_handler::get_is_right_trigger(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
return keyCode == DS3KeyCodes::R2;
}
bool ds3_pad_handler::get_is_left_stick(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
switch (keyCode)
{
case DS3KeyCodes::LSXNeg:
case DS3KeyCodes::LSXPos:
case DS3KeyCodes::LSYPos:
case DS3KeyCodes::LSYNeg:
return true;
default:
return false;
}
}
bool ds3_pad_handler::get_is_right_stick(const std::shared_ptr<PadDevice>& /*device*/, u64 keyCode)
{
switch (keyCode)
{
case DS3KeyCodes::RSXNeg:
case DS3KeyCodes::RSXPos:
case DS3KeyCodes::RSYPos:
case DS3KeyCodes::RSYNeg:
return true;
default:
return false;
}
}
PadHandlerBase::connection ds3_pad_handler::update_connection(const std::shared_ptr<PadDevice>& device)
{
ds3_device* dev = static_cast<ds3_device*>(device.get());
if (!dev || dev->path.empty())
return connection::disconnected;
if (dev->hidDevice == nullptr)
{
if (hid_device* hid_dev = hid_open_path(dev->path.c_str()))
{
if (hid_set_nonblocking(hid_dev, 1) == -1)
{
ds3_log.error("Reconnecting Device %s: hid_set_nonblocking failed with error %s", dev->path, hid_error(hid_dev));
}
dev->hidDevice = hid_dev;
}
else
{
return connection::disconnected;
}
}
if (get_data(dev) == DataStatus::ReadError)
{
// this also can mean disconnected, either way deal with it on next loop and reconnect
dev->close();
return connection::no_data;
}
return connection::connected;
}
void ds3_pad_handler::apply_pad_data(const pad_ensemble& binding)
{
const auto& device = binding.device;
const auto& pad = binding.pad;
ds3_device* dev = static_cast<ds3_device*>(device.get());
if (!dev || !dev->hidDevice || !dev->config || !pad)
return;
cfg_pad* config = dev->config;
const int idx_l = config->switch_vibration_motors ? 1 : 0;
const int idx_s = config->switch_vibration_motors ? 0 : 1;
const u8 speed_large = config->enable_vibration_motor_large ? pad->m_vibrateMotors[idx_l].m_value : 0;
const u8 speed_small = config->enable_vibration_motor_small ? pad->m_vibrateMotors[idx_s].m_value : 0;
const bool wireless = dev->cable_state == 0;
const bool low_battery = dev->battery_level < 25;
const bool is_blinking = dev->led_delay_on > 0 || dev->led_delay_off > 0;
// Blink LED when battery is low
if (config->led_low_battery_blink)
{
// we are now wired or have okay battery level -> stop blinking
if (is_blinking && !(wireless && low_battery))
{
dev->led_delay_on = 0;
dev->led_delay_off = 0;
dev->new_output_data = true;
}
// we are now wireless and low on battery -> blink
else if (!is_blinking && wireless && low_battery)
{
dev->led_delay_on = 0x80;
dev->led_delay_off = 0xFF - dev->led_delay_on;
dev->new_output_data = true;
}
}
// Use LEDs to indicate battery level
if (config->led_battery_indicator)
{
if (dev->last_battery_level != dev->battery_level)
{
dev->new_output_data = true;
dev->last_battery_level = dev->battery_level;
}
}
// Use LEDs to indicate battery level
if (dev->enable_player_leds != config->player_led_enabled.get())
{
dev->new_output_data = true;
dev->enable_player_leds = config->player_led_enabled.get();
}
dev->new_output_data |= dev->large_motor != speed_large || dev->small_motor != speed_small;
dev->large_motor = speed_large;
dev->small_motor = speed_small;
const auto now = steady_clock::now();
const auto elapsed = now - dev->last_output;
if (dev->new_output_data || elapsed > min_output_interval)
{
if (const int res = send_output_report(dev); res >= 0)
{
dev->new_output_data = false;
dev->last_output = now;
}
else if (res == -1)
{
ds3_log.error("apply_pad_data: send_output_report failed! error=%s", hid_error(dev->hidDevice));
}
}
}
| 19,572
|
C++
|
.cpp
| 525
| 34.813333
| 209
| 0.681806
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,020
|
mm_joystick_handler.cpp
|
RPCS3_rpcs3/rpcs3/Input/mm_joystick_handler.cpp
|
#ifdef _WIN32
#include "mm_joystick_handler.h"
#include "Emu/Io/pad_config.h"
mm_joystick_handler::mm_joystick_handler() : PadHandlerBase(pad_handler::mm)
{
init_configs();
// Define border values
thumb_max = 255;
trigger_min = 0;
trigger_max = 255;
// set capabilities
b_has_config = true;
b_has_deadzones = true;
m_name_string = "Joystick #";
m_trigger_threshold = trigger_max / 2;
m_thumb_threshold = thumb_max / 2;
}
void mm_joystick_handler::init_config(cfg_pad* cfg)
{
if (!cfg) return;
// Set default button mapping
cfg->ls_left.def = ::at32(axis_list, mmjoy_axis::joy_x_neg);
cfg->ls_down.def = ::at32(axis_list, mmjoy_axis::joy_y_neg);
cfg->ls_right.def = ::at32(axis_list, mmjoy_axis::joy_x_pos);
cfg->ls_up.def = ::at32(axis_list, mmjoy_axis::joy_y_pos);
cfg->rs_left.def = ::at32(axis_list, mmjoy_axis::joy_z_neg);
cfg->rs_down.def = ::at32(axis_list, mmjoy_axis::joy_r_neg);
cfg->rs_right.def = ::at32(axis_list, mmjoy_axis::joy_z_pos);
cfg->rs_up.def = ::at32(axis_list, mmjoy_axis::joy_r_pos);
cfg->start.def = ::at32(button_list, JOY_BUTTON9);
cfg->select.def = ::at32(button_list, JOY_BUTTON10);
cfg->ps.def = ::at32(button_list, JOY_BUTTON17);
cfg->square.def = ::at32(button_list, JOY_BUTTON4);
cfg->cross.def = ::at32(button_list, JOY_BUTTON3);
cfg->circle.def = ::at32(button_list, JOY_BUTTON2);
cfg->triangle.def = ::at32(button_list, JOY_BUTTON1);
cfg->left.def = ::at32(pov_list, JOY_POVLEFT);
cfg->down.def = ::at32(pov_list, JOY_POVBACKWARD);
cfg->right.def = ::at32(pov_list, JOY_POVRIGHT);
cfg->up.def = ::at32(pov_list, JOY_POVFORWARD);
cfg->r1.def = ::at32(button_list, JOY_BUTTON8);
cfg->r2.def = ::at32(button_list, JOY_BUTTON6);
cfg->r3.def = ::at32(button_list, JOY_BUTTON12);
cfg->l1.def = ::at32(button_list, JOY_BUTTON7);
cfg->l2.def = ::at32(button_list, JOY_BUTTON5);
cfg->l3.def = ::at32(button_list, JOY_BUTTON11);
cfg->pressure_intensity_button.def = ::at32(button_list, NO_BUTTON);
cfg->analog_limiter_button.def = ::at32(button_list, NO_BUTTON);
// Set default misc variables
cfg->lstick_anti_deadzone.def = static_cast<u32>(0.13 * thumb_max); // 13%
cfg->rstick_anti_deadzone.def = static_cast<u32>(0.13 * thumb_max); // 13%
cfg->lstickdeadzone.def = 0; // between 0 and 255
cfg->rstickdeadzone.def = 0; // between 0 and 255
cfg->ltriggerthreshold.def = 0; // between 0 and 255
cfg->rtriggerthreshold.def = 0; // between 0 and 255
cfg->lpadsquircling.def = 8000;
cfg->rpadsquircling.def = 8000;
// apply defaults
cfg->from_default();
}
bool mm_joystick_handler::Init()
{
if (m_is_init)
return true;
m_devices.clear();
m_max_devices = joyGetNumDevs();
if (m_max_devices <= 0)
{
input_log.error("mmjoy: Driver doesn't support Joysticks");
return false;
}
input_log.notice("mmjoy: Driver supports %u joysticks", m_max_devices);
enumerate_devices();
m_is_init = true;
return true;
}
void mm_joystick_handler::enumerate_devices()
{
// Mark all known devices as unplugged
for (auto& [name, device] : m_devices)
{
if (!device) continue;
device->device_status = JOYERR_UNPLUGGED;
}
for (int i = 0; i < static_cast<int>(m_max_devices); i++)
{
MMJOYDevice dev;
if (GetMMJOYDevice(i, &dev) == false)
continue;
auto it = m_devices.find(dev.device_name);
if (it == m_devices.end())
{
// Create a new device
m_devices.emplace(dev.device_name, std::make_shared<MMJOYDevice>(dev));
continue;
}
auto& device = it->second;
if (!device)
continue;
// Update the device (don't update the base class members)
device->device_id = dev.device_id;
device->device_name = dev.device_name;
device->device_info = dev.device_info;
device->device_caps = dev.device_caps;
device->device_status = dev.device_status;
}
}
std::vector<pad_list_entry> mm_joystick_handler::list_devices()
{
std::vector<pad_list_entry> devices;
if (!Init())
return devices;
enumerate_devices();
for (const auto& [name, dev] : m_devices)
{
if (!dev) continue;
devices.emplace_back(name, false);
}
return devices;
}
template <typename T>
std::set<T> mm_joystick_handler::find_keys(const cfg::string& cfg_string) const
{
return find_keys<T>(cfg_pad::get_buttons(cfg_string));
}
template <typename T>
std::set<T> mm_joystick_handler::find_keys(const std::vector<std::string>& names) const
{
std::set<T> keys;
for (const T& k : FindKeyCodes<u64, T>(axis_list, names)) keys.insert(k);
for (const T& k : FindKeyCodes<u64, T>(pov_list, names)) keys.insert(k);
for (const T& k : FindKeyCodes<u64, T>(button_list, names)) keys.insert(k);
return keys;
}
std::array<std::set<u32>, PadHandlerBase::button::button_count> mm_joystick_handler::get_mapped_key_codes(const std::shared_ptr<PadDevice>& device, const cfg_pad* cfg)
{
std::array<std::set<u32>, button::button_count> mapping{};
MMJOYDevice* dev = static_cast<MMJOYDevice*>(device.get());
if (!dev || !cfg)
return mapping;
dev->trigger_code_left = find_keys<u64>(cfg->l2);
dev->trigger_code_right = find_keys<u64>(cfg->r2);
dev->axis_code_left[0] = find_keys<u64>(cfg->ls_left);
dev->axis_code_left[1] = find_keys<u64>(cfg->ls_right);
dev->axis_code_left[2] = find_keys<u64>(cfg->ls_down);
dev->axis_code_left[3] = find_keys<u64>(cfg->ls_up);
dev->axis_code_right[0] = find_keys<u64>(cfg->rs_left);
dev->axis_code_right[1] = find_keys<u64>(cfg->rs_right);
dev->axis_code_right[2] = find_keys<u64>(cfg->rs_down);
dev->axis_code_right[3] = find_keys<u64>(cfg->rs_up);
mapping[button::up] = find_keys<u32>(cfg->up);
mapping[button::down] = find_keys<u32>(cfg->down);
mapping[button::left] = find_keys<u32>(cfg->left);
mapping[button::right] = find_keys<u32>(cfg->right);
mapping[button::cross] = find_keys<u32>(cfg->cross);
mapping[button::square] = find_keys<u32>(cfg->square);
mapping[button::circle] = find_keys<u32>(cfg->circle);
mapping[button::triangle] = find_keys<u32>(cfg->triangle);
mapping[button::l1] = find_keys<u32>(cfg->l1);
mapping[button::l2] = narrow_set(dev->trigger_code_left);
mapping[button::l3] = find_keys<u32>(cfg->l3);
mapping[button::r1] = find_keys<u32>(cfg->r1);
mapping[button::r2] = narrow_set(dev->trigger_code_right);
mapping[button::r3] = find_keys<u32>(cfg->r3);
mapping[button::start] = find_keys<u32>(cfg->start);
mapping[button::select] = find_keys<u32>(cfg->select);
mapping[button::ps] = find_keys<u32>(cfg->ps);
mapping[button::ls_left] = narrow_set(dev->axis_code_left[0]);
mapping[button::ls_right] = narrow_set(dev->axis_code_left[1]);
mapping[button::ls_down] = narrow_set(dev->axis_code_left[2]);
mapping[button::ls_up] = narrow_set(dev->axis_code_left[3]);
mapping[button::rs_left] = narrow_set(dev->axis_code_right[0]);
mapping[button::rs_right] = narrow_set(dev->axis_code_right[1]);
mapping[button::rs_down] = narrow_set(dev->axis_code_right[2]);
mapping[button::rs_up] = narrow_set(dev->axis_code_right[3]);
mapping[button::skateboard_ir_nose] = find_keys<u32>(cfg->ir_nose);
mapping[button::skateboard_ir_tail] = find_keys<u32>(cfg->ir_tail);
mapping[button::skateboard_ir_left] = find_keys<u32>(cfg->ir_left);
mapping[button::skateboard_ir_right] = find_keys<u32>(cfg->ir_right);
mapping[button::skateboard_tilt_left] = find_keys<u32>(cfg->tilt_left);
mapping[button::skateboard_tilt_right] = find_keys<u32>(cfg->tilt_right);
if (b_has_pressure_intensity_button)
{
mapping[button::pressure_intensity_button] = find_keys<u32>(cfg->pressure_intensity_button);
}
if (b_has_analog_limiter_button)
{
mapping[button::analog_limiter_button] = find_keys<u32>(cfg->analog_limiter_button);
}
return mapping;
}
PadHandlerBase::connection mm_joystick_handler::get_next_button_press(const std::string& padId, const pad_callback& callback, const pad_fail_callback& fail_callback, gui_call_type call_type, const std::vector<std::string>& buttons)
{
if (call_type == gui_call_type::blacklist)
m_blacklist.clear();
if (call_type == gui_call_type::reset_input || call_type == gui_call_type::blacklist)
m_min_button_values.clear();
if (!Init())
{
if (fail_callback)
fail_callback(padId);
return connection::disconnected;
}
static std::string cur_pad;
static int id = -1;
if (cur_pad != padId)
{
cur_pad = padId;
const auto dev = get_device_by_name(padId);
id = dev ? static_cast<int>(dev->device_id) : -1;
if (id < 0)
{
input_log.error("MMJOY get_next_button_press for device [%s] failed with id = %d", padId, id);
if (fail_callback)
fail_callback(padId);
return connection::disconnected;
}
}
JOYINFOEX js_info{};
JOYCAPS js_caps{};
js_info.dwSize = sizeof(js_info);
js_info.dwFlags = JOY_RETURNALL;
MMRESULT status = joyGetDevCaps(id, &js_caps, sizeof(js_caps));
if (status == JOYERR_NOERROR)
status = joyGetPosEx(id, &js_info);
switch (status)
{
case JOYERR_UNPLUGGED:
{
if (fail_callback)
fail_callback(padId);
return connection::disconnected;
}
case JOYERR_NOERROR:
{
if (call_type == gui_call_type::get_connection)
{
return connection::connected;
}
auto data = GetButtonValues(js_info, js_caps);
// Check for each button in our list if its corresponding (maybe remapped) button or axis was pressed.
// Return the new value if the button was pressed (aka. its value was bigger than 0 or the defined threshold)
// Get all the legally pressed buttons and use the one with highest value (prioritize first)
struct
{
u16 value = 0;
std::string name;
} pressed_button{};
const auto set_button_press = [&](const u64& keycode, const std::string& name, std::string_view type, u16 threshold)
{
if (call_type != gui_call_type::blacklist && m_blacklist.contains(keycode))
return;
const u16 value = data[keycode];
u16& min_value = m_min_button_values[keycode];
if (call_type == gui_call_type::reset_input || value < min_value)
{
min_value = value;
return;
}
if (value <= threshold)
return;
if (call_type == gui_call_type::blacklist)
{
m_blacklist.insert(keycode);
input_log.error("MMJOY Calibration: Added %s [ %d = %s ] to blacklist. Value = %d", type, keycode, name, value);
return;
}
const u16 diff = value > min_value ? value - min_value : 0;
if (diff > button_press_threshold && value > pressed_button.value)
{
pressed_button = { .value = value, .name = name };
}
};
for (const auto& [keycode, name] : axis_list)
{
set_button_press(keycode, name, "axis"sv, m_thumb_threshold);
}
for (const auto& [keycode, name] : pov_list)
{
set_button_press(keycode, name, "pov"sv, 0);
}
for (const auto& [keycode, name] : button_list)
{
if (keycode == NO_BUTTON)
continue;
set_button_press(keycode, name, "button"sv, 0);
}
if (call_type == gui_call_type::reset_input)
{
return connection::no_data;
}
if (call_type == gui_call_type::blacklist)
{
if (m_blacklist.empty())
input_log.success("MMJOY Calibration: Blacklist is clear. No input spam detected");
return connection::connected;
}
if (callback)
{
pad_preview_values preview_values{};
if (buttons.size() == 10)
{
const auto get_key_value = [this, &data](const std::string& str) -> u16
{
u16 value{};
for (u32 key_code : find_keys<u32>(cfg_pad::get_buttons(str)))
{
if (const auto it = data.find(key_code); it != data.cend())
{
value = std::max(value, it->second);
}
}
return value;
};
preview_values[0] = get_key_value(buttons[0]);
preview_values[1] = get_key_value(buttons[1]);
preview_values[2] = get_key_value(buttons[3]) - get_key_value(buttons[2]);
preview_values[3] = get_key_value(buttons[5]) - get_key_value(buttons[4]);
preview_values[4] = get_key_value(buttons[7]) - get_key_value(buttons[6]);
preview_values[5] = get_key_value(buttons[9]) - get_key_value(buttons[8]);
}
if (pressed_button.value > 0)
callback(pressed_button.value, pressed_button.name, padId, 0, std::move(preview_values));
else
callback(0, "", padId, 0, std::move(preview_values));
}
return connection::connected;
}
default:
return connection::disconnected;
}
return connection::no_data;
}
std::unordered_map<u64, u16> mm_joystick_handler::GetButtonValues(const JOYINFOEX& js_info, const JOYCAPS& js_caps)
{
std::unordered_map<u64, u16> button_values;
for (const auto& entry : button_list)
{
if (entry.first == NO_BUTTON)
continue;
button_values.emplace(entry.first, js_info.dwButtons & entry.first ? 255 : 0);
}
if (js_caps.wCaps & JOYCAPS_HASPOV)
{
if (js_caps.wCaps & JOYCAPS_POVCTS)
{
if (js_info.dwPOV == JOY_POVCENTERED)
{
button_values.emplace(JOY_POVFORWARD, 0);
button_values.emplace(JOY_POVRIGHT, 0);
button_values.emplace(JOY_POVBACKWARD, 0);
button_values.emplace(JOY_POVLEFT, 0);
}
else
{
auto emplacePOVs = [&](float val, u64 pov_neg, u64 pov_pos)
{
if (val < 0)
{
button_values.emplace(pov_neg, static_cast<u16>(std::abs(val)));
button_values.emplace(pov_pos, 0);
}
else
{
button_values.emplace(pov_neg, 0);
button_values.emplace(pov_pos, static_cast<u16>(val));
}
};
const float rad = static_cast<float>(js_info.dwPOV / 100 * acos(-1) / 180);
emplacePOVs(cosf(rad) * 255.0f, JOY_POVBACKWARD, JOY_POVFORWARD);
emplacePOVs(sinf(rad) * 255.0f, JOY_POVLEFT, JOY_POVRIGHT);
}
}
else if (js_caps.wCaps & JOYCAPS_POV4DIR)
{
const int val = static_cast<int>(js_info.dwPOV);
auto emplacePOV = [&button_values, &val](int pov)
{
const int cw = pov + 4500, ccw = pov - 4500;
const bool pressed = (val == pov) || (val == cw) || (ccw < 0 ? val == 36000 - std::abs(ccw) : val == ccw);
button_values.emplace(pov, pressed ? 255 : 0);
};
emplacePOV(JOY_POVFORWARD);
emplacePOV(JOY_POVRIGHT);
emplacePOV(JOY_POVBACKWARD);
emplacePOV(JOY_POVLEFT);
}
}
auto add_axis_value = [&](DWORD axis, UINT min, UINT max, u64 pos, u64 neg)
{
constexpr f32 deadzone = 0.0f;
const float val = ScaledAxisInput(static_cast<f32>(axis), static_cast<f32>(min), static_cast<f32>(max), deadzone);
if (val < 0)
{
button_values.emplace(pos, 0);
button_values.emplace(neg, static_cast<u16>(std::abs(val)));
}
else
{
button_values.emplace(pos, static_cast<u16>(val));
button_values.emplace(neg, 0);
}
};
add_axis_value(js_info.dwXpos, js_caps.wXmin, js_caps.wXmax, mmjoy_axis::joy_x_pos, mmjoy_axis::joy_x_neg);
add_axis_value(js_info.dwYpos, js_caps.wYmin, js_caps.wYmax, mmjoy_axis::joy_y_pos, mmjoy_axis::joy_y_neg);
if (js_caps.wCaps & JOYCAPS_HASZ)
add_axis_value(js_info.dwZpos, js_caps.wZmin, js_caps.wZmax, mmjoy_axis::joy_z_pos, mmjoy_axis::joy_z_neg);
if (js_caps.wCaps & JOYCAPS_HASR)
add_axis_value(js_info.dwRpos, js_caps.wRmin, js_caps.wRmax, mmjoy_axis::joy_r_pos, mmjoy_axis::joy_r_neg);
if (js_caps.wCaps & JOYCAPS_HASU)
add_axis_value(js_info.dwUpos, js_caps.wUmin, js_caps.wUmax, mmjoy_axis::joy_u_pos, mmjoy_axis::joy_u_neg);
if (js_caps.wCaps & JOYCAPS_HASV)
add_axis_value(js_info.dwVpos, js_caps.wVmin, js_caps.wVmax, mmjoy_axis::joy_v_pos, mmjoy_axis::joy_v_neg);
return button_values;
}
std::unordered_map<u64, u16> mm_joystick_handler::get_button_values(const std::shared_ptr<PadDevice>& device)
{
MMJOYDevice* dev = static_cast<MMJOYDevice*>(device.get());
if (!dev)
return std::unordered_map<u64, u16>();
return GetButtonValues(dev->device_info, dev->device_caps);
}
std::shared_ptr<mm_joystick_handler::MMJOYDevice> mm_joystick_handler::get_device_by_name(const std::string& name)
{
// Try to find a device with valid name and index
if (auto it = m_devices.find(name); it != m_devices.end())
{
if (it->second && it->second->device_id != umax)
return it->second;
}
// Make sure we have a device pointer (marked as invalid and unplugged)
std::shared_ptr<MMJOYDevice> dev = create_device_by_name(name);
m_devices.emplace(name, dev);
return dev;
}
std::shared_ptr<mm_joystick_handler::MMJOYDevice> mm_joystick_handler::create_device_by_name(const std::string& name)
{
std::shared_ptr<MMJOYDevice> dev = std::make_shared<MMJOYDevice>();
dev->device_name = name;
// Assign the proper index if possible
if (name.size() > m_name_string.size() && m_max_devices > 0)
{
u64 index = 0;
std::string_view suffix(name.begin() + m_name_string.size(), name.end());
if (try_to_uint64(&index, suffix, 1, m_max_devices))
{
dev->device_id = ::narrow<u32>(index - 1);
}
}
return dev;
}
bool mm_joystick_handler::GetMMJOYDevice(int index, MMJOYDevice* dev) const
{
if (!dev)
return false;
JOYINFOEX js_info{};
JOYCAPS js_caps{};
js_info.dwSize = sizeof(js_info);
js_info.dwFlags = JOY_RETURNALL;
dev->device_status = joyGetDevCaps(index, &js_caps, sizeof(js_caps));
if (dev->device_status != JOYERR_NOERROR)
return false;
dev->device_status = joyGetPosEx(index, &js_info);
if (dev->device_status != JOYERR_NOERROR)
return false;
char drv[MAXPNAMELEN]{};
wcstombs(drv, js_caps.szPname, MAXPNAMELEN - 1);
input_log.notice("Joystick nr.%d found. Driver: %s", index, drv);
dev->device_id = index;
dev->device_name = m_name_string + std::to_string(index + 1); // Controllers 1-n in GUI
dev->device_info = js_info;
dev->device_caps = js_caps;
return true;
}
std::shared_ptr<PadDevice> mm_joystick_handler::get_device(const std::string& device)
{
if (!Init())
return nullptr;
return get_device_by_name(device);
}
bool mm_joystick_handler::get_is_left_trigger(const std::shared_ptr<PadDevice>& device, u64 keyCode)
{
const MMJOYDevice* dev = static_cast<MMJOYDevice*>(device.get());
return dev && dev->trigger_code_left.contains(keyCode);
}
bool mm_joystick_handler::get_is_right_trigger(const std::shared_ptr<PadDevice>& device, u64 keyCode)
{
const MMJOYDevice* dev = static_cast<MMJOYDevice*>(device.get());
return dev && dev->trigger_code_right.contains(keyCode);
}
bool mm_joystick_handler::get_is_left_stick(const std::shared_ptr<PadDevice>& device, u64 keyCode)
{
const MMJOYDevice* dev = static_cast<MMJOYDevice*>(device.get());
return dev && std::any_of(dev->axis_code_left.cbegin(), dev->axis_code_left.cend(), [&keyCode](const std::set<u64>& s){ return s.contains(keyCode); });
}
bool mm_joystick_handler::get_is_right_stick(const std::shared_ptr<PadDevice>& device, u64 keyCode)
{
const MMJOYDevice* dev = static_cast<MMJOYDevice*>(device.get());
return dev && std::any_of(dev->axis_code_right.cbegin(), dev->axis_code_right.cend(), [&keyCode](const std::set<u64>& s){ return s.contains(keyCode); });
}
PadHandlerBase::connection mm_joystick_handler::update_connection(const std::shared_ptr<PadDevice>& device)
{
MMJOYDevice* dev = static_cast<MMJOYDevice*>(device.get());
if (!dev || dev->device_id == umax)
return connection::disconnected;
// Quickly check if the device is connected and fetch the button values
const auto old_status = dev->device_status;
dev->device_status = joyGetPosEx(dev->device_id, &dev->device_info);
// The device is connected and was connected
if (dev->device_status == JOYERR_NOERROR && old_status == JOYERR_NOERROR)
return connection::connected;
// The device is not connected or was not connected
if (dev->device_status != JOYERR_NOERROR)
{
// Only try to reconnect once every now and then.
const steady_clock::time_point now = steady_clock::now();
const s64 elapsed_ms = std::chrono::duration_cast<std::chrono::milliseconds>(now - dev->last_update).count();
if (elapsed_ms < 1000)
return connection::disconnected;
dev->last_update = now;
}
// Try to connect properly again
if (GetMMJOYDevice(dev->device_id, dev))
return connection::connected;
return connection::disconnected;
}
#endif
| 19,975
|
C++
|
.cpp
| 527
| 35.011385
| 231
| 0.685871
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,021
|
raw_mouse_handler.cpp
|
RPCS3_rpcs3/rpcs3/Input/raw_mouse_handler.cpp
|
#include "stdafx.h"
#include "raw_mouse_handler.h"
#include "Emu/RSX/GSRender.h"
#include "Emu/RSX/RSXThread.h"
#include "Emu/Io/interception.h"
#include "Input/raw_mouse_config.h"
#include "Utilities/Timer.h"
#ifdef _WIN32
#include <hidusage.h>
#endif
#define RAW_MOUSE_DEBUG_CURSOR_ENABLED 0
#if RAW_MOUSE_DEBUG_CURSOR_ENABLED
#include "Emu/RSX/Overlays/overlay_cursor.h"
static inline void draw_overlay_cursor(u32 index, s32 x_pos, s32 y_pos, s32 x_max, s32 y_max)
{
const s16 x = static_cast<s16>(x_pos / (x_max / static_cast<f32>(rsx::overlays::overlay::virtual_width)));
const s16 y = static_cast<s16>(y_pos / (y_max / static_cast<f32>(rsx::overlays::overlay::virtual_height)));
const color4f color = { 1.0f, 0.0f, 0.0f, 1.0f };
rsx::overlays::set_cursor(rsx::overlays::cursor_offset::last + index, x, y, color, 2'000'000, false);
}
#else
[[maybe_unused]] static inline void draw_overlay_cursor(u32, s32, s32, s32, s32) {}
#endif
LOG_CHANNEL(input_log, "Input");
raw_mice_config g_cfg_raw_mouse;
shared_mutex g_registered_handlers_mutex;
u32 g_registered_handlers = 0;
raw_mouse::raw_mouse(u32 index, const std::string& device_name, void* handle, raw_mouse_handler* handler)
: m_index(index), m_device_name(device_name), m_handle(handle), m_handler(handler)
{
reload_config();
}
raw_mouse::~raw_mouse()
{
}
void raw_mouse::reload_config()
{
m_buttons.clear();
if (m_index < ::size32(g_cfg_raw_mouse.players))
{
if (const auto& player = ::at32(g_cfg_raw_mouse.players, m_index))
{
input_log.notice("Raw mouse config for player %d=\n%s", m_index, player->to_string());
m_mouse_acceleration = static_cast<float>(player->mouse_acceleration.get()) / 100.0f;
m_buttons[CELL_MOUSE_BUTTON_1] = get_mouse_button(player->mouse_button_1);
m_buttons[CELL_MOUSE_BUTTON_2] = get_mouse_button(player->mouse_button_2);
m_buttons[CELL_MOUSE_BUTTON_3] = get_mouse_button(player->mouse_button_3);
m_buttons[CELL_MOUSE_BUTTON_4] = get_mouse_button(player->mouse_button_4);
m_buttons[CELL_MOUSE_BUTTON_5] = get_mouse_button(player->mouse_button_5);
m_buttons[CELL_MOUSE_BUTTON_6] = get_mouse_button(player->mouse_button_6);
m_buttons[CELL_MOUSE_BUTTON_7] = get_mouse_button(player->mouse_button_7);
m_buttons[CELL_MOUSE_BUTTON_8] = get_mouse_button(player->mouse_button_8);
}
}
}
void raw_mouse::set_index(u32 index)
{
m_index = index;
reload_requested = true;
}
std::pair<int, int> raw_mouse::get_mouse_button(const cfg::string& button)
{
const std::string value = button.to_string();
#ifdef _WIN32
static const std::unordered_map<int, std::pair<int, int>> btn_pairs
{
{ 0, {}},
{ RI_MOUSE_BUTTON_1_UP, { RI_MOUSE_BUTTON_1_DOWN, RI_MOUSE_BUTTON_1_UP }},
{ RI_MOUSE_BUTTON_2_UP, { RI_MOUSE_BUTTON_2_DOWN, RI_MOUSE_BUTTON_2_UP }},
{ RI_MOUSE_BUTTON_3_UP, { RI_MOUSE_BUTTON_3_DOWN, RI_MOUSE_BUTTON_3_UP }},
{ RI_MOUSE_BUTTON_4_UP, { RI_MOUSE_BUTTON_4_DOWN, RI_MOUSE_BUTTON_4_UP }},
{ RI_MOUSE_BUTTON_5_UP, { RI_MOUSE_BUTTON_5_DOWN, RI_MOUSE_BUTTON_5_UP }},
};
if (const auto it = raw_mouse_button_map.find(value); it != raw_mouse_button_map.cend())
{
return ::at32(btn_pairs, it->second);
}
#endif
return {};
}
void raw_mouse::update_window_handle()
{
#ifdef _WIN32
if (GSRender* render = static_cast<GSRender*>(g_fxo->try_get<rsx::thread>()))
{
if (GSFrameBase* frame = render->get_frame())
{
if (display_handle_t window_handle = frame->handle(); window_handle && window_handle == GetActiveWindow())
{
m_window_handle = window_handle;
m_window_width = frame->client_width();
m_window_height = frame->client_height();
return;
}
}
}
#endif
m_window_handle = {};
m_window_width = 0;
m_window_height = 0;
}
void raw_mouse::center_cursor()
{
m_pos_x = m_window_width / 2;
m_pos_y = m_window_height / 2;
}
#ifdef _WIN32
void raw_mouse::update_values(const RAWMOUSE& state)
{
ensure(m_handler != nullptr);
// Update window handle and size
update_window_handle();
if (std::exchange(reload_requested, false))
{
reload_config();
}
const auto get_button_pressed = [this](u8 button, int button_flags)
{
const auto it = m_buttons.find(button);
if (it == m_buttons.cend()) return;
const auto& [down, up] = it->second;
// Only update the value if either down or up flags are present
if ((button_flags & down))
{
m_handler->Button(m_index, button, true);
m_handler->mouse_press_callback(m_device_name, button, true);
}
else if ((button_flags & up))
{
m_handler->Button(m_index, button, false);
m_handler->mouse_press_callback(m_device_name, button, false);
}
};
// Get mouse buttons
get_button_pressed(CELL_MOUSE_BUTTON_1, state.usButtonFlags);
get_button_pressed(CELL_MOUSE_BUTTON_2, state.usButtonFlags);
get_button_pressed(CELL_MOUSE_BUTTON_3, state.usButtonFlags);
get_button_pressed(CELL_MOUSE_BUTTON_4, state.usButtonFlags);
get_button_pressed(CELL_MOUSE_BUTTON_5, state.usButtonFlags);
get_button_pressed(CELL_MOUSE_BUTTON_6, state.usButtonFlags);
get_button_pressed(CELL_MOUSE_BUTTON_7, state.usButtonFlags);
get_button_pressed(CELL_MOUSE_BUTTON_8, state.usButtonFlags);
// Get mouse wheel
if ((state.usButtonFlags & RI_MOUSE_WHEEL))
{
m_handler->Scroll(m_index, 0, std::clamp(static_cast<s16>(state.usButtonData) / WHEEL_DELTA, -128, 127));
}
else if ((state.usButtonFlags & RI_MOUSE_HWHEEL))
{
m_handler->Scroll(m_index, std::clamp(static_cast<s16>(state.usButtonData) / WHEEL_DELTA, -128, 127), 0);
}
// Get mouse movement
if ((state.usFlags & MOUSE_MOVE_ABSOLUTE))
{
// Get absolute mouse movement
if (m_window_handle && m_window_width && m_window_height)
{
// Convert virtual coordinates to screen coordinates
const bool is_virtual_desktop = (state.usFlags & MOUSE_VIRTUAL_DESKTOP) == MOUSE_VIRTUAL_DESKTOP;
const int width = GetSystemMetrics(is_virtual_desktop ? SM_CXVIRTUALSCREEN : SM_CXSCREEN);
const int height = GetSystemMetrics(is_virtual_desktop ? SM_CYVIRTUALSCREEN : SM_CYSCREEN);
if (width && height)
{
POINT pt {
.x = long(state.lLastX / 65535.0f * width),
.y = long(state.lLastY / 65535.0f * height)
};
if (ScreenToClient(m_window_handle, &pt))
{
// Move mouse with absolute position
m_handler->Move(m_index, pt.x, pt.y, m_window_width, m_window_height);
draw_overlay_cursor(m_index, pt.x, pt.y, m_window_width, m_window_height);
}
}
}
}
else if (state.lLastX || state.lLastY)
{
// Get relative mouse movement (units most likely in raw dpi)
if (m_window_handle && m_window_width && m_window_height)
{
// Apply mouse acceleration
const int delta_x = static_cast<int>(state.lLastX * m_mouse_acceleration);
const int delta_y = static_cast<int>(state.lLastY * m_mouse_acceleration);
// Adjust mouse position if the window size changed
if (m_window_width_old != m_window_width || m_window_height_old != m_window_height)
{
m_pos_x = static_cast<int>(std::round((m_pos_x / static_cast<f32>(m_window_width_old)) * m_window_width));
m_pos_y = static_cast<int>(std::round((m_pos_y / static_cast<f32>(m_window_height_old)) * m_window_height));
m_window_width_old = m_window_width;
m_window_height_old = m_window_height;
}
// Calculate new position
m_pos_x = std::max(0, std::min(m_pos_x + delta_x, m_window_width - 1));
m_pos_y = std::max(0, std::min(m_pos_y + delta_y, m_window_height - 1));
// Move mouse relative to old position
m_handler->Move(m_index, m_pos_x, m_pos_y, m_window_width, m_window_height, true, delta_x, delta_y);
draw_overlay_cursor(m_index, m_pos_x, m_pos_y, m_window_width, m_window_height);
}
}
}
#endif
raw_mouse_handler::~raw_mouse_handler()
{
if (m_thread)
{
auto& thread = *m_thread;
thread = thread_state::aborting;
thread();
m_thread.reset();
}
#ifdef _WIN32
unregister_raw_input_devices();
#endif
}
void raw_mouse_handler::Init(const u32 max_connect)
{
if (m_info.max_connect > 0)
{
// Already initialized
return;
}
if (!g_cfg_raw_mouse.load())
{
input_log.notice("raw_mouse_handler: Could not load raw mouse config. Using defaults.");
}
m_mice.clear();
m_mice.resize(max_connect);
// Get max device index
std::set<u32> connected_mice{};
const u32 now_connect = get_now_connect(connected_mice);
// Init mouse info
m_info = {};
m_info.max_connect = max_connect;
m_info.now_connect = std::min(now_connect, max_connect);
m_info.info = input::g_mice_intercepted ? CELL_MOUSE_INFO_INTERCEPTED : 0; // Ownership of mouse data: 0=Application, 1=System
for (u32 i = 0; i < m_info.max_connect; i++)
{
m_info.status[i] = connected_mice.contains(i) ? CELL_MOUSE_STATUS_CONNECTED : CELL_MOUSE_STATUS_DISCONNECTED;
m_info.mode[i] = CELL_MOUSE_INFO_TABLET_MOUSE_MODE;
m_info.tablet_is_supported[i] = CELL_MOUSE_INFO_TABLET_NOT_SUPPORTED;
m_info.vendor_id[0] = 0x1234;
m_info.product_id[0] = 0x1234;
}
type = mouse_handler::raw;
if (m_is_for_gui)
{
// No need for a thread. We call update_devices manually.
return;
}
m_thread = std::make_unique<named_thread<std::function<void()>>>("Raw Mouse Thread", [this]()
{
input_log.notice("raw_mouse_handler: thread started");
while (thread_ctrl::state() != thread_state::aborting)
{
update_devices();
thread_ctrl::wait_for(1'000'000);
}
input_log.notice("raw_mouse_handler: thread stopped");
});
}
void raw_mouse_handler::update_devices()
{
u32 max_connect;
{
std::lock_guard lock(mutex);
max_connect = m_info.max_connect;
}
{
std::map<void*, raw_mouse> enumerated = enumerate_devices(max_connect);
std::lock_guard lock(m_raw_mutex);
if (m_is_for_gui)
{
// Use the new devices
m_raw_mice = std::move(enumerated);
}
else
{
// Integrate the new devices
std::map<void*, raw_mouse> updated_mice;
for (u32 i = 0; i < std::min(max_connect, ::size32(g_cfg_raw_mouse.players)); i++)
{
const auto& player = ::at32(g_cfg_raw_mouse.players, i);
const std::string device_name = player->device.to_string();
// Check if the configured device for this player is connected
if (const auto it = std::find_if(enumerated.begin(), enumerated.end(), [&device_name](const auto& entry){ return entry.second.device_name() == device_name; });
it != enumerated.cend())
{
// Check if the device was already known
const auto it_exists = m_raw_mice.find(it->first);
const bool exists = it_exists != m_raw_mice.cend();
// Copy by value to allow for the same device for multiple players
raw_mouse& mouse = updated_mice[it->first];
mouse = exists ? it_exists->second : it->second;
mouse.set_index(i);
if (!exists)
{
// Initialize and center mouse
mouse.update_window_handle();
mouse.center_cursor();
input_log.notice("raw_mouse_handler: added new device for player %d: '%s'", i, device_name);
}
}
}
// Log disconnected devices
for (const auto& [handle, mouse] : m_raw_mice)
{
if (!updated_mice.contains(handle))
{
input_log.notice("raw_mouse_handler: removed device for player %d: '%s'", mouse.index(), mouse.device_name());
}
}
m_raw_mice = std::move(updated_mice);
}
}
// Update mouse info
std::set<u32> connected_mice{};
const u32 now_connect = get_now_connect(connected_mice);
{
std::lock_guard lock(mutex);
m_info.now_connect = std::min(now_connect, m_info.max_connect);
for (u32 i = 0; i < m_info.max_connect; i++)
{
m_info.status[i] = connected_mice.contains(i) ? CELL_MOUSE_STATUS_CONNECTED : CELL_MOUSE_STATUS_DISCONNECTED;
}
}
#ifdef _WIN32
register_raw_input_devices();
#endif
}
#ifdef _WIN32
void raw_mouse_handler::register_raw_input_devices()
{
std::lock_guard lock(m_raw_mutex);
if (m_registered_raw_input_devices || !m_info.max_connect || m_raw_mice.empty())
{
return;
}
// Get the window handle of the first mouse
raw_mouse& mouse = m_raw_mice.begin()->second;
std::vector<RAWINPUTDEVICE> raw_input_devices;
raw_input_devices.push_back(RAWINPUTDEVICE {
.usUsagePage = HID_USAGE_PAGE_GENERIC,
.usUsage = HID_USAGE_GENERIC_MOUSE,
.dwFlags = 0,
.hwndTarget = mouse.window_handle()
});
{
std::lock_guard lock(g_registered_handlers_mutex);
if (!RegisterRawInputDevices(raw_input_devices.data(), ::size32(raw_input_devices), sizeof(RAWINPUTDEVICE)))
{
input_log.error("raw_mouse_handler: RegisterRawInputDevices failed: %s", fmt::win_error{GetLastError(), nullptr});
return;
}
g_registered_handlers++;
}
m_registered_raw_input_devices = true;
}
void raw_mouse_handler::unregister_raw_input_devices() const
{
if (!m_registered_raw_input_devices)
{
return;
}
std::lock_guard lock(g_registered_handlers_mutex);
if (!g_registered_handlers || (--g_registered_handlers > 0))
{
input_log.notice("raw_mouse_handler: Skip unregistering devices. %d other handlers are still registered.", g_registered_handlers);
return;
}
input_log.notice("raw_mouse_handler: Unregistering devices");
std::vector<RAWINPUTDEVICE> raw_input_devices;
raw_input_devices.push_back(RAWINPUTDEVICE {
.usUsagePage = HID_USAGE_PAGE_GENERIC,
.usUsage = HID_USAGE_GENERIC_MOUSE,
.dwFlags = RIDEV_REMOVE,
.hwndTarget = nullptr
});
if (!RegisterRawInputDevices(raw_input_devices.data(), ::size32(raw_input_devices), sizeof(RAWINPUTDEVICE)))
{
input_log.error("raw_mouse_handler: RegisterRawInputDevices (unregister) failed: %s", fmt::win_error{GetLastError(), nullptr});
}
}
#endif
u32 raw_mouse_handler::get_now_connect(std::set<u32>& connected_mice)
{
u32 now_connect = 0;
connected_mice.clear();
{
std::lock_guard lock(m_raw_mutex);
for (const auto& [handle, mouse] : m_raw_mice)
{
now_connect = std::max(now_connect, mouse.index() + 1);
connected_mice.insert(mouse.index());
}
}
return now_connect;
}
std::map<void*, raw_mouse> raw_mouse_handler::enumerate_devices(u32 max_connect)
{
input_log.trace("raw_mouse_handler: enumerating devices (max_connect=%d)", max_connect);
std::map<void*, raw_mouse> raw_mice;
if (max_connect == 0)
{
return raw_mice;
}
Timer timer{};
#ifdef _WIN32
u32 num_devices{};
u32 res = GetRawInputDeviceList(nullptr, &num_devices, sizeof(RAWINPUTDEVICELIST));
if (res == umax)
{
input_log.error("raw_mouse_handler: GetRawInputDeviceList (count) failed: %s", fmt::win_error{GetLastError(), nullptr});
return raw_mice;
}
if (num_devices == 0)
{
return raw_mice;
}
std::vector<RAWINPUTDEVICELIST> device_list(num_devices);
res = GetRawInputDeviceList(device_list.data(), &num_devices, sizeof(RAWINPUTDEVICELIST));
if (res == umax)
{
input_log.error("raw_mouse_handler: GetRawInputDeviceList (fetch) failed: %s", fmt::win_error{GetLastError(), nullptr});
return raw_mice;
}
for (RAWINPUTDEVICELIST& device : device_list)
{
if (device.dwType != RIM_TYPEMOUSE)
{
continue;
}
u32 size = 0;
res = GetRawInputDeviceInfoW(device.hDevice, RIDI_DEVICENAME, nullptr, &size);
if (res == umax)
{
input_log.error("raw_mouse_handler: GetRawInputDeviceInfoA (RIDI_DEVICENAME count) failed: %s", fmt::win_error{GetLastError(), nullptr});
continue;
}
if (size == 0)
{
continue;
}
std::vector<wchar_t> buf(size);
res = GetRawInputDeviceInfoW(device.hDevice, RIDI_DEVICENAME, buf.data(), &size);
if (res == umax)
{
input_log.error("raw_mouse_handler: GetRawInputDeviceInfoA (RIDI_DEVICENAME fetch) failed: %s", fmt::win_error{GetLastError(), nullptr});
continue;
}
const std::string device_name = wchar_to_utf8(buf.data());
input_log.trace("raw_mouse_handler: found device: '%s'", device_name);
raw_mice[device.hDevice] = raw_mouse(::size32(raw_mice), device_name, device.hDevice, this);
}
#endif
input_log.trace("raw_mouse_handler: found %d devices in %f ms", raw_mice.size(), timer.GetElapsedTimeInMilliSec());
return raw_mice;
}
#ifdef _WIN32
void raw_mouse_handler::handle_native_event(const MSG& msg)
{
if (m_info.max_connect == 0)
{
// Not initialized
return;
}
if (msg.message != WM_INPUT)
{
return;
}
if (GET_RAWINPUT_CODE_WPARAM(msg.wParam) != RIM_INPUT)
{
return;
}
RAWINPUT raw_input{};
UINT size = sizeof(RAWINPUT);
u32 res = GetRawInputData(reinterpret_cast<HRAWINPUT>(msg.lParam), RID_INPUT, &raw_input, &size, sizeof(RAWINPUTHEADER));
if (res == umax)
{
return;
}
switch (raw_input.header.dwType)
{
case RIM_TYPEMOUSE:
{
std::lock_guard lock(m_raw_mutex);
if (g_cfg_raw_mouse.reload_requested.exchange(false))
{
for (auto& [handle, mouse] : m_raw_mice)
{
mouse.request_reload();
}
}
if (auto it = m_raw_mice.find(raw_input.header.hDevice); it != m_raw_mice.end())
{
it->second.update_values(raw_input.data.mouse);
}
break;
}
default:
{
break;
}
}
}
#endif
| 16,798
|
C++
|
.cpp
| 506
| 30.335968
| 163
| 0.697659
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,022
|
basic_keyboard_handler.cpp
|
RPCS3_rpcs3/rpcs3/Input/basic_keyboard_handler.cpp
|
#include "basic_keyboard_handler.h"
#include <QApplication>
#include "Emu/system_config.h"
#include "Emu/Io/interception.h"
#ifdef _WIN32
#include "windows.h"
#endif
LOG_CHANNEL(input_log, "Input");
void basic_keyboard_handler::Init(keyboard_consumer& consumer, const u32 max_connect)
{
KbInfo& info = consumer.GetInfo();
std::vector<Keyboard>& keyboards = consumer.GetKeyboards();
info = {};
keyboards.clear();
for (u32 i = 0; i < max_connect; i++)
{
Keyboard kb{};
kb.m_config.arrange = g_cfg.sys.keyboard_type;
if (consumer.id() == keyboard_consumer::identifier::overlays)
{
// Enable key repeat
kb.m_key_repeat = true;
}
LoadSettings(kb);
keyboards.emplace_back(kb);
}
info.max_connect = max_connect;
info.now_connect = std::min(::size32(keyboards), max_connect);
info.info = input::g_keyboards_intercepted ? CELL_KB_INFO_INTERCEPTED : 0; // Ownership of keyboard data: 0=Application, 1=System
info.status[0] = CELL_KB_STATUS_CONNECTED; // (TODO: Support for more keyboards)
}
/* Sets the target window for the event handler, and also installs an event filter on the target. */
void basic_keyboard_handler::SetTargetWindow(QWindow* target)
{
if (target != nullptr)
{
m_target = target;
target->installEventFilter(this);
}
else
{
// If this is hit, it probably means that some refactoring occurs because currently a gsframe is created in Load.
// We still want events so filter from application instead since target is null.
QApplication::instance()->installEventFilter(this);
input_log.error("Trying to set keyboard handler to a null target window.");
}
}
bool basic_keyboard_handler::eventFilter(QObject* watched, QEvent* event)
{
if (!event) [[unlikely]]
{
return false;
}
if (input::g_active_mouse_and_keyboard != input::active_mouse_and_keyboard::emulated)
{
if (!m_keys_released)
{
ReleaseAllKeys();
}
return false;
}
m_keys_released = false;
// !m_target is for future proofing when gsrender isn't automatically initialized on load.
// !m_target->isVisible() is a hack since currently a guiless application will STILL inititialize a gsrender (providing a valid target)
if (!m_target || !m_target->isVisible() || watched == m_target)
{
switch (event->type())
{
case QEvent::KeyPress:
{
keyPressEvent(static_cast<QKeyEvent*>(event));
break;
}
case QEvent::KeyRelease:
{
keyReleaseEvent(static_cast<QKeyEvent*>(event));
break;
}
case QEvent::FocusOut:
{
ReleaseAllKeys();
break;
}
default:
{
break;
}
}
}
return false;
}
void basic_keyboard_handler::keyPressEvent(QKeyEvent* keyEvent)
{
if (!keyEvent) [[unlikely]]
{
return;
}
if (m_consumers.empty())
{
keyEvent->ignore();
return;
}
const int key = getUnmodifiedKey(keyEvent);
if (key < 0 || !HandleKey(static_cast<u32>(key), keyEvent->nativeScanCode(), true, keyEvent->isAutoRepeat(), keyEvent->text().toStdU32String()))
{
keyEvent->ignore();
}
}
void basic_keyboard_handler::keyReleaseEvent(QKeyEvent* keyEvent)
{
if (!keyEvent) [[unlikely]]
{
return;
}
if (m_consumers.empty())
{
keyEvent->ignore();
return;
}
const int key = getUnmodifiedKey(keyEvent);
if (key < 0 || !HandleKey(static_cast<u32>(key), keyEvent->nativeScanCode(), false, keyEvent->isAutoRepeat(), keyEvent->text().toStdU32String()))
{
keyEvent->ignore();
}
}
// This should get the actual unmodified key without getting too crazy.
// key() only shows the modifiers and the modified key (e.g. no easy way of knowing that - was pressed in 'SHIFT+-' in order to get _)
s32 basic_keyboard_handler::getUnmodifiedKey(QKeyEvent* keyEvent)
{
if (!keyEvent) [[unlikely]]
{
return -1;
}
const int key = keyEvent->key();
if (key < 0)
{
return key;
}
u32 raw_key = static_cast<u32>(key);
#ifdef _WIN32
if (keyEvent->modifiers() != Qt::NoModifier && !keyEvent->text().isEmpty())
{
u32 mapped_key = static_cast<u32>(MapVirtualKeyA(static_cast<UINT>(keyEvent->nativeVirtualKey()), MAPVK_VK_TO_CHAR));
if (raw_key != mapped_key)
{
if (mapped_key > 0x80000000) // diacritics
{
mapped_key -= 0x80000000;
}
raw_key = mapped_key;
}
}
#endif
return static_cast<s32>(raw_key);
}
void basic_keyboard_handler::LoadSettings(Keyboard& keyboard)
{
std::vector<KbButton> buttons;
// Meta Keys
buttons.emplace_back(Qt::Key_Control, CELL_KB_MKEY_L_CTRL);
buttons.emplace_back(Qt::Key_Shift, CELL_KB_MKEY_L_SHIFT);
buttons.emplace_back(Qt::Key_Alt, CELL_KB_MKEY_L_ALT);
buttons.emplace_back(Qt::Key_Meta, CELL_KB_MKEY_L_WIN);
//buttons.emplace_back(, CELL_KB_MKEY_R_CTRL); // There is no way to know if it's left or right in Qt at the moment
//buttons.emplace_back(, CELL_KB_MKEY_R_SHIFT); // There is no way to know if it's left or right in Qt at the moment
//buttons.emplace_back(, CELL_KB_MKEY_R_ALT); // There is no way to know if it's left or right in Qt at the moment
//buttons.emplace_back(, CELL_KB_MKEY_R_WIN); // There is no way to know if it's left or right in Qt at the moment
buttons.emplace_back(Qt::Key_Super_L, CELL_KB_MKEY_L_WIN); // The super keys are supposed to be the windows keys, but they trigger the meta key instead. Let's assign the windows keys to both.
buttons.emplace_back(Qt::Key_Super_R, CELL_KB_MKEY_R_WIN); // The super keys are supposed to be the windows keys, but they trigger the meta key instead. Let's assign the windows keys to both.
// CELL_KB_RAWDAT
//buttons.emplace_back(, CELL_KEYC_NO_EVENT); // Redundant, listed for completeness
//buttons.emplace_back(, CELL_KEYC_E_ROLLOVER);
//buttons.emplace_back(, CELL_KEYC_E_POSTFAIL);
//buttons.emplace_back(, CELL_KEYC_E_UNDEF);
buttons.emplace_back(Qt::Key_Escape, CELL_KEYC_ESCAPE);
buttons.emplace_back(Qt::Key_Kanji, CELL_KEYC_106_KANJI);
buttons.emplace_back(Qt::Key_CapsLock, CELL_KEYC_CAPS_LOCK);
buttons.emplace_back(Qt::Key_F1, CELL_KEYC_F1);
buttons.emplace_back(Qt::Key_F2, CELL_KEYC_F2);
buttons.emplace_back(Qt::Key_F3, CELL_KEYC_F3);
buttons.emplace_back(Qt::Key_F4, CELL_KEYC_F4);
buttons.emplace_back(Qt::Key_F5, CELL_KEYC_F5);
buttons.emplace_back(Qt::Key_F6, CELL_KEYC_F6);
buttons.emplace_back(Qt::Key_F7, CELL_KEYC_F7);
buttons.emplace_back(Qt::Key_F8, CELL_KEYC_F8);
buttons.emplace_back(Qt::Key_F9, CELL_KEYC_F9);
buttons.emplace_back(Qt::Key_F10, CELL_KEYC_F10);
buttons.emplace_back(Qt::Key_F11, CELL_KEYC_F11);
buttons.emplace_back(Qt::Key_F12, CELL_KEYC_F12);
buttons.emplace_back(Qt::Key_Print, CELL_KEYC_PRINTSCREEN);
buttons.emplace_back(Qt::Key_ScrollLock, CELL_KEYC_SCROLL_LOCK);
buttons.emplace_back(Qt::Key_Pause, CELL_KEYC_PAUSE);
buttons.emplace_back(Qt::Key_Insert, CELL_KEYC_INSERT);
buttons.emplace_back(Qt::Key_Home, CELL_KEYC_HOME);
buttons.emplace_back(Qt::Key_PageUp, CELL_KEYC_PAGE_UP);
buttons.emplace_back(Qt::Key_Delete, CELL_KEYC_DELETE);
buttons.emplace_back(Qt::Key_End, CELL_KEYC_END);
buttons.emplace_back(Qt::Key_PageDown, CELL_KEYC_PAGE_DOWN);
buttons.emplace_back(Qt::Key_Right, CELL_KEYC_RIGHT_ARROW);
buttons.emplace_back(Qt::Key_Left, CELL_KEYC_LEFT_ARROW);
buttons.emplace_back(Qt::Key_Down, CELL_KEYC_DOWN_ARROW);
buttons.emplace_back(Qt::Key_Up, CELL_KEYC_UP_ARROW);
//buttons.emplace_back(, CELL_KEYC_NUM_LOCK);
//buttons.emplace_back(, CELL_KEYC_APPLICATION); // This is probably the PS key on the PS3 keyboard
buttons.emplace_back(Qt::Key_Kana_Shift, CELL_KEYC_KANA); // maybe Key_Kana_Lock
buttons.emplace_back(Qt::Key_Henkan, CELL_KEYC_HENKAN);
buttons.emplace_back(Qt::Key_Muhenkan, CELL_KEYC_MUHENKAN);
// CELL_KB_KEYPAD
buttons.emplace_back(Qt::Key_NumLock, CELL_KEYC_KPAD_NUMLOCK);
buttons.emplace_back(Qt::Key_division, CELL_KEYC_KPAD_SLASH); // should ideally be slash but that's occupied obviously
buttons.emplace_back(Qt::Key_multiply, CELL_KEYC_KPAD_ASTERISK); // should ideally be asterisk but that's occupied obviously
//buttons.emplace_back(Qt::Key_Minus, CELL_KEYC_KPAD_MINUS); // should ideally be minus but that's occupied obviously
buttons.emplace_back(Qt::Key_Plus, CELL_KEYC_KPAD_PLUS);
buttons.emplace_back(Qt::Key_Enter, CELL_KEYC_KPAD_ENTER);
//buttons.emplace_back(Qt::Key_1, CELL_KEYC_KPAD_1);
//buttons.emplace_back(Qt::Key_2, CELL_KEYC_KPAD_2);
//buttons.emplace_back(Qt::Key_3, CELL_KEYC_KPAD_3);
//buttons.emplace_back(Qt::Key_4, CELL_KEYC_KPAD_4);
//buttons.emplace_back(Qt::Key_5, CELL_KEYC_KPAD_5);
//buttons.emplace_back(Qt::Key_6, CELL_KEYC_KPAD_6);
//buttons.emplace_back(Qt::Key_7, CELL_KEYC_KPAD_7);
//buttons.emplace_back(Qt::Key_8, CELL_KEYC_KPAD_8);
//buttons.emplace_back(Qt::Key_9, CELL_KEYC_KPAD_9);
//buttons.emplace_back(Qt::Key_0, CELL_KEYC_KPAD_0);
//buttons.emplace_back(Qt::Key_Delete, CELL_KEYC_KPAD_PERIOD);
// ASCII Printable characters
buttons.emplace_back(Qt::Key_A, CELL_KEYC_A);
buttons.emplace_back(Qt::Key_B, CELL_KEYC_B);
buttons.emplace_back(Qt::Key_C, CELL_KEYC_C);
buttons.emplace_back(Qt::Key_D, CELL_KEYC_D);
buttons.emplace_back(Qt::Key_E, CELL_KEYC_E);
buttons.emplace_back(Qt::Key_F, CELL_KEYC_F);
buttons.emplace_back(Qt::Key_G, CELL_KEYC_G);
buttons.emplace_back(Qt::Key_H, CELL_KEYC_H);
buttons.emplace_back(Qt::Key_I, CELL_KEYC_I);
buttons.emplace_back(Qt::Key_J, CELL_KEYC_J);
buttons.emplace_back(Qt::Key_K, CELL_KEYC_K);
buttons.emplace_back(Qt::Key_L, CELL_KEYC_L);
buttons.emplace_back(Qt::Key_M, CELL_KEYC_M);
buttons.emplace_back(Qt::Key_N, CELL_KEYC_N);
buttons.emplace_back(Qt::Key_O, CELL_KEYC_O);
buttons.emplace_back(Qt::Key_P, CELL_KEYC_P);
buttons.emplace_back(Qt::Key_Q, CELL_KEYC_Q);
buttons.emplace_back(Qt::Key_R, CELL_KEYC_R);
buttons.emplace_back(Qt::Key_S, CELL_KEYC_S);
buttons.emplace_back(Qt::Key_T, CELL_KEYC_T);
buttons.emplace_back(Qt::Key_U, CELL_KEYC_U);
buttons.emplace_back(Qt::Key_V, CELL_KEYC_V);
buttons.emplace_back(Qt::Key_W, CELL_KEYC_W);
buttons.emplace_back(Qt::Key_X, CELL_KEYC_X);
buttons.emplace_back(Qt::Key_Y, CELL_KEYC_Y);
buttons.emplace_back(Qt::Key_Z, CELL_KEYC_Z);
buttons.emplace_back(Qt::Key_1, CELL_KEYC_1);
buttons.emplace_back(Qt::Key_2, CELL_KEYC_2);
buttons.emplace_back(Qt::Key_3, CELL_KEYC_3);
buttons.emplace_back(Qt::Key_4, CELL_KEYC_4);
buttons.emplace_back(Qt::Key_5, CELL_KEYC_5);
buttons.emplace_back(Qt::Key_6, CELL_KEYC_6);
buttons.emplace_back(Qt::Key_7, CELL_KEYC_7);
buttons.emplace_back(Qt::Key_8, CELL_KEYC_8);
buttons.emplace_back(Qt::Key_9, CELL_KEYC_9);
buttons.emplace_back(Qt::Key_0, CELL_KEYC_0);
buttons.emplace_back(Qt::Key_Return, CELL_KEYC_ENTER);
buttons.emplace_back(Qt::Key_Backspace, CELL_KEYC_BS);
buttons.emplace_back(Qt::Key_Tab, CELL_KEYC_TAB);
buttons.emplace_back(Qt::Key_Space, CELL_KEYC_SPACE);
buttons.emplace_back(Qt::Key_Minus, CELL_KEYC_MINUS);
buttons.emplace_back(Qt::Key_Equal, CELL_KEYC_EQUAL_101);
buttons.emplace_back(Qt::Key_AsciiCircum, CELL_KEYC_ACCENT_CIRCONFLEX_106);
buttons.emplace_back(Qt::Key_At, CELL_KEYC_ATMARK_106);
buttons.emplace_back(Qt::Key_Semicolon, CELL_KEYC_SEMICOLON);
buttons.emplace_back(Qt::Key_Apostrophe, CELL_KEYC_QUOTATION_101);
buttons.emplace_back(Qt::Key_Colon, CELL_KEYC_COLON_106);
buttons.emplace_back(Qt::Key_Comma, CELL_KEYC_COMMA);
buttons.emplace_back(Qt::Key_Period, CELL_KEYC_PERIOD);
buttons.emplace_back(Qt::Key_Slash, CELL_KEYC_SLASH);
buttons.emplace_back(Qt::Key_yen, CELL_KEYC_YEN_106);
// Some buttons share the same key code on different layouts
if (keyboard.m_config.arrange == CELL_KB_MAPPING_106)
{
buttons.emplace_back(Qt::Key_Backslash, CELL_KEYC_BACKSLASH_106);
buttons.emplace_back(Qt::Key_BracketLeft, CELL_KEYC_LEFT_BRACKET_106);
buttons.emplace_back(Qt::Key_BracketRight, CELL_KEYC_RIGHT_BRACKET_106);
}
else
{
buttons.emplace_back(Qt::Key_Backslash, CELL_KEYC_BACKSLASH_101);
buttons.emplace_back(Qt::Key_BracketLeft, CELL_KEYC_LEFT_BRACKET_101);
buttons.emplace_back(Qt::Key_BracketRight, CELL_KEYC_RIGHT_BRACKET_101);
}
// Made up helper buttons
buttons.emplace_back(Qt::Key_Less, CELL_KEYC_LESS);
buttons.emplace_back(Qt::Key_NumberSign, CELL_KEYC_HASHTAG);
buttons.emplace_back(Qt::Key_ssharp, CELL_KEYC_SSHARP);
buttons.emplace_back(Qt::Key_QuoteLeft, CELL_KEYC_BACK_QUOTE);
buttons.emplace_back(Qt::Key_acute, CELL_KEYC_BACK_QUOTE);
// Fill our map
for (const KbButton& button : buttons)
{
if (!keyboard.m_keys.try_emplace(button.m_keyCode, button).second)
{
input_log.error("basic_keyboard_handler failed to set key code %d", button.m_keyCode);
}
}
}
| 12,462
|
C++
|
.cpp
| 305
| 38.540984
| 192
| 0.730252
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,024
|
sha256.cpp
|
RPCS3_rpcs3/rpcs3/Crypto/sha256.cpp
|
/*
* FIPS-180-2 compliant SHA-256 implementation
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: GPL-2.0
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
/*
* The SHA-256 Secure Hash Standard was published by NIST in 2002.
*
* http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
*/
#include "sha256.h"
#include "utils.h"
#include <string.h>
#if defined(MBEDTLS_SELF_TEST)
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdio.h>
#include <stdlib.h>
#define mbedtls_printf printf
#define mbedtls_calloc calloc
#define mbedtls_free free
#endif /* MBEDTLS_PLATFORM_C */
#endif /* MBEDTLS_SELF_TEST */
#define SHA256_VALIDATE_RET(cond)
#define SHA256_VALIDATE(cond)
#if !defined(MBEDTLS_SHA256_ALT)
/*
* 32-bit integer manipulation macros (big endian)
*/
#ifndef GET_UINT32_BE
#define GET_UINT32_BE(n,b,i) \
do { \
(n) = ( static_cast<uint32_t>((b)[(i) ]) << 24 ) \
| ( static_cast<uint32_t>((b)[(i) + 1]) << 16 ) \
| ( static_cast<uint32_t>((b)[(i) + 2]) << 8 ) \
| ( static_cast<uint32_t>((b)[(i) + 3]) );\
} while( 0 )
#endif
#ifndef PUT_UINT32_BE
#define PUT_UINT32_BE(n,b,i) \
do { \
(b)[(i) ] = static_cast<unsigned char> ( (n) >> 24 ); \
(b)[(i) + 1] = static_cast<unsigned char> ( (n) >> 16 ); \
(b)[(i) + 2] = static_cast<unsigned char> ( (n) >> 8 ); \
(b)[(i) + 3] = static_cast<unsigned char> ( (n) ); \
} while( 0 )
#endif
void mbedtls_sha256_init( mbedtls_sha256_context *ctx )
{
SHA256_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_sha256_context ) );
}
void mbedtls_sha256_free( mbedtls_sha256_context *ctx )
{
if( ctx == NULL )
return;
mbedtls_zeroize(ctx, sizeof(mbedtls_sha256_context));
}
void mbedtls_sha256_clone( mbedtls_sha256_context *dst,
const mbedtls_sha256_context *src )
{
SHA256_VALIDATE( dst != NULL );
SHA256_VALIDATE( src != NULL );
*dst = *src;
}
/*
* SHA-256 context setup
*/
int mbedtls_sha256_starts_ret( mbedtls_sha256_context *ctx, int is224 )
{
SHA256_VALIDATE_RET( ctx != NULL );
SHA256_VALIDATE_RET( is224 == 0 || is224 == 1 );
ctx->total[0] = 0;
ctx->total[1] = 0;
if( is224 == 0 )
{
/* SHA-256 */
ctx->state[0] = 0x6A09E667;
ctx->state[1] = 0xBB67AE85;
ctx->state[2] = 0x3C6EF372;
ctx->state[3] = 0xA54FF53A;
ctx->state[4] = 0x510E527F;
ctx->state[5] = 0x9B05688C;
ctx->state[6] = 0x1F83D9AB;
ctx->state[7] = 0x5BE0CD19;
}
else
{
/* SHA-224 */
ctx->state[0] = 0xC1059ED8;
ctx->state[1] = 0x367CD507;
ctx->state[2] = 0x3070DD17;
ctx->state[3] = 0xF70E5939;
ctx->state[4] = 0xFFC00B31;
ctx->state[5] = 0x68581511;
ctx->state[6] = 0x64F98FA7;
ctx->state[7] = 0xBEFA4FA4;
}
ctx->is224 = is224;
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha256_starts( mbedtls_sha256_context *ctx,
int is224 )
{
mbedtls_sha256_starts_ret( ctx, is224 );
}
#endif
#if !defined(MBEDTLS_SHA256_PROCESS_ALT)
static const uint32_t K[] =
{
0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2,
};
#define SHR(x,n) (((x) & 0xFFFFFFFF) >> (n))
#define ROTR(x,n) (SHR(x,n) | ((x) << (32 - (n))))
#define S0(x) (ROTR(x, 7) ^ ROTR(x,18) ^ SHR(x, 3))
#define S1(x) (ROTR(x,17) ^ ROTR(x,19) ^ SHR(x,10))
#define S2(x) (ROTR(x, 2) ^ ROTR(x,13) ^ ROTR(x,22))
#define S3(x) (ROTR(x, 6) ^ ROTR(x,11) ^ ROTR(x,25))
#define F0(x,y,z) (((x) & (y)) | ((z) & ((x) | (y))))
#define F1(x,y,z) ((z) ^ ((x) & ((y) ^ (z))))
#define R(t) \
( \
W[t] = S1(W[(t) - 2]) + W[(t) - 7] + \
S0(W[(t) - 15]) + W[(t) - 16] \
)
#define P(a,b,c,d,e,f,g,h,x,K) \
do \
{ \
temp1 = (h) + S3(e) + F1((e),(f),(g)) + (K) + (x); \
temp2 = S2(a) + F0((a),(b),(c)); \
(d) += temp1; (h) = temp1 + temp2; \
} while( 0 )
int mbedtls_internal_sha256_process( mbedtls_sha256_context *ctx,
const unsigned char data[64] )
{
uint32_t temp1, temp2, W[64];
uint32_t A[8];
unsigned int i;
SHA256_VALIDATE_RET( ctx != NULL );
SHA256_VALIDATE_RET( (const unsigned char *)data != NULL );
for( i = 0; i < 8; i++ )
A[i] = ctx->state[i];
#if defined(MBEDTLS_SHA256_SMALLER)
for( i = 0; i < 64; i++ )
{
if( i < 16 )
GET_UINT32_BE( W[i], data, 4 * i );
else
R( i );
P( A[0], A[1], A[2], A[3], A[4], A[5], A[6], A[7], W[i], K[i] );
temp1 = A[7]; A[7] = A[6]; A[6] = A[5]; A[5] = A[4]; A[4] = A[3];
A[3] = A[2]; A[2] = A[1]; A[1] = A[0]; A[0] = temp1;
}
#else /* MBEDTLS_SHA256_SMALLER */
for( i = 0; i < 16; i++ )
GET_UINT32_BE( W[i], data, 4 * i );
for( i = 0; i < 16; i += 8 )
{
P( A[0], A[1], A[2], A[3], A[4], A[5], A[6], A[7], W[i+0], K[i+0] );
P( A[7], A[0], A[1], A[2], A[3], A[4], A[5], A[6], W[i+1], K[i+1] );
P( A[6], A[7], A[0], A[1], A[2], A[3], A[4], A[5], W[i+2], K[i+2] );
P( A[5], A[6], A[7], A[0], A[1], A[2], A[3], A[4], W[i+3], K[i+3] );
P( A[4], A[5], A[6], A[7], A[0], A[1], A[2], A[3], W[i+4], K[i+4] );
P( A[3], A[4], A[5], A[6], A[7], A[0], A[1], A[2], W[i+5], K[i+5] );
P( A[2], A[3], A[4], A[5], A[6], A[7], A[0], A[1], W[i+6], K[i+6] );
P( A[1], A[2], A[3], A[4], A[5], A[6], A[7], A[0], W[i+7], K[i+7] );
}
for( i = 16; i < 64; i += 8 )
{
P( A[0], A[1], A[2], A[3], A[4], A[5], A[6], A[7], R(i+0), K[i+0] );
P( A[7], A[0], A[1], A[2], A[3], A[4], A[5], A[6], R(i+1), K[i+1] );
P( A[6], A[7], A[0], A[1], A[2], A[3], A[4], A[5], R(i+2), K[i+2] );
P( A[5], A[6], A[7], A[0], A[1], A[2], A[3], A[4], R(i+3), K[i+3] );
P( A[4], A[5], A[6], A[7], A[0], A[1], A[2], A[3], R(i+4), K[i+4] );
P( A[3], A[4], A[5], A[6], A[7], A[0], A[1], A[2], R(i+5), K[i+5] );
P( A[2], A[3], A[4], A[5], A[6], A[7], A[0], A[1], R(i+6), K[i+6] );
P( A[1], A[2], A[3], A[4], A[5], A[6], A[7], A[0], R(i+7), K[i+7] );
}
#endif /* MBEDTLS_SHA256_SMALLER */
for( i = 0; i < 8; i++ )
ctx->state[i] += A[i];
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha256_process( mbedtls_sha256_context *ctx,
const unsigned char data[64] )
{
mbedtls_internal_sha256_process( ctx, data );
}
#endif
#endif /* !MBEDTLS_SHA256_PROCESS_ALT */
/*
* SHA-256 process buffer
*/
int mbedtls_sha256_update_ret( mbedtls_sha256_context *ctx,
const unsigned char *input,
size_t ilen )
{
int ret;
size_t fill;
uint32_t left;
SHA256_VALIDATE_RET( ctx != NULL );
SHA256_VALIDATE_RET( ilen == 0 || input != NULL );
if( ilen == 0 )
return( 0 );
left = ctx->total[0] & 0x3F;
fill = 64 - left;
ctx->total[0] += static_cast<uint32_t>(ilen);
ctx->total[0] &= 0xFFFFFFFF;
if( ctx->total[0] < static_cast<uint32_t>(ilen) )
ctx->total[1]++;
if( left && ilen >= fill )
{
memcpy( ctx->buffer + left, input, fill );
if( ( ret = mbedtls_internal_sha256_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
input += fill;
ilen -= fill;
left = 0;
}
while( ilen >= 64 )
{
if( ( ret = mbedtls_internal_sha256_process( ctx, input ) ) != 0 )
return( ret );
input += 64;
ilen -= 64;
}
if( ilen > 0 )
memcpy( ctx->buffer + left, input, ilen );
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha256_update( mbedtls_sha256_context *ctx,
const unsigned char *input,
size_t ilen )
{
mbedtls_sha256_update_ret( ctx, input, ilen );
}
#endif
/*
* SHA-256 final digest
*/
int mbedtls_sha256_finish_ret( mbedtls_sha256_context *ctx,
unsigned char output[32] )
{
int ret;
uint32_t used;
uint32_t high, low;
SHA256_VALIDATE_RET( ctx != NULL );
SHA256_VALIDATE_RET( (unsigned char *)output != NULL );
/*
* Add padding: 0x80 then 0x00 until 8 bytes remain for the length
*/
used = ctx->total[0] & 0x3F;
ctx->buffer[used++] = 0x80;
if( used <= 56 )
{
/* Enough room for padding + length in current block */
memset( ctx->buffer + used, 0, 56 - used );
}
else
{
/* We'll need an extra block */
memset( ctx->buffer + used, 0, 64 - used );
if( ( ret = mbedtls_internal_sha256_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
memset( ctx->buffer, 0, 56 );
}
/*
* Add message length
*/
high = ( ctx->total[0] >> 29 )
| ( ctx->total[1] << 3 );
low = ( ctx->total[0] << 3 );
PUT_UINT32_BE( high, ctx->buffer, 56 );
PUT_UINT32_BE( low, ctx->buffer, 60 );
if( ( ret = mbedtls_internal_sha256_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
/*
* Output final state
*/
PUT_UINT32_BE( ctx->state[0], output, 0 );
PUT_UINT32_BE( ctx->state[1], output, 4 );
PUT_UINT32_BE( ctx->state[2], output, 8 );
PUT_UINT32_BE( ctx->state[3], output, 12 );
PUT_UINT32_BE( ctx->state[4], output, 16 );
PUT_UINT32_BE( ctx->state[5], output, 20 );
PUT_UINT32_BE( ctx->state[6], output, 24 );
if( ctx->is224 == 0 )
PUT_UINT32_BE( ctx->state[7], output, 28 );
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha256_finish( mbedtls_sha256_context *ctx,
unsigned char output[32] )
{
mbedtls_sha256_finish_ret( ctx, output );
}
#endif
#endif /* !MBEDTLS_SHA256_ALT */
/*
* output = SHA-256( input buffer )
*/
int mbedtls_sha256_ret( const unsigned char *input,
size_t ilen,
unsigned char output[32],
int is224 )
{
int ret;
mbedtls_sha256_context ctx;
SHA256_VALIDATE_RET( is224 == 0 || is224 == 1 );
SHA256_VALIDATE_RET( ilen == 0 || input != NULL );
SHA256_VALIDATE_RET( (unsigned char *)output != NULL );
mbedtls_sha256_init( &ctx );
if( ( ret = mbedtls_sha256_starts_ret( &ctx, is224 ) ) != 0 )
goto exit;
if( ( ret = mbedtls_sha256_update_ret( &ctx, input, ilen ) ) != 0 )
goto exit;
if( ( ret = mbedtls_sha256_finish_ret( &ctx, output ) ) != 0 )
goto exit;
exit:
mbedtls_sha256_free( &ctx );
return( ret );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha256( const unsigned char *input,
size_t ilen,
unsigned char output[32],
int is224 )
{
mbedtls_sha256_ret( input, ilen, output, is224 );
}
#endif
| 13,013
|
C++
|
.cpp
| 367
| 29.716621
| 80
| 0.530348
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
5,025
|
unedat.cpp
|
RPCS3_rpcs3/rpcs3/Crypto/unedat.cpp
|
#include "stdafx.h"
#include "key_vault.h"
#include "unedat.h"
#include "sha1.h"
#include "lz.h"
#include "ec.h"
#include "Emu/system_utils.hpp"
#include "util/asm.hpp"
#include <algorithm>
#include <span>
LOG_CHANNEL(edat_log, "EDAT");
void generate_key(int crypto_mode, int version, unsigned char *key_final, unsigned char *iv_final, unsigned char *key, unsigned char *iv)
{
int mode = crypto_mode & 0xF0000000;
uchar temp_iv[16]{};
switch (mode)
{
case 0x10000000:
// Encrypted ERK.
// Decrypt the key with EDAT_KEY + EDAT_IV and copy the original IV.
memcpy(temp_iv, EDAT_IV, 0x10);
aescbc128_decrypt(const_cast<u8*>(version ? EDAT_KEY_1 : EDAT_KEY_0), temp_iv, key, key_final, 0x10);
memcpy(iv_final, iv, 0x10);
break;
case 0x20000000:
// Default ERK.
// Use EDAT_KEY and EDAT_IV.
memcpy(key_final, version ? EDAT_KEY_1 : EDAT_KEY_0, 0x10);
memcpy(iv_final, EDAT_IV, 0x10);
break;
case 0x00000000:
// Unencrypted ERK.
// Use the original key and iv.
memcpy(key_final, key, 0x10);
memcpy(iv_final, iv, 0x10);
break;
}
}
void generate_hash(int hash_mode, int version, unsigned char *hash_final, unsigned char *hash)
{
int mode = hash_mode & 0xF0000000;
uchar temp_iv[16]{};
switch (mode)
{
case 0x10000000:
// Encrypted HASH.
// Decrypt the hash with EDAT_KEY + EDAT_IV.
memcpy(temp_iv, EDAT_IV, 0x10);
aescbc128_decrypt(const_cast<u8*>(version ? EDAT_KEY_1 : EDAT_KEY_0), temp_iv, hash, hash_final, 0x10);
break;
case 0x20000000:
// Default HASH.
// Use EDAT_HASH.
memcpy(hash_final, version ? EDAT_HASH_1 : EDAT_HASH_0, 0x10);
break;
case 0x00000000:
// Unencrypted ERK.
// Use the original hash.
memcpy(hash_final, hash, 0x10);
break;
};
}
bool decrypt(int hash_mode, int crypto_mode, int version, unsigned char *in, unsigned char *out, usz length, unsigned char *key, unsigned char *iv, unsigned char *hash, unsigned char *test_hash)
{
// Setup buffers for key, iv and hash.
unsigned char key_final[0x10] = {};
unsigned char iv_final[0x10] = {};
unsigned char hash_final_10[0x10] = {};
unsigned char hash_final_14[0x14] = {};
// Generate crypto key and hash.
generate_key(crypto_mode, version, key_final, iv_final, key, iv);
if ((hash_mode & 0xFF) == 0x01)
generate_hash(hash_mode, version, hash_final_14, hash);
else
generate_hash(hash_mode, version, hash_final_10, hash);
if ((crypto_mode & 0xFF) == 0x01) // No algorithm.
{
memcpy(out, in, length);
}
else if ((crypto_mode & 0xFF) == 0x02) // AES128-CBC
{
aescbc128_decrypt(key_final, iv_final, in, out, length);
}
else
{
edat_log.error("Unknown crypto algorithm!");
return false;
}
if ((hash_mode & 0xFF) == 0x01) // 0x14 SHA1-HMAC
{
return hmac_hash_compare(hash_final_14, 0x14, in, length, test_hash, 0x14);
}
else if ((hash_mode & 0xFF) == 0x02) // 0x10 AES-CMAC
{
return cmac_hash_compare(hash_final_10, 0x10, in, length, test_hash, 0x10);
}
else if ((hash_mode & 0xFF) == 0x04) //0x10 SHA1-HMAC
{
return hmac_hash_compare(hash_final_10, 0x10, in, length, test_hash, 0x10);
}
else
{
edat_log.error("Unknown hashing algorithm!");
return false;
}
}
// EDAT/SDAT functions.
std::tuple<u64, s32, s32> dec_section(unsigned char* metadata)
{
std::array<u8, 0x10> dec;
dec[0x00] = (metadata[0xC] ^ metadata[0x8] ^ metadata[0x10]);
dec[0x01] = (metadata[0xD] ^ metadata[0x9] ^ metadata[0x11]);
dec[0x02] = (metadata[0xE] ^ metadata[0xA] ^ metadata[0x12]);
dec[0x03] = (metadata[0xF] ^ metadata[0xB] ^ metadata[0x13]);
dec[0x04] = (metadata[0x4] ^ metadata[0x8] ^ metadata[0x14]);
dec[0x05] = (metadata[0x5] ^ metadata[0x9] ^ metadata[0x15]);
dec[0x06] = (metadata[0x6] ^ metadata[0xA] ^ metadata[0x16]);
dec[0x07] = (metadata[0x7] ^ metadata[0xB] ^ metadata[0x17]);
dec[0x08] = (metadata[0xC] ^ metadata[0x0] ^ metadata[0x18]);
dec[0x09] = (metadata[0xD] ^ metadata[0x1] ^ metadata[0x19]);
dec[0x0A] = (metadata[0xE] ^ metadata[0x2] ^ metadata[0x1A]);
dec[0x0B] = (metadata[0xF] ^ metadata[0x3] ^ metadata[0x1B]);
dec[0x0C] = (metadata[0x4] ^ metadata[0x0] ^ metadata[0x1C]);
dec[0x0D] = (metadata[0x5] ^ metadata[0x1] ^ metadata[0x1D]);
dec[0x0E] = (metadata[0x6] ^ metadata[0x2] ^ metadata[0x1E]);
dec[0x0F] = (metadata[0x7] ^ metadata[0x3] ^ metadata[0x1F]);
u64 offset = read_from_ptr<be_t<u64>>(dec, 0);
s32 length = read_from_ptr<be_t<s32>>(dec, 8);
s32 compression_end = read_from_ptr<be_t<s32>>(dec, 12);
return std::make_tuple(offset, length, compression_end);
}
u128 get_block_key(int block, NPD_HEADER *npd)
{
unsigned char empty_key[0x10] = {};
unsigned char *src_key = (npd->version <= 1) ? empty_key : npd->dev_hash;
u128 dest_key{};
std::memcpy(&dest_key, src_key, 0xC);
s32 swappedBlock = std::bit_cast<be_t<s32>>(block);
std::memcpy(reinterpret_cast<uchar*>(&dest_key) + 0xC, &swappedBlock, sizeof(swappedBlock));
return dest_key;
}
// for out data, allocate a buffer the size of 'edat->block_size'
// Also, set 'in file' to the beginning of the encrypted data, which may be offset if inside another file, but normally just reset to beginning of file
// returns number of bytes written, -1 for error
s64 decrypt_block(const fs::file* in, u8* out, EDAT_HEADER *edat, NPD_HEADER *npd, u8* crypt_key, u32 block_num, u32 total_blocks, u64 size_left, bool is_out_buffer_aligned = false)
{
// Get metadata info and setup buffers.
const int metadata_section_size = ((edat->flags & EDAT_COMPRESSED_FLAG) != 0 || (edat->flags & EDAT_FLAG_0x20) != 0) ? 0x20 : 0x10;
const int metadata_offset = 0x100;
u8 hash[0x10] = { 0 };
u8 key_result[0x10] = { 0 };
u8 hash_result[0x14] = { 0 };
u64 offset = 0;
u64 metadata_sec_offset = 0;
u64 length = 0;
s32 compression_end = 0;
unsigned char empty_iv[0x10] = {};
// Decrypt the metadata.
if ((edat->flags & EDAT_COMPRESSED_FLAG) != 0)
{
metadata_sec_offset = metadata_offset + u64{block_num} * metadata_section_size;
u8 metadata[0x20]{};
in->read_at(metadata_sec_offset, metadata, 0x20);
// If the data is compressed, decrypt the metadata.
// NOTE: For NPD version 1 the metadata is not encrypted.
if (npd->version <= 1)
{
offset = read_from_ptr<be_t<u64>>(metadata, 0x10);
length = read_from_ptr<be_t<s32>>(metadata, 0x18);
compression_end = read_from_ptr<be_t<s32>>(metadata, 0x1C);
}
else
{
std::tie(offset, length, compression_end) = dec_section(metadata);
}
std::memcpy(hash_result, metadata, 0x10);
}
else if ((edat->flags & EDAT_FLAG_0x20) != 0)
{
// If FLAG 0x20, the metadata precedes each data block.
metadata_sec_offset = metadata_offset + u64{block_num} * (metadata_section_size + edat->block_size);
u8 metadata[0x20]{};
in->read_at(metadata_sec_offset, metadata, 0x20);
std::memcpy(hash_result, metadata, 0x14);
// If FLAG 0x20 is set, apply custom xor.
for (int j = 0; j < 0x10; j++)
hash_result[j] = metadata[j] ^ metadata[j + 0x10];
offset = metadata_sec_offset + 0x20;
length = edat->block_size;
if ((block_num == (total_blocks - 1)) && (edat->file_size % edat->block_size))
length = static_cast<s32>(edat->file_size % edat->block_size);
}
else
{
metadata_sec_offset = metadata_offset + u64{block_num} * metadata_section_size;
in->read_at(metadata_sec_offset, hash_result, 0x10);
offset = metadata_offset + u64{block_num} * edat->block_size + total_blocks * metadata_section_size;
length = edat->block_size;
if ((block_num == (total_blocks - 1)) && (edat->file_size % edat->block_size))
length = static_cast<s32>(edat->file_size % edat->block_size);
}
// Locate the real data.
const usz pad_length = length;
length = utils::align<usz>(pad_length, 0x10);
// Setup buffers for decryption and read the data.
std::vector<u8> enc_data_buf(is_out_buffer_aligned || length == pad_length ? 0 : length);
std::vector<u8> dec_data_buf(length);
// Try to use out buffer for file reads if no padding is needed instead of a new buffer
u8* enc_data = enc_data_buf.empty() ? out : enc_data_buf.data();
// Variable to avoid copies when possible
u8* dec_data = dec_data_buf.data();
std::memset(hash, 0, 0x10);
std::memset(key_result, 0, 0x10);
in->read_at(offset, enc_data, length);
// Generate a key for the current block.
auto b_key = get_block_key(block_num, npd);
// Encrypt the block key with the crypto key.
aesecb128_encrypt(crypt_key, reinterpret_cast<uchar*>(&b_key), key_result);
if ((edat->flags & EDAT_FLAG_0x10) != 0)
{
aesecb128_encrypt(crypt_key, key_result, hash); // If FLAG 0x10 is set, encrypt again to get the final hash.
}
else
{
std::memcpy(hash, key_result, 0x10);
}
// Setup the crypto and hashing mode based on the extra flags.
int crypto_mode = ((edat->flags & EDAT_FLAG_0x02) == 0) ? 0x2 : 0x1;
int hash_mode;
if ((edat->flags & EDAT_FLAG_0x10) == 0)
hash_mode = 0x02;
else if ((edat->flags & EDAT_FLAG_0x20) == 0)
hash_mode = 0x04;
else
hash_mode = 0x01;
if ((edat->flags & EDAT_ENCRYPTED_KEY_FLAG) != 0)
{
crypto_mode |= 0x10000000;
hash_mode |= 0x10000000;
}
const bool should_decompress = ((edat->flags & EDAT_COMPRESSED_FLAG) != 0) && compression_end;
if ((edat->flags & EDAT_DEBUG_DATA_FLAG) != 0)
{
// Reset the flags.
crypto_mode |= 0x01000000;
hash_mode |= 0x01000000;
// Simply copy the data without the header or the footer.
if (should_decompress)
{
std::memcpy(dec_data, enc_data, length);
}
else
{
// Optimize when decompression is not needed by avoiding 2 copies
dec_data = enc_data;
}
}
else
{
// IV is null if NPD version is 1 or 0.
u8* iv = (npd->version <= 1) ? empty_iv : npd->digest;
// Call main crypto routine on this data block.
if (!decrypt(hash_mode, crypto_mode, (npd->version == 4), enc_data, dec_data, length, key_result, iv, hash, hash_result))
{
edat_log.error("Block at offset 0x%llx has invalid hash!", offset);
return -1;
}
}
// Apply additional de-compression if needed and write the decrypted data.
if (should_decompress)
{
const int res = decompress(out, dec_data, edat->block_size);
size_left -= res;
if (size_left == 0)
{
if (res < 0)
{
edat_log.error("Decompression failed!");
return -1;
}
}
return res;
}
if (dec_data != out)
{
std::memcpy(out, dec_data, pad_length);
}
return pad_length;
}
// set file offset to beginning before calling
bool check_data(u8* key, EDAT_HEADER* edat, NPD_HEADER* npd, const fs::file* f, bool verbose)
{
u8 header[0xA0] = { 0 };
u8 empty_header[0xA0] = { 0 };
u8 header_hash[0x10] = { 0 };
u8 metadata_hash[0x10] = { 0 };
const u64 file_offset = f->pos();
// Check NPD version and flags.
if ((npd->version == 0) || (npd->version == 1))
{
if (edat->flags & 0x7EFFFFFE)
{
edat_log.error("Bad header flags!");
return false;
}
}
else if (npd->version == 2)
{
if (edat->flags & 0x7EFFFFE0)
{
edat_log.error("Bad header flags!");
return false;
}
}
else if ((npd->version == 3) || (npd->version == 4))
{
if (edat->flags & 0x7EFFFFC0)
{
edat_log.error("Bad header flags!");
return false;
}
}
else
{
edat_log.error("Unknown version!");
return false;
}
// Read in the file header.
f->read(header, 0xA0);
// Read in the header and metadata section hashes.
f->seek(file_offset + 0x90);
f->read(metadata_hash, 0x10);
f->read(header_hash, 0x10);
// Setup the hashing mode and the crypto mode used in the file.
const int crypto_mode = 0x1;
int hash_mode = ((edat->flags & EDAT_ENCRYPTED_KEY_FLAG) == 0) ? 0x00000002 : 0x10000002;
if ((edat->flags & EDAT_DEBUG_DATA_FLAG) != 0)
{
hash_mode |= 0x01000000;
if (verbose)
edat_log.warning("DEBUG data detected!");
}
// Setup header key and iv buffers.
unsigned char header_key[0x10] = { 0 };
unsigned char header_iv[0x10] = { 0 };
// Test the header hash (located at offset 0xA0).
if (!decrypt(hash_mode, crypto_mode, (npd->version == 4), header, empty_header, 0xA0, header_key, header_iv, key, header_hash))
{
if (verbose)
edat_log.warning("Header hash is invalid!");
// If the header hash test fails and the data is not DEBUG, then RAP/RIF/KLIC key is invalid.
if ((edat->flags & EDAT_DEBUG_DATA_FLAG) != EDAT_DEBUG_DATA_FLAG)
{
edat_log.error("RAP/RIF/KLIC key is invalid!");
return false;
}
}
// Parse the metadata info.
const int metadata_section_size = ((edat->flags & EDAT_COMPRESSED_FLAG) != 0 || (edat->flags & EDAT_FLAG_0x20) != 0) ? 0x20 : 0x10;
if (((edat->flags & EDAT_COMPRESSED_FLAG) != 0))
{
if (verbose)
edat_log.warning("COMPRESSED data detected!");
}
if (!edat->block_size)
{
return false;
}
const usz block_num = utils::aligned_div<u64>(edat->file_size, edat->block_size);
constexpr usz metadata_offset = 0x100;
const usz metadata_size = utils::mul_saturate<u64>(metadata_section_size, block_num);
u64 metadata_section_offset = metadata_offset;
if (utils::add_saturate<u64>(utils::add_saturate<u64>(file_offset, metadata_section_offset), metadata_size) > f->size())
{
return false;
}
u64 bytes_read = 0;
const auto metadata = std::make_unique<u8[]>(metadata_size);
const auto empty_metadata = std::make_unique<u8[]>(metadata_size);
while (bytes_read < metadata_size)
{
// Locate the metadata blocks.
const usz offset = file_offset + metadata_section_offset;
// Read in the metadata.
f->read_at(offset, metadata.get() + bytes_read, metadata_section_size);
// Adjust sizes.
bytes_read += metadata_section_size;
if (((edat->flags & EDAT_FLAG_0x20) != 0)) // Metadata block before each data block.
metadata_section_offset += (metadata_section_size + edat->block_size);
else
metadata_section_offset += metadata_section_size;
}
// Test the metadata section hash (located at offset 0x90).
if (!decrypt(hash_mode, crypto_mode, (npd->version == 4), metadata.get(), empty_metadata.get(), metadata_size, header_key, header_iv, key, metadata_hash))
{
if (verbose)
edat_log.warning("Metadata section hash is invalid!");
}
// Checking ECDSA signatures.
if ((edat->flags & EDAT_DEBUG_DATA_FLAG) == 0)
{
// Setup buffers.
unsigned char metadata_signature[0x28] = { 0 };
unsigned char header_signature[0x28] = { 0 };
unsigned char signature_hash[20] = { 0 };
unsigned char signature_r[0x15] = { 0 };
unsigned char signature_s[0x15] = { 0 };
unsigned char zero_buf[0x15] = { 0 };
// Setup ECDSA curve and public key.
ecdsa_set_curve(VSH_CURVE_P, VSH_CURVE_A, VSH_CURVE_B, VSH_CURVE_N, VSH_CURVE_GX, VSH_CURVE_GY);
ecdsa_set_pub(VSH_PUB);
// Read in the metadata and header signatures.
f->seek(0xB0);
f->read(metadata_signature, 0x28);
f->read(header_signature, 0x28);
// Checking metadata signature.
// Setup signature r and s.
signature_r[0] = 0;
signature_s[0] = 0;
std::memcpy(signature_r + 1, metadata_signature, 0x14);
std::memcpy(signature_s + 1, metadata_signature + 0x14, 0x14);
if ((!std::memcmp(signature_r, zero_buf, 0x15)) || (!std::memcmp(signature_s, zero_buf, 0x15)))
{
edat_log.warning("Metadata signature is invalid!");
}
else
{
// Setup signature hash.
if ((edat->flags & EDAT_FLAG_0x20) != 0) //Sony failed again, they used buffer from 0x100 with half size of real metadata.
{
const usz metadata_buf_size = block_num * 0x10;
std::vector<u8> metadata_buf(metadata_buf_size);
f->read_at(file_offset + metadata_offset, metadata_buf.data(), metadata_buf_size);
sha1(metadata_buf.data(), metadata_buf_size, signature_hash);
}
else
sha1(metadata.get(), metadata_size, signature_hash);
if (!ecdsa_verify(signature_hash, signature_r, signature_s))
{
edat_log.warning("Metadata signature is invalid!");
if (((edat->block_size + 0ull) * block_num) > 0x100000000)
edat_log.warning("*Due to large file size, metadata signature status may be incorrect!");
}
}
// Checking header signature.
// Setup header signature r and s.
signature_r[0] = 0;
signature_s[0] = 0;
std::memcpy(signature_r + 1, header_signature, 0x14);
std::memcpy(signature_s + 1, header_signature + 0x14, 0x14);
if ((!std::memcmp(signature_r, zero_buf, 0x15)) || (!std::memcmp(signature_s, zero_buf, 0x15)))
{
edat_log.warning("Header signature is invalid!");
}
else
{
// Setup header signature hash.
std::memset(signature_hash, 0, 20);
u8 header_buf[0xD8]{};
f->read_at(file_offset, header_buf, 0xD8);
sha1(header_buf, 0xD8, signature_hash);
if (!ecdsa_verify(signature_hash, signature_r, signature_s))
edat_log.warning("Header signature is invalid!");
}
}
return true;
}
bool validate_dev_klic(const u8* klicensee, NPD_HEADER *npd)
{
if ((npd->license & 0x3) != 0x3)
{
return true;
}
unsigned char dev[0x60]{};
// Build the dev buffer (first 0x60 bytes of NPD header in big-endian).
std::memcpy(dev, npd, 0x60);
// Fix endianness.
s32 version = std::bit_cast<be_t<s32>>(npd->version);
s32 license = std::bit_cast<be_t<s32>>(npd->license);
s32 type = std::bit_cast<be_t<s32>>(npd->type);
std::memcpy(dev + 0x4, &version, 4);
std::memcpy(dev + 0x8, &license, 4);
std::memcpy(dev + 0xC, &type, 4);
// Check for an empty dev_hash (can't validate if devklic is NULL);
u128 klic;
std::memcpy(&klic, klicensee, sizeof(klic));
// Generate klicensee xor key.
u128 key = klic ^ std::bit_cast<u128>(NP_OMAC_KEY_2);
// Hash with generated key and compare with dev_hash.
return cmac_hash_compare(reinterpret_cast<uchar*>(&key), 0x10, dev, 0x60, npd->dev_hash, 0x10);
}
bool validate_npd_hashes(std::string_view file_name, const u8* klicensee, NPD_HEADER* npd, EDAT_HEADER* edat, bool verbose)
{
// Ignore header validation in DEBUG data.
if (edat->flags & EDAT_DEBUG_DATA_FLAG)
{
return true;
}
if (!validate_dev_klic(klicensee, npd))
{
return false;
}
if (file_name.empty())
{
return true;
}
const usz buf_len = 0x30 + file_name.size();
std::unique_ptr<u8[]> buf(new u8[buf_len]);
std::unique_ptr<u8[]> buf_lower(new u8[buf_len]);
std::unique_ptr<u8[]> buf_upper(new u8[buf_len]);
// Build the title buffer (content_id + file_name).
std::memcpy(buf.get(), npd->content_id, 0x30);
std::memcpy(buf.get() + 0x30, file_name.data(), file_name.size());
std::memcpy(buf_lower.get(), buf.get(), buf_len);
std::memcpy(buf_upper.get(), buf.get(), buf_len);
const auto buf_span = std::span(buf.get(), buf.get() + buf_len);
const auto it = std::find(buf_span.rbegin(), buf_span.rend() - 0x30, '.');
for (usz i = std::distance(it, buf_span.rend()) - 1; i < buf_len; ++i)
{
const u8 c = buf[i];
buf_upper[i] = std::toupper(c);
buf_lower[i] = std::tolower(c);
}
// Hash with NPDRM_OMAC_KEY_3 and compare with title_hash.
// Try to ignore case sensivity with file extension
const bool title_hash_result =
cmac_hash_compare(const_cast<u8*>(NP_OMAC_KEY_3), 0x10, buf.get(), buf_len, npd->title_hash, 0x10) ||
cmac_hash_compare(const_cast<u8*>(NP_OMAC_KEY_3), 0x10, buf_lower.get(), buf_len, npd->title_hash, 0x10) ||
cmac_hash_compare(const_cast<u8*>(NP_OMAC_KEY_3), 0x10, buf_upper.get(), buf_len, npd->title_hash, 0x10);
if (verbose)
{
if (title_hash_result)
edat_log.notice("NPD title hash is valid!");
else
edat_log.warning("NPD title hash is invalid!");
}
return title_hash_result;
}
void read_npd_edat_header(const fs::file* input, NPD_HEADER& NPD, EDAT_HEADER& EDAT)
{
char npd_header[0x80]{};
char edat_header[0x10]{};
usz pos = input->pos();
pos += input->read_at(pos, npd_header, sizeof(npd_header));
input->read_at(pos, edat_header, sizeof(edat_header));
std::memcpy(&NPD.magic, npd_header, 4);
NPD.version = read_from_ptr<be_t<s32>>(npd_header, 4);
NPD.license = read_from_ptr<be_t<s32>>(npd_header, 8);
NPD.type = read_from_ptr<be_t<s32>>(npd_header, 12);
std::memcpy(NPD.content_id, &npd_header[16], 0x30);
std::memcpy(NPD.digest, &npd_header[64], 0x10);
std::memcpy(NPD.title_hash, &npd_header[80], 0x10);
std::memcpy(NPD.dev_hash, &npd_header[96], 0x10);
NPD.activate_time = read_from_ptr<be_t<s64>>(npd_header, 112);
NPD.expire_time = read_from_ptr<be_t<s64>>(npd_header, 120);
EDAT.flags = read_from_ptr<be_t<s32>>(edat_header, 0);
EDAT.block_size = read_from_ptr<be_t<s32>>(edat_header, 4);
EDAT.file_size = read_from_ptr<be_t<u64>>(edat_header, 8);
}
u128 GetEdatRifKeyFromRapFile(const fs::file& rap_file)
{
u128 rapkey{};
u128 rifkey{};
rap_file.read<u128>(rapkey);
rap_to_rif(reinterpret_cast<uchar*>(&rapkey), reinterpret_cast<uchar*>(&rifkey));
return rifkey;
}
bool VerifyEDATHeaderWithKLicense(const fs::file& input, const std::string& input_file_name, const u8* custom_klic, NPD_HEADER* npd_out)
{
// Setup NPD and EDAT/SDAT structs.
NPD_HEADER NPD;
EDAT_HEADER EDAT;
// Read in the NPD and EDAT/SDAT headers.
read_npd_edat_header(&input, NPD, EDAT);
if (NPD.magic != "NPD\0"_u32)
{
edat_log.error("%s has invalid NPD header or already decrypted.", input_file_name);
return false;
}
if ((EDAT.flags & SDAT_FLAG) == SDAT_FLAG)
{
edat_log.error("SDATA file given to edat function");
return false;
}
// Perform header validation (EDAT only).
char real_file_name[CRYPTO_MAX_PATH]{};
extract_file_name(input_file_name.c_str(), real_file_name);
if (!validate_npd_hashes(real_file_name, custom_klic, &NPD, &EDAT, false))
{
edat_log.error("NPD hash validation failed!");
return false;
}
std::string_view sv{NPD.content_id, std::size(NPD.content_id)};
sv = sv.substr(0, sv.find_first_of('\0'));
if (npd_out)
{
memcpy(npd_out, &NPD, sizeof(NPD_HEADER));
}
return true;
}
// Decrypts full file
fs::file DecryptEDAT(const fs::file& input, const std::string& input_file_name, int mode, u8 *custom_klic)
{
if (!input)
{
return {};
}
// Prepare the files.
input.seek(0);
// Set DEVKLIC
u128 devklic{};
// Select the EDAT key mode.
switch (mode)
{
case 0:
break;
case 1:
memcpy(&devklic, NP_KLIC_FREE, 0x10);
break;
case 2:
memcpy(&devklic, NP_OMAC_KEY_2, 0x10);
break;
case 3:
memcpy(&devklic, NP_OMAC_KEY_3, 0x10);
break;
case 4:
memcpy(&devklic, NP_KLIC_KEY, 0x10);
break;
case 5:
memcpy(&devklic, NP_PSX_KEY, 0x10);
break;
case 6:
memcpy(&devklic, NP_PSP_KEY_1, 0x10);
break;
case 7:
memcpy(&devklic, NP_PSP_KEY_2, 0x10);
break;
case 8:
{
if (custom_klic != NULL)
memcpy(&devklic, custom_klic, 0x10);
else
{
edat_log.error("Invalid custom klic!");
return fs::file{};
}
break;
}
default:
edat_log.error("Invalid mode!");
return fs::file{};
}
// Delete the bad output file if any errors arise.
auto data = std::make_unique<EDATADecrypter>(input, devklic, input_file_name, false);
if (!data->ReadHeader())
{
return fs::file{};
}
fs::file output;
output.reset(std::move(data));
return output;
}
bool EDATADecrypter::ReadHeader()
{
edata_file.seek(0);
// Read in the NPD and EDAT/SDAT headers.
read_npd_edat_header(&edata_file, npdHeader, edatHeader);
if (npdHeader.magic != "NPD\0"_u32)
{
edat_log.error("Not an NPDRM file");
return false;
}
// Check for SDAT flag.
if ((edatHeader.flags & SDAT_FLAG) == SDAT_FLAG)
{
// Generate SDAT key.
dec_key = std::bit_cast<u128>(npdHeader.dev_hash) ^ std::bit_cast<u128>(SDAT_KEY);
}
else
{
// extract key from RIF
char real_file_name[CRYPTO_MAX_PATH]{};
extract_file_name(m_file_name.c_str(), real_file_name);
if (!validate_npd_hashes(real_file_name, reinterpret_cast<const u8*>(&dec_key), &npdHeader, &edatHeader, false))
{
edat_log.error("NPD hash validation failed!");
return true;
}
// Select EDAT key.
if (m_is_key_final)
{
// Already provided
}
// Type 3: Use supplied dec_key.
else if ((npdHeader.license & 0x3) == 0x3)
{
//
}
// Type 2: Use key from RAP file (RIF key). (also used for type 1 at the moment)
else
{
const std::string rap_path = rpcs3::utils::get_rap_file_path(npdHeader.content_id);
if (fs::file rap{rap_path}; rap && rap.size() >= sizeof(dec_key))
{
dec_key = GetEdatRifKeyFromRapFile(rap);
}
// Make sure we don't have an empty RIF key.
if (!dec_key)
{
edat_log.error("A valid RAP file is needed for this EDAT file! (license=%d)", npdHeader.license);
return true;
}
edat_log.trace("RIFKEY: %s", std::bit_cast<be_t<u128>>(dec_key));
}
}
edata_file.seek(0);
// k the ecdsa_verify function in this check_data function takes a ridiculous amount of time
// like it slows down load time by a factor of x20, at least, so its ignored for now
//if (!check_data(reinterpret_cast<u8*>(&dec_key), &edatHeader, &npdHeader, &edata_file, false))
//{
// edat_log.error("NPDRM check_data() failed!");
// return false;
//}
file_size = edatHeader.file_size;
total_blocks = ::narrow<u32>(utils::aligned_div(edatHeader.file_size, edatHeader.block_size));
// Try decrypting the first block instead
u8 data_sample[1];
if (file_size && !ReadData(0, data_sample, 1))
{
edat_log.error("NPDRM ReadData() failed!");
return false;
}
return true;
}
u64 EDATADecrypter::ReadData(u64 pos, u8* data, u64 size)
{
size = std::min<u64>(size, pos > edatHeader.file_size ? 0 : edatHeader.file_size - pos);
if (!size)
{
return 0;
}
// Now we need to offset things to account for the actual 'range' requested
const u64 startOffset = pos % edatHeader.block_size;
const u64 num_blocks = utils::aligned_div(startOffset + size, edatHeader.block_size);
// Find and decrypt block range covering pos + size
const u32 starting_block = ::narrow<u32>(pos / edatHeader.block_size);
const u32 ending_block = ::narrow<u32>(std::min<u64>(starting_block + num_blocks, total_blocks));
u64 writeOffset = 0;
std::vector<u8> data_buf(edatHeader.block_size + 16);
for (u32 i = starting_block; i < ending_block; i++)
{
u64 res = decrypt_block(&edata_file, data_buf.data(), &edatHeader, &npdHeader, reinterpret_cast<uchar*>(&dec_key), i, total_blocks, edatHeader.file_size, true);
if (res == umax)
{
edat_log.error("Error Decrypting data");
return 0;
}
const usz skip_start = (i == starting_block ? startOffset : 0);
if (skip_start >= res)
{
break;
}
const usz end_pos = (i != total_blocks - 1 ? edatHeader.block_size : (edatHeader.file_size - 1) % edatHeader.block_size + 1);
const usz read_end = std::min<usz>(res, i == ending_block - 1 ? std::min<usz>(end_pos, (startOffset + size - 1) % edatHeader.block_size + 1) : end_pos);
std::memcpy(data + writeOffset, data_buf.data() + skip_start, read_end - skip_start);
std::memset(data_buf.data(), 0, read_end - skip_start);
writeOffset += read_end - skip_start;
}
return writeOffset;
}
| 26,631
|
C++
|
.cpp
| 770
| 31.9
| 194
| 0.681127
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,027
|
decrypt_binaries.cpp
|
RPCS3_rpcs3/rpcs3/Crypto/decrypt_binaries.cpp
|
#include "stdafx.h"
#include "decrypt_binaries.h"
#include "unedat.h"
#include "unself.h"
#include "Emu/IdManager.h"
#include "Emu/System.h"
#include "Utilities/StrUtil.h"
#include <charconv>
#include <iostream>
LOG_CHANNEL(dec_log, "DECRYPT");
usz decrypt_binaries_t::decrypt(std::string_view klic_input)
{
if (m_index >= m_modules.size())
{
std::cout << "No paths specified" << std::endl; // For CLI
m_index = umax;
return umax;
}
if (m_klics.empty())
{
dec_log.notice("Decrypting binaries...");
std::cout << "Decrypting binaries..." << std::endl; // For CLI
// Always start with no KLIC
m_klics.emplace_back(u128{});
if (const auto keys = g_fxo->try_get<loaded_npdrm_keys>())
{
// Second klic: get it from a running game
if (const u128 klic = keys->last_key())
{
m_klics.emplace_back(klic);
}
}
// Try to use the key that has been for the current running ELF
m_klics.insert(m_klics.end(), Emu.klic.begin(), Emu.klic.end());
}
if (std::string_view text = klic_input.substr(klic_input.find_first_of('x') + 1); text.size() == 32)
{
// Allowed to fail (would simply repeat the operation if fails again)
u64 lo = 0;
u64 hi = 0;
bool success = false;
if (auto res = std::from_chars(text.data() + 0, text.data() + 16, lo, 16); res.ec == std::errc() && res.ptr == text.data() + 16)
{
if (res = std::from_chars(text.data() + 16, text.data() + 32, hi, 16); res.ec == std::errc() && res.ptr == text.data() + 32)
{
success = true;
}
}
if (success)
{
lo = std::bit_cast<be_t<u64>>(lo);
hi = std::bit_cast<be_t<u64>>(hi);
if (u128 input_key = ((u128{hi} << 64) | lo))
{
m_klics.emplace_back(input_key);
}
}
}
while (m_index < m_modules.size())
{
const std::string& _module = m_modules[m_index];
const std::string old_path = _module;
fs::file elf_file;
fs::file internal_file;
bool invalid = false;
usz key_it = 0;
u32 file_magic{};
while (true)
{
for (; key_it < m_klics.size(); key_it++)
{
internal_file.close();
if (!elf_file.open(old_path) || !elf_file.read(file_magic))
{
file_magic = 0;
}
switch (file_magic)
{
case "SCE\0"_u32:
{
// First KLIC is no KLIC
elf_file = decrypt_self(std::move(elf_file), key_it != 0 ? reinterpret_cast<u8*>(&m_klics[key_it]) : nullptr);
if (!elf_file)
{
// Try another key
continue;
}
break;
}
case "NPD\0"_u32:
{
// EDAT / SDAT
internal_file = std::move(elf_file);
elf_file = DecryptEDAT(internal_file, old_path, key_it != 0 ? 8 : 1, reinterpret_cast<u8*>(&m_klics[key_it]));
if (!elf_file)
{
// Try another key
continue;
}
break;
}
default:
{
invalid = true;
break;
}
}
if (invalid)
{
elf_file.close();
}
break;
}
if (elf_file)
{
const std::string exec_ext = fmt::to_lower(_module).ends_with(".sprx") ? ".prx" : ".elf";
const std::string new_path = file_magic == "NPD\0"_u32 ? old_path + ".unedat" :
old_path.substr(0, old_path.find_last_of('.')) + exec_ext;
if (fs::file new_file{new_path, fs::rewrite})
{
// 16MB buffer
std::vector<u8> buffer(std::min<usz>(elf_file.size(), 1u << 24));
elf_file.seek(0);
while (usz read_size = elf_file.read(buffer.data(), buffer.size()))
{
new_file.write(buffer.data(), read_size);
}
dec_log.success("Decrypted %s -> %s", old_path, new_path);
std::cout << "Decrypted " << old_path << " -> " << new_path << std::endl; // For CLI
m_index++;
}
else
{
dec_log.error("Failed to create %s", new_path);
std::cout << "Failed to create " << new_path << std::endl; // For CLI
m_index = umax;
}
break;
}
if (!invalid)
{
// Allow the user to manually type KLIC if decryption failed
return m_index;
}
dec_log.error("Failed to decrypt \"%s\".", old_path);
std::cout << "Failed to decrypt \"" << old_path << "\"." << std::endl; // For CLI
return m_index;
}
}
dec_log.notice("Finished decrypting all binaries.");
std::cout << "Finished decrypting all binaries." << std::endl; // For CLI
return m_index;
}
| 4,250
|
C++
|
.cpp
| 153
| 23.51634
| 130
| 0.59016
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,028
|
unself.cpp
|
RPCS3_rpcs3/rpcs3/Crypto/unself.cpp
|
#include "stdafx.h"
#include "aes.h"
#include "utils.h"
#include "unself.h"
#include "Emu/VFS.h"
#include "Emu/System.h"
#include "Emu/system_utils.hpp"
#include "Crypto/unzip.h"
#include <algorithm>
inline u8 Read8(const fs::file& f)
{
u8 ret;
f.read(&ret, sizeof(ret));
return ret;
}
inline u16 Read16(const fs::file& f)
{
be_t<u16> ret;
f.read(&ret, sizeof(ret));
return ret;
}
inline u32 Read32(const fs::file& f)
{
be_t<u32> ret;
f.read(&ret, sizeof(ret));
return ret;
}
inline u64 Read64(const fs::file& f)
{
be_t<u64> ret;
f.read(&ret, sizeof(ret));
return ret;
}
inline u16 Read16LE(const fs::file& f)
{
u16 ret;
f.read(&ret, sizeof(ret));
return ret;
}
inline u32 Read32LE(const fs::file& f)
{
u32 ret;
f.read(&ret, sizeof(ret));
return ret;
}
inline u64 Read64LE(const fs::file& f)
{
u64 ret;
f.read(&ret, sizeof(ret));
return ret;
}
inline void Write8(const fs::file& f, const u8 data)
{
f.write(&data, sizeof(data));
}
inline void Write16LE(const fs::file& f, const u16 data)
{
f.write(&data, sizeof(data));
}
inline void Write32LE(const fs::file& f, const u32 data)
{
f.write(&data, sizeof(data));
}
inline void Write64LE(const fs::file& f, const u64 data)
{
f.write(&data, sizeof(data));
}
inline void Write16(const fs::file& f, const be_t<u16> data)
{
f.write(&data, sizeof(data));
}
inline void Write32(const fs::file& f, const be_t<u32> data)
{
f.write(&data, sizeof(data));
}
inline void Write64(const fs::file& f, const be_t<u64> data)
{
f.write(&data, sizeof(data));
}
void WriteEhdr(const fs::file& f, Elf64_Ehdr& ehdr)
{
Write32(f, ehdr.e_magic);
Write8(f, ehdr.e_class);
Write8(f, ehdr.e_data);
Write8(f, ehdr.e_curver);
Write8(f, ehdr.e_os_abi);
Write64(f, ehdr.e_abi_ver);
Write16(f, ehdr.e_type);
Write16(f, ehdr.e_machine);
Write32(f, ehdr.e_version);
Write64(f, ehdr.e_entry);
Write64(f, ehdr.e_phoff);
Write64(f, ehdr.e_shoff);
Write32(f, ehdr.e_flags);
Write16(f, ehdr.e_ehsize);
Write16(f, ehdr.e_phentsize);
Write16(f, ehdr.e_phnum);
Write16(f, ehdr.e_shentsize);
Write16(f, ehdr.e_shnum);
Write16(f, ehdr.e_shstrndx);
}
void WritePhdr(const fs::file& f, Elf64_Phdr& phdr)
{
Write32(f, phdr.p_type);
Write32(f, phdr.p_flags);
Write64(f, phdr.p_offset);
Write64(f, phdr.p_vaddr);
Write64(f, phdr.p_paddr);
Write64(f, phdr.p_filesz);
Write64(f, phdr.p_memsz);
Write64(f, phdr.p_align);
}
void WriteShdr(const fs::file& f, Elf64_Shdr& shdr)
{
Write32(f, shdr.sh_name);
Write32(f, shdr.sh_type);
Write64(f, shdr.sh_flags);
Write64(f, shdr.sh_addr);
Write64(f, shdr.sh_offset);
Write64(f, shdr.sh_size);
Write32(f, shdr.sh_link);
Write32(f, shdr.sh_info);
Write64(f, shdr.sh_addralign);
Write64(f, shdr.sh_entsize);
}
void WriteEhdr(const fs::file& f, Elf32_Ehdr& ehdr)
{
Write32(f, ehdr.e_magic);
Write8(f, ehdr.e_class);
Write8(f, ehdr.e_data);
Write8(f, ehdr.e_curver);
Write8(f, ehdr.e_os_abi);
Write64(f, ehdr.e_abi_ver);
Write16(f, ehdr.e_type);
Write16(f, ehdr.e_machine);
Write32(f, ehdr.e_version);
Write32(f, ehdr.e_entry);
Write32(f, ehdr.e_phoff);
Write32(f, ehdr.e_shoff);
Write32(f, ehdr.e_flags);
Write16(f, ehdr.e_ehsize);
Write16(f, ehdr.e_phentsize);
Write16(f, ehdr.e_phnum);
Write16(f, ehdr.e_shentsize);
Write16(f, ehdr.e_shnum);
Write16(f, ehdr.e_shstrndx);
}
void WritePhdr(const fs::file& f, Elf32_Phdr& phdr)
{
Write32(f, phdr.p_type);
Write32(f, phdr.p_offset);
Write32(f, phdr.p_vaddr);
Write32(f, phdr.p_paddr);
Write32(f, phdr.p_filesz);
Write32(f, phdr.p_memsz);
Write32(f, phdr.p_flags);
Write32(f, phdr.p_align);
}
void WriteShdr(const fs::file& f, Elf32_Shdr& shdr)
{
Write32(f, shdr.sh_name);
Write32(f, shdr.sh_type);
Write32(f, shdr.sh_flags);
Write32(f, shdr.sh_addr);
Write32(f, shdr.sh_offset);
Write32(f, shdr.sh_size);
Write32(f, shdr.sh_link);
Write32(f, shdr.sh_info);
Write32(f, shdr.sh_addralign);
Write32(f, shdr.sh_entsize);
}
void program_identification_header::Load(const fs::file& f)
{
program_authority_id = Read64(f);
program_vendor_id = Read32(f);
program_type = Read32(f);
program_sceversion = Read64(f);
padding = Read64(f);
}
void program_identification_header::Show() const
{
self_log.notice("AuthID: 0x%llx", program_authority_id);
self_log.notice("VendorID: 0x%08x", program_vendor_id);
self_log.notice("SELF type: 0x%08x", program_type);
self_log.notice("Version: 0x%llx", program_sceversion);
}
void segment_ext_header::Load(const fs::file& f)
{
offset = Read64(f);
size = Read64(f);
compression = Read32(f);
unknown = Read32(f);
encryption = Read64(f);
}
void segment_ext_header::Show() const
{
self_log.notice("Offset: 0x%llx", offset);
self_log.notice("Size: 0x%llx", size);
self_log.notice("Compression: 0x%08x", compression);
self_log.notice("Unknown: 0x%08x", unknown);
self_log.notice("Encryption: 0x%08x", encryption);
}
void version_header::Load(const fs::file& f)
{
subheader_type = Read32(f);
present = Read32(f);
size = Read32(f);
unknown4 = Read32(f);
}
void version_header::Show() const
{
self_log.notice("Sub-header type: 0x%08x", subheader_type);
self_log.notice("Present: 0x%08x", present);
self_log.notice("Size: 0x%08x", size);
self_log.notice("Unknown: 0x%08x", unknown4);
}
void supplemental_header::Load(const fs::file& f)
{
type = Read32(f);
size = Read32(f);
next = Read64(f);
if (type == 1)
{
PS3_plaintext_capability_header.ctrl_flag1 = Read32(f);
PS3_plaintext_capability_header.unknown1 = Read32(f);
PS3_plaintext_capability_header.unknown2 = Read32(f);
PS3_plaintext_capability_header.unknown3 = Read32(f);
PS3_plaintext_capability_header.unknown4 = Read32(f);
PS3_plaintext_capability_header.unknown5 = Read32(f);
PS3_plaintext_capability_header.unknown6 = Read32(f);
PS3_plaintext_capability_header.unknown7 = Read32(f);
}
else if (type == 2)
{
if (size == 0x30)
{
f.read(PS3_elf_digest_header_30.constant_or_elf_digest, sizeof(PS3_elf_digest_header_30.constant_or_elf_digest));
f.read(PS3_elf_digest_header_30.padding, sizeof(PS3_elf_digest_header_30.padding));
}
else if (size == 0x40)
{
f.read(PS3_elf_digest_header_40.constant, sizeof(PS3_elf_digest_header_40.constant));
f.read(PS3_elf_digest_header_40.elf_digest, sizeof(PS3_elf_digest_header_40.elf_digest));
PS3_elf_digest_header_40.required_system_version = Read64(f);
}
}
else if (type == 3)
{
PS3_npdrm_header.npd.magic = Read32(f);
PS3_npdrm_header.npd.version = Read32(f);
PS3_npdrm_header.npd.license = Read32(f);
PS3_npdrm_header.npd.type = Read32(f);
f.read(PS3_npdrm_header.npd.content_id, 48);
f.read(PS3_npdrm_header.npd.digest, 16);
f.read(PS3_npdrm_header.npd.title_hash, 16);
f.read(PS3_npdrm_header.npd.dev_hash, 16);
PS3_npdrm_header.npd.activate_time = Read64(f);
PS3_npdrm_header.npd.expire_time = Read64(f);
}
}
void supplemental_header::Show() const
{
self_log.notice("Type: 0x%08x", type);
self_log.notice("Size: 0x%08x", size);
self_log.notice("Next: 0x%llx", next);
if (type == 1)
{
self_log.notice("Control flag 1: 0x%08x", PS3_plaintext_capability_header.ctrl_flag1);
self_log.notice("Unknown1: 0x%08x", PS3_plaintext_capability_header.unknown1);
self_log.notice("Unknown2: 0x%08x", PS3_plaintext_capability_header.unknown2);
self_log.notice("Unknown3: 0x%08x", PS3_plaintext_capability_header.unknown3);
self_log.notice("Unknown4: 0x%08x", PS3_plaintext_capability_header.unknown4);
self_log.notice("Unknown5: 0x%08x", PS3_plaintext_capability_header.unknown5);
self_log.notice("Unknown6: 0x%08x", PS3_plaintext_capability_header.unknown6);
self_log.notice("Unknown7: 0x%08x", PS3_plaintext_capability_header.unknown7);
}
else if (type == 2)
{
if (size == 0x30)
{
self_log.notice("Digest: %s", PS3_elf_digest_header_30.constant_or_elf_digest);
self_log.notice("Unknown: 0x%llx", PS3_elf_digest_header_30.padding);
}
else if (size == 0x40)
{
self_log.notice("Digest1: %s", PS3_elf_digest_header_40.constant);
self_log.notice("Digest2: %s", PS3_elf_digest_header_40.elf_digest);
self_log.notice("Unknown: 0x%llx", PS3_elf_digest_header_40.required_system_version);
}
}
else if (type == 3)
{
self_log.notice("Magic: 0x%08x", PS3_npdrm_header.npd.magic);
self_log.notice("Version: 0x%08x", PS3_npdrm_header.npd.version);
self_log.notice("License: 0x%08x", PS3_npdrm_header.npd.license);
self_log.notice("Type: 0x%08x", PS3_npdrm_header.npd.type);
self_log.notice("ContentID: %s", PS3_npdrm_header.npd.content_id);
self_log.notice("Digest: %s", PS3_npdrm_header.npd.digest);
self_log.notice("Inverse digest: %s", PS3_npdrm_header.npd.title_hash);
self_log.notice("XOR digest: %s", PS3_npdrm_header.npd.dev_hash);
self_log.notice("Activation time: 0x%llx", PS3_npdrm_header.npd.activate_time);
self_log.notice("Expiration time: 0x%llx", PS3_npdrm_header.npd.expire_time);
}
}
void MetadataInfo::Load(u8* in)
{
memcpy(key, in, 0x10);
memcpy(key_pad, in + 0x10, 0x10);
memcpy(iv, in + 0x20, 0x10);
memcpy(iv_pad, in + 0x30, 0x10);
}
void MetadataInfo::Show() const
{
std::string key_str;
std::string key_pad_str;
std::string iv_str;
std::string iv_pad_str;
for (int i = 0; i < 0x10; i++)
{
fmt::append(key_str, "%02x", key[i]);
fmt::append(key_pad_str, "%02x", key_pad[i]);
fmt::append(iv_str, "%02x", iv[i]);
fmt::append(iv_pad_str, "%02x", iv_pad[i]);
}
self_log.notice("Key: %s", key_str.c_str());
self_log.notice("Key pad: %s", key_pad_str.c_str());
self_log.notice("IV: %s", iv_str.c_str());
self_log.notice("IV pad: %s", iv_pad_str.c_str());
}
void MetadataHeader::Load(u8* in)
{
// Endian swap.
signature_input_length = read_from_ptr<be_t<u64>>(in);
unknown1 = read_from_ptr<be_t<u32>>(in, 8);
section_count = read_from_ptr<be_t<u32>>(in, 12);
key_count = read_from_ptr<be_t<u32>>(in, 16);
opt_header_size = read_from_ptr<be_t<u32>>(in, 20);
unknown2 = read_from_ptr<be_t<u32>>(in, 24);
unknown3 = read_from_ptr<be_t<u32>>(in, 28);
}
void MetadataHeader::Show() const
{
self_log.notice("Signature input length: 0x%llx", signature_input_length);
self_log.notice("Unknown1: 0x%08x", unknown1);
self_log.notice("Section count: 0x%08x", section_count);
self_log.notice("Key count: 0x%08x", key_count);
self_log.notice("Optional header size: 0x%08x", opt_header_size);
self_log.notice("Unknown2: 0x%08x", unknown2);
self_log.notice("Unknown3: 0x%08x", unknown3);
}
void MetadataSectionHeader::Load(u8* in)
{
// Endian swap.
data_offset = read_from_ptr<be_t<u64>>(in);
data_size = read_from_ptr<be_t<u64>>(in, 8);
type = read_from_ptr<be_t<u32>>(in, 16);
program_idx = read_from_ptr<be_t<u32>>(in, 20);
hashed = read_from_ptr<be_t<u32>>(in, 24);
sha1_idx = read_from_ptr<be_t<u32>>(in, 28);
encrypted = read_from_ptr<be_t<u32>>(in, 32);
key_idx = read_from_ptr<be_t<u32>>(in, 36);
iv_idx = read_from_ptr<be_t<u32>>(in, 40);
compressed = read_from_ptr<be_t<u32>>(in, 44);
}
void MetadataSectionHeader::Show() const
{
self_log.notice("Data offset: 0x%llx", data_offset);
self_log.notice("Data size: 0x%llx", data_size);
self_log.notice("Type: 0x%08x", type);
self_log.notice("Program index: 0x%08x", program_idx);
self_log.notice("Hashed: 0x%08x", hashed);
self_log.notice("SHA1 index: 0x%08x", sha1_idx);
self_log.notice("Encrypted: 0x%08x", encrypted);
self_log.notice("Key index: 0x%08x", key_idx);
self_log.notice("IV index: 0x%08x", iv_idx);
self_log.notice("Compressed: 0x%08x", compressed);
}
void SectionHash::Load(const fs::file& f)
{
f.read(sha1, 20);
f.read(padding, 12);
f.read(hmac_key, 64);
}
void CapabilitiesInfo::Load(const fs::file& f)
{
type = Read32(f);
capabilities_size = Read32(f);
next = Read32(f);
unknown1 = Read32(f);
unknown2 = Read64(f);
unknown3 = Read64(f);
flags = Read64(f);
unknown4 = Read32(f);
unknown5 = Read32(f);
}
void Signature::Load(const fs::file& f)
{
f.read(r, 21);
f.read(s, 21);
f.read(padding, 6);
}
void SelfSection::Load(const fs::file& f)
{
*data = Read32(f);
size = Read64(f);
offset = Read64(f);
}
void Elf32_Ehdr::Load(const fs::file& f)
{
e_magic = Read32(f);
e_class = Read8(f);
e_data = Read8(f);
e_curver = Read8(f);
e_os_abi = Read8(f);
if (IsLittleEndian())
{
e_abi_ver = Read64LE(f);
e_type = Read16LE(f);
e_machine = Read16LE(f);
e_version = Read32LE(f);
e_entry = Read32LE(f);
e_phoff = Read32LE(f);
e_shoff = Read32LE(f);
e_flags = Read32LE(f);
e_ehsize = Read16LE(f);
e_phentsize = Read16LE(f);
e_phnum = Read16LE(f);
e_shentsize = Read16LE(f);
e_shnum = Read16LE(f);
e_shstrndx = Read16LE(f);
}
else
{
e_abi_ver = Read64(f);
e_type = Read16(f);
e_machine = Read16(f);
e_version = Read32(f);
e_entry = Read32(f);
e_phoff = Read32(f);
e_shoff = Read32(f);
e_flags = Read32(f);
e_ehsize = Read16(f);
e_phentsize = Read16(f);
e_phnum = Read16(f);
e_shentsize = Read16(f);
e_shnum = Read16(f);
e_shstrndx = Read16(f);
}
}
void Elf32_Shdr::Load(const fs::file& f)
{
sh_name = Read32(f);
sh_type = Read32(f);
sh_flags = Read32(f);
sh_addr = Read32(f);
sh_offset = Read32(f);
sh_size = Read32(f);
sh_link = Read32(f);
sh_info = Read32(f);
sh_addralign = Read32(f);
sh_entsize = Read32(f);
}
void Elf32_Shdr::LoadLE(const fs::file& f)
{
f.read(this, sizeof(*this));
}
void Elf32_Phdr::Load(const fs::file& f)
{
p_type = Read32(f);
p_offset = Read32(f);
p_vaddr = Read32(f);
p_paddr = Read32(f);
p_filesz = Read32(f);
p_memsz = Read32(f);
p_flags = Read32(f);
p_align = Read32(f);
}
void Elf32_Phdr::LoadLE(const fs::file& f)
{
f.read(this, sizeof(*this));
}
void Elf64_Ehdr::Load(const fs::file& f)
{
e_magic = Read32(f);
e_class = Read8(f);
e_data = Read8(f);
e_curver = Read8(f);
e_os_abi = Read8(f);
e_abi_ver = Read64(f);
e_type = Read16(f);
e_machine = Read16(f);
e_version = Read32(f);
e_entry = Read64(f);
e_phoff = Read64(f);
e_shoff = Read64(f);
e_flags = Read32(f);
e_ehsize = Read16(f);
e_phentsize = Read16(f);
e_phnum = Read16(f);
e_shentsize = Read16(f);
e_shnum = Read16(f);
e_shstrndx = Read16(f);
}
void Elf64_Shdr::Load(const fs::file& f)
{
sh_name = Read32(f);
sh_type = Read32(f);
sh_flags = Read64(f);
sh_addr = Read64(f);
sh_offset = Read64(f);
sh_size = Read64(f);
sh_link = Read32(f);
sh_info = Read32(f);
sh_addralign = Read64(f);
sh_entsize = Read64(f);
}
void Elf64_Phdr::Load(const fs::file& f)
{
p_type = Read32(f);
p_flags = Read32(f);
p_offset = Read64(f);
p_vaddr = Read64(f);
p_paddr = Read64(f);
p_filesz = Read64(f);
p_memsz = Read64(f);
p_align = Read64(f);
}
void SceHeader::Load(const fs::file& f)
{
se_magic = Read32(f);
se_hver = Read32(f);
se_flags = Read16(f);
se_type = Read16(f);
se_meta = Read32(f);
se_hsize = Read64(f);
se_esize = Read64(f);
}
void ext_hdr::Load(const fs::file& f)
{
ext_hdr_version = Read64(f);
program_identification_hdr_offset = Read64(f);
ehdr_offset = Read64(f);
phdr_offset = Read64(f);
shdr_offset = Read64(f);
segment_ext_hdr_offset = Read64(f);
version_hdr_offset = Read64(f);
supplemental_hdr_offset = Read64(f);
supplemental_hdr_size = Read64(f);
padding = Read64(f);
}
SCEDecrypter::SCEDecrypter(const fs::file& s)
: sce_f(s)
, data_buf_length(0)
{
}
bool SCEDecrypter::LoadHeaders()
{
// Read SCE header.
sce_f.seek(0);
sce_hdr.Load(sce_f);
// Check SCE magic.
if (!sce_hdr.CheckMagic())
{
self_log.error("Not a SELF file!");
return false;
}
return true;
}
bool SCEDecrypter::LoadMetadata(const u8 erk[32], const u8 riv[16])
{
aes_context aes;
const auto metadata_info = std::make_unique<u8[]>(sizeof(meta_info));
const auto metadata_headers_size = sce_hdr.se_hsize - (sizeof(sce_hdr) + sce_hdr.se_meta + sizeof(meta_info));
const auto metadata_headers = std::make_unique<u8[]>(metadata_headers_size);
// Locate and read the encrypted metadata info.
sce_f.seek(sce_hdr.se_meta + sizeof(sce_hdr));
sce_f.read(metadata_info.get(), sizeof(meta_info));
// Locate and read the encrypted metadata header and section header.
sce_f.seek(sce_hdr.se_meta + sizeof(sce_hdr) + sizeof(meta_info));
sce_f.read(metadata_headers.get(), metadata_headers_size);
// Copy the necessary parameters.
u8 metadata_key[0x20];
u8 metadata_iv[0x10];
memcpy(metadata_key, erk, 0x20);
memcpy(metadata_iv, riv, 0x10);
// Check DEBUG flag.
if ((sce_hdr.se_flags & 0x8000) != 0x8000)
{
// Decrypt the metadata info.
aes_setkey_dec(&aes, metadata_key, 256); // AES-256
aes_crypt_cbc(&aes, AES_DECRYPT, sizeof(meta_info), metadata_iv, metadata_info.get(), metadata_info.get());
}
// Load the metadata info.
meta_info.Load(metadata_info.get());
// If the padding is not NULL for the key or iv fields, the metadata info
// is not properly decrypted.
if ((meta_info.key_pad[0] != 0x00) ||
(meta_info.iv_pad[0] != 0x00))
{
self_log.error("Failed to decrypt SCE metadata info!");
return false;
}
// Perform AES-CTR encryption on the metadata headers.
usz ctr_nc_off = 0;
u8 ctr_stream_block[0x10];
aes_setkey_enc(&aes, meta_info.key, 128);
aes_crypt_ctr(&aes, metadata_headers_size, &ctr_nc_off, meta_info.iv, ctr_stream_block, metadata_headers.get(), metadata_headers.get());
// Load the metadata header.
meta_hdr.Load(metadata_headers.get());
// Load the metadata section headers.
meta_shdr.clear();
for (unsigned int i = 0; i < meta_hdr.section_count; i++)
{
meta_shdr.emplace_back();
meta_shdr.back().Load(metadata_headers.get() + sizeof(meta_hdr) + sizeof(MetadataSectionHeader) * i);
}
// Copy the decrypted data keys.
data_keys_length = meta_hdr.key_count * 0x10;
data_keys = std::make_unique<u8[]>(data_keys_length);
memcpy(data_keys.get(), metadata_headers.get() + sizeof(meta_hdr) + meta_hdr.section_count * sizeof(MetadataSectionHeader), data_keys_length);
return true;
}
bool SCEDecrypter::DecryptData()
{
aes_context aes;
// Calculate the total data size.
for (unsigned int i = 0; i < meta_hdr.section_count; i++)
{
data_buf_length += ::narrow<u32>(meta_shdr[i].data_size);
}
// Allocate a buffer to store decrypted data.
data_buf = std::make_unique<u8[]>(data_buf_length);
// Set initial offset.
u32 data_buf_offset = 0;
// Parse the metadata section headers to find the offsets of encrypted data.
for (unsigned int i = 0; i < meta_hdr.section_count; i++)
{
usz ctr_nc_off = 0;
u8 ctr_stream_block[0x10];
u8 data_key[0x10];
u8 data_iv[0x10];
// Check if this is an encrypted section.
if (meta_shdr[i].encrypted == 3)
{
// Make sure the key and iv are not out of boundaries.
if ((meta_shdr[i].key_idx <= meta_hdr.key_count - 1) && (meta_shdr[i].iv_idx <= meta_hdr.key_count))
{
// Get the key and iv from the previously stored key buffer.
memcpy(data_key, data_keys.get() + meta_shdr[i].key_idx * 0x10, 0x10);
memcpy(data_iv, data_keys.get() + meta_shdr[i].iv_idx * 0x10, 0x10);
// Allocate a buffer to hold the data.
auto buf = std::make_unique<u8[]>(meta_shdr[i].data_size);
// Seek to the section data offset and read the encrypted data.
sce_f.seek(meta_shdr[i].data_offset);
sce_f.read(buf.get(), meta_shdr[i].data_size);
// Zero out our ctr nonce.
memset(ctr_stream_block, 0, sizeof(ctr_stream_block));
// Perform AES-CTR encryption on the data blocks.
aes_setkey_enc(&aes, data_key, 128);
aes_crypt_ctr(&aes, meta_shdr[i].data_size, &ctr_nc_off, data_iv, ctr_stream_block, buf.get(), buf.get());
// Copy the decrypted data.
memcpy(data_buf.get() + data_buf_offset, buf.get(), meta_shdr[i].data_size);
}
}
else
{
auto buf = std::make_unique<u8[]>(meta_shdr[i].data_size);
sce_f.seek(meta_shdr[i].data_offset);
sce_f.read(buf.get(), meta_shdr[i].data_size);
memcpy(data_buf.get() + data_buf_offset, buf.get(), meta_shdr[i].data_size);
}
// Advance the buffer's offset.
data_buf_offset += ::narrow<u32>(meta_shdr[i].data_size);
}
return true;
}
// Each section gets put into its own file.
std::vector<fs::file> SCEDecrypter::MakeFile()
{
std::vector<fs::file> vec;
// Set initial offset.
u32 data_buf_offset = 0;
// Write data.
for (u32 i = 0; i < meta_hdr.section_count; i++)
{
const MetadataSectionHeader& hdr = meta_shdr[i];
const u8* src = data_buf.get() + data_buf_offset;
fs::file out_f = fs::make_stream<std::vector<u8>>();
bool is_valid = true;
// Decompress if necessary.
if (hdr.compressed == 2)
{
is_valid = unzip(src, hdr.data_size, out_f);
}
else
{
// Write the data.
out_f.write(src, hdr.data_size);
}
// Advance the data buffer offset by data size.
data_buf_offset += ::narrow<u32>(hdr.data_size);
if (out_f.pos() != out_f.size())
fmt::throw_exception("MakeELF written bytes (%llu) does not equal buffer size (%llu).", out_f.pos(), out_f.size());
if (is_valid) vec.push_back(std::move(out_f));
}
return vec;
}
SELFDecrypter::SELFDecrypter(const fs::file& s)
: self_f(s)
, key_v()
{
}
bool SELFDecrypter::LoadHeaders(bool isElf32, SelfAdditionalInfo* out_info)
{
// Read SCE header.
self_f.seek(0);
sce_hdr.Load(self_f);
if (out_info)
{
*out_info = {};
}
// Check SCE magic.
if (!sce_hdr.CheckMagic())
{
self_log.error("Not a SELF file!");
return false;
}
// Read SELF header.
m_ext_hdr.Load(self_f);
// Read the APP INFO.
self_f.seek(m_ext_hdr.program_identification_hdr_offset);
m_prog_id_hdr.Load(self_f);
if (out_info)
{
out_info->prog_id_hdr = m_prog_id_hdr;
}
// Read ELF header.
self_f.seek(m_ext_hdr.ehdr_offset);
if (isElf32)
elf32_hdr.Load(self_f);
else
elf64_hdr.Load(self_f);
// Read ELF program headers.
if (isElf32)
{
phdr32_arr.clear();
if(elf32_hdr.e_phoff == 0 && elf32_hdr.e_phnum)
{
self_log.error("ELF program header offset is null!");
return false;
}
self_f.seek(m_ext_hdr.phdr_offset);
for(u32 i = 0; i < elf32_hdr.e_phnum; ++i)
{
phdr32_arr.emplace_back();
phdr32_arr.back().Load(self_f);
}
}
else
{
phdr64_arr.clear();
if (elf64_hdr.e_phoff == 0 && elf64_hdr.e_phnum)
{
self_log.error("ELF program header offset is null!");
return false;
}
self_f.seek(m_ext_hdr.phdr_offset);
for (u32 i = 0; i < elf64_hdr.e_phnum; ++i)
{
phdr64_arr.emplace_back();
phdr64_arr.back().Load(self_f);
}
}
// Read section info.
m_seg_ext_hdr.clear();
self_f.seek(m_ext_hdr.segment_ext_hdr_offset);
for(u32 i = 0; i < (isElf32 ? elf32_hdr.e_phnum : elf64_hdr.e_phnum); ++i)
{
if (self_f.pos() >= self_f.size())
{
return false;
}
m_seg_ext_hdr.emplace_back();
m_seg_ext_hdr.back().Load(self_f);
}
if (m_ext_hdr.version_hdr_offset == 0 || utils::add_saturate<u64>(m_ext_hdr.version_hdr_offset, sizeof(version_header)) > self_f.size())
{
return false;
}
// Read SCE version info.
self_f.seek(m_ext_hdr.version_hdr_offset);
m_version_hdr.Load(self_f);
// Read control info.
m_supplemental_hdr_arr.clear();
self_f.seek(m_ext_hdr.supplemental_hdr_offset);
for (u64 i = 0; i < m_ext_hdr.supplemental_hdr_size;)
{
if (self_f.pos() >= self_f.size())
{
return false;
}
m_supplemental_hdr_arr.emplace_back();
supplemental_header& cinfo = m_supplemental_hdr_arr.back();
cinfo.Load(self_f);
i += cinfo.size;
}
if (out_info)
{
out_info->supplemental_hdr = m_supplemental_hdr_arr;
}
// Read ELF section headers.
if (isElf32)
{
shdr32_arr.clear();
if (elf32_hdr.e_shoff == 0 && elf32_hdr.e_shnum)
{
self_log.warning("ELF section header offset is null!");
return true;
}
self_f.seek(m_ext_hdr.shdr_offset);
for(u32 i = 0; i < elf32_hdr.e_shnum; ++i)
{
shdr32_arr.emplace_back();
shdr32_arr.back().Load(self_f);
}
}
else
{
shdr64_arr.clear();
if (elf64_hdr.e_shoff == 0 && elf64_hdr.e_shnum)
{
self_log.warning("ELF section header offset is null!");
return true;
}
self_f.seek(m_ext_hdr.shdr_offset);
for(u32 i = 0; i < elf64_hdr.e_shnum; ++i)
{
shdr64_arr.emplace_back();
shdr64_arr.back().Load(self_f);
}
}
if (out_info)
{
out_info->valid = true;
}
return true;
}
void SELFDecrypter::ShowHeaders(bool isElf32)
{
self_log.notice("SCE header");
self_log.notice("----------------------------------------------------");
sce_hdr.Show();
self_log.notice("----------------------------------------------------");
self_log.notice("SELF header");
self_log.notice("----------------------------------------------------");
m_ext_hdr.Show();
self_log.notice("----------------------------------------------------");
self_log.notice("APP INFO");
self_log.notice("----------------------------------------------------");
m_prog_id_hdr.Show();
self_log.notice("----------------------------------------------------");
self_log.notice("ELF header");
self_log.notice("----------------------------------------------------");
isElf32 ? elf32_hdr.Show() : elf64_hdr.Show();
self_log.notice("----------------------------------------------------");
self_log.notice("ELF program headers");
self_log.notice("----------------------------------------------------");
for(unsigned int i = 0; i < ((isElf32) ? phdr32_arr.size() : phdr64_arr.size()); i++)
isElf32 ? phdr32_arr[i].Show() : phdr64_arr[i].Show();
self_log.notice("----------------------------------------------------");
self_log.notice("Section info");
self_log.notice("----------------------------------------------------");
for(unsigned int i = 0; i < m_seg_ext_hdr.size(); i++)
m_seg_ext_hdr[i].Show();
self_log.notice("----------------------------------------------------");
self_log.notice("SCE version info");
self_log.notice("----------------------------------------------------");
m_version_hdr.Show();
self_log.notice("----------------------------------------------------");
self_log.notice("Control info");
self_log.notice("----------------------------------------------------");
for(unsigned int i = 0; i < m_supplemental_hdr_arr.size(); i++)
m_supplemental_hdr_arr[i].Show();
self_log.notice("----------------------------------------------------");
self_log.notice("ELF section headers");
self_log.notice("----------------------------------------------------");
for(unsigned int i = 0; i < ((isElf32) ? shdr32_arr.size() : shdr64_arr.size()); i++)
isElf32 ? shdr32_arr[i].Show() : shdr64_arr[i].Show();
self_log.notice("----------------------------------------------------");
}
bool SELFDecrypter::DecryptNPDRM(u8 *metadata, u32 metadata_size)
{
aes_context aes;
u8 npdrm_key[0x10];
u8 npdrm_iv[0x10];
// Check if we have a valid NPDRM control info structure.
// If not, the data has no NPDRM layer.
const NPD_HEADER* npd = GetNPDHeader();
if (!npd)
{
self_log.trace("No NPDRM control info found!");
return true;
}
if (npd->license == 1) // Network license.
{
// Try to find a RAP file to get the key.
if (!GetKeyFromRap(npd->content_id, npdrm_key))
{
self_log.error("Can't decrypt network NPDRM!");
return false;
}
}
else if (npd->license == 2) // Local license.
{
// Try to find a RAP file to get the key.
if (!GetKeyFromRap(npd->content_id, npdrm_key))
{
self_log.error("Can't find RAP file for NPDRM decryption!");
return false;
}
}
else if (npd->license == 3) // Free license.
{
// Use klicensee if available.
if (key_v.GetKlicenseeKey())
memcpy(npdrm_key, key_v.GetKlicenseeKey(), 0x10);
else
memcpy(npdrm_key, NP_KLIC_FREE, 0x10);
}
else
{
self_log.error("Invalid NPDRM license type!");
return false;
}
// Decrypt our key with NP_KLIC_KEY.
aes_setkey_dec(&aes, NP_KLIC_KEY, 128);
aes_crypt_ecb(&aes, AES_DECRYPT, npdrm_key, npdrm_key);
// IV is empty.
memset(npdrm_iv, 0, 0x10);
// Use our final key to decrypt the NPDRM layer.
aes_setkey_dec(&aes, npdrm_key, 128);
aes_crypt_cbc(&aes, AES_DECRYPT, metadata_size, npdrm_iv, metadata, metadata);
return true;
}
const NPD_HEADER* SELFDecrypter::GetNPDHeader() const
{
// Parse the control info structures to find the NPDRM control info.
for (const supplemental_header& info : m_supplemental_hdr_arr)
{
if (info.type == 3)
{
return &info.PS3_npdrm_header.npd;
}
}
return nullptr;
}
bool SELFDecrypter::LoadMetadata(u8* klic_key)
{
aes_context aes;
const auto metadata_info = std::make_unique<u8[]>(sizeof(meta_info));
const auto metadata_headers_size = sce_hdr.se_hsize - (sizeof(sce_hdr) + sce_hdr.se_meta + sizeof(meta_info));
const auto metadata_headers = std::make_unique<u8[]>(metadata_headers_size);
// Locate and read the encrypted metadata info.
self_f.seek(sce_hdr.se_meta + sizeof(sce_hdr));
self_f.read(metadata_info.get(), sizeof(meta_info));
// Locate and read the encrypted metadata header and section header.
self_f.seek(sce_hdr.se_meta + sizeof(sce_hdr) + sizeof(meta_info));
self_f.read(metadata_headers.get(), metadata_headers_size);
// Find the right keyset from the key vault.
SELF_KEY keyset = key_v.FindSelfKey(m_prog_id_hdr.program_type, sce_hdr.se_flags, m_prog_id_hdr.program_sceversion);
// Set klic if given
if (klic_key)
key_v.SetKlicenseeKey(klic_key);
// Copy the necessary parameters.
u8 metadata_key[0x20];
u8 metadata_iv[0x10];
memcpy(metadata_key, keyset.erk, 0x20);
memcpy(metadata_iv, keyset.riv, 0x10);
// Check DEBUG flag.
if ((sce_hdr.se_flags & 0x8000) != 0x8000)
{
// Decrypt the NPDRM layer.
if (!DecryptNPDRM(metadata_info.get(), sizeof(meta_info)))
return false;
// Decrypt the metadata info.
aes_setkey_dec(&aes, metadata_key, 256); // AES-256
aes_crypt_cbc(&aes, AES_DECRYPT, sizeof(meta_info), metadata_iv, metadata_info.get(), metadata_info.get());
}
// Load the metadata info.
meta_info.Load(metadata_info.get());
// If the padding is not NULL for the key or iv fields, the metadata info
// is not properly decrypted.
if ((meta_info.key_pad[0] != 0x00) ||
(meta_info.iv_pad[0] != 0x00))
{
self_log.error("Failed to decrypt SELF metadata info!");
return false;
}
// Perform AES-CTR encryption on the metadata headers.
usz ctr_nc_off = 0;
u8 ctr_stream_block[0x10];
aes_setkey_enc(&aes, meta_info.key, 128);
aes_crypt_ctr(&aes, metadata_headers_size, &ctr_nc_off, meta_info.iv, ctr_stream_block, metadata_headers.get(), metadata_headers.get());
// Load the metadata header.
meta_hdr.Load(metadata_headers.get());
// Load the metadata section headers.
meta_shdr.clear();
for (unsigned int i = 0; i < meta_hdr.section_count; i++)
{
meta_shdr.emplace_back();
meta_shdr.back().Load(metadata_headers.get() + sizeof(meta_hdr) + sizeof(MetadataSectionHeader) * i);
}
// Copy the decrypted data keys.
data_keys_length = meta_hdr.key_count * 0x10;
data_keys = std::make_unique<u8[]>(data_keys_length);
memcpy(data_keys.get(), metadata_headers.get() + sizeof(meta_hdr) + meta_hdr.section_count * sizeof(MetadataSectionHeader), data_keys_length);
return true;
}
bool SELFDecrypter::DecryptData()
{
aes_context aes;
// Calculate the total data size.
for (unsigned int i = 0; i < meta_hdr.section_count; i++)
{
if (meta_shdr[i].encrypted == 3)
{
if ((meta_shdr[i].key_idx <= meta_hdr.key_count - 1) && (meta_shdr[i].iv_idx <= meta_hdr.key_count))
data_buf_length += ::narrow<u32>(meta_shdr[i].data_size);
}
}
// Allocate a buffer to store decrypted data.
data_buf = std::make_unique<u8[]>(data_buf_length);
// Set initial offset.
u32 data_buf_offset = 0;
// Parse the metadata section headers to find the offsets of encrypted data.
for (unsigned int i = 0; i < meta_hdr.section_count; i++)
{
usz ctr_nc_off = 0;
u8 ctr_stream_block[0x10];
u8 data_key[0x10];
u8 data_iv[0x10];
// Check if this is an encrypted section.
if (meta_shdr[i].encrypted == 3)
{
// Make sure the key and iv are not out of boundaries.
if((meta_shdr[i].key_idx <= meta_hdr.key_count - 1) && (meta_shdr[i].iv_idx <= meta_hdr.key_count))
{
// Get the key and iv from the previously stored key buffer.
memcpy(data_key, data_keys.get() + meta_shdr[i].key_idx * 0x10, 0x10);
memcpy(data_iv, data_keys.get() + meta_shdr[i].iv_idx * 0x10, 0x10);
// Allocate a buffer to hold the data.
auto buf = std::make_unique<u8[]>(meta_shdr[i].data_size);
// Seek to the section data offset and read the encrypted data.
self_f.seek(meta_shdr[i].data_offset);
self_f.read(buf.get(), meta_shdr[i].data_size);
// Zero out our ctr nonce.
memset(ctr_stream_block, 0, sizeof(ctr_stream_block));
// Perform AES-CTR encryption on the data blocks.
aes_setkey_enc(&aes, data_key, 128);
aes_crypt_ctr(&aes, meta_shdr[i].data_size, &ctr_nc_off, data_iv, ctr_stream_block, buf.get(), buf.get());
// Copy the decrypted data.
memcpy(data_buf.get() + data_buf_offset, buf.get(), meta_shdr[i].data_size);
// Advance the buffer's offset.
data_buf_offset += ::narrow<u32>(meta_shdr[i].data_size);
}
}
}
return true;
}
fs::file SELFDecrypter::MakeElf(bool isElf32)
{
// Create a new ELF file.
fs::file e = fs::make_stream<std::vector<u8>>();
if (isElf32)
{
WriteElf(e, elf32_hdr, shdr32_arr, phdr32_arr);
}
else
{
WriteElf(e, elf64_hdr, shdr64_arr, phdr64_arr);
}
return e;
}
bool SELFDecrypter::GetKeyFromRap(const char* content_id, u8* npdrm_key)
{
// Set empty RAP key.
u8 rap_key[0x10];
memset(rap_key, 0, 0x10);
// Try to find a matching RAP file under exdata folder.
const std::string ci_str = content_id;
const std::string rap_path = rpcs3::utils::get_rap_file_path(ci_str);
// Open the RAP file and read the key.
const fs::file rap_file(rap_path);
if (!rap_file)
{
self_log.fatal("Failed to locate the game license file: %s."
"\nEnsure the .rap license file is placed in the dev_hdd0/home/%s/exdata folder with a lowercase file extension."
"\nIf you need assistance on dumping the license file from your PS3, read our quickstart guide: https://rpcs3.net/quickstart", rap_path, Emu.GetUsr());
return false;
}
self_log.notice("Loading RAP file %s.rap", ci_str);
if (rap_file.read(rap_key, 0x10) != 0x10)
{
self_log.fatal("Failed to load %s: RAP file exists but is invalid. Try reinstalling it.", rap_path);
return false;
}
// Convert the RAP key.
rap_to_rif(rap_key, npdrm_key);
return true;
}
static bool IsSelfElf32(const fs::file& f)
{
if (!f) return false;
f.seek(0);
SceHeader hdr{};
ext_hdr sh{};
hdr.Load(f);
sh.Load(f);
// Locate the class byte and check it.
u8 elf_class[0x8];
f.seek(sh.ehdr_offset);
f.read(elf_class, 0x8);
return (elf_class[4] == 1);
}
static bool IsDebugSelf(const fs::file& f)
{
if (f.size() < 0x18)
{
return false;
}
// Get the key version.
f.seek(0x08);
const u16 key_version = f.read<le_t<u16>>();
// Check for DEBUG version.
if (key_version == 0x80 || key_version == 0xc0)
{
return true;
}
return false;
}
static bool CheckDebugSelf(fs::file& s)
{
if (s.size() < 0x18)
{
return false;
}
// Get the key version.
s.seek(0x08);
const u16 key_version = s.read<le_t<u16>>();
// Check for DEBUG version.
if (key_version == 0x80 || key_version == 0xc0)
{
self_log.warning("Debug SELF detected! Removing fake header...");
// Get the real elf offset.
s.seek(0x10);
// Start at the real elf offset.
s.seek(key_version == 0x80 ? +s.read<be_t<u64>>() : +s.read<le_t<u64>>());
// Write the real ELF file back.
fs::file e = fs::make_stream<std::vector<u8>>();
// Copy the data.
char buf[2048];
while (const u64 size = s.read(buf, 2048))
{
e.write(buf, size);
}
s = std::move(e);
return true;
}
// Leave the file untouched.
return false;
}
fs::file decrypt_self(fs::file elf_or_self, u8* klic_key, SelfAdditionalInfo* out_info, bool require_encrypted)
{
if (out_info)
{
*out_info = {};
}
if (!elf_or_self)
{
return fs::file{};
}
elf_or_self.seek(0);
// Check SELF header first. Check for a debug SELF.
if (elf_or_self.size() >= 4 && elf_or_self.read<u32>() == "SCE\0"_u32)
{
if (CheckDebugSelf(elf_or_self))
{
// TODO: Decrypt
return elf_or_self;
}
// Check the ELF file class (32 or 64 bit).
const bool isElf32 = IsSelfElf32(elf_or_self);
// Start the decrypter on this SELF file.
SELFDecrypter self_dec(elf_or_self);
// Load the SELF file headers.
if (!self_dec.LoadHeaders(isElf32, out_info))
{
self_log.error("Failed to load SELF file headers!");
return fs::file{};
}
// Load and decrypt the SELF file metadata.
if (!self_dec.LoadMetadata(klic_key))
{
self_log.error("Failed to load SELF file metadata!");
return fs::file{};
}
// Decrypt the SELF file data.
if (!self_dec.DecryptData())
{
self_log.error("Failed to decrypt SELF file data!");
return fs::file{};
}
// Make a new ELF file from this SELF.
return self_dec.MakeElf(isElf32);
}
if (require_encrypted)
{
return {};
}
return elf_or_self;
}
bool verify_npdrm_self_headers(const fs::file& self, u8* klic_key, NPD_HEADER* npd_out)
{
if (!self)
return false;
self.seek(0);
if (self.size() >= 4 && self.read<u32>() == "SCE\0"_u32 && !IsDebugSelf(self))
{
// Check the ELF file class (32 or 64 bit).
const bool isElf32 = IsSelfElf32(self);
// Start the decrypter on this SELF file.
SELFDecrypter self_dec(self);
// Load the SELF file headers.
if (!self_dec.LoadHeaders(isElf32))
{
self_log.error("Failed to load SELF file headers!");
return false;
}
// Load and decrypt the SELF file metadata.
if (!self_dec.LoadMetadata(klic_key))
{
self_log.error("Failed to load SELF file metadata!");
return false;
}
if (npd_out)
{
if (const NPD_HEADER* npd = self_dec.GetNPDHeader())
{
memcpy(npd_out, npd, sizeof(NPD_HEADER));
}
}
}
return true;
}
bool get_npdrm_self_header(const fs::file& self, NPD_HEADER &npd_out)
{
if (!self)
return false;
self.seek(0);
if (self.size() >= 4 && self.read<u32>() == "SCE\0"_u32 && !IsDebugSelf(self))
{
// Check the ELF file class (32 or 64 bit).
const bool isElf32 = IsSelfElf32(self);
// Start the decrypter on this SELF file.
SELFDecrypter self_dec(self);
// Load the SELF file headers.
if (!self_dec.LoadHeaders(isElf32))
{
self_log.error("Failed to load SELF file headers!");
return false;
}
if (const NPD_HEADER* npd = self_dec.GetNPDHeader())
{
memcpy(&npd_out, npd, sizeof(NPD_HEADER));
return true;
}
}
return false;
}
u128 get_default_self_klic()
{
return std::bit_cast<u128>(NP_KLIC_FREE);
}
| 38,595
|
C++
|
.cpp
| 1,283
| 27.650818
| 157
| 0.66167
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,029
|
unpkg.cpp
|
RPCS3_rpcs3/rpcs3/Crypto/unpkg.cpp
|
#include "stdafx.h"
#include "aes.h"
#include "sha1.h"
#include "key_vault.h"
#include "util/logs.hpp"
#include "Utilities/StrUtil.h"
#include "Utilities/Thread.h"
#include "Utilities/mutex.h"
#include "Emu/System.h"
#include "Emu/system_utils.hpp"
#include "Emu/VFS.h"
#include "unpkg.h"
#include "util/sysinfo.hpp"
#include "Loader/PSF.h"
#include <filesystem>
LOG_CHANNEL(pkg_log, "PKG");
package_reader::package_reader(const std::string& path)
: m_path(path)
{
if (!m_file.open(path))
{
pkg_log.error("PKG file not found!");
return;
}
m_is_valid = read_header();
if (!m_is_valid)
{
return;
}
m_is_valid = read_metadata();
if (!m_is_valid)
{
return;
}
const bool param_sfo_found = read_param_sfo();
if (!param_sfo_found)
{
pkg_log.notice("PKG does not contain a PARAM.SFO");
}
}
package_reader::~package_reader()
{
}
bool package_reader::read_header()
{
if (m_path.empty() || !m_file)
{
pkg_log.error("Reading PKG header: no file to read!");
return false;
}
if (archive_read(&m_header, sizeof(m_header)) != sizeof(m_header))
{
pkg_log.error("Reading PKG header: file is too short!");
return false;
}
pkg_log.notice("Path: '%s'", m_path);
pkg_log.notice("Header: pkg_magic = 0x%x = \"%s\"", +m_header.pkg_magic, std::string_view(reinterpret_cast<const char*>(&m_header.pkg_magic + 1), 3)); // Skip 0x7F
pkg_log.notice("Header: pkg_type = 0x%x = %d", m_header.pkg_type, m_header.pkg_type);
pkg_log.notice("Header: pkg_platform = 0x%x = %d", m_header.pkg_platform, m_header.pkg_platform);
pkg_log.notice("Header: meta_offset = 0x%x = %d", m_header.meta_offset, m_header.meta_offset);
pkg_log.notice("Header: meta_count = 0x%x = %d", m_header.meta_count, m_header.meta_count);
pkg_log.notice("Header: meta_size = 0x%x = %d", m_header.meta_size, m_header.meta_size);
pkg_log.notice("Header: file_count = 0x%x = %d", m_header.file_count, m_header.file_count);
pkg_log.notice("Header: pkg_size = 0x%x = %d", m_header.pkg_size, m_header.pkg_size);
pkg_log.notice("Header: data_offset = 0x%x = %d", m_header.data_offset, m_header.data_offset);
pkg_log.notice("Header: data_size = 0x%x = %d", m_header.data_size, m_header.data_size);
pkg_log.notice("Header: title_id = %s", m_header.title_id);
pkg_log.notice("Header: qa_digest = 0x%x 0x%x", m_header.qa_digest[0], m_header.qa_digest[1]);
pkg_log.notice("Header: klicensee = %s", m_header.klicensee.value());
// Get extended PKG information for PSP or PSVita
if (m_header.pkg_platform == PKG_PLATFORM_TYPE_PSP_PSVITA)
{
PKGExtHeader ext_header;
archive_seek(PKG_HEADER_SIZE);
if (archive_read(&ext_header, sizeof(ext_header)) != sizeof(ext_header))
{
pkg_log.error("Reading extended PKG header: file is too short!");
return false;
}
pkg_log.notice("Extended header: magic = 0x%x = \"%s\"", +ext_header.magic, std::string_view(reinterpret_cast<const char*>(&ext_header.magic + 1), 3));
pkg_log.notice("Extended header: unknown_1 = 0x%x = %d", ext_header.unknown_1, ext_header.unknown_1);
pkg_log.notice("Extended header: ext_hdr_size = 0x%x = %d", ext_header.ext_hdr_size, ext_header.ext_hdr_size);
pkg_log.notice("Extended header: ext_data_size = 0x%x = %d", ext_header.ext_data_size, ext_header.ext_data_size);
pkg_log.notice("Extended header: main_and_ext_headers_hmac_offset = 0x%x = %d", ext_header.main_and_ext_headers_hmac_offset, ext_header.main_and_ext_headers_hmac_offset);
pkg_log.notice("Extended header: metadata_header_hmac_offset = 0x%x = %d", ext_header.metadata_header_hmac_offset, ext_header.metadata_header_hmac_offset);
pkg_log.notice("Extended header: tail_offset = 0x%x = %d", ext_header.tail_offset, ext_header.tail_offset);
//pkg_log.notice("Extended header: padding1 = 0x%x = %d", ext_header.padding1, ext_header.padding1);
pkg_log.notice("Extended header: pkg_key_id = 0x%x = %d", ext_header.pkg_key_id, ext_header.pkg_key_id);
pkg_log.notice("Extended header: full_header_hmac_offset = 0x%x = %d", ext_header.full_header_hmac_offset, ext_header.full_header_hmac_offset);
//pkg_log.notice("Extended header: padding2 = 0x%x = %d", ext_header.padding2, ext_header.padding2);
}
if (m_header.pkg_magic != std::bit_cast<le_t<u32>>("\x7FPKG"_u32))
{
pkg_log.error("Not a PKG file!");
return false;
}
switch (const u16 type = m_header.pkg_type)
{
case PKG_RELEASE_TYPE_DEBUG: break;
case PKG_RELEASE_TYPE_RELEASE: break;
default:
{
pkg_log.error("Unknown PKG type (0x%x)", type);
return false;
}
}
switch (const u16 platform = m_header.pkg_platform)
{
case PKG_PLATFORM_TYPE_PS3: break;
case PKG_PLATFORM_TYPE_PSP_PSVITA: break;
default:
{
pkg_log.error("Unknown PKG platform (0x%x)", platform);
return false;
}
}
if (m_header.pkg_size > m_file.size())
{
// Check if multi-files pkg
if (!m_path.ends_with("_00.pkg"))
{
pkg_log.error("PKG file size mismatch (pkg_size=0x%llx)", m_header.pkg_size);
return false;
}
std::vector<fs::file> filelist;
filelist.emplace_back(std::move(m_file));
const std::string name_wo_number = m_path.substr(0, m_path.size() - 7);
u64 cursize = filelist[0].size();
while (cursize < m_header.pkg_size)
{
const std::string archive_filename = fmt::format("%s_%02d.pkg", name_wo_number, filelist.size());
fs::file archive_file(archive_filename);
if (!archive_file)
{
pkg_log.error("Missing part of the multi-files pkg: %s", archive_filename);
return false;
}
const usz add_size = archive_file.size();
if (!add_size)
{
pkg_log.error("%s is empty, cannot read PKG", archive_filename);
return false;
}
cursize += add_size;
filelist.emplace_back(std::move(archive_file));
}
// Gather files
m_file = fs::make_gather(std::move(filelist));
}
if (m_header.data_size + m_header.data_offset > m_header.pkg_size)
{
pkg_log.error("PKG data size mismatch (data_size=0x%llx, data_offset=0x%llx, file_size=0x%llx)", m_header.data_size, m_header.data_offset, m_header.pkg_size);
return false;
}
return true;
}
bool package_reader::read_metadata()
{
if (!decrypt_data())
{
return false;
}
// Read title ID and use it as an installation directory
m_install_dir.resize(9);
archive_read_block(55, &m_install_dir.front(), m_install_dir.size());
// Read package metadata
archive_seek(m_header.meta_offset);
for (u32 i = 0; i < m_header.meta_count; i++)
{
struct packet_T
{
be_t<u32> id;
be_t<u32> size;
} packet;
archive_read(&packet, sizeof(packet));
// TODO
switch (+packet.id)
{
case 0x1:
{
if (packet.size == sizeof(m_metadata.drm_type))
{
archive_read(&m_metadata.drm_type, sizeof(m_metadata.drm_type));
pkg_log.notice("Metadata: DRM Type = 0x%x = %d", m_metadata.drm_type, m_metadata.drm_type);
continue;
}
else
{
pkg_log.error("Metadata: DRM Type size mismatch (0x%x)", packet.size);
}
break;
}
case 0x2:
{
if (packet.size == sizeof(m_metadata.content_type))
{
archive_read(&m_metadata.content_type, sizeof(m_metadata.content_type));
pkg_log.notice("Metadata: Content Type = 0x%x = %d", m_metadata.content_type, m_metadata.content_type);
continue;
}
else
{
pkg_log.error("Metadata: Content Type size mismatch (0x%x)", packet.size);
}
break;
}
case 0x3:
{
if (packet.size == sizeof(m_metadata.package_type))
{
archive_read(&m_metadata.package_type, sizeof(m_metadata.package_type));
pkg_log.notice("Metadata: Package Type = 0x%x = %d", m_metadata.package_type, m_metadata.package_type);
continue;
}
else
{
pkg_log.error("Metadata: Package Type size mismatch (0x%x)", packet.size);
}
break;
}
case 0x4:
{
if (packet.size == sizeof(m_metadata.package_size))
{
archive_read(&m_metadata.package_size, sizeof(m_metadata.package_size));
pkg_log.notice("Metadata: Package Size = 0x%x = %d", m_metadata.package_size, m_metadata.package_size);
continue;
}
else
{
pkg_log.error("Metadata: Package Size size mismatch (0x%x)", packet.size);
}
break;
}
case 0x5:
{
if (packet.size == sizeof(m_metadata.package_revision.data))
{
archive_read(&m_metadata.package_revision.data, sizeof(m_metadata.package_revision.data));
m_metadata.package_revision.interpret_data();
pkg_log.notice("Metadata: Package Revision = %s", m_metadata.package_revision.to_string());
continue;
}
else
{
pkg_log.error("Metadata: Package Revision size mismatch (0x%x)", packet.size);
}
break;
}
case 0x6:
{
m_metadata.title_id.resize(12);
if (packet.size == m_metadata.title_id.size())
{
archive_read(&m_metadata.title_id.front(), m_metadata.title_id.size());
m_metadata.title_id = fmt::trim(m_metadata.title_id);
pkg_log.notice("Metadata: Title ID = %s", m_metadata.title_id);
continue;
}
else
{
pkg_log.error("Metadata: Title ID size mismatch (0x%x)", packet.size);
}
break;
}
case 0x7:
{
if (packet.size == sizeof(m_metadata.qa_digest))
{
archive_read(&m_metadata.qa_digest, sizeof(m_metadata.qa_digest));
pkg_log.notice("Metadata: QA Digest = 0x%x", m_metadata.qa_digest);
continue;
}
else
{
pkg_log.error("Metadata: QA Digest size mismatch (0x%x)", packet.size);
}
break;
}
case 0x8:
{
if (packet.size == sizeof(m_metadata.software_revision.data))
{
archive_read(&m_metadata.software_revision.data, sizeof(m_metadata.software_revision.data));
m_metadata.software_revision.interpret_data();
pkg_log.notice("Metadata: Software Revision = %s", m_metadata.software_revision.to_string());
continue;
}
else
{
pkg_log.error("Metadata: Software Revision size mismatch (0x%x)", packet.size);
}
break;
}
case 0x9:
{
if (packet.size == sizeof(m_metadata.unk_0x9))
{
archive_read(&m_metadata.unk_0x9, sizeof(m_metadata.unk_0x9));
pkg_log.notice("Metadata: unk_0x9 = 0x%x = %d", m_metadata.unk_0x9, m_metadata.unk_0x9);
continue;
}
else
{
pkg_log.error("Metadata: unk_0x9 size mismatch (0x%x)", packet.size);
}
break;
}
case 0xA:
{
if (packet.size > 8)
{
// Read an actual installation directory (DLC)
m_install_dir.resize(packet.size);
archive_read(&m_install_dir.front(), packet.size);
m_install_dir = m_install_dir.c_str() + 8;
m_metadata.install_dir = m_install_dir;
pkg_log.notice("Metadata: Install Dir = %s", m_metadata.install_dir);
continue;
}
else
{
pkg_log.error("Metadata: Install Dir size mismatch (0x%x)", packet.size);
}
break;
}
case 0xB:
{
if (packet.size == sizeof(m_metadata.unk_0xB))
{
archive_read(&m_metadata.unk_0xB, sizeof(m_metadata.unk_0xB));
pkg_log.notice("Metadata: unk_0xB = 0x%x = %d", m_metadata.unk_0xB, m_metadata.unk_0xB);
continue;
}
else
{
pkg_log.error("Metadata: unk_0xB size mismatch (0x%x)", packet.size);
}
break;
}
case 0xC:
{
// Unknown
break;
}
case 0xD: // PSVita stuff
{
if (packet.size == sizeof(m_metadata.item_info))
{
archive_read(&m_metadata.item_info, sizeof(m_metadata.item_info));
pkg_log.notice("Metadata: PSVita item info = %s", m_metadata.item_info.to_string());
continue;
}
else
{
pkg_log.error("Metadata: Item info size mismatch (0x%x)", packet.size);
}
break;
}
case 0xE: // PSVita stuff
{
if (packet.size == sizeof(m_metadata.sfo_info))
{
archive_read(&m_metadata.sfo_info, sizeof(m_metadata.sfo_info));
pkg_log.notice("Metadata: PSVita sfo info = %s", m_metadata.sfo_info.to_string());
continue;
}
else
{
pkg_log.error("Metadata: SFO info size mismatch (0x%x)", packet.size);
}
break;
}
case 0xF: // PSVita stuff
{
if (packet.size == sizeof(m_metadata.unknown_data_info))
{
archive_read(&m_metadata.unknown_data_info, sizeof(m_metadata.unknown_data_info));
pkg_log.notice("Metadata: PSVita unknown data info = %s", m_metadata.unknown_data_info.to_string());
continue;
}
else
{
pkg_log.error("Metadata: unknown data info size mismatch (0x%x)", packet.size);
}
break;
}
case 0x10: // PSVita stuff
{
if (packet.size == sizeof(m_metadata.entirety_info))
{
archive_read(&m_metadata.entirety_info, sizeof(m_metadata.entirety_info));
pkg_log.notice("Metadata: PSVita entirety info = %s", m_metadata.entirety_info.to_string());
continue;
}
else
{
pkg_log.error("Metadata: Entirety info size mismatch (0x%x)", packet.size);
}
break;
}
case 0x11: // PSVita stuff
{
if (packet.size == sizeof(m_metadata.version_info))
{
archive_read(&m_metadata.version_info, sizeof(m_metadata.version_info));
pkg_log.notice("Metadata: PSVita version info = %s", m_metadata.version_info.to_string());
continue;
}
else
{
pkg_log.error("Metadata: Version info size mismatch (0x%x)", packet.size);
}
break;
}
case 0x12: // PSVita stuff
{
if (packet.size == sizeof(m_metadata.self_info))
{
archive_read(&m_metadata.self_info, sizeof(m_metadata.self_info));
pkg_log.notice("Metadata: PSVita self info = %s", m_metadata.self_info.to_string());
continue;
}
else
{
pkg_log.error("Metadata: Self info size mismatch (0x%x)", packet.size);
}
break;
}
default:
{
pkg_log.error("Unknown packet id %d", packet.id);
break;
}
}
archive_seek(packet.size, fs::seek_cur);
}
return true;
}
bool package_reader::decrypt_data()
{
if (!m_is_valid)
{
return false;
}
if (m_header.pkg_platform == PKG_PLATFORM_TYPE_PSP_PSVITA && m_metadata.content_type >= 0x15 && m_metadata.content_type <= 0x17)
{
// PSVita
// TODO: Not all the keys seem to match the content types. I was only able to install a dlc (0x16) with PKG_AES_KEY_VITA_1
aes_context ctx;
aes_setkey_enc(&ctx, m_metadata.content_type == 0x15u ? PKG_AES_KEY_VITA_1 : m_metadata.content_type == 0x16u ? PKG_AES_KEY_VITA_2 : PKG_AES_KEY_VITA_3, 128);
aes_crypt_ecb(&ctx, AES_ENCRYPT, reinterpret_cast<const uchar*>(&m_header.klicensee), m_dec_key.data());
decrypt(0, m_header.file_count * sizeof(PKGEntry), m_dec_key.data());
}
else
{
std::memcpy(m_dec_key.data(), PKG_AES_KEY, m_dec_key.size());
decrypt(0, m_header.file_count * sizeof(PKGEntry), m_header.pkg_platform == PKG_PLATFORM_TYPE_PSP_PSVITA ? PKG_AES_KEY2 : m_dec_key.data());
}
return true;
}
bool package_reader::read_param_sfo()
{
if (!decrypt_data())
{
return false;
}
std::vector<PKGEntry> entries(m_header.file_count);
std::memcpy(entries.data(), m_bufs.back().get(), entries.size() * sizeof(PKGEntry));
for (const PKGEntry& entry : entries)
{
if (entry.name_size > 256)
{
pkg_log.error("PKG name size is too big (0x%x)", entry.name_size);
continue;
}
const bool is_psp = (entry.type & PKG_FILE_ENTRY_PSP) != 0u;
decrypt(entry.name_offset, entry.name_size, is_psp ? PKG_AES_KEY2 : m_dec_key.data());
const std::string_view name{reinterpret_cast<char*>(m_bufs.back().get()), entry.name_size};
// We're looking for the PARAM.SFO file, if there is any
if (usz ndelim = name.find_first_not_of('/'); ndelim == umax || name.substr(ndelim) != "PARAM.SFO")
{
continue;
}
// Read the package's PARAM.SFO
if (fs::file tmp = fs::make_stream<std::vector<uchar>>())
{
for (u64 pos = 0; pos < entry.file_size; pos += BUF_SIZE)
{
const u64 block_size = std::min<u64>(BUF_SIZE, entry.file_size - pos);
if (decrypt(entry.file_offset + pos, block_size, is_psp ? PKG_AES_KEY2 : m_dec_key.data()).size() != block_size)
{
pkg_log.error("Failed to decrypt PARAM.SFO file");
return false;
}
if (tmp.write(m_bufs.back().get(), block_size) != block_size)
{
pkg_log.error("Failed to write to temporary PARAM.SFO file");
return false;
}
}
tmp.seek(0);
m_psf = psf::load_object(tmp, name);
if (m_psf.empty())
{
// Invalid
continue;
}
return true;
}
pkg_log.error("Failed to create temporary PARAM.SFO file");
return false;
}
return false;
}
// TODO: maybe also check if VERSION matches
package_install_result package_reader::check_target_app_version() const
{
if (!m_is_valid)
{
return {package_install_result::error_type::other};
}
const auto category = psf::get_string(m_psf, "CATEGORY", "");
const auto title_id = psf::get_string(m_psf, "TITLE_ID", "");
const auto app_ver = psf::get_string(m_psf, "APP_VER", "");
const auto target_app_ver = psf::get_string(m_psf, "TARGET_APP_VER", "");
if (category != "GD")
{
// We allow anything that isn't an update for now
return {package_install_result::error_type::no_error};
}
if (title_id.empty())
{
// Let's allow packages without ID for now
return {package_install_result::error_type::no_error};
}
if (app_ver.empty())
{
if (!target_app_ver.empty())
{
// Let's see if this case exists
pkg_log.fatal("Trying to install an unversioned patch with a target app version (%s). Please contact a developer!", target_app_ver);
}
// This is probably not a version dependant patch, so we may install the package
return {package_install_result::error_type::no_error};
}
const std::string sfo_path = rpcs3::utils::get_hdd0_dir() + "game/" + std::string(title_id) + "/PARAM.SFO";
const fs::file installed_sfo_file(sfo_path);
if (!installed_sfo_file)
{
if (!target_app_ver.empty())
{
// We are unable to compare anything with the target app version
pkg_log.error("A target app version is required (%s), but no PARAM.SFO was found for %s. (path='%s', error=%s)", target_app_ver, title_id, sfo_path, fs::g_tls_error);
return {package_install_result::error_type::app_version, {std::string(target_app_ver)}};
}
// There is nothing we need to compare, so we may install the package
return {package_install_result::error_type::no_error};
}
const auto installed_psf = psf::load_object(installed_sfo_file, sfo_path);
const auto installed_title_id = psf::get_string(installed_psf, "TITLE_ID", "");
const auto installed_app_ver = psf::get_string(installed_psf, "APP_VER", "");
if (title_id != installed_title_id || installed_app_ver.empty())
{
// Let's allow this package for now
return {package_install_result::error_type::no_error};
}
std::add_pointer_t<char> ev0, ev1;
const double old_version = std::strtod(installed_app_ver.data(), &ev0);
if (installed_app_ver.data() + installed_app_ver.size() != ev0)
{
pkg_log.error("Failed to convert the installed app version to double (%s)", installed_app_ver);
return {package_install_result::error_type::other};
}
if (target_app_ver.empty())
{
// This is most likely the first patch. Let's make sure its version is high enough for the installed game.
const double new_version = std::strtod(app_ver.data(), &ev1);
if (app_ver.data() + app_ver.size() != ev1)
{
pkg_log.error("Failed to convert the package's app version to double (%s)", app_ver);
return {package_install_result::error_type::other};
}
if (new_version >= old_version)
{
// Yay! The patch has a higher or equal version than the installed game.
return {package_install_result::error_type::no_error};
}
pkg_log.error("The new app version (%s) is smaller than the installed app version (%s)", app_ver, installed_app_ver);
return {package_install_result::error_type::app_version, {std::string(app_ver), std::string(installed_app_ver)}};
}
// Check if the installed app version matches the target app version
const double target_version = std::strtod(target_app_ver.data(), &ev1);
if (target_app_ver.data() + target_app_ver.size() != ev1)
{
pkg_log.error("Failed to convert the package's target app version to double (%s)", target_app_ver);
return {package_install_result::error_type::other};
}
if (target_version == old_version)
{
// Yay! This patch is for the installed game version.
return {package_install_result::error_type::no_error};
}
pkg_log.error("The installed app version (%s) does not match the target app version (%s)", installed_app_ver, target_app_ver);
return {package_install_result::error_type::app_version, {std::string(target_app_ver), std::string(installed_app_ver)}};
}
bool package_reader::set_install_path()
{
if (!m_is_valid)
{
return false;
}
m_install_path.clear();
// Get full path
std::string dir = rpcs3::utils::get_hdd0_dir();
// Based on https://www.psdevwiki.com/ps3/PKG_files#ContentType
switch (m_metadata.content_type)
{
case PKG_CONTENT_TYPE_THEME:
dir += "theme/";
break;
case PKG_CONTENT_TYPE_WIDGET:
dir += "widget/";
break;
case PKG_CONTENT_TYPE_LICENSE:
dir += "home/" + Emu.GetUsr() + "/exdata/";
break;
case PKG_CONTENT_TYPE_VSH_MODULE:
dir += "vsh/modules/";
break;
case PKG_CONTENT_TYPE_PSN_AVATAR:
dir += "home/" + Emu.GetUsr() + "/psn_avatar/";
break;
case PKG_CONTENT_TYPE_VMC:
dir += "tmp/vmc/";
break;
// TODO: Find out if other content types are installed elsewhere
default:
dir += "game/";
break;
}
// TODO: Verify whether other content types require appending title ID
if (m_metadata.content_type != PKG_CONTENT_TYPE_LICENSE)
dir += m_install_dir + '/';
// If false, an existing directory is being overwritten: cannot cancel the operation
m_was_null = !fs::is_dir(dir);
m_install_path = dir;
return true;
}
bool package_reader::fill_data(std::map<std::string, install_entry*>& all_install_entries)
{
if (!m_is_valid)
{
return false;
}
if (!fs::create_path(m_install_path))
{
pkg_log.error("Could not create the installation directory %s (error=%s)", m_install_path, fs::g_tls_error);
return false;
}
m_install_entries.clear();
m_bootable_file_path.clear();
m_entry_indexer = 0;
m_written_bytes = 0;
if (!decrypt_data())
{
return false;
}
usz num_failures = 0;
std::vector<PKGEntry> entries(m_header.file_count);
std::memcpy(entries.data(), m_bufs.back().get(), entries.size() * sizeof(PKGEntry));
// Create directories first
for (const auto& entry : entries)
{
if (entry.name_size > PKG_MAX_FILENAME_SIZE)
{
num_failures++;
pkg_log.error("PKG name size is too big (0x%x)", entry.name_size);
break;
}
const bool is_psp = (entry.type & PKG_FILE_ENTRY_PSP) != 0u;
decrypt(entry.name_offset, entry.name_size, is_psp ? PKG_AES_KEY2 : m_dec_key.data());
const std::string_view name{reinterpret_cast<char*>(m_bufs.back().get()), entry.name_size};
std::string path = m_install_path + vfs::escape(name);
if (entry.pad || (entry.type & ~PKG_FILE_ENTRY_KNOWN_BITS))
{
pkg_log.todo("Entry with unknown type or padding: type=0x%08x, pad=0x%x, name='%s'", entry.type, entry.pad, name);
}
else
{
pkg_log.notice("Entry: type=0x%08x, name='%s'", entry.type, name);
}
const u8 entry_type = entry.type & 0xff;
switch (entry_type)
{
case PKG_FILE_ENTRY_FOLDER:
case 0x12:
{
if (fs::is_dir(path))
{
pkg_log.warning("Reused existing directory %s", path);
}
else if (fs::create_path(path))
{
pkg_log.notice("Created directory %s", path);
}
else
{
num_failures++;
pkg_log.error("Failed to create directory %s", path);
break;
}
break;
}
default:
{
// TODO: check for valid utf8 characters
const std::string true_path = std::filesystem::weakly_canonical(path).string();
if (true_path.empty())
{
num_failures++;
pkg_log.error("Failed to get weakly_canonical path for '%s'", path);
break;
}
auto map_ptr = &*all_install_entries.try_emplace(true_path).first;
m_install_entries.push_back({
.weak_reference = map_ptr,
.name = std::string(name),
.file_offset = entry.file_offset,
.file_size = entry.file_size,
.type = entry.type,
.pad = entry.pad
});
if (map_ptr->second && !(entry.type & PKG_FILE_ENTRY_OVERWRITE))
{
// Cannot override
continue;
}
// Link
map_ptr->second = &m_install_entries.back();
continue;
}
}
}
if (num_failures != 0)
{
pkg_log.error("Package installation failed: %s", m_install_path);
return false;
}
return true;
}
fs::file DecryptEDAT(const fs::file& input, const std::string& input_file_name, int mode, u8 *custom_klic);
void package_reader::extract_worker(thread_key thread_data_key)
{
std::vector<u8> read_cache;
while (m_num_failures == 0 && !m_aborted)
{
// Make sure m_entry_indexer does not exceed m_install_entries
const usz index = m_entry_indexer.fetch_op([this](usz& v)
{
if (v < m_install_entries.size())
{
v++;
return true;
}
return false;
}).first;
if (index >= m_install_entries.size())
{
break;
}
const install_entry& entry = ::at32(m_install_entries, index);
if (!entry.is_dominating())
{
// Overwritten by another entry
m_written_bytes += entry.file_size;
continue;
}
const bool is_psp = (entry.type & PKG_FILE_ENTRY_PSP) != 0u;
const std::string& path = entry.weak_reference->first;
const std::string& name = entry.name;
if (entry.pad || (entry.type & ~PKG_FILE_ENTRY_KNOWN_BITS))
{
pkg_log.todo("Entry with unknown type or padding: type=0x%08x, pad=0x%x, name='%s'", entry.type, entry.pad, name);
}
else
{
pkg_log.notice("Entry: type=0x%08x, name='%s'", entry.type, name);
}
switch (const u8 entry_type = entry.type & 0xff)
{
case PKG_FILE_ENTRY_NPDRM:
case PKG_FILE_ENTRY_NPDRMEDAT:
case PKG_FILE_ENTRY_SDAT:
case PKG_FILE_ENTRY_REGULAR:
case PKG_FILE_ENTRY_UNK0:
case PKG_FILE_ENTRY_UNK1:
case 0xe:
case 0x10:
case 0x11:
case 0x13:
case 0x14:
case 0x15:
case 0x16:
case 0x18:
case 0x19:
{
const bool did_overwrite = fs::is_file(path);
if (did_overwrite && !(entry.type & PKG_FILE_ENTRY_OVERWRITE))
{
pkg_log.notice("Didn't overwrite %s", path);
break;
}
const bool is_buffered = entry_type == PKG_FILE_ENTRY_SDAT;
if (entry_type == PKG_FILE_ENTRY_NPDRMEDAT)
{
pkg_log.warning("NPDRM EDAT!");
}
if (fs::file out{ path, did_overwrite ? fs::rewrite : fs::write_new })
{
bool extract_success = true;
struct pkg_file_reader : fs::file_base
{
const std::function<u64(u64, void*, u64)> m_read_func;
const install_entry& m_entry;
usz m_pos;
explicit pkg_file_reader(std::function<u64(u64, void* buffer, u64)> read_func, const install_entry& entry) noexcept
: m_read_func(std::move(read_func))
, m_entry(entry)
, m_pos(0)
{
}
fs::stat_t get_stat() override
{
fs::stat_t stat{};
stat.size = m_entry.file_size;
return stat;
}
bool trunc(u64) override
{
return false;
}
u64 read(void* buffer, u64 size) override
{
const u64 result = pkg_file_reader::read_at(m_pos, buffer, size);
m_pos += result;
return result;
}
u64 read_at(u64 offset, void* buffer, u64 size) override
{
return m_read_func(offset, buffer, size);
}
u64 write(const void*, u64) override
{
return 0;
}
u64 seek(s64 offset, fs::seek_mode whence) override
{
const s64 new_pos =
whence == fs::seek_set ? offset :
whence == fs::seek_cur ? offset + m_pos :
whence == fs::seek_end ? offset + size() : -1;
if (new_pos < 0)
{
fs::g_tls_error = fs::error::inval;
return -1;
}
m_pos = new_pos;
return m_pos;
}
u64 size() override
{
return m_entry.file_size;
}
fs::file_id get_id() override
{
fs::file_id id{};
id.type.insert(0, "pkg_file_reader: "sv);
return id;
}
};
read_cache.clear();
auto reader = std::make_unique<pkg_file_reader>([&, cache_off = u64{umax}](usz pos, void* ptr, usz size) mutable -> u64
{
if (pos >= entry.file_size || !size)
{
return 0;
}
size = std::min<u64>(entry.file_size - pos, size);
u64 size_cache_end = 0;
u64 read_size = 0;
// Check if exists in cache
if (!read_cache.empty() && cache_off <= pos && pos < cache_off + read_cache.size())
{
read_size = std::min<u64>(pos + size, cache_off + read_cache.size()) - pos;
std::memcpy(ptr, read_cache.data() + (pos - cache_off), read_size);
pos += read_size;
}
else if (!read_cache.empty() && cache_off < pos + size && cache_off + read_cache.size() >= pos + size)
{
size_cache_end = size - (std::max<u64>(cache_off, pos) - pos);
std::memcpy(static_cast<u8*>(ptr) + (cache_off - pos), read_cache.data(), size_cache_end);
size -= size_cache_end;
}
if (pos >= entry.file_size || !size)
{
return read_size + size_cache_end;
}
// Try to cache for later
if (size <= BUF_SIZE && !size_cache_end && !read_size)
{
const u64 block_size = std::min<u64>({BUF_SIZE, std::max<u64>(size * 5 / 3, 65536), entry.file_size - pos});
read_cache.resize(block_size);
cache_off = pos;
const std::span<const char> data_span = decrypt(entry.file_offset + pos, block_size, is_psp ? PKG_AES_KEY2 : m_dec_key.data(), thread_data_key);
if (data_span.empty())
{
cache_off = umax;
read_cache.clear();
return 0;
}
read_cache.resize(data_span.size());
std::memcpy(read_cache.data(), data_span.data(), data_span.size());
size = std::min<usz>(data_span.size(), size);
std::memcpy(ptr, data_span.data(), size);
return size;
}
while (read_size < size)
{
const u64 block_size = std::min<u64>(BUF_SIZE, size - read_size);
const std::span<const char> data_span = decrypt(entry.file_offset + pos, block_size, is_psp ? PKG_AES_KEY2 : m_dec_key.data(), thread_data_key);
if (data_span.empty())
{
break;
}
std::memcpy(static_cast<u8*>(ptr) + read_size, data_span.data(), data_span.size());
read_size += data_span.size();
pos += data_span.size();
}
return read_size + size_cache_end;
}, entry);
fs::file in_data;
in_data.reset(std::move(reader));
fs::file final_data;
if (is_buffered)
{
final_data = DecryptEDAT(in_data, name, 1, reinterpret_cast<u8*>(&m_header.klicensee));
}
else
{
final_data = std::move(in_data);
}
if (!final_data)
{
m_num_failures++;
pkg_log.error("Failed to decrypt EDAT file %s (error=%s)", path, fs::g_tls_error);
break;
}
// 16MB buffer
std::vector<u8> buffer(std::min<usz>(entry.file_size, 1u << 24));
while (usz read_size = final_data.read(buffer.data(), buffer.size()))
{
out.write(buffer.data(), read_size);
m_written_bytes += read_size;
}
final_data.close();
out.close();
if (extract_success)
{
if (did_overwrite)
{
pkg_log.warning("Overwritten file %s", path);
}
else
{
pkg_log.notice("Created file %s", path);
if (name == "USRDIR/EBOOT.BIN" && entry.file_size > 4)
{
// Expose the creation of a bootable file
m_bootable_file_path = path;
}
}
}
else
{
m_num_failures++;
}
}
else
{
m_num_failures++;
pkg_log.error("Failed to create file %s (is_buffered=%d, did_overwrite=%d, error=%s)", path, is_buffered, did_overwrite, fs::g_tls_error);
}
break;
}
default:
{
m_num_failures++;
pkg_log.error("Unknown PKG entry type (0x%x) %s", entry.type, name);
break;
}
}
}
}
package_install_result package_reader::extract_data(std::deque<package_reader>& readers, std::deque<std::string>& bootable_paths)
{
package_install_result::error_type error = package_install_result::error_type::no_error;
usz num_failures = 0;
// Set paths first in order to know if the install dir was empty before starting any installations.
// This will also allow us to remove all the new packages in one path at once if any of them fail.
for (package_reader& reader : readers)
{
reader.m_result = result::not_started;
if (!reader.set_install_path())
{
error = package_install_result::error_type::other;
reader.m_result = result::error; // We don't know if it's dirty yet.
return {error};
}
}
for (package_reader& reader : readers)
{
// Use a seperate map for each reader. We need to check if the target app version exists for each package in sequence.
std::map<std::string, install_entry*> all_install_entries;
if (error != package_install_result::error_type::no_error || num_failures > 0)
{
ensure(reader.m_result == result::error || reader.m_result == result::error_dirty);
return {error};
}
// Check if this package is allowed to be installed on top of the existing data
const package_install_result version_check = reader.check_target_app_version();
if (version_check.error != package_install_result::error_type::no_error)
{
reader.m_result = result::error; // We don't know if it's dirty yet.
return version_check;
}
reader.m_result = result::started;
// Parse the files to be installed and create all paths.
if (!reader.fill_data(all_install_entries))
{
error = package_install_result::error_type::other;
// Do not return yet. We may need to clean up down below.
}
reader.m_num_failures = error == package_install_result::error_type::no_error ? 0 : 1;
if (reader.m_num_failures == 0)
{
reader.m_bufs.resize(std::min<usz>(utils::get_thread_count(), reader.m_install_entries.size()));
atomic_t<usz> thread_indexer = 0;
named_thread_group workers("PKG Installer "sv, std::max<u32>(::narrow<u32>(reader.m_bufs.size()), 1) - 1, [&]()
{
reader.extract_worker(thread_key{thread_indexer++});
});
reader.extract_worker(thread_key{thread_indexer++});
workers.join();
reader.m_bufs.clear();
reader.m_bufs.shrink_to_fit();
}
num_failures += reader.m_num_failures;
// We don't count this package as aborted if all entries were processed.
if (reader.m_num_failures || (reader.m_aborted && reader.m_entry_indexer < reader.m_install_entries.size()))
{
// Clear boot path. We don't want to propagate potentially broken paths to the caller.
reader.m_bootable_file_path.clear();
bool cleaned = reader.m_was_null;
if (reader.m_was_null && fs::is_dir(reader.m_install_path))
{
pkg_log.notice("Removing partial installation ('%s')", reader.m_install_path);
if (!fs::remove_all(reader.m_install_path, true))
{
pkg_log.notice("Failed to remove partial installation ('%s') (error=%s)", reader.m_install_path, fs::g_tls_error);
cleaned = false;
}
}
if (reader.m_num_failures)
{
pkg_log.error("Package failed to install ('%s')", reader.m_install_path);
reader.m_result = cleaned ? result::error : result::error_dirty;
}
else
{
pkg_log.warning("Package installation aborted ('%s')", reader.m_install_path);
reader.m_result = cleaned ? result::aborted : result::aborted_dirty;
}
break;
}
reader.m_result = result::success;
if (reader.get_progress(1) != 1)
{
pkg_log.warning("Missing %d bytes from PKG total files size.", reader.m_header.data_size - reader.m_written_bytes);
reader.m_written_bytes = reader.m_header.data_size; // Mark as completed anyway
}
// May be empty
bootable_paths.emplace_back(std::move(reader.m_bootable_file_path));
}
if (error == package_install_result::error_type::no_error && num_failures > 0)
{
error = package_install_result::error_type::other;
}
return {error};
}
void package_reader::archive_seek(const s64 new_offset, const fs::seek_mode damode)
{
if (m_file) m_file.seek(new_offset, damode);
}
u64 package_reader::archive_read(void* data_ptr, const u64 num_bytes)
{
return m_file ? m_file.read(data_ptr, num_bytes) : 0;
}
std::span<const char> package_reader::archive_read_block(u64 offset, void* data_ptr, u64 num_bytes)
{
const usz read_n = m_file.read_at(offset, data_ptr, num_bytes);
return {static_cast<const char*>(data_ptr), read_n};
}
std::span<const char> package_reader::decrypt(u64 offset, u64 size, const uchar* key, thread_key thread_data_key)
{
if (!m_is_valid)
{
return {};
}
if (m_bufs.empty())
{
// Assume in single-threaded mode still
m_bufs.resize(1);
}
auto& local_buf = ::at32(m_bufs, thread_data_key.unique_num);
if (!local_buf)
{
// Allocate buffer with BUF_SIZE size or more if required
local_buf.reset(new u128[std::max<u64>(BUF_SIZE, sizeof(PKGEntry) * m_header.file_count) / sizeof(u128)]);
}
// Read the data and set available size
const auto data_span = archive_read_block(m_header.data_offset + offset, local_buf.get(), size);
ensure(data_span.data() == static_cast<void*>(local_buf.get()));
// Get block count
const u64 blocks = (data_span.size() + 15) / 16;
if (m_header.pkg_type == PKG_RELEASE_TYPE_DEBUG)
{
// Debug key
be_t<u64> input[8] =
{
m_header.qa_digest[0],
m_header.qa_digest[0],
m_header.qa_digest[1],
m_header.qa_digest[1],
};
for (u64 i = 0; i < blocks; i++)
{
// Initialize stream cipher for current position
input[7] = offset / 16 + i;
union sha1_hash
{
u8 data[20];
u128 _v128;
} hash;
sha1(reinterpret_cast<const u8*>(input), sizeof(input), hash.data);
local_buf[i] ^= hash._v128;
}
}
else if (m_header.pkg_type == PKG_RELEASE_TYPE_RELEASE)
{
aes_context ctx;
// Set encryption key for stream cipher
aes_setkey_enc(&ctx, key, 128);
// Initialize stream cipher for start position
be_t<u128> input = m_header.klicensee.value() + offset / 16;
// Increment stream position for every block
for (u64 i = 0; i < blocks; i++, input++)
{
u128 key;
aes_crypt_ecb(&ctx, AES_ENCRYPT, reinterpret_cast<const u8*>(&input), reinterpret_cast<u8*>(&key));
local_buf[i] ^= key;
}
}
else
{
pkg_log.error("Unknown release type (0x%x)", m_header.pkg_type);
}
// Return the amount of data written in buf
return data_span;
}
int package_reader::get_progress(int maximum) const
{
const usz wr = m_written_bytes;
return wr >= m_header.data_size ? maximum : ::narrow<int>(wr * maximum / m_header.data_size);
}
void package_reader::abort_extract()
{
m_aborted = true;
}
| 38,310
|
C++
|
.cpp
| 1,189
| 28.450799
| 172
| 0.661084
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,030
|
aesni.cpp
|
RPCS3_rpcs3/rpcs3/Crypto/aesni.cpp
|
#if defined(__SSE2__) || defined(_M_X64)
/*
* AES-NI support functions
*
* Copyright (C) 2013, Brainspark B.V.
*
* This file is part of PolarSSL (http://www.polarssl.org)
* Lead Maintainer: Paul Bakker <polarssl_maintainer at polarssl.org>
*
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/*
* [AES-WP] http://software.intel.com/en-us/articles/intel-advanced-encryption-standard-aes-instructions-set
* [CLMUL-WP] http://software.intel.com/en-us/articles/intel-carry-less-multiplication-instruction-and-its-usage-for-computing-the-gcm-mode/
*/
#include "aesni.h"
#if defined(_MSC_VER) && defined(_M_X64)
#define POLARSSL_HAVE_MSVC_X64_INTRINSICS
#include <intrin.h>
#endif
/*
* AES-NI support detection routine
*/
int aesni_supports( unsigned int what )
{
static int done = 0;
static unsigned int c = 0;
if( ! done )
{
#if defined(POLARSSL_HAVE_MSVC_X64_INTRINSICS)
int regs[4]; // eax, ebx, ecx, edx
__cpuid( regs, 1 );
c = regs[2];
#else
asm( "movl $1, %%eax \n"
"cpuid \n"
: "=c" (c)
:
: "eax", "ebx", "edx" );
#endif /* POLARSSL_HAVE_MSVC_X64_INTRINSICS */
done = 1;
}
return( ( c & what ) != 0 );
}
/*
* AES-NI AES-ECB block en(de)cryption
*/
int aesni_crypt_ecb( aes_context *ctx,
int mode,
const unsigned char input[16],
unsigned char output[16] )
{
#if defined(POLARSSL_HAVE_MSVC_X64_INTRINSICS)
__m128i* rk, a;
int i;
rk = (__m128i*)ctx->rk;
a = _mm_xor_si128( _mm_loadu_si128( (__m128i*)input ), _mm_loadu_si128( rk++ ) );
if (mode == AES_ENCRYPT)
{
for (i = ctx->nr - 1; i; --i)
a = _mm_aesenc_si128( a, _mm_loadu_si128( rk++ ) );
a = _mm_aesenclast_si128( a, _mm_loadu_si128( rk ) );
}
else
{
for (i = ctx->nr - 1; i; --i)
a = _mm_aesdec_si128( a, _mm_loadu_si128( rk++ ) );
a = _mm_aesdeclast_si128( a, _mm_loadu_si128( rk ) );
}
_mm_storeu_si128( (__m128i*)output, a );
#else
asm( "movdqu (%3), %%xmm0 \n" // load input
"movdqu (%1), %%xmm1 \n" // load round key 0
"pxor %%xmm1, %%xmm0 \n" // round 0
"addq $16, %1 \n" // point to next round key
"subl $1, %0 \n" // normal rounds = nr - 1
"test %2, %2 \n" // mode?
"jz 2f \n" // 0 = decrypt
"1: \n" // encryption loop
"movdqu (%1), %%xmm1 \n" // load round key
"aesenc %%xmm1, %%xmm0 \n" // do round
"addq $16, %1 \n" // point to next round key
"subl $1, %0 \n" // loop
"jnz 1b \n"
"movdqu (%1), %%xmm1 \n" // load round key
"aesenclast %%xmm1, %%xmm0 \n" // last round
"jmp 3f \n"
"2: \n" // decryption loop
"movdqu (%1), %%xmm1 \n"
"aesdec %%xmm1, %%xmm0 \n"
"addq $16, %1 \n"
"subl $1, %0 \n"
"jnz 2b \n"
"movdqu (%1), %%xmm1 \n" // load round key
"aesdeclast %%xmm1, %%xmm0 \n" // last round
"3: \n"
"movdqu %%xmm0, (%4) \n" // export output
:
: "r" (ctx->nr), "r" (ctx->rk), "r" (mode), "r" (input), "r" (output)
: "memory", "cc", "xmm0", "xmm1" );
#endif /* POLARSSL_HAVE_MSVC_X64_INTRINSICS */
return( 0 );
}
#if defined(POLARSSL_HAVE_MSVC_X64_INTRINSICS)
static inline void clmul256( __m128i a, __m128i b, __m128i* r0, __m128i* r1 )
{
__m128i c, d, e, f, ef;
c = _mm_clmulepi64_si128( a, b, 0x00 );
d = _mm_clmulepi64_si128( a, b, 0x11 );
e = _mm_clmulepi64_si128( a, b, 0x10 );
f = _mm_clmulepi64_si128( a, b, 0x01 );
// r0 = f0^e0^c1:c0 = c1:c0 ^ f0^e0:0
// r1 = d1:f1^e1^d0 = d1:d0 ^ 0:f1^e1
ef = _mm_xor_si128( e, f );
*r0 = _mm_xor_si128( c, _mm_slli_si128( ef, 8 ) );
*r1 = _mm_xor_si128( d, _mm_srli_si128( ef, 8 ) );
}
static inline void sll256( __m128i a0, __m128i a1, __m128i* s0, __m128i* s1 )
{
__m128i l0, l1, r0, r1;
l0 = _mm_slli_epi64( a0, 1 );
l1 = _mm_slli_epi64( a1, 1 );
r0 = _mm_srli_epi64( a0, 63 );
r1 = _mm_srli_epi64( a1, 63 );
*s0 = _mm_or_si128( l0, _mm_slli_si128( r0, 8 ) );
*s1 = _mm_or_si128( _mm_or_si128( l1, _mm_srli_si128( r0, 8 ) ), _mm_slli_si128( r1, 8 ) );
}
static inline __m128i reducemod128( __m128i x10, __m128i x32 )
{
__m128i a, b, c, dx0, e, f, g, h;
// (1) left shift x0 by 63, 62 and 57
a = _mm_slli_epi64( x10, 63 );
b = _mm_slli_epi64( x10, 62 );
c = _mm_slli_epi64( x10, 57 );
// (2) compute D xor'ing a, b, c and x1
// d:x0 = x1:x0 ^ [a^b^c:0]
dx0 = _mm_xor_si128( x10, _mm_slli_si128( _mm_xor_si128( _mm_xor_si128( a, b ), c ), 8 ) );
// (3) right shift [d:x0] by 1, 2, 7
e = _mm_or_si128( _mm_srli_epi64( dx0, 1 ), _mm_srli_si128( _mm_slli_epi64( dx0, 63 ), 8 ) );
f = _mm_or_si128( _mm_srli_epi64( dx0, 2 ), _mm_srli_si128( _mm_slli_epi64( dx0, 62 ), 8 ) );
g = _mm_or_si128( _mm_srli_epi64( dx0, 7 ), _mm_srli_si128( _mm_slli_epi64( dx0, 57 ), 8 ) );
// (4) compute h = d^e1^f1^g1 : x0^e0^f0^g0
h = _mm_xor_si128( dx0, _mm_xor_si128( e, _mm_xor_si128( f, g ) ) );
// result is x3^h1:x2^h0
return _mm_xor_si128( x32, h );
}
#endif /* POLARSSL_HAVE_MSVC_X64_INTRINSICS */
/*
* GCM multiplication: c = a times b in GF(2^128)
* Based on [CLMUL-WP] algorithms 1 (with equation 27) and 5.
*/
void aesni_gcm_mult( unsigned char c[16],
const unsigned char a[16],
const unsigned char b[16] )
{
#if defined(POLARSSL_HAVE_MSVC_X64_INTRINSICS)
__m128i xa, xb, m0, m1, x10, x32, r;
xa.m128i_u64[1] = _byteswap_uint64( *((unsigned __int64*)a + 0) );
xa.m128i_u64[0] = _byteswap_uint64( *((unsigned __int64*)a + 1) );
xb.m128i_u64[1] = _byteswap_uint64( *((unsigned __int64*)b + 0) );
xb.m128i_u64[0] = _byteswap_uint64( *((unsigned __int64*)b + 1) );
clmul256( xa, xb, &m0, &m1 );
sll256( m0, m1, &x10, &x32 );
r = reducemod128( x10, x32 );
*((unsigned __int64*)c + 0) = _byteswap_uint64( r.m128i_u64[1] );
*((unsigned __int64*)c + 1) = _byteswap_uint64( r.m128i_u64[0] );
#else
unsigned char aa[16], bb[16], cc[16];
size_t i;
/* The inputs are in big-endian order, so byte-reverse them */
for( i = 0; i < 16; i++ )
{
aa[i] = a[15 - i];
bb[i] = b[15 - i];
}
asm( "movdqu (%0), %%xmm0 \n" // a1:a0
"movdqu (%1), %%xmm1 \n" // b1:b0
/*
* Caryless multiplication xmm2:xmm1 = xmm0 * xmm1
* using [CLMUL-WP] algorithm 1 (p. 13).
*/
"movdqa %%xmm1, %%xmm2 \n" // copy of b1:b0
"movdqa %%xmm1, %%xmm3 \n" // same
"movdqa %%xmm1, %%xmm4 \n" // same
"pclmulqdq $0x00, %%xmm0, %%xmm1 \n" // a0*b0 = c1:c0
"pclmulqdq $0x11, %%xmm0, %%xmm2 \n" // a1*b1 = d1:d0
"pclmulqdq $0x10, %%xmm0, %%xmm3 \n" // a0*b1 = e1:e0
"pclmulqdq $0x01, %%xmm0, %%xmm4 \n" // a1*b0 = f1:f0
"pxor %%xmm3, %%xmm4 \n" // e1+f1:e0+f0
"movdqa %%xmm4, %%xmm3 \n" // same
"psrldq $8, %%xmm4 \n" // 0:e1+f1
"pslldq $8, %%xmm3 \n" // e0+f0:0
"pxor %%xmm4, %%xmm2 \n" // d1:d0+e1+f1
"pxor %%xmm3, %%xmm1 \n" // c1+e0+f1:c0
/*
* Now shift the result one bit to the left,
* taking advantage of [CLMUL-WP] eq 27 (p. 20)
*/
"movdqa %%xmm1, %%xmm3 \n" // r1:r0
"movdqa %%xmm2, %%xmm4 \n" // r3:r2
"psllq $1, %%xmm1 \n" // r1<<1:r0<<1
"psllq $1, %%xmm2 \n" // r3<<1:r2<<1
"psrlq $63, %%xmm3 \n" // r1>>63:r0>>63
"psrlq $63, %%xmm4 \n" // r3>>63:r2>>63
"movdqa %%xmm3, %%xmm5 \n" // r1>>63:r0>>63
"pslldq $8, %%xmm3 \n" // r0>>63:0
"pslldq $8, %%xmm4 \n" // r2>>63:0
"psrldq $8, %%xmm5 \n" // 0:r1>>63
"por %%xmm3, %%xmm1 \n" // r1<<1|r0>>63:r0<<1
"por %%xmm4, %%xmm2 \n" // r3<<1|r2>>62:r2<<1
"por %%xmm5, %%xmm2 \n" // r3<<1|r2>>62:r2<<1|r1>>63
/*
* Now reduce modulo the GCM polynomial x^128 + x^7 + x^2 + x + 1
* using [CLMUL-WP] algorithm 5 (p. 20).
* Currently xmm2:xmm1 holds x3:x2:x1:x0 (already shifted).
*/
/* Step 2 (1) */
"movdqa %%xmm1, %%xmm3 \n" // x1:x0
"movdqa %%xmm1, %%xmm4 \n" // same
"movdqa %%xmm1, %%xmm5 \n" // same
"psllq $63, %%xmm3 \n" // x1<<63:x0<<63 = stuff:a
"psllq $62, %%xmm4 \n" // x1<<62:x0<<62 = stuff:b
"psllq $57, %%xmm5 \n" // x1<<57:x0<<57 = stuff:c
/* Step 2 (2) */
"pxor %%xmm4, %%xmm3 \n" // stuff:a+b
"pxor %%xmm5, %%xmm3 \n" // stuff:a+b+c
"pslldq $8, %%xmm3 \n" // a+b+c:0
"pxor %%xmm3, %%xmm1 \n" // x1+a+b+c:x0 = d:x0
/* Steps 3 and 4 */
"movdqa %%xmm1,%%xmm0 \n" // d:x0
"movdqa %%xmm1,%%xmm4 \n" // same
"movdqa %%xmm1,%%xmm5 \n" // same
"psrlq $1, %%xmm0 \n" // e1:x0>>1 = e1:e0'
"psrlq $2, %%xmm4 \n" // f1:x0>>2 = f1:f0'
"psrlq $7, %%xmm5 \n" // g1:x0>>7 = g1:g0'
"pxor %%xmm4, %%xmm0 \n" // e1+f1:e0'+f0'
"pxor %%xmm5, %%xmm0 \n" // e1+f1+g1:e0'+f0'+g0'
// e0'+f0'+g0' is almost e0+f0+g0, except for some missing
// bits carried from d. Now get those bits back in.
"movdqa %%xmm1,%%xmm3 \n" // d:x0
"movdqa %%xmm1,%%xmm4 \n" // same
"movdqa %%xmm1,%%xmm5 \n" // same
"psllq $63, %%xmm3 \n" // d<<63:stuff
"psllq $62, %%xmm4 \n" // d<<62:stuff
"psllq $57, %%xmm5 \n" // d<<57:stuff
"pxor %%xmm4, %%xmm3 \n" // d<<63+d<<62:stuff
"pxor %%xmm5, %%xmm3 \n" // missing bits of d:stuff
"psrldq $8, %%xmm3 \n" // 0:missing bits of d
"pxor %%xmm3, %%xmm0 \n" // e1+f1+g1:e0+f0+g0
"pxor %%xmm1, %%xmm0 \n" // h1:h0
"pxor %%xmm2, %%xmm0 \n" // x3+h1:x2+h0
"movdqu %%xmm0, (%2) \n" // done
:
: "r" (aa), "r" (bb), "r" (cc)
: "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5" );
/* Now byte-reverse the outputs */
for( i = 0; i < 16; i++ )
c[i] = cc[15 - i];
#endif /* POLARSSL_HAVE_MSVC_X64_INTRINSICS */
return;
}
/*
* Compute decryption round keys from encryption round keys
*/
void aesni_inverse_key( unsigned char *invkey,
const unsigned char *fwdkey, int nr )
{
unsigned char *ik = invkey;
const unsigned char *fk = fwdkey + 16 * nr;
memcpy( ik, fk, 16 );
for( fk -= 16, ik += 16; fk > fwdkey; fk -= 16, ik += 16 )
#if defined(POLARSSL_HAVE_MSVC_X64_INTRINSICS)
_mm_storeu_si128( (__m128i*)ik, _mm_aesimc_si128( _mm_loadu_si128( (__m128i*)fk) ) );
#else
asm( "movdqu (%0), %%xmm0 \n"
"aesimc %%xmm0, %%xmm0 \n"
"movdqu %%xmm0, (%1) \n"
:
: "r" (fk), "r" (ik)
: "memory", "xmm0" );
#endif /* POLARSSL_HAVE_MSVC_X64_INTRINSICS */
memcpy( ik, fk, 16 );
}
#if defined(POLARSSL_HAVE_MSVC_X64_INTRINSICS)
inline static __m128i aes_key_128_assist( __m128i key, __m128i kg )
{
key = _mm_xor_si128( key, _mm_slli_si128( key, 4 ) );
key = _mm_xor_si128( key, _mm_slli_si128( key, 4 ) );
key = _mm_xor_si128( key, _mm_slli_si128( key, 4 ) );
kg = _mm_shuffle_epi32( kg, _MM_SHUFFLE( 3, 3, 3, 3 ) );
return _mm_xor_si128( key, kg );
}
// [AES-WP] Part of Fig. 25 page 32
inline static void aes_key_192_assist( __m128i* temp1, __m128i * temp3, __m128i kg )
{
__m128i temp4;
kg = _mm_shuffle_epi32( kg, 0x55 );
temp4 = _mm_slli_si128( *temp1, 0x4 );
*temp1 = _mm_xor_si128( *temp1, temp4 );
temp4 = _mm_slli_si128( temp4, 0x4 );
*temp1 = _mm_xor_si128( *temp1, temp4 );
temp4 = _mm_slli_si128( temp4, 0x4 );
*temp1 = _mm_xor_si128( *temp1, temp4 );
*temp1 = _mm_xor_si128( *temp1, kg );
kg = _mm_shuffle_epi32( *temp1, 0xff );
temp4 = _mm_slli_si128( *temp3, 0x4 );
*temp3 = _mm_xor_si128( *temp3, temp4 );
*temp3 = _mm_xor_si128( *temp3, kg );
}
// [AES-WP] Part of Fig. 26 page 34
inline static void aes_key_256_assist_1( __m128i* temp1, __m128i kg )
{
__m128i temp4;
kg = _mm_shuffle_epi32( kg, 0xff );
temp4 = _mm_slli_si128( *temp1, 0x4 );
*temp1 = _mm_xor_si128( *temp1, temp4 );
temp4 = _mm_slli_si128( temp4, 0x4 );
*temp1 = _mm_xor_si128( *temp1, temp4 );
temp4 = _mm_slli_si128( temp4, 0x4 );
*temp1 = _mm_xor_si128( *temp1, temp4 );
*temp1 = _mm_xor_si128( *temp1, kg );
}
inline static void aes_key_256_assist_2( __m128i* temp1, __m128i* temp3 )
{
__m128i temp2, temp4;
temp4 = _mm_aeskeygenassist_si128( *temp1, 0x0 );
temp2 = _mm_shuffle_epi32( temp4, 0xaa );
temp4 = _mm_slli_si128( *temp3, 0x4 );
*temp3 = _mm_xor_si128( *temp3, temp4 );
temp4 = _mm_slli_si128( temp4, 0x4 );
*temp3 = _mm_xor_si128( *temp3, temp4 );
temp4 = _mm_slli_si128( temp4, 0x4 );
*temp3 = _mm_xor_si128( *temp3, temp4 );
*temp3 = _mm_xor_si128( *temp3, temp2 );
}
#endif /* POLARSSL_HAVE_MSVC_X64_INTRINSICS */
/*
* Key expansion, 128-bit case
*/
static void aesni_setkey_enc_128( unsigned char *rk,
const unsigned char *key )
{
#if defined(POLARSSL_HAVE_MSVC_X64_INTRINSICS)
__m128i* xrk, k;
xrk = (__m128i*)rk;
#define EXPAND_ROUND(k, rcon) \
_mm_storeu_si128( xrk++, k ); \
k = aes_key_128_assist( k, _mm_aeskeygenassist_si128( k, rcon ) )
k = _mm_loadu_si128( (__m128i*)key );
EXPAND_ROUND( k, 0x01 );
EXPAND_ROUND( k, 0x02 );
EXPAND_ROUND( k, 0x04 );
EXPAND_ROUND( k, 0x08 );
EXPAND_ROUND( k, 0x10 );
EXPAND_ROUND( k, 0x20 );
EXPAND_ROUND( k, 0x40 );
EXPAND_ROUND( k, 0x80 );
EXPAND_ROUND( k, 0x1b );
EXPAND_ROUND( k, 0x36 );
_mm_storeu_si128( xrk, k );
#undef EXPAND_ROUND
#else
asm( "movdqu (%1), %%xmm0 \n" // copy the original key
"movdqu %%xmm0, (%0) \n" // as round key 0
"jmp 2f \n" // skip auxiliary routine
/*
* Finish generating the next round key.
*
* On entry xmm0 is r3:r2:r1:r0 and xmm1 is X:stuff:stuff:stuff
* with X = rot( sub( r3 ) ) ^ RCON.
*
* On exit, xmm0 is r7:r6:r5:r4
* with r4 = X + r0, r5 = r4 + r1, r6 = r5 + r2, r7 = r6 + r3
* and those are written to the round key buffer.
*/
"1: \n"
"pshufd $0xff, %%xmm1, %%xmm1 \n" // X:X:X:X
"pxor %%xmm0, %%xmm1 \n" // X+r3:X+r2:X+r1:r4
"pslldq $4, %%xmm0 \n" // r2:r1:r0:0
"pxor %%xmm0, %%xmm1 \n" // X+r3+r2:X+r2+r1:r5:r4
"pslldq $4, %%xmm0 \n" // etc
"pxor %%xmm0, %%xmm1 \n"
"pslldq $4, %%xmm0 \n"
"pxor %%xmm1, %%xmm0 \n" // update xmm0 for next time!
"add $16, %0 \n" // point to next round key
"movdqu %%xmm0, (%0) \n" // write it
"ret \n"
/* Main "loop" */
"2: \n"
"aeskeygenassist $0x01, %%xmm0, %%xmm1 \ncall 1b \n"
"aeskeygenassist $0x02, %%xmm0, %%xmm1 \ncall 1b \n"
"aeskeygenassist $0x04, %%xmm0, %%xmm1 \ncall 1b \n"
"aeskeygenassist $0x08, %%xmm0, %%xmm1 \ncall 1b \n"
"aeskeygenassist $0x10, %%xmm0, %%xmm1 \ncall 1b \n"
"aeskeygenassist $0x20, %%xmm0, %%xmm1 \ncall 1b \n"
"aeskeygenassist $0x40, %%xmm0, %%xmm1 \ncall 1b \n"
"aeskeygenassist $0x80, %%xmm0, %%xmm1 \ncall 1b \n"
"aeskeygenassist $0x1B, %%xmm0, %%xmm1 \ncall 1b \n"
"aeskeygenassist $0x36, %%xmm0, %%xmm1 \ncall 1b \n"
:
: "r" (rk), "r" (key)
: "memory", "cc", "0" );
#endif /* POLARSSL_HAVE_MSVC_X64_INTRINSICS */
}
/*
* Key expansion, 192-bit case
*/
static void aesni_setkey_enc_192( unsigned char *rk,
const unsigned char *key )
{
#if defined(POLARSSL_HAVE_MSVC_X64_INTRINSICS)
__m128i temp1, temp3;
__m128i *key_schedule = (__m128i*)rk;
temp1 = _mm_loadu_si128( (__m128i*)key );
temp3 = _mm_loadu_si128( (__m128i*)(key + 16) );
key_schedule[0] = temp1;
key_schedule[1] = temp3;
aes_key_192_assist( &temp1, &temp3, _mm_aeskeygenassist_si128(temp3, 0x1) );
key_schedule[1] = _mm_castpd_si128( _mm_shuffle_pd( _mm_castsi128_pd( key_schedule[1] ), _mm_castsi128_pd( temp1 ), 0 ) );
key_schedule[2] = _mm_castpd_si128( _mm_shuffle_pd( _mm_castsi128_pd( temp1 ), _mm_castsi128_pd( temp3 ), 1 ) );
aes_key_192_assist( &temp1, &temp3, _mm_aeskeygenassist_si128( temp3, 0x2 ) );
key_schedule[3] = temp1;
key_schedule[4] = temp3;
aes_key_192_assist( &temp1, &temp3, _mm_aeskeygenassist_si128( temp3, 0x4 ) );
key_schedule[4] = _mm_castpd_si128( _mm_shuffle_pd( _mm_castsi128_pd( key_schedule[4] ), _mm_castsi128_pd( temp1 ), 0 ) );
key_schedule[5] = _mm_castpd_si128( _mm_shuffle_pd( _mm_castsi128_pd( temp1 ), _mm_castsi128_pd( temp3 ), 1 ) );
aes_key_192_assist( &temp1, &temp3, _mm_aeskeygenassist_si128( temp3, 0x8 ) );
key_schedule[6] = temp1;
key_schedule[7] = temp3;
aes_key_192_assist( &temp1, &temp3, _mm_aeskeygenassist_si128( temp3, 0x10 ) );
key_schedule[7] = _mm_castpd_si128( _mm_shuffle_pd( _mm_castsi128_pd( key_schedule[7] ), _mm_castsi128_pd( temp1 ), 0 ) );
key_schedule[8] = _mm_castpd_si128( _mm_shuffle_pd( _mm_castsi128_pd( temp1 ), _mm_castsi128_pd( temp3 ), 1 ) );
aes_key_192_assist( &temp1, &temp3, _mm_aeskeygenassist_si128( temp3, 0x20 ) );
key_schedule[9] = temp1;
key_schedule[10] = temp3;
aes_key_192_assist( &temp1, &temp3, _mm_aeskeygenassist_si128( temp3, 0x40 ) );
key_schedule[10] = _mm_castpd_si128( _mm_shuffle_pd( _mm_castsi128_pd( key_schedule[10] ), _mm_castsi128_pd( temp1 ), 0 ) );
key_schedule[11] = _mm_castpd_si128( _mm_shuffle_pd( _mm_castsi128_pd( temp1 ), _mm_castsi128_pd( temp3 ), 1 ) );
aes_key_192_assist( &temp1, &temp3, _mm_aeskeygenassist_si128( temp3, 0x80 ) );
key_schedule[12] = temp1;
#else
asm( "movdqu (%1), %%xmm0 \n" // copy original round key
"movdqu %%xmm0, (%0) \n"
"add $16, %0 \n"
"movq 16(%1), %%xmm1 \n"
"movq %%xmm1, (%0) \n"
"add $8, %0 \n"
"jmp 2f \n" // skip auxiliary routine
/*
* Finish generating the next 6 quarter-keys.
*
* On entry xmm0 is r3:r2:r1:r0, xmm1 is stuff:stuff:r5:r4
* and xmm2 is stuff:stuff:X:stuff with X = rot( sub( r3 ) ) ^ RCON.
*
* On exit, xmm0 is r9:r8:r7:r6 and xmm1 is stuff:stuff:r11:r10
* and those are written to the round key buffer.
*/
"1: \n"
"pshufd $0x55, %%xmm2, %%xmm2 \n" // X:X:X:X
"pxor %%xmm0, %%xmm2 \n" // X+r3:X+r2:X+r1:r4
"pslldq $4, %%xmm0 \n" // etc
"pxor %%xmm0, %%xmm2 \n"
"pslldq $4, %%xmm0 \n"
"pxor %%xmm0, %%xmm2 \n"
"pslldq $4, %%xmm0 \n"
"pxor %%xmm2, %%xmm0 \n" // update xmm0 = r9:r8:r7:r6
"movdqu %%xmm0, (%0) \n"
"add $16, %0 \n"
"pshufd $0xff, %%xmm0, %%xmm2 \n" // r9:r9:r9:r9
"pxor %%xmm1, %%xmm2 \n" // stuff:stuff:r9+r5:r10
"pslldq $4, %%xmm1 \n" // r2:r1:r0:0
"pxor %%xmm2, %%xmm1 \n" // update xmm1 = stuff:stuff:r11:r10
"movq %%xmm1, (%0) \n"
"add $8, %0 \n"
"ret \n"
"2: \n"
"aeskeygenassist $0x01, %%xmm1, %%xmm2 \ncall 1b \n"
"aeskeygenassist $0x02, %%xmm1, %%xmm2 \ncall 1b \n"
"aeskeygenassist $0x04, %%xmm1, %%xmm2 \ncall 1b \n"
"aeskeygenassist $0x08, %%xmm1, %%xmm2 \ncall 1b \n"
"aeskeygenassist $0x10, %%xmm1, %%xmm2 \ncall 1b \n"
"aeskeygenassist $0x20, %%xmm1, %%xmm2 \ncall 1b \n"
"aeskeygenassist $0x40, %%xmm1, %%xmm2 \ncall 1b \n"
"aeskeygenassist $0x80, %%xmm1, %%xmm2 \ncall 1b \n"
:
: "r" (rk), "r" (key)
: "memory", "cc", "0" );
#endif /* POLARSSL_HAVE_MSVC_X64_INTRINSICS */
}
/*
* Key expansion, 256-bit case
*/
static void aesni_setkey_enc_256( unsigned char *rk,
const unsigned char *key )
{
#if defined(POLARSSL_HAVE_MSVC_X64_INTRINSICS)
__m128i temp1, temp3;
__m128i *key_schedule = (__m128i*)rk;
temp1 = _mm_loadu_si128( (__m128i*)key );
temp3 = _mm_loadu_si128( (__m128i*)(key + 16) );
key_schedule[0] = temp1;
key_schedule[1] = temp3;
aes_key_256_assist_1( &temp1, _mm_aeskeygenassist_si128( temp3, 0x01 ) );
key_schedule[2] = temp1;
aes_key_256_assist_2( &temp1, &temp3 );
key_schedule[3] = temp3;
aes_key_256_assist_1( &temp1, _mm_aeskeygenassist_si128( temp3, 0x02 ) );
key_schedule[4] = temp1;
aes_key_256_assist_2( &temp1, &temp3 );
key_schedule[5] = temp3;
aes_key_256_assist_1( &temp1, _mm_aeskeygenassist_si128( temp3, 0x04 ) );
key_schedule[6] = temp1;
aes_key_256_assist_2( &temp1, &temp3 );
key_schedule[7] = temp3;
aes_key_256_assist_1( &temp1, _mm_aeskeygenassist_si128( temp3, 0x08 ) );
key_schedule[8] = temp1;
aes_key_256_assist_2( &temp1, &temp3 );
key_schedule[9] = temp3;
aes_key_256_assist_1( &temp1, _mm_aeskeygenassist_si128( temp3, 0x10 ) );
key_schedule[10] = temp1;
aes_key_256_assist_2( &temp1, &temp3 );
key_schedule[11] = temp3;
aes_key_256_assist_1( &temp1, _mm_aeskeygenassist_si128( temp3, 0x20 ) );
key_schedule[12] = temp1;
aes_key_256_assist_2( &temp1, &temp3 );
key_schedule[13] = temp3;
aes_key_256_assist_1( &temp1, _mm_aeskeygenassist_si128( temp3, 0x40 ) );
key_schedule[14] = temp1;
#else
asm( "movdqu (%1), %%xmm0 \n"
"movdqu %%xmm0, (%0) \n"
"add $16, %0 \n"
"movdqu 16(%1), %%xmm1 \n"
"movdqu %%xmm1, (%0) \n"
"jmp 2f \n" // skip auxiliary routine
/*
* Finish generating the next two round keys.
*
* On entry xmm0 is r3:r2:r1:r0, xmm1 is r7:r6:r5:r4 and
* xmm2 is X:stuff:stuff:stuff with X = rot( sub( r7 )) ^ RCON
*
* On exit, xmm0 is r11:r10:r9:r8 and xmm1 is r15:r14:r13:r12
* and those have been written to the output buffer.
*/
"1: \n"
"pshufd $0xff, %%xmm2, %%xmm2 \n"
"pxor %%xmm0, %%xmm2 \n"
"pslldq $4, %%xmm0 \n"
"pxor %%xmm0, %%xmm2 \n"
"pslldq $4, %%xmm0 \n"
"pxor %%xmm0, %%xmm2 \n"
"pslldq $4, %%xmm0 \n"
"pxor %%xmm2, %%xmm0 \n"
"add $16, %0 \n"
"movdqu %%xmm0, (%0) \n"
/* Set xmm2 to stuff:Y:stuff:stuff with Y = subword( r11 )
* and proceed to generate next round key from there */
"aeskeygenassist $0, %%xmm0, %%xmm2\n"
"pshufd $0xaa, %%xmm2, %%xmm2 \n"
"pxor %%xmm1, %%xmm2 \n"
"pslldq $4, %%xmm1 \n"
"pxor %%xmm1, %%xmm2 \n"
"pslldq $4, %%xmm1 \n"
"pxor %%xmm1, %%xmm2 \n"
"pslldq $4, %%xmm1 \n"
"pxor %%xmm2, %%xmm1 \n"
"add $16, %0 \n"
"movdqu %%xmm1, (%0) \n"
"ret \n"
/*
* Main "loop" - Generating one more key than necessary,
* see definition of aes_context.buf
*/
"2: \n"
"aeskeygenassist $0x01, %%xmm1, %%xmm2 \ncall 1b \n"
"aeskeygenassist $0x02, %%xmm1, %%xmm2 \ncall 1b \n"
"aeskeygenassist $0x04, %%xmm1, %%xmm2 \ncall 1b \n"
"aeskeygenassist $0x08, %%xmm1, %%xmm2 \ncall 1b \n"
"aeskeygenassist $0x10, %%xmm1, %%xmm2 \ncall 1b \n"
"aeskeygenassist $0x20, %%xmm1, %%xmm2 \ncall 1b \n"
"aeskeygenassist $0x40, %%xmm1, %%xmm2 \ncall 1b \n"
:
: "r" (rk), "r" (key)
: "memory", "cc", "0" );
#endif /* POLARSSL_HAVE_MSVC_X64_INTRINSICS */
}
/*
* Key expansion, wrapper
*/
int aesni_setkey_enc( unsigned char *rk,
const unsigned char *key,
size_t bits )
{
switch( bits )
{
case 128: aesni_setkey_enc_128( rk, key ); break;
case 192: aesni_setkey_enc_192( rk, key ); break;
case 256: aesni_setkey_enc_256( rk, key ); break;
default : return( POLARSSL_ERR_AES_INVALID_KEY_LENGTH );
}
return( 0 );
}
#endif
| 27,351
|
C++
|
.cpp
| 617
| 37.319287
| 140
| 0.491956
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
5,031
|
unzip.cpp
|
RPCS3_rpcs3/rpcs3/Crypto/unzip.cpp
|
#include "stdafx.h"
#include "unzip.h"
#include <zlib.h>
#include "util/serialization_ext.hpp"
std::vector<u8> unzip(const void* src, usz size)
{
if (!src || !size) [[unlikely]]
{
return {};
}
std::vector<uchar> out(size * 6);
z_stream zs{};
#ifndef _MSC_VER
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif
int res = inflateInit2(&zs, 16 + 15);
if (res != Z_OK)
{
return {};
}
#ifndef _MSC_VER
#pragma GCC diagnostic pop
#endif
zs.avail_in = static_cast<uInt>(size);
zs.next_in = reinterpret_cast<const u8*>(src);
zs.avail_out = static_cast<uInt>(out.size());
zs.next_out = out.data();
while (zs.avail_in)
{
switch (inflate(&zs, Z_FINISH))
{
case Z_OK:
case Z_STREAM_END:
break;
case Z_BUF_ERROR:
if (zs.avail_in)
break;
[[fallthrough]];
default:
inflateEnd(&zs);
return out;
}
if (zs.avail_in)
{
const auto cur_size = zs.next_out - out.data();
out.resize(out.size() + 65536);
zs.avail_out = static_cast<uInt>(out.size() - cur_size);
zs.next_out = &out[cur_size];
}
}
out.resize(zs.next_out - out.data());
res = inflateEnd(&zs);
return out;
}
bool unzip(const void* src, usz size, fs::file& out)
{
if (!src || !size || !out)
{
return false;
}
bool is_valid = true;
constexpr usz BUFSIZE = 32ULL * 1024ULL;
std::vector<u8> tempbuf(BUFSIZE);
z_stream strm{};
strm.avail_in = ::narrow<uInt>(size);
strm.avail_out = static_cast<uInt>(tempbuf.size());
strm.next_in = reinterpret_cast<const u8*>(src);
strm.next_out = tempbuf.data();
#ifndef _MSC_VER
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif
int res = inflateInit(&strm);
if (res != Z_OK)
{
return false;
}
#ifndef _MSC_VER
#pragma GCC diagnostic pop
#endif
while (strm.avail_in)
{
res = inflate(&strm, Z_NO_FLUSH);
if (res == Z_STREAM_END)
break;
if (res != Z_OK)
is_valid = false;
if (strm.avail_out)
break;
if (out.write(tempbuf.data(), tempbuf.size()) != tempbuf.size())
{
is_valid = false;
}
strm.next_out = tempbuf.data();
strm.avail_out = static_cast<uInt>(tempbuf.size());
}
res = inflate(&strm, Z_FINISH);
if (res != Z_STREAM_END)
is_valid = false;
if (strm.avail_out < tempbuf.size())
{
const usz bytes_to_write = tempbuf.size() - strm.avail_out;
if (out.write(tempbuf.data(), bytes_to_write) != bytes_to_write)
{
is_valid = false;
}
}
res = inflateEnd(&strm);
return is_valid;
}
bool zip(const void* src, usz size, fs::file& out, bool multi_thread_it)
{
if (!src || !size || !out)
{
return false;
}
utils::serial compressor;
compressor.set_expect_little_data(!multi_thread_it || size < 0x40'0000);
compressor.m_file_handler = make_compressed_serialization_file_handler(out);
std::string_view buffer_view{static_cast<const char*>(src), size};
while (!buffer_view.empty())
{
if (!compressor.m_file_handler->is_valid())
{
return false;
}
const std::string_view slice = buffer_view.substr(0, 0x50'0000);
compressor(slice);
compressor.breathe();
buffer_view = buffer_view.substr(slice.size());
}
compressor.m_file_handler->finalize(compressor);
if (!compressor.m_file_handler->is_valid())
{
return false;
}
return true;
}
| 3,267
|
C++
|
.cpp
| 139
| 20.971223
| 77
| 0.673232
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,033
|
key_vault.cpp
|
RPCS3_rpcs3/rpcs3/Crypto/key_vault.cpp
|
#include "utils.h"
#include "aes.h"
#include "key_vault.h"
#include "util/logs.hpp"
LOG_CHANNEL(key_vault_log, "KEY_VAULT");
SELF_KEY::SELF_KEY(u64 ver_start, u64 ver_end, u16 rev, u32 type, const std::string& e, const std::string& r, const std::string& pb, const std::string& pr, u32 ct)
{
version_start = ver_start;
version_end = ver_end;
revision = rev;
self_type = type;
hex_to_bytes(erk, e.c_str(), 0);
hex_to_bytes(riv, r.c_str(), 0);
hex_to_bytes(pub, pb.c_str(), 0);
hex_to_bytes(priv, pr.c_str(), 0);
curve_type = ct;
}
KeyVault::KeyVault()
{
}
void KeyVault::LoadSelfLV0Keys()
{
sk_LV0_arr.clear();
sk_LV0_arr.emplace_back(0x0000000000000000, 0x0000000000000000, 0x0000, KEY_LV0,
"CA7A24EC38BDB45B98CCD7D363EA2AF0C326E65081E0630CB9AB2D215865878A",
"F9205F46F6021697E670F13DFA726212",
"A8FD6DB24532D094EFA08CB41C9A72287D905C6B27B42BE4AB925AAF4AFFF34D41EEB54DD128700D",
"001AD976FCDE86F5B8FF3E63EF3A7F94E861975BA3",
0x33);
}
void KeyVault::LoadSelfLDRKeys()
{
sk_LDR_arr.clear();
sk_LDR_arr.emplace_back(0x0000000000000000, 0x0000000000000000, 0x0000, KEY_LDR,
"C0CEFE84C227F75BD07A7EB846509F93B238E770DACB9FF4A388F812482BE21B",
"47EE7454E4774CC9B8960C7B59F4C14D",
"C2D4AAF319355019AF99D44E2B58CA29252C89123D11D6218F40B138CAB29B7101F3AEB72A975019",
"00C5B2BFA1A413DD16F26D31C0F2ED4720DCFB0670",
0x20);
}
void KeyVault::LoadSelfLV1Keys()
{
sk_LV1_arr.clear();
sk_LV1_arr.emplace_back(0x0003000000000000, 0x0003003100000000, 0x0000, KEY_LV1,
"B9F3F9E6107CFF2680A91E118C2403CF4A6F18F3C7EFD7D13D1AC4DB760BD222",
"B43661B9A79BAD9D8E2B046469CDA1E7",
"4C870BE86DDD996A92A3F7F404F33604244A1D02AB5B78BC9DAF030B78BE8867CF586171B7D45D20",
"002CC736C7AD06D264E9AB663EB1F35F5DC159248C",
0x33);
sk_LV1_arr.emplace_back(0x0003004000000000, 0x0003004200000000, 0x0000, KEY_LV1,
"B880593856C8C6D2037585626A12977F50DCFCF3F132D2C89AA6E670EAFC1646",
"A79B05D4E37B8117A95E6E7C14FB640E",
"7454C7CCBFC2F66C142D78A730A3A6F973CC0FB75A46FCBB390790138910A0CAC78E5E21F4DA3375",
"00033A699FDD2DA6CDD6CCC03B2C6145F998706F74",
0x34);
sk_LV1_arr.emplace_back(0x0003005000000000, 0x0003005000000000, 0x0000, KEY_LV1,
"1E8EEEA9E80A729F3FA52CF523B25941EA44B4155D94E5DADC5C5A77847620C7",
"E034D31A80316960024D1B3D3164FDC3",
"7E3A196f4A5879F3A7B091A2263F7C24E1716129B580566D308D9C2254B36AEE53DEF30EC85F8398",
"005815D17125D04C33790321DE29EB6241365100B5",
0x35);
sk_LV1_arr.emplace_back(0x0003005500000000, 0x0003005500000000, 0x0000, KEY_LV1,
"53ABDF84BE08B0351B734F2B97D2BE1621BC6C889E4362E5C70F39D6C3ED9F23",
"44E652661AC7584DBE08ECB810FB5FC0",
"733198A7759BC07326755BC9773A8A17C8A7043C7BDAB83D88E230512E2EA3852D7DA4263A7E97F9",
"004312C65347ACBE95CC306442FEFD0AF4C2935EB3",
0x05);
sk_LV1_arr.emplace_back(0x0003005600000000, 0x0003005600000000, 0x0000, KEY_LV1,
"48793EBDDA1AF65D737DA2FDA2DD104447A698F8A82CAAEE992831711BA94E83",
"15DCF3C67147A45D09DE7521EECA07A1",
"85A8868C320127F10B6598964C69221C086702021D31803520E21FDE4DBE827766BE41825CB7328C",
"",
0x07);
sk_LV1_arr.emplace_back(0x0003006000000000, 0x0003006100000000, 0x0000, KEY_LV1,
"5FF17D836E2C4AD69476E2614F64BDD05B9115389A9A6D055B5B544B1C34E3D5",
"DF0F50EC3C4743C5B17839D7B49F24A4",
"1CDABE30833823F461CA534104115FFF60010B710631E435A7D915E82AE88EDE667264656CB7062E",
"",
0x05);
sk_LV1_arr.emplace_back(0x0003006500000000, 0x0003006600000000, 0x0000, KEY_LV1,
"BD0621FA19383C3C72ECBC3B008F1CD55FFD7C3BB7510BF11AD0CF0FC2B70951",
"569AF3745E1E02E3E288273CDE244CD8",
"21E26F11C2D69478609DD1BD278CDFC940D90386455BA52FCD1FA7E27AC2AFA826C79A10193B625C",
"",
0x07);
sk_LV1_arr.emplace_back(0x0003007000000000, 0x0003007400000000, 0x0000, KEY_LV1,
"41A6E0039041E9D8AAF4EF2F2A2971248EDBD96A3985611ED7B4CE73EE4804FE",
"C8C98D5A5CE23AF5607A352AECACB0DC",
"4389664390265F96C1A882374C0F856364E33DB09BE124A4666F9A12F0DD9C811EDD55BA21ED0667",
"",
0x12);
sk_LV1_arr.emplace_back(0x0004000000000000, 0x0004001100000000, 0x0000, KEY_LV1,
"557EDF6C063F3272B0D44EEC12F418DA774815B5415597CC5F75C21E048BAD74",
"7144D7574937818517826227EF4AC0B4",
"085D38DBF9B757329EB862107929909D32FA1DAE60641BF4AC25319D7650597EE977F8E810FEEA96",
"",
0x13);
sk_LV1_arr.emplace_back(0x0004002000000000, 0xFFFFFFFFFFFFFFFF, 0x0000, KEY_LV1,
"10CEA04973FCCC12EC19924510822D8D4C41F657FD3D7E73F415A8D687421BCD",
"ED8699562C6AC65204FA166257E7FCF4",
"9AF86FC869C159FBB62F7D9674EE257ABF12E5A96D5875B4AA73C13C2BC13E2A4079F98B9B935EE2",
"",
0x14);
}
void KeyVault::LoadSelfLV2Keys()
{
sk_LV2_arr.clear();
sk_LV2_arr.emplace_back(0x0000000300000000, 0x0003003100000000, 0x0000, KEY_LV2,
"94303F69513572AB5AE17C8C2A1839D2C24C28F65389D3BBB11894CE23E0798F",
"9769BFD187B90990AE5FEA4E110B9CF5",
"AFAF5E96AF396CBB69071082C46A8F34A030E8EDB799E0A7BE00AA264DFF3AEBF7923920D559404D",
"0070ABF9361B02291829D479F56AB248203CD3EB46",
0x20);
sk_LV2_arr.emplace_back(0x0003004000000000, 0x0003004200000000, 0x0000, KEY_LV2,
"575B0A6C4B4F2760A03FE4189EBAF4D947279FD982B14070349098B08FF92C10",
"411CB18F460CE50CAF2C426D8F0D93C8",
"3FEE313954CB3039C321A7E33B97FFDEC8988A8B55759161B04DBF4731284E4A8191E3F17D32B0EA",
"0073076441A08CD179E5FACE349B86DA58B5B7BA78",
0x21);
sk_LV2_arr.emplace_back(0x0003005000000000, 0x0003005000000000, 0x0000, KEY_LV2,
"6DBD48D787C58803A8D724DA5ACF04FF8FCE91D7545D2322F2B7ABF57014AF68",
"603A36213708520ED5D745DEC1325BA5",
"5888CB83AC3CCA9610BC173C53141C0CA58B93719E744660CA8823D5EAEE8F9BF736997054E4B7E3",
"0009EBC3DE442FA5FBF6C4F3D4F9EAB07778A142BD",
0x22);
sk_LV2_arr.emplace_back(0x0003005500000000, 0x0003005500000000, 0x0000, KEY_LV2,
"84015E90FA23139628A3C75CC09714E6427B527A82D18ABC3E91CD8D7DDAFF17",
"5B240444D645F2038118F97FD5A145D5",
"B266318245266B2D33641CD8A864066D077FAC60B7E27399099A70A683454B70F9888E7CC0C2BF72",
"009D4CBA2BFB1A8330D3E20E59D281D476D231C73A",
0x32);
sk_LV2_arr.emplace_back(0x0003005600000000, 0x0003005600000000, 0x0000, KEY_LV2,
"EAE15444048EFDE7A831BFA9F5D96F047C9FCFF50723E292CF50F5417D81E359",
"9CA9282DC7FA9F315EF3156D970B7CD4",
"0D58938CB47598A6A672874F1768068F8B80D8D17014D2ABEBAC85E5B0993D9FB6F307DDC3DDA699",
"",
0x33);
sk_LV2_arr.emplace_back(0x0003006000000000, 0x0003006100000000, 0x0000, KEY_LV2,
"88AD367EDEC2FEED3E2F99B1C685075C41BDEC90C84F526CAF588F89BBD1CBCC",
"8D18E8E525230E63DE10291C9DD615BF",
"86EED1D65E58890ABDA9ACA486A2BDDB9C0A529C2053FAE301F0F698EAF443DA0F60595A597A7027",
"",
0x32);
sk_LV2_arr.emplace_back(0x0003006500000000, 0x0003006600000000, 0x0000, KEY_LV2,
"688D5FCAC6F4EA35AC6AC79B10506007286131EE038116DB8AA2C0B0340D9FB0",
"75E0239D18B0B669EAE650972F99726B",
"008E1C820AC567D1BFB8FE3CC6AD2E1845A1D1B19ED2E18B18CA34A8D28A83EC60C63859CDB3DACA",
"",
0x33);
sk_LV2_arr.emplace_back(0x0003007000000000, 0x0003007400000000, 0x0000, KEY_LV2,
"E81C5B04C29FB079A4A2687A39D4EA97BFB49D80EF546CEB292979A5F77A6254",
"15058FA7F2CAD7C528B5F605F6444EB0",
"438D0E5C1E7AFB18234DB6867472FF5F52B750F30C379C7DD1EE0FD23E417B3EA819CC01BAC480ED",
"",
0x11);
sk_LV2_arr.emplace_back(0x0004001000000000, 0x0004001100000000, 0x0000, KEY_LV2,
"A1E4B86ED02BF7F1372A2C73FE02BC738907EB37CE3BA605FE783C999FAFDB97",
"BBE7799B9A37CB272E386618FDFD4AEC",
"5B31A8E2A663EBD673196E2E1022E0D64988C4E1BBFE5E474415883A3BA0D9C562A2BE9C30E9B4A8",
"",
0x07);
sk_LV2_arr.emplace_back(0x0004002000000000, 0xFFFFFFFFFFFFFFFF, 0x0000, KEY_LV2,
"0CAF212B6FA53C0DA7E2C575ADF61DBE68F34A33433B1B891ABF5C4251406A03",
"9B79374722AD888EB6A35A2DF25A8B3E",
"1034A6F98AF6625CC3E3604B59B971CA617DF337538D2179EBB22F3BDC9D0C6DA56BA7DDFD205A50",
"",
0x14);
}
void KeyVault::LoadSelfISOKeys()
{
sk_ISO_arr.clear();
sk_ISO_arr.emplace_back(0x0000006000000000, 0x0003003000000000, 0x0001, KEY_ISO,
"8860D0CFF4D0DC688D3223321B96B59A777E6914961488E07048DAECB020ECA4",
"C82D015D46CF152F1DD0C16F18B5B1E5",
"733918D7C888130509346E6B4A8B6CAA357AB557E814E8122BF102C14A314BF9475B9D70EAF9EC29",
"009BE892E122A5C943C1BB7403A67318AA9E1B286F",
0x36);
sk_ISO_arr.emplace_back(0x0003004000000000, 0x0003004200000000, 0x0001, KEY_ISO,
"101E27F3FA2FB53ACA924F783AD553162D56B975D05B81351A1111799F20254D",
"8D2E9C6297B8AD252998458296AC773C",
"138446EE0BDDA5638F97328C8956E6489CBBFE57C5961D40DD5C43BB4138F1C400A8B27204A5D625",
"00849DBC57D3B92F01864E6E82EB4EF0EF6311E122",
0x32);
sk_ISO_arr.emplace_back(0x0003005000000000, 0x0003005000000000, 0x0001, KEY_ISO,
"3F2604FA27AEADFBE1AC69EB00BB16EF196C2193CBD62900FFD8C25041680843",
"A414AC1DB7987E43777651B330B899E1",
"1F4633AFDE18614D6CEF38A2FD6C4CCAC7B6EB8109D72CD066ECEBA0193EA3F43C37AE83179A4E5F",
"0085B4B05DEBA7E6AD831653C974D95149803BB272",
0x33);
sk_ISO_arr.emplace_back(0x0003005500000000, 0x0003005500000000, 0x0001, KEY_ISO,
"BDB74AA6E3BA2DC10B1BD7F17198399A158DBE1FA0BEA68C90FCACBE4D04BE37",
"0207A479B1574F8E7F697528F05D5435",
"917E1F1DC48A54EB5F10B38E7569BB5383628A7C906F0DCA62FDA33805C15FAB270016940A09DB58",
"00294411363290975BA551336D3965D88AF029A17B",
0x03);
sk_ISO_arr.emplace_back(0x0003005600000000, 0x0003005600000000, 0x0001, KEY_ISO,
"311C015F169F2A1E0757F7064B14C7C9F3A3FFEE015BD4E3A22401A2667857CE",
"7BB8B3F5AC8E0890E3148AE5688C7350",
"3F040EFA2335FED5670BA4D5C3AB2D9D0B4BA69D154A0062EA995A7D21DBAF0DC5A0DAD333D1C1DD",
"",
0x08);
sk_ISO_arr.emplace_back(0x0003006000000000, 0x0003006100000000, 0x0001, KEY_ISO,
"8474ADCA3B3244931EECEB9357841442442A1C4A4BCF4E498E6738950F4E4093",
"FFF9CACCC4129125CAFB240F419E5F39",
"098E1A53E59A95316B00D5A29C05FFEBAE41D1A8A386F9DA96F98858FD25E07BB7A3BC96A5D5B556",
"",
0x03);
sk_ISO_arr.emplace_back(0x0003006500000000, 0x0003006600000000, 0x0001, KEY_ISO,
"E6A21C599B75696C169EC02582BDA74A776134A6E05108EA701EC0CA2AC03592",
"D292A7BD57C0BB2EABBCA1252FA9EDEF",
"2ED078A13DC4617EB550AD06E228C83C142A2D588EB5E729402D18038A14842FD65B277DCAD225A5",
"",
0x08);
sk_ISO_arr.emplace_back(0x0003007000000000, 0x0003007400000000, 0x0001, KEY_ISO,
"072D3A5C3BDB0D674DE209381432B20414BC9BDA0F583ECB94BD9A134176DD51",
"8516A81F02CF938740498A406C880871",
"5A778DEB5C4F12E8D48E06A2BBBBE3C90FA8C6C47DF9BDB5697FD4A8EB7941CE3F59A557E81C787D",
"",
0x21);
sk_ISO_arr.emplace_back(0x0003007000000000, 0x0003007400000000, 0x0100, KEY_ISO,
"786FAB8A0B89474A2CB80B3EA104CCCB9E13F66B45EC499BB31865D07C661EA8",
"94662F13D99A9F5D211C979FFDF65FE3",
"912C94C252B7799CEB45DFBB73EF7CAD9BCC0793A3331BBB79E3C47C0F5C782F698065A8D4DB0D8B",
"",
0x0E);
sk_ISO_arr.emplace_back(0x0004001000000000, 0x0004001100000000, 0x0001, KEY_ISO,
"4262657A3185D9480F82C8BD2F81766FCC2C8FD7DD5EBE8657B00B939E0C75BD",
"4F1E3EF07D893A4714B1B3D5A4E50479",
"4DBFCFA68B52F1D66E09AFA6C18EC65479EDBD027B6B8C6A5D85FE5C84D43EA40CEF1672078A0702",
"",
0x11);
sk_ISO_arr.emplace_back(0x0004001000000000, 0x0004001100000000, 0x0100, KEY_ISO,
"16AA7D7C35399E2B1BFAF68CD19D7512A7855029C08BECC4CC3F035DF7F9C70B",
"0E50DB6D937D262CB0499136852FCB80",
"AEE2795BF295662A50DFAFE70D1B0B6F0A2EBB211E1323A275FC6E2D13BE4F2F10CA34784F4CF1EC",
"",
0x0F);
sk_ISO_arr.emplace_back(0x0004002000000000, 0xFFFFFFFFFFFFFFFF, 0x0001, KEY_ISO,
"63565DBE98C3B1A52AADC907C47130FE57A10734E84F22592670F86ED2B0A086",
"953F6A99891B4739358F5363A00C08B9",
"26BE7B02E7D65C6C21BF4063CDB8C0092FE1679D62FA1A8CCC284A1D21885473A959992537A06612",
"",
0x15);
sk_ISO_arr.emplace_back(0x0004002000000000, 0xFFFFFFFFFFFFFFFF, 0x0100, KEY_ISO,
"B96EA32CB96EA32DB96EA32CB96EA32CB96EA32CB96EA32DB96EA32CB96EA32C",
"B96EA32CB96EA32DB96EA32DB96EA32C",
"2D7066E68C6AC3373B1346FD76FE7D18A207C811500E65D85DB57BC4A27AD78F59FD53F38F50E151",
"0044AA25B4276D79B494A29CB8DE104642424F8EEF",
0x02);
}
void KeyVault::LoadSelfAPPKeys()
{
sk_APP_arr.clear();
sk_APP_arr.emplace_back(0x0000009200000000, 0x0000009200000000, 0x0000, KEY_APP,
"95F50019E7A68E341FA72EFDF4D60ED376E25CF46BB48DFDD1F080259DC93F04",
"4A0955D946DB70D691A640BB7FAECC4C",
"6F8DF8EBD0A1D1DB08B30DD3A951E3F1F27E34030B42C729C55555232D61B834B8BDFFB07E54B343",
"006C3E4CCB2C69A5AD7C6F60448E50C7F9184EEAF4",
0x21);
sk_APP_arr.emplace_back(0x0003003000000000, 0x0003003000000000, 0x0001, KEY_APP,
"79481839C406A632BDB4AC093D73D99AE1587F24CE7E69192C1CD0010274A8AB",
"6F0F25E1C8C4B7AE70DF968B04521DDA",
"94D1B7378BAFF5DFED269240A7A364ED68446741622E50BC6079B6E606A2F8E0A4C56E5CFF836526",
"003DE80167D2F0E9D30F2145144A558D1174F5410C",
0x11);
sk_APP_arr.emplace_back(0x0003003000000000, 0x0003003000000000, 0x0002, KEY_APP,
"4F89BE98DDD43CAD343F5BA6B1A133B0A971566F770484AAC20B5DD1DC9FA06A",
"90C127A9B43BA9D8E89FE6529E25206F",
"8CA6905F46148D7D8D84D2AFCEAE61B41E6750FC22EA435DFA61FCE6F4F860EE4F54D9196CA5290E",
"",
0x13);
sk_APP_arr.emplace_back(0x0003003000000000, 0x0003003000000000, 0x0003, KEY_APP,
"C1E6A351FCED6A0636BFCB6801A0942DB7C28BDFC5E0A053A3F52F52FCE9754E",
"E0908163F457576440466ACAA443AE7C",
"50022D5D37C97905F898E78E7AA14A0B5CAAD5CE8190AE5629A10D6F0CF4173597B37A95A7545C92",
"",
0x0B);
sk_APP_arr.emplace_back(0x0003004200000000, 0x0003004200000000, 0x0004, KEY_APP,
"838F5860CF97CDAD75B399CA44F4C214CDF951AC795298D71DF3C3B7E93AAEDA",
"7FDBB2E924D182BB0D69844ADC4ECA5B",
"1F140E8EF887DAB52F079A06E6915A6460B75CD256834A43FA7AF90C23067AF412EDAFE2C1778D69",
"0074E922FDEE5DC4CDF22FC8D7986477F813400860",
0x14);
sk_APP_arr.emplace_back(0x0003004200000000, 0x0003004200000000, 0x0005, KEY_APP,
"C109AB56593DE5BE8BA190578E7D8109346E86A11088B42C727E2B793FD64BDC",
"15D3F191295C94B09B71EBDE088A187A",
"B6BB0A84C649A90D97EBA55B555366F52381BB38A84C8BB71DA5A5A0949043C6DB249029A43156F7",
"",
0x15);
sk_APP_arr.emplace_back(0x0003004200000000, 0x0003004200000000, 0x0006, KEY_APP,
"6DFD7AFB470D2B2C955AB22264B1FF3C67F180983B26C01615DE9F2ECCBE7F41",
"24BD1C19D2A8286B8ACE39E4A37801C2",
"71F46AC33FF89DF589A100A7FB64CEAC244C9A0CBBC1FDCE80FB4BF8A0D2E66293309CB8EE8CFA95",
"",
0x2C);
sk_APP_arr.emplace_back(0x0003005000000000, 0x0003005000000000, 0x0007, KEY_APP,
"945B99C0E69CAF0558C588B95FF41B232660ECB017741F3218C12F9DFDEEDE55",
"1D5EFBE7C5D34AD60F9FBC46A5977FCE",
"AB284CA549B2DE9AA5C903B75652F78D192F8F4A8F3CD99209415C0A84C5C9FD6BF3095C1C18FFCD",
"002CF896D35DB871D0E6A252E799876A70D043C23E",
0x15);
sk_APP_arr.emplace_back(0x0003005000000000, 0x0003005000000000, 0x0008, KEY_APP,
"2C9E8969EC44DFB6A8771DC7F7FDFBCCAF329EC3EC070900CABB23742A9A6E13",
"5A4CEFD5A9C3C093D0B9352376D19405",
"6E82F6B54A0E9DEBE4A8B3043EE3B24CD9BBB62B4416B0482582E419A2552E29AB4BEA0A4D7FA2D5",
"",
0x16);
sk_APP_arr.emplace_back(0x0003005000000000, 0x0003005000000000, 0x0009, KEY_APP,
"F69E4A2934F114D89F386CE766388366CDD210F1D8913E3B973257F1201D632B",
"F4D535069301EE888CC2A852DB654461",
"1D7B974D10E61C2ED087A0981535904677EC07E96260F89565FF7EBDA4EE035C2AA9BCBDD5893F99",
"",
0x2D);
sk_APP_arr.emplace_back(0x0003005500000000, 0x0003005500000000, 0x000A, KEY_APP,
"29805302E7C92F204009161CA93F776A072141A8C46A108E571C46D473A176A3",
"5D1FAB844107676ABCDFC25EAEBCB633",
"09301B6436C85B53CB1585300A3F1AF9FB14DB7C30088C4642AD66D5C148B8995BB1A698A8C71827",
"0010818ED8A666051C6198662C3D6DDE2CA4901DDC",
0x25);
sk_APP_arr.emplace_back(0x0003005500000000, 0x0003005500000000, 0x000B, KEY_APP,
"A4C97402CC8A71BC7748661FE9CE7DF44DCE95D0D58938A59F47B9E9DBA7BFC3",
"E4792F2B9DB30CB8D1596077A13FB3B5",
"2733C889D289550FE00EAA5A47A34CEF0C1AF187610EB07BA35D2C09BB73C80B244EB4147700D1BF",
"",
0x26);
sk_APP_arr.emplace_back(0x0003005500000000, 0x0003005500000000, 0x000C, KEY_APP,
"9814EFFF67B7074D1B263BF85BDC8576CE9DEC914123971B169472A1BC2387FA",
"D43B1FA8BE15714B3078C23908BB2BCA",
"7D1986C6BEE6CE1E0C5893BD2DF203881F40D5056761CC3F1F2E9D9A378617A2DE40BA5F09844CEB",
"",
0x3D);
sk_APP_arr.emplace_back(0x0003005600000000, 0x0003005600000000, 0x000D, KEY_APP,
"03B4C421E0C0DE708C0F0B71C24E3EE04306AE7383D8C5621394CCB99FF7A194",
"5ADB9EAFE897B54CB1060D6885BE22CF",
"71502ADB5783583AB88B2D5F23F419AF01C8B1E72FCA1E694AD49FE3266F1F9C61EFC6F29B351142",
"",
0x12);
sk_APP_arr.emplace_back(0x0003005600000000, 0x0003005600000000, 0x000E, KEY_APP,
"39A870173C226EB8A3EEE9CA6FB675E82039B2D0CCB22653BFCE4DB013BAEA03",
"90266C98CBAA06C1BF145FF760EA1B45",
"84DE5692809848E5ACBE25BE548F6981E3DB14735A5DDE1A0FD1F475866532B862B1AB6A004B7255",
"",
0x27);
sk_APP_arr.emplace_back(0x0003005600000000, 0x0003005600000000, 0x000F, KEY_APP,
"FD52DFA7C6EEF5679628D12E267AA863B9365E6DB95470949CFD235B3FCA0F3B",
"64F50296CF8CF49CD7C643572887DA0B",
"0696D6CCBD7CF585EF5E00D547503C185D7421581BAD196E081723CD0A97FA40B2C0CD2492B0B5A1",
"",
0x3A);
sk_APP_arr.emplace_back(0x0003006100000000, 0x0003006100000000, 0x0010, KEY_APP,
"A5E51AD8F32FFBDE808972ACEE46397F2D3FE6BC823C8218EF875EE3A9B0584F",
"7A203D5112F799979DF0E1B8B5B52AA4",
"50597B7F680DD89F6594D9BDC0CBEE03666AB53647D0487F7F452FE2DD02694631EA755548C9E934",
"",
0x25);
sk_APP_arr.emplace_back(0x0003006100000000, 0x0003006100000000, 0x0011, KEY_APP,
"0F8EAB8884A51D092D7250597388E3B8B75444AC138B9D36E5C7C5B8C3DF18FD",
"97AF39C383E7EF1C98FA447C597EA8FE",
"2FDA7A56AAEA65921C0284FF1942C6DE137370093D106034B59191951A5201B422D462F8726F852D",
"",
0x26);
sk_APP_arr.emplace_back(0x0003006600000000, 0x0003006600000000, 0x0013, KEY_APP,
"DBF62D76FC81C8AC92372A9D631DDC9219F152C59C4B20BFF8F96B64AB065E94",
"CB5DD4BE8CF115FFB25801BC6086E729",
"B26FE6D3E3A1E766FAE79A8E6A7F48998E7FC1E4B0AD8745FF54C018C2A6CC7A0DD7525FAFEA4917",
"",
0x12);
sk_APP_arr.emplace_back(0x0003006600000000, 0x0003006600000000, 0x0014, KEY_APP,
"491B0D72BB21ED115950379F4564CE784A4BFAABB00E8CB71294B192B7B9F88E",
"F98843588FED8B0E62D7DDCB6F0CECF4",
"04275E8838EF95BD013B223C3DF674540932F21B534C7ED2944B9104D938FEB03B824DDB866AB26E",
"",
0x27);
sk_APP_arr.emplace_back(0x0003007400000000, 0x0003007400000000, 0x0016, KEY_APP,
"A106692224F1E91E1C4EBAD4A25FBFF66B4B13E88D878E8CD072F23CD1C5BF7C",
"62773C70BD749269C0AFD1F12E73909E",
"566635D3E1DCEC47243AAD1628AE6B2CEB33463FC155E4635846CE33899C5E353DDFA47FEF5694AF",
"",
0x30);
sk_APP_arr.emplace_back(0x0003007400000000, 0x0003007400000000, 0x0017, KEY_APP,
"4E104DCE09BA878C75DA98D0B1636F0E5F058328D81419E2A3D22AB0256FDF46",
"954A86C4629E116532304A740862EF85",
"3B7B04C71CAE2B1199D57453C038BB1B541A05AD1B94167B0AB47A9B24CAECB9000CB21407009666",
"",
0x08);
sk_APP_arr.emplace_back(0x0003007400000000, 0x0003007400000000, 0x0018, KEY_APP,
"1F876AB252DDBCB70E74DC4A20CD8ED51E330E62490E652F862877E8D8D0F997",
"BF8D6B1887FA88E6D85C2EDB2FBEC147",
"64A04126D77BF6B4D686F6E8F87DD150A5B014BA922D2B694FFF4453E11239A6E0B58F1703C51494",
"",
0x11);
sk_APP_arr.emplace_back(0x0004001100000000, 0x0004001100000000, 0x0019, KEY_APP,
"3236B9937174DF1DC12EC2DD8A318A0EA4D3ECDEA5DFB4AC1B8278447000C297",
"6153DEE781B8ADDC6A439498B816DC46",
"148DCA961E2738BAF84B2D1B6E2DA2ABD6A95F2C9571E54C6922F9ED9674F062B7F1BE5BD6FA5268",
"",
0x31);
sk_APP_arr.emplace_back(0x0004001100000000, 0x0004001100000000, 0x001A, KEY_APP,
"5EFD1E9961462794E3B9EF2A4D0C1F46F642AAE053B5025504130590E66F19C9",
"1AC8FA3B3C90F8FDE639515F91B58327",
"BE4B1B513536960618BFEF12A713F6673881B02F9DC616191E823FC8337CCF99ADAA6172019C0C23",
"",
0x17);
sk_APP_arr.emplace_back(0x0004001100000000, 0x0004001100000000, 0x001B, KEY_APP,
"66637570D1DEC098467DB207BAEA786861964D0964D4DBAF89E76F46955D181B",
"9F7B5713A5ED59F6B35CD8F8A165D4B8",
"4AB6FB1F6F0C3D9219923C1AC683137AB05DF667833CC6A5E8F590E4E28FE2EB180C7D5861117CFB",
"",
0x12);
sk_APP_arr.emplace_back(0x0004004600000000, 0x0004004600000000, 0x001C, KEY_APP,
"CFF025375BA0079226BE01F4A31F346D79F62CFB643CA910E16CF60BD9092752",
"FD40664E2EBBA01BF359B0DCDF543DA4",
"36C1ACE6DD5CCC0006FDF3424750FAC515FC5CFA2C93EC53C6EC2BC421708D154E91F2E7EA54A893",
"",
0x09);
sk_APP_arr.emplace_back(0x0004004600000000, 0x0004004600000000, 0x001D, KEY_APP,
"D202174EB65A62048F3674B59EF6FE72E1872962F3E1CD658DE8D7AF71DA1F3E",
"ACB9945914EBB7B9A31ECE320AE09F2D",
"430322887503CF52928FAAA410FD623C7321281C8825D95F5B47EF078EFCFC44454C3AB4F00BB879",
"",
0x1A);
}
void KeyVault::LoadSelfNPDRMKeys()
{
sk_NPDRM_arr.clear();
sk_NPDRM_arr.emplace_back(0x0001000000000000, 0x0001000000000000, 0x0001, KEY_NPDRM,
"F9EDD0301F770FABBA8863D9897F0FEA6551B09431F61312654E28F43533EA6B",
"A551CCB4A42C37A734A2B4F9657D5540",
"B05F9DA5F9121EE4031467E74C505C29A8E29D1022379EDFF0500B9AE480B5DAB4578A4C61C5D6BF",
"00040AB47509BED04BD96521AD1B365B86BF620A98",
0x11);
sk_NPDRM_arr.emplace_back(0x0001000000000000, 0x0001000000000000, 0x0002, KEY_NPDRM,
"8E737230C80E66AD0162EDDD32F1F774EE5E4E187449F19079437A508FCF9C86",
"7AAECC60AD12AED90C348D8C11D2BED5",
"05BF09CB6FD78050C78DE69CC316FF27C9F1ED66A45BFCE0A1E5A6749B19BD546BBB4602CF373440",
"",
0x0A);
sk_NPDRM_arr.emplace_back(0x0003003000000000, 0x0003003000000000, 0x0003, KEY_NPDRM,
"1B715B0C3E8DC4C1A5772EBA9C5D34F7CCFE5B82025D453F3167566497239664",
"E31E206FBB8AEA27FAB0D9A2FFB6B62F",
"3F51E59FC74D6618D34431FA67987FA11ABBFACC7111811473CD9988FE91C43FC74605E7B8CB732D",
"",
0x08);
sk_NPDRM_arr.emplace_back(0x0003004200000000, 0x0003004200000000, 0x0004, KEY_NPDRM,
"BB4DBF66B744A33934172D9F8379A7A5EA74CB0F559BB95D0E7AECE91702B706",
"ADF7B207A15AC601110E61DDFC210AF6",
"9C327471BAFF1F877AE4FE29F4501AF5AD6A2C459F8622697F583EFCA2CA30ABB5CD45D1131CAB30",
"00B61A91DF4AB6A9F142C326BA9592B5265DA88856",
0x16);
sk_NPDRM_arr.emplace_back(0x0003004200000000, 0x0003004200000000, 0x0006, KEY_NPDRM,
"8B4C52849765D2B5FA3D5628AFB17644D52B9FFEE235B4C0DB72A62867EAA020",
"05719DF1B1D0306C03910ADDCE4AF887",
"2A5D6C6908CA98FC4740D834C6400E6D6AD74CF0A712CF1E7DAE806E98605CC308F6A03658F2970E",
"",
0x29);
sk_NPDRM_arr.emplace_back(0x0003005000000000, 0x0003005000000000, 0x0007, KEY_NPDRM,
"3946DFAA141718C7BE339A0D6C26301C76B568AEBC5CD52652F2E2E0297437C3",
"E4897BE553AE025CDCBF2B15D1C9234E",
"A13AFE8B63F897DA2D3DC3987B39389DC10BAD99DFB703838C4A0BC4E8BB44659C726CFD0CE60D0E",
"009EF86907782A318D4CC3617EBACE2480E73A46F6",
0x17);
sk_NPDRM_arr.emplace_back(0x0003005000000000, 0x0003005000000000, 0x0009, KEY_NPDRM,
"0786F4B0CA5937F515BDCE188F569B2EF3109A4DA0780A7AA07BD89C3350810A",
"04AD3C2F122A3B35E804850CAD142C6D",
"A1FE61035DBBEA5A94D120D03C000D3B2F084B9F4AFA99A2D4A588DF92B8F36327CE9E47889A45D0",
"",
0x2A);
sk_NPDRM_arr.emplace_back(0x0003005500000000, 0x0003005500000000, 0x000A, KEY_NPDRM,
"03C21AD78FBB6A3D425E9AAB1298F9FD70E29FD4E6E3A3C151205DA50C413DE4",
"0A99D4D4F8301A88052D714AD2FB565E",
"3995C390C9F7FBBAB124A1C14E70F9741A5E6BDF17A605D88239652C8EA7D5FC9F24B30546C1E44B",
"009AC6B22A056BA9E0B6D1520F28A57A3135483F9F",
0x27);
sk_NPDRM_arr.emplace_back(0x0003005500000000, 0x0003005500000000, 0x000C, KEY_NPDRM,
"357EBBEA265FAEC271182D571C6CD2F62CFA04D325588F213DB6B2E0ED166D92",
"D26E6DD2B74CD78E866E742E5571B84F",
"00DCF5391618604AB42C8CFF3DC304DF45341EBA4551293E9E2B68FFE2DF527FFA3BE8329E015E57",
"",
0x3A);
sk_NPDRM_arr.emplace_back(0x0003005600000000, 0x0003005600000000, 0x000D, KEY_NPDRM,
"337A51416105B56E40D7CAF1B954CDAF4E7645F28379904F35F27E81CA7B6957",
"8405C88E042280DBD794EC7E22B74002",
"9BFF1CC7118D2393DE50D5CF44909860683411A532767BFDAC78622DB9E5456753FE422CBAFA1DA1",
"",
0x18);
sk_NPDRM_arr.emplace_back(0x0003005600000000, 0x0003005600000000, 0x000F, KEY_NPDRM,
"135C098CBE6A3E037EBE9F2BB9B30218DDE8D68217346F9AD33203352FBB3291",
"4070C898C2EAAD1634A288AA547A35A8",
"BBD7CCCB556C2EF0F908DC7810FAFC37F2E56B3DAA5F7FAF53A4944AA9B841F76AB091E16B231433",
"",
0x3B);
sk_NPDRM_arr.emplace_back(0x0003006100000000, 0x0003006100000000, 0x0010, KEY_NPDRM,
"4B3CD10F6A6AA7D99F9B3A660C35ADE08EF01C2C336B9E46D1BB5678B4261A61",
"C0F2AB86E6E0457552DB50D7219371C5",
"64A5C60BC2AD18B8A237E4AA690647E12BF7A081523FAD4F29BE89ACAC72F7AB43C74EC9AFFDA213",
"",
0x27);
sk_NPDRM_arr.emplace_back(0x0003006600000000, 0x0003006600000000, 0x0013, KEY_NPDRM,
"265C93CF48562EC5D18773BEB7689B8AD10C5EB6D21421455DEBC4FB128CBF46",
"8DEA5FF959682A9B98B688CEA1EF4A1D",
"9D8DB5A880608DC69717991AFC3AD5C0215A5EE413328C2ABC8F35589E04432373DB2E2339EEF7C8",
"",
0x18);
sk_NPDRM_arr.emplace_back(0x0003007400000000, 0x0003007400000000, 0x0016, KEY_NPDRM,
"7910340483E419E55F0D33E4EA5410EEEC3AF47814667ECA2AA9D75602B14D4B",
"4AD981431B98DFD39B6388EDAD742A8E",
"62DFE488E410B1B6B2F559E4CB932BCB78845AB623CC59FDF65168400FD76FA82ED1DC60E091D1D1",
"",
0x25);
sk_NPDRM_arr.emplace_back(0x0004001100000000, 0x0004001100000000, 0x0019, KEY_NPDRM,
"FBDA75963FE690CFF35B7AA7B408CF631744EDEF5F7931A04D58FD6A921FFDB3",
"F72C1D80FFDA2E3BF085F4133E6D2805",
"637EAD34E7B85C723C627E68ABDD0419914EBED4008311731DD87FDDA2DAF71F856A70E14DA17B42",
"",
0x24);
sk_NPDRM_arr.emplace_back(0x0004004600000000, 0x0004004600000000, 0x001C, KEY_NPDRM,
"8103EA9DB790578219C4CEDF0592B43064A7D98B601B6C7BC45108C4047AA80F",
"246F4B8328BE6A2D394EDE20479247C5",
"503172C9551308A87621ECEE90362D14889BFED2CF32B0B3E32A4F9FE527A41464B735E1ADBC6762",
"",
0x30);
}
void KeyVault::LoadSelfUNK7Keys()
{
sk_UNK7_arr.clear();
sk_UNK7_arr.emplace_back(0x0000008400000000, 0x0003003100000000, 0x0000, KEY_UNK7,
"D91166973979EA8694476B011AC62C7E9F37DA26DE1E5C2EE3D66E42B8517085",
"DC01280A6E46BC674B81A7E8801EBE6E",
"A0FC44108236141BF3517A662B027AFC1AC513A05690496C754DEB7D43BDC41B80FD75C212624EE4",
"",
0x11);
sk_UNK7_arr.emplace_back(0x0003004000000000, 0x0003004200000000, 0x0000, KEY_UNK7,
"B73111B0B00117E48DE5E2EE5E534C0F0EFFA4890BBB8CAD01EE0F848F91583E",
"86F56F9E5DE513894874B8BA253334B1",
"B0BA1A1AB9723BB4E87CED9637BE056066BC56E16572D43D0210A06411DBF8FEB8885CD912384AE5",
"",
0x12);
sk_UNK7_arr.emplace_back(0x0003005000000000, 0x0003005000000000, 0x0000, KEY_UNK7,
"8E944267C02E69A4FE474B7F5FCD7974A4F936FF4355AEC4F80EFA123858D8F6",
"908A75754E521EAC2F5A4889C6D7B72D",
"91201DA7D79E8EE2563142ECBD646DA026C963AC09E760E5390FFE24DAE6864310ABE147F8204D0B",
"",
0x13);
sk_UNK7_arr.emplace_back(0x0003005500000000, 0x0003005500000000, 0x0000, KEY_UNK7,
"BB31DF9A6F62C0DF853075FAA65134D9CE2240306C1731D1F7DA9B5329BD699F",
"263057225873F83940A65C8C926AC3E4",
"BC3A82A4F44C43A197070CD236FDC94FCC542D69A3E803E0AFF78D1F3DA19A79D2F61FAB5B94B437",
"",
0x23);
sk_UNK7_arr.emplace_back(0x0003005600000000, 0x0003005600000000, 0x0000, KEY_UNK7,
"71AA75C70A255580E4AE9BDAA0B08828C53EAA713CD0713797F143B284C1589B",
"9DED878CB6BA07121C0F50E7B172A8BF",
"387FCDAEAFF1B59CFAF79CE6215A065ACEAFFAF4048A4F217E1FF5CE67C66EC3F089DB235E52F9D3",
"",
0x29);
sk_UNK7_arr.emplace_back(0x0003006000000000, 0x0003006100000000, 0x0000, KEY_UNK7,
"F5D1DBC182F5083CD4EA37C431C7DAC73882C07F232D2699B1DD9FDDF1BF4195",
"D3A7C3C91CBA014FCBCA6D5570DE13FF",
"97CA8A9781F45E557E98F176EF794FCDA6B151EB3DFD1ABA12151E00AE59957C3B15628FC8875D28",
"",
0x23);
sk_UNK7_arr.emplace_back(0x0003006500000000, 0x0003006600000000, 0x0000, KEY_UNK7,
"BF10F09590C0152F7EF749FF4B990122A4E8E5491DA49A2D931E72EEB990F860",
"22C19C5522F7A782AFC547C2640F5BDE",
"3233BA2B284189FB1687DF653002257A0925D8EB0C64EBBE8CC7DE87F548D107DE1FD3D1D285DB4F",
"",
0x29);
sk_UNK7_arr.emplace_back(0x0003007000000000, 0x0003007400000000, 0x0000, KEY_UNK7,
"F11DBD2C97B32AD37E55F8E743BC821D3E67630A6784D9A058DDD26313482F0F",
"FC5FA12CA3D2D336C4B8B425D679DA55",
"19E27EE90E33EDAB16B22E688B5F704E5C6EC1062070EBF43554CD03DFDAE16D684BB8B5574DBECA",
"",
0x15);
sk_UNK7_arr.emplace_back(0x0004000000000000, 0x0004001100000000, 0x0000, KEY_UNK7,
"751EE949CD3ADF50A469197494A1EC358409CCBE6E85217EBDE7A87D3FF1ABD8",
"23AE4ADA4D3F798DC5ED98000337FF77",
"1BABA87CD1AD705C462D4E7427B6DAF59A50383A348A15088F0EDFCF1ADF2B5C2B2D507B2A357D36",
"",
0x1A);
sk_UNK7_arr.emplace_back(0x0004002000000000, 0xFFFFFFFFFFFFFFFF, 0x0000, KEY_UNK7,
"46BD0891224E0CE13E2162921D4BB76193AEEE4416A729FCDD111C5536BF87C9",
"BF036387CDB613C0AC88A6D9D2CC5316",
"A14F6D5F9AD7EBB3B7A39A7C32F13E5DC3B0BA16BDC33D39FDDF88F4AEEA6CFEEB0C0796C917A952",
"",
0x0F);
}
SELF_KEY KeyVault::GetSelfLV0Key() const
{
return sk_LV0_arr[0];
}
SELF_KEY KeyVault::GetSelfLDRKey() const
{
return sk_LDR_arr[0];
}
SELF_KEY KeyVault::GetSelfLV1Key(u64 version) const
{
SELF_KEY key(0, 0, 0, 0, "", "", "", "", 0);
for (uint i = 0; i < sk_LV1_arr.size(); i++)
{
if (version >= sk_LV1_arr[i].version_start && version <= sk_LV1_arr[i].version_end)
{
key = sk_LV1_arr[i];
break;
}
}
return key;
}
SELF_KEY KeyVault::GetSelfLV2Key(u64 version) const
{
SELF_KEY key(0, 0, 0, 0, "", "", "", "", 0);
for (uint i = 0; i < sk_LV2_arr.size(); i++)
{
if (version >= sk_LV2_arr[i].version_start && version <= sk_LV2_arr[i].version_end)
{
key = sk_LV2_arr[i];
break;
}
}
return key;
}
SELF_KEY KeyVault::GetSelfISOKey(u16 revision, u64 version) const
{
SELF_KEY key(0, 0, 0, 0, "", "", "", "", 0);
for (uint i = 0; i < sk_ISO_arr.size(); i++)
{
if ((version >= sk_ISO_arr[i].version_start && version <= sk_ISO_arr[i].version_end) && (sk_ISO_arr[i].revision == revision))
{
key = sk_ISO_arr[i];
break;
}
}
return key;
}
SELF_KEY KeyVault::GetSelfAPPKey(u16 revision) const
{
SELF_KEY key(0, 0, 0, 0, "", "", "", "", 0);
for (uint i = 0; i < sk_APP_arr.size(); i++)
{
if (sk_APP_arr[i].revision == revision)
{
key = sk_APP_arr[i];
break;
}
}
return key;
}
SELF_KEY KeyVault::GetSelfUNK7Key(u64 version) const
{
SELF_KEY key(0, 0, 0, 0, "", "", "", "", 0);
for (uint i = 0; i < sk_UNK7_arr.size(); i++)
{
if (version >= sk_UNK7_arr[i].version_start && version <= sk_UNK7_arr[i].version_end)
{
key = sk_UNK7_arr[i];
break;
}
}
return key;
}
SELF_KEY KeyVault::GetSelfNPDRMKey(u16 revision) const
{
SELF_KEY key(0, 0, 0, 0, "", "", "", "", 0);
for (uint i = 0; i < sk_NPDRM_arr.size(); i++)
{
if (sk_NPDRM_arr[i].revision == revision)
{
key = sk_NPDRM_arr[i];
break;
}
}
return key;
}
SELF_KEY KeyVault::FindSelfKey(u32 type, u16 revision, u64 version)
{
// Empty key.
SELF_KEY key(0, 0, 0, 0, "", "", "", "", 0);
key_vault_log.trace("FindSelfKey: Type:0x%x, Revision:0x%x, Version:0x%x", type, revision, version);
// Check SELF type.
switch (type)
{
case KEY_LV0:
LoadSelfLV0Keys();
key = GetSelfLV0Key();
break;
case KEY_LV1:
LoadSelfLV1Keys();
key = GetSelfLV1Key(version);
break;
case KEY_LV2:
LoadSelfLV2Keys();
key = GetSelfLV2Key(version);
break;
case KEY_APP:
LoadSelfAPPKeys();
key = GetSelfAPPKey(revision);
break;
case KEY_ISO:
LoadSelfISOKeys();
key = GetSelfISOKey(revision, version);
break;
case KEY_LDR:
LoadSelfLDRKeys();
key = GetSelfLDRKey();
break;
case KEY_UNK7:
LoadSelfUNK7Keys();
key = GetSelfUNK7Key(version);
break;
case KEY_NPDRM:
LoadSelfNPDRMKeys();
key = GetSelfNPDRMKey(revision);
break;
default:
break;
}
return key;
}
void KeyVault::SetKlicenseeKey(u8* key)
{
klicensee_key = std::make_unique<u8[]>(0x10);
memcpy(klicensee_key.get(), key, 0x10);
}
u8* KeyVault::GetKlicenseeKey() const
{
return klicensee_key.get();
}
void rap_to_rif(unsigned char* rap, unsigned char* rif)
{
int i;
int round;
aes_context aes;
unsigned char key[0x10];
unsigned char iv[0x10];
memset(key, 0, 0x10);
memset(iv, 0, 0x10);
// Initial decrypt.
aes_setkey_dec(&aes, RAP_KEY, 128);
aes_crypt_cbc(&aes, AES_DECRYPT, 0x10, iv, rap, key);
// rap2rifkey round.
for (round = 0; round < 5; ++round)
{
for (i = 0; i < 16; ++i)
{
const int p = RAP_PBOX[i];
key[p] ^= RAP_E1[p];
}
for (i = 15; i >= 1; --i)
{
const int p = RAP_PBOX[i];
const int pp = RAP_PBOX[i - 1];
key[p] ^= key[pp];
}
int o = 0;
for (i = 0; i < 16; ++i)
{
const int p = RAP_PBOX[i];
const unsigned char kc = key[p] - o;
const unsigned char ec2 = RAP_E2[p];
if (o != 1 || kc != 0xFF)
{
o = kc < ec2 ? 1 : 0;
key[p] = kc - ec2;
}
else if (kc == 0xFF)
{
key[p] = kc - ec2;
}
else
{
key[p] = kc;
}
}
}
memcpy(rif, key, 0x10);
}
| 32,067
|
C++
|
.cpp
| 775
| 38.68129
| 163
| 0.83472
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
5,034
|
ec.cpp
|
RPCS3_rpcs3/rpcs3/Crypto/ec.cpp
|
// Copyright 2007,2008,2010 Segher Boessenkool <segher@kernel.crashing.org>
// Licensed under the terms of the GNU GPL, version 2
// http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
#include "utils.h"
#include <cstring>
static inline int bn_compare(u8* a, u8* b, u32 n)
{
for (u32 i = 0; i < n; i++)
{
if (a[i] < b[i])
return -1;
if (a[i] > b[i])
return 1;
}
return 0;
}
static u8 bn_add_1(u8* d, u8* a, u8* b, u32 n)
{
u8 c = 0;
for (u32 i = n - 1; i != umax; i--)
{
const u32 dig = a[i] + b[i] + c;
c = dig >> 8;
d[i] = dig;
}
return c;
}
static u8 bn_sub_1(u8* d, u8* a, u8* b, u32 n)
{
u8 c = 1;
for (u32 i = n - 1; i != umax; i--)
{
const u32 dig = a[i] + 255 - b[i] + c;
c = dig >> 8;
d[i] = dig;
}
return 1 - c;
}
static void bn_reduce(u8* d, u8* N, u32 n)
{
if (bn_compare(d, N, n) >= 0)
bn_sub_1(d, d, N, n);
}
static void bn_add(u8* d, u8* a, u8* b, u8* N, u32 n)
{
if (bn_add_1(d, a, b, n))
bn_sub_1(d, d, N, n);
bn_reduce(d, N, n);
}
static void bn_sub(u8* d, u8* a, u8* b, u8* N, u32 n)
{
if (bn_sub_1(d, a, b, n))
bn_add_1(d, d, N, n);
}
static constexpr u8 inv256[0x80] = {
0x01, 0xab, 0xcd, 0xb7, 0x39, 0xa3, 0xc5, 0xef,
0xf1, 0x1b, 0x3d, 0xa7, 0x29, 0x13, 0x35, 0xdf,
0xe1, 0x8b, 0xad, 0x97, 0x19, 0x83, 0xa5, 0xcf,
0xd1, 0xfb, 0x1d, 0x87, 0x09, 0xf3, 0x15, 0xbf,
0xc1, 0x6b, 0x8d, 0x77, 0xf9, 0x63, 0x85, 0xaf,
0xb1, 0xdb, 0xfd, 0x67, 0xe9, 0xd3, 0xf5, 0x9f,
0xa1, 0x4b, 0x6d, 0x57, 0xd9, 0x43, 0x65, 0x8f,
0x91, 0xbb, 0xdd, 0x47, 0xc9, 0xb3, 0xd5, 0x7f,
0x81, 0x2b, 0x4d, 0x37, 0xb9, 0x23, 0x45, 0x6f,
0x71, 0x9b, 0xbd, 0x27, 0xa9, 0x93, 0xb5, 0x5f,
0x61, 0x0b, 0x2d, 0x17, 0x99, 0x03, 0x25, 0x4f,
0x51, 0x7b, 0x9d, 0x07, 0x89, 0x73, 0x95, 0x3f,
0x41, 0xeb, 0x0d, 0xf7, 0x79, 0xe3, 0x05, 0x2f,
0x31, 0x5b, 0x7d, 0xe7, 0x69, 0x53, 0x75, 0x1f,
0x21, 0xcb, 0xed, 0xd7, 0x59, 0xc3, 0xe5, 0x0f,
0x11, 0x3b, 0x5d, 0xc7, 0x49, 0x33, 0x55, 0xff,
};
static void bn_mon_muladd_dig(u8* d, u8* a, u8 b, u8* N, u32 n)
{
const u8 z = -(d[n - 1] + a[n - 1] * b) * inv256[N[n - 1] / 2];
u32 dig = d[n - 1] + a[n - 1] * b + N[n - 1] * z;
dig >>= 8;
for (u32 i = n - 2; i < n; i--)
{
dig += d[i] + a[i] * b + N[i] * z;
d[i + 1] = dig;
dig >>= 8;
}
d[0] = dig;
dig >>= 8;
if (dig)
bn_sub_1(d, d, N, n);
bn_reduce(d, N, n);
}
static void bn_mon_mul(u8* d, u8* a, u8* b, u8* N, u32 n)
{
u8 t[512];
memset(t, 0, n);
for (u32 i = n - 1; i != umax; i--)
bn_mon_muladd_dig(t, a, b[i], N, n);
memcpy(d, t, n);
}
static void bn_to_mon(u8* d, u8* N, u32 n)
{
for (u32 i = 0; i < 8 * n; i++)
bn_add(d, d, d, N, n);
}
static void bn_from_mon(u8* d, u8* N, u32 n)
{
u8 t[512];
memset(t, 0, n);
t[n - 1] = 1;
bn_mon_mul(d, d, t, N, n);
}
static void bn_mon_exp(u8* d, u8* a, u8* N, u32 n, u8* e, u32 en)
{
u8 t[512];
memset(d, 0, n);
d[n - 1] = 1;
bn_to_mon(d, N, n);
for (u32 i = 0; i < en; i++)
{
for (u8 mask = 0x80; mask != 0; mask >>= 1)
{
bn_mon_mul(t, d, d, N, n);
if ((e[i] & mask) != 0)
bn_mon_mul(d, t, a, N, n);
else
memcpy(d, t, n);
}
}
}
static void bn_mon_inv(u8* d, u8* a, u8* N, u32 n)
{
u8 t[512], s[512];
memset(s, 0, n);
s[n - 1] = 2;
bn_sub_1(t, N, s, n);
bn_mon_exp(d, a, N, n, t, n);
}
struct point
{
u8 x[20];
u8 y[20];
};
static thread_local u8 ec_p[20]{};
static thread_local u8 ec_a[20]{}; // mon
static thread_local u8 ec_b[20]{}; // mon
static thread_local u8 ec_N[21]{};
static thread_local point ec_G{}; // mon
static thread_local point ec_Q{}; // mon
static thread_local u8 ec_k[21]{};
static thread_local bool ec_curve_initialized{};
static thread_local bool ec_pub_initialized{};
static inline bool elt_is_zero(u8* d)
{
for (u32 i = 0; i < 20; i++)
if (d[i] != 0)
return false;
return true;
}
static void elt_add(u8* d, u8* a, u8* b)
{
bn_add(d, a, b, ec_p, 20);
}
static void elt_sub(u8* d, u8* a, u8* b)
{
bn_sub(d, a, b, ec_p, 20);
}
static void elt_mul(u8* d, u8* a, u8* b)
{
bn_mon_mul(d, a, b, ec_p, 20);
}
static void elt_square(u8* d, u8* a)
{
elt_mul(d, a, a);
}
static void elt_inv(u8* d, u8* a)
{
u8 s[20];
memcpy(s, a, 20);
bn_mon_inv(d, s, ec_p, 20);
}
static void point_to_mon(point* p)
{
bn_to_mon(p->x, ec_p, 20);
bn_to_mon(p->y, ec_p, 20);
}
static void point_from_mon(point* p)
{
bn_from_mon(p->x, ec_p, 20);
bn_from_mon(p->y, ec_p, 20);
}
static inline void point_zero(point* p)
{
memset(p->x, 0, 20);
memset(p->y, 0, 20);
}
static inline bool point_is_zero(point* p)
{
return elt_is_zero(p->x) && elt_is_zero(p->y);
}
static void point_double(point* r, point* p)
{
u8 s[20], t[20];
point pp = *p;
u8* px = pp.x;
u8* py = pp.y;
u8* rx = r->x;
u8* ry = r->y;
if (elt_is_zero(py))
{
point_zero(r);
return;
}
elt_square(t, px); // t = px*px
elt_add(s, t, t); // s = 2*px*px
elt_add(s, s, t); // s = 3*px*px
elt_add(s, s, ec_a); // s = 3*px*px + a
elt_add(t, py, py); // t = 2*py
elt_inv(t, t); // t = 1/(2*py)
elt_mul(s, s, t); // s = (3*px*px+a)/(2*py)
elt_square(rx, s); // rx = s*s
elt_add(t, px, px); // t = 2*px
elt_sub(rx, rx, t); // rx = s*s - 2*px
elt_sub(t, px, rx); // t = -(rx-px)
elt_mul(ry, s, t); // ry = -s*(rx-px)
elt_sub(ry, ry, py); // ry = -s*(rx-px) - py
}
static void point_add(point* r, point* p, point* q)
{
u8 s[20], t[20], u[20];
point pp = *p;
point qq = *q;
u8* px = pp.x;
u8* py = pp.y;
u8* qx = qq.x;
u8* qy = qq.y;
u8* rx = r->x;
u8* ry = r->y;
if (point_is_zero(&pp))
{
memcpy(rx, qx, 20);
memcpy(ry, qy, 20);
return;
}
if (point_is_zero(&qq))
{
memcpy(rx, px, 20);
memcpy(ry, py, 20);
return;
}
elt_sub(u, qx, px);
if (elt_is_zero(u))
{
elt_sub(u, qy, py);
if (elt_is_zero(u))
point_double(r, &pp);
else
point_zero(r);
return;
}
elt_inv(t, u); // t = 1/(qx-px)
elt_sub(u, qy, py); // u = qy-py
elt_mul(s, t, u); // s = (qy-py)/(qx-px)
elt_square(rx, s); // rx = s*s
elt_add(t, px, qx); // t = px+qx
elt_sub(rx, rx, t); // rx = s*s - (px+qx)
elt_sub(t, px, rx); // t = -(rx-px)
elt_mul(ry, s, t); // ry = -s*(rx-px)
elt_sub(ry, ry, py); // ry = -s*(rx-px) - py
}
static void point_mul(point* d, u8* a, point* b) // a is bignum
{
point_zero(d);
for (u32 i = 0; i < 21; i++)
{
for (u8 mask = 0x80; mask != 0; mask >>= 1)
{
point_double(d, d);
if ((a[i] & mask) != 0)
point_add(d, d, b);
}
}
}
static bool check_ecdsa(struct point* Q, u8* R, u8* S, u8* hash)
{
u8 Sinv[21];
u8 e[21];
u8 w1[21], w2[21];
struct point r1, r2;
u8 rr[21];
e[0] = 0;
memcpy(e + 1, hash, 20);
bn_reduce(e, ec_N, 21);
bn_to_mon(R, ec_N, 21);
bn_to_mon(S, ec_N, 21);
bn_to_mon(e, ec_N, 21);
bn_mon_inv(Sinv, S, ec_N, 21);
bn_mon_mul(w1, e, Sinv, ec_N, 21);
bn_mon_mul(w2, R, Sinv, ec_N, 21);
bn_from_mon(w1, ec_N, 21);
bn_from_mon(w2, ec_N, 21);
point_mul(&r1, w1, &ec_G);
point_mul(&r2, w2, Q);
point_add(&r1, &r1, &r2);
point_from_mon(&r1);
rr[0] = 0;
memcpy(rr + 1, r1.x, 20);
bn_reduce(rr, ec_N, 21);
bn_from_mon(R, ec_N, 21);
bn_from_mon(S, ec_N, 21);
return (bn_compare(rr, R, 21) == 0);
}
void ecdsa_set_curve(const u8* p, const u8* a, const u8* b, const u8* N, const u8* Gx, const u8* Gy)
{
if (ec_curve_initialized) return;
memcpy(ec_p, p, 20);
memcpy(ec_a, a, 20);
memcpy(ec_b, b, 20);
memcpy(ec_N, N, 21);
memcpy(ec_G.x, Gx, 20);
memcpy(ec_G.y, Gy, 20);
bn_to_mon(ec_a, ec_p, 20);
bn_to_mon(ec_b, ec_p, 20);
point_to_mon(&ec_G);
ec_curve_initialized = true;
}
void ecdsa_set_pub(const u8* Q)
{
if (ec_pub_initialized) return;
memcpy(ec_Q.x, Q, 20);
memcpy(ec_Q.y, Q + 20, 20);
point_to_mon(&ec_Q);
ec_pub_initialized = true;
}
void ecdsa_set_priv(const u8* k)
{
memcpy(ec_k, k, sizeof ec_k);
}
bool ecdsa_verify(u8* hash, u8* R, u8* S)
{
return check_ecdsa(&ec_Q, R, S, hash);
}
| 7,853
|
C++
|
.cpp
| 339
| 21.047198
| 100
| 0.561104
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,036
|
utils.cpp
|
RPCS3_rpcs3/rpcs3/Crypto/utils.cpp
|
// Copyright (C) 2014 Hykem <hykem@hotmail.com>
// Licensed under the terms of the GNU GPL, version 2.0 or later versions.
// http://www.gnu.org/licenses/gpl-2.0.txt
#include "utils.h"
#include "aes.h"
#include "sha1.h"
#include "sha256.h"
#include "key_vault.h"
#include <cstring>
#include <stdio.h>
#include <time.h>
#include "Utilities/StrUtil.h"
#include "Utilities/File.h"
#include <memory>
#include <string>
#include <string_view>
#include <span>
// Auxiliary functions (endian swap, xor).
// Hex string conversion auxiliary functions.
u64 hex_to_u64(const char* hex_str)
{
auto length = std::strlen(hex_str);
u64 tmp = 0;
u64 result = 0;
char c;
while (length--)
{
c = *hex_str++;
if((c >= '0') && (c <= '9'))
tmp = c - '0';
else if((c >= 'a') && (c <= 'f'))
tmp = c - 'a' + 10;
else if((c >= 'A') && (c <= 'F'))
tmp = c - 'A' + 10;
else
tmp = 0;
result |= (tmp << (length * 4));
}
return result;
}
void hex_to_bytes(unsigned char* data, const char* hex_str, unsigned int str_length)
{
const auto strn_length = (str_length > 0) ? str_length : std::strlen(hex_str);
auto data_length = strn_length / 2;
char tmp_buf[3] = {0, 0, 0};
// Don't convert if the string length is odd.
if ((strn_length % 2) == 0)
{
while (data_length--)
{
tmp_buf[0] = *hex_str++;
tmp_buf[1] = *hex_str++;
*data++ = static_cast<u8>(hex_to_u64(tmp_buf) & 0xFF);
}
}
}
// Crypto functions (AES128-CBC, AES128-ECB, SHA1-HMAC and AES-CMAC).
void aescbc128_decrypt(unsigned char *key, unsigned char *iv, unsigned char *in, unsigned char *out, usz len)
{
aes_context ctx;
aes_setkey_dec(&ctx, key, 128);
aes_crypt_cbc(&ctx, AES_DECRYPT, len, iv, in, out);
// Reset the IV.
memset(iv, 0, 0x10);
}
void aescbc128_encrypt(unsigned char *key, unsigned char *iv, unsigned char *in, unsigned char *out, usz len)
{
aes_context ctx;
aes_setkey_enc(&ctx, key, 128);
aes_crypt_cbc(&ctx, AES_ENCRYPT, len, iv, in, out);
// Reset the IV.
memset(iv, 0, 0x10);
}
void aesecb128_encrypt(unsigned char *key, unsigned char *in, unsigned char *out)
{
aes_context ctx;
aes_setkey_enc(&ctx, key, 128);
aes_crypt_ecb(&ctx, AES_ENCRYPT, in, out);
}
bool hmac_hash_compare(unsigned char *key, int key_len, unsigned char *in, usz in_len, unsigned char *hash, usz hash_len)
{
const std::unique_ptr<u8[]> out(new u8[key_len]);
sha1_hmac(key, key_len, in, in_len, out.get());
return std::memcmp(out.get(), hash, hash_len) == 0;
}
void hmac_hash_forge(unsigned char *key, int key_len, unsigned char *in, usz in_len, unsigned char *hash)
{
sha1_hmac(key, key_len, in, in_len, hash);
}
bool cmac_hash_compare(unsigned char *key, int key_len, unsigned char *in, usz in_len, unsigned char *hash, usz hash_len)
{
const std::unique_ptr<u8[]> out(new u8[key_len]);
aes_context ctx;
aes_setkey_enc(&ctx, key, 128);
aes_cmac(&ctx, in_len, in, out.get());
return std::memcmp(out.get(), hash, hash_len) == 0;
}
void cmac_hash_forge(unsigned char *key, int /*key_len*/, unsigned char *in, usz in_len, unsigned char *hash)
{
aes_context ctx;
aes_setkey_enc(&ctx, key, 128);
aes_cmac(&ctx, in_len, in, hash);
}
char* extract_file_name(const char* file_path, char real_file_name[CRYPTO_MAX_PATH])
{
std::string_view v(file_path);
if (const auto pos = v.find_last_of(fs::delim); pos != umax)
{
v.remove_prefix(pos + 1);
}
std::span r(real_file_name, CRYPTO_MAX_PATH);
strcpy_trunc(r, v);
return real_file_name;
}
std::string sha256_get_hash(const char* data, usz size, bool lower_case)
{
u8 res_hash[32];
mbedtls_sha256_context ctx;
mbedtls_sha256_init(&ctx);
mbedtls_sha256_starts_ret(&ctx, 0);
mbedtls_sha256_update_ret(&ctx, reinterpret_cast<const unsigned char*>(data), size);
mbedtls_sha256_finish_ret(&ctx, res_hash);
std::string res_hash_string("0000000000000000000000000000000000000000000000000000000000000000");
for (usz index = 0; index < 32; index++)
{
const auto pal = lower_case ? "0123456789abcdef" : "0123456789ABCDEF";
res_hash_string[index * 2] = pal[res_hash[index] >> 4];
res_hash_string[(index * 2) + 1] = pal[res_hash[index] & 15];
}
return res_hash_string;
}
void mbedtls_zeroize(void *v, size_t n)
{
static void *(*const volatile unop_memset)(void *, int, size_t) = &memset;
(void)unop_memset(v, 0, n);
}
// SC passphrase crypto
void sc_form_key(const u8* sc_key, const std::array<u8, PASSPHRASE_KEY_LEN>& laid_paid, u8* key)
{
for (u32 i = 0; i < PASSPHRASE_KEY_LEN; i++)
{
key[i] = static_cast<u8>(sc_key[i] ^ laid_paid[i]);
}
}
std::array<u8, PASSPHRASE_KEY_LEN> sc_combine_laid_paid(s64 laid, s64 paid)
{
const std::string paid_laid = fmt::format("%016llx%016llx", laid, paid);
std::array<u8, PASSPHRASE_KEY_LEN> out{};
hex_to_bytes(out.data(), paid_laid.c_str(), PASSPHRASE_KEY_LEN * 2);
return out;
}
std::array<u8, PASSPHRASE_KEY_LEN> vtrm_get_laid_paid_from_type(int type)
{
// No idea what this type stands for
switch (type)
{
case 0: return sc_combine_laid_paid(0xFFFFFFFFFFFFFFFFL, 0xFFFFFFFFFFFFFFFFL);
case 1: return sc_combine_laid_paid(LAID_2, 0x1070000000000001L);
case 2: return sc_combine_laid_paid(LAID_2, 0x0000000000000000L);
case 3: return sc_combine_laid_paid(LAID_2, PAID_69);
default:
fmt::throw_exception("vtrm_get_laid_paid_from_type: Wrong type specified (type=%d)", type);
}
}
std::array<u8, PASSPHRASE_KEY_LEN> vtrm_portability_laid_paid()
{
// 107000002A000001
return sc_combine_laid_paid(0x0000000000000000L, 0x0000000000000000L);
}
int sc_decrypt(const u8* sc_key, const std::array<u8, PASSPHRASE_KEY_LEN>& laid_paid, u8* iv, u8* input, u8* output)
{
aes_context ctx;
u8 key[PASSPHRASE_KEY_LEN];
sc_form_key(sc_key, laid_paid, key);
aes_setkey_dec(&ctx, key, 128);
return aes_crypt_cbc(&ctx, AES_DECRYPT, PASSPHRASE_OUT_LEN, iv, input, output);
}
int vtrm_decrypt(int type, u8* iv, u8* input, u8* output)
{
return sc_decrypt(SC_ISO_SERIES_KEY_2, vtrm_get_laid_paid_from_type(type), iv, input, output);
}
int vtrm_decrypt_master(s64 laid, s64 paid, u8* iv, u8* input, u8* output)
{
return sc_decrypt(SC_ISO_SERIES_INTERNAL_KEY_3, sc_combine_laid_paid(laid, paid), iv, input, output);
}
const u8* vtrm_portability_type_mapper(int type)
{
// No idea what this type stands for
switch (type)
{
//case 0: return key_for_type_1;
case 1: return SC_ISO_SERIES_KEY_2;
case 2: return SC_ISO_SERIES_KEY_1;
case 3: return SC_KEY_FOR_MASTER_2;
default:
fmt::throw_exception("vtrm_portability_type_mapper: Wrong type specified (type=%d)", type);
}
}
int vtrm_decrypt_with_portability(int type, u8* iv, u8* input, u8* output)
{
return sc_decrypt(vtrm_portability_type_mapper(type), vtrm_portability_laid_paid(), iv, input, output);
}
| 6,969
|
C++
|
.cpp
| 202
| 31.351485
| 122
| 0.671405
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,037
|
atomic.cpp
|
RPCS3_rpcs3/rpcs3/util/atomic.cpp
|
#include "atomic.hpp"
#if defined(__linux__)
#define USE_FUTEX
#elif !defined(_WIN32)
#define USE_STD
#endif
#ifdef _MSC_VER
#include "emmintrin.h"
#include "immintrin.h"
namespace utils
{
u128 __vectorcall atomic_load16(const void* ptr)
{
return std::bit_cast<u128>(_mm_load_si128((__m128i*)ptr));
}
void __vectorcall atomic_store16(void* ptr, u128 value)
{
_mm_store_si128((__m128i*)ptr, std::bit_cast<__m128i>(value));
}
}
#endif
#include "Utilities/sync.h"
#include "Utilities/StrFmt.h"
#ifdef __linux__
static bool has_waitv()
{
static const bool s_has_waitv = []
{
syscall(SYS_futex_waitv, 0, 0, 0, 0, 0);
if (errno == ENOSYS)
return false;
return true;
}();
return s_has_waitv;
}
#endif
#include <utility>
#include <cstdint>
#include <array>
#include <random>
#include "asm.hpp"
#include "endian.hpp"
#include "tsc.hpp"
// Total number of entries.
static constexpr usz s_hashtable_size = 1u << 17;
// Reference counter combined with shifted pointer (which is assumed to be 48 bit)
static constexpr uptr s_ref_mask = 0xffff;
// Fix for silly on-first-use initializer
static bool s_null_wait_cb(const void*, u64, u64){ return true; };
// Callback for wait() function, returns false if wait should return
static thread_local bool(*s_tls_wait_cb)(const void* data, u64 attempts, u64 stamp0) = s_null_wait_cb;
// Callback for wait() function for a second custon condition, commonly passed with timeout
static thread_local bool(*s_tls_one_time_wait_cb)(u64 attempts) = nullptr;
// Compare data in memory with old value, and return true if they are equal
static NEVER_INLINE bool ptr_cmp(const void* data, u32 old, atomic_wait::info* ext = nullptr)
{
// Check other wait variables if provided
if (reinterpret_cast<const atomic_t<u32>*>(data)->load() == old)
{
if (ext) [[unlikely]]
{
for (auto e = ext; e->data; e++)
{
if (!ptr_cmp(e->data, e->old))
{
return false;
}
}
}
return true;
}
return false;
}
static atomic_t<u64> s_min_tsc{0};
namespace
{
#ifdef USE_STD
// Just madness to keep some members uninitialized and get zero initialization otherwise
template <typename T>
struct alignas(T) un_t
{
std::byte data[sizeof(T)];
T* get() noexcept
{
return std::launder(reinterpret_cast<T*>(+data));
}
const T* get() const noexcept
{
return std::launder(reinterpret_cast<const T*>(+data));
}
T& operator =(const T& r) noexcept
{
return *get() = r;
}
T* operator ->() noexcept
{
return get();
}
const T* operator ->() const noexcept
{
return get();
}
operator T&() noexcept
{
return *get();
}
operator const T&() const noexcept
{
return *get();
}
static void init(un_t& un)
{
new (un.data) T();
}
void destroy()
{
get()->~T();
}
};
#endif
// Essentially a fat semaphore
struct alignas(64) cond_handle
{
// Combined pointer (most significant 48 bits) and ref counter (16 least significant bits)
atomic_t<u64> ptr_ref;
u64 tid;
u32 oldv;
u64 tsc0;
u16 link;
atomic_t<u32> sync;
#ifdef USE_STD
// Standard CV/mutex pair (often contains pthread_cond_t/pthread_mutex_t)
un_t<std::condition_variable> cv;
un_t<std::mutex> mtx;
#endif
void init(uptr iptr)
{
#ifdef _WIN32
tid = GetCurrentThreadId();
#else
tid = reinterpret_cast<u64>(pthread_self());
#endif
#ifdef USE_STD
cv.init(cv);
mtx.init(mtx);
#endif
ensure(!ptr_ref.exchange((iptr << 16) | 1));
}
void destroy()
{
tid = 0;
tsc0 = 0;
link = 0;
sync.release(0);
oldv = 0;
#ifdef USE_STD
mtx.destroy();
cv.destroy();
#endif
}
bool forced_wakeup()
{
const auto [_old, ok] = sync.fetch_op([](u32& val)
{
if (val - 1 <= 1)
{
val = 3;
return true;
}
return false;
});
// Prevent collision between normal wake-up and forced one
return ok && _old == 1;
}
bool wakeup(u32 cmp_res)
{
if (cmp_res == 1) [[likely]]
{
const auto [_old, ok] = sync.fetch_op([](u32& val)
{
if (val == 1)
{
val = 2;
return true;
}
return false;
});
return ok;
}
if (cmp_res > 1) [[unlikely]]
{
// TODO.
// Used when notify function is provided with enforced new value.
return forced_wakeup();
}
return false;
}
bool set_sleep()
{
const auto [_old, ok] = sync.fetch_op([](u32& val)
{
if (val == 2)
{
val = 1;
return true;
}
return false;
});
return ok;
}
void alert_native()
{
#ifdef USE_FUTEX
// Use "wake all" arg for robustness, only 1 thread is expected
futex(&sync, FUTEX_WAKE_PRIVATE, 0x7fff'ffff);
#elif defined(USE_STD)
// Not super efficient: locking is required to avoid lost notifications
mtx->lock();
mtx->unlock();
cv->notify_all();
#elif defined(_WIN32)
if (NtWaitForAlertByThreadId)
{
// Sets some sticky alert bit, at least I believe so
NtAlertThreadByThreadId(tid);
}
else
{
// Can wait in rare cases, which is its annoying weakness
NtReleaseKeyedEvent(nullptr, &sync, 1, nullptr);
}
#endif
}
bool try_alert_native()
{
#if defined(USE_FUTEX)
return false;
#elif defined(USE_STD)
// Optimistic non-blocking path
if (mtx->try_lock())
{
mtx->unlock();
cv->notify_all();
return true;
}
return false;
#elif defined(_WIN32)
if (NtAlertThreadByThreadId)
{
// Don't notify prematurely with this API
return false;
}
static LARGE_INTEGER instant{};
if (NtReleaseKeyedEvent(nullptr, &sync, 1, &instant) != NTSTATUS_SUCCESS)
{
// Failed to notify immediately
return false;
}
return true;
#endif
}
};
#ifndef USE_STD
static_assert(sizeof(cond_handle) == 64);
#endif
}
// Produce u128 value that repeats val 8 times
static constexpr u128 dup8(u32 val)
{
const u32 shift = 32 - std::countl_zero(val);
const u128 it0 = u128{val};
const u128 it1 = it0 | (it0 << shift);
const u128 it2 = it1 | (it1 << (shift * 2));
const u128 it3 = it2 | (it2 << (shift * 4));
return it3;
}
// Free or put in specified tls slot
static void cond_free(u32 cond_id, u32 tls_slot);
// Semaphore tree root (level 1) - split in 8 parts (8192 in each)
static atomic_t<u128> s_cond_sem1{1};
// Semaphore tree (level 2) - split in 8 parts (1024 in each)
static atomic_t<u128> s_cond_sem2[8]{{1}};
// Semaphore tree (level 3) - split in 16 parts (128 in each)
static atomic_t<u128> s_cond_sem3[64]{{1}};
// Allocation bits (level 4) - guarantee 1 free bit
static atomic_t<u64> s_cond_bits[65536 / 64]{1};
// Max allowed thread number is chosen to fit in 16 bits
static cond_handle s_cond_list[65536]{};
namespace
{
struct tls_cond_handler
{
u16 cond[4]{};
constexpr tls_cond_handler() noexcept = default;
~tls_cond_handler()
{
for (u32 cond_id : cond)
{
if (cond_id)
{
// Set fake refctr
s_cond_list[cond_id].ptr_ref.release(1);
cond_free(cond_id, -1);
}
}
}
};
}
// TLS storage for few allocaded "semaphores" to allow skipping initialization
static thread_local tls_cond_handler s_tls_conds{};
static u32 cond_alloc(uptr iptr, u32 tls_slot = -1)
{
// Try to get cond from tls slot instead
u16* ptls = tls_slot >= std::size(s_tls_conds.cond) ? nullptr : s_tls_conds.cond + tls_slot;
if (ptls && *ptls) [[likely]]
{
// Fast reinitialize
const u32 id = std::exchange(*ptls, 0);
s_cond_list[id].ptr_ref.release((iptr << 16) | 1);
return id;
}
const u32 level1 = s_cond_sem1.atomic_op([](u128& val) -> u32
{
constexpr u128 max_mask = dup8(8192);
// Leave only bits indicating sub-semaphore is full, find free one
const u32 pos = utils::ctz128(~val & max_mask);
if (pos == 128) [[unlikely]]
{
// No free space
return -1;
}
val += u128{1} << (pos / 14 * 14);
return pos / 14;
});
// Determine whether there is a free slot or not
if (level1 < 8) [[likely]]
{
const u32 level2 = level1 * 8 + s_cond_sem2[level1].atomic_op([](u128& val)
{
constexpr u128 max_mask = dup8(1024);
const u32 pos = utils::ctz128(~val & max_mask);
val += u128{1} << (pos / 11 * 11);
return pos / 11;
});
const u32 level3 = level2 * 16 + s_cond_sem3[level2].atomic_op([](u128& val)
{
constexpr u128 max_mask = dup8(64) | (dup8(64) << 56);
const u32 pos = utils::ctz128(~val & max_mask);
val += u128{1} << (pos / 7 * 7);
return pos / 7;
});
// Set lowest clear bit
const u64 bits = s_cond_bits[level3].fetch_op(AOFN(x |= x + 1, void()));
// Find lowest clear bit (before it was set in fetch_op)
const u32 id = level3 * 64 + std::countr_one(bits);
// Initialize new "semaphore"
s_cond_list[id].init(iptr);
return id;
}
fmt::throw_exception("Thread semaphore limit (65535) reached in atomic wait.");
}
static void cond_free(u32 cond_id, u32 tls_slot = -1)
{
if (cond_id - 1 >= u16{umax}) [[unlikely]]
{
fmt::throw_exception("bad id %u", cond_id);
}
const auto cond = s_cond_list + cond_id;
// Dereference, destroy on last ref
const bool last = cond->ptr_ref.atomic_op([](u64& val)
{
ensure(val & s_ref_mask);
val--;
if ((val & s_ref_mask) == 0)
{
val = 0;
return true;
}
return false;
});
if (!last)
{
return;
}
u16* ptls = tls_slot >= std::size(s_tls_conds.cond) ? nullptr : s_tls_conds.cond + tls_slot;
if (ptls && !*ptls) [[likely]]
{
// Fast finalization
cond->sync.release(0);
*ptls = static_cast<u16>(cond_id);
return;
}
// Call the destructor if necessary
utils::prefetch_write(s_cond_bits + cond_id / 64);
const u32 level3 = cond_id / 64 % 16;
const u32 level2 = cond_id / 1024 % 8;
const u32 level1 = cond_id / 8192 % 8;
utils::prefetch_write(s_cond_sem3 + level2);
utils::prefetch_write(s_cond_sem2 + level1);
utils::prefetch_write(&s_cond_sem1);
cond->destroy();
// Release the semaphore tree in the reverse order
s_cond_bits[cond_id / 64] &= ~(1ull << (cond_id % 64));
s_cond_sem3[level2].atomic_op(AOFN(x -= u128{1} << (level3 * 7)));
s_cond_sem2[level1].atomic_op(AOFN(x -= u128{1} << (level2 * 11)));
s_cond_sem1.atomic_op(AOFN(x -= u128{1} << (level1 * 14)));
}
static cond_handle* cond_id_lock(u32 cond_id, uptr iptr = 0)
{
bool did_ref = false;
if (cond_id - 1 >= u16{umax})
{
return nullptr;
}
const auto cond = s_cond_list + cond_id;
while (true)
{
const auto [old, ok] = cond->ptr_ref.fetch_op([&](u64& val)
{
if (!val || (val & s_ref_mask) == s_ref_mask)
{
// Don't reference already deallocated semaphore
return false;
}
if (iptr && (val >> 16) != iptr)
{
// Pointer mismatch
return false;
}
const u32 sync_val = cond->sync;
if (sync_val == 0 || sync_val == 3)
{
return false;
}
if (!did_ref)
{
val++;
}
return true;
});
if (ok)
{
// Check other fields again
if (const u32 sync_val = cond->sync; sync_val == 0 || sync_val == 3)
{
did_ref = true;
continue;
}
return cond;
}
if ((old & s_ref_mask) == s_ref_mask)
{
fmt::throw_exception("Reference count limit (%u) reached in an atomic notifier.", s_ref_mask);
}
break;
}
if (did_ref)
{
cond_free(cond_id, -1);
}
return nullptr;
}
namespace
{
struct alignas(16) slot_allocator
{
u64 maxc: 5; // Collision counter
u64 maxd: 11; // Distance counter
u64 bits: 24; // Allocated bits
u64 prio: 24; // Reserved
u64 ref : 16; // Ref counter
u64 iptr: 48; // First pointer to use slot (to count used slots)
};
// Need to spare 16 bits for ref counter
static constexpr u64 max_threads = 24;
// (Arbitrary, not justified) Can only allow extended allocations go as far as this
static constexpr u64 max_distance = 500;
// Thread list
struct alignas(64) root_info
{
// Allocation bits (least significant)
atomic_t<slot_allocator> bits;
// Allocation pool, pointers to allocated semaphores
atomic_t<u16> slots[max_threads];
static atomic_t<u16>* slot_alloc(uptr ptr) noexcept;
static void slot_free(uptr ptr, atomic_t<u16>* slot, u32 tls_slot) noexcept;
template <typename F>
static auto slot_search(uptr iptr, F func) noexcept;
};
static_assert(sizeof(root_info) == 64);
}
// Main hashtable for atomic wait.
static root_info s_hashtable[s_hashtable_size]{};
namespace
{
struct hash_engine
{
// Pseudo-RNG, seeded with input pointer
using rng = std::linear_congruential_engine<u64, 2862933555777941757, 3037000493, 0>;
const u64 init;
// Subpointers
u16 r0;
u16 r1;
// Pointer to the current hashtable slot
u32 id;
// Initialize: PRNG on iptr, split into two 16 bit chunks, choose first chunk
explicit hash_engine(uptr iptr)
: init(rng(iptr)())
, r0(static_cast<u16>(init >> 48))
, r1(static_cast<u16>(init >> 32))
, id(static_cast<u32>(init) >> 31 ? r0 : r1 + 0x10000)
{
}
// Advance: linearly to prevent self-collisions, but always switch between two big 2^16 chunks
void advance() noexcept
{
if (id >= 0x10000)
{
id = r0++;
}
else
{
id = r1++ + 0x10000;
}
}
root_info* current() const noexcept
{
return &s_hashtable[id];
}
root_info* operator ->() const noexcept
{
return current();
}
};
}
u64 utils::get_unique_tsc()
{
const u64 stamp0 = utils::get_tsc();
if (!s_min_tsc.fetch_op([=](u64& tsc)
{
if (stamp0 <= tsc)
{
// Add 1 if new stamp is too old
return false;
}
else
{
// Update last tsc with new stamp otherwise
tsc = stamp0;
return true;
}
}).second)
{
// Add 1 if new stamp is too old
// Avoid doing it in the atomic operaion because, if it gets here it means there is already much cntention
// So break the race (at least on x86)
return s_min_tsc.add_fetch(1);
}
return stamp0;
}
atomic_t<u16>* root_info::slot_alloc(uptr ptr) noexcept
{
atomic_t<u16>* slot = nullptr;
u32 limit = 0;
for (hash_engine _this(ptr);; _this.advance())
{
slot = _this->bits.atomic_op([&](slot_allocator& bits) -> atomic_t<u16>*
{
// Increment reference counter on every hashtable slot we attempt to allocate on
if (bits.ref == u16{umax})
{
fmt::throw_exception("Thread limit (65535) reached for a single hashtable slot.");
return nullptr;
}
if (bits.iptr == 0)
bits.iptr = ptr;
if (bits.maxc == 0 && bits.iptr != ptr && bits.ref)
bits.maxc = 1;
if (bits.maxd < limit)
bits.maxd = limit;
bits.ref++;
if (bits.bits != (1ull << max_threads) - 1)
{
const u32 id = std::countr_one(bits.bits);
bits.bits |= bits.bits + 1;
return _this->slots + id;
}
return nullptr;
});
if (slot)
{
break;
}
// Keep trying adjacent slots in the hashtable, they are often free due to alignment.
limit++;
if (limit == max_distance) [[unlikely]]
{
fmt::throw_exception("Distance limit (500) exceeded for the atomic wait hashtable.");
return nullptr;
}
}
return slot;
}
void root_info::slot_free(uptr iptr, atomic_t<u16>* slot, u32 tls_slot) noexcept
{
const auto begin = reinterpret_cast<uptr>(std::begin(s_hashtable));
const auto ptr = reinterpret_cast<uptr>(slot) - begin;
if (ptr >= sizeof(s_hashtable))
{
fmt::throw_exception("Failed to find slot in hashtable slot deallocation.");
return;
}
root_info* _this = &s_hashtable[ptr / sizeof(root_info)];
if (!(slot >= _this->slots && slot < std::end(_this->slots)))
{
fmt::throw_exception("Failed to find slot in hashtable slot deallocation.");
return;
}
const u32 diff = static_cast<u32>(slot - _this->slots);
ensure(slot == &_this->slots[diff]);
const u32 cond_id = slot->exchange(0);
if (cond_id)
{
cond_free(cond_id, tls_slot);
}
for (hash_engine curr(iptr);; curr.advance())
{
// Reset reference counter and allocation bit in every slot
curr->bits.atomic_op([&](slot_allocator& bits)
{
ensure(bits.ref--);
if (_this == curr.current())
{
bits.bits &= ~(1ull << diff);
}
});
if (_this == curr.current())
{
break;
}
}
}
template <typename F>
FORCE_INLINE auto root_info::slot_search(uptr iptr, F func) noexcept
{
u32 index = 0;
[[maybe_unused]] u32 total = 0;
for (hash_engine _this(iptr);; _this.advance())
{
const auto bits = _this->bits.load();
if (bits.ref == 0) [[likely]]
{
return;
}
u16 cond_ids[max_threads];
u32 cond_count = 0;
u64 bits_val = bits.bits;
for (u64 bits = bits_val; bits; bits &= bits - 1)
{
if (u16 cond_id = _this->slots[std::countr_zero(bits)])
{
utils::prefetch_read(s_cond_list + cond_id);
cond_ids[cond_count++] = cond_id;
}
}
for (u32 i = 0; i < cond_count; i++)
{
if (cond_id_lock(cond_ids[i], iptr))
{
if (func(cond_ids[i]))
{
return;
}
}
}
total += cond_count;
index++;
if (index == max_distance)
{
return;
}
}
}
SAFE_BUFFERS(void)
atomic_wait_engine::wait(const void* data, u32 old_value, u64 timeout, atomic_wait::info* ext)
{
uint ext_size = 0;
#ifdef __linux__
::timespec ts{};
if (timeout + 1)
{
if (ext && ext->data) [[unlikely]]
{
// futex_waitv uses absolute timeout
::clock_gettime(CLOCK_MONOTONIC, &ts);
}
ts.tv_sec += timeout / 1'000'000'000;
ts.tv_nsec += timeout % 1'000'000'000;
if (ts.tv_nsec >= 1'000'000'000)
{
ts.tv_sec++;
ts.tv_nsec -= 1'000'000'000;
}
}
futex_waitv vec[atomic_wait::max_list]{};
vec[0].flags = FUTEX_32 | FUTEX_PRIVATE_FLAG;
vec[0].uaddr = reinterpret_cast<__u64>(data);
vec[0].val = old_value;
if (ext) [[unlikely]]
{
for (auto e = ext; e->data; e++)
{
ext_size++;
vec[ext_size].flags = FUTEX_32 | FUTEX_PRIVATE_FLAG;
vec[ext_size].uaddr = reinterpret_cast<__u64>(e->data);
vec[ext_size].val = e->old;
}
}
if (ext_size && has_waitv()) [[unlikely]]
{
if (syscall(SYS_futex_waitv, +vec, ext_size + 1, 0, timeout + 1 ? &ts : nullptr, CLOCK_MONOTONIC) == -1)
{
if (errno == ENOSYS)
{
fmt::throw_exception("futex_waitv is not supported (Linux kernel is too old)");
}
if (errno == EINVAL)
{
fmt::throw_exception("futex_waitv: bad param");
}
}
return;
}
else if (has_waitv())
{
if (futex(const_cast<void*>(data), FUTEX_WAIT_PRIVATE, old_value, timeout + 1 ? &ts : nullptr) == -1)
{
if (errno == EINVAL)
{
fmt::throw_exception("futex: bad param");
}
}
return;
}
ext_size = 0;
#endif
if (!s_tls_wait_cb(data, 0, 0))
{
return;
}
const auto stamp0 = utils::get_unique_tsc();
const uptr iptr = reinterpret_cast<uptr>(data) & (~s_ref_mask >> 16);
uptr iptr_ext[atomic_wait::max_list - 1]{};
if (ext) [[unlikely]]
{
for (auto e = ext; e->data; e++)
{
if (data == e->data)
{
fmt::throw_exception("Address duplication in atomic_wait::list");
}
for (u32 j = 0; j < ext_size; j++)
{
if (e->data == ext[j].data)
{
fmt::throw_exception("Address duplication in atomic_wait::list");
}
}
iptr_ext[ext_size] = reinterpret_cast<uptr>(e->data) & (~s_ref_mask >> 16);
ext_size++;
}
}
const u32 cond_id = cond_alloc(iptr, 0);
u32 cond_id_ext[atomic_wait::max_list - 1]{};
for (u32 i = 0; i < ext_size; i++)
{
cond_id_ext[i] = cond_alloc(iptr_ext[i], i + 1);
}
const auto slot = root_info::slot_alloc(iptr);
std::array<atomic_t<u16>*, atomic_wait::max_list - 1> slot_ext{};
std::array<cond_handle*, atomic_wait::max_list - 1> cond_ext{};
for (u32 i = 0; i < ext_size; i++)
{
// Allocate slot for cond id location
slot_ext[i] = root_info::slot_alloc(iptr_ext[i]);
// Get pointers to the semaphores
cond_ext[i] = s_cond_list + cond_id_ext[i];
}
// Save for notifiers
const auto cond = s_cond_list + cond_id;
// Store some info for notifiers (some may be unused)
cond->link = 0;
cond->oldv = old_value;
cond->tsc0 = stamp0;
cond->sync.release(1);
for (u32 i = 0; i < ext_size; i++)
{
// Extensions point to original cond_id, copy remaining info
cond_ext[i]->link = cond_id;
cond_ext[i]->oldv = ext[i].old;
cond_ext[i]->tsc0 = stamp0;
// Cannot be notified, should be redirected to main semaphore
cond_ext[i]->sync.release(4);
}
// Final deployment
slot->store(static_cast<u16>(cond_id));
for (u32 i = 0; i < ext_size; i++)
{
slot_ext[i]->release(static_cast<u16>(cond_id_ext[i]));
}
#ifdef USE_STD
// Lock mutex
std::unique_lock lock(*cond->mtx.get());
#else
if (ext_size)
atomic_fence_seq_cst();
#endif
// Can skip unqueue process if true
#if defined(USE_FUTEX) || defined(USE_STD)
constexpr bool fallback = true;
#else
bool fallback = false;
#endif
u64 attempts = 0;
while (ptr_cmp(data, old_value, ext))
{
if (s_tls_one_time_wait_cb)
{
if (!s_tls_one_time_wait_cb(attempts))
{
break;
}
}
#ifdef USE_FUTEX
struct timespec ts;
ts.tv_sec = timeout / 1'000'000'000;
ts.tv_nsec = timeout % 1'000'000'000;
const u32 val = cond->sync;
if (val > 1) [[unlikely]]
{
// Signaled prematurely
if (!cond->set_sleep())
{
break;
}
}
else
{
futex(&cond->sync, FUTEX_WAIT_PRIVATE, val, timeout + 1 ? &ts : nullptr);
}
#elif defined(USE_STD)
if (cond->sync > 1) [[unlikely]]
{
if (!cond->set_sleep())
{
break;
}
}
else if (timeout + 1)
{
cond->cv->wait_for(lock, std::chrono::nanoseconds(timeout));
}
else
{
cond->cv->wait(lock);
}
#elif defined(_WIN32)
LARGE_INTEGER qw;
qw.QuadPart = -static_cast<s64>(timeout / 100);
if (timeout % 100)
{
// Round up to closest 100ns unit
qw.QuadPart -= 1;
}
if (fallback) [[unlikely]]
{
if (!cond->set_sleep())
{
if (cond->sync == 3)
{
break;
}
}
fallback = false;
}
else if (NtWaitForAlertByThreadId)
{
switch (DWORD status = NtWaitForAlertByThreadId(cond, timeout + 1 ? &qw : nullptr))
{
case NTSTATUS_ALERTED: fallback = true; break;
case NTSTATUS_TIMEOUT: break;
default:
{
SetLastError(status);
ensure(false); // Unexpected result
}
}
}
else
{
if (NtWaitForKeyedEvent(nullptr, &cond->sync, false, timeout + 1 ? &qw : nullptr) == NTSTATUS_SUCCESS)
{
// Error code assumed to be timeout
fallback = true;
}
}
#endif
if (!s_tls_wait_cb(data, ++attempts, stamp0))
{
break;
}
if (timeout + 1)
{
if (s_tls_one_time_wait_cb)
{
// The condition of the callback overrides timeout escape because it makes little sense to do so when a custom condition is passed
continue;
}
// TODO: reduce timeout instead
break;
}
}
while (!fallback)
{
#if defined(_WIN32)
static LARGE_INTEGER instant{};
if (cond->wakeup(1))
{
// Succeeded in self-notifying
break;
}
if (NtWaitForAlertByThreadId)
{
if (NtWaitForAlertByThreadId(cond, &instant) == NTSTATUS_ALERTED)
{
break;
}
continue;
}
if (!NtWaitForKeyedEvent(nullptr, &cond->sync, false, &instant))
{
// Succeeded in obtaining an event without waiting
break;
}
continue;
#endif
}
#ifdef USE_STD
if (lock)
{
lock.unlock();
}
#endif
// Release resources in reverse order
for (u32 i = ext_size - 1; i != umax; i--)
{
root_info::slot_free(iptr_ext[i], slot_ext[i], i + 1);
}
root_info::slot_free(iptr, slot, 0);
s_tls_wait_cb(data, -1, stamp0);
s_tls_one_time_wait_cb = nullptr;
}
template <bool NoAlert = false>
static u32 alert_sema(u32 cond_id, u32 size)
{
ensure(cond_id);
const auto cond = s_cond_list + cond_id;
u32 ok = 0;
if (true)
{
// Redirect if necessary
const auto _old = cond;
const auto _new = _old->link ? cond_id_lock(_old->link) : _old;
if (_new && _new->tsc0 == _old->tsc0)
{
if constexpr (NoAlert)
{
if (_new != _old)
{
// Keep base cond for actual alert attempt, free only secondary cond
ok = ~_old->link;
cond_free(cond_id);
return ok;
}
else
{
ok = ~cond_id;
return ok;
}
}
else if (_new->wakeup(size ? 1 : 2))
{
ok = cond_id;
{
_new->alert_native();
}
}
}
if (_new && _new != _old)
{
cond_free(_old->link);
}
}
// Remove lock, possibly deallocate cond
cond_free(cond_id);
return ok;
}
void atomic_wait_engine::set_wait_callback(bool(*cb)(const void*, u64, u64))
{
if (cb)
{
s_tls_wait_cb = cb;
}
else
{
s_tls_wait_cb = s_null_wait_cb;
}
}
void atomic_wait_engine::set_one_time_use_wait_callback(bool(*cb)(u64 progress))
{
s_tls_one_time_wait_cb = cb;
}
void atomic_wait_engine::notify_one(const void* data)
{
#ifdef __linux__
if (has_waitv())
{
futex(const_cast<void*>(data), FUTEX_WAKE_PRIVATE, 1);
return;
}
#endif
const uptr iptr = reinterpret_cast<uptr>(data) & (~s_ref_mask >> 16);
root_info::slot_search(iptr, [&](u32 cond_id)
{
if (alert_sema(cond_id, 4))
{
return true;
}
return false;
});
}
SAFE_BUFFERS(void)
atomic_wait_engine::notify_all(const void* data)
{
#ifdef __linux__
if (has_waitv())
{
futex(const_cast<void*>(data), FUTEX_WAKE_PRIVATE, INT_MAX);
return;
}
#endif
const uptr iptr = reinterpret_cast<uptr>(data) & (~s_ref_mask >> 16);
// Array count for batch notification
u32 count = 0;
// Array itself.
u32 cond_ids[128];
root_info::slot_search(iptr, [&](u32 cond_id)
{
if (count >= 128)
{
// Unusual big amount of sema: fallback to notify_one alg
alert_sema(cond_id, 4);
return false;
}
u32 res = alert_sema<true>(cond_id, 4);
if (~res <= u16{umax})
{
// Add to the end of the "stack"
*(std::end(cond_ids) - ++count) = ~res;
}
return false;
});
// Try alert
for (u32 i = 0; i < count; i++)
{
const u32 cond_id = *(std::end(cond_ids) - i - 1);
if (!s_cond_list[cond_id].wakeup(1))
{
*(std::end(cond_ids) - i - 1) = ~cond_id;
}
}
// Second stage (non-blocking alert attempts)
if (count > 1)
{
for (u32 i = 0; i < count; i++)
{
const u32 cond_id = *(std::end(cond_ids) - i - 1);
if (cond_id <= u16{umax})
{
if (s_cond_list[cond_id].try_alert_native())
{
*(std::end(cond_ids) - i - 1) = ~cond_id;
}
}
}
}
// Final stage and cleanup
for (u32 i = 0; i < count; i++)
{
const u32 cond_id = *(std::end(cond_ids) - i - 1);
if (cond_id <= u16{umax})
{
s_cond_list[cond_id].alert_native();
*(std::end(cond_ids) - i - 1) = ~cond_id;
}
}
for (u32 i = 0; i < count; i++)
{
cond_free(~*(std::end(cond_ids) - i - 1));
}
}
namespace atomic_wait
{
extern void parse_hashtable(bool(*cb)(u64 id, u32 refs, u64 ptr, u32 max_coll))
{
for (u64 i = 0; i < s_hashtable_size; i++)
{
const auto root = &s_hashtable[i];
const auto slot = root->bits.load();
if (cb(i, static_cast<u32>(slot.ref), slot.iptr, static_cast<u32>(slot.maxc)))
{
break;
}
}
}
}
| 26,690
|
C++
|
.cpp
| 1,126
| 20.563943
| 134
| 0.637815
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,038
|
sysinfo.cpp
|
RPCS3_rpcs3/rpcs3/util/sysinfo.cpp
|
#include "util/sysinfo.hpp"
#include "Utilities/StrFmt.h"
#include "Utilities/File.h"
#include "Emu/vfs_config.h"
#include "Utilities/Thread.h"
#if defined(ARCH_ARM64)
#include "Emu/CPU/Backends/AArch64/AArch64Common.h"
#endif
#ifdef _WIN32
#include "windows.h"
#include "sysinfoapi.h"
#include "subauth.h"
#include "stringapiset.h"
#else
#include <unistd.h>
#include <sys/resource.h>
#ifndef __APPLE__
#include <sys/utsname.h>
#include <errno.h>
#endif
#endif
#include <thread>
#include "util/asm.hpp"
#include "util/fence.hpp"
#if defined(_M_X64) && defined(_MSC_VER)
extern "C" u64 _xgetbv(u32);
#endif
#if defined(ARCH_X64)
static inline std::array<u32, 4> get_cpuid(u32 func, u32 subfunc)
{
int regs[4];
#ifdef _MSC_VER
__cpuidex(regs, func, subfunc);
#else
__asm__ volatile("cpuid" : "=a" (regs[0]), "=b" (regs[1]), "=c" (regs[2]), "=d" (regs[3]) : "a" (func), "c" (subfunc));
#endif
return {0u+regs[0], 0u+regs[1], 0u+regs[2], 0u+regs[3]};
}
static inline u64 get_xgetbv(u32 xcr)
{
#ifdef _MSC_VER
return _xgetbv(xcr);
#else
u32 eax, edx;
__asm__ volatile("xgetbv" : "=a"(eax), "=d"(edx) : "c"(xcr));
return eax | (u64(edx) << 32);
#endif
}
#endif
#ifdef __APPLE__
// sysinfo_darwin.mm
namespace Darwin_Version
{
extern int getNSmajorVersion();
extern int getNSminorVersion();
extern int getNSpatchVersion();
}
namespace Darwin_ProcessInfo
{
extern bool getLowPowerModeEnabled();
}
#endif
namespace utils
{
#ifdef _WIN32
// Alternative way to read OS version using the registry.
static std::string get_fallback_windows_version()
{
// Some helpers for sanity
const auto read_reg_dword = [](HKEY hKey, std::string_view value_name) -> std::pair<bool, DWORD>
{
DWORD val;
DWORD len = sizeof(val);
if (ERROR_SUCCESS != RegQueryValueExA(hKey, value_name.data(), nullptr, nullptr, reinterpret_cast<LPBYTE>(&val), &len))
{
return { false, 0 };
}
return { true, val };
};
const auto read_reg_sz = [](HKEY hKey, std::string_view value_name) -> std::pair<bool, std::string>
{
constexpr usz MAX_SZ_LEN = 255;
char sz[MAX_SZ_LEN + 1];
DWORD sz_len = MAX_SZ_LEN;
// Safety; null terminate
sz[0] = 0;
sz[MAX_SZ_LEN] = 0;
// Read string
if (ERROR_SUCCESS != RegQueryValueExA(hKey, value_name.data(), nullptr, nullptr, reinterpret_cast<LPBYTE>(sz), &sz_len))
{
return { false, "" };
}
// Safety, force null terminator
if (sz_len < MAX_SZ_LEN)
{
sz[sz_len] = 0;
}
return { true, sz };
};
HKEY hKey;
if (ERROR_SUCCESS != RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", 0, KEY_READ, &hKey))
{
return "Unknown Windows";
}
// ProductName (SZ) - Actual windows install name e.g Windows 10 Pro)
// CurrentMajorVersionNumber (DWORD) - e.g 10 for windows 10, 11 for windows 11
// CurrentMinorVersionNumber (DWORD) - usually 0 for newer windows, pairs with major version
// CurrentBuildNumber (SZ) - Windows build number, e.g 19045, used to identify different releases like 23H2, 24H2, etc
// CurrentVersion (SZ) - NT kernel version, e.g 6.3 for Windows 10
const auto [product_valid, product_name] = read_reg_sz(hKey, "ProductName");
if (!product_valid)
{
RegCloseKey(hKey);
return "Unknown Windows";
}
const auto [check_major, version_major] = read_reg_dword(hKey, "CurrentMajorVersionNumber");
const auto [check_minor, version_minor] = read_reg_dword(hKey, "CurrentMinorVersionNumber");
const auto [check_build_no, build_no] = read_reg_sz(hKey, "CurrentBuildNumber");
const auto [check_nt_ver, nt_ver] = read_reg_sz(hKey, "CurrentVersion");
// Close the registry key
RegCloseKey(hKey);
std::string version_id = "Unknown";
if (check_major && check_minor && check_build_no)
{
version_id = fmt::format("%u.%u.%s", version_major, version_minor, build_no);
if (check_nt_ver)
{
version_id += " NT" + nt_ver;
}
}
return fmt::format("Operating system: %s, Version %s", product_name, version_id);
}
#endif
}
bool utils::has_ssse3()
{
#if defined(ARCH_X64)
static const bool g_value = get_cpuid(0, 0)[0] >= 0x1 && get_cpuid(1, 0)[2] & 0x200;
return g_value;
#else
return false;
#endif
}
bool utils::has_sse41()
{
#if defined(ARCH_X64)
static const bool g_value = get_cpuid(0, 0)[0] >= 0x1 && get_cpuid(1, 0)[2] & 0x80000;
return g_value;
#else
return false;
#endif
}
bool utils::has_avx()
{
#if defined(ARCH_X64)
static const bool g_value = get_cpuid(0, 0)[0] >= 0x1 && get_cpuid(1, 0)[2] & 0x10000000 && (get_cpuid(1, 0)[2] & 0x0C000000) == 0x0C000000 && (get_xgetbv(0) & 0x6) == 0x6;
return g_value;
#else
return false;
#endif
}
bool utils::has_avx2()
{
#if defined(ARCH_X64)
static const bool g_value = get_cpuid(0, 0)[0] >= 0x7 && get_cpuid(7, 0)[1] & 0x20 && (get_cpuid(1, 0)[2] & 0x0C000000) == 0x0C000000 && (get_xgetbv(0) & 0x6) == 0x6;
return g_value;
#else
return false;
#endif
}
bool utils::has_rtm()
{
#if defined(ARCH_X64)
static const bool g_value = get_cpuid(0, 0)[0] >= 0x7 && (get_cpuid(7, 0)[1] & 0x800) == 0x800;
return g_value;
#elif defined(ARCH_ARM64)
return false;
#endif
}
bool utils::has_tsx_force_abort()
{
#if defined(ARCH_X64)
static const bool g_value = get_cpuid(0, 0)[0] >= 0x7 && (get_cpuid(7, 0)[3] & 0x2000) == 0x2000;
return g_value;
#else
return false;
#endif
}
bool utils::has_rtm_always_abort()
{
#if defined(ARCH_X64)
static const bool g_value = get_cpuid(0, 0)[0] >= 0x7 && (get_cpuid(7, 0)[3] & 0x800) == 0x800;
return g_value;
#else
return false;
#endif
}
bool utils::has_mpx()
{
#if defined(ARCH_X64)
static const bool g_value = get_cpuid(0, 0)[0] >= 0x7 && (get_cpuid(7, 0)[1] & 0x4000) == 0x4000;
return g_value;
#else
return false;
#endif
}
bool utils::has_avx512()
{
#if defined(ARCH_X64)
// Check AVX512F, AVX512CD, AVX512DQ, AVX512BW, AVX512VL extensions (Skylake-X level support)
static const bool g_value = get_cpuid(0, 0)[0] >= 0x7 && (get_cpuid(7, 0)[1] & 0xd0030000) == 0xd0030000 && (get_cpuid(1, 0)[2] & 0x0C000000) == 0x0C000000 && (get_xgetbv(0) & 0xe6) == 0xe6;
return g_value;
#else
return false;
#endif
}
bool utils::has_avx512_icl()
{
#if defined(ARCH_X64)
// Check AVX512IFMA, AVX512VBMI, AVX512VBMI2, AVX512VPOPCNTDQ, AVX512BITALG, AVX512VNNI, AVX512VPCLMULQDQ, AVX512GFNI, AVX512VAES (Icelake-client level support)
static const bool g_value = has_avx512() && (get_cpuid(7, 0)[1] & 0x00200000) == 0x00200000 && (get_cpuid(7, 0)[2] & 0x00005f42) == 0x00005f42;
return g_value;
#else
return false;
#endif
}
bool utils::has_avx512_vnni()
{
#if defined(ARCH_X64)
// Check AVX512VNNI
static const bool g_value = has_avx512() && get_cpuid(7, 0)[2] & 0x00000800;
return g_value;
#else
return false;
#endif
}
bool utils::has_avx10()
{
#if defined(ARCH_X64)
// Implies support for most AVX-512 instructions
static const bool g_value = get_cpuid(0, 0)[0] >= 0x7 && get_cpuid(7, 1)[3] & 0x80000;
return g_value;
#else
return false;
#endif
}
bool utils::has_avx10_512()
{
#if defined(ARCH_X64)
// AVX10 with 512 wide vectors
static const bool g_value = has_avx10() && get_cpuid(24, 0)[2] & 0x40000;
return g_value;
#else
return false;
#endif
}
u32 utils::avx10_isa_version()
{
#if defined(ARCH_X64)
// 8bit value
static const u32 g_value = []()
{
u32 isa_version = 0;
if (has_avx10())
{
isa_version = get_cpuid(24, 0)[2] & 0x000ff;
}
return isa_version;
}();
return g_value;
#else
return 0;
#endif
}
bool utils::has_avx512_256()
{
#if defined(ARCH_X64)
// Either AVX10 or AVX512 implies support for 256-bit length AVX-512 SKL-X tier instructions
static const bool g_value = (has_avx512() || has_avx10());
return g_value;
#else
return false;
#endif
}
bool utils::has_avx512_icl_256()
{
#if defined(ARCH_X64)
// Check for AVX512_ICL or check for AVX10, together with GFNI, VAES, and VPCLMULQDQ, implies support for the same instructions that AVX-512_icl does at 256 bit length
static const bool g_value = (has_avx512_icl() || (has_avx10() && get_cpuid(7, 0)[2] & 0x00000700));
return g_value;
#else
return false;
#endif
}
bool utils::has_xop()
{
#if defined(ARCH_X64)
static const bool g_value = has_avx() && get_cpuid(0x80000001, 0)[2] & 0x800;
return g_value;
#else
return false;
#endif
}
bool utils::has_clwb()
{
#if defined(ARCH_X64)
static const bool g_value = get_cpuid(0, 0)[0] >= 0x7 && (get_cpuid(7, 0)[1] & 0x1000000) == 0x1000000;
return g_value;
#else
return false;
#endif
}
bool utils::has_invariant_tsc()
{
#if defined(ARCH_X64)
static const bool g_value = get_cpuid(0, 0)[0] >= 0x7 && (get_cpuid(0x80000007, 0)[3] & 0x100) == 0x100;
return g_value;
#elif defined(ARCH_ARM64)
return true;
#endif
}
bool utils::has_fma3()
{
#if defined(ARCH_X64)
static const bool g_value = get_cpuid(0, 0)[0] >= 0x1 && get_cpuid(1, 0)[2] & 0x1000;
return g_value;
#elif defined(ARCH_ARM64)
return true;
#endif
}
bool utils::has_fma4()
{
#if defined(ARCH_X64)
static const bool g_value = get_cpuid(0, 0)[0] >= 0x7 && (get_cpuid(0x80000001, 0)[2] & 0x10000) == 0x10000;
return g_value;
#else
return false;
#endif
}
// The Zen4 based CPUs support VPERMI2B/VPERMT2B in a single uop.
// Current Intel cpus (as of 2022) need 3 uops to execute these instructions.
// Check for SSE4A (which intel doesn't doesn't support) as well as VBMI.
bool utils::has_fast_vperm2b()
{
#if defined(ARCH_X64)
static const bool g_value = has_avx512() && (get_cpuid(7, 0)[2] & 0x2) == 0x2 && get_cpuid(0, 0)[0] >= 0x7 && (get_cpuid(0x80000001, 0)[2] & 0x40) == 0x40;
return g_value;
#else
return false;
#endif
}
bool utils::has_erms()
{
#if defined(ARCH_X64)
static const bool g_value = get_cpuid(0, 0)[0] >= 0x7 && (get_cpuid(7, 0)[1] & 0x200) == 0x200;
return g_value;
#else
return false;
#endif
}
bool utils::has_fsrm()
{
#if defined(ARCH_X64)
static const bool g_value = get_cpuid(0, 0)[0] >= 0x7 && (get_cpuid(7, 0)[3] & 0x10) == 0x10;
return g_value;
#else
return false;
#endif
}
bool utils::has_waitx()
{
#if defined(ARCH_X64)
static const bool g_value = get_cpuid(0, 0)[0] >= 0x7 && (get_cpuid(0x80000001, 0)[2] & 0x20000000) == 0x20000000;
return g_value;
#else
return false;
#endif
}
bool utils::has_waitpkg()
{
#if defined(ARCH_X64)
static const bool g_value = get_cpuid(0, 0)[0] >= 0x7 && (get_cpuid(7, 0)[2] & 0x20) == 0x20;
return g_value;
#else
return false;
#endif
}
// User mode waits may be unfriendly to low thread CPUs
// Filter out systems with less than 8 threads for linux and less than 12 threads for other platforms
bool utils::has_appropriate_um_wait()
{
#ifdef __linux__
static const bool g_value = (has_waitx() || has_waitpkg()) && (get_thread_count() >= 8) && get_tsc_freq();
return g_value;
#else
static const bool g_value = (has_waitx() || has_waitpkg()) && (get_thread_count() >= 12) && get_tsc_freq();
return g_value;
#endif
}
// Similar to the above function but allow execution if alternatives such as yield are not wanted
bool utils::has_um_wait()
{
static const bool g_value = (has_waitx() || has_waitpkg()) && get_tsc_freq();
return g_value;
}
u32 utils::get_rep_movsb_threshold()
{
static const u32 g_value = []()
{
u32 thresh_value = umax;
if (has_fsrm())
{
thresh_value = 2047;
}
else if (has_erms())
{
thresh_value = 4095;
}
return thresh_value;
}();
return g_value;
}
std::string utils::get_cpu_brand()
{
#if defined(ARCH_X64)
std::string brand;
if (get_cpuid(0x80000000, 0)[0] >= 0x80000004)
{
for (u32 i = 0; i < 3; i++)
{
brand.append(reinterpret_cast<const char*>(get_cpuid(0x80000002 + i, 0).data()), 16);
}
}
else
{
brand = "Unknown CPU";
}
brand.erase(brand.find_last_not_of('\0') + 1);
brand.erase(brand.find_last_not_of(' ') + 1);
brand.erase(0, brand.find_first_not_of(' '));
while (auto found = brand.find(" ") + 1)
{
brand.erase(brand.begin() + found);
}
return brand;
#elif defined(ARCH_ARM64)
static const auto g_cpu_brand = aarch64::get_cpu_brand();
return g_cpu_brand;
#else
return "Unidentified CPU";
#endif
}
std::string utils::get_system_info()
{
std::string result;
const std::string brand = get_cpu_brand();
const u64 mem_total = get_total_memory();
const u32 num_proc = get_thread_count();
fmt::append(result, "%s | %d Threads | %.2f GiB RAM", brand, num_proc, mem_total / (1024.0f * 1024 * 1024));
if (const ullong tsc_freq = get_tsc_freq())
{
fmt::append(result, " | TSC: %.03fGHz", tsc_freq / 1000000000.);
}
else
{
fmt::append(result, " | TSC: Bad");
}
if (has_avx())
{
result += " | AVX";
if (has_avx10())
{
const u32 avx10_version = avx10_isa_version();
fmt::append(result, "10.%d", avx10_version);
if (has_avx10_512())
{
result += "-512";
}
else
{
result += "-256";
}
}
else if (has_avx512())
{
result += "-512";
if (has_avx512_icl())
{
result += '+';
}
}
else if (has_avx2())
{
result += '+';
}
if (has_xop())
{
result += 'x';
}
}
if (has_fma3() || has_fma4())
{
result += " | FMA";
if (has_fma3() && has_fma4())
{
result += "3+4";
}
else if (has_fma3())
{
result += "3";
}
else if (has_fma4())
{
result += "4";
}
}
if (has_rtm())
{
result += " | TSX";
if (has_tsx_force_abort())
{
result += "-FA";
}
if (!has_mpx() || has_tsx_force_abort())
{
result += " disabled by default";
}
}
else if (has_rtm_always_abort())
{
result += " | TSX disabled via microcode";
}
return result;
}
std::string utils::get_firmware_version()
{
const std::string file_path = g_cfg_vfs.get_dev_flash() + "vsh/etc/version.txt";
if (fs::file version_file{file_path})
{
const std::string version_str = version_file.to_string();
std::string_view version = version_str;
// Extract version
const usz start = version.find_first_of(':') + 1;
const usz end = version.find_first_of(':', start);
if (!start || end == umax)
{
return {};
}
version = version.substr(start, end - start);
// Trim version (e.g. '04.8900' becomes '4.89')
usz trim_start = version.find_first_not_of('0');
if (trim_start == umax)
{
return {};
}
// Keep at least one preceding 0 (e.g. '00.3100' becomes '0.31' instead of '.31')
if (version[trim_start] == '.')
{
if (trim_start == 0)
{
// Version starts with '.' for some reason
return {};
}
trim_start--;
}
const usz dot_pos = version.find_first_of('.', trim_start);
if (dot_pos == umax)
{
return {};
}
// Try to keep the second 0 in the minor version (e.g. '04.9000' becomes '4.90' instead of '4.9')
const usz trim_end = std::max(version.find_last_not_of('0', dot_pos + 1), std::min(dot_pos + 2, version.size()));
return std::string(version.substr(trim_start, trim_end));
}
return {};
}
std::string utils::get_OS_version()
{
std::string output;
#ifdef _WIN32
// GetVersionEx is deprecated, RtlGetVersion is kernel-mode only and AnalyticsInfo is UWP only.
// So we're forced to read PEB instead to get Windows version info. It's ugly but works.
#if defined(ARCH_X64)
const DWORD peb_offset = 0x60;
const INT_PTR peb = __readgsqword(peb_offset);
const DWORD version_major = *reinterpret_cast<const DWORD*>(peb + 0x118);
const DWORD version_minor = *reinterpret_cast<const DWORD*>(peb + 0x11c);
const WORD build = *reinterpret_cast<const WORD*>(peb + 0x120);
const UNICODE_STRING service_pack = *reinterpret_cast<const UNICODE_STRING*>(peb + 0x02E8);
const u64 compatibility_mode = *reinterpret_cast<const u64*>(peb + 0x02C8); // Two DWORDs, major & minor version
const bool has_sp = service_pack.Length > 0;
std::vector<char> holder(service_pack.Length + 1, '\0');
if (has_sp)
{
WideCharToMultiByte(CP_UTF8, 0, service_pack.Buffer, service_pack.Length,
static_cast<LPSTR>(holder.data()), static_cast<int>(holder.size()), nullptr, nullptr);
}
fmt::append(output,
"Operating system: Windows, Major: %lu, Minor: %lu, Build: %u, Service Pack: %s, Compatibility mode: %llu",
version_major, version_minor, build, has_sp ? holder.data() : "none", compatibility_mode);
#else
// PEB cannot be easily accessed on ARM64, fall back to registry
static const auto s_windows_version = utils::get_fallback_windows_version();
return s_windows_version;
#endif
#elif defined (__APPLE__)
const int major_version = Darwin_Version::getNSmajorVersion();
const int minor_version = Darwin_Version::getNSminorVersion();
const int patch_version = Darwin_Version::getNSpatchVersion();
fmt::append(output, "Operating system: macOS, Version: %d.%d.%d",
major_version, minor_version, patch_version);
#else
struct utsname details = {};
if (!uname(&details))
{
fmt::append(output, "Operating system: POSIX, Name: %s, Release: %s, Version: %s",
details.sysname, details.release, details.version);
}
else
{
fmt::append(output, "Operating system: POSIX, Unknown version! (Error: %d)", errno);
}
#endif
return output;
}
int utils::get_maxfiles()
{
#ifdef _WIN32
// Virtually unlimited on Windows
return INT_MAX;
#else
struct rlimit limits;
ensure(getrlimit(RLIMIT_NOFILE, &limits) == 0);
return limits.rlim_cur;
#endif
}
bool utils::get_low_power_mode()
{
#ifdef __APPLE__
return Darwin_ProcessInfo::getLowPowerModeEnabled();
#else
return false;
#endif
}
static constexpr ullong round_tsc(ullong val, ullong known_error)
{
if (known_error >= 500'000)
{
// Do not accept large errors
return 0;
}
ullong by = 1000;
known_error /= 1000;
while (known_error && by < 100'000)
{
by *= 10;
known_error /= 10;
}
return utils::rounded_div(val, by) * by;
}
namespace utils
{
u64 s_tsc_freq = 0;
}
static const bool s_tsc_freq_evaluated = []() -> bool
{
static const ullong cal_tsc = []() -> ullong
{
#ifdef ARCH_ARM64
u64 r = 0;
__asm__ volatile("mrs %0, cntfrq_el0" : "=r" (r));
return r;
#endif
if (!utils::has_invariant_tsc())
return 0;
#ifdef _WIN32
LARGE_INTEGER freq;
if (!QueryPerformanceFrequency(&freq))
return 0;
if (freq.QuadPart <= 9'999'999)
return 0;
const ullong timer_freq = freq.QuadPart;
#else
constexpr ullong timer_freq = 1'000'000'000;
#endif
constexpr u64 retry_count = 1024;
// First is entry is for the onset measurements, last is for the end measurements
constexpr usz sample_count = 2;
std::array<u64, sample_count> rdtsc_data{};
std::array<u64, sample_count> rdtsc_diff{};
std::array<u64, sample_count> timer_data{};
#ifdef _WIN32
LARGE_INTEGER ctr0;
QueryPerformanceCounter(&ctr0);
const ullong time_base = ctr0.QuadPart;
#else
struct timespec ts0;
clock_gettime(CLOCK_MONOTONIC, &ts0);
const ullong sec_base = ts0.tv_sec;
#endif
constexpr usz sleep_time_ms = 40;
for (usz sample = 0; sample < sample_count; sample++)
{
for (usz i = 0; i < retry_count; i++)
{
const u64 rdtsc_read = (utils::lfence(), utils::get_tsc());
#ifdef _WIN32
LARGE_INTEGER ctr;
QueryPerformanceCounter(&ctr);
#else
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
#endif
const u64 rdtsc_read2 = (utils::lfence(), utils::get_tsc());
#ifdef _WIN32
const u64 timer_read = ctr.QuadPart - time_base;
#else
const u64 timer_read = ts.tv_nsec + (ts.tv_sec - sec_base) * 1'000'000'000;
#endif
if (i == 0 || (rdtsc_read2 >= rdtsc_read && rdtsc_read2 - rdtsc_read < rdtsc_diff[sample]))
{
rdtsc_data[sample] = rdtsc_read; // Note: rdtsc_read2 can also be written here because of the assumption of accuracy
timer_data[sample] = timer_read;
rdtsc_diff[sample] = rdtsc_read2 >= rdtsc_read ? rdtsc_read2 - rdtsc_read : u64{umax};
}
// 80 results in an error range of 4000 hertz (0.00025% of 4GHz CPU, quite acceptable)
// Error of 2.5 seconds per month
if (rdtsc_read2 - rdtsc_read < 80 && rdtsc_read2 >= rdtsc_read)
{
break;
}
// 8 yields seems to reduce significantly thread contention, improving accuracy
// Even 3 seem to do the job though, but just in case
if (i % 128 == 64)
{
std::this_thread::yield();
}
// Take 50% more yields with the last sample because it helps accuracy additionally the more time that passes
if (sample == sample_count - 1 && i % 256 == 128)
{
std::this_thread::yield();
}
}
if (sample < sample_count - 1)
{
// Sleep between first and last sample
#ifdef _WIN32
Sleep(sleep_time_ms);
#else
usleep(sleep_time_ms * 1000);
#endif
}
}
if (timer_data[1] == timer_data[0])
{
// Division by zero
return 0;
}
const u128 data = u128_from_mul(rdtsc_data[1] - rdtsc_data[0], timer_freq);
const u64 res = utils::udiv128(static_cast<u64>(data >> 64), static_cast<u64>(data), (timer_data[1] - timer_data[0]));
// Rounding
return round_tsc(res, utils::mul_saturate<u64>(utils::add_saturate<u64>(rdtsc_diff[0], rdtsc_diff[1]), utils::aligned_div(timer_freq, timer_data[1] - timer_data[0])));
}();
atomic_storage<u64>::release(utils::s_tsc_freq, cal_tsc);
return true;
}();
u64 utils::get_total_memory()
{
#ifdef _WIN32
::MEMORYSTATUSEX memInfo;
memInfo.dwLength = sizeof(memInfo);
::GlobalMemoryStatusEx(&memInfo);
return memInfo.ullTotalPhys;
#else
return ::sysconf(_SC_PHYS_PAGES) * ::sysconf(_SC_PAGE_SIZE);
#endif
}
u32 utils::get_thread_count()
{
static const u32 g_count = []()
{
#ifdef _WIN32
::SYSTEM_INFO sysInfo;
::GetNativeSystemInfo(&sysInfo);
return sysInfo.dwNumberOfProcessors;
#else
return ::sysconf(_SC_NPROCESSORS_ONLN);
#endif
}();
return g_count;
}
u32 utils::get_cpu_family()
{
#if defined(ARCH_X64)
static const u32 g_value = []()
{
const u32 reg_value = get_cpuid(0x00000001, 0)[0]; // Processor feature info
const u32 base_value = (reg_value >> 8) & 0xF;
if (base_value == 0xF) [[likely]]
{
const u32 extended_value = (reg_value >> 20) & 0xFF;
return base_value + extended_value;
}
else
{
return base_value;
}
}();
return g_value;
#elif defined(ARCH_ARM64)
return 0;
#endif
}
u32 utils::get_cpu_model()
{
#if defined(ARCH_X64)
static const u32 g_value = []()
{
const u32 reg_value = get_cpuid(0x00000001, 0)[0]; // Processor feature info
const u32 base_value = (reg_value >> 4) & 0xF;
if (const auto base_family_id = (reg_value >> 8) & 0xF;
base_family_id == 0x6 || base_family_id == 0xF) [[likely]]
{
const u32 extended_value = (reg_value >> 16) & 0xF;
return base_value + (extended_value << 4);
}
else
{
return base_value;
}
}();
return g_value;
#elif defined(ARCH_ARM64)
return 0;
#endif
}
namespace utils
{
u64 _get_main_tid()
{
return thread_ctrl::get_tid();
}
}
| 22,563
|
C++
|
.cpp
| 843
| 24.441281
| 191
| 0.675328
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,039
|
video_provider.cpp
|
RPCS3_rpcs3/rpcs3/util/video_provider.cpp
|
#include "stdafx.h"
#include "video_provider.h"
#include "Emu/RSX/Overlays/overlay_message.h"
extern "C"
{
#include <libavutil/pixfmt.h>
}
LOG_CHANNEL(media_log, "Media");
atomic_t<recording_mode> g_recording_mode = recording_mode::stopped;
template <>
void fmt_class_string<recording_mode>::format(std::string& out, u64 arg)
{
format_enum(out, arg, [](recording_mode value)
{
switch (value)
{
case recording_mode::stopped: return "stopped";
case recording_mode::rpcs3: return "rpcs3";
case recording_mode::cell: return "cell";
}
return unknown;
});
}
namespace utils
{
video_provider::~video_provider()
{
g_recording_mode = recording_mode::stopped;
}
bool video_provider::set_video_sink(std::shared_ptr<video_sink> sink, recording_mode type)
{
media_log.notice("video_provider: setting new video sink. sink=%d, type=%s", !!sink, type);
if (type == recording_mode::stopped)
{
// Prevent misuse. type is supposed to be a valid state.
media_log.error("video_provider: cannot set video sink with type %s", type);
return false;
}
std::scoped_lock lock(m_video_mutex, m_audio_mutex);
if (m_video_sink)
{
// cell has preference
if (m_type == recording_mode::cell && m_type != type)
{
media_log.warning("video_provider: cannot set video sink with type %s if type %s is active", type, m_type);
return false;
}
if (m_type != type || m_video_sink != sink)
{
media_log.warning("video_provider: stopping current video sink of type %s", m_type);
m_video_sink->stop();
}
}
m_type = sink ? type : recording_mode::stopped;
m_video_sink = sink;
m_active = (m_type != recording_mode::stopped);
if (!m_active)
{
m_last_video_pts_incoming = -1;
m_last_audio_pts_incoming = -1;
m_start_time_us.store(umax);
}
return true;
}
void video_provider::set_pause_time_us(usz pause_time_us)
{
std::scoped_lock lock(m_video_mutex, m_audio_mutex);
m_pause_time_us = pause_time_us;
}
recording_mode video_provider::check_mode()
{
if (!m_video_sink || m_video_sink->has_error)
{
g_recording_mode = recording_mode::stopped;
rsx::overlays::queue_message(localized_string_id::RECORDING_ABORTED);
}
if (g_recording_mode == recording_mode::stopped)
{
m_active = false;
}
return g_recording_mode;
}
bool video_provider::can_consume_frame()
{
if (!m_active)
{
return false;
}
std::lock_guard lock_video(m_video_mutex);
if (!m_video_sink || !m_video_sink->use_internal_video)
{
return false;
}
const usz elapsed_us = get_system_time() - m_start_time_us;
ensure(elapsed_us >= m_pause_time_us);
const usz timestamp_ms = (elapsed_us - m_pause_time_us) / 1000;
const s64 pts = m_video_sink->get_pts(timestamp_ms);
return pts > m_last_video_pts_incoming;
}
void video_provider::present_frame(std::vector<u8>& data, u32 pitch, u32 width, u32 height, bool is_bgra)
{
if (!m_active)
{
return;
}
std::lock_guard lock_video(m_video_mutex);
if (check_mode() == recording_mode::stopped)
{
return;
}
const u64 current_time_us = get_system_time();
if (m_start_time_us.compare_and_swap_test(umax, current_time_us))
{
media_log.notice("video_provider: start time = %d", current_time_us);
}
// Calculate presentation timestamp.
const usz elapsed_us = current_time_us - m_start_time_us;
ensure(elapsed_us >= m_pause_time_us);
const usz timestamp_ms = (elapsed_us - m_pause_time_us) / 1000;
const s64 pts = m_video_sink->get_pts(timestamp_ms);
// We can just skip this frame if it has the same timestamp.
if (pts <= m_last_video_pts_incoming)
{
return;
}
if (m_video_sink->add_frame(data, pitch, width, height, is_bgra ? AVPixelFormat::AV_PIX_FMT_BGRA : AVPixelFormat::AV_PIX_FMT_RGBA, timestamp_ms))
{
m_last_video_pts_incoming = pts;
}
}
void video_provider::present_samples(u8* buf, u32 sample_count, u16 channels)
{
if (!buf || !sample_count || !channels || !m_active)
{
return;
}
std::lock_guard lock_audio(m_audio_mutex);
if (!m_video_sink || !m_video_sink->use_internal_audio)
{
return;
}
if (check_mode() == recording_mode::stopped)
{
return;
}
const u64 current_time_us = get_system_time();
if (m_start_time_us.compare_and_swap_test(umax, current_time_us))
{
media_log.notice("video_provider: start time = %d", current_time_us);
}
// Calculate presentation timestamp.
const usz elapsed_us = current_time_us - m_start_time_us;
ensure(elapsed_us >= m_pause_time_us);
const usz timestamp_us = elapsed_us - m_pause_time_us;
const s64 pts = m_video_sink->get_audio_pts(timestamp_us);
// We can just skip this sample if it has the same timestamp.
if (pts <= m_last_audio_pts_incoming)
{
return;
}
if (m_video_sink->add_audio_samples(buf, sample_count, channels, timestamp_us))
{
m_last_audio_pts_incoming = pts;
}
}
}
| 4,915
|
C++
|
.cpp
| 166
| 26.46988
| 147
| 0.683875
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,040
|
console.cpp
|
RPCS3_rpcs3/rpcs3/util/console.cpp
|
#include "console.h"
#ifdef _WIN32
#include "Windows.h"
#include <stdio.h>
#endif
#include <iostream>
namespace utils
{
void attach_console([[maybe_unused]] int stream, [[maybe_unused]] bool open_console)
{
#ifdef _WIN32
if (!stream)
{
return;
}
if (!(AttachConsole(ATTACH_PARENT_PROCESS) || (open_console && AllocConsole())))
{
return;
}
if (stream & console_stream::std_out)
{
[[maybe_unused]] const auto con_out = freopen("CONOUT$", "w", stdout);
}
if (stream & console_stream::std_err)
{
[[maybe_unused]] const auto con_err = freopen("CONOUT$", "w", stderr);
}
if (stream & console_stream::std_in)
{
[[maybe_unused]] const auto con_in = freopen("CONIN$", "r", stdin);
}
#endif
}
void output_stderr(std::string_view str, bool with_endline)
{
if (with_endline)
{
#ifdef _WIN32
std::clog << str;
#else
std::cerr << str;
#endif
str = "\n";
}
#ifdef _WIN32
// Flush seems broken on Windows (deadlocks)
std::clog << str;
#else
std::cerr << str;
#endif
}
}
| 1,035
|
C++
|
.cpp
| 52
| 17.346154
| 85
| 0.649897
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,041
|
dyn_lib.cpp
|
RPCS3_rpcs3/rpcs3/util/dyn_lib.cpp
|
#include "stdafx.h"
#include "dyn_lib.hpp"
#ifdef _WIN32
#include <Windows.h>
#else
#include <dlfcn.h>
#endif
namespace utils
{
dynamic_library::dynamic_library(const std::string& path)
{
load(path);
}
dynamic_library::~dynamic_library()
{
close();
}
bool dynamic_library::load(const std::string& path)
{
#ifdef _WIN32
m_handle = LoadLibraryA(path.c_str());
#else
m_handle = dlopen(path.c_str(), RTLD_LAZY);
#endif
return loaded();
}
void dynamic_library::close()
{
#ifdef _WIN32
FreeLibrary(reinterpret_cast<HMODULE>(m_handle));
#else
dlclose(m_handle);
#endif
m_handle = nullptr;
}
void* dynamic_library::get_impl(const std::string& name) const
{
#ifdef _WIN32
return reinterpret_cast<void*>(GetProcAddress(reinterpret_cast<HMODULE>(m_handle), name.c_str()));
#else
return dlsym(m_handle, name.c_str());
#endif
}
bool dynamic_library::loaded() const
{
return m_handle != nullptr;
}
dynamic_library::operator bool() const
{
return loaded();
}
void* get_proc_address(const char* lib, const char* name)
{
#ifdef _WIN32
return reinterpret_cast<void*>(GetProcAddress(GetModuleHandleA(lib), name));
#else
return dlsym(dlopen(lib, RTLD_NOLOAD), name);
#endif
}
}
| 1,221
|
C++
|
.cpp
| 60
| 18.3
| 100
| 0.723958
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
5,042
|
yaml.cpp
|
RPCS3_rpcs3/rpcs3/util/yaml.cpp
|
#include "util/yaml.hpp"
#include "util/types.hpp"
#include "Utilities/cheat_info.h"
#include "Utilities/Config.h"
namespace YAML
{
template <>
struct convert<cheat_info>
{
static bool decode(const Node& node, cheat_info& rhs)
{
if (node.size() != 3)
{
return false;
}
rhs.description = node[0].Scalar();
u64 type64 = 0;
if (!cfg::try_to_enum_value(&type64, &fmt_class_string<cheat_type>::format, node[1].Scalar()))
return false;
if (type64 >= cheat_type_max)
return false;
rhs.type = cheat_type{::narrow<u8>(type64)};
rhs.red_script = node[2].Scalar();
return true;
}
};
} // namespace YAML
std::pair<YAML::Node, std::string> yaml_load(const std::string& from)
{
YAML::Node result;
try
{
result = YAML::Load(from);
}
catch (const std::exception& e)
{
return {YAML::Node(), std::string("YAML exception: ") + e.what()};
}
return {result, ""};
}
template <typename T>
T get_yaml_node_value(const YAML::Node& node, std::string& error_message)
{
try
{
return node.as<T>();
}
catch (const std::exception& e)
{
error_message = e.what();
}
return {};
}
std::string get_yaml_node_location(const YAML::Node& node)
{
try
{
const auto mark = node.Mark();
if (mark.is_null())
return "unknown";
return fmt::format("line %d, column %d", mark.line, mark.column); // Don't need the pos. It's not really useful.
}
catch (const std::exception& e)
{
return e.what();
}
}
std::string get_yaml_node_location(const YAML::detail::iterator_value& it)
{
return get_yaml_node_location(it.first);
}
template u8 get_yaml_node_value<u8>(const YAML::Node&, std::string&);
template s8 get_yaml_node_value<s8>(const YAML::Node&, std::string&);
template u16 get_yaml_node_value<u16>(const YAML::Node&, std::string&);
template s16 get_yaml_node_value<s16>(const YAML::Node&, std::string&);
template u32 get_yaml_node_value<u32>(const YAML::Node&, std::string&);
template s32 get_yaml_node_value<s32>(const YAML::Node&, std::string&);
template u64 get_yaml_node_value<u64>(const YAML::Node&, std::string&);
template s64 get_yaml_node_value<s64>(const YAML::Node&, std::string&);
template f32 get_yaml_node_value<f32>(const YAML::Node&, std::string&);
template f64 get_yaml_node_value<f64>(const YAML::Node&, std::string&);
template std::string get_yaml_node_value<std::string>(const YAML::Node&, std::string&);
template cheat_info get_yaml_node_value<cheat_info>(const YAML::Node&, std::string&);
| 2,478
|
C++
|
.cpp
| 83
| 27.590361
| 114
| 0.689887
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,043
|
serialization_ext.cpp
|
RPCS3_rpcs3/rpcs3/util/serialization_ext.cpp
|
#include "util/types.hpp"
#include "util/logs.hpp"
#include "util/asm.hpp"
#include "util/simd.hpp"
#include "util/endian.hpp"
#include "Utilities/lockless.h"
#include "Utilities/File.h"
#include "Utilities/StrFmt.h"
#include "serialization_ext.hpp"
#include <zlib.h>
#include <zstd.h>
LOG_CHANNEL(sys_log, "SYS");
template <>
void fmt_class_string<utils::serial>::format(std::string& out, u64 arg)
{
const utils::serial& ar = get_object(arg);
be_t<u64> sample64 = 0;
const usz read_size = std::min<usz>(ar.data.size(), sizeof(sample64));
std::memcpy(&sample64, ar.data.data() + ar.data.size() - read_size, read_size);
fmt::append(out, "{ %s, 0x%x/0x%x, memory=0x%x, sample64=0x%016x }", ar.is_writing() ? "writing" : "reading", ar.pos, ar.data_offset + ar.data.size(), ar.data.size(), sample64);
}
static constexpr uInt adjust_for_uint(usz size)
{
return static_cast<uInt>(std::min<usz>(uInt{umax}, size));
}
bool uncompressed_serialization_file_handler::handle_file_op(utils::serial& ar, usz pos, usz size, const void* data)
{
if (ar.is_writing())
{
if (data)
{
m_file->seek(pos);
m_file->write(data, size);
return true;
}
m_file->seek(ar.data_offset);
m_file->write(ar.data);
if (pos == umax && size == umax)
{
// Request to flush the file to disk
m_file->sync();
}
ar.seek_end();
ar.data_offset = ar.pos;
ar.data.clear();
return true;
}
if (!size)
{
return true;
}
if (pos == 0 && size == umax)
{
// Discard loaded data until pos if profitable
const usz limit = ar.data_offset + ar.data.size();
if (ar.pos > ar.data_offset && ar.pos < limit)
{
const usz may_discard_bytes = ar.pos - ar.data_offset;
const usz moved_byte_count_on_discard = limit - ar.pos;
// Cheeck profitability (check recycled memory and std::memmove costs)
if (may_discard_bytes >= 0x50'0000 || (may_discard_bytes >= 0x20'0000 && moved_byte_count_on_discard / may_discard_bytes < 3))
{
ar.data_offset += may_discard_bytes;
ar.data.erase(ar.data.begin(), ar.data.begin() + may_discard_bytes);
if (ar.data.capacity() >= 0x200'0000)
{
// Discard memory
ar.data.shrink_to_fit();
}
}
return true;
}
// Discard all loaded data
ar.data_offset = ar.pos;
ar.data.clear();
if (ar.data.capacity() >= 0x200'0000)
{
// Discard memory
ar.data.shrink_to_fit();
}
return true;
}
if (~pos < size - 1)
{
// Overflow
return false;
}
if (ar.data.empty())
{
// Relocate instead of over-fetch
ar.data_offset = pos;
}
const usz read_pre_buffer = ar.data.empty() ? 0 : utils::sub_saturate<usz>(ar.data_offset, pos);
if (read_pre_buffer)
{
// Read past data
// Harsh operation on performance, luckily rare and not typically needed
// Also this may would be disallowed when moving to compressed files
// This may be a result of wrong usage of breathe() function
ar.data.resize(ar.data.size() + read_pre_buffer);
std::memmove(ar.data.data() + read_pre_buffer, ar.data.data(), ar.data.size() - read_pre_buffer);
ensure(m_file->read_at(pos, ar.data.data(), read_pre_buffer) == read_pre_buffer);
ar.data_offset -= read_pre_buffer;
}
// Adjustment to prevent overflow
const usz subtrahend = ar.data.empty() ? 0 : 1;
const usz read_past_buffer = utils::sub_saturate<usz>(pos + (size - subtrahend), ar.data_offset + (ar.data.size() - subtrahend));
const usz read_limit = utils::sub_saturate<usz>(ar.m_max_data, ar.data_offset);
if (read_past_buffer)
{
// Read proceeding data
// More lightweight operation, this is the common operation
// Allowed to fail, if memory is truly needed an assert would take place later
const usz old_size = ar.data.size();
// Try to prefetch data by reading more than requested
ar.data.resize(std::min<usz>(read_limit, std::max<usz>({ ar.data.capacity(), ar.data.size() + read_past_buffer * 3 / 2, ar.expect_little_data() ? usz{4096} : usz{0x10'0000} })));
ar.data.resize(m_file->read_at(old_size + ar.data_offset, data ? const_cast<void*>(data) : ar.data.data() + old_size, ar.data.size() - old_size) + old_size);
}
return true;
}
usz uncompressed_serialization_file_handler::get_size(const utils::serial& ar, usz recommended) const
{
if (ar.is_writing())
{
return *m_file ? m_file->size() : 0;
}
const usz memory_available = ar.data_offset + ar.data.size();
if (memory_available >= recommended || !*m_file)
{
// Avoid calling size() if possible
return memory_available;
}
return std::max<usz>(m_file->size(), memory_available);
}
void uncompressed_serialization_file_handler::finalize(utils::serial& ar)
{
ar.seek_end();
handle_file_op(ar, 0, umax, nullptr);
ar.data = {}; // Deallocate and clear
}
enum : u64
{
pending_compress_bytes_bound = 0x400'0000,
pending_data_wait_bit = 1ull << 63,
};
struct compressed_stream_data
{
z_stream m_zs{};
lf_queue<std::vector<u8>> m_queued_data_to_process;
lf_queue<std::vector<u8>> m_queued_data_to_write;
};
void compressed_serialization_file_handler::initialize(utils::serial& ar)
{
if (!m_stream)
{
m_stream = std::make_shared<compressed_stream_data>();
}
if (ar.is_writing())
{
if (m_write_inited)
{
return;
}
z_stream& m_zs = m_stream->m_zs;
#ifndef _MSC_VER
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif
if (m_read_inited)
{
finalize(ar);
}
m_zs = {};
ensure(deflateInit2(&m_zs, ar.expect_little_data() ? 9 : 8, Z_DEFLATED, 16 + 15, 9, Z_DEFAULT_STRATEGY) == Z_OK);
#ifndef _MSC_VER
#pragma GCC diagnostic pop
#endif
m_write_inited = true;
m_errored = false;
if (!ar.expect_little_data())
{
m_stream_data_prepare_thread = std::make_unique<named_thread<std::function<void()>>>("CompressedPrepare Thread"sv, [this]() { this->stream_data_prepare_thread_op(); });
m_file_writer_thread = std::make_unique<named_thread<std::function<void()>>>("CompressedWriter Thread"sv, [this]() { this->file_writer_thread_op(); });
}
}
else
{
if (m_read_inited)
{
return;
}
if (m_write_inited)
{
finalize(ar);
}
z_stream& m_zs = m_stream->m_zs;
m_zs.avail_in = 0;
m_zs.avail_out = 0;
m_zs.next_in = nullptr;
m_zs.next_out = nullptr;
#ifndef _MSC_VER
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif
ensure(inflateInit2(&m_zs, 16 + 15) == Z_OK);
m_read_inited = true;
m_errored = false;
}
}
bool compressed_serialization_file_handler::handle_file_op(utils::serial& ar, usz pos, usz size, const void* data)
{
if (ar.is_writing())
{
initialize(ar);
if (m_errored)
{
return false;
}
auto& manager = *m_stream;
auto& stream_data = manager.m_queued_data_to_process;
if (data)
{
ensure(false);
}
// Writing not at the end is forbidden
ensure(ar.pos == ar.data_offset + ar.data.size());
if (ar.data.empty())
{
if (pos == umax && size == umax && *m_file)
{
// Request to flush the file to disk
m_file->sync();
}
return true;
}
ar.seek_end();
if (!m_file_writer_thread)
{
// Avoid multi-threading for small files
blocked_compressed_write(ar.data);
}
else
{
while (true)
{
// Avoid flooding RAM, wait if there is too much pending memory
const usz new_value = m_pending_bytes.atomic_op([&](usz& v)
{
v &= ~pending_data_wait_bit;
if (v >= pending_compress_bytes_bound)
{
v |= pending_data_wait_bit;
}
else
{
// Overflow detector
ensure(~v - pending_data_wait_bit > ar.data.size());
v += ar.data.size();
}
return v;
});
if (new_value & pending_data_wait_bit)
{
m_pending_bytes.wait(new_value);
}
else
{
break;
}
}
stream_data.push(std::move(ar.data));
}
ar.data_offset = ar.pos;
ar.data.clear();
if (pos == umax && size == umax && *m_file)
{
// Request to flush the file to disk
m_file->sync();
}
return true;
}
initialize(ar);
if (m_errored)
{
return false;
}
if (!size)
{
return true;
}
if (pos == 0 && size == umax)
{
// Discard loaded data until pos if profitable
const usz limit = ar.data_offset + ar.data.size();
if (ar.pos > ar.data_offset && ar.pos < limit)
{
const usz may_discard_bytes = ar.pos - ar.data_offset;
const usz moved_byte_count_on_discard = limit - ar.pos;
// Cheeck profitability (check recycled memory and std::memmove costs)
if (may_discard_bytes >= 0x50'0000 || (may_discard_bytes >= 0x20'0000 && moved_byte_count_on_discard / may_discard_bytes < 3))
{
ar.data_offset += may_discard_bytes;
ar.data.erase(ar.data.begin(), ar.data.begin() + may_discard_bytes);
if (ar.data.capacity() >= 0x200'0000)
{
// Discard memory
ar.data.shrink_to_fit();
}
}
return true;
}
// Discard all loaded data
ar.data_offset += ar.data.size();
ensure(ar.pos >= ar.data_offset);
ar.data.clear();
if (ar.data.capacity() >= 0x200'0000)
{
// Discard memory
ar.data.shrink_to_fit();
}
return true;
}
if (~pos < size - 1)
{
// Overflow
return false;
}
// TODO: Investigate if this optimization is worth an implementation for compressed stream
// if (ar.data.empty() && pos != ar.pos)
// {
// // Relocate instead of over-fetch
// ar.seek_pos(pos);
// }
const usz read_pre_buffer = utils::sub_saturate<usz>(ar.data_offset, pos);
if (read_pre_buffer)
{
// Not allowed with compressed data for now
// Unless someone implements mechanism for it
ensure(false);
}
// Adjustment to prevent overflow
const usz subtrahend = ar.data.empty() ? 0 : 1;
const usz read_past_buffer = utils::sub_saturate<usz>(pos + (size - subtrahend), ar.data_offset + (ar.data.size() - subtrahend));
const usz read_limit = utils::sub_saturate<usz>(ar.m_max_data, ar.data_offset);
if (read_past_buffer)
{
// Read proceeding data
// More lightweight operation, this is the common operation
// Allowed to fail, if memory is truly needed an assert would take place later
const usz old_size = ar.data.size();
// Try to prefetch data by reading more than requested
const usz new_size = std::min<usz>(read_limit, std::max<usz>({ ar.data.capacity(), ar.data.size() + read_past_buffer * 3 / 2, ar.expect_little_data() ? usz{4096} : usz{0x10'0000} }));
if (new_size < old_size)
{
// Read limit forbids further reads at this point
return true;
}
ar.data.resize(new_size);
ar.data.resize(this->read_at(ar, old_size + ar.data_offset, data ? const_cast<void*>(data) : ar.data.data() + old_size, ar.data.size() - old_size) + old_size);
}
return true;
}
usz compressed_serialization_file_handler::read_at(utils::serial& ar, usz read_pos, void* data, usz size)
{
ensure(read_pos == ar.data.size() + ar.data_offset - size);
if (!size || m_errored)
{
return 0;
}
initialize(ar);
z_stream& m_zs = m_stream->m_zs;
const usz total_to_read = size;
usz read_size = 0;
u8* out_data = static_cast<u8*>(data);
for (; read_size < total_to_read;)
{
// Drain extracted memory stash (also before first file read)
out_data = static_cast<u8*>(data) + read_size;
m_zs.avail_in = adjust_for_uint(m_stream_data.size() - m_stream_data_index);
m_zs.next_in = reinterpret_cast<const u8*>(m_stream_data.data() + m_stream_data_index);
m_zs.next_out = out_data;
m_zs.avail_out = adjust_for_uint(size - read_size);
while (read_size < total_to_read && m_zs.avail_in)
{
const int res = inflate(&m_zs, Z_BLOCK);
bool need_more_file_memory = false;
switch (res)
{
case Z_OK:
case Z_STREAM_END:
break;
case Z_BUF_ERROR:
{
if (m_zs.avail_in)
{
need_more_file_memory = true;
break;
}
[[fallthrough]];
}
default:
m_errored = true;
inflateEnd(&m_zs);
m_read_inited = false;
sys_log.error("Failure of compressed data reading. (res=%d, read_size=0x%x, avail_in=0x%x, avail_out=0x%x, ar=%s)", res, read_size, m_zs.avail_in, m_zs.avail_out, ar);
return read_size;
}
read_size = m_zs.next_out - static_cast<u8*>(data);
m_stream_data_index = m_zs.avail_in ? m_zs.next_in - m_stream_data.data() : m_stream_data.size();
// Adjust again in case the values simply did not fit into uInt
m_zs.avail_out = adjust_for_uint(utils::sub_saturate<usz>(total_to_read, read_size));
m_zs.avail_in = adjust_for_uint(m_stream_data.size() - m_stream_data_index);
if (need_more_file_memory)
{
break;
}
}
if (read_size >= total_to_read)
{
break;
}
const usz add_size = ar.expect_little_data() ? 0x1'0000 : 0x10'0000;
const usz old_file_buf_size = m_stream_data.size();
m_stream_data.resize(old_file_buf_size + add_size);
m_stream_data.resize(old_file_buf_size + m_file->read_at(m_file_read_index, m_stream_data.data() + old_file_buf_size, add_size));
if (m_stream_data.size() == old_file_buf_size)
{
// EOF
break;
}
m_file_read_index += m_stream_data.size() - old_file_buf_size;
}
if (m_stream_data.size() - m_stream_data_index <= m_stream_data_index / 5)
{
// Shrink to required memory size
m_stream_data.erase(m_stream_data.begin(), m_stream_data.begin() + m_stream_data_index);
if (m_stream_data.capacity() >= 0x200'0000)
{
// Discard memory
m_stream_data.shrink_to_fit();
}
m_stream_data_index = 0;
}
return read_size;
}
void compressed_serialization_file_handler::skip_until(utils::serial& ar)
{
ensure(!ar.is_writing() && ar.pos >= ar.data_offset);
if (ar.pos > ar.data_offset)
{
handle_file_op(ar, ar.data_offset, ar.pos - ar.data_offset, nullptr);
}
}
void compressed_serialization_file_handler::finalize(utils::serial& ar)
{
handle_file_op(ar, 0, umax, nullptr);
if (!m_stream)
{
return;
}
auto& stream = *m_stream;
z_stream& m_zs = m_stream->m_zs;
if (m_read_inited)
{
ensure(inflateEnd(&m_zs) == Z_OK);
m_read_inited = false;
return;
}
stream.m_queued_data_to_process.push(std::vector<u8>());
if (m_file_writer_thread)
{
// Join here to avoid log messages in the destructor
(*m_file_writer_thread)();
}
m_stream_data_prepare_thread.reset();
m_file_writer_thread.reset();
m_zs.avail_in = 0;
m_zs.next_in = nullptr;
m_stream_data.resize(0x10'0000);
do
{
m_zs.avail_out = static_cast<uInt>(m_stream_data.size());
m_zs.next_out = m_stream_data.data();
if (deflate(&m_zs, Z_FINISH) == Z_STREAM_ERROR)
{
break;
}
m_file->write(m_stream_data.data(), m_stream_data.size() - m_zs.avail_out);
}
while (m_zs.avail_out == 0);
m_stream_data = {};
ensure(deflateEnd(&m_zs) == Z_OK);
m_write_inited = false;
ar.data = {}; // Deallocate and clear
m_file->sync();
}
void compressed_serialization_file_handler::stream_data_prepare_thread_op()
{
compressed_stream_data& stream = *m_stream;
z_stream& m_zs = stream.m_zs;
while (true)
{
stream.m_queued_data_to_process.wait();
for (auto&& data : stream.m_queued_data_to_process.pop_all())
{
if (data.empty())
{
// Abort is requested, flush data and exit
stream.m_queued_data_to_write.push(std::vector<u8>());
return;
}
m_zs.avail_in = adjust_for_uint(data.size());
m_zs.next_in = data.data();
usz buffer_offset = 0;
m_stream_data.resize(::compressBound(m_zs.avail_in));
do
{
m_zs.avail_out = adjust_for_uint(m_stream_data.size() - buffer_offset);
m_zs.next_out = m_stream_data.data() + buffer_offset;
if (deflate(&m_zs, Z_NO_FLUSH) == Z_STREAM_ERROR)
{
m_errored = true;
deflateEnd(&m_zs);
// Abort
stream.m_queued_data_to_write.push(std::vector<u8>());
break;
}
buffer_offset = m_zs.next_out - m_stream_data.data();
m_zs.avail_in = adjust_for_uint(data.size() - (m_zs.next_in - data.data()));
if (m_zs.avail_out == 0)
{
m_stream_data.resize(m_stream_data.size() + (m_zs.avail_in / 4) + (m_stream_data.size() / 16) + 1);
}
}
while (m_zs.avail_out == 0 || m_zs.avail_in != 0);
if (m_errored)
{
return;
}
// Forward for file write
const usz queued_size = data.size();
const usz size_diff = buffer_offset - queued_size;
const usz new_val = m_pending_bytes.add_fetch(size_diff);
const usz left = new_val & ~pending_data_wait_bit;
if (new_val & pending_data_wait_bit && left < pending_compress_bytes_bound && left - size_diff >= pending_compress_bytes_bound && !m_pending_signal)
{
// Notification is postponed until data write and memory release
m_pending_signal = true;
}
// Ensure wait bit state has not changed by the update
ensure(~((new_val - size_diff) ^ new_val) & pending_data_wait_bit);
if (!buffer_offset)
{
if (m_pending_signal)
{
m_pending_bytes.notify_all();
}
continue;
}
m_stream_data.resize(buffer_offset);
stream.m_queued_data_to_write.push(std::move(m_stream_data));
}
}
}
void compressed_serialization_file_handler::file_writer_thread_op()
{
compressed_stream_data& stream = *m_stream;
while (true)
{
stream.m_queued_data_to_write.wait();
for (auto&& data : stream.m_queued_data_to_write.pop_all())
{
if (data.empty())
{
return;
}
const usz last_size = data.size();
m_file->write(data);
data = {}; // Deallocate before notification
const usz new_val = m_pending_bytes.sub_fetch(last_size);
const usz left = new_val & ~pending_data_wait_bit;
const bool pending_sig = m_pending_signal && m_pending_signal.exchange(false);
if (pending_sig || (new_val & pending_data_wait_bit && left < pending_compress_bytes_bound && left + last_size >= pending_compress_bytes_bound))
{
m_pending_bytes.notify_all();
}
// Ensure wait bit state has not changed by the update
ensure(~((new_val + last_size) ^ new_val) & pending_data_wait_bit);
}
}
}
void compressed_serialization_file_handler::blocked_compressed_write(const std::vector<u8>& data)
{
z_stream& m_zs = m_stream->m_zs;
m_zs.avail_in = adjust_for_uint(data.size());
m_zs.next_in = data.data();
m_stream_data.resize(::compressBound(m_zs.avail_in));
do
{
m_zs.avail_out = adjust_for_uint(m_stream_data.size());
m_zs.next_out = m_stream_data.data();
if (deflate(&m_zs, Z_NO_FLUSH) == Z_STREAM_ERROR || m_file->write(m_stream_data.data(), m_stream_data.size() - m_zs.avail_out) != m_stream_data.size() - m_zs.avail_out)
{
m_errored = true;
deflateEnd(&m_zs);
break;
}
m_zs.avail_in = adjust_for_uint(data.size() - (m_zs.next_in - data.data()));
}
while (m_zs.avail_out == 0);
}
usz compressed_serialization_file_handler::get_size(const utils::serial& ar, usz recommended) const
{
if (ar.is_writing())
{
return *m_file ? m_file->size() : 0;
}
const usz memory_available = ar.data_offset + ar.data.size();
if (memory_available >= recommended || !*m_file)
{
// Avoid calling size() if possible
return memory_available;
}
return std::max<usz>(utils::mul_saturate<usz>(m_file->size(), 6), memory_available);
}
struct compressed_zstd_stream_data
{
ZSTD_DCtx* m_zd{};
ZSTD_DStream* m_zs{};
lf_queue<std::vector<u8>> m_queued_data_to_process;
lf_queue<std::vector<u8>> m_queued_data_to_write;
};
void compressed_zstd_serialization_file_handler::initialize(utils::serial& ar)
{
if (!m_stream)
{
m_stream = std::make_shared<compressed_zstd_stream_data>();
}
if (ar.is_writing())
{
if (m_write_inited)
{
return;
}
if (m_read_inited && m_stream->m_zd)
{
finalize(ar);
}
m_write_inited = true;
m_errored = false;
m_compression_threads.clear();
m_file_writer_thread.reset();
// Make sure at least one thread is free
// Limit thread count in order to make sure memory limits are under control (TODO: scale with RAM size)
const usz thread_count = std::min<u32>(std::max<u32>(utils::get_thread_count(), 2) - 1, 16);
for (usz i = 0; i < thread_count; i++)
{
m_compression_threads.emplace_back().m_thread = std::make_unique<named_thread<std::function<void()>>>(fmt::format("CompressedPrepare Thread %d", i + 1), [this]() { this->stream_data_prepare_thread_op(); });
}
m_file_writer_thread = std::make_unique<named_thread<std::function<void()>>>("CompressedWriter Thread"sv, [this]() { this->file_writer_thread_op(); });
}
else
{
if (m_read_inited)
{
return;
}
if (m_write_inited)
{
finalize(ar);
}
auto& m_zd = m_stream->m_zd;
m_zd = ZSTD_createDCtx();
m_stream->m_zs = ZSTD_createDStream();
m_read_inited = true;
m_errored = false;
}
}
bool compressed_zstd_serialization_file_handler::handle_file_op(utils::serial& ar, usz pos, usz size, const void* data)
{
if (ar.is_writing())
{
initialize(ar);
if (m_errored)
{
return false;
}
if (data)
{
ensure(false);
}
// Writing not at the end is forbidden
ensure(ar.pos == ar.data_offset + ar.data.size());
if (ar.data.empty())
{
if (pos == umax && size == umax && *m_file)
{
// Request to flush the file to disk
m_file->sync();
}
return true;
}
ar.seek_end();
const usz buffer_idx = m_input_buffer_index++ % m_compression_threads.size();
auto& input = m_compression_threads[buffer_idx].m_input;
while (input)
{
// No waiting support on non-null pointer
thread_ctrl::wait_for(2'000);
}
input.store(stx::make_single_value(std::move(ar.data)));
input.notify_all();
ar.data_offset = ar.pos;
ar.data.clear();
if (pos == umax && size == umax && *m_file)
{
// Request to flush the file to disk
m_file->sync();
}
return true;
}
initialize(ar);
if (m_errored)
{
return false;
}
if (!size)
{
return true;
}
if (pos == 0 && size == umax)
{
// Discard loaded data until pos if profitable
const usz limit = ar.data_offset + ar.data.size();
if (ar.pos > ar.data_offset && ar.pos < limit)
{
const usz may_discard_bytes = ar.pos - ar.data_offset;
const usz moved_byte_count_on_discard = limit - ar.pos;
// Cheeck profitability (check recycled memory and std::memmove costs)
if (may_discard_bytes >= 0x50'0000 || (may_discard_bytes >= 0x20'0000 && moved_byte_count_on_discard / may_discard_bytes < 3))
{
ar.data_offset += may_discard_bytes;
ar.data.erase(ar.data.begin(), ar.data.begin() + may_discard_bytes);
if (ar.data.capacity() >= 0x200'0000)
{
// Discard memory
ar.data.shrink_to_fit();
}
}
return true;
}
// Discard all loaded data
ar.data_offset += ar.data.size();
ensure(ar.pos >= ar.data_offset);
ar.data.clear();
if (ar.data.capacity() >= 0x200'0000)
{
// Discard memory
ar.data.shrink_to_fit();
}
return true;
}
if (~pos < size - 1)
{
// Overflow
return false;
}
// TODO: Investigate if this optimization is worth an implementation for compressed stream
// if (ar.data.empty() && pos != ar.pos)
// {
// // Relocate instead of over-fetch
// ar.seek_pos(pos);
// }
const usz read_pre_buffer = utils::sub_saturate<usz>(ar.data_offset, pos);
if (read_pre_buffer)
{
// Not allowed with compressed data for now
// Unless someone implements mechanism for it
ensure(false);
}
// Adjustment to prevent overflow
const usz subtrahend = ar.data.empty() ? 0 : 1;
const usz read_past_buffer = utils::sub_saturate<usz>(pos + (size - subtrahend), ar.data_offset + (ar.data.size() - subtrahend));
const usz read_limit = utils::sub_saturate<usz>(ar.m_max_data, ar.data_offset);
if (read_past_buffer)
{
// Read proceeding data
// More lightweight operation, this is the common operation
// Allowed to fail, if memory is truly needed an assert would take place later
const usz old_size = ar.data.size();
// Try to prefetch data by reading more than requested
const usz new_size = std::min<usz>(read_limit, std::max<usz>({ ar.data.capacity(), ar.data.size() + read_past_buffer * 3 / 2, ar.expect_little_data() ? usz{4096} : usz{0x10'0000} }));
if (new_size < old_size)
{
// Read limit forbids further reads at this point
return true;
}
ar.data.resize(new_size);
ar.data.resize(this->read_at(ar, old_size + ar.data_offset, data ? const_cast<void*>(data) : ar.data.data() + old_size, ar.data.size() - old_size) + old_size);
}
return true;
}
usz compressed_zstd_serialization_file_handler::read_at(utils::serial& ar, usz read_pos, void* data, usz size)
{
ensure(read_pos == ar.data.size() + ar.data_offset - size);
if (!size || m_errored)
{
return 0;
}
initialize(ar);
auto& m_zd = m_stream->m_zd;
const usz total_to_read = size;
usz read_size = 0;
u8* out_data = static_cast<u8*>(data);
for (; read_size < total_to_read;)
{
// Drain extracted memory stash (also before first file read)
out_data = static_cast<u8*>(data) + read_size;
auto avail_in = m_stream_data.size() - m_stream_data_index;
auto next_in = reinterpret_cast<const u8*>(m_stream_data.data() + m_stream_data_index);
auto next_out = out_data;
auto avail_out = size - read_size;
for (bool is_first = true; read_size < total_to_read && avail_in; is_first = false)
{
bool need_more_file_memory = false;
ZSTD_outBuffer outs{next_out, avail_out, 0};
// Try to extract previously held data first
ZSTD_inBuffer ins{next_in, is_first ? 0 : avail_in, 0};
const usz res = ZSTD_decompressStream(m_zd, &outs, &ins);
if (ZSTD_isError(res))
{
need_more_file_memory = true;
// finalize(ar);
// m_errored = true;
// sys_log.error("Failure of compressed data reading. (res=%d, read_size=0x%x, avail_in=0x%x, avail_out=0x%x, ar=%s)", res, read_size, avail_in, avail_out, ar);
// return read_size;
}
read_size += outs.pos;
next_out += outs.pos;
avail_out -= outs.pos;
next_in += ins.pos;
avail_in -= ins.pos;
m_stream_data_index = next_in - m_stream_data.data();
if (need_more_file_memory)
{
break;
}
}
if (read_size >= total_to_read)
{
break;
}
const usz add_size = ar.expect_little_data() ? 0x1'0000 : 0x10'0000;
const usz old_file_buf_size = m_stream_data.size();
m_stream_data.resize(old_file_buf_size + add_size);
m_stream_data.resize(old_file_buf_size + m_file->read_at(m_file_read_index, m_stream_data.data() + old_file_buf_size, add_size));
if (m_stream_data.size() == old_file_buf_size)
{
// EOF
//ensure(read_size == total_to_read);
break;
}
m_file_read_index += m_stream_data.size() - old_file_buf_size;
}
if (m_stream_data.size() - m_stream_data_index <= m_stream_data_index / 5)
{
// Shrink to required memory size
m_stream_data.erase(m_stream_data.begin(), m_stream_data.begin() + m_stream_data_index);
if (m_stream_data.capacity() >= 0x200'0000)
{
// Discard memory
m_stream_data.shrink_to_fit();
}
m_stream_data_index = 0;
}
return read_size;
}
void compressed_zstd_serialization_file_handler::skip_until(utils::serial& ar)
{
ensure(!ar.is_writing() && ar.pos >= ar.data_offset);
if (ar.pos > ar.data_offset)
{
handle_file_op(ar, ar.data_offset, ar.pos - ar.data_offset, nullptr);
}
}
void compressed_zstd_serialization_file_handler::finalize(utils::serial& ar)
{
handle_file_op(ar, 0, umax, nullptr);
if (!m_stream)
{
return;
}
auto& m_zd = m_stream->m_zd;
if (m_read_inited)
{
//ZSTD_decompressEnd(m_stream->m_zd);
ensure(ZSTD_freeDCtx(m_zd));
m_read_inited = false;
return;
}
const stx::shared_ptr<std::vector<u8>> empty_data = stx::make_single<std::vector<u8>>();
const stx::shared_ptr<std::vector<u8>> null_ptr = stx::null_ptr;
for (auto& context : m_compression_threads)
{
// Try to notify all on the first iteration
if (context.m_input.compare_and_swap_test(null_ptr, empty_data))
{
context.notified = true;
context.m_input.notify_one();
}
}
for (auto& context : m_compression_threads)
{
// Notify to abort
while (!context.notified)
{
const auto data = context.m_input.compare_and_swap(null_ptr, empty_data);
if (!data)
{
context.notified = true;
context.m_input.notify_one();
break;
}
// Wait until valid input is processed
thread_ctrl::wait_for(1000);
}
}
for (auto& context : m_compression_threads)
{
// Wait for notification to be consumed
while (context.m_input)
{
thread_ctrl::wait_for(1000);
}
}
for (auto& context : m_compression_threads)
{
// Wait for data to be writen to be read by the thread
while (context.m_output)
{
thread_ctrl::wait_for(1000);
}
}
for (usz idx = m_output_buffer_index;;)
{
auto& out_cur = m_compression_threads[idx % m_compression_threads.size()].m_output;
auto& out_next = m_compression_threads[(idx + 1) % m_compression_threads.size()].m_output;
out_cur.compare_and_swap_test(null_ptr, empty_data);
out_next.compare_and_swap_test(null_ptr, empty_data);
if (usz new_val = m_output_buffer_index; idx != new_val)
{
// Index was changed inbetween, retry on the next index
idx = new_val;
continue;
}
// Must be waiting on either of the two
out_cur.notify_all();
// Check for single thread
if (&out_next != &out_cur)
{
out_next.notify_all();
}
break;
}
if (m_file_writer_thread)
{
// Join here to avoid log messages in the destructor
(*m_file_writer_thread)();
}
m_compression_threads.clear();
m_file_writer_thread.reset();
m_stream_data = {};
m_write_inited = false;
ar.data = {}; // Deallocate and clear
m_file->sync();
}
void compressed_zstd_serialization_file_handler::stream_data_prepare_thread_op()
{
ZSTD_CCtx* m_zc = ZSTD_createCCtx();
std::vector<u8> stream_data;
const stx::shared_ptr<std::vector<u8>> null_ptr = stx::null_ptr;
const usz thread_index = m_thread_buffer_index++;
while (true)
{
auto& input = m_compression_threads[thread_index].m_input;
auto& output = m_compression_threads[thread_index].m_output;
while (!input)
{
input.wait(nullptr);
}
auto data = input.exchange(stx::null_ptr);
input.notify_all();
if (data->empty())
{
// Abort is requested, flush data and exit
break;
}
stream_data.resize(::ZSTD_compressBound(data->size()));
const usz out_size = ZSTD_compressCCtx(m_zc, stream_data.data(), stream_data.size(), data->data(), data->size(), ZSTD_btultra);
ensure(!ZSTD_isError(out_size) && out_size);
if (m_errored)
{
break;
}
stream_data.resize(out_size);
const stx::shared_ptr<std::vector<u8>> data_ptr = make_single<std::vector<u8>>(std::move(stream_data));
while (output || !output.compare_and_swap_test(null_ptr, data_ptr))
{
thread_ctrl::wait_for(1000);
}
//if (m_output_buffer_index % m_compression_threads.size() == thread_index)
{
output.notify_all();
}
}
ZSTD_freeCCtx(m_zc);
}
void compressed_zstd_serialization_file_handler::file_writer_thread_op()
{
for (m_output_buffer_index = 0;; m_output_buffer_index++)
{
auto& output = m_compression_threads[m_output_buffer_index % m_compression_threads.size()].m_output;
while (!output)
{
output.wait(nullptr);
}
auto data = output.exchange(stx::null_ptr);
output.notify_all();
if (data->empty())
{
break;
}
m_file->write(*data);
}
}
usz compressed_zstd_serialization_file_handler::get_size(const utils::serial& ar, usz recommended) const
{
if (ar.is_writing())
{
return *m_file ? m_file->size() : 0;
}
const usz memory_available = ar.data_offset + ar.data.size();
if (memory_available >= recommended || !*m_file)
{
// Avoid calling size() if possible
return memory_available;
}
return recommended;
//return std::max<usz>(utils::mul_saturate<usz>(ZSTD_decompressBound(m_file->size()), 2), memory_available);
}
bool null_serialization_file_handler::handle_file_op(utils::serial&, usz, usz, const void*)
{
return true;
}
void null_serialization_file_handler::finalize(utils::serial&)
{
}
| 31,725
|
C++
|
.cpp
| 1,057
| 26.820246
| 209
| 0.665164
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,044
|
vm_native.cpp
|
RPCS3_rpcs3/rpcs3/util/vm_native.cpp
|
#include "stdafx.h"
#include "util/logs.hpp"
#include "util/vm.hpp"
#include "util/asm.hpp"
#ifdef _WIN32
#include "Utilities/File.h"
#include "util/dyn_lib.hpp"
#include "Utilities/lockless.h"
#include <Windows.h>
#include <span>
#else
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#endif
#if defined(__FreeBSD__)
#include <sys/sysctl.h>
#include <vm/vm_param.h>
#endif
#ifdef __linux__
#include <sys/syscall.h>
#include <linux/memfd.h>
#ifdef __NR_memfd_create
#elif __x86_64__
#define __NR_memfd_create 319
#elif ARCH_ARM64
#define __NR_memfd_create 279
#endif
static int memfd_create_(const char *name, uint flags)
{
return syscall(__NR_memfd_create, name, flags);
}
#elif defined(__FreeBSD__)
# if __FreeBSD__ < 13
// XXX Drop after FreeBSD 12.* reaches EOL on 2024-06-30
#define MFD_CLOEXEC O_CLOEXEC
#define memfd_create_(name, flags) shm_open(SHM_ANON, O_RDWR | flags, 0600)
# else
#define memfd_create_ memfd_create
# endif
#endif
namespace utils
{
#ifdef MAP_NORESERVE
constexpr int c_map_noreserve = MAP_NORESERVE;
#else
[[maybe_unused]] constexpr int c_map_noreserve = 0;
#endif
#ifdef MADV_FREE
[[maybe_unused]] constexpr int c_madv_free = MADV_FREE;
#elif defined(MADV_DONTNEED)
[[maybe_unused]] constexpr int c_madv_free = MADV_DONTNEED;
#else
[[maybe_unused]] constexpr int c_madv_free = 0;
#endif
#ifdef MADV_HUGEPAGE
constexpr int c_madv_hugepage = MADV_HUGEPAGE;
#else
[[maybe_unused]] constexpr int c_madv_hugepage = 0;
#endif
#if defined(MADV_DONTDUMP) && defined(MADV_DODUMP)
constexpr int c_madv_no_dump = MADV_DONTDUMP;
constexpr int c_madv_dump = MADV_DODUMP;
#elif defined(MADV_NOCORE) && defined(MADV_CORE)
constexpr int c_madv_no_dump = MADV_NOCORE;
constexpr int c_madv_dump = MADV_CORE;
#else
[[maybe_unused]] constexpr int c_madv_no_dump = 0;
[[maybe_unused]] constexpr int c_madv_dump = 0;
#endif
#if defined(MFD_HUGETLB) && defined(MFD_HUGE_2MB)
constexpr int c_mfd_huge_2mb = MFD_HUGETLB | MFD_HUGE_2MB;
#elif defined(__linux__) || defined(__FreeBSD__)
constexpr int c_mfd_huge_2mb = 0;
#endif
#ifdef _WIN32
DYNAMIC_IMPORT("KernelBase.dll", VirtualAlloc2, PVOID(HANDLE Process, PVOID Base, SIZE_T Size, ULONG AllocType, ULONG Prot, MEM_EXTENDED_PARAMETER*, ULONG));
DYNAMIC_IMPORT("KernelBase.dll", MapViewOfFile3, PVOID(HANDLE Handle, HANDLE Process, PVOID Base, ULONG64 Off, SIZE_T ViewSize, ULONG AllocType, ULONG Prot, MEM_EXTENDED_PARAMETER*, ULONG));
DYNAMIC_IMPORT("KernelBase.dll", UnmapViewOfFile2, BOOL(HANDLE Process, PVOID BaseAddress, ULONG UnmapFlags));
bool has_win10_memory_mapping_api()
{
return VirtualAlloc2 && MapViewOfFile3 && UnmapViewOfFile2;
}
struct map_info_t
{
u64 addr = 0;
u64 size = 0;
atomic_t<u8> state{};
};
lf_array<map_info_t, 32> s_is_mapping{};
bool is_memory_mappping_memory(u64 addr)
{
if (!addr)
{
return false;
}
const u64 map_size = s_is_mapping.size();
for (u64 i = map_size - 1; i != umax; i--)
{
const auto& info = s_is_mapping[i];
if (info.state == 1)
{
if (addr >= info.addr && addr < info.addr + info.size)
{
return true;
}
}
}
return false;
}
u64 unmap_mappping_memory(u64 addr, u64 size)
{
if (!addr || !size)
{
return false;
}
const u64 map_size = s_is_mapping.size();
for (u64 i = map_size - 1; i != umax; i--)
{
auto& info = s_is_mapping[i];
if (info.state == 1)
{
if (addr == info.addr && size == info.size)
{
if (info.state.compare_and_swap_test(1, 0))
{
return info.size;
}
}
}
}
return false;
}
bool map_mappping_memory(u64 addr, u64 size)
{
if (!addr || !size)
{
return false;
}
for (u64 i = 0;; i++)
{
auto& info = s_is_mapping[i];
if (!info.addr && info.state.compare_and_swap_test(0, 2))
{
info.addr = addr;
info.size = size;
info.state = 1;
return true;
}
}
}
bool is_memory_mappping_memory(const void* addr)
{
return is_memory_mappping_memory(reinterpret_cast<u64>(addr));
}
#endif
long get_page_size()
{
static const long r = []() -> long
{
#ifdef _WIN32
SYSTEM_INFO info;
::GetSystemInfo(&info);
return info.dwPageSize;
#else
return ::sysconf(_SC_PAGESIZE);
#endif
}();
return ensure(r, FN(((x & (x - 1)) == 0 && x > 0 && x <= 0x10000)));
}
// Convert memory protection (internal)
static auto operator +(protection prot)
{
#ifdef _WIN32
DWORD _prot = PAGE_NOACCESS;
switch (prot)
{
case protection::rw: _prot = PAGE_READWRITE; break;
case protection::ro: _prot = PAGE_READONLY; break;
case protection::no: break;
case protection::wx: _prot = PAGE_EXECUTE_READWRITE; break;
case protection::rx: _prot = PAGE_EXECUTE_READ; break;
}
#else
int _prot = PROT_NONE;
switch (prot)
{
case protection::rw: _prot = PROT_READ | PROT_WRITE; break;
case protection::ro: _prot = PROT_READ; break;
case protection::no: break;
case protection::wx: _prot = PROT_READ | PROT_WRITE | PROT_EXEC; break;
case protection::rx: _prot = PROT_READ | PROT_EXEC; break;
}
#endif
return _prot;
}
void* memory_reserve(usz size, void* use_addr, [[maybe_unused]] bool is_memory_mapping)
{
#ifdef _WIN32
if (is_memory_mapping && has_win10_memory_mapping_api())
{
if (auto ptr = VirtualAlloc2(nullptr, use_addr, size, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, nullptr, 0))
{
map_mappping_memory(reinterpret_cast<u64>(ptr), size);
return ptr;
}
return nullptr;
}
return ::VirtualAlloc(use_addr, size, MEM_RESERVE, PAGE_NOACCESS);
#else
if (use_addr && reinterpret_cast<uptr>(use_addr) % 0x10000)
{
return nullptr;
}
const auto orig_size = size;
if (!use_addr)
{
// Hack: Ensure aligned 64k allocations
size += 0x10000;
}
#ifdef __APPLE__
#ifdef ARCH_ARM64
auto ptr = ::mmap(use_addr, size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE | MAP_JIT | c_map_noreserve, -1, 0);
#else
auto ptr = ::mmap(use_addr, size, PROT_NONE, MAP_ANON | MAP_PRIVATE | MAP_JIT | c_map_noreserve, -1, 0);
#endif
#else
auto ptr = ::mmap(use_addr, size, PROT_NONE, MAP_ANON | MAP_PRIVATE | c_map_noreserve, -1, 0);
#endif
if (ptr == reinterpret_cast<void*>(uptr{umax}))
{
return nullptr;
}
if (use_addr && ptr != use_addr)
{
::munmap(ptr, size);
return nullptr;
}
if (!use_addr && ptr)
{
// Continuation of the hack above
const auto misalign = reinterpret_cast<uptr>(ptr) % 0x10000;
::munmap(ptr, 0x10000 - misalign);
if (misalign)
{
::munmap(static_cast<u8*>(ptr) + size - misalign, misalign);
}
ptr = static_cast<u8*>(ptr) + (0x10000 - misalign);
}
if constexpr (c_madv_hugepage != 0)
{
if (orig_size % 0x200000 == 0)
{
::madvise(ptr, orig_size, c_madv_hugepage);
}
}
if constexpr (c_madv_no_dump != 0)
{
ensure(::madvise(ptr, orig_size, c_madv_no_dump) != -1);
}
else
{
ensure(::madvise(ptr, orig_size, c_madv_free) != -1);
}
return ptr;
#endif
}
void memory_commit(void* pointer, usz size, protection prot)
{
#ifdef _WIN32
ensure(::VirtualAlloc(pointer, size, MEM_COMMIT, +prot));
#else
const u64 ptr64 = reinterpret_cast<u64>(pointer);
ensure(::mprotect(reinterpret_cast<void*>(ptr64 & -c_page_size), size + (ptr64 & (c_page_size - 1)), +prot) != -1);
if constexpr (c_madv_dump != 0)
{
ensure(::madvise(reinterpret_cast<void*>(ptr64 & -c_page_size), size + (ptr64 & (c_page_size - 1)), c_madv_dump) != -1);
}
else
{
ensure(::madvise(reinterpret_cast<void*>(ptr64 & -c_page_size), size + (ptr64 & (c_page_size - 1)), MADV_WILLNEED) != -1);
}
#endif
}
void memory_decommit(void* pointer, usz size)
{
#ifdef _WIN32
ensure(::VirtualFree(pointer, size, MEM_DECOMMIT));
#else
const u64 ptr64 = reinterpret_cast<u64>(pointer);
#if defined(__APPLE__) && defined(ARCH_ARM64)
// Hack: on macOS, Apple explicitly fails mmap if you combine MAP_FIXED and MAP_JIT.
// So we unmap the space and just hope it maps to the same address we got before instead.
// The Xcode manpage says the pointer is a hint and the OS will try to map at the hint location
// so this isn't completely undefined behavior.
ensure(::munmap(pointer, size) != -1);
ensure(::mmap(pointer, size, PROT_NONE, MAP_ANON | MAP_PRIVATE | MAP_JIT, -1, 0) == pointer);
#else
ensure(::mmap(pointer, size, PROT_NONE, MAP_FIXED | MAP_ANON | MAP_PRIVATE | c_map_noreserve, -1, 0) != reinterpret_cast<void*>(uptr{umax}));
#endif
if constexpr (c_madv_no_dump != 0)
{
ensure(::madvise(reinterpret_cast<void*>(ptr64 & -c_page_size), size + (ptr64 & (c_page_size - 1)), c_madv_no_dump) != -1);
}
else
{
ensure(::madvise(reinterpret_cast<void*>(ptr64 & -c_page_size), size + (ptr64 & (c_page_size - 1)), c_madv_free) != -1);
}
#endif
}
void memory_reset(void* pointer, usz size, protection prot)
{
#ifdef _WIN32
memory_decommit(pointer, size);
memory_commit(pointer, size, prot);
#else
const u64 ptr64 = reinterpret_cast<u64>(pointer);
#if defined(__APPLE__) && defined(ARCH_ARM64)
ensure(::munmap(pointer, size) != -1);
ensure(::mmap(pointer, size, +prot, MAP_ANON | MAP_PRIVATE | MAP_JIT, -1, 0) == pointer);
#else
ensure(::mmap(pointer, size, +prot, MAP_FIXED | MAP_ANON | MAP_PRIVATE, -1, 0) != reinterpret_cast<void*>(uptr{umax}));
#endif
if constexpr (c_madv_hugepage != 0)
{
if (size % 0x200000 == 0)
{
::madvise(reinterpret_cast<void*>(ptr64 & -c_page_size), size + (ptr64 & (c_page_size - 1)), c_madv_hugepage);
}
}
if constexpr (c_madv_dump != 0)
{
ensure(::madvise(reinterpret_cast<void*>(ptr64 & -c_page_size), size + (ptr64 & (c_page_size - 1)), c_madv_dump) != -1);
}
else
{
ensure(::madvise(reinterpret_cast<void*>(ptr64 & -c_page_size), size + (ptr64 & (c_page_size - 1)), MADV_WILLNEED) != -1);
}
#endif
}
void memory_release(void* pointer, usz size)
{
#ifdef _WIN32
unmap_mappping_memory(reinterpret_cast<u64>(pointer), size);
ensure(::VirtualFree(pointer, 0, MEM_RELEASE));
#else
ensure(::munmap(pointer, size) != -1);
#endif
}
void memory_protect(void* pointer, usz size, protection prot)
{
#ifdef _WIN32
DWORD old;
if (::VirtualProtect(pointer, size, +prot, &old))
{
return;
}
for (u64 addr = reinterpret_cast<u64>(pointer), end = addr + size; addr < end;)
{
const u64 boundary = (addr + 0x10000) & -0x10000;
const u64 block_size = std::min(boundary, end) - addr;
if (!::VirtualProtect(reinterpret_cast<LPVOID>(addr), block_size, +prot, &old))
{
fmt::throw_exception("VirtualProtect failed (%p, 0x%x, addr=0x%x, error=%s)", pointer, size, addr, fmt::win_error{GetLastError(), nullptr});
}
// Next region
addr += block_size;
}
#else
const u64 ptr64 = reinterpret_cast<u64>(pointer);
ensure(::mprotect(reinterpret_cast<void*>(ptr64 & -c_page_size), size + (ptr64 & (c_page_size - 1)), +prot) != -1);
#endif
}
bool memory_lock(void* pointer, usz size)
{
#ifdef _WIN32
return ::VirtualLock(pointer, size);
#else
return !::mlock(pointer, size);
#endif
}
void* memory_map_fd([[maybe_unused]] native_handle fd, [[maybe_unused]] usz size, [[maybe_unused]] protection prot)
{
#ifdef _WIN32
// TODO
return nullptr;
#else
const auto result = ::mmap(nullptr, size, +prot, MAP_SHARED, fd, 0);
if (result == reinterpret_cast<void*>(uptr{umax}))
{
[[unlikely]] return nullptr;
}
return result;
#endif
}
shm::shm(u64 size, u32 flags)
: m_flags(flags)
, m_size(utils::align(size, 0x10000))
{
#ifdef _WIN32
const ULARGE_INTEGER max_size{ .QuadPart = m_size };
m_handle = ensure(::CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_EXECUTE_READWRITE, max_size.HighPart, max_size.LowPart, nullptr));
#elif defined(__linux__) || defined(__FreeBSD__)
m_file = -1;
// Try to use 2MB pages for 2M-aligned shm
if constexpr (c_mfd_huge_2mb != 0)
{
if (m_size % 0x200000 == 0 && flags & 2)
{
m_file = ::memfd_create_("2M", c_mfd_huge_2mb);
}
}
if (m_file == -1)
{
m_file = ::memfd_create_("", 0);
}
ensure(m_file >= 0);
ensure(::ftruncate(m_file, m_size) >= 0);
#else
const std::string name = "/rpcs3-mem-" + std::to_string(reinterpret_cast<u64>(this));
while ((m_file = ::shm_open(name.c_str(), O_RDWR | O_CREAT | O_EXCL, S_IWUSR | S_IRUSR)) == -1)
{
if (errno == EMFILE)
{
fmt::throw_exception("Too many open files. Raise the limit and try again.");
}
ensure(errno == EEXIST);
}
ensure(::shm_unlink(name.c_str()) >= 0);
ensure(::ftruncate(m_file, m_size) >= 0);
#endif
}
shm::shm(u64 size, const std::string& storage)
: m_size(utils::align(size, 0x10000))
{
#ifdef _WIN32
fs::file f;
auto open_with_cleanup = [](fs::file& f, const std::string& path)
{
f.close();
for (u32 try_count = 3, i = 0; !f && i < try_count; i++)
{
// Bug workaround: removing old file may be safer than rewriting it
if (!fs::remove_file(path) && fs::g_tls_error != fs::error::noent)
{
return false;
}
if (!f.open(path, fs::read + fs::write + fs::create + fs::excl) && fs::g_tls_error != fs::error::exist)
{
return false;
}
}
return f.operator bool();
};
std::string storage1 = fs::get_temp_dir();
std::string storage2 = fs::get_cache_dir();
if (storage.empty())
{
storage1 += "rpcs3_vm_sparse.tmp";
storage2 += "rpcs3_vm_sparse.tmp";
}
else
{
storage1 += storage;
storage2 += storage;
}
std::function<bool(const std::string&, HANDLE, usz)> set_sparse_and_map = [&](const std::string& storagex, HANDLE h, usz m_size) -> bool
{
// In case failed, revert changes and forward failure
auto clean = [&](bool result)
{
if (!result)
{
const fs::error last_fs_error = fs::g_tls_error;
const DWORD last_win_error = ::GetLastError();
fs::remove_file(storagex);
fs::g_tls_error = last_fs_error;
::SetLastError(last_win_error);
}
return result;
};
FILE_SET_SPARSE_BUFFER arg{.SetSparse = true};
FILE_BASIC_INFO info0{};
ensure(clean(GetFileInformationByHandleEx(h, FileBasicInfo, &info0, sizeof(info0))));
if ((info0.FileAttributes & FILE_ATTRIBUTE_ARCHIVE) || (~info0.FileAttributes & FILE_ATTRIBUTE_TEMPORARY))
{
info0.FileAttributes &= ~FILE_ATTRIBUTE_ARCHIVE;
info0.FileAttributes |= FILE_ATTRIBUTE_TEMPORARY;
ensure(clean(SetFileInformationByHandle(h, FileBasicInfo, &info0, sizeof(info0))));
}
if (DWORD bytesReturned{}; (info0.FileAttributes & FILE_ATTRIBUTE_SPARSE_FILE) || DeviceIoControl(h, FSCTL_SET_SPARSE, &arg, sizeof(arg), nullptr, 0, &bytesReturned, nullptr))
{
if ((info0.FileAttributes & FILE_ATTRIBUTE_SPARSE_FILE) == 0 && !storagex.empty())
{
// Retry once (bug workaround)
if (!open_with_cleanup(f, storagex))
{
return false;
}
return set_sparse_and_map("", f.get_handle(), m_size);
}
FILE_STANDARD_INFO info;
FILE_END_OF_FILE_INFO _eof{};
ensure(clean(GetFileInformationByHandleEx(h, FileStandardInfo, &info, sizeof(info))));
ensure(clean(GetFileSizeEx(h, &_eof.EndOfFile)));
if (info.AllocationSize.QuadPart && _eof.EndOfFile.QuadPart == static_cast<LONGLONG>(m_size))
{
// Truncate file since it may be dirty (fool-proof)
DWORD ret = 0;
FILE_ALLOCATED_RANGE_BUFFER dummy{};
dummy.Length.QuadPart = m_size;
if (!DeviceIoControl(h, FSCTL_QUERY_ALLOCATED_RANGES, &dummy, sizeof(dummy), nullptr, 0, &ret, 0) || ret)
{
_eof.EndOfFile.QuadPart = 0;
}
}
if (_eof.EndOfFile.QuadPart != static_cast<LONGLONG>(m_size))
{
// Reset file size to 0 if it doesn't match
_eof.EndOfFile.QuadPart = 0;
ensure(clean(SetFileInformationByHandle(h, FileEndOfFileInfo, &_eof, sizeof(_eof))));
}
// It seems impossible to automatically delete file on exit when file mapping is used
if (f.size() != m_size)
{
// Resize the file gradually (bug workaround)
for (usz i = 0; i < m_size / (1024 * 1024 * 256); i++)
{
ensure(clean(f.trunc((i + 1) * (1024 * 1024 * 256))));
}
ensure(clean(f.trunc(m_size)));
}
m_handle = ::CreateFileMappingW(f.get_handle(), nullptr, PAGE_READWRITE, 0, 0, nullptr);
if (clean(!m_handle))
{
ensure(storagex == storage1);
return false;
}
return true;
}
return false;
};
// Attempt to remove from secondary storage in case this succeeds
fs::remove_file(storage2);
if (!open_with_cleanup(f, storage1) || !set_sparse_and_map(storage1, f.get_handle(), m_size))
{
// Attempt to remove from main storage in case this succeeds
f.close();
fs::remove_file(storage1);
// Fallback storage
ensure(open_with_cleanup(f, storage2));
if (!set_sparse_and_map(storage2, f.get_handle(), m_size))
{
MessageBoxW(0, L"Failed to initialize sparse file.\nCan't find a filesystem with sparse file support (NTFS).", L"RPCS3", MB_ICONERROR);
}
m_storage = std::move(storage2);
}
else
{
m_storage = std::move(storage1);
}
#else
#ifdef __linux__
if (const char c = fs::file("/proc/sys/vm/overcommit_memory").read<char>(); c == '0' || c == '1')
{
// Simply use memfd for overcommit memory
m_file = ensure(::memfd_create_("", 0), FN(x >= 0));
ensure(::ftruncate(m_file, m_size) >= 0);
return;
}
else
{
fprintf(stderr, "Reading /proc/sys/vm/overcommit_memory: %c", c);
}
#else
int vm_overcommit = 0;
#if defined(__NetBSD__) || defined(__APPLE__)
// Always ON
vm_overcommit = 0;
#elif defined(__FreeBSD__)
auto vm_sz = sizeof(int);
int mib[2]{CTL_VM, VM_OVERCOMMIT};
if (::sysctl(mib, 2, &vm_overcommit, &vm_sz, NULL, 0) != 0)
vm_overcommit = -1;
#else
vm_overcommit = -1;
#endif
if ((vm_overcommit & 3) == 0)
{
#if defined(__FreeBSD__)
m_file = ensure(::memfd_create_("", 0), FN(x >= 0));
#else
const std::string name = "/rpcs3-mem2-" + std::to_string(reinterpret_cast<u64>(this));
while ((m_file = ::shm_open(name.c_str(), O_RDWR | O_CREAT | O_EXCL, S_IWUSR | S_IRUSR)) == -1)
{
if (errno == EMFILE)
{
fmt::throw_exception("Too many open files. Raise the limit and try again.");
}
ensure(errno == EEXIST);
}
ensure(::shm_unlink(name.c_str()) >= 0);
#endif
ensure(::ftruncate(m_file, m_size) >= 0);
return;
}
#endif
if (!storage.empty())
{
m_file = ::open(storage.c_str(), O_RDWR | O_CREAT, S_IWUSR | S_IRUSR);
::unlink(storage.c_str());
}
else
{
std::string storage = fs::get_cache_dir() + "rpcs3_vm_sparse.tmp";
m_file = ::open(storage.c_str(), O_RDWR | O_CREAT, S_IWUSR | S_IRUSR);
::unlink(storage.c_str());
}
ensure(m_file >= 0);
struct ::stat stats;
ensure(::fstat(m_file, &stats) >= 0);
if (!(stats.st_size ^ m_size) && !stats.st_blocks)
{
// Already initialized
return;
}
// Truncate file since it may be dirty (fool-proof)
ensure(::ftruncate(m_file, 0) >= 0);
ensure(::ftruncate(m_file, 0x100000) >= 0);
stats.st_size = 0x100000;
#ifdef SEEK_DATA
errno = EINVAL;
if (stats.st_blocks * 512 >= 0x100000 && ::lseek(m_file, 0, SEEK_DATA) ^ stats.st_size && errno != ENXIO)
{
fmt::throw_exception("Failed to initialize sparse file in '%s'\n"
"It seems this filesystem doesn't support sparse files (%d).\n",
storage.empty() ? fs::get_cache_dir().c_str() : storage.c_str(), +errno);
}
#endif
if (stats.st_size ^ m_size)
{
// Fix file size
ensure(::ftruncate(m_file, m_size) >= 0);
}
#endif
}
shm::~shm()
{
this->unmap_self();
#ifdef _WIN32
::CloseHandle(m_handle);
#else
::close(m_file);
#endif
if (!m_storage.empty())
fs::remove_file(m_storage);
}
u8* shm::map(void* ptr, protection prot, bool cow) const
{
#ifdef _WIN32
DWORD access = FILE_MAP_WRITE;
switch (prot)
{
case protection::rw:
case protection::ro:
case protection::no:
break;
case protection::wx:
case protection::rx:
access |= FILE_MAP_EXECUTE;
break;
}
if (cow)
{
access |= FILE_MAP_COPY;
}
if (auto ret = static_cast<u8*>(::MapViewOfFileEx(m_handle, access, 0, 0, m_size, ptr)))
{
if (prot != protection::rw && prot != protection::wx)
{
DWORD old;
if (!::VirtualProtect(ret, m_size, +prot, &old))
{
::UnmapViewOfFile(ret);
return nullptr;
}
}
return ret;
}
return nullptr;
#else
const u64 ptr64 = reinterpret_cast<u64>(ptr) & -0x10000;
if (ptr64)
{
const auto result = ::mmap(reinterpret_cast<void*>(ptr64), m_size, +prot, (cow ? MAP_PRIVATE : MAP_SHARED) | MAP_FIXED, m_file, 0);
return reinterpret_cast<u8*>(result);
}
else
{
const u64 res64 = reinterpret_cast<u64>(::mmap(reinterpret_cast<void*>(ptr64), m_size + 0xf000, PROT_NONE, MAP_ANON | MAP_PRIVATE, -1, 0));
const u64 aligned = utils::align(res64, 0x10000);
const auto result = ::mmap(reinterpret_cast<void*>(aligned), m_size, +prot, (cow ? MAP_PRIVATE : MAP_SHARED) | MAP_FIXED, m_file, 0);
// Now cleanup remnants
if (aligned > res64)
{
ensure(::munmap(reinterpret_cast<void*>(res64), aligned - res64) == 0);
}
if (aligned < res64 + 0xf000)
{
ensure(::munmap(reinterpret_cast<void*>(aligned + m_size), (res64 + 0xf000) - (aligned)) == 0);
}
return reinterpret_cast<u8*>(result);
}
#endif
}
u8* shm::try_map(void* ptr, protection prot, bool cow) const
{
// Non-null pointer shall be specified
const auto target = ensure(reinterpret_cast<u8*>(reinterpret_cast<u64>(ptr) & -0x10000));
#ifdef _WIN32
return this->map(target, prot, cow);
#else
const auto result = reinterpret_cast<u8*>(::mmap(reinterpret_cast<void*>(target), m_size, +prot, (cow ? MAP_PRIVATE : MAP_SHARED), m_file, 0));
if (result == reinterpret_cast<void*>(uptr{umax}))
{
[[unlikely]] return nullptr;
}
return result;
#endif
}
std::pair<u8*, std::string> shm::map_critical(void* ptr, protection prot, bool cow)
{
const auto target = reinterpret_cast<u8*>(reinterpret_cast<u64>(ptr) & -0x10000);
#ifdef _WIN32
::MEMORY_BASIC_INFORMATION mem{};
if (!::VirtualQuery(target, &mem, sizeof(mem)) || mem.State != MEM_RESERVE)
{
return {nullptr, fmt::format("VirtualQuery() Unexpceted memory info: state=0x%x, %s", mem.State, std::as_bytes(std::span(&mem, 1)))};
}
const auto base = static_cast<u8*>(mem.AllocationBase);
const auto size = mem.RegionSize + (target - base);
if (is_memory_mappping_memory(ptr))
{
if (base < target && !::VirtualFree(base, target - base, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER))
{
return {nullptr, "Failed to split allocation base"};
}
if (target + m_size < base + size && !::VirtualFree(target, m_size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER))
{
return {nullptr, "Failed to split allocation end"};
}
DWORD access = 0;
switch (prot)
{
case protection::rw:
case protection::ro:
case protection::no:
access = cow ? PAGE_WRITECOPY : PAGE_READWRITE;
break;
case protection::wx:
case protection::rx:
access = cow ? PAGE_EXECUTE_WRITECOPY : PAGE_EXECUTE_READWRITE;
break;
}
if (MapViewOfFile3(m_handle, GetCurrentProcess(), target, 0, m_size, MEM_REPLACE_PLACEHOLDER, access, nullptr, 0))
{
if (prot != protection::rw && prot != protection::wx)
{
DWORD old;
if (!::VirtualProtect(target, m_size, +prot, &old))
{
UnmapViewOfFile2(GetCurrentProcess(), target, MEM_PRESERVE_PLACEHOLDER);
return {nullptr, "Failed to protect"};
}
}
return {target, {}};
}
return {nullptr, "Failed to map3"};
}
if (!::VirtualFree(mem.AllocationBase, 0, MEM_RELEASE))
{
return {nullptr, "VirtualFree() failed on allocation base"};
}
if (base < target && !::VirtualAlloc(base, target - base, MEM_RESERVE, PAGE_NOACCESS))
{
return {nullptr, "VirtualAlloc() failed to reserve allocation base"};
}
if (target + m_size < base + size && !::VirtualAlloc(target + m_size, base + size - target - m_size, MEM_RESERVE, PAGE_NOACCESS))
{
return {nullptr, "VirtualAlloc() failed to reserve allocation end"};
}
#endif
return {this->map(target, prot, cow), "Failed to map"};
}
u8* shm::map_self(protection prot)
{
void* ptr = m_ptr;
while (!ptr)
{
const auto mapped = this->map(nullptr, prot);
// Install mapped memory
if (!m_ptr.compare_exchange(ptr, mapped))
{
// Mapped already, nothing to do.
this->unmap(mapped);
}
else
{
ptr = mapped;
}
}
return static_cast<u8*>(ptr);
}
void shm::unmap(void* ptr) const
{
#ifdef _WIN32
::UnmapViewOfFile(ptr);
#else
::munmap(ptr, m_size);
#endif
}
void shm::unmap_critical(void* ptr)
{
const auto target = reinterpret_cast<u8*>(reinterpret_cast<u64>(ptr) & -0x10000);
#ifdef _WIN32
if (is_memory_mappping_memory(ptr))
{
ensure(UnmapViewOfFile2(GetCurrentProcess(), target, MEM_PRESERVE_PLACEHOLDER));
::MEMORY_BASIC_INFORMATION mem{}, mem2{};
ensure(::VirtualQuery(target - 1, &mem, sizeof(mem)) && ::VirtualQuery(target + m_size, &mem2, sizeof(mem2)));
const auto size1 = mem.State == MEM_RESERVE ? target - static_cast<u8*>(mem.AllocationBase) : 0;
const auto size2 = mem2.State == MEM_RESERVE ? mem2.RegionSize : 0;
if (!size1 && !size2)
{
return;
}
ensure(::VirtualFree(size1 ? mem.AllocationBase : target, m_size + size1 + size2, MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS));
return;
}
this->unmap(target);
::MEMORY_BASIC_INFORMATION mem, mem2;
if (!::VirtualQuery(target - 1, &mem, sizeof(mem)) || !::VirtualQuery(target + m_size, &mem2, sizeof(mem2)))
{
return;
}
if (mem.State == MEM_RESERVE && !::VirtualFree(mem.AllocationBase, 0, MEM_RELEASE))
{
return;
}
if (mem2.State == MEM_RESERVE && !::VirtualFree(mem2.AllocationBase, 0, MEM_RELEASE))
{
return;
}
const auto size1 = mem.State == MEM_RESERVE ? target - static_cast<u8*>(mem.AllocationBase) : 0;
const auto size2 = mem2.State == MEM_RESERVE ? mem2.RegionSize : 0;
if (!::VirtualAlloc(mem.State == MEM_RESERVE ? mem.AllocationBase : target, m_size + size1 + size2, MEM_RESERVE, PAGE_NOACCESS))
{
return;
}
#else
// This method is faster but leaves mapped remnants of the shm (until overwritten)
ensure(::mprotect(target, m_size, PROT_NONE) != -1);
#endif
}
void shm::unmap_self()
{
if (auto ptr = m_ptr.exchange(nullptr))
{
this->unmap(ptr);
}
}
}
| 26,477
|
C++
|
.cpp
| 875
| 26.946286
| 191
| 0.655176
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,045
|
cpu_stats.cpp
|
RPCS3_rpcs3/rpcs3/util/cpu_stats.cpp
|
#include "util/types.hpp"
#include "util/cpu_stats.hpp"
#include "util/sysinfo.hpp"
#include "util/logs.hpp"
#include "util/asm.hpp"
#include "Utilities/StrUtil.h"
#include <algorithm>
#ifdef _WIN32
#include "windows.h"
#include "tlhelp32.h"
#ifdef _MSC_VER
#pragma comment(lib, "pdh.lib")
#endif
#else
#include "fstream"
#include "sstream"
#include "stdlib.h"
#include "sys/times.h"
#include "sys/types.h"
#include "unistd.h"
#endif
#ifdef __APPLE__
# include <mach/mach_init.h>
# include <mach/task.h>
# include <mach/vm_map.h>
#endif
#ifdef __linux__
# include <dirent.h>
#endif
#if defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
# include <sys/sysctl.h>
# if defined(__DragonFly__) || defined(__FreeBSD__)
# include <sys/user.h>
# endif
# if defined(__NetBSD__)
# undef KERN_PROC
# define KERN_PROC KERN_PROC2
# define kinfo_proc kinfo_proc2
# endif
# if defined(__DragonFly__)
# define KP_NLWP(kp) (kp.kp_nthreads)
# elif defined(__FreeBSD__)
# define KP_NLWP(kp) (kp.ki_numthreads)
# elif defined(__NetBSD__)
# define KP_NLWP(kp) (kp.p_nlwps)
# endif
#endif
LOG_CHANNEL(perf_log, "PERF");
namespace utils
{
#ifdef _WIN32
fmt::win_error pdh_error(PDH_STATUS status)
{
return fmt::win_error{static_cast<unsigned long>(status), LoadLibrary(L"pdh.dll")};
}
#endif
cpu_stats::cpu_stats()
{
#ifdef _WIN32
FILETIME ftime, fsys, fuser;
GetSystemTimeAsFileTime(&ftime);
memcpy(&m_last_cpu, &ftime, sizeof(FILETIME));
GetProcessTimes(GetCurrentProcess(), &ftime, &ftime, &fsys, &fuser);
memcpy(&m_sys_cpu, &fsys, sizeof(FILETIME));
memcpy(&m_usr_cpu, &fuser, sizeof(FILETIME));
#else
struct tms timeSample;
m_last_cpu = times(&timeSample);
m_sys_cpu = timeSample.tms_stime;
m_usr_cpu = timeSample.tms_utime;
#endif
}
cpu_stats::~cpu_stats()
{
#ifdef _WIN32
if (m_cpu_query)
{
PDH_STATUS status = PdhCloseQuery(m_cpu_query);
if (ERROR_SUCCESS != status)
{
perf_log.error("Failed to close cpu query of per core cpu usage: %s", pdh_error(status));
}
}
#endif
}
void cpu_stats::init_cpu_query()
{
#ifdef _WIN32
PDH_STATUS status = PdhOpenQuery(NULL, 0, &m_cpu_query);
if (ERROR_SUCCESS != status)
{
perf_log.error("Failed to open cpu query for per core cpu usage: %s", pdh_error(status));
return;
}
status = PdhAddEnglishCounter(m_cpu_query, L"\\Processor(*)\\% Processor Time", 0, &m_cpu_cores);
if (ERROR_SUCCESS != status)
{
perf_log.error("Failed to add processor time counter for per core cpu usage: %s", pdh_error(status));
return;
}
status = PdhCollectQueryData(m_cpu_query);
if (ERROR_SUCCESS != status)
{
perf_log.error("Failed to collect per core cpu usage: %s", pdh_error(status));
return;
}
#endif
}
void cpu_stats::get_per_core_usage(std::vector<double>& per_core_usage, double& total_usage)
{
total_usage = 0.0;
per_core_usage.resize(utils::get_thread_count());
std::fill(per_core_usage.begin(), per_core_usage.end(), 0.0);
#if defined(_WIN32) || defined(__linux__)
const auto string_to_number = [](const std::string& str) -> std::pair<bool, size_t>
{
std::add_pointer_t<char> eval;
const size_t number = std::strtol(str.c_str(), &eval, 10);
if (str.c_str() + str.size() == eval)
{
return { true, number };
}
return { false, 0 };
};
#ifdef _WIN32
if (!m_cpu_cores || !m_cpu_query)
{
perf_log.warning("Can not collect per core cpu usage: The required API is not initialized.");
return;
}
PDH_STATUS status = PdhCollectQueryData(m_cpu_query);
if (ERROR_SUCCESS != status)
{
perf_log.error("Failed to collect per core cpu usage: %s", pdh_error(status));
return;
}
DWORD dwBufferSize = 0; // Size of the items buffer
DWORD dwItemCount = 0; // Number of items in the items buffer
status = PdhGetFormattedCounterArray(m_cpu_cores, PDH_FMT_DOUBLE, &dwBufferSize, &dwItemCount, nullptr);
if (static_cast<PDH_STATUS>(PDH_MORE_DATA) == status)
{
std::vector<PDH_FMT_COUNTERVALUE_ITEM> items(utils::aligned_div(dwBufferSize, sizeof(PDH_FMT_COUNTERVALUE_ITEM)));
if (items.size() >= dwItemCount)
{
status = PdhGetFormattedCounterArray(m_cpu_cores, PDH_FMT_DOUBLE, &dwBufferSize, &dwItemCount, items.data());
if (ERROR_SUCCESS == status)
{
ensure(dwItemCount == per_core_usage.size() + 1); // Plus one for _Total
// Loop through the array and get the instance name and percentage.
for (usz i = 0; i < dwItemCount; i++)
{
const PDH_FMT_COUNTERVALUE_ITEM& item = items[i];
const std::string token = wchar_to_utf8(item.szName);
if (const std::string lower = fmt::to_lower(token); lower.find("total") != umax)
{
total_usage = item.FmtValue.doubleValue;
continue;
}
if (const auto [success, cpu_index] = string_to_number(token); success && cpu_index < dwItemCount)
{
per_core_usage[cpu_index] = item.FmtValue.doubleValue;
}
else if (!success)
{
perf_log.error("Can not convert string to cpu index for per core cpu usage. (token='%s')", token);
}
else
{
perf_log.error("Invalid cpu index for per core cpu usage. (token='%s', cpu_index=%d, cores=%d)", token, cpu_index, dwItemCount);
}
}
}
else if (static_cast<PDH_STATUS>(PDH_CALC_NEGATIVE_DENOMINATOR) == status) // Apparently this is a common uncritical error
{
perf_log.notice("Failed to get per core cpu usage: %s", pdh_error(status));
}
else
{
perf_log.error("Failed to get per core cpu usage: %s", pdh_error(status));
}
}
else
{
perf_log.error("Failed to allocate buffer for per core cpu usage. (size=%d, dwItemCount=%d)", items.size(), dwItemCount);
}
}
#elif __linux__
m_previous_idle_times_per_cpu.resize(utils::get_thread_count(), 0.0);
m_previous_total_times_per_cpu.resize(utils::get_thread_count(), 0.0);
if (std::ifstream proc_stat("/proc/stat"); proc_stat.good())
{
std::stringstream content;
content << proc_stat.rdbuf();
proc_stat.close();
const std::vector<std::string> lines = fmt::split(content.str(), {"\n"});
if (lines.empty())
{
perf_log.error("/proc/stat is empty");
return;
}
for (const std::string& line : lines)
{
const std::vector<std::string> tokens = fmt::split(line, {" "});
if (tokens.size() < 5)
{
return;
}
const std::string& token = tokens[0];
if (!token.starts_with("cpu"))
{
return;
}
// Get CPU index
int cpu_index = -1; // -1 for total
constexpr size_t size_of_cpu = 3;
if (token.size() > size_of_cpu)
{
if (const auto [success, val] = string_to_number(token.substr(size_of_cpu)); success && val < per_core_usage.size())
{
cpu_index = val;
}
else if (!success)
{
perf_log.error("Can not convert string to cpu index for per core cpu usage. (token='%s', line='%s')", token, line);
continue;
}
else
{
perf_log.error("Invalid cpu index for per core cpu usage. (cpu_index=%d, cores=%d, token='%s', line='%s')", cpu_index, per_core_usage.size(), token, line);
continue;
}
}
size_t idle_time = 0;
size_t total_time = 0;
for (size_t i = 1; i < tokens.size(); i++)
{
if (const auto [success, val] = string_to_number(tokens[i]); success)
{
if (i == 4)
{
idle_time = val;
}
total_time += val;
}
else
{
perf_log.error("Can not convert string to time for per core cpu usage. (i=%d, token='%s', line='%s')", i, tokens[i], line);
}
}
if (cpu_index < 0)
{
const double idle_time_delta = idle_time - std::exchange(m_previous_idle_time_total, idle_time);
const double total_time_delta = total_time - std::exchange(m_previous_total_time_total, total_time);
total_usage = 100.0 * (1.0 - idle_time_delta / total_time_delta);
}
else
{
const double idle_time_delta = idle_time - std::exchange(m_previous_idle_times_per_cpu[cpu_index], idle_time);
const double total_time_delta = total_time - std::exchange(m_previous_total_times_per_cpu[cpu_index], total_time);
per_core_usage[cpu_index] = 100.0 * (1.0 - idle_time_delta / total_time_delta);
}
}
}
else
{
perf_log.error("Failed to open /proc/stat (%s)", strerror(errno));
}
#endif
#else
total_usage = get_usage();
#endif
}
double cpu_stats::get_usage()
{
#ifdef _WIN32
FILETIME ftime, fsys, fusr;
ULARGE_INTEGER now, sys, usr;
double percent;
GetSystemTimeAsFileTime(&ftime);
memcpy(&now, &ftime, sizeof(FILETIME));
GetProcessTimes(GetCurrentProcess(), &ftime, &ftime, &fsys, &fusr);
memcpy(&sys, &fsys, sizeof(FILETIME));
memcpy(&usr, &fusr, sizeof(FILETIME));
if (now.QuadPart <= m_last_cpu || sys.QuadPart < m_sys_cpu || usr.QuadPart < m_usr_cpu)
{
// Overflow detection. Just skip this value.
percent = 0.0;
}
else
{
percent = static_cast<double>((sys.QuadPart - m_sys_cpu) + (usr.QuadPart - m_usr_cpu));
percent /= (now.QuadPart - m_last_cpu);
percent /= utils::get_thread_count(); // Let's assume this is at least 1
percent *= 100;
}
m_last_cpu = now.QuadPart;
m_usr_cpu = usr.QuadPart;
m_sys_cpu = sys.QuadPart;
return std::clamp(percent, 0.0, 100.0);
#else
struct tms timeSample;
clock_t now = times(&timeSample);
double percent;
if (now <= static_cast<clock_t>(m_last_cpu) || timeSample.tms_stime < static_cast<clock_t>(m_sys_cpu) || timeSample.tms_utime < static_cast<clock_t>(m_usr_cpu))
{
// Overflow detection. Just skip this value.
percent = 0.0;
}
else
{
percent = (timeSample.tms_stime - m_sys_cpu) + (timeSample.tms_utime - m_usr_cpu);
percent /= (now - m_last_cpu);
percent /= utils::get_thread_count();
percent *= 100;
}
m_last_cpu = now;
m_sys_cpu = timeSample.tms_stime;
m_usr_cpu = timeSample.tms_utime;
return std::clamp(percent, 0.0, 100.0);
#endif
}
u32 cpu_stats::get_current_thread_count() // static
{
#ifdef _WIN32
// first determine the id of the current process
const DWORD id = GetCurrentProcessId();
// then get a process list snapshot.
const HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
// initialize the process entry structure.
PROCESSENTRY32 entry = {0};
entry.dwSize = sizeof(entry);
// get the first process info.
BOOL ret = Process32First(snapshot, &entry);
while (ret && entry.th32ProcessID != id)
{
ret = Process32Next(snapshot, &entry);
}
CloseHandle(snapshot);
return ret ? entry.cntThreads : 0;
#elif defined(__APPLE__)
const task_t task = mach_task_self();
mach_msg_type_number_t thread_count;
thread_act_array_t thread_list;
if (task_threads(task, &thread_list, &thread_count) != KERN_SUCCESS)
{
return 0;
}
vm_deallocate(task, reinterpret_cast<vm_address_t>(thread_list),
sizeof(thread_t) * thread_count);
return static_cast<u32>(thread_count);
#elif defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__)
int mib[] = {
CTL_KERN,
KERN_PROC,
KERN_PROC_PID,
getpid(),
#if defined(__NetBSD__)
sizeof(struct kinfo_proc),
1,
#endif
};
u_int miblen = std::size(mib);
struct kinfo_proc info;
usz size = sizeof(info);
if (sysctl(mib, miblen, &info, &size, NULL, 0))
{
return 0;
}
return KP_NLWP(info);
#elif defined(__OpenBSD__)
int mib[] = {
CTL_KERN,
KERN_PROC,
KERN_PROC_PID | KERN_PROC_SHOW_THREADS,
getpid(),
sizeof(struct kinfo_proc),
0,
};
u_int miblen = std::size(mib);
// get number of structs
usz size;
if (sysctl(mib, miblen, NULL, &size, NULL, 0))
{
return 0;
}
mib[5] = size / mib[4];
// populate array of structs
struct kinfo_proc info[mib[5]];
if (sysctl(mib, miblen, &info, &size, NULL, 0))
{
return 0;
}
// exclude empty members
u32 thread_count{0};
for (int i = 0; i < size / mib[4]; i++)
{
if (info[i].p_tid != -1)
++thread_count;
}
return thread_count;
#elif defined(__linux__)
u32 thread_count{0};
DIR* proc_dir = opendir("/proc/self/task");
if (proc_dir)
{
// proc available, iterate through tasks and count them
struct dirent* entry;
while ((entry = readdir(proc_dir)) != NULL)
{
if (entry->d_name[0] == '.')
continue;
++thread_count;
}
closedir(proc_dir);
}
return thread_count;
#else
// unimplemented
return 0;
#endif
}
}
| 12,505
|
C++
|
.cpp
| 422
| 26.00237
| 162
| 0.651838
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,046
|
media_utils.cpp
|
RPCS3_rpcs3/rpcs3/util/media_utils.cpp
|
#include "stdafx.h"
#include "media_utils.h"
#include "Emu/System.h"
#include <random>
#ifdef _MSC_VER
#pragma warning(push, 0)
#else
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wall"
#pragma GCC diagnostic ignored "-Wextra"
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif
extern "C" {
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libavutil/dict.h"
#include "libavutil/opt.h"
#include "libavutil/imgutils.h"
#include "libswscale/swscale.h"
#include "libswresample/swresample.h"
}
constexpr int averror_eof = AVERROR_EOF; // workaround for old-style-cast error
constexpr int averror_invalid_data = AVERROR_INVALIDDATA; // workaround for old-style-cast error
#ifdef _MSC_VER
#pragma warning(pop)
#else
#pragma GCC diagnostic pop
#endif
LOG_CHANNEL(media_log, "Media");
namespace utils
{
template <typename T>
static inline void write_byteswapped(const void* src, void* dst)
{
*reinterpret_cast<T*>(dst) = *reinterpret_cast<const be_t<T>*>(src);
}
template <typename T>
static inline void copy_samples(const u8* src, u8* dst, usz sample_count, bool swap_endianness)
{
if (swap_endianness)
{
for (usz i = 0; i < sample_count; i++)
{
write_byteswapped<T>(src + i * sizeof(T), dst + i * sizeof(T));
}
}
else
{
std::memcpy(dst, src, sample_count * sizeof(T));
}
}
const auto free_packet = [](AVPacket* p)
{
if (p)
{
av_packet_unref(p);
av_packet_free(&p);
}
};
const auto av_log_callback = [](void* avcl, int level, const char* fmt, va_list vl) -> void
{
if (level > av_log_get_level())
{
return;
}
constexpr int line_size = 1024;
char line[line_size]{};
int print_prefix = 1;
if (int err = av_log_format_line2(avcl, level, fmt, vl, line, line_size, &print_prefix); err < 0)
{
media_log.error("av_log: av_log_format_line2 failed. Error: %d='%s'", err, av_error_to_string(err));
return;
}
std::string msg = line;
fmt::trim_back(msg, "\n\r\t ");
if (level <= AV_LOG_ERROR)
media_log.error("av_log: %s", msg);
else if (level <= AV_LOG_WARNING)
media_log.warning("av_log: %s", msg);
else
media_log.notice("av_log: %s", msg);
};
template <>
std::string media_info::get_metadata(const std::string& key, const std::string& def) const
{
if (metadata.contains(key))
{
return ::at32(metadata, key);
}
return def;
}
template <>
s64 media_info::get_metadata(const std::string& key, const s64& def) const
{
if (metadata.contains(key))
{
s64 result{};
if (try_to_int64(&result, ::at32(metadata, key), smin, smax))
{
return result;
}
}
return def;
}
std::string av_error_to_string(int error)
{
char av_error[AV_ERROR_MAX_STRING_SIZE]{};
av_make_error_string(av_error, AV_ERROR_MAX_STRING_SIZE, error);
return av_error;
}
std::vector<ffmpeg_codec> list_ffmpeg_codecs(bool list_decoders)
{
std::vector<ffmpeg_codec> codecs;
void* opaque = nullptr;
for (const AVCodec* codec = av_codec_iterate(&opaque); !!codec; codec = av_codec_iterate(&opaque))
{
if (list_decoders ? av_codec_is_decoder(codec) : av_codec_is_encoder(codec))
{
codecs.emplace_back(ffmpeg_codec{
.codec_id = static_cast<int>(codec->id),
.name = codec->name ? codec->name : "unknown",
.long_name = codec->long_name ? codec->long_name : "unknown"
});
}
}
std::sort(codecs.begin(), codecs.end(), [](const ffmpeg_codec& l, const ffmpeg_codec& r){ return l.name < r.name; });
return codecs;
}
std::vector<ffmpeg_codec> list_ffmpeg_decoders()
{
return list_ffmpeg_codecs(true);
}
std::vector<ffmpeg_codec> list_ffmpeg_encoders()
{
return list_ffmpeg_codecs(false);
}
std::pair<bool, media_info> get_media_info(const std::string& path, s32 av_media_type)
{
media_info info{};
info.path = path;
if (av_media_type == AVMEDIA_TYPE_UNKNOWN) // Let's use this for image info
{
const bool success = Emu.GetCallbacks().get_image_info(path, info.sub_type, info.width, info.height, info.orientation);
if (!success) media_log.error("get_media_info: failed to get image info for '%s'", path);
return { success, std::move(info) };
}
// Only print FFMPEG errors, fatals and panics
av_log_set_callback(av_log_callback);
av_log_set_level(AV_LOG_ERROR);
AVDictionary* av_dict_opts = nullptr;
if (int err = av_dict_set(&av_dict_opts, "probesize", "96", 0); err < 0)
{
media_log.error("get_media_info: av_dict_set: returned with error=%d='%s'", err, av_error_to_string(err));
return { false, std::move(info) };
}
AVFormatContext* av_format_ctx = avformat_alloc_context();
// Open input file
if (int err = avformat_open_input(&av_format_ctx, path.c_str(), nullptr, &av_dict_opts); err < 0)
{
// Failed to open file
av_dict_free(&av_dict_opts);
avformat_free_context(av_format_ctx);
media_log.notice("get_media_info: avformat_open_input: could not open file. error=%d='%s' file='%s'", err, av_error_to_string(err), path);
return { false, std::move(info) };
}
av_dict_free(&av_dict_opts);
// Find stream information
if (int err = avformat_find_stream_info(av_format_ctx, nullptr); err < 0)
{
// Failed to load stream information
avformat_close_input(&av_format_ctx);
media_log.notice("get_media_info: avformat_find_stream_info: could not load stream information. error=%d='%s' file='%s'", err, av_error_to_string(err), path);
return { false, std::move(info) };
}
// Derive first stream id and type from avformat context.
// We are only interested in the first matching stream for now.
int audio_stream_index = -1;
int video_stream_index = -1;
for (uint i = 0; i < av_format_ctx->nb_streams; i++)
{
switch (av_format_ctx->streams[i]->codecpar->codec_type)
{
case AVMEDIA_TYPE_AUDIO:
if (audio_stream_index < 0)
audio_stream_index = i;
break;
case AVMEDIA_TYPE_VIDEO:
if (video_stream_index < 0)
video_stream_index = i;
break;
default:
break;
}
}
// Abort if there is no natching stream or if the stream isn't the first one
if ((av_media_type == AVMEDIA_TYPE_AUDIO && audio_stream_index != 0) ||
(av_media_type == AVMEDIA_TYPE_VIDEO && video_stream_index != 0))
{
// Failed to find a stream
avformat_close_input(&av_format_ctx);
media_log.notice("get_media_info: Failed to match stream of type %d in file='%s'", av_media_type, path);
return { false, std::move(info) };
}
// Get video info if available
if (video_stream_index >= 0)
{
const AVStream* stream = av_format_ctx->streams[video_stream_index];
info.video_av_codec_id = stream->codecpar->codec_id;
info.video_bitrate_bps = static_cast<s32>(stream->codecpar->bit_rate);
}
// Get audio info if available
if (audio_stream_index >= 0)
{
const AVStream* stream = av_format_ctx->streams[audio_stream_index];
info.audio_av_codec_id = stream->codecpar->codec_id;
info.audio_bitrate_bps = static_cast<s32>(stream->codecpar->bit_rate);
info.sample_rate = stream->codecpar->sample_rate;
}
info.duration_us = av_format_ctx->duration;
AVDictionaryEntry* tag = nullptr;
while ((tag = av_dict_get(av_format_ctx->metadata, "", tag, AV_DICT_IGNORE_SUFFIX)))
{
info.metadata[tag->key] = tag->value;
}
avformat_close_input(&av_format_ctx);
return { true, std::move(info) };
}
struct scoped_av
{
struct ctx
{
const AVCodec* codec = nullptr;
AVCodecContext* context = nullptr;
AVStream* stream = nullptr;
AVPacket* packet = nullptr;
AVFrame* frame = nullptr;
};
ctx audio{};
ctx video{};
AVFormatContext* format_context = nullptr;
SwrContext* swr = nullptr;
SwsContext* sws = nullptr;
std::function<void()> kill_callback = nullptr;
~scoped_av()
{
// Clean up
if (audio.frame)
{
av_frame_unref(audio.frame);
av_frame_free(&audio.frame);
}
if (video.frame)
{
av_frame_unref(video.frame);
av_frame_free(&video.frame);
}
free_packet(audio.packet);
free_packet(video.packet);
if (swr)
swr_free(&swr);
if (sws)
sws_freeContext(sws);
if (audio.context)
avcodec_free_context(&audio.context);
if (video.context)
avcodec_free_context(&video.context);
// AVCodec is managed by libavformat, no need to free it
// see: https://stackoverflow.com/a/18047320
if (format_context)
avformat_close_input(&format_context);
//if (stream)
// av_free(stream);
if (kill_callback)
kill_callback();
}
};
static std::string channel_layout_name(const AVChannelLayout& ch_layout)
{
std::vector<char> ch_layout_buf(64);
int len = av_channel_layout_describe(&ch_layout, ch_layout_buf.data(), ch_layout_buf.size());
if (len < 0)
{
media_log.error("av_channel_layout_describe failed. Error: %d='%s'", len, av_error_to_string(len));
return {};
}
if (len > static_cast<int>(ch_layout_buf.size()))
{
// Try again with a bigger buffer
media_log.notice("av_channel_layout_describe needs a bigger buffer: len=%d", len);
ch_layout_buf.clear();
ch_layout_buf.resize(len);
len = av_channel_layout_describe(&ch_layout, ch_layout_buf.data(), ch_layout_buf.size());
if (len < 0)
{
media_log.error("av_channel_layout_describe failed. Error: %d='%s'", len, av_error_to_string(len));
return {};
}
}
return ch_layout_buf.data();
}
// check that a given sample format is supported by the encoder
static bool check_sample_fmt(const AVCodec* codec, enum AVSampleFormat sample_fmt)
{
if (!codec) return false;
for (const AVSampleFormat* p = codec->sample_fmts; p && *p != AV_SAMPLE_FMT_NONE; p++)
{
if (*p == sample_fmt)
{
return true;
}
}
return false;
}
// just pick the highest supported samplerate
static int select_sample_rate(const AVCodec* codec)
{
if (!codec || !codec->supported_samplerates)
return 48000;
int best_samplerate = 0;
for (const int* samplerate = codec->supported_samplerates; samplerate && *samplerate != 0; samplerate++)
{
if (!best_samplerate || abs(48000 - *samplerate) < abs(48000 - best_samplerate))
{
best_samplerate = *samplerate;
}
}
return best_samplerate;
}
AVChannelLayout get_preferred_channel_layout(int channels)
{
switch (channels)
{
case 2:
return AV_CHANNEL_LAYOUT_STEREO;
case 6:
return AV_CHANNEL_LAYOUT_5POINT1;
case 8:
return AV_CHANNEL_LAYOUT_7POINT1;
default:
break;
}
return {};
}
static constexpr AVChannelLayout empty_ch_layout = {};
// select layout with the exact channel count
static const AVChannelLayout* select_channel_layout(const AVCodec* codec, int channels)
{
if (!codec) return nullptr;
const AVChannelLayout preferred_ch_layout = get_preferred_channel_layout(channels);
const AVChannelLayout* found_ch_layout = nullptr;
for (const AVChannelLayout* ch_layout = codec->ch_layouts;
ch_layout && memcmp(ch_layout, &empty_ch_layout, sizeof(AVChannelLayout)) != 0;
ch_layout++)
{
media_log.notice("select_channel_layout: listing channel layout '%s' with %d channels", channel_layout_name(*ch_layout), ch_layout->nb_channels);
if (ch_layout->nb_channels == channels && memcmp(ch_layout, &preferred_ch_layout, sizeof(AVChannelLayout)) == 0)
{
found_ch_layout = ch_layout;
}
}
return found_ch_layout;
}
audio_decoder::audio_decoder()
{
}
audio_decoder::~audio_decoder()
{
stop();
}
void audio_decoder::set_context(music_selection_context context)
{
m_context = std::move(context);
}
void audio_decoder::set_swap_endianness(bool swapped)
{
m_swap_endianness = swapped;
}
void audio_decoder::clear()
{
track_fully_decoded = 0;
track_fully_consumed = 0;
has_error = false;
m_size = 0;
timestamps_ms.clear();
data.clear();
}
void audio_decoder::stop()
{
if (m_thread)
{
auto& thread = *m_thread;
thread = thread_state::aborting;
track_fully_consumed = 1;
track_fully_consumed.notify_one();
thread();
m_thread.reset();
}
clear();
}
void audio_decoder::decode()
{
stop();
media_log.notice("audio_decoder: %d entries in playlist. Start decoding...", m_context.playlist.size());
const auto decode_track = [this](const std::string& path)
{
media_log.notice("audio_decoder: decoding %s", path);
// Only print FFMPEG errors, fatals and panics
av_log_set_callback(av_log_callback);
av_log_set_level(AV_LOG_ERROR);
scoped_av av;
// Get format from audio file
av.format_context = avformat_alloc_context();
if (int err = avformat_open_input(&av.format_context, path.c_str(), nullptr, nullptr); err < 0)
{
media_log.error("audio_decoder: Could not open file '%s'. Error: %d='%s'", path, err, av_error_to_string(err));
has_error = true;
return;
}
if (int err = avformat_find_stream_info(av.format_context, nullptr); err < 0)
{
media_log.error("audio_decoder: Could not retrieve stream info from file '%s'. Error: %d='%s'", path, err, av_error_to_string(err));
has_error = true;
return;
}
// Find the first audio stream
AVStream* stream = nullptr;
unsigned int stream_index;
for (stream_index = 0; stream_index < av.format_context->nb_streams; stream_index++)
{
if (av.format_context->streams[stream_index]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
{
stream = av.format_context->streams[stream_index];
break;
}
}
if (!stream)
{
media_log.error("audio_decoder: Could not retrieve audio stream from file '%s'", path);
has_error = true;
return;
}
// Find decoder
av.audio.codec = avcodec_find_decoder(stream->codecpar->codec_id);
if (!av.audio.codec)
{
media_log.error("audio_decoder: Failed to find decoder for stream #%u in file '%s'", stream_index, path);
has_error = true;
return;
}
// Allocate context
av.audio.context = avcodec_alloc_context3(av.audio.codec);
if (!av.audio.context)
{
media_log.error("audio_decoder: Failed to allocate context for stream #%u in file '%s'", stream_index, path);
has_error = true;
return;
}
// Open decoder
if (int err = avcodec_open2(av.audio.context, av.audio.codec, nullptr); err < 0)
{
media_log.error("audio_decoder: Failed to open decoder for stream #%u in file '%s'. Error: %d='%s'", stream_index, path, err, av_error_to_string(err));
has_error = true;
return;
}
// Prepare resampler
av.swr = swr_alloc();
if (!av.swr)
{
media_log.error("audio_decoder: Failed to allocate resampler for stream #%u in file '%s'", stream_index, path);
has_error = true;
return;
}
const int dst_channels = 2;
const AVChannelLayout dst_channel_layout = AV_CHANNEL_LAYOUT_STEREO;
const AVSampleFormat dst_format = AV_SAMPLE_FMT_FLT;
int set_err = 0;
if ((set_err = av_opt_set_int(av.swr, "in_channel_count", stream->codecpar->ch_layout.nb_channels, 0)) ||
(set_err = av_opt_set_int(av.swr, "out_channel_count", dst_channels, 0)) ||
(set_err = av_opt_set_chlayout(av.swr, "in_channel_layout", &stream->codecpar->ch_layout, 0)) ||
(set_err = av_opt_set_chlayout(av.swr, "out_channel_layout", &dst_channel_layout, 0)) ||
(set_err = av_opt_set_int(av.swr, "in_sample_rate", stream->codecpar->sample_rate, 0)) ||
(set_err = av_opt_set_int(av.swr, "out_sample_rate", sample_rate, 0)) ||
(set_err = av_opt_set_sample_fmt(av.swr, "in_sample_fmt", static_cast<AVSampleFormat>(stream->codecpar->format), 0)) ||
(set_err = av_opt_set_sample_fmt(av.swr, "out_sample_fmt", dst_format, 0)))
{
media_log.error("audio_decoder: Failed to set resampler options: Error: %d='%s'", set_err, av_error_to_string(set_err));
has_error = true;
return;
}
if (int err = swr_init(av.swr); err < 0 || !swr_is_initialized(av.swr))
{
media_log.error("audio_decoder: Resampler has not been properly initialized: %d='%s'", err, av_error_to_string(err));
has_error = true;
return;
}
// Prepare to read data
av.audio.frame = av_frame_alloc();
if (!av.audio.frame)
{
media_log.error("audio_decoder: Error allocating the frame");
has_error = true;
return;
}
AVPacket* packet = av_packet_alloc();
if (!packet)
{
media_log.error("audio_decoder: Error allocating the packet");
has_error = true;
return;
}
std::unique_ptr<AVPacket, decltype(free_packet)> packet_(packet);
bool is_first_error = true;
// Iterate through frames
while (thread_ctrl::state() != thread_state::aborting && av_read_frame(av.format_context, packet) >= 0)
{
if (int err = avcodec_send_packet(av.audio.context, packet); err < 0)
{
if (is_first_error)
{
is_first_error = false;
if (err == averror_invalid_data)
{
// Some mp3s contain some invalid data at the beginning of the stream. They work fine if we just ignore them.
// So let's skip the first invalid data error. Maybe there is a better way, but let's just roll with it for now.
media_log.warning("audio_decoder: Ignoring first error: %d='%s'", err, av_error_to_string(err));
continue;
}
}
media_log.error("audio_decoder: Queuing error: %d='%s'", err, av_error_to_string(err));
has_error = true;
return;
}
while (thread_ctrl::state() != thread_state::aborting)
{
if (int err = avcodec_receive_frame(av.audio.context, av.audio.frame); err < 0)
{
if (err == AVERROR(EAGAIN) || err == averror_eof)
break;
media_log.error("audio_decoder: Decoding error: %d='%s'", err, av_error_to_string(err));
has_error = true;
return;
}
// Resample frames
u8* buffer = nullptr;
const int align = 1;
const int buffer_size = av_samples_alloc(&buffer, nullptr, dst_channels, av.audio.frame->nb_samples, dst_format, align);
if (buffer_size < 0)
{
media_log.error("audio_decoder: Error allocating buffer: %d='%s'", buffer_size, av_error_to_string(buffer_size));
has_error = true;
return;
}
const int frame_count = swr_convert(av.swr, &buffer, av.audio.frame->nb_samples, const_cast<const uint8_t**>(av.audio.frame->data), av.audio.frame->nb_samples);
if (frame_count < 0)
{
media_log.error("audio_decoder: Error converting frame: %d='%s'", frame_count, av_error_to_string(frame_count));
has_error = true;
if (buffer)
av_freep(&buffer);
return;
}
// Append resampled frames to data
{
std::scoped_lock lock(m_mtx);
data.resize(m_size + buffer_size);
// The format is float 32bit per channel.
copy_samples<f32>(buffer, &data[m_size], buffer_size / sizeof(f32), m_swap_endianness);
const s64 timestamp_ms = stream->time_base.den ? (1000 * av.audio.frame->best_effort_timestamp * stream->time_base.num) / stream->time_base.den : 0;
timestamps_ms.push_back({m_size, timestamp_ms});
m_size += buffer_size;
}
if (buffer)
av_freep(&buffer);
media_log.notice("audio_decoder: decoded frame_count=%d buffer_size=%d timestamp_us=%d", frame_count, buffer_size, av.audio.frame->best_effort_timestamp);
}
}
};
m_thread = std::make_unique<named_thread<std::function<void()>>>("Music Decode Thread", [this, decode_track]()
{
for (const std::string& track : m_context.playlist)
{
media_log.notice("audio_decoder: playlist entry: %s", track);
}
if (m_context.playlist.empty())
{
media_log.error("audio_decoder: Can not play empty playlist");
has_error = true;
return;
}
m_context.current_track = m_context.first_track;
if (m_context.context_option == CELL_SEARCH_CONTEXTOPTION_SHUFFLE && m_context.playlist.size() > 1)
{
// Shuffle once if necessary
media_log.notice("audio_decoder: shuffling initial playlist...");
auto engine = std::default_random_engine{};
std::shuffle(std::begin(m_context.playlist), std::end(m_context.playlist), engine);
}
while (thread_ctrl::state() != thread_state::aborting)
{
media_log.notice("audio_decoder: about to decode: %s (index=%d)", ::at32(m_context.playlist, m_context.current_track), m_context.current_track);
decode_track(::at32(m_context.playlist, m_context.current_track));
track_fully_decoded = 1;
if (has_error)
{
media_log.notice("audio_decoder: stopping with error...");
break;
}
// Let's only decode one track at a time. Wait for the consumer to finish reading the track.
media_log.notice("audio_decoder: waiting until track is consumed...");
thread_ctrl::wait_on(track_fully_consumed, 0);
track_fully_consumed = false;
}
media_log.notice("audio_decoder: finished playlist");
});
}
u32 audio_decoder::set_next_index(bool next)
{
return m_context.step_track(next);
}
video_encoder::video_encoder()
: utils::video_sink()
{
}
video_encoder::~video_encoder()
{
stop();
}
std::string video_encoder::path() const
{
return m_path;
}
s64 video_encoder::last_video_pts() const
{
return m_last_video_pts;
}
void video_encoder::set_path(const std::string& path)
{
m_path = path;
}
void video_encoder::set_framerate(u32 framerate)
{
m_framerate = framerate;
}
void video_encoder::set_video_bitrate(u32 bitrate)
{
m_video_bitrate_bps = bitrate;
}
void video_encoder::set_output_format(video_encoder::frame_format format)
{
m_out_format = std::move(format);
}
void video_encoder::set_video_codec(s32 codec_id)
{
m_video_codec_id = codec_id;
}
void video_encoder::set_max_b_frames(s32 max_b_frames)
{
m_max_b_frames = max_b_frames;
}
void video_encoder::set_gop_size(s32 gop_size)
{
m_gop_size = gop_size;
}
void video_encoder::set_sample_rate(u32 sample_rate)
{
m_sample_rate = sample_rate;
}
void video_encoder::set_audio_channels(u32 channels)
{
m_channels = channels;
}
void video_encoder::set_audio_bitrate(u32 bitrate)
{
m_audio_bitrate_bps = bitrate;
}
void video_encoder::set_audio_codec(s32 codec_id)
{
m_audio_codec_id = codec_id;
}
void video_encoder::pause(bool flush)
{
if (m_thread)
{
m_paused = true;
m_flush = flush;
if (flush)
{
// Let's assume this will finish in a timely manner
while (m_flush && m_running)
{
std::this_thread::sleep_for(1us);
}
}
}
}
void video_encoder::stop(bool flush)
{
media_log.notice("video_encoder: Stopping video encoder. flush=%d", flush);
if (m_thread)
{
m_flush = flush;
if (flush)
{
// Let's assume this will finish in a timely manner
while (m_flush && m_running)
{
std::this_thread::sleep_for(1ms);
}
}
auto& thread = *m_thread;
thread = thread_state::aborting;
thread();
m_thread.reset();
}
std::scoped_lock lock(m_video_mtx, m_audio_mtx);
m_frames_to_encode.clear();
m_samples_to_encode.clear();
has_error = false;
m_flush = false;
m_paused = false;
m_running = false;
}
void video_encoder::resume()
{
media_log.notice("video_encoder: Resuming video encoder");
m_flush = false;
m_paused = false;
}
void video_encoder::encode()
{
if (m_running)
{
// Resume
resume();
media_log.success("video_encoder: resuming recording of '%s'", m_path);
return;
}
m_last_audio_pts = 0;
m_last_video_pts = 0;
stop();
if (const std::string dir = fs::get_parent_dir(m_path); !fs::is_dir(dir))
{
media_log.error("video_encoder: Could not find directory: '%s' for file '%s'", dir, m_path);
has_error = true;
return;
}
media_log.success("video_encoder: Starting recording of '%s'", m_path);
m_thread = std::make_unique<named_thread<std::function<void()>>>("Video Encode Thread", [this, path = m_path]()
{
m_running = true;
// Only print FFMPEG errors, fatals and panics
av_log_set_callback(av_log_callback);
av_log_set_level(AV_LOG_ERROR);
// Reset variables at all costs
scoped_av av;
av.kill_callback = [this]()
{
m_flush = false;
m_running = false;
};
// Let's list the encoders first
std::vector<const AVCodec*> audio_codecs;
std::vector<const AVCodec*> video_codecs;
void* opaque = nullptr;
while (const AVCodec* codec = av_codec_iterate(&opaque))
{
if (codec->type == AVMediaType::AVMEDIA_TYPE_AUDIO)
{
media_log.notice("video_encoder: Found audio codec %d = %s", static_cast<int>(codec->id), codec->name);
audio_codecs.push_back(codec);
}
else if (codec->type == AVMediaType::AVMEDIA_TYPE_VIDEO)
{
media_log.notice("video_encoder: Found video codec %d = %s", static_cast<int>(codec->id), codec->name);
video_codecs.push_back(codec);
}
}
const AVPixelFormat out_pix_format = static_cast<AVPixelFormat>(m_out_format.av_pixel_format);
const auto find_format = [&](AVCodecID video_codec, AVCodecID audio_codec) -> const AVOutputFormat*
{
// Try to find a preferable output format
std::vector<const AVOutputFormat*> oformats;
void* opaque = nullptr;
for (const AVOutputFormat* oformat = av_muxer_iterate(&opaque); !!oformat; oformat = av_muxer_iterate(&opaque))
{
media_log.notice("video_encoder: Listing output format '%s' (video_codec=%d, audio_codec=%d)", oformat->name, static_cast<int>(oformat->video_codec), static_cast<int>(oformat->audio_codec));
if (avformat_query_codec(oformat, video_codec, FF_COMPLIANCE_NORMAL) == 1 &&
avformat_query_codec(oformat, audio_codec, FF_COMPLIANCE_NORMAL) == 1)
{
oformats.push_back(oformat);
}
}
for (const AVOutputFormat* oformat : oformats)
{
if (!oformat) continue;
media_log.notice("video_encoder: Found compatible output format '%s' (video_codec=%d, audio_codec=%d)", oformat->name, static_cast<int>(oformat->video_codec), static_cast<int>(oformat->audio_codec));
}
// Select best match
for (const AVOutputFormat* oformat : oformats)
{
if (oformat && oformat->video_codec == video_codec && oformat->audio_codec == audio_codec)
{
media_log.notice("video_encoder: Using matching output format '%s' (video_codec=%d, audio_codec=%d)", oformat->name, static_cast<int>(oformat->video_codec), static_cast<int>(oformat->audio_codec));
return oformat;
}
}
// Fallback to first found format
if (const AVOutputFormat* oformat = oformats.empty() ? nullptr : oformats.front())
{
media_log.notice("video_encoder: Using suboptimal output format '%s' (video_codec=%d, audio_codec=%d)", oformat->name, static_cast<int>(oformat->video_codec), static_cast<int>(oformat->audio_codec));
return oformat;
}
return nullptr;
};
const AVCodecID video_codec = static_cast<AVCodecID>(m_video_codec_id);
const AVCodecID audio_codec = static_cast<AVCodecID>(m_audio_codec_id);
const AVOutputFormat* out_format = find_format(video_codec, audio_codec);
if (out_format)
{
media_log.success("video_encoder: Found requested output format '%s'", out_format->name);
}
else
{
media_log.error("video_encoder: Could not find a format for the requested video_codec %d and audio_codec %d", m_video_codec_id, m_audio_codec_id);
// Fallback to some other codec
for (const AVCodec* video_codec : video_codecs)
{
for (const AVCodec* audio_codec : audio_codecs)
{
out_format = find_format(video_codec->id, audio_codec->id);
if (out_format)
{
media_log.success("video_encoder: Found fallback output format '%s'", out_format->name);
break;
}
}
if (out_format)
{
break;
}
}
}
if (!out_format)
{
media_log.error("video_encoder: Could not find any output format");
has_error = true;
return;
}
if (int err = avformat_alloc_output_context2(&av.format_context, out_format, nullptr, nullptr); err < 0)
{
media_log.error("video_encoder: avformat_alloc_output_context2 for '%s' failed. Error: %d='%s'", out_format->name, err, av_error_to_string(err));
has_error = true;
return;
}
if (!av.format_context)
{
media_log.error("video_encoder: avformat_alloc_output_context2 failed");
has_error = true;
return;
}
const auto create_context = [this, &av](bool is_video) -> bool
{
const std::string type = is_video ? "video" : "audio";
scoped_av::ctx& ctx = is_video ? av.video : av.audio;
if (is_video)
{
if (!(ctx.codec = avcodec_find_encoder(av.format_context->oformat->video_codec)))
{
media_log.error("video_encoder: avcodec_find_encoder for video failed. video_codec=%d", static_cast<int>(av.format_context->oformat->video_codec));
return false;
}
}
else
{
if (!(ctx.codec = avcodec_find_encoder(av.format_context->oformat->audio_codec)))
{
media_log.error("video_encoder: avcodec_find_encoder for audio failed. audio_codec=%d", static_cast<int>(av.format_context->oformat->audio_codec));
return false;
}
}
if (!(ctx.stream = avformat_new_stream(av.format_context, nullptr)))
{
media_log.error("video_encoder: avformat_new_stream for %s failed", type);
return false;
}
ctx.stream->id = is_video ? 0 : 1;
if (!(ctx.context = avcodec_alloc_context3(ctx.codec)))
{
media_log.error("video_encoder: avcodec_alloc_context3 for %s failed", type);
return false;
}
if (av.format_context->oformat->flags & AVFMT_GLOBALHEADER)
{
ctx.context->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
}
return true;
};
if (!create_context(true))
{
has_error = true;
return;
}
if (!create_context(false))
{
has_error = true;
return;
}
media_log.notice("video_encoder: using audio_codec = %d", static_cast<int>(av.format_context->oformat->audio_codec));
media_log.notice("video_encoder: using sample_rate = %d", m_sample_rate);
media_log.notice("video_encoder: using audio_bitrate = %d", m_audio_bitrate_bps);
media_log.notice("video_encoder: using audio channels = %d", m_channels);
media_log.notice("video_encoder: using video_codec = %d", static_cast<int>(av.format_context->oformat->video_codec));
media_log.notice("video_encoder: using video_bitrate = %d", m_video_bitrate_bps);
media_log.notice("video_encoder: using out width = %d", m_out_format.width);
media_log.notice("video_encoder: using out height = %d", m_out_format.height);
media_log.notice("video_encoder: using framerate = %d", m_framerate);
media_log.notice("video_encoder: using gop_size = %d", m_gop_size);
media_log.notice("video_encoder: using max_b_frames = %d", m_max_b_frames);
// select audio parameters supported by the encoder
if (av.audio.context)
{
if (const AVChannelLayout* ch_layout = select_channel_layout(av.audio.codec, m_channels))
{
media_log.notice("video_encoder: found channel layout '%s' with %d channels", channel_layout_name(*ch_layout), ch_layout->nb_channels);
if (int err = av_channel_layout_copy(&av.audio.context->ch_layout, ch_layout); err != 0)
{
media_log.error("video_encoder: av_channel_layout_copy failed. Error: %d='%s'", err, av_error_to_string(err));
has_error = true;
return;
}
}
else
{
media_log.notice("video_encoder: select_channel_layout returned nullptr, trying with own layout...");
const AVChannelLayout new_ch_layout = get_preferred_channel_layout(m_channels);
if (memcmp(&new_ch_layout, &empty_ch_layout, sizeof(AVChannelLayout)) == 0)
{
media_log.error("video_encoder: unsupported audio channel count: %d", m_channels);
has_error = true;
return;
}
if (int err = av_channel_layout_copy(&av.audio.context->ch_layout, &new_ch_layout); err != 0)
{
media_log.error("video_encoder: av_channel_layout_copy failed. Error: %d='%s'", err, av_error_to_string(err));
has_error = true;
return;
}
}
m_sample_rate = select_sample_rate(av.audio.codec);
av.audio.context->codec_id = av.format_context->oformat->audio_codec;
av.audio.context->codec_type = AVMEDIA_TYPE_AUDIO;
av.audio.context->bit_rate = m_audio_bitrate_bps;
av.audio.context->sample_rate = m_sample_rate;
av.audio.context->time_base = {.num = 1, .den = av.audio.context->sample_rate};
av.audio.context->sample_fmt = AV_SAMPLE_FMT_FLTP; // AV_SAMPLE_FMT_FLT is not supported in regular AC3
av.audio.stream->time_base = av.audio.context->time_base;
// check that the encoder supports the format
if (!check_sample_fmt(av.audio.codec, av.audio.context->sample_fmt))
{
media_log.error("video_encoder: Audio encoder does not support sample format %s", av_get_sample_fmt_name(av.audio.context->sample_fmt));
has_error = true;
return;
}
if (int err = avcodec_open2(av.audio.context, av.audio.codec, nullptr); err != 0)
{
media_log.error("video_encoder: avcodec_open2 for audio failed. Error: %d='%s'", err, av_error_to_string(err));
has_error = true;
return;
}
if (!(av.audio.packet = av_packet_alloc()))
{
media_log.error("video_encoder: av_packet_alloc for audio packet failed");
has_error = true;
return;
}
if (!(av.audio.frame = av_frame_alloc()))
{
media_log.error("video_encoder: av_frame_alloc for audio frame failed");
has_error = true;
return;
}
av.audio.frame->format = AV_SAMPLE_FMT_FLTP;
av.audio.frame->nb_samples = av.audio.context->frame_size;
if (int err = av_channel_layout_copy(&av.audio.frame->ch_layout, &av.audio.context->ch_layout); err < 0)
{
media_log.error("video_encoder: av_channel_layout_copy for audio frame failed. Error: %d='%s'", err, av_error_to_string(err));
has_error = true;
return;
}
if (int err = av_frame_get_buffer(av.audio.frame, 0); err < 0)
{
media_log.error("video_encoder: av_frame_get_buffer for audio frame failed. Error: %d='%s'", err, av_error_to_string(err));
has_error = true;
return;
}
if (int err = avcodec_parameters_from_context(av.audio.stream->codecpar, av.audio.context); err < 0)
{
media_log.error("video_encoder: avcodec_parameters_from_context for audio failed. Error: %d='%s'", err, av_error_to_string(err));
has_error = true;
return;
}
// Log channel layout
media_log.notice("video_encoder: av_channel_layout='%s'", channel_layout_name(av.audio.frame->ch_layout));
}
// select video parameters supported by the encoder
if (av.video.context)
{
av.video.context->codec_id = av.format_context->oformat->video_codec;
av.video.context->codec_type = AVMEDIA_TYPE_VIDEO;
av.video.context->bit_rate = m_video_bitrate_bps;
av.video.context->width = static_cast<int>(m_out_format.width);
av.video.context->height = static_cast<int>(m_out_format.height);
av.video.context->time_base = {.num = 1, .den = static_cast<int>(m_framerate)};
av.video.context->framerate = {.num = static_cast<int>(m_framerate), .den = 1};
av.video.context->pix_fmt = out_pix_format;
av.video.context->gop_size = m_gop_size;
av.video.context->max_b_frames = m_max_b_frames;
av.video.stream->time_base = av.video.context->time_base;
if (int err = avcodec_open2(av.video.context, av.video.codec, nullptr); err != 0)
{
media_log.error("video_encoder: avcodec_open2 for video failed. Error: %d='%s'", err, av_error_to_string(err));
has_error = true;
return;
}
if (!(av.video.packet = av_packet_alloc()))
{
media_log.error("video_encoder: av_packet_alloc for video packet failed");
has_error = true;
return;
}
if (!(av.video.frame = av_frame_alloc()))
{
media_log.error("video_encoder: av_frame_alloc for video frame failed");
has_error = true;
return;
}
av.video.frame->format = av.video.context->pix_fmt;
av.video.frame->width = av.video.context->width;
av.video.frame->height = av.video.context->height;
if (int err = av_frame_get_buffer(av.video.frame, 0); err < 0)
{
media_log.error("video_encoder: av_frame_get_buffer for video frame failed. Error: %d='%s'", err, av_error_to_string(err));
has_error = true;
return;
}
if (int err = avcodec_parameters_from_context(av.video.stream->codecpar, av.video.context); err < 0)
{
media_log.error("video_encoder: avcodec_parameters_from_context for video failed. Error: %d='%s'", err, av_error_to_string(err));
has_error = true;
return;
}
}
media_log.notice("video_encoder: av_dump_format");
for (u32 i = 0; i < av.format_context->nb_streams; i++)
{
av_dump_format(av.format_context, i, path.c_str(), 1);
}
// open the output file, if needed
if (!(av.format_context->flags & AVFMT_NOFILE))
{
if (int err = avio_open(&av.format_context->pb, path.c_str(), AVIO_FLAG_WRITE); err != 0)
{
media_log.error("video_encoder: avio_open failed. Error: %d='%s'", err, av_error_to_string(err));
has_error = true;
return;
}
}
if (int err = avformat_write_header(av.format_context, nullptr); err < 0)
{
media_log.error("video_encoder: avformat_write_header failed. Error: %d='%s'", err, av_error_to_string(err));
if (int err = avio_closep(&av.format_context->pb); err != 0)
{
media_log.error("video_encoder: avio_closep failed. Error: %d='%s'", err, av_error_to_string(err));
}
has_error = true;
return;
}
const auto flush = [&](scoped_av::ctx& ctx)
{
while ((thread_ctrl::state() != thread_state::aborting || m_flush) && !has_error && ctx.context)
{
if (int err = avcodec_receive_packet(ctx.context, ctx.packet); err < 0)
{
if (err == AVERROR(EAGAIN) || err == averror_eof)
break;
media_log.error("video_encoder: avcodec_receive_packet failed. Error: %d='%s'", err, av_error_to_string(err));
has_error = true;
return;
}
av_packet_rescale_ts(ctx.packet, ctx.context->time_base, ctx.stream->time_base);
ctx.packet->stream_index = ctx.stream->index;
if (int err = av_interleaved_write_frame(av.format_context, ctx.packet); err < 0)
{
media_log.error("video_encoder: av_write_frame failed. Error: %d='%s'", err, av_error_to_string(err));
has_error = true;
return;
}
}
};
u32 audio_sample_remainder = 0;
s64 last_audio_pts = -1;
s64 last_audio_frame_pts = 0;
s64 last_video_pts = -1;
// Allocate audio buffer for our audio frame
std::vector<u8> audio_frame;
u32 audio_frame_sample_count = 0;
const bool sample_fmt_is_planar = av.audio.context && av_sample_fmt_is_planar(av.audio.context->sample_fmt) != 0;
const int sample_fmt_bytes = av.audio.context ? av_get_bytes_per_sample(av.audio.context->sample_fmt) : 0;
ensure(sample_fmt_bytes == sizeof(f32)); // We only support FLT or FLTP for now
if (av.audio.frame)
{
audio_frame.resize(av.audio.frame->nb_samples * av.audio.frame->ch_layout.nb_channels * sizeof(f32));
last_audio_frame_pts -= av.audio.frame->nb_samples;
}
encoder_sample last_samples;
u32 leftover_sample_count = 0;
while ((thread_ctrl::state() != thread_state::aborting || m_flush) && !has_error)
{
// Fetch video frame
encoder_frame frame_data;
bool got_frame = false;
{
m_video_mtx.lock();
if (m_frames_to_encode.empty())
{
m_video_mtx.unlock();
}
else
{
frame_data = std::move(m_frames_to_encode.front());
m_frames_to_encode.pop_front();
m_video_mtx.unlock();
got_frame = true;
// Calculate presentation timestamp.
const s64 pts = get_pts(frame_data.timestamp_ms);
// We need to skip this frame if it has the same timestamp.
if (pts <= last_video_pts)
{
media_log.trace("video_encoder: skipping frame. last_pts=%d, pts=%d, timestamp_ms=%d", last_video_pts, pts, frame_data.timestamp_ms);
}
else if (av.video.context)
{
media_log.trace("video_encoder: adding new frame. timestamp_ms=%d", frame_data.timestamp_ms);
if (int err = av_frame_make_writable(av.video.frame); err < 0)
{
media_log.error("video_encoder: av_frame_make_writable failed. Error: %d='%s'", err, av_error_to_string(err));
has_error = true;
break;
}
u8* in_data[4]{};
int in_line[4]{};
const AVPixelFormat in_format = static_cast<AVPixelFormat>(frame_data.av_pixel_format);
if (int ret = av_image_fill_linesizes(in_line, in_format, frame_data.width); ret < 0)
{
fmt::throw_exception("video_encoder: av_image_fill_linesizes failed (ret=0x%x): %s", ret, utils::av_error_to_string(ret));
}
if (int ret = av_image_fill_pointers(in_data, in_format, frame_data.height, frame_data.data.data(), in_line); ret < 0)
{
fmt::throw_exception("video_encoder: av_image_fill_pointers failed (ret=0x%x): %s", ret, utils::av_error_to_string(ret));
}
// Update the context in case the frame format has changed
av.sws = sws_getCachedContext(av.sws, frame_data.width, frame_data.height, in_format,
av.video.context->width, av.video.context->height, out_pix_format, SWS_BICUBIC, nullptr, nullptr, nullptr);
if (!av.sws)
{
media_log.error("video_encoder: sws_getCachedContext failed");
has_error = true;
break;
}
if (int err = sws_scale(av.sws, in_data, in_line, 0, frame_data.height, av.video.frame->data, av.video.frame->linesize); err < 0)
{
media_log.error("video_encoder: sws_scale failed. Error: %d='%s'", err, av_error_to_string(err));
has_error = true;
break;
}
av.video.frame->pts = pts;
if (int err = avcodec_send_frame(av.video.context, av.video.frame); err < 0)
{
media_log.error("video_encoder: avcodec_send_frame for video failed. Error: %d='%s'", err, av_error_to_string(err));
has_error = true;
break;
}
flush(av.video);
last_video_pts = av.video.frame->pts;
m_last_video_pts = last_video_pts;
}
}
}
// Fetch audio sample
encoder_sample sample_data;
bool got_sample = false;
{
m_audio_mtx.lock();
if (m_samples_to_encode.empty())
{
m_audio_mtx.unlock();
}
else
{
sample_data = std::move(m_samples_to_encode.front());
m_samples_to_encode.pop_front();
m_audio_mtx.unlock();
got_sample = true;
if (sample_data.channels != av.audio.frame->ch_layout.nb_channels)
{
fmt::throw_exception("video_encoder: Audio sample channel count %d does not match frame channel count %d", sample_data.channels, av.audio.frame->ch_layout.nb_channels);
}
// Calculate presentation timestamp.
const s64 pts = get_audio_pts(sample_data.timestamp_us);
// We need to skip this frame if it has the same timestamp.
if (pts <= last_audio_pts)
{
media_log.trace("video_encoder: skipping sample. last_pts=%d, pts=%d, timestamp_us=%d", last_audio_pts, pts, sample_data.timestamp_us);
}
else if (av.audio.context)
{
media_log.trace("video_encoder: adding new sample. timestamp_us=%d", sample_data.timestamp_us);
static constexpr bool swap_endianness = false;
const auto send_frame = [&]()
{
if (audio_frame_sample_count < static_cast<u32>(av.audio.frame->nb_samples))
{
return;
}
audio_frame_sample_count = 0;
if (int err = av_frame_make_writable(av.audio.frame); err < 0)
{
media_log.error("video_encoder: av_frame_make_writable failed. Error: %d='%s'", err, av_error_to_string(err));
has_error = true;
return;
}
// NOTE: The ffmpeg channel layout should match our downmix channel layout
if (sample_fmt_is_planar)
{
const int channels = av.audio.frame->ch_layout.nb_channels;
const int samples = av.audio.frame->nb_samples;
for (int ch = 0; ch < channels; ch++)
{
f32* dst = reinterpret_cast<f32*>(av.audio.frame->data[ch]);
for (int sample = 0; sample < samples; sample++)
{
dst[sample] = *reinterpret_cast<f32*>(&audio_frame[(sample * channels + ch) * sizeof(f32)]);
}
}
}
else
{
std::memcpy(av.audio.frame->data[0], audio_frame.data(), audio_frame.size());
}
av.audio.frame->pts = last_audio_frame_pts + av.audio.frame->nb_samples;
if (int err = avcodec_send_frame(av.audio.context, av.audio.frame); err < 0)
{
media_log.error("video_encoder: avcodec_send_frame failed: %d='%s'", err, av_error_to_string(err));
has_error = true;
return;
}
flush(av.audio);
last_audio_frame_pts = av.audio.frame->pts;
};
const auto add_encoder_sample = [&](bool add_new_sample, u32 silence_to_add = 0)
{
const auto update_last_pts = [&](u32 samples_to_add)
{
const u32 sample_count = audio_sample_remainder + samples_to_add;
const u32 pts_to_add = sample_count / m_samples_per_block;
audio_sample_remainder = sample_count % m_samples_per_block;
last_audio_pts += pts_to_add;
};
// Copy as many old samples to our audio frame as possible
if (leftover_sample_count > 0)
{
const u32 samples_to_add = std::min(leftover_sample_count, av.audio.frame->nb_samples - audio_frame_sample_count);
if (samples_to_add > 0)
{
const u8* src = &last_samples.data[(last_samples.sample_count - leftover_sample_count) * last_samples.channels * sizeof(f32)];
u8* dst = &audio_frame[audio_frame_sample_count * last_samples.channels * sizeof(f32)];
copy_samples<f32>(src, dst, samples_to_add * last_samples.channels, swap_endianness);
audio_frame_sample_count += samples_to_add;
leftover_sample_count -= samples_to_add;
update_last_pts(samples_to_add);
}
if (samples_to_add < leftover_sample_count)
{
media_log.error("video_encoder: audio frame buffer is already filled entirely by last sample package...");
}
}
else if (silence_to_add > 0)
{
const u32 samples_to_add = std::min<s32>(silence_to_add, av.audio.frame->nb_samples - audio_frame_sample_count);
if (samples_to_add > 0)
{
u8* dst = &audio_frame[audio_frame_sample_count * av.audio.frame->ch_layout.nb_channels * sizeof(f32)];
std::memset(dst, 0, samples_to_add * sample_data.channels * sizeof(f32));
audio_frame_sample_count += samples_to_add;
update_last_pts(samples_to_add);
}
}
else if (add_new_sample)
{
// Copy as many new samples to our audio frame as possible
const u32 samples_to_add = std::min<s32>(sample_data.sample_count, av.audio.frame->nb_samples - audio_frame_sample_count);
if (samples_to_add > 0)
{
const u8* src = sample_data.data.data();
u8* dst = &audio_frame[audio_frame_sample_count * sample_data.channels * sizeof(f32)];
copy_samples<f32>(src, dst, samples_to_add * sample_data.channels, swap_endianness);
audio_frame_sample_count += samples_to_add;
update_last_pts(samples_to_add);
}
if (samples_to_add < sample_data.sample_count)
{
// Save this sample package for the next loop if it wasn't fully used.
leftover_sample_count = sample_data.sample_count - samples_to_add;
}
else
{
// Mark this sample package as fully used.
leftover_sample_count = 0;
}
last_samples = std::move(sample_data);
}
send_frame();
};
for (u32 sample = 0; !has_error;)
{
if (leftover_sample_count > 0)
{
// Add leftover samples
add_encoder_sample(false);
}
else if (pts > (last_audio_pts + 1))
{
// Add silence to fill the gap
const u32 silence_to_add = static_cast<u32>(pts - (last_audio_pts + 1));
add_encoder_sample(false, silence_to_add);
}
else if (sample == 0)
{
// Add new samples
add_encoder_sample(true);
sample++;
}
else
{
break;
}
}
m_last_audio_pts = last_audio_pts;
}
}
}
if (!got_frame && !got_sample)
{
if (m_flush)
{
m_flush = false;
if (!m_paused)
{
// We only stop the thread after a flush if we are not paused
break;
}
}
// We only actually pause after we process all frames
const u64 sleeptime_us = m_paused ? 10000 : 1;
thread_ctrl::wait_for(sleeptime_us);
continue;
}
}
if (av.video.context)
{
if (int err = avcodec_send_frame(av.video.context, nullptr); err != 0)
{
media_log.error("video_encoder: final avcodec_send_frame failed. Error: %d='%s'", err, av_error_to_string(err));
}
}
if (av.audio.context)
{
if (int err = avcodec_send_frame(av.audio.context, nullptr); err != 0)
{
media_log.error("video_encoder: final avcodec_send_frame failed. Error: %d='%s'", err, av_error_to_string(err));
}
}
flush(av.video);
flush(av.audio);
if (int err = av_write_trailer(av.format_context); err != 0)
{
media_log.error("video_encoder: av_write_trailer failed. Error: %d='%s'", err, av_error_to_string(err));
}
if (int err = avio_closep(&av.format_context->pb); err != 0)
{
media_log.error("video_encoder: avio_closep failed. Error: %d='%s'", err, av_error_to_string(err));
}
});
}
}
| 50,141
|
C++
|
.cpp
| 1,395
| 30.856631
| 204
| 0.647945
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,047
|
logs.cpp
|
RPCS3_rpcs3/rpcs3/util/logs.cpp
|
#include "util/logs.hpp"
#include "Utilities/File.h"
#include "Utilities/mutex.h"
#include "Utilities/Thread.h"
#include "Utilities/StrFmt.h"
#include <cstring>
#include <cstdarg>
#include <string>
#include <unordered_map>
#include <thread>
#include <chrono>
#include <cstring>
#include <cerrno>
#include <regex>
using namespace std::literals::chrono_literals;
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <Windows.h>
#else
#include <sys/mman.h>
#include <sys/stat.h>
#endif
#include <zlib.h>
static std::string default_string()
{
if (thread_ctrl::is_main())
{
return {};
}
return fmt::format("TID: %u", thread_ctrl::get_tid());
}
// Thread-specific log prefix provider
thread_local std::string(*g_tls_log_prefix)() = &default_string;
// Another thread-specific callback
thread_local void(*g_tls_log_control)(const char* fmt, u64 progress) = [](const char*, u64){};
template<>
void fmt_class_string<logs::level>::format(std::string& out, u64 arg)
{
format_enum(out, arg, [](auto lev)
{
switch (lev)
{
case logs::level::always: return "Nothing";
case logs::level::fatal: return "Fatal";
case logs::level::error: return "Error";
case logs::level::todo: return "TODO";
case logs::level::success: return "Success";
case logs::level::warning: return "Warning";
case logs::level::notice: return "Notice";
case logs::level::trace: return "Trace";
}
return unknown;
});
}
namespace logs
{
static_assert(std::is_empty_v<message> && sizeof(message) == 1);
static_assert(sizeof(channel) == alignof(channel));
static_assert(uchar(level::always) == 0);
static_assert(uchar(level::fatal) == 1);
static_assert(uchar(level::trace) == 7);
static_assert((offsetof(channel, fatal) & 7) == 1);
static_assert((offsetof(channel, trace) & 7) == 7);
// Memory-mapped buffer size
constexpr u64 s_log_size = 32 * 1024 * 1024;
static_assert(s_log_size * s_log_size > s_log_size && (s_log_size & (s_log_size - 1)) == 0); // Assert on an overflowing value
class file_writer
{
std::thread m_writer{};
fs::file m_fout{};
fs::file m_fout2{};
u64 m_max_size{};
std::unique_ptr<uchar[]> m_fptr{};
z_stream m_zs{};
shared_mutex m_m{};
atomic_t<u64, 64> m_buf{0}; // MSB (39 bits): push begin, LSB (25 bis): push size
atomic_t<u64, 64> m_out{0}; // Amount of bytes written to file
uchar m_zout[65536]{};
// Write buffered logs immediately
bool flush(u64 bufv);
public:
file_writer(const std::string& name, u64 max_size);
virtual ~file_writer();
// Append raw data
void log(const char* text, usz size);
// Ensure written to disk
void sync();
// Close file handle after flushing to disk
void close_prematurely();
};
struct file_listener final : file_writer, public listener
{
file_listener(const std::string& path, u64 max_size);
~file_listener() override = default;
void log(u64 stamp, const message& msg, const std::string& prefix, const std::string& text) override;
void sync() override
{
file_writer::sync();
}
void close_prematurely() override
{
file_writer::close_prematurely();
}
};
struct root_listener final : public listener
{
root_listener() = default;
~root_listener() override = default;
// Encode level, current thread name, channel name and write log message
void log(u64, const message&, const std::string&, const std::string&) override
{
// Do nothing
}
// Channel registry
std::unordered_multimap<std::string, channel*> channels{};
// Messages for delayed listener initialization
std::vector<stored_message> messages{};
};
static root_listener* get_logger()
{
// Use magic static
static root_listener logger{};
return &logger;
}
static u64 get_stamp()
{
static struct time_initializer
{
#ifdef _WIN32
LARGE_INTEGER freq;
LARGE_INTEGER start;
time_initializer()
{
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&start);
}
#else
steady_clock::time_point start = steady_clock::now();
#endif
u64 get() const
{
#ifdef _WIN32
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
const LONGLONG diff = now.QuadPart - start.QuadPart;
return diff / freq.QuadPart * 1'000'000 + diff % freq.QuadPart * 1'000'000 / freq.QuadPart;
#else
return (steady_clock::now() - start).count() / 1000;
#endif
}
} timebase{};
return timebase.get();
}
// Channel registry mutex
static shared_mutex g_mutex;
// Must be set to true in main()
static atomic_t<bool> g_init{false};
void reset()
{
std::lock_guard lock(g_mutex);
for (auto&& pair : get_logger()->channels)
{
pair.second->enabled.release(level::notice);
}
}
void silence()
{
std::lock_guard lock(g_mutex);
for (auto&& pair : get_logger()->channels)
{
pair.second->enabled.release(level::always);
}
}
void set_level(const std::string& ch_name, level value)
{
std::lock_guard lock(g_mutex);
if (ch_name.find_first_of(".+*?^$()[]{}|\\") != umax)
{
const std::regex ex(ch_name);
// RegEx pattern
for (auto& channel_pair : get_logger()->channels)
{
std::smatch sm;
if (std::regex_match(channel_pair.first, sm, ex))
{
channel_pair.second->enabled.release(value);
}
}
return;
}
auto found = get_logger()->channels.equal_range(ch_name);
while (found.first != found.second)
{
found.first->second->enabled.release(value);
found.first++;
}
}
level get_level(const std::string& ch_name)
{
std::lock_guard lock(g_mutex);
auto found = get_logger()->channels.equal_range(ch_name);
if (found.first != found.second)
{
return found.first->second->enabled.observe();
}
else
{
return level::always;
}
}
void set_channel_levels(const std::map<std::string, logs::level, std::less<>>& map)
{
for (auto&& pair : map)
{
logs::set_level(pair.first, pair.second);
}
}
std::vector<std::string> get_channels()
{
std::vector<std::string> result;
std::lock_guard lock(g_mutex);
for (auto&& p : get_logger()->channels)
{
// Copy names removing duplicates
if (result.empty() || result.back() != p.first)
{
result.push_back(p.first);
}
}
return result;
}
// Must be called in main() to stop accumulating messages in g_messages
void set_init(std::initializer_list<stored_message> init_msg)
{
if (!g_init)
{
std::lock_guard lock(g_mutex);
// Prepend main messages
for (const auto& msg : init_msg)
{
get_logger()->broadcast(msg);
}
// Send initial messages
for (const auto& msg : get_logger()->messages)
{
get_logger()->broadcast(msg);
}
// Clear it
get_logger()->messages.clear();
g_init = true;
}
}
}
logs::listener::~listener()
{
// Shut up all channels on exit
if (auto logger = get_logger())
{
if (logger == this)
{
return;
}
for (auto&& pair : logger->channels)
{
pair.second->enabled.release(level::always);
}
}
}
void logs::listener::add(logs::listener* _new)
{
// Get first (main) listener
listener* lis = get_logger();
std::lock_guard lock(g_mutex);
// Install new listener at the end of linked list
listener* null = nullptr;
while (lis->m_next || !lis->m_next.compare_exchange(null, _new))
{
lis = lis->m_next;
null = nullptr;
}
}
void logs::listener::broadcast(const logs::stored_message& msg) const
{
for (auto lis = m_next.load(); lis; lis = lis->m_next)
{
lis->log(msg.stamp, msg.m, msg.prefix, msg.text);
}
}
void logs::listener::sync()
{
}
void logs::listener::close_prematurely()
{
}
void logs::listener::sync_all()
{
for (listener* lis = get_logger(); lis; lis = lis->m_next)
{
lis->sync();
}
}
void logs::listener::close_all_prematurely()
{
for (listener* lis = get_logger(); lis; lis = lis->m_next)
{
lis->close_prematurely();
}
}
logs::registerer::registerer(channel& _ch)
{
std::lock_guard lock(g_mutex);
get_logger()->channels.emplace(_ch.name, &_ch);
}
void logs::message::broadcast(const char* fmt, const fmt_type_info* sup, ...) const
{
// Get timestamp
const u64 stamp = get_stamp();
// Notify start operation
g_tls_log_control(fmt, 0);
// Get text, extract va_args
/*constinit thread_local*/ std::string text;
/*constinit thread_local*/ std::vector<u64> args;
static constexpr fmt_type_info empty_sup{};
usz args_count = 0;
for (auto v = sup; v && v->fmt_string; v++)
args_count++;
text.reserve(50000);
args.resize(args_count);
va_list c_args;
va_start(c_args, sup);
for (u64& arg : args)
arg = va_arg(c_args, u64);
va_end(c_args);
fmt::raw_append(text, fmt, sup ? sup : &empty_sup, args.data());
std::string prefix = g_tls_log_prefix();
// Get first (main) listener
listener* lis = get_logger();
if (!g_init)
{
std::lock_guard lock(g_mutex);
if (!g_init)
{
while (lis)
{
lis->log(stamp, *this, prefix, text);
lis = lis->m_next;
}
// Store message additionally
get_logger()->messages.emplace_back(stored_message{*this, stamp, std::move(prefix), text});
}
}
// Send message to all listeners
while (lis)
{
lis->log(stamp, *this, prefix, text);
lis = lis->m_next;
}
// Notify end operation
g_tls_log_control(fmt, -1);
}
logs::file_writer::file_writer(const std::string& name, u64 max_size)
: m_max_size(max_size)
{
if (name.empty() || !max_size)
{
return;
}
// Initialize ringbuffer
m_fptr = std::make_unique<uchar[]>(s_log_size);
// Actual log file (allowed to fail)
if (!m_fout.open(name, fs::rewrite))
{
fprintf(stderr, "Log file open failed: %s (error %d)\n", name.c_str(), errno);
}
// Compressed log, make it inaccessible (foolproof)
if (m_fout2.open(name + ".gz", fs::rewrite + fs::unread))
{
#ifndef _MSC_VER
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#endif
if (deflateInit2(&m_zs, 9, Z_DEFLATED, 16 + 15, 9, Z_DEFAULT_STRATEGY) != Z_OK)
#ifndef _MSC_VER
#pragma GCC diagnostic pop
#endif
{
m_fout2.close();
}
}
if (!m_fout2)
{
fprintf(stderr, "Log file open failed: %s.gz (error %d)\n", name.c_str(), errno);
}
#ifdef _WIN32
// Autodelete compressed log file
FILE_DISPOSITION_INFO disp{};
disp.DeleteFileW = true;
SetFileInformationByHandle(m_fout2.get_handle(), FileDispositionInfo, &disp, sizeof(disp));
#endif
m_writer = std::thread([this]()
{
thread_base::set_name("Log Writer");
thread_ctrl::scoped_priority low_prio(-1);
while (true)
{
const u64 bufv = m_buf;
if (bufv % s_log_size)
{
// Wait if threads are writing logs
std::this_thread::yield();
continue;
}
if (!flush(bufv))
{
if (m_out == umax)
{
break;
}
std::this_thread::sleep_for(10ms);
}
}
});
}
logs::file_writer::~file_writer()
{
if (!m_fptr)
{
return;
}
// Stop writer thread
file_writer::sync();
m_out = -1;
m_writer.join();
if (m_fout2)
{
m_zs.avail_in = 0;
m_zs.next_in = nullptr;
do
{
m_zs.avail_out = sizeof(m_zout);
m_zs.next_out = m_zout;
if (deflate(&m_zs, Z_FINISH) == Z_STREAM_ERROR || m_fout2.write(m_zout, sizeof(m_zout) - m_zs.avail_out) != sizeof(m_zout) - m_zs.avail_out)
{
break;
}
}
while (m_zs.avail_out == 0);
deflateEnd(&m_zs);
}
#ifdef _WIN32
// Cancel compressed log file auto-deletion
FILE_DISPOSITION_INFO disp;
disp.DeleteFileW = false;
SetFileInformationByHandle(m_fout2.get_handle(), FileDispositionInfo, &disp, sizeof(disp));
#else
// Restore compressed log file permissions
::fchmod(m_fout2.get_handle(), S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
#endif
}
bool logs::file_writer::flush(u64 bufv)
{
std::lock_guard lock(m_m);
const u64 read_pos = m_out;
const u64 out_index = read_pos % s_log_size;
const u64 pushed = (bufv / s_log_size) % s_log_size;
const u64 end = std::min<u64>(out_index <= pushed ? read_pos - out_index + pushed : ((read_pos + s_log_size) & ~(s_log_size - 1)), m_max_size);
if (end > read_pos)
{
// Avoid writing too big fragments
const u64 size = std::min<u64>(end - read_pos, sizeof(m_zout) / 2);
// Write uncompressed
if (m_fout && m_fout.write(m_fptr.get() + out_index, size) != size)
{
m_fout.close();
}
// Write compressed
if (m_fout2)
{
m_zs.avail_in = static_cast<uInt>(size);
m_zs.next_in = m_fptr.get() + out_index;
do
{
m_zs.avail_out = sizeof(m_zout);
m_zs.next_out = m_zout;
if (deflate(&m_zs, Z_NO_FLUSH) == Z_STREAM_ERROR || m_fout2.write(m_zout, sizeof(m_zout) - m_zs.avail_out) != sizeof(m_zout) - m_zs.avail_out)
{
deflateEnd(&m_zs);
m_fout2.close();
break;
}
}
while (m_zs.avail_out == 0);
}
m_out += size;
return true;
}
return false;
}
void logs::file_writer::log(const char* text, usz size)
{
if (!m_fptr)
{
return;
}
// TODO: write bigger fragment directly in blocking manner
while (size && size < s_log_size)
{
const auto [bufv, pos] = m_buf.fetch_op([&](u64& v) -> uchar*
{
const u64 out = m_out % s_log_size;
const u64 v1 = (v / s_log_size) % s_log_size;
const u64 v2 = v % s_log_size;
if (v1 + v2 + size >= (out <= v1 ? out + s_log_size : out)) [[unlikely]]
{
return nullptr;
}
v += size;
return m_fptr.get() + (v1 + v2) % s_log_size;
});
if (!pos) [[unlikely]]
{
if (m_out >= m_max_size || (!m_fout && !m_fout2))
{
// Logging is inactive
return;
}
if ((bufv % s_log_size) + size >= s_log_size || bufv % s_log_size)
{
// Concurrency limit reached
std::this_thread::yield();
}
else if (!m_m.is_free())
{
// Wait for another flush call to complete
m_m.lock_unlock();
}
else
{
// Queue is full, need to write out
flush(bufv);
}
continue;
}
if (pos - m_fptr.get() + size > s_log_size)
{
const auto frag = s_log_size - (pos - m_fptr.get());
std::memcpy(pos, text, frag);
std::memcpy(m_fptr.get(), text + frag, size - frag);
}
else
{
std::memcpy(pos, text, size);
}
m_buf += (size * s_log_size) - size;
break;
}
}
void logs::file_writer::sync()
{
if (!m_fptr)
{
return;
}
// Wait for the writer thread
while ((m_out % s_log_size) * s_log_size != m_buf % (s_log_size * s_log_size))
{
if (m_out >= m_max_size)
{
break;
}
std::this_thread::yield();
}
// Ensure written to disk
if (m_fout)
{
m_fout.sync();
}
if (m_fout2)
{
m_fout2.sync();
}
}
void logs::file_writer::close_prematurely()
{
if (!m_fptr)
{
return;
}
// Ensure written to disk
sync();
std::lock_guard lock(m_m);
if (m_fout2)
{
m_zs.avail_in = 0;
m_zs.next_in = nullptr;
do
{
m_zs.avail_out = sizeof(m_zout);
m_zs.next_out = m_zout;
if (deflate(&m_zs, Z_FINISH) == Z_STREAM_ERROR || m_fout2.write(m_zout, sizeof(m_zout) - m_zs.avail_out) != sizeof(m_zout) - m_zs.avail_out)
{
break;
}
}
while (m_zs.avail_out == 0);
deflateEnd(&m_zs);
#ifdef _WIN32
// Cancel compressed log file auto-deletion
FILE_DISPOSITION_INFO disp;
disp.DeleteFileW = false;
SetFileInformationByHandle(m_fout2.get_handle(), FileDispositionInfo, &disp, sizeof(disp));
#else
// Restore compressed log file permissions
::fchmod(m_fout2.get_handle(), S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
#endif
m_fout2.close();
}
if (m_fout)
{
m_fout.close();
}
}
logs::file_listener::file_listener(const std::string& path, u64 max_size)
: file_writer(path, max_size)
, listener()
{
// Write UTF-8 BOM
file_writer::log("\xEF\xBB\xBF", 3);
}
void logs::file_listener::log(u64 stamp, const logs::message& msg, const std::string& prefix, const std::string& _text)
{
/*constinit thread_local*/ std::string text;
text.reserve(50000);
// Used character: U+00B7 (Middle Dot)
switch (msg)
{
case level::always: text = reinterpret_cast<const char*>(u8"·A "); break;
case level::fatal: text = reinterpret_cast<const char*>(u8"·F "); break;
case level::error: text = reinterpret_cast<const char*>(u8"·E "); break;
case level::todo: text = reinterpret_cast<const char*>(u8"·U "); break;
case level::success: text = reinterpret_cast<const char*>(u8"·S "); break;
case level::warning: text = reinterpret_cast<const char*>(u8"·W "); break;
case level::notice: text = reinterpret_cast<const char*>(u8"·! "); break;
case level::trace: text = reinterpret_cast<const char*>(u8"·T "); break;
}
// Print µs timestamp
const u64 hours = stamp / 3600'000'000;
const u64 mins = (stamp % 3600'000'000) / 60'000'000;
const u64 secs = (stamp % 60'000'000) / 1'000'000;
const u64 frac = (stamp % 1'000'000);
fmt::append(text, "%u:%02u:%02u.%06u ", hours, mins, secs, frac);
if (stamp == 0)
{
// Workaround for first special messages to keep backward compatibility
text.clear();
}
if (!prefix.empty())
{
text += "{";
text += prefix;
text += "} ";
}
if (stamp && msg->name && '\0' != *msg->name)
{
text += msg->name;
text += msg == level::todo ? " TODO: " : ": ";
}
else if (msg == level::todo)
{
text += "TODO: ";
}
text += _text;
text += '\n';
file_writer::log(text.data(), text.size());
}
std::unique_ptr<logs::listener> logs::make_file_listener(const std::string& path, u64 max_size)
{
std::unique_ptr<logs::listener> result = std::make_unique<logs::file_listener>(path, max_size);
// Register file listener
result->add(result.get());
return result;
}
| 17,322
|
C++
|
.cpp
| 684
| 22.488304
| 146
| 0.655419
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,048
|
gl_gs_frame.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/gl_gs_frame.cpp
|
#include "gl_gs_frame.h"
#include "Emu/System.h"
#include "Emu/system_config.h"
#include <QOpenGLContext>
#include <QOffscreenSurface>
gl_gs_frame::gl_gs_frame(QScreen* screen, const QRect& geometry, const QIcon& appIcon, std::shared_ptr<gui_settings> gui_settings, bool force_fullscreen)
: gs_frame(screen, geometry, appIcon, std::move(gui_settings), force_fullscreen)
{
setSurfaceType(QSurface::OpenGLSurface);
m_format.setRenderableType(QSurfaceFormat::OpenGL);
m_format.setMajorVersion(4);
m_format.setMinorVersion(3);
m_format.setProfile(QSurfaceFormat::CoreProfile);
m_format.setAlphaBufferSize(0);
m_format.setDepthBufferSize(0);
m_format.setSwapBehavior(QSurfaceFormat::SwapBehavior::DoubleBuffer);
m_format.setSwapInterval(0);
if (g_cfg.video.debug_output)
{
m_format.setOption(QSurfaceFormat::FormatOption::DebugContext);
}
setFormat(m_format);
create();
show();
}
draw_context_t gl_gs_frame::make_context()
{
auto context = new GLContext();
context->handle = new QOpenGLContext();
if (m_primary_context)
{
QOffscreenSurface* surface = nullptr;
// Workaround for the Qt warning: "Attempting to create QWindow-based QOffscreenSurface outside the gui thread. Expect failures."
Emu.BlockingCallFromMainThread([&]()
{
surface = new QOffscreenSurface();
surface->setFormat(m_format);
surface->create();
});
// Share resources with the first created context
context->handle->setShareContext(m_primary_context->handle);
context->surface = surface;
context->owner = true;
}
else
{
// This is the first created context, all others will share resources with this one
m_primary_context = context;
context->surface = this;
context->owner = false;
}
context->handle->setFormat(m_format);
if (!context->handle->create())
{
fmt::throw_exception("Failed to create OpenGL context");
}
return context;
}
void gl_gs_frame::set_current(draw_context_t ctx)
{
if (!ctx)
{
fmt::throw_exception("Null context handle passed to set_current");
}
const auto context = static_cast<GLContext*>(ctx);
if (!context->handle->makeCurrent(context->surface))
{
if (!context->owner)
{
create();
}
else if (!context->handle->isValid())
{
if (!context->handle->create())
{
fmt::throw_exception("Failed to create OpenGL context");
}
}
if (!context->handle->makeCurrent(context->surface))
{
fmt::throw_exception("Could not bind OpenGL context");
}
}
}
void gl_gs_frame::delete_context(draw_context_t ctx)
{
const auto gl_ctx = static_cast<GLContext*>(ctx);
gl_ctx->handle->doneCurrent();
#ifdef _MSC_VER
//AMD driver crashes when executing wglDeleteContext
//Catch with SEH
__try
{
delete gl_ctx->handle;
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
{
rsx_log.fatal("Your graphics driver just crashed whilst cleaning up. All consumed VRAM should have been released, but you may want to restart the emulator just in case");
}
#else
delete gl_ctx->handle;
#endif
if (gl_ctx->owner)
{
delete gl_ctx->surface;
}
delete gl_ctx;
}
void gl_gs_frame::flip(draw_context_t context, bool skip_frame)
{
gs_frame::flip(context);
//Do not swap buffers if frame skip is active
if (skip_frame) return;
const auto gl_ctx = static_cast<GLContext*>(context);
if (auto window = dynamic_cast<QWindow*>(gl_ctx->surface); window && window->isExposed())
{
gl_ctx->handle->swapBuffers(gl_ctx->surface);
}
}
| 3,491
|
C++
|
.cpp
| 119
| 26.92437
| 172
| 0.740741
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,049
|
pad_motion_settings_dialog.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/pad_motion_settings_dialog.cpp
|
#include "stdafx.h"
#include "pad_motion_settings_dialog.h"
#include <QComboBox>
#include <thread>
LOG_CHANNEL(cfg_log, "CFG");
pad_motion_settings_dialog::pad_motion_settings_dialog(QDialog* parent, std::shared_ptr<PadHandlerBase> handler, cfg_player* cfg)
: QDialog(parent)
, ui(new Ui::pad_motion_settings_dialog)
, m_handler(handler)
, m_cfg(cfg)
{
ui->setupUi(this);
setModal(true);
ensure(m_handler);
ensure(m_cfg);
cfg_pad& pad = m_cfg->config;
m_preview_sliders = {{ ui->slider_x, ui->slider_y, ui->slider_z, ui->slider_g }};
m_preview_labels = {{ ui->label_x, ui->label_y, ui->label_z, ui->label_g }};
m_axis_names = {{ ui->combo_x, ui->combo_y, ui->combo_z, ui->combo_g }};
m_mirrors = {{ ui->mirror_x, ui->mirror_y, ui->mirror_z, ui->mirror_g }};
m_shifts = {{ ui->shift_x, ui->shift_y, ui->shift_z, ui->shift_g }};
m_config_entries = {{ &pad.motion_sensor_x, &pad.motion_sensor_y, &pad.motion_sensor_z, &pad.motion_sensor_g }};
for (usz i = 0; i < m_preview_sliders.size(); i++)
{
m_preview_sliders[i]->setRange(0, 1023);
m_preview_labels[i]->setText("0");
}
#if HAVE_LIBEVDEV
const bool has_device_list = m_handler->m_type == pad_handler::evdev;
#else
const bool has_device_list = false;
#endif
if (has_device_list)
{
// Combobox: Motion Devices
m_device_name = m_cfg->buddy_device.to_string();
ui->cb_choose_device->addItem(tr("Disabled"), QVariant::fromValue(pad_device_info{}));
const std::vector<pad_list_entry> device_list = m_handler->list_devices();
for (const pad_list_entry& device : device_list)
{
if (device.is_buddy_only)
{
const QString device_name = QString::fromStdString(device.name);
const QVariant user_data = QVariant::fromValue(pad_device_info{ device.name, device_name, true });
ui->cb_choose_device->addItem(device_name, user_data);
}
}
for (int i = 0; i < ui->cb_choose_device->count(); i++)
{
const QVariant user_data = ui->cb_choose_device->itemData(i);
ensure(user_data.canConvert<pad_device_info>());
if (const pad_device_info info = user_data.value<pad_device_info>(); info.name == m_device_name)
{
ui->cb_choose_device->setCurrentIndex(i);
break;
}
}
connect(ui->cb_choose_device, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &pad_motion_settings_dialog::change_device);
// Combobox: Configure Axis
m_motion_axis_list = m_handler->get_motion_axis_list();
for (const auto& [code, axis] : m_motion_axis_list)
{
const QString q_axis = QString::fromStdString(axis);
for (usz i = 0; i < m_axis_names.size(); i++)
{
m_axis_names[i]->addItem(q_axis, code);
if (m_config_entries[i]->axis.to_string() == axis)
{
m_axis_names[i]->setCurrentIndex(m_axis_names[i]->findData(code));
}
}
}
for (usz i = 0; i < m_axis_names.size(); i++)
{
const cfg_sensor* config = m_config_entries[i];
m_mirrors[i]->setChecked(config->mirrored.get());
m_shifts[i]->setRange(config->shift.min, config->shift.max);
m_shifts[i]->setValue(config->shift.get());
connect(m_mirrors[i], &QCheckBox::checkStateChanged, this, [this, i](Qt::CheckState state)
{
std::lock_guard lock(m_config_mutex);
m_config_entries[i]->mirrored.set(state != Qt::Unchecked);
});
connect(m_shifts[i], QOverload<int>::of(&QSpinBox::valueChanged), this, [this, i](int value)
{
std::lock_guard lock(m_config_mutex);
m_config_entries[i]->shift.set(value);
});
connect(m_axis_names[i], QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this, i](int index)
{
std::lock_guard lock(m_config_mutex);
if (!m_config_entries[i]->axis.from_string(m_axis_names[i]->itemText(index).toStdString()))
{
cfg_log.error("Failed to convert motion axis string: %s", m_axis_names[i]->itemData(index).toString());
}
});
}
}
else
{
m_device_name = m_cfg->device.to_string();
ui->gb_device->setVisible(false);
ui->cancelButton->setVisible(false);
for (usz i = 0; i < m_axis_names.size(); i++)
{
m_axis_names[i]->setVisible(false);
m_mirrors[i]->setVisible(false);
m_shifts[i]->setVisible(false);
}
}
// Use timer to display button input
connect(&m_timer_input, &QTimer::timeout, this, [this]()
{
motion_callback_data data;
{
std::lock_guard lock(m_input_mutex);
data = m_motion_callback_data;
m_motion_callback_data.has_new_data = false;
}
if (data.has_new_data)
{
// Starting with 1 because the first entry is the Disabled entry.
for (int i = 1; i < ui->cb_choose_device->count(); i++)
{
const QVariant user_data = ui->cb_choose_device->itemData(i);
ensure(user_data.canConvert<pad_device_info>());
if (const pad_device_info info = user_data.value<pad_device_info>(); info.name == data.pad_name)
{
switch_buddy_pad_info(i, info, data.success);
break;
}
}
for (usz i = 0; i < data.preview_values.size(); i++)
{
m_preview_sliders[i]->setValue(data.preview_values[i]);
m_preview_labels[i]->setText(QString::number(data.preview_values[i]));
}
}
});
m_timer_input.start(10);
// Use thread to get button input
m_input_thread = std::make_unique<named_thread<std::function<void()>>>("UI Pad Motion Thread", [this]()
{
while (thread_ctrl::state() != thread_state::aborting)
{
thread_ctrl::wait_for(1000);
if (m_input_thread_state != input_thread_state::active)
{
if (m_input_thread_state == input_thread_state::pausing)
{
m_input_thread_state = input_thread_state::paused;
}
continue;
}
std::array<AnalogSensor, 4> sensors{};
{
std::lock_guard lock(m_config_mutex);
for (usz i = 0; i < sensors.size(); i++)
{
AnalogSensor& sensor = sensors[i];
const cfg_sensor* config = m_config_entries[i];
const std::string cfgname = config->axis.to_string();
for (const auto& [code, name] : m_motion_axis_list)
{
if (cfgname == name)
{
sensor.m_keyCode = code;
sensor.m_mirrored = config->mirrored.get();
sensor.m_shift = config->shift.get();
break;
}
}
}
}
m_handler->get_motion_sensors(m_device_name,
[this](std::string pad_name, motion_preview_values preview_values)
{
std::lock_guard lock(m_input_mutex);
m_motion_callback_data.pad_name = std::move(pad_name);
m_motion_callback_data.preview_values = std::move(preview_values);
m_motion_callback_data.has_new_data = true;
m_motion_callback_data.success = true;
},
[this](std::string pad_name, motion_preview_values preview_values)
{
std::lock_guard lock(m_input_mutex);
m_motion_callback_data.pad_name = std::move(pad_name);
m_motion_callback_data.preview_values = std::move(preview_values);
m_motion_callback_data.has_new_data = true;
m_motion_callback_data.success = false;
},
m_motion_callback_data.preview_values, sensors);
}
});
start_input_thread();
}
pad_motion_settings_dialog::~pad_motion_settings_dialog()
{
if (m_input_thread)
{
m_input_thread_state = input_thread_state::pausing;
auto& thread = *m_input_thread;
thread = thread_state::aborting;
thread();
}
}
void pad_motion_settings_dialog::change_device(int index)
{
if (index < 0)
return;
const QVariant user_data = ui->cb_choose_device->itemData(index);
ensure(user_data.canConvert<pad_device_info>());
const pad_device_info info = user_data.value<pad_device_info>();
if (!m_cfg->buddy_device.from_string(info.name))
{
cfg_log.error("Failed to convert motion device string: %s", info.name);
}
m_device_name = m_cfg->buddy_device.to_string();
}
void pad_motion_settings_dialog::switch_buddy_pad_info(int index, pad_device_info info, bool is_connected)
{
if (index >= 0 && info.is_connected != is_connected)
{
info.is_connected = is_connected;
ui->cb_choose_device->setItemData(index, QVariant::fromValue(info));
ui->cb_choose_device->setItemText(index, is_connected ? QString::fromStdString(info.name) : (QString::fromStdString(info.name) + Disconnected_suffix));
}
}
void pad_motion_settings_dialog::start_input_thread()
{
m_input_thread_state = input_thread_state::active;
}
void pad_motion_settings_dialog::pause_input_thread()
{
if (m_input_thread)
{
m_input_thread_state = input_thread_state::pausing;
while (m_input_thread_state != input_thread_state::paused)
{
std::this_thread::sleep_for(1ms);
}
}
}
| 8,430
|
C++
|
.cpp
| 243
| 31.037037
| 153
| 0.671334
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,050
|
cheat_manager.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/cheat_manager.cpp
|
#include <QHBoxLayout>
#include <QGroupBox>
#include <QLabel>
#include <QMessageBox>
#include <QMenu>
#include <QClipboard>
#include <QGuiApplication>
#include "cheat_manager.h"
#include "Emu/System.h"
#include "Emu/Memory/vm.h"
#include "Emu/CPU/CPUThread.h"
#include "Emu/IdManager.h"
#include "Emu/Cell/PPUAnalyser.h"
#include "Emu/Cell/PPUFunction.h"
#include "util/yaml.hpp"
#include "util/asm.hpp"
#include "util/to_endian.hpp"
#include "Utilities/File.h"
#include "Utilities/StrUtil.h"
#include "Utilities/bin_patch.h" // get_patches_path()
LOG_CHANNEL(log_cheat, "Cheat");
cheat_manager_dialog* cheat_manager_dialog::inst = nullptr;
template <>
void fmt_class_string<cheat_type>::format(std::string& out, u64 arg)
{
format_enum(out, arg, [](cheat_type value)
{
switch (value)
{
case cheat_type::unsigned_8_cheat: return "Unsigned 8 bits";
case cheat_type::unsigned_16_cheat: return "Unsigned 16 bits";
case cheat_type::unsigned_32_cheat: return "Unsigned 32 bits";
case cheat_type::unsigned_64_cheat: return "Unsigned 64 bits";
case cheat_type::signed_8_cheat: return "Signed 8 bits";
case cheat_type::signed_16_cheat: return "Signed 16 bits";
case cheat_type::signed_32_cheat: return "Signed 32 bits";
case cheat_type::signed_64_cheat: return "Signed 64 bits";
case cheat_type::max: break;
}
return unknown;
});
}
YAML::Emitter& operator<<(YAML::Emitter& out, const cheat_info& rhs)
{
std::string type_formatted;
fmt::append(type_formatted, "%s", rhs.type);
out << YAML::BeginSeq << rhs.description << type_formatted << rhs.red_script << YAML::EndSeq;
return out;
}
cheat_engine::cheat_engine()
{
const std::string patches_path = patch_engine::get_patches_path();
if (!fs::create_path(patches_path))
{
log_cheat.fatal("Failed to create path: %s (%s)", patches_path, fs::g_tls_error);
return;
}
const std::string path = patches_path + m_cheats_filename;
if (fs::file cheat_file{path, fs::read + fs::create})
{
auto [yml_cheats, error] = yaml_load(cheat_file.to_string());
if (!error.empty())
{
log_cheat.error("Error parsing %s: %s", path, error);
return;
}
for (const auto& yml_cheat : yml_cheats)
{
const std::string& game_name = yml_cheat.first.Scalar();
for (const auto& yml_offset : yml_cheat.second)
{
const u32 offset = get_yaml_node_value<u32>(yml_offset.first, error);
if (!error.empty())
{
log_cheat.error("Error parsing %s: node key %s is not a u32 offset", path, yml_offset.first.Scalar());
return;
}
cheat_info cheat = get_yaml_node_value<cheat_info>(yml_offset.second, error);
if (!error.empty())
{
log_cheat.error("Error parsing %s: node %s is not a cheat_info node", path, yml_offset.first.Scalar());
return;
}
cheat.game = game_name;
cheat.offset = offset;
cheats[game_name][offset] = std::move(cheat);
}
}
}
else
{
log_cheat.error("Error loading %s", path);
}
}
void cheat_engine::save() const
{
const std::string patches_path = patch_engine::get_patches_path();
if (!fs::create_path(patches_path))
{
log_cheat.fatal("Failed to create path: %s (%s)", patches_path, fs::g_tls_error);
return;
}
const std::string path = patches_path + m_cheats_filename;
fs::file cheat_file(path, fs::rewrite);
if (!cheat_file)
return;
YAML::Emitter out;
out << YAML::BeginMap;
for (const auto& game_entry : cheats)
{
out << game_entry.first;
out << YAML::BeginMap;
for (const auto& offset_entry : game_entry.second)
{
out << YAML::Hex << offset_entry.first;
out << offset_entry.second;
}
out << YAML::EndMap;
}
out << YAML::EndMap;
cheat_file.write(out.c_str(), out.size());
}
void cheat_engine::import_cheats_from_str(const std::string& str_cheats)
{
auto cheats_vec = fmt::split(str_cheats, {"^^^"});
for (auto& cheat_line : cheats_vec)
{
cheat_info new_cheat;
if (new_cheat.from_str(cheat_line))
cheats[new_cheat.game][new_cheat.offset] = new_cheat;
}
}
std::string cheat_engine::export_cheats_to_str() const
{
std::string cheats_str;
for (const auto& game : cheats)
{
for (const auto& offset : ::at32(cheats, game.first))
{
cheats_str += offset.second.to_str();
cheats_str += "^^^";
}
}
return cheats_str;
}
bool cheat_engine::exist(const std::string& game, const u32 offset) const
{
return cheats.contains(game) && ::at32(cheats, game).contains(offset);
}
void cheat_engine::add(const std::string& game, const std::string& description, const cheat_type type, const u32 offset, const std::string& red_script)
{
cheats[game][offset] = cheat_info{game, description, type, offset, red_script};
}
cheat_info* cheat_engine::get(const std::string& game, const u32 offset)
{
if (!exist(game, offset))
return nullptr;
return &cheats[game][offset];
}
bool cheat_engine::erase(const std::string& game, const u32 offset)
{
if (!exist(game, offset))
return false;
cheats[game].erase(offset);
return true;
}
bool cheat_engine::resolve_script(u32& final_offset, const u32 offset, const std::string& red_script)
{
enum operand
{
operand_equal,
operand_add,
operand_sub
};
auto do_operation = [](const operand op, u32& param1, const u32 param2) -> u32
{
switch (op)
{
case operand_equal: return param1 = param2;
case operand_add: return param1 += param2;
case operand_sub: return param1 -= param2;
}
return ensure(0);
};
operand cur_op = operand_equal;
u32 index = 0;
while (index < red_script.size())
{
if (std::isdigit(static_cast<u8>(red_script[index])))
{
std::string num_string;
for (; index < red_script.size(); index++)
{
if (!std::isdigit(static_cast<u8>(red_script[index])))
break;
num_string += red_script[index];
}
const u32 num_value = std::stoul(num_string);
do_operation(cur_op, final_offset, num_value);
}
else
{
switch (red_script[index])
{
case '$':
{
do_operation(cur_op, final_offset, offset);
index++;
break;
}
case '[':
{
// find corresponding ]
s32 found_close = 1;
std::string sub_script;
for (index++; index < red_script.size(); index++)
{
if (found_close == 0)
break;
if (red_script[index] == ']')
found_close--;
else if (red_script[index] == '[')
found_close++;
if (found_close != 0)
sub_script += red_script[index];
}
if (found_close)
return false;
// Resolves content of []
u32 res_addr = 0;
if (!resolve_script(res_addr, offset, sub_script))
return false;
// Tries to get value at resolved address
bool success;
const u32 res_value = get_value<u32>(res_addr, success);
if (!success)
return false;
do_operation(cur_op, final_offset, res_value);
break;
}
case '+':
cur_op = operand_add;
index++;
break;
case '-':
cur_op = operand_sub;
index++;
break;
case ' ': index++; break;
default: log_cheat.fatal("invalid character in redirection script"); return false;
}
}
}
return true;
}
template <typename T>
std::vector<u32> cheat_engine::search(const T value, const std::vector<u32>& to_filter)
{
std::vector<u32> results;
to_be_t<T> value_swapped = value;
if (Emu.IsStopped())
return {};
cpu_thread::suspend_all(nullptr, {}, [&]
{
if (!to_filter.empty())
{
for (const auto& off : to_filter)
{
if (vm::check_addr<sizeof(T)>(off))
{
if (*vm::get_super_ptr<T>(off) == value_swapped)
results.push_back(off);
}
}
}
else
{
// Looks through mapped memory
for (u32 page_start = 0x10000; page_start < 0xF0000000; page_start += 4096)
{
if (vm::check_addr(page_start))
{
// Assumes the values are aligned
for (u32 index = 0; index < 4096; index += sizeof(T))
{
if (*vm::get_super_ptr<T>(page_start + index) == value_swapped)
results.push_back(page_start + index);
}
}
}
}
});
return results;
}
template <typename T>
T cheat_engine::get_value(const u32 offset, bool& success)
{
if (Emu.IsStopped())
{
success = false;
return 0;
}
return cpu_thread::suspend_all(nullptr, {}, [&]() -> T
{
if (!vm::check_addr<sizeof(T)>(offset))
{
success = false;
return 0;
}
success = true;
return *vm::get_super_ptr<T>(offset);
});
}
template <typename T>
bool cheat_engine::set_value(const u32 offset, const T value)
{
if (Emu.IsStopped())
return false;
if (!vm::check_addr<sizeof(T)>(offset))
{
return false;
}
return cpu_thread::suspend_all(nullptr, {}, [&]
{
if (!vm::check_addr<sizeof(T)>(offset))
{
return false;
}
*vm::get_super_ptr<T>(offset) = value;
const bool exec_code_at_start = vm::check_addr(offset, vm::page_executable);
const bool exec_code_at_end = [&]()
{
if constexpr (sizeof(T) == 1)
{
return exec_code_at_start;
}
else
{
return vm::check_addr(offset + sizeof(T) - 1, vm::page_executable);
}
}();
if (exec_code_at_end || exec_code_at_start)
{
extern void ppu_register_function_at(u32, u32, ppu_intrp_func_t);
u32 addr = offset, size = sizeof(T);
if (exec_code_at_end && exec_code_at_start)
{
size = utils::align<u32>(addr + size, 4) - (addr & -4);
addr &= -4;
}
else if (exec_code_at_end)
{
size -= utils::align<u32>(size - 4096 + (addr & 4095), 4);
addr = utils::align<u32>(addr, 4096);
}
else if (exec_code_at_start)
{
size = utils::align<u32>(4096 - (addr & 4095), 4);
addr &= -4;
}
// Reinitialize executable code
ppu_register_function_at(addr, size, nullptr);
}
return true;
});
}
bool cheat_engine::is_addr_safe(const u32 offset)
{
if (Emu.IsStopped())
return false;
const auto ppum = g_fxo->try_get<main_ppu_module>();
if (!ppum)
{
log_cheat.fatal("Failed to get ppu_module");
return false;
}
std::vector<std::pair<u32, u32>> segs;
for (const auto& seg : ppum->segs)
{
if ((seg.flags & 3))
{
segs.emplace_back(seg.addr, seg.size);
}
}
if (segs.empty())
{
log_cheat.fatal("Couldn't find a +rw-x section");
return false;
}
for (const auto& seg : segs)
{
if (offset >= seg.first && offset < (seg.first + seg.second))
return true;
}
return false;
}
u32 cheat_engine::reverse_lookup(const u32 addr, const u32 max_offset, const u32 max_depth, const u32 cur_depth)
{
for (u32 index = 0; index <= max_offset; index += 4)
{
std::vector<u32> ptrs = search(addr - index, {});
log_cheat.fatal("Found %d pointer(s) for addr 0x%x [offset: %d cur_depth:%d]", ptrs.size(), addr, index, cur_depth);
for (const auto& ptr : ptrs)
{
if (is_addr_safe(ptr))
return ptr;
}
// If depth has not been reached dig deeper
if (!ptrs.empty() && cur_depth < max_depth)
{
for (const auto& ptr : ptrs)
{
const u32 result = reverse_lookup(ptr, max_offset, max_depth, cur_depth + 1);
if (result)
return result;
}
}
}
return 0;
}
enum cheat_table_columns : int
{
title = 0,
description,
type,
offset,
script
};
cheat_manager_dialog::cheat_manager_dialog(QWidget* parent)
: QDialog(parent)
{
setWindowTitle(tr("Cheat Manager"));
setObjectName("cheat_manager");
setMinimumSize(QSize(800, 400));
QVBoxLayout* main_layout = new QVBoxLayout();
tbl_cheats = new QTableWidget(this);
tbl_cheats->setSelectionMode(QAbstractItemView::SelectionMode::ExtendedSelection);
tbl_cheats->setSelectionBehavior(QAbstractItemView::SelectRows);
tbl_cheats->setContextMenuPolicy(Qt::CustomContextMenu);
tbl_cheats->setColumnCount(5);
tbl_cheats->setHorizontalHeaderLabels(QStringList() << tr("Game") << tr("Description") << tr("Type") << tr("Offset") << tr("Script"));
main_layout->addWidget(tbl_cheats);
QHBoxLayout* btn_layout = new QHBoxLayout();
QLabel* lbl_value_final = new QLabel(tr("Current Value:"));
edt_value_final = new QLineEdit();
btn_apply = new QPushButton(tr("Apply"), this);
btn_apply->setEnabled(false);
btn_layout->addWidget(lbl_value_final);
btn_layout->addWidget(edt_value_final);
btn_layout->addWidget(btn_apply);
main_layout->addLayout(btn_layout);
QGroupBox* grp_add_cheat = new QGroupBox(tr("Cheat Search"));
QVBoxLayout* grp_add_cheat_layout = new QVBoxLayout();
QHBoxLayout* grp_add_cheat_sub_layout = new QHBoxLayout();
QPushButton* btn_new_search = new QPushButton(tr("New Search"));
btn_new_search->setEnabled(false);
btn_filter_results = new QPushButton(tr("Filter Results"));
btn_filter_results->setEnabled(false);
edt_cheat_search_value = new QLineEdit();
cbx_cheat_search_type = new QComboBox();
for (u64 i = 0; i < cheat_type_max; i++)
{
const QString item_text = get_localized_cheat_type(static_cast<cheat_type>(i));
cbx_cheat_search_type->addItem(item_text);
}
cbx_cheat_search_type->setCurrentIndex(static_cast<u8>(cheat_type::signed_32_cheat));
grp_add_cheat_sub_layout->addWidget(btn_new_search);
grp_add_cheat_sub_layout->addWidget(btn_filter_results);
grp_add_cheat_sub_layout->addWidget(edt_cheat_search_value);
grp_add_cheat_sub_layout->addWidget(cbx_cheat_search_type);
grp_add_cheat_layout->addLayout(grp_add_cheat_sub_layout);
lst_search = new QListWidget(this);
lst_search->setSelectionMode(QAbstractItemView::SelectionMode::SingleSelection);
lst_search->setSelectionBehavior(QAbstractItemView::SelectRows);
lst_search->setContextMenuPolicy(Qt::CustomContextMenu);
grp_add_cheat_layout->addWidget(lst_search);
grp_add_cheat->setLayout(grp_add_cheat_layout);
main_layout->addWidget(grp_add_cheat);
setLayout(main_layout);
// Edit/Manage UI
connect(tbl_cheats, &QTableWidget::itemClicked, [this](QTableWidgetItem* item)
{
if (!item)
return;
const int row = item->row();
if (row == -1)
return;
cheat_info* cheat = g_cheat.get(tbl_cheats->item(row, cheat_table_columns::title)->text().toStdString(), tbl_cheats->item(row, cheat_table_columns::offset)->data(Qt::UserRole).toUInt());
if (!cheat)
{
log_cheat.fatal("Failed to retrieve cheat selected from internal cheat_engine");
return;
}
u32 final_offset;
if (!cheat->red_script.empty())
{
final_offset = 0;
if (!cheat_engine::resolve_script(final_offset, cheat->offset, cheat->red_script))
{
btn_apply->setEnabled(false);
edt_value_final->setText(tr("Failed to resolve redirection script"));
return;
}
}
else
{
final_offset = cheat->offset;
}
if (Emu.IsStopped())
{
btn_apply->setEnabled(false);
edt_value_final->setText(tr("This Application is not running"));
return;
}
bool success;
u64 result_value;
switch (cheat->type)
{
case cheat_type::unsigned_8_cheat: result_value = cheat_engine::get_value<u8>(final_offset, success); break;
case cheat_type::unsigned_16_cheat: result_value = cheat_engine::get_value<u16>(final_offset, success); break;
case cheat_type::unsigned_32_cheat: result_value = cheat_engine::get_value<u32>(final_offset, success); break;
case cheat_type::unsigned_64_cheat: result_value = cheat_engine::get_value<u64>(final_offset, success); break;
case cheat_type::signed_8_cheat: result_value = cheat_engine::get_value<s8>(final_offset, success); break;
case cheat_type::signed_16_cheat: result_value = cheat_engine::get_value<s16>(final_offset, success); break;
case cheat_type::signed_32_cheat: result_value = cheat_engine::get_value<s32>(final_offset, success); break;
case cheat_type::signed_64_cheat: result_value = cheat_engine::get_value<s64>(final_offset, success); break;
default: log_cheat.fatal("Unsupported cheat type"); return;
}
if (success)
{
if (cheat->type >= cheat_type::signed_8_cheat && cheat->type <= cheat_type::signed_64_cheat)
edt_value_final->setText(tr("%1").arg(static_cast<s64>(result_value)));
else
edt_value_final->setText(tr("%1").arg(result_value));
}
else
{
edt_value_final->setText(tr("Failed to get the value from memory"));
}
btn_apply->setEnabled(success);
});
connect(tbl_cheats, &QTableWidget::cellChanged, [this](int row, int column)
{
QTableWidgetItem* item = tbl_cheats->item(row, column);
if (!item)
{
return;
}
if (column != cheat_table_columns::description && column != cheat_table_columns::script)
{
log_cheat.fatal("A column other than description and script was edited");
return;
}
cheat_info* cheat = g_cheat.get(tbl_cheats->item(row, cheat_table_columns::title)->text().toStdString(), tbl_cheats->item(row, cheat_table_columns::offset)->data(Qt::UserRole).toUInt());
if (!cheat)
{
log_cheat.fatal("Failed to retrieve cheat edited from internal cheat_engine");
return;
}
switch (column)
{
case cheat_table_columns::description: cheat->description = item->text().toStdString(); break;
case cheat_table_columns::script: cheat->red_script = item->text().toStdString(); break;
default: break;
}
g_cheat.save();
});
connect(tbl_cheats, &QTableWidget::customContextMenuRequested, [this](const QPoint& loc)
{
const QPoint globalPos = tbl_cheats->mapToGlobal(loc);
QMenu* menu = new QMenu();
QAction* delete_cheats = new QAction(tr("Delete"), menu);
QAction* import_cheats = new QAction(tr("Import Cheats"));
QAction* export_cheats = new QAction(tr("Export Cheats"));
QAction* reverse_cheat = new QAction(tr("Reverse-Lookup Cheat"));
connect(delete_cheats, &QAction::triggered, [this]()
{
const auto selected = tbl_cheats->selectedItems();
std::set<int> rows;
for (const auto& sel : selected)
{
const int row = sel->row();
if (rows.count(row))
continue;
g_cheat.erase(tbl_cheats->item(row, cheat_table_columns::title)->text().toStdString(), tbl_cheats->item(row, cheat_table_columns::offset)->data(Qt::UserRole).toUInt());
rows.insert(row);
}
update_cheat_list();
});
connect(import_cheats, &QAction::triggered, [this]()
{
QClipboard* clipboard = QGuiApplication::clipboard();
g_cheat.import_cheats_from_str(clipboard->text().toStdString());
update_cheat_list();
});
connect(export_cheats, &QAction::triggered, [this]()
{
const auto selected = tbl_cheats->selectedItems();
std::set<int> rows;
std::string export_string;
for (const auto& sel : selected)
{
const int row = sel->row();
if (rows.count(row))
continue;
cheat_info* cheat = g_cheat.get(tbl_cheats->item(row, cheat_table_columns::title)->text().toStdString(), tbl_cheats->item(row, cheat_table_columns::offset)->data(Qt::UserRole).toUInt());
if (cheat)
export_string += cheat->to_str() + "^^^";
rows.insert(row);
}
QClipboard* clipboard = QGuiApplication::clipboard();
clipboard->setText(QString::fromStdString(export_string));
});
connect(reverse_cheat, &QAction::triggered, [this]()
{
QTableWidgetItem* item = tbl_cheats->item(tbl_cheats->currentRow(), cheat_table_columns::offset);
if (item)
{
const u32 offset = item->data(Qt::UserRole).toUInt();
const u32 result = cheat_engine::reverse_lookup(offset, 32, 12);
log_cheat.fatal("Result is 0x%x", result);
}
});
menu->addAction(delete_cheats);
menu->addSeparator();
// menu->addAction(reverse_cheat);
// menu->addSeparator();
menu->addAction(import_cheats);
menu->addAction(export_cheats);
menu->exec(globalPos);
});
connect(btn_apply, &QPushButton::clicked, [this](bool /*checked*/)
{
const int row = tbl_cheats->currentRow();
cheat_info* cheat = g_cheat.get(tbl_cheats->item(row, cheat_table_columns::title)->text().toStdString(), tbl_cheats->item(row, cheat_table_columns::offset)->data(Qt::UserRole).toUInt());
if (!cheat)
{
log_cheat.fatal("Failed to retrieve cheat selected from internal cheat_engine");
return;
}
std::pair<bool, bool> results;
u32 final_offset;
if (!cheat->red_script.empty())
{
final_offset = 0;
if (!g_cheat.resolve_script(final_offset, cheat->offset, cheat->red_script))
{
btn_apply->setEnabled(false);
edt_value_final->setText(tr("Failed to resolve redirection script"));
}
}
else
{
final_offset = cheat->offset;
}
// TODO: better way to do this?
switch (static_cast<cheat_type>(cbx_cheat_search_type->currentIndex()))
{
case cheat_type::unsigned_8_cheat: results = convert_and_set<u8>(final_offset); break;
case cheat_type::unsigned_16_cheat: results = convert_and_set<u16>(final_offset); break;
case cheat_type::unsigned_32_cheat: results = convert_and_set<u32>(final_offset); break;
case cheat_type::unsigned_64_cheat: results = convert_and_set<u64>(final_offset); break;
case cheat_type::signed_8_cheat: results = convert_and_set<s8>(final_offset); break;
case cheat_type::signed_16_cheat: results = convert_and_set<s16>(final_offset); break;
case cheat_type::signed_32_cheat: results = convert_and_set<s32>(final_offset); break;
case cheat_type::signed_64_cheat: results = convert_and_set<s64>(final_offset); break;
default: log_cheat.fatal("Unsupported cheat type"); return;
}
if (!results.first)
{
QMessageBox::warning(this, tr("Error converting value"), tr("Couldn't convert the value you typed to the integer type of that cheat"), QMessageBox::Ok);
return;
}
if (!results.second)
{
QMessageBox::warning(this, tr("Error applying value"), tr("Couldn't patch memory"), QMessageBox::Ok);
return;
}
});
// Search UI
connect(btn_new_search, &QPushButton::clicked, [this](bool /*checked*/)
{
offsets_found.clear();
do_the_search();
});
connect(edt_cheat_search_value, &QLineEdit::textChanged, this, [btn_new_search, this](const QString& text)
{
if (btn_new_search)
{
btn_new_search->setEnabled(!text.isEmpty());
}
if (btn_filter_results)
{
btn_filter_results->setEnabled(!text.isEmpty() && !offsets_found.empty());
}
});
connect(btn_filter_results, &QPushButton::clicked, [this](bool /*checked*/) { do_the_search(); });
connect(lst_search, &QListWidget::customContextMenuRequested, [this](const QPoint& loc)
{
const QPoint globalPos = lst_search->mapToGlobal(loc);
const int current_row = lst_search->currentRow();
QListWidgetItem* item = lst_search->item(current_row);
// Skip if the item was a placeholder
if (!item || item->data(Qt::UserRole).toBool())
return;
QMenu* menu = new QMenu();
QAction* add_to_cheat_list = new QAction(tr("Add to cheat list"), menu);
const u32 offset = offsets_found[current_row];
const cheat_type type = static_cast<cheat_type>(cbx_cheat_search_type->currentIndex());
connect(add_to_cheat_list, &QAction::triggered, [name = Emu.GetTitle(), offset, type, this]()
{
if (g_cheat.exist(name, offset))
{
if (QMessageBox::question(this, tr("Cheat already exists"), tr("Do you want to overwrite the existing cheat?"), QMessageBox::Ok | QMessageBox::Cancel) != QMessageBox::Ok)
return;
}
std::string comment;
if (!cheat_engine::is_addr_safe(offset))
comment = "Unsafe";
g_cheat.add(name, comment, type, offset, "");
update_cheat_list();
});
menu->addAction(add_to_cheat_list);
menu->exec(globalPos);
});
update_cheat_list();
}
cheat_manager_dialog::~cheat_manager_dialog()
{
inst = nullptr;
}
cheat_manager_dialog* cheat_manager_dialog::get_dlg(QWidget* parent)
{
if (inst == nullptr)
inst = new cheat_manager_dialog(parent);
return inst;
}
template <typename T>
T cheat_manager_dialog::convert_from_QString(const QString& str, bool& success)
{
T result;
if constexpr (std::is_same_v<T, u8>)
{
const u16 result_16 = str.toUShort(&success);
if (result_16 > 0xFF)
success = false;
result = static_cast<T>(result_16);
}
if constexpr (std::is_same_v<T, u16>)
result = str.toUShort(&success);
if constexpr (std::is_same_v<T, u32>)
result = str.toUInt(&success);
if constexpr (std::is_same_v<T, u64>)
result = str.toULongLong(&success);
if constexpr (std::is_same_v<T, s8>)
{
const s16 result_16 = str.toShort(&success);
if (result_16 < -128 || result_16 > 127)
success = false;
result = static_cast<T>(result_16);
}
if constexpr (std::is_same_v<T, s16>)
result = str.toShort(&success);
if constexpr (std::is_same_v<T, s32>)
result = str.toInt(&success);
if constexpr (std::is_same_v<T, s64>)
result = str.toLongLong(&success);
return result;
}
template <typename T>
bool cheat_manager_dialog::convert_and_search()
{
bool res_conv;
const QString to_search = edt_cheat_search_value->text();
T value = convert_from_QString<T>(to_search, res_conv);
if (!res_conv)
return false;
offsets_found = cheat_engine::search(value, offsets_found);
return true;
}
template <typename T>
std::pair<bool, bool> cheat_manager_dialog::convert_and_set(u32 offset)
{
bool res_conv;
const QString to_set = edt_value_final->text();
T value = convert_from_QString<T>(to_set, res_conv);
if (!res_conv)
return {false, false};
return {true, cheat_engine::set_value(offset, value)};
}
void cheat_manager_dialog::do_the_search()
{
bool res_conv = false;
// TODO: better way to do this?
switch (static_cast<cheat_type>(cbx_cheat_search_type->currentIndex()))
{
case cheat_type::unsigned_8_cheat: res_conv = convert_and_search<u8>(); break;
case cheat_type::unsigned_16_cheat: res_conv = convert_and_search<u16>(); break;
case cheat_type::unsigned_32_cheat: res_conv = convert_and_search<u32>(); break;
case cheat_type::unsigned_64_cheat: res_conv = convert_and_search<u64>(); break;
case cheat_type::signed_8_cheat: res_conv = convert_and_search<s8>(); break;
case cheat_type::signed_16_cheat: res_conv = convert_and_search<s16>(); break;
case cheat_type::signed_32_cheat: res_conv = convert_and_search<s32>(); break;
case cheat_type::signed_64_cheat: res_conv = convert_and_search<s64>(); break;
default: log_cheat.fatal("Unsupported cheat type"); break;
}
if (!res_conv)
{
QMessageBox::warning(this, tr("Error converting value"), tr("Couldn't convert the search value you typed to the integer type you selected"), QMessageBox::Ok);
return;
}
lst_search->clear();
const usz size = offsets_found.size();
if (size == 0)
{
QListWidgetItem* item = new QListWidgetItem(tr("Nothing found"));
item->setData(Qt::UserRole, true);
lst_search->insertItem(0, item);
}
else if (size > 10000)
{
// Only show entries below a fixed amount. Too many entries can take forever to render and fill up memory quickly.
QListWidgetItem* item = new QListWidgetItem(tr("Too many entries to display (%0)").arg(size));
item->setData(Qt::UserRole, true);
lst_search->insertItem(0, item);
}
else
{
for (u32 row = 0; row < size; row++)
{
lst_search->insertItem(row, tr("0x%0").arg(offsets_found[row], 1, 16).toUpper());
}
}
btn_filter_results->setEnabled(!offsets_found.empty() && edt_cheat_search_value && !edt_cheat_search_value->text().isEmpty());
}
void cheat_manager_dialog::update_cheat_list()
{
usz num_rows = 0;
for (const auto& name : g_cheat.cheats)
num_rows += name.second.size();
tbl_cheats->setRowCount(::narrow<int>(num_rows));
u32 row = 0;
{
const QSignalBlocker blocker(tbl_cheats);
for (const auto& game : g_cheat.cheats)
{
for (const auto& offset : game.second)
{
QTableWidgetItem* item_game = new QTableWidgetItem(QString::fromStdString(offset.second.game));
item_game->setFlags(item_game->flags() & ~Qt::ItemIsEditable);
tbl_cheats->setItem(row, cheat_table_columns::title, item_game);
tbl_cheats->setItem(row, cheat_table_columns::description, new QTableWidgetItem(QString::fromStdString(offset.second.description)));
std::string type_formatted;
fmt::append(type_formatted, "%s", offset.second.type);
QTableWidgetItem* item_type = new QTableWidgetItem(QString::fromStdString(type_formatted));
item_type->setFlags(item_type->flags() & ~Qt::ItemIsEditable);
tbl_cheats->setItem(row, cheat_table_columns::type, item_type);
QTableWidgetItem* item_offset = new QTableWidgetItem(tr("0x%1").arg(offset.second.offset, 1, 16).toUpper());
item_offset->setData(Qt::UserRole, QVariant(offset.second.offset));
item_offset->setFlags(item_offset->flags() & ~Qt::ItemIsEditable);
tbl_cheats->setItem(row, cheat_table_columns::offset, item_offset);
tbl_cheats->setItem(row, cheat_table_columns::script, new QTableWidgetItem(QString::fromStdString(offset.second.red_script)));
row++;
}
}
}
g_cheat.save();
}
QString cheat_manager_dialog::get_localized_cheat_type(cheat_type type)
{
switch (type)
{
case cheat_type::unsigned_8_cheat: return tr("Unsigned 8 bits");
case cheat_type::unsigned_16_cheat: return tr("Unsigned 16 bits");
case cheat_type::unsigned_32_cheat: return tr("Unsigned 32 bits");
case cheat_type::unsigned_64_cheat: return tr("Unsigned 64 bits");
case cheat_type::signed_8_cheat: return tr("Signed 8 bits");
case cheat_type::signed_16_cheat: return tr("Signed 16 bits");
case cheat_type::signed_32_cheat: return tr("Signed 32 bits");
case cheat_type::signed_64_cheat: return tr("Signed 64 bits");
case cheat_type::max: break;
}
std::string type_formatted;
fmt::append(type_formatted, "%s", type);
return QString::fromStdString(type_formatted);
}
| 29,211
|
C++
|
.cpp
| 886
| 29.823928
| 190
| 0.688297
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,051
|
game_list_delegate.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/game_list_delegate.cpp
|
#include "game_list_delegate.h"
#include "movie_item.h"
#include "gui_settings.h"
#include <QHeaderView>
game_list_delegate::game_list_delegate(QObject* parent)
: table_item_delegate(parent, true)
{}
void game_list_delegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
table_item_delegate::paint(painter, option, index);
// Find out if the icon or size items are visible
if (index.column() == static_cast<int>(gui::game_list_columns::dir_size) || (m_has_icons && index.column() == static_cast<int>(gui::game_list_columns::icon)))
{
if (const QTableWidget* table = static_cast<const QTableWidget*>(parent()))
{
// We need to remove the headers from our calculation. The visualItemRect starts at 0,0 while the visibleRegion doesn't.
QRegion visible_region = table->visibleRegion();
visible_region.translate(-table->verticalHeader()->width(), -table->horizontalHeader()->height());
if (const QTableWidgetItem* current_item = table->item(index.row(), index.column());
current_item && visible_region.intersects(table->visualItemRect(current_item)))
{
if (movie_item* item = static_cast<movie_item*>(table->item(index.row(), static_cast<int>(gui::game_list_columns::icon))))
{
if (index.column() == static_cast<int>(gui::game_list_columns::dir_size))
{
if (!item->size_on_disk_loading())
{
item->call_size_calc_func();
}
}
else if (m_has_icons && index.column() == static_cast<int>(gui::game_list_columns::icon))
{
if (!item->icon_loading())
{
item->call_icon_load_func(index.row());
}
}
}
}
}
}
}
| 1,674
|
C++
|
.cpp
| 42
| 35.738095
| 159
| 0.679779
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,052
|
persistent_settings.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/persistent_settings.cpp
|
#include "persistent_settings.h"
#include "util/logs.hpp"
#include "Emu/system_utils.hpp"
LOG_CHANNEL(cfg_log, "CFG");
persistent_settings::persistent_settings(QObject* parent) : settings(parent)
{
// Don't use the .ini file ending for now, as it will be confused for a regular gui_settings file.
m_settings = std::make_unique<QSettings>(ComputeSettingsDir() + gui::persistent::persistent_file_name + ".dat", QSettings::Format::IniFormat, parent);
}
void persistent_settings::SetPlaytime(const QString& serial, quint64 playtime, bool sync)
{
m_playtime[serial] = playtime;
SetValue(gui::persistent::playtime, serial, playtime, sync);
}
void persistent_settings::AddPlaytime(const QString& serial, quint64 elapsed, bool sync)
{
const quint64 playtime = GetValue(gui::persistent::playtime, serial, 0).toULongLong();
SetPlaytime(serial, playtime + elapsed, sync);
}
quint64 persistent_settings::GetPlaytime(const QString& serial)
{
return m_playtime[serial];
}
void persistent_settings::SetLastPlayed(const QString& serial, const QString& date, bool sync)
{
m_last_played[serial] = date;
SetValue(gui::persistent::last_played, serial, date, sync);
}
QString persistent_settings::GetLastPlayed(const QString& serial)
{
return m_last_played[serial];
}
QString persistent_settings::GetCurrentUser(const QString& fallback) const
{
// Load user
QString user = GetValue(gui::persistent::active_user).toString();
if (user.isEmpty())
{
user = fallback;
}
// Set user if valid
if (rpcs3::utils::check_user(user.toStdString()) > 0)
{
return user;
}
cfg_log.fatal("Could not parse user setting: '%s'.", user);
return QString();
}
| 1,652
|
C++
|
.cpp
| 48
| 32.666667
| 151
| 0.762084
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,053
|
microphone_creator.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/microphone_creator.cpp
|
#include "stdafx.h"
#include "microphone_creator.h"
#include "Utilities/StrFmt.h"
#include "Utilities/StrUtil.h"
#include "3rdparty/OpenAL/openal-soft/include/AL/alext.h"
LOG_CHANNEL(cfg_log, "CFG");
microphone_creator::microphone_creator()
{
setObjectName("microphone_creator");
}
// We need to recreate the localized string because the microphone creator is currently only created once.
QString microphone_creator::get_none()
{
return tr("None", "Microphone device");
}
void microphone_creator::refresh_list()
{
m_microphone_list.clear();
m_microphone_list.append(get_none());
if (alcIsExtensionPresent(nullptr, "ALC_ENUMERATION_EXT") == AL_TRUE)
{
if (const char* devices = alcGetString(nullptr, ALC_CAPTURE_DEVICE_SPECIFIER))
{
while (*devices != 0)
{
m_microphone_list.append(devices);
devices += strlen(devices) + 1;
}
}
}
else
{
// Without enumeration we can only use one device
cfg_log.error("OpenAl extension ALC_ENUMERATION_EXT not supported. The microphone list will only contain the default microphone.");
if (const char* device = alcGetString(nullptr, ALC_DEFAULT_DEVICE_SPECIFIER))
{
m_microphone_list.append(device);
}
}
}
QStringList microphone_creator::get_microphone_list() const
{
return m_microphone_list;
}
std::array<std::string, 4> microphone_creator::get_selection_list() const
{
return m_sel_list;
}
std::string microphone_creator::set_device(u32 num, const QString& text)
{
ensure(num < m_sel_list.size());
if (text == get_none())
m_sel_list[num].clear();
else
m_sel_list[num] = text.toStdString();
return m_sel_list[0] + "@@@" + m_sel_list[1] + "@@@" + m_sel_list[2] + "@@@" + m_sel_list[3] + "@@@";
}
void microphone_creator::parse_devices(const std::string& list)
{
m_sel_list = {};
const std::vector<std::string> devices_list = fmt::split(list, { "@@@" });
for (usz index = 0; index < std::min(m_sel_list.size(), devices_list.size()); index++)
{
m_sel_list[index] = devices_list[index];
}
}
| 1,999
|
C++
|
.cpp
| 66
| 28.106061
| 133
| 0.711679
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,054
|
auto_pause_settings_dialog.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/auto_pause_settings_dialog.cpp
|
#include "auto_pause_settings_dialog.h"
#include "table_item_delegate.h"
#include "Emu/System.h"
#include <QFontDatabase>
#include <QMenu>
#include <QMouseEvent>
#include <QVBoxLayout>
#include <QPushButton>
#include "util/logs.hpp"
#include "Utilities/File.h"
LOG_CHANNEL(autopause_log, "AutoPause");
auto_pause_settings_dialog::auto_pause_settings_dialog(QWidget *parent) : QDialog(parent)
{
QLabel *description = new QLabel(tr("To use auto pause: enter the ID(s) of a function or a system call.\nRestart of the game is required to apply. You can enable/disable this in the settings."), this);
m_pause_list = new QTableWidget(this);
m_pause_list->setColumnCount(2);
m_pause_list->setHorizontalHeaderLabels(QStringList() << tr("Call ID") << tr("Type"));
//m_pause_list->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
m_pause_list->setSelectionBehavior(QAbstractItemView::SelectRows);
m_pause_list->setContextMenuPolicy(Qt::CustomContextMenu);
m_pause_list->setItemDelegate(new table_item_delegate(this));
m_pause_list->setShowGrid(false);
QPushButton *clearButton = new QPushButton(tr("Clear"), this);
QPushButton *reloadButton = new QPushButton(tr("Reload"), this);
QPushButton *saveButton = new QPushButton(tr("Save"), this);
QPushButton *cancelButton = new QPushButton(tr("Cancel"), this);
cancelButton->setDefault(true);
QHBoxLayout *buttonsLayout = new QHBoxLayout();
buttonsLayout->addWidget(clearButton);
buttonsLayout->addWidget(reloadButton);
buttonsLayout->addStretch();
buttonsLayout->addWidget(saveButton);
buttonsLayout->addWidget(cancelButton);
QVBoxLayout *mainLayout = new QVBoxLayout(this);
mainLayout->addWidget(description);
mainLayout->addWidget(m_pause_list);
mainLayout->addLayout(buttonsLayout);
setLayout(mainLayout);
setMinimumSize(QSize(400, 360));
setWindowTitle(tr("Auto Pause Manager"));
setObjectName("auto_pause_manager");
// Events
connect(m_pause_list, &QTableWidget::customContextMenuRequested, this, &auto_pause_settings_dialog::ShowContextMenu);
connect(clearButton, &QAbstractButton::clicked, [this](){ m_entries.clear(); UpdateList(); });
connect(reloadButton, &QAbstractButton::clicked, [this](){ LoadEntries(); UpdateList(); });
connect(saveButton, &QAbstractButton::clicked, [this]()
{
SaveEntries();
autopause_log.success("File pause.bin was updated.");
});
connect(cancelButton, &QAbstractButton::clicked, this, &QWidget::close);
Emu.GracefulShutdown(false);
LoadEntries();
UpdateList();
setFixedSize(sizeHint());
}
// Copied some from AutoPause.
void auto_pause_settings_dialog::LoadEntries()
{
m_entries.clear();
m_entries.reserve(16);
const fs::file list(fs::get_config_dir() + "pause.bin");
if (list)
{
// System calls ID and Function calls ID are all u32 iirc.
u32 num;
const usz fmax = list.size();
usz fcur = 0;
list.seek(0);
while (fcur <= fmax - sizeof(u32))
{
list.read(&num, sizeof(u32));
fcur += sizeof(u32);
if (num == 0xFFFFFFFF) break;
m_entries.emplace_back(num);
}
}
}
// Copied some from AutoPause.
// Tip: This one doesn't check for the file is being read or not.
// This would always use a 0xFFFFFFFF as end of the pause.bin
void auto_pause_settings_dialog::SaveEntries()
{
fs::file list(fs::get_config_dir() + "pause.bin", fs::rewrite);
//System calls ID and Function calls ID are all u32 iirc.
u32 num = 0;
list.seek(0);
for (usz i = 0; i < m_entries.size(); ++i)
{
if (num == 0xFFFFFFFF) continue;
num = m_entries[i];
list.write(&num, sizeof(u32));
}
num = 0xFFFFFFFF;
list.write(&num, sizeof(u32));
}
void auto_pause_settings_dialog::UpdateList()
{
const int entries_size = static_cast<int>(m_entries.size());
m_pause_list->clearContents();
m_pause_list->setRowCount(entries_size);
for (int i = 0; i < entries_size; ++i)
{
QTableWidgetItem* callItem = new QTableWidgetItem;
QTableWidgetItem* typeItem = new QTableWidgetItem;
callItem->setFlags(callItem->flags() & ~Qt::ItemIsEditable);
typeItem->setFlags(typeItem->flags() & ~Qt::ItemIsEditable);
if (m_entries[i] != 0xFFFFFFFF)
{
callItem->setData(Qt::DisplayRole, QString::fromStdString(fmt::format("%08x", m_entries[i])));
}
else
{
callItem->setData(Qt::DisplayRole, tr("Unset"));
}
if (m_entries[i] < 1024)
{
typeItem->setData(Qt::DisplayRole, tr("System Call"));
}
else
{
typeItem->setData(Qt::DisplayRole, tr("Function Call"));
}
m_pause_list->setItem(i, 0, callItem);
m_pause_list->setItem(i, 1, typeItem);
}
}
void auto_pause_settings_dialog::ShowContextMenu(const QPoint &pos)
{
const int row = m_pause_list->indexAt(pos).row();
QMenu myMenu;
// Make Actions
QAction* add = myMenu.addAction(tr("&Add"));
QAction* remove = myMenu.addAction(tr("&Remove"));
myMenu.addSeparator();
QAction* config = myMenu.addAction(tr("&Config"));
if (row == -1)
{
remove->setEnabled(false);
config->setEnabled(false);
}
auto OnEntryConfig = [this](int row, bool newEntry)
{
AutoPauseConfigDialog *config = new AutoPauseConfigDialog(this, this, newEntry, &m_entries[row]);
config->setModal(true);
config->exec();
UpdateList();
};
connect(add, &QAction::triggered, this, [=, this]()
{
m_entries.emplace_back(0xFFFFFFFF);
UpdateList();
const int idx = static_cast<int>(m_entries.size()) - 1;
m_pause_list->selectRow(idx);
OnEntryConfig(idx, true);
});
connect(remove, &QAction::triggered, this, &auto_pause_settings_dialog::OnRemove);
connect(config, &QAction::triggered, this, [=, this]() {OnEntryConfig(row, false); });
myMenu.exec(m_pause_list->viewport()->mapToGlobal(pos));
}
void auto_pause_settings_dialog::OnRemove()
{
QModelIndexList selection = m_pause_list->selectionModel()->selectedRows();
std::sort(selection.begin(), selection.end());
for (int i = selection.count() - 1; i >= 0; i--)
{
m_entries.erase(m_entries.begin() + ::at32(selection, i).row());
}
UpdateList();
}
void auto_pause_settings_dialog::keyPressEvent(QKeyEvent *event)
{
if (event->isAutoRepeat())
{
return;
}
if (event->key() == Qt::Key_Delete)
{
OnRemove();
}
}
AutoPauseConfigDialog::AutoPauseConfigDialog(QWidget* parent, auto_pause_settings_dialog* apsd, bool newEntry, u32 *entry)
: QDialog(parent), m_presult(entry), m_newEntry(newEntry), m_apsd(apsd)
{
m_entry = *m_presult;
setMinimumSize(QSize(300, -1));
QPushButton* button_ok = new QPushButton(tr("&Ok"), this);
QPushButton* button_cancel = new QPushButton(tr("&Cancel"), this);
button_ok->setFixedWidth(50);
button_cancel->setFixedWidth(50);
QLabel* description = new QLabel(tr("Specify ID of System Call or Function Call below. You need to use a Hexadecimal ID."), this);
description->setWordWrap(true);
m_current_converted = new QLabel(tr("Currently it gets an id of \"Unset\"."), this);
m_current_converted->setWordWrap(true);
m_id = new QLineEdit(this);
m_id->setText(QString::fromStdString(fmt::format("%08x", m_entry)));
m_id->setPlaceholderText("ffffffff");
m_id->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
m_id->setMaxLength(8);
m_id->setFixedWidth(65);
setWindowTitle("Auto Pause Setting: " + m_id->text());
connect(button_cancel, &QAbstractButton::clicked, this, &AutoPauseConfigDialog::OnCancel);
connect(button_ok, &QAbstractButton::clicked, this, &AutoPauseConfigDialog::OnOk);
connect(m_id, &QLineEdit::textChanged, this, &AutoPauseConfigDialog::OnUpdateValue);
QHBoxLayout* configHBox = new QHBoxLayout();
configHBox->addWidget(m_id);
configHBox->addWidget(button_ok);
configHBox->addWidget(button_cancel);
configHBox->setAlignment(Qt::AlignCenter);
QVBoxLayout* mainLayout = new QVBoxLayout(this);
mainLayout->addWidget(description);
mainLayout->addLayout(configHBox);
mainLayout->addWidget(m_current_converted);
setLayout(mainLayout);
setFixedSize(QSize(300, sizeHint().height()));
OnUpdateValue();
}
void AutoPauseConfigDialog::OnOk()
{
bool ok;
const ullong value = m_id->text().toULongLong(&ok, 16);
m_entry = value;
*m_presult = m_entry;
accept();
}
void AutoPauseConfigDialog::OnCancel()
{
if (m_newEntry)
{
m_apsd->OnRemove();
}
close();
}
void AutoPauseConfigDialog::OnUpdateValue() const
{
bool ok;
const ullong value = m_id->text().toULongLong(&ok, 16);
const bool is_ok = ok && value <= u32{umax};
m_current_converted->setText(tr("Current value: %1 (%2)").arg(value, 8, 16).arg(is_ok ? tr("OK") : tr("Conversion failed")));
}
| 8,447
|
C++
|
.cpp
| 240
| 32.945833
| 202
| 0.731651
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,055
|
patch_creator_dialog.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/patch_creator_dialog.cpp
|
#include "ui_patch_creator_dialog.h"
#include "patch_creator_dialog.h"
#include "table_item_delegate.h"
#include "qt_utils.h"
#include "Utilities/Config.h"
#include <QCompleter>
#include <QFontDatabase>
#include <QMenu>
#include <QMessageBox>
#include <QFileDialog>
#include <QMenuBar>
#include <QStringBuilder>
#include <regex>
LOG_CHANNEL(patch_log, "PAT");
Q_DECLARE_METATYPE(patch_type)
enum patch_column : int
{
type = 0,
offset,
value,
comment
};
patch_creator_dialog::patch_creator_dialog(QWidget* parent)
: QDialog(parent)
, ui(new Ui::patch_creator_dialog)
, mMonoFont(QFontDatabase::systemFont(QFontDatabase::FixedFont))
, mValidColor(gui::utils::get_label_color("log_level_success", Qt::darkGreen, Qt::green))
, mInvalidColor(gui::utils::get_label_color("log_level_error", Qt::red, Qt::red))
, m_offset_validator(new QRegularExpressionValidator(QRegularExpression("^(0[xX])?[a-fA-F0-9]{0,8}$"), this))
{
ui->setupUi(this);
ui->patchEdit->setFont(mMonoFont);
ui->patchEdit->setAcceptRichText(true);
ui->addPatchOffsetEdit->setFont(mMonoFont);
ui->addPatchOffsetEdit->setClearButtonEnabled(true);
ui->addPatchValueEdit->setFont(mMonoFont);
ui->addPatchValueEdit->setClearButtonEnabled(true);
ui->addPatchCommentEdit->setClearButtonEnabled(true);
ui->instructionTable->setFont(mMonoFont);
ui->instructionTable->setItemDelegate(new table_item_delegate(this, false));
ui->instructionTable->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeMode::Fixed);
ui->instructionTable->installEventFilter(this);
ui->versionMinorSpinBox->setValue(0);
ui->versionMajorSpinBox->setValue(0);
QMenuBar* menu_bar = new QMenuBar(this);
QMenu* file_menu = menu_bar->addMenu(tr("File"));
QAction* export_act = file_menu->addAction(tr("&Export Patch"));
export_act->setShortcut(QKeySequence("Ctrl+E"));
export_act->installEventFilter(this);
layout()->setMenuBar(menu_bar);
connect(export_act, &QAction::triggered, this, &patch_creator_dialog::export_patch);
connect(ui->hashEdit, &QLineEdit::textChanged, this, &patch_creator_dialog::generate_yml);
connect(ui->authorEdit, &QLineEdit::textChanged, this, &patch_creator_dialog::generate_yml);
connect(ui->patchNameEdit, &QLineEdit::textChanged, this, &patch_creator_dialog::generate_yml);
connect(ui->gameEdit, &QLineEdit::textChanged, this, &patch_creator_dialog::generate_yml);
connect(ui->gameVersionEdit, &QLineEdit::textChanged, this, &patch_creator_dialog::generate_yml);
connect(ui->serialEdit, &QLineEdit::textChanged, this, &patch_creator_dialog::generate_yml);
connect(ui->notesEdit, &QLineEdit::textChanged, this, &patch_creator_dialog::generate_yml);
connect(ui->groupEdit, &QLineEdit::textChanged, this, &patch_creator_dialog::generate_yml);
connect(ui->versionMinorSpinBox, &QSpinBox::textChanged, this, &patch_creator_dialog::generate_yml);
connect(ui->versionMajorSpinBox, &QSpinBox::textChanged, this, &patch_creator_dialog::generate_yml);
connect(ui->instructionTable, &QTableWidget::itemChanged, this, [this](QTableWidgetItem*){ generate_yml(); });
connect(ui->instructionTable, &QTableWidget::customContextMenuRequested, this, &patch_creator_dialog::show_table_menu);
connect(ui->addPatchButton, &QAbstractButton::clicked, this, [this]() { add_instruction(ui->instructionTable->rowCount()); });
init_patch_type_bombo_box(ui->addPatchTypeComboBox, patch_type::be32, false);
connect(ui->addPatchTypeComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int index){ update_validator(index, ui->addPatchTypeComboBox, ui->addPatchOffsetEdit); });
update_validator(ui->addPatchTypeComboBox->currentIndex(), ui->addPatchTypeComboBox, ui->addPatchOffsetEdit);
generate_yml();
}
patch_creator_dialog::~patch_creator_dialog()
{
}
void patch_creator_dialog::init_patch_type_bombo_box(QComboBox* combo_box, patch_type set_type, bool searchable)
{
if (!combo_box) return;
combo_box->clear();
QStringList types;
for (const std::string& type : cfg::try_to_enum_list(&fmt_class_string<patch_type>::format))
{
if (const patch_type t = patch_engine::get_patch_type(type); t != patch_type::invalid)
{
types << QString::fromStdString(type);
combo_box->addItem(types.last(), QVariant::fromValue<patch_type>(t));
if (t == set_type)
{
combo_box->setCurrentText(types.last());
}
}
}
if (searchable)
{
QCompleter* completer = new QCompleter(types, combo_box);
completer->setCaseSensitivity(Qt::CaseInsensitive);
completer->setCompletionMode(QCompleter::PopupCompletion);
completer->setFilterMode(Qt::MatchContains);
combo_box->setCompleter(completer);
combo_box->setEditable(true);
combo_box->setInsertPolicy(QComboBox::NoInsert);
}
}
QComboBox* patch_creator_dialog::create_patch_type_bombo_box(patch_type set_type) const
{
QComboBox* combo_box = new QComboBox;
init_patch_type_bombo_box(combo_box, set_type, true);
connect(combo_box, &QComboBox::currentTextChanged, this, &patch_creator_dialog::generate_yml);
return combo_box;
}
void patch_creator_dialog::show_table_menu(const QPoint& pos)
{
QMenu menu;
QModelIndexList selection = ui->instructionTable->selectionModel()->selectedRows();
if (selection.isEmpty())
{
QAction* act_add_instruction = menu.addAction(tr("&Add Instruction"));
connect(act_add_instruction, &QAction::triggered, [this]()
{
add_instruction(ui->instructionTable->rowCount());
});
}
else
{
if (selection.count() == 1)
{
QAction* act_add_instruction_above = menu.addAction(tr("&Add Instruction Above"));
connect(act_add_instruction_above, &QAction::triggered, [this, row = selection.first().row()]()
{
add_instruction(row);
});
QAction* act_add_instruction_below = menu.addAction(tr("&Add Instruction Below"));
connect(act_add_instruction_below, &QAction::triggered, [this, row = selection.first().row()]()
{
add_instruction(row + 1);
});
}
const bool can_move_up = can_move_instructions(selection, move_direction::up);
const bool can_move_down = can_move_instructions(selection, move_direction::down);
if (can_move_up)
{
menu.addSeparator();
QAction* act_move_instruction_up = menu.addAction(tr("&Move Instruction(s) Up"));
connect(act_move_instruction_up, &QAction::triggered, [this, &selection]()
{
move_instructions(selection.first().row(), selection.count(), 1, move_direction::up);
});
}
if (can_move_down)
{
if (!can_move_up)
menu.addSeparator();
QAction* act_move_instruction_down = menu.addAction(tr("&Move Instruction(s) Down"));
connect(act_move_instruction_down, &QAction::triggered, [this, &selection]()
{
move_instructions(selection.first().row(), selection.count(), 1, move_direction::down);
});
}
menu.addSeparator();
QAction* act_remove_instruction = menu.addAction(tr("&Remove Instruction(s)"));
connect(act_remove_instruction, &QAction::triggered, [this]()
{
remove_instructions();
});
}
menu.addSeparator();
QAction* act_clear_table = menu.addAction(tr("&Clear Table"));
connect(act_clear_table, &QAction::triggered, [this]()
{
patch_log.notice("Patch Creator: Clearing instruction table...");
ui->instructionTable->clearContents();
ui->instructionTable->setRowCount(0);
generate_yml();
});
menu.exec(ui->instructionTable->viewport()->mapToGlobal(pos));
}
void patch_creator_dialog::update_validator(int index, QComboBox* combo_box, QLineEdit* line_edit) const
{
if (index < 0 || !combo_box || !line_edit || !combo_box->itemData(index).canConvert<patch_type>())
{
return;
}
switch (combo_box->itemData(index).value<patch_type>())
{
case patch_type::move_file:
case patch_type::hide_file:
line_edit->setValidator(nullptr);
break;
default:
line_edit->setValidator(m_offset_validator);
break;
}
}
void patch_creator_dialog::add_instruction(int row)
{
const QString type = ui->addPatchTypeComboBox->currentText();
const QString offset = ui->addPatchOffsetEdit->text();
const QString value = ui->addPatchValueEdit->text();
const QString comment = ui->addPatchCommentEdit->text();
const patch_type t = patch_engine::get_patch_type(type.toStdString());
switch (t)
{
case patch_type::move_file:
case patch_type::hide_file:
break;
default:
{
int pos = 0;
QString text_to_validate = offset;
if (m_offset_validator->validate(text_to_validate, pos) == QValidator::Invalid)
{
QMessageBox::information(this, tr("Offset invalid!"), tr("The patch offset is invalid.\nThe offset has to be a hexadecimal number with 8 digits at most."));
return;
}
break;
}
}
QComboBox* combo_box = create_patch_type_bombo_box(t);
ui->instructionTable->insertRow(std::max(0, std::min(row, ui->instructionTable->rowCount())));
ui->instructionTable->setCellWidget(row, patch_column::type, combo_box);
ui->instructionTable->setItem(row, patch_column::offset, new QTableWidgetItem(offset));
ui->instructionTable->setItem(row, patch_column::value, new QTableWidgetItem(value));
ui->instructionTable->setItem(row, patch_column::comment, new QTableWidgetItem(comment));
patch_log.notice("Patch Creator: Inserted instruction [ %s, %s, %s ] at row %d", combo_box->currentText(), offset, value, row);
generate_yml();
}
void patch_creator_dialog::remove_instructions()
{
QModelIndexList selection(ui->instructionTable->selectionModel()->selectedRows());
if (selection.empty())
return;
std::sort(selection.rbegin(), selection.rend());
for (const QModelIndex& index : selection)
{
patch_log.notice("Patch Creator: Removing instruction in row %d...", index.row());
ui->instructionTable->removeRow(index.row());
}
generate_yml();
}
void patch_creator_dialog::move_instructions(int src_row, int rows_to_move, int distance, move_direction dir)
{
patch_log.notice("Patch Creator: Moving %d instruction(s) from row %d %s by %d...", rows_to_move, src_row, dir == move_direction::up ? "up" : "down", distance);
if (src_row < 0 || src_row >= ui->instructionTable->rowCount() || distance < 1)
return;
rows_to_move = std::max(0, std::min(rows_to_move, ui->instructionTable->rowCount() - src_row));
if (rows_to_move < 1)
return;
const int dst_row = std::max(0, std::min(ui->instructionTable->rowCount() - rows_to_move, dir == move_direction::up ? src_row - distance : src_row + distance));
if (dir == move_direction::up ? dst_row >= src_row : dst_row <= src_row)
return;
const int friends_to_relocate = std::abs(dst_row - src_row);
const int friends_src_row = dir == move_direction::up ? dst_row : src_row + rows_to_move;
const int friends_dst_row = dir == move_direction::up ? dst_row + rows_to_move : src_row;
std::vector<patch_type> moving_types(rows_to_move);
std::vector<std::vector<QTableWidgetItem*>> moving_rows(rows_to_move);
std::vector<patch_type> friend_types(friends_to_relocate);
std::vector<std::vector<QTableWidgetItem*>> friend_rows(friends_to_relocate);
const auto get_row_type = [this](int i) -> patch_type
{
if (const QComboBox* type_item = qobject_cast<QComboBox*>(ui->instructionTable->cellWidget(i, patch_column::type)))
return type_item->currentData().value<patch_type>();
return patch_type::invalid;
};
for (int i = 0; i < rows_to_move; i++)
{
moving_types[i] = get_row_type(src_row + i);
moving_rows[i].push_back(ui->instructionTable->takeItem(src_row + i, patch_column::type));
moving_rows[i].push_back(ui->instructionTable->takeItem(src_row + i, patch_column::offset));
moving_rows[i].push_back(ui->instructionTable->takeItem(src_row + i, patch_column::value));
moving_rows[i].push_back(ui->instructionTable->takeItem(src_row + i, patch_column::comment));
}
for (int i = 0; i < friends_to_relocate; i++)
{
friend_types[i] = get_row_type(friends_src_row + i);
friend_rows[i].push_back(ui->instructionTable->takeItem(friends_src_row + i, patch_column::type));
friend_rows[i].push_back(ui->instructionTable->takeItem(friends_src_row + i, patch_column::offset));
friend_rows[i].push_back(ui->instructionTable->takeItem(friends_src_row + i, patch_column::value));
friend_rows[i].push_back(ui->instructionTable->takeItem(friends_src_row + i, patch_column::comment));
}
for (int i = 0; i < rows_to_move; i++)
{
int item_index = 0;
ui->instructionTable->setCellWidget(dst_row + i, patch_column::type, create_patch_type_bombo_box(moving_types[i]));
ui->instructionTable->setItem(dst_row + i, patch_column::type, moving_rows[i][item_index++]);
ui->instructionTable->setItem(dst_row + i, patch_column::offset, moving_rows[i][item_index++]);
ui->instructionTable->setItem(dst_row + i, patch_column::value, moving_rows[i][item_index++]);
ui->instructionTable->setItem(dst_row + i, patch_column::comment, moving_rows[i][item_index++]);
}
for (int i = 0; i < friends_to_relocate; i++)
{
int item_index = 0;
ui->instructionTable->setCellWidget(friends_dst_row + i, patch_column::type, create_patch_type_bombo_box(friend_types[i]));
ui->instructionTable->setItem(friends_dst_row + i, patch_column::type, friend_rows[i][item_index++]);
ui->instructionTable->setItem(friends_dst_row + i, patch_column::offset, friend_rows[i][item_index++]);
ui->instructionTable->setItem(friends_dst_row + i, patch_column::value, friend_rows[i][item_index++]);
ui->instructionTable->setItem(friends_dst_row + i, patch_column::comment, friend_rows[i][item_index++]);
}
ui->instructionTable->clearSelection();
ui->instructionTable->setRangeSelected(QTableWidgetSelectionRange(dst_row, 0, dst_row + rows_to_move - 1, ui->instructionTable->columnCount() - 1), true);
generate_yml();
}
bool patch_creator_dialog::can_move_instructions(QModelIndexList& selection, move_direction dir)
{
if (selection.isEmpty())
return false;
std::sort(selection.begin(), selection.end());
// Check if there are any gaps in the selection
for (int i = 1, row = selection.first().row(); i < selection.count(); i++)
{
if (++row != selection[i].row())
return false;
}
if (dir == move_direction::up)
return selection.first().row() > 0;
return selection.last().row() < ui->instructionTable->rowCount() - 1;
}
void patch_creator_dialog::validate(const QString& patch)
{
patch_engine::patch_map patches;
const std::string content = patch.toStdString();
std::stringstream messages;
const bool is_valid = patch_engine::load(patches, "From Patch Creator", content, true, &messages);
if (is_valid != m_valid)
{
QPalette palette = ui->validLabel->palette();
if (is_valid)
{
ui->validLabel->setText(tr("Valid Patch"));
palette.setColor(ui->validLabel->foregroundRole(), mValidColor);
patch_log.success("Patch Creator: Validation successful!");
}
else
{
ui->validLabel->setText(tr("Validation Failed"));
palette.setColor(ui->validLabel->foregroundRole(), mInvalidColor);
patch_log.error("Patch Creator: Validation failed!");
}
ui->validLabel->setPalette(palette);
m_valid = is_valid;
}
if (is_valid)
{
ui->patchEdit->setText(patch);
return;
}
// Search for erronous yml node locations in log message
static const std::regex r("(line )(\\d+)(, column )(\\d+)");
std::smatch sm;
std::set<int> faulty_lines;
for (std::string err = messages.str(); !err.empty() && std::regex_search(err, sm, r) && sm.size() == 5; err = sm.suffix())
{
if (s64 row{}; try_to_int64(&row, sm[2].str(), 0, u32{umax}))
{
faulty_lines.insert(row);
}
}
// Create html and colorize offending lines
const QString font_start_tag = QStringLiteral("<font color = \"") % mInvalidColor.name() % QStringLiteral("\">");;
static const QString font_end_tag = QStringLiteral("</font>");
static const QString line_break_tag = QStringLiteral("<br/>");
QStringList lines = patch.split("\n");
QString new_text;
for (int i = 0; i < lines.size(); i++)
{
// Escape each line and replace raw whitespace
const QString line = lines[i].toHtmlEscaped().replace(" ", " ");
if (faulty_lines.empty() || faulty_lines.contains(i))
{
new_text += font_start_tag + line + font_end_tag + line_break_tag;
}
else
{
new_text += line + line_break_tag;
}
}
ui->patchEdit->setHtml(new_text);
}
void patch_creator_dialog::export_patch()
{
if (!m_valid)
{
QMessageBox::information(this, tr("Patch invalid!"), tr("The patch validation failed.\nThe export of invalid patches is not allowed."));
return;
}
const QString file_path = QFileDialog::getSaveFileName(this, tr("Select Patch File"), QString::fromStdString(patch_engine::get_patches_path()), tr("patch.yml files (*.yml);;All files (*.*)"));
if (file_path.isEmpty())
{
return;
}
if (QFile patch_file(file_path); patch_file.open(QIODevice::WriteOnly | QIODevice::Truncate))
{
patch_file.write(ui->patchEdit->toPlainText().toUtf8());
patch_file.close();
patch_log.success("Exported patch to file '%s'", file_path);
}
else
{
patch_log.fatal("Failed to export patch to file '%s'", file_path);
}
}
void patch_creator_dialog::generate_yml(const QString& /*text*/)
{
YAML::Emitter out;
out << YAML::BeginMap;
out << patch_key::version << patch_engine_version;
out << YAML::Newline;
out << ui->hashEdit->text().toStdString();
{
out << YAML::BeginMap;
out << YAML::DoubleQuoted << ui->patchNameEdit->text().toStdString();
{
out << YAML::BeginMap;
out << patch_key::games;
{
out << YAML::BeginMap;
out << YAML::DoubleQuoted << ui->gameEdit->text().toStdString();
{
out << YAML::BeginMap;
out << ui->serialEdit->text().simplified().toStdString();
{
out << YAML::Flow << fmt::split(ui->gameVersionEdit->text().toStdString(), { ",", " " });
}
out << YAML::EndMap;
}
out << YAML::EndMap;
}
out << patch_key::author << YAML::DoubleQuoted << ui->authorEdit->text().toStdString();
out << patch_key::patch_version << fmt::format("%s.%s", ui->versionMajorSpinBox->text(), ui->versionMinorSpinBox->text());
out << patch_key::group << YAML::DoubleQuoted << ui->groupEdit->text().toStdString();
out << patch_key::notes << YAML::DoubleQuoted << ui->notesEdit->text().toStdString();
out << patch_key::patch;
{
out << YAML::BeginSeq;
for (int i = 0; i < ui->instructionTable->rowCount(); i++)
{
const QComboBox* type_item = qobject_cast<QComboBox*>(ui->instructionTable->cellWidget(i, patch_column::type));
const QTableWidgetItem* offset_item = ui->instructionTable->item(i, patch_column::offset);
const QTableWidgetItem* value_item = ui->instructionTable->item(i, patch_column::value);
const QTableWidgetItem* comment_item = ui->instructionTable->item(i, patch_column::comment);
const std::string type = type_item ? type_item->currentText().toStdString() : "";
const std::string offset = offset_item ? offset_item->text().toStdString() : "";
const std::string value = value_item ? value_item->text().toStdString() : "";
const std::string comment = comment_item ? comment_item->text().toStdString() : "";
if (patch_engine::get_patch_type(type) == patch_type::invalid)
{
ui->patchEdit->setText(tr("Instruction %0: Type '%1' is invalid!").arg(i + 1).arg(type_item ? type_item->currentText() : ""));
return;
}
out << YAML::Flow << YAML::BeginSeq << type << offset << value << YAML::EndSeq;
if (!comment.empty())
{
out << YAML::Comment(comment);
}
}
out << YAML::EndSeq;
}
out << YAML::EndMap;
}
out << YAML::EndMap;
}
out << YAML::EndMap;
const QString patch = QString::fromUtf8(out.c_str(), out.size());
validate(patch);
}
bool patch_creator_dialog::eventFilter(QObject* object, QEvent* event)
{
if (object != ui->instructionTable)
{
return QDialog::eventFilter(object, event);
}
if (event->type() == QEvent::KeyPress)
{
if (QKeyEvent* key_event = static_cast<QKeyEvent*>(event))
{
if (key_event->modifiers() == Qt::AltModifier)
{
switch (key_event->key())
{
case Qt::Key_Up:
{
QModelIndexList selection = ui->instructionTable->selectionModel()->selectedRows();
if (can_move_instructions(selection, move_direction::up))
move_instructions(selection.first().row(), selection.count(), 1, move_direction::up);
return true;
}
case Qt::Key_Down:
{
QModelIndexList selection = ui->instructionTable->selectionModel()->selectedRows();
if (can_move_instructions(selection, move_direction::down))
move_instructions(selection.first().row(), selection.count(), 1, move_direction::down);
return true;
}
default:
break;
}
}
else if (!key_event->isAutoRepeat())
{
switch (key_event->key())
{
case Qt::Key_Delete:
{
remove_instructions();
return true;
}
default:
break;
}
}
}
}
return QDialog::eventFilter(object, event);
}
| 20,808
|
C++
|
.cpp
| 510
| 37.805882
| 193
| 0.707309
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,056
|
patch_manager_dialog.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/patch_manager_dialog.cpp
|
#include <QPushButton>
#include <QDialogButtonBox>
#include <QGuiApplication>
#include <QScreen>
#include <QDir>
#include <QMenu>
#include <QAction>
#include <QCheckBox>
#include <QMessageBox>
#include <QTimer>
#include <QJsonObject>
#include <QJsonDocument>
#include <QDoubleSpinBox>
#include "ui_patch_manager_dialog.h"
#include "patch_manager_dialog.h"
#include "table_item_delegate.h"
#include "gui_settings.h"
#include "downloader.h"
#include "qt_utils.h"
#include "Utilities/File.h"
#include "util/logs.hpp"
#include "Crypto/utils.h"
LOG_CHANNEL(patch_log, "PAT");
enum patch_column : int
{
enabled,
title,
serials,
description,
patch_version,
author,
notes
};
enum patch_role : int
{
hash_role = Qt::UserRole,
title_role,
serial_role,
app_version_role,
description_role,
patch_group_role,
persistance_role,
node_level_role,
config_values_role,
config_key_role,
};
enum node_level : int
{
title_level,
serial_level,
patch_level
};
Q_DECLARE_METATYPE(patch_engine::patch_config_value);
patch_manager_dialog::patch_manager_dialog(std::shared_ptr<gui_settings> gui_settings, std::unordered_map<std::string, std::set<std::string>> games, const std::string& title_id, const std::string& version, QWidget* parent)
: QDialog(parent)
, m_gui_settings(std::move(gui_settings))
, m_expand_current_match(!title_id.empty() && !version.empty()) // Expand first search results
, m_search_version(QString::fromStdString(version))
, m_owned_games(std::move(games))
, ui(new Ui::patch_manager_dialog)
{
ui->setupUi(this);
setModal(true);
// Load gui settings
m_show_owned_games_only = m_gui_settings->GetValue(gui::pm_show_owned).toBool();
// Initialize gui controls
ui->patch_filter->setText(QString::fromStdString(title_id));
ui->cb_owned_games_only->setChecked(m_show_owned_games_only);
ui->buttonBox->button(QDialogButtonBox::RestoreDefaults)->setText(tr("Download latest patches"));
m_downloader = new downloader(this);
ui->configurable_selector->setEnabled(false);
ui->configurable_combo_box->setEnabled(false);
ui->configurable_combo_box->setVisible(false);
ui->configurable_spin_box->setEnabled(false);
ui->configurable_spin_box->setVisible(false);
ui->configurable_double_spin_box->setEnabled(false);
ui->configurable_double_spin_box->setVisible(false);
// Create connects
connect(ui->patch_filter, &QLineEdit::textChanged, this, &patch_manager_dialog::filter_patches);
connect(ui->patch_tree, &QTreeWidget::currentItemChanged, this, &patch_manager_dialog::handle_item_selected);
connect(ui->patch_tree, &QTreeWidget::itemChanged, this, &patch_manager_dialog::handle_item_changed);
connect(ui->patch_tree, &QTreeWidget::customContextMenuRequested, this, &patch_manager_dialog::handle_custom_context_menu_requested);
connect(ui->cb_owned_games_only, &QCheckBox::checkStateChanged, this, &patch_manager_dialog::handle_show_owned_games_only);
connect(ui->configurable_selector, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int index)
{
if (index >= 0)
{
QList<QTreeWidgetItem*> list = ui->patch_tree->selectedItems();
QTreeWidgetItem* item = list.size() == 1 ? list.first() : nullptr;
handle_item_selected(item, item);
}
});
connect(ui->configurable_combo_box, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int index)
{
if (index >= 0)
{
handle_config_value_changed(ui->configurable_combo_box->itemData(index).toDouble());
}
});
connect(ui->configurable_spin_box, QOverload<int>::of(&QSpinBox::valueChanged), this, &patch_manager_dialog::handle_config_value_changed);
connect(ui->configurable_double_spin_box, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, &patch_manager_dialog::handle_config_value_changed);
connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QWidget::close);
connect(ui->buttonBox, &QDialogButtonBox::clicked, [this](QAbstractButton* button)
{
if (button == ui->buttonBox->button(QDialogButtonBox::Save))
{
save_config();
accept();
}
else if (button == ui->buttonBox->button(QDialogButtonBox::Apply))
{
save_config();
}
else if (button == ui->buttonBox->button(QDialogButtonBox::RestoreDefaults))
{
download_update(false, true);
}
});
connect(m_downloader, &downloader::signal_download_error, this, [this](const QString& /*error*/)
{
QMessageBox::warning(this, tr("Patch downloader"), tr("An error occurred during the download process.\nCheck the log for more information."));
ui->buttonBox->button(QDialogButtonBox::RestoreDefaults)->setEnabled(true);
});
connect(m_downloader, &downloader::signal_download_finished, this, [this](const QByteArray& data)
{
const bool result_json = handle_json(data);
if (!result_json)
{
if (!m_download_automatic)
{
QMessageBox::warning(this, tr("Patch downloader"), tr("An error occurred during the download process.\nCheck the log for more information."));
}
}
ui->buttonBox->button(QDialogButtonBox::RestoreDefaults)->setEnabled(true);
});
download_update(true, false);
}
void patch_manager_dialog::closeEvent(QCloseEvent* event)
{
// Save gui settings
m_gui_settings->SetValue(gui::pm_geometry, saveGeometry(), false);
m_gui_settings->SetValue(gui::pm_splitter_state, ui->splitter->saveState(), true);
QDialog::closeEvent(event);
}
patch_manager_dialog::~patch_manager_dialog()
{
}
int patch_manager_dialog::exec()
{
show();
refresh(true);
return QDialog::exec();
}
void patch_manager_dialog::refresh(bool restore_layout)
{
load_patches(restore_layout);
populate_tree();
filter_patches(ui->patch_filter->text());
if (restore_layout)
{
if (!restoreGeometry(m_gui_settings->GetValue(gui::pm_geometry).toByteArray()))
{
resize(QGuiApplication::primaryScreen()->availableSize() * 0.7);
}
if (!ui->splitter->restoreState(m_gui_settings->GetValue(gui::pm_splitter_state).toByteArray()))
{
const int width_left = ui->splitter->width() * 0.7;
const int width_right = ui->splitter->width() - width_left;
ui->splitter->setSizes({ width_left, width_right });
}
}
}
void patch_manager_dialog::load_patches(bool show_error)
{
m_map.clear();
// NOTE: Make sure these paths are loaded in the same order as they are applied on boot
const std::string patches_path = patch_engine::get_patches_path();
const QStringList filters = QStringList() << "*_patch.yml";
QStringList path_list;
path_list << "patch.yml";
path_list << "imported_patch.yml";
path_list << QDir(QString::fromStdString(patches_path)).entryList(filters);
path_list.removeDuplicates(); // make sure to load patch.yml and imported_patch.yml only once
bool has_errors = false;
for (const QString& path : path_list)
{
if (!patch_engine::load(m_map, patches_path + path.toStdString()))
{
has_errors = true;
patch_log.error("Errors in patch file '%s'", path);
}
}
if (show_error && has_errors)
{
// Open a warning dialog after the patch manager was opened
QTimer::singleShot(100, [this, patches_path]()
{
QMessageBox::warning(this, tr("Incompatible patches detected"),
tr("Some of your patches are not compatible with the current version of RPCS3's Patch Manager.\n\nMake sure that all the patches located in \"%0\" contain the proper formatting that is required for the Patch Manager Version %1.")
.arg(QString::fromStdString(patches_path)).arg(QString::fromStdString(patch_engine_version)));
});
}
}
void patch_manager_dialog::populate_tree()
{
// "Reset" currently used items. Items that aren't persisted will be removed later.
// Using this logic instead of clearing the tree here should persist the expanded status of items.
for (auto item : ui->patch_tree->findItems(".*", Qt::MatchFlag::MatchRegularExpression | Qt::MatchFlag::MatchRecursive))
{
if (item)
{
item->setData(0, persistance_role, false);
}
}
for (const auto& [hash, container] : m_map)
{
const QString q_hash = QString::fromStdString(hash);
// Add patch items
for (const auto& [description, patch] : container.patch_info_map)
{
const QString q_patch_group = QString::fromStdString(patch.patch_group);
for (const auto& [title, serials] : patch.titles)
{
if (serials.empty())
{
continue;
}
const QString q_title = QString::fromStdString(title);
const QString visible_title = title == patch_key::all ? tr_all_titles : q_title;
QTreeWidgetItem* title_level_item = nullptr;
// Find top level item for this title
if (const auto list = ui->patch_tree->findItems(visible_title, Qt::MatchFlag::MatchExactly, 0); !list.empty())
{
title_level_item = list[0];
}
// Add a top level item for this title if it doesn't exist yet
if (!title_level_item)
{
title_level_item = new QTreeWidgetItem();
title_level_item->setText(0, visible_title);
title_level_item->setData(0, title_role, q_title);
title_level_item->setData(0, node_level_role, node_level::title_level);
ui->patch_tree->addTopLevelItem(title_level_item);
}
ensure(title_level_item);
title_level_item->setData(0, persistance_role, true);
for (const auto& [serial, app_versions] : serials)
{
if (app_versions.empty())
{
continue;
}
const QString q_serial = QString::fromStdString(serial);
const QString visible_serial = serial == patch_key::all ? tr_all_serials : q_serial;
for (const auto& [app_version, config_values] : app_versions)
{
const QString q_app_version = QString::fromStdString(app_version);
const QString q_version_suffix = app_version == patch_key::all ? (QStringLiteral(" - ") + tr_all_versions) : (QStringLiteral(" v.") + q_app_version);
const QString q_serial_and_version = visible_serial + q_version_suffix;
// Find out if there is a node item for this serial
QTreeWidgetItem* serial_level_item = gui::utils::find_child(title_level_item, q_serial_and_version);
// Add a node item for this serial if it doesn't exist yet
if (!serial_level_item)
{
serial_level_item = new QTreeWidgetItem();
serial_level_item->setText(0, q_serial_and_version);
serial_level_item->setData(0, title_role, q_title);
serial_level_item->setData(0, serial_role, q_serial);
serial_level_item->setData(0, app_version_role, q_app_version);
serial_level_item->setData(0, node_level_role, node_level::serial_level);
title_level_item->addChild(serial_level_item);
}
ensure(serial_level_item);
serial_level_item->setData(0, persistance_role, true);
// Add a checkable leaf item for this patch
const QString q_description = QString::fromStdString(description);
QString visible_description = q_description;
const std::vector<std::pair<int, QVariant>> match_criteria =
{
std::pair<int, QVariant>(description_role, q_description),
std::pair<int, QVariant>(persistance_role, true)
};
// Add counter to leafs if the name already exists due to different hashes of the same game (PPU, SPU, PRX, OVL)
std::vector<QTreeWidgetItem*> matches;
gui::utils::find_children_by_data(serial_level_item, matches, match_criteria, false);
if (!matches.empty())
{
if (auto only_match = matches.size() == 1 ? matches[0] : nullptr)
{
only_match->setText(0, q_description + QStringLiteral(" (01)"));
}
const usz counter = matches.size() + 1;
visible_description += QStringLiteral(" (");
if (counter < 10) visible_description += '0';
visible_description += QString::number(counter) + ')';
}
QVariantMap q_config_values;
for (const auto& [key, default_config_value] : patch.default_config_values)
{
patch_engine::patch_config_value config_value = default_config_value;
if (config_values.config_values.contains(key))
{
config_value.set_and_check_value(config_values.config_values.at(key).value, key);
}
q_config_values[QString::fromStdString(key)] = QVariant::fromValue(config_value);
}
QTreeWidgetItem* patch_level_item = new QTreeWidgetItem();
patch_level_item->setText(0, visible_description);
patch_level_item->setCheckState(0, config_values.enabled ? Qt::CheckState::Checked : Qt::CheckState::Unchecked);
patch_level_item->setData(0, hash_role, q_hash);
patch_level_item->setData(0, title_role, q_title);
patch_level_item->setData(0, serial_role, q_serial);
patch_level_item->setData(0, app_version_role, q_app_version);
patch_level_item->setData(0, description_role, q_description);
patch_level_item->setData(0, patch_group_role, q_patch_group);
patch_level_item->setData(0, node_level_role, node_level::patch_level);
patch_level_item->setData(0, persistance_role, true);
patch_level_item->setData(0, config_values_role, q_config_values);
patch_level_item->setData(0, config_key_role, QString()); // Start with empty key. We will use this to keep track of the current config value during editing.
serial_level_item->addChild(patch_level_item);
}
}
}
}
}
const std::vector<std::pair<int, QVariant>> match_criteria =
{
std::pair<int, QVariant>(persistance_role, true)
};
for (int i = ui->patch_tree->topLevelItemCount() - 1; i >= 0; i--)
{
if (const auto title_level_item = ui->patch_tree->topLevelItem(i))
{
if (!title_level_item->data(0, persistance_role).toBool())
{
delete ui->patch_tree->takeTopLevelItem(i);
continue;
}
gui::utils::remove_children(title_level_item, match_criteria, true);
}
}
gui::utils::sort_tree(ui->patch_tree, Qt::SortOrder::AscendingOrder, true);
// Move "All titles" to the top
// NOTE: "All serials" is only allowed as the only node in "All titles", so there is no need to move it up
// NOTE: "All versions" will be above valid numerical versions through sorting anyway
if (const auto all_title_items = ui->patch_tree->findItems(tr_all_titles, Qt::MatchExactly); !all_title_items.empty())
{
const auto item = all_title_items[0];
ensure(item && all_title_items.size() == 1);
if (const int index = ui->patch_tree->indexOfTopLevelItem(item); item && index >= 0)
{
const bool all_titles_expanded = item->isExpanded();
const auto all_serials_item = item->child(0);
const bool all_serials_expanded = all_serials_item && all_serials_item->isExpanded();
ui->patch_tree->takeTopLevelItem(index);
ui->patch_tree->insertTopLevelItem(0, item);
item->setExpanded(all_titles_expanded);
if (all_serials_item)
{
all_serials_item->setExpanded(all_serials_expanded);
}
}
}
}
void patch_manager_dialog::save_config() const
{
patch_engine::save_config(m_map);
}
void patch_manager_dialog::filter_patches(const QString& term)
{
// Recursive function to show all matching items and their children.
// @return number of visible children of item, including item
std::function<int(QTreeWidgetItem*, bool)> show_matches;
show_matches = [this, &show_matches, search_text = term.toLower()](QTreeWidgetItem* item, bool parent_visible) -> int
{
if (!item) return 0;
const node_level level = static_cast<node_level>(item->data(0, node_level_role).toInt());
// Hide nodes that aren't in the game list
if (m_show_owned_games_only)
{
if (level == node_level::serial_level)
{
const std::string serial = item->data(0, serial_role).toString().toStdString();
const std::string app_version = item->data(0, app_version_role).toString().toStdString();
if (serial != patch_key::all &&
(!m_owned_games.contains(serial) || (app_version != patch_key::all && !::at32(m_owned_games, serial).contains(app_version))))
{
item->setHidden(true);
return 0;
}
}
}
// Only try to match if the parent is not visible
parent_visible = parent_visible || item->text(0).toLower().contains(search_text);
int visible_items = 0;
// Get the number of visible children recursively
for (int i = 0; i < item->childCount(); i++)
{
visible_items += show_matches(item->child(i), parent_visible);
}
if (parent_visible)
{
// Only show the title node if it has visible children when filtering for game list entries
if (!m_show_owned_games_only || level != node_level::title_level || visible_items > 0)
{
visible_items++;
}
}
// Only show item if itself or any of its children is visible
item->setHidden(visible_items <= 0);
return visible_items;
};
bool found_version = false;
// Go through each top level item and try to find matches
for (auto top_level_item : ui->patch_tree->findItems(".*", Qt::MatchRegularExpression))
{
if (!top_level_item)
continue;
const int matches = show_matches(top_level_item, false);
if (matches <= 0 || !m_expand_current_match)
continue;
// Expand only items that match the serial and version
for (int i = 0; i < top_level_item->childCount(); i++)
{
if (const auto item = top_level_item->child(i);
item && !item->isHidden() && item->data(0, app_version_role).toString() == m_search_version)
{
// This should always be a serial level item
ensure(item->data(0, node_level_role) == node_level::serial_level);
top_level_item->setExpanded(true);
item->setExpanded(true);
found_version = true;
break;
}
}
}
if (m_expand_current_match && !found_version)
{
// Expand all matching top_level items if the correct version wasn't found
for (auto top_level_item : ui->patch_tree->findItems(".*", Qt::MatchRegularExpression))
{
if (!top_level_item || top_level_item->isHidden())
continue;
top_level_item->setExpanded(true);
// Expand the "All Versions" item
for (int i = 0; i < top_level_item->childCount(); i++)
{
if (const auto item = top_level_item->child(i);
item && !item->isHidden() && item->data(0, app_version_role).toString().toStdString() == patch_key::all)
{
// This should always be a serial level item
ensure(item->data(0, node_level_role) == node_level::serial_level);
item->setExpanded(true);
break;
}
}
}
}
m_expand_current_match = false;
}
void patch_manager_dialog::update_patch_info(const patch_manager_dialog::gui_patch_info& info) const
{
ui->label_hash->setText(info.hash);
ui->label_author->setText(info.author);
ui->label_notes->setText(info.notes);
ui->label_description->setText(info.description);
ui->label_patch_version->setText(info.patch_version);
ui->label_serial->setText(info.serial);
ui->label_title->setText(info.title);
ui->label_app_version->setText(info.app_version);
const QString key = ui->configurable_selector->currentIndex() < 0 ? "" : ui->configurable_selector->currentData().toString();
if (info.config_values.empty() || key.isEmpty())
{
ui->configurable_combo_box->setEnabled(false);
ui->configurable_combo_box->setVisible(false);
ui->configurable_spin_box->setEnabled(false);
ui->configurable_spin_box->setVisible(false);
ui->configurable_double_spin_box->setEnabled(false);
ui->configurable_double_spin_box->setVisible(false);
ui->configurable_selector->blockSignals(true);
ui->configurable_selector->clear();
ui->configurable_selector->blockSignals(false);
ui->configurable_selector->setEnabled(false);
return;
}
if (key == info.config_value_key)
{
// Don't update widget if the config key did not change
return;
}
// Disable all config widgets first
ui->configurable_combo_box->setEnabled(false);
ui->configurable_combo_box->setVisible(false);
ui->configurable_spin_box->setEnabled(false);
ui->configurable_spin_box->setVisible(false);
ui->configurable_double_spin_box->setEnabled(false);
ui->configurable_double_spin_box->setVisible(false);
// Fetch the config values of this item
const QVariant& variant = ::at32(info.config_values, key);
ensure(variant.canConvert<patch_engine::patch_config_value>());
const patch_engine::patch_config_value config_value = variant.value<patch_engine::patch_config_value>();
// Setup the proper config widget
switch (config_value.type)
{
case patch_configurable_type::double_range:
ui->configurable_double_spin_box->blockSignals(true);
ui->configurable_double_spin_box->setRange(config_value.min, config_value.max);
ui->configurable_double_spin_box->setValue(config_value.value);
ui->configurable_double_spin_box->setEnabled(true);
ui->configurable_double_spin_box->setVisible(true);
ui->configurable_double_spin_box->blockSignals(false);
break;
case patch_configurable_type::long_range:
ui->configurable_spin_box->blockSignals(true);
ui->configurable_spin_box->setRange(config_value.min, config_value.max);
ui->configurable_spin_box->setValue(config_value.value);
ui->configurable_spin_box->setEnabled(true);
ui->configurable_spin_box->setVisible(true);
ui->configurable_spin_box->blockSignals(false);
break;
case patch_configurable_type::double_enum:
case patch_configurable_type::long_enum:
ui->configurable_combo_box->blockSignals(true);
ui->configurable_combo_box->clear();
for (const patch_engine::patch_allowed_value& allowed_value : config_value.allowed_values)
{
ui->configurable_combo_box->addItem(QString::fromStdString(allowed_value.label), allowed_value.value);
if (allowed_value.value == config_value.value)
{
ui->configurable_combo_box->setCurrentIndex(ui->configurable_combo_box->findData(allowed_value.value));
}
}
ui->configurable_combo_box->setEnabled(true);
ui->configurable_combo_box->setVisible(true);
ui->configurable_combo_box->blockSignals(false);
break;
}
}
void patch_manager_dialog::handle_item_selected(QTreeWidgetItem* current, QTreeWidgetItem* previous)
{
if (!current)
{
// Clear patch info if no item is selected
update_patch_info({});
return;
}
// Clear key of previous patch level item
if (previous && current != previous && static_cast<node_level>(previous->data(0, node_level_role).toInt()) == node_level::patch_level)
{
previous->setData(0, config_key_role, QString());
}
const node_level level = static_cast<node_level>(current->data(0, node_level_role).toInt());
patch_manager_dialog::gui_patch_info info{};
switch (level)
{
case node_level::patch_level:
{
// Get patch identifiers stored in item data
info.hash = current->data(0, hash_role).toString();
const std::string hash = info.hash.toStdString();
const std::string description = current->data(0, description_role).toString().toStdString();
// Find the patch for this item and get its metadata
if (m_map.contains(hash))
{
const auto& container = ::at32(m_map, hash);
if (container.patch_info_map.contains(description))
{
const auto& found_info = ::at32(container.patch_info_map, description);
info.author = QString::fromStdString(found_info.author);
info.notes = QString::fromStdString(found_info.notes);
info.description = QString::fromStdString(found_info.description);
info.patch_version = QString::fromStdString(found_info.patch_version);
info.config_values = current->data(0, config_values_role).toMap().toStdMap();
info.config_value_key = current->data(0, config_key_role).toString();
if (current != previous)
{
// Update the config value combo box with the new config keys
ui->configurable_selector->blockSignals(true);
ui->configurable_selector->clear();
for (const auto& [key, variant] : info.config_values)
{
ensure(variant.canConvert<patch_engine::patch_config_value>());
ui->configurable_selector->addItem(key, key);
}
if (ui->configurable_selector->count() > 0)
{
ui->configurable_selector->setCurrentIndex(0);
}
ui->configurable_selector->blockSignals(false);
ui->configurable_selector->setEnabled(ui->configurable_selector->count() > 0);
}
}
}
[[fallthrough]];
}
case node_level::serial_level:
{
const QString serial = current->data(0, serial_role).toString();
info.serial = serial.toStdString() == patch_key::all ? tr_all_serials : serial;
const QString app_version = current->data(0, app_version_role).toString();
info.app_version = app_version.toStdString() == patch_key::all ? tr_all_versions : app_version;
[[fallthrough]];
}
case node_level::title_level:
{
const QString title = current->data(0, title_role).toString();
info.title = title.toStdString() == patch_key::all ? tr_all_titles : title;
break;
}
}
update_patch_info(info);
const QString key = ui->configurable_selector->currentIndex() < 0 ? "" : ui->configurable_selector->currentData().toString();
current->setData(0, config_key_role, key);
}
void patch_manager_dialog::handle_item_changed(QTreeWidgetItem* item, int /*column*/)
{
if (!item)
{
return;
}
// Get checkstate of the item
const bool enabled = item->checkState(0) == Qt::CheckState::Checked;
// Get patch identifiers stored in item data
const node_level level = static_cast<node_level>(item->data(0, node_level_role).toInt());
const std::string hash = item->data(0, hash_role).toString().toStdString();
const std::string title = item->data(0, title_role).toString().toStdString();
const std::string serial = item->data(0, serial_role).toString().toStdString();
const std::string app_version = item->data(0, app_version_role).toString().toStdString();
const std::string description = item->data(0, description_role).toString().toStdString();
const std::string patch_group = item->data(0, patch_group_role).toString().toStdString();
// Uncheck other patches with the same patch_group if this patch was enabled
if (const auto node = item->parent(); node && enabled && !patch_group.empty() && level == node_level::patch_level)
{
for (int i = 0; i < node->childCount(); i++)
{
if (const auto other = node->child(i); other && other != item)
{
const std::string other_patch_group = other->data(0, patch_group_role).toString().toStdString();
if (other_patch_group == patch_group)
{
other->setCheckState(0, Qt::CheckState::Unchecked);
}
}
}
}
// Enable/disable the patch for this item and show its metadata
if (m_map.contains(hash))
{
auto& info = m_map[hash].patch_info_map;
if (info.contains(description))
{
info[description].titles[title][serial][app_version].enabled = enabled;
handle_item_selected(item, item);
}
}
}
void patch_manager_dialog::handle_config_value_changed(double value)
{
QList<QTreeWidgetItem*> list = ui->patch_tree->selectedItems();
QTreeWidgetItem* item = list.size() == 1 ? list.first() : nullptr;
if (!item)
{
return;
}
const node_level level = static_cast<node_level>(item->data(0, node_level_role).toInt());
if (level != node_level::patch_level)
{
return;
}
// Fetch the config values of this item
const QString key = ui->configurable_selector->currentText();
const QVariant data = item->data(0, config_values_role);
QVariantMap q_config_values = data.canConvert<QVariantMap>() ? data.toMap() : QVariantMap{};
if (q_config_values.isEmpty() || !q_config_values.contains(key))
{
return;
}
// Fetch the config value for the current key
QVariant& variant = q_config_values[key];
ensure(variant.canConvert<patch_engine::patch_config_value>());
patch_engine::patch_config_value config_value = variant.value<patch_engine::patch_config_value>();
config_value.value = value;
variant = QVariant::fromValue(config_value);
// Set the key first. setData will trigger the itemChanged signal and we don't want to re-create the config widgets each time we set the config values.
item->setData(0, config_key_role, key);
item->setData(0, config_values_role, q_config_values);
// Update the configurable value of the patch for this item
const std::string hash = item->data(0, hash_role).toString().toStdString();
const std::string title = item->data(0, title_role).toString().toStdString();
const std::string serial = item->data(0, serial_role).toString().toStdString();
const std::string app_version = item->data(0, app_version_role).toString().toStdString();
const std::string description = item->data(0, description_role).toString().toStdString();
if (m_map.contains(hash))
{
auto& info = m_map[hash].patch_info_map;
if (info.contains(description))
{
auto& patch = info[description];
auto& config_values = patch.titles[title][serial][app_version].config_values;
for (const QString& q_key : q_config_values.keys())
{
if (const std::string s_key = q_key.toStdString(); key == q_key && patch.default_config_values.contains(s_key))
{
config_values[s_key].value = value;
}
}
}
}
}
void patch_manager_dialog::handle_custom_context_menu_requested(const QPoint &pos)
{
QTreeWidgetItem* item = ui->patch_tree->itemAt(pos);
if (!item)
{
return;
}
const node_level level = static_cast<node_level>(item->data(0, node_level_role).toInt());
QMenu* menu = new QMenu(this);
if (level == node_level::patch_level)
{
// Find the patch for this item and add menu items accordingly
const std::string hash = item->data(0, hash_role).toString().toStdString();
const std::string description = item->data(0, description_role).toString().toStdString();
if (m_map.contains(hash))
{
const auto& container = ::at32(m_map, hash);
if (container.patch_info_map.contains(description))
{
const auto& info = ::at32(container.patch_info_map, description);
QAction* open_filepath = new QAction(tr("Show Patch File"));
menu->addAction(open_filepath);
connect(open_filepath, &QAction::triggered, this, [info](bool)
{
gui::utils::open_dir(info.source_path);
});
menu->addSeparator();
if (info.source_path == patch_engine::get_imported_patch_path())
{
QAction* remove_patch = new QAction(tr("Remove Patch"));
menu->addAction(remove_patch);
connect(remove_patch, &QAction::triggered, this, [info, this](bool)
{
const auto answer = QMessageBox::question(this, tr("Remove Patch?"),
tr("Do you really want to remove the selected patch?\nThis action is immediate and irreversible!"));
if (answer != QMessageBox::StandardButton::Yes)
{
return;
}
if (patch_engine::remove_patch(info))
{
patch_log.success("Successfully removed patch %s: %s from %s", info.hash, info.description, info.source_path);
refresh(); // Refresh before showing the dialog
QMessageBox::information(this, tr("Success"), tr("The patch was successfully removed!"));
}
else
{
patch_log.error("Could not remove patch %s: %s from %s", info.hash, info.description, info.source_path);
refresh(); // Refresh before showing the dialog
QMessageBox::critical(this, tr("Failure"), tr("The patch could not be removed!"));
}
});
menu->addSeparator();
}
}
}
}
if (item->childCount() > 0)
{
if (item->isExpanded())
{
QAction* collapse = new QAction(tr("Collapse"));
menu->addAction(collapse);
connect(collapse, &QAction::triggered, this, [&item](bool)
{
item->setExpanded(false);
});
if (level < (node_level::patch_level - 1))
{
menu->addSeparator();
QAction* expand_children = new QAction(tr("Expand Children"));
menu->addAction(expand_children);
connect(expand_children, &QAction::triggered, this, [&item](bool)
{
for (int i = 0; i < item->childCount(); i++)
{
item->child(i)->setExpanded(true);
}
});
QAction* collapse_children = new QAction(tr("Collapse Children"));
menu->addAction(collapse_children);
connect(collapse_children, &QAction::triggered, this, [&item](bool)
{
for (int i = 0; i < item->childCount(); i++)
{
item->child(i)->setExpanded(false);
}
});
}
}
else
{
QAction* expand = new QAction(tr("Expand"));
menu->addAction(expand);
connect(expand, &QAction::triggered, this, [&item](bool)
{
item->setExpanded(true);
});
}
menu->addSeparator();
}
QAction* expand_all = new QAction(tr("Expand All"));
menu->addAction(expand_all);
connect(expand_all, &QAction::triggered, ui->patch_tree, &QTreeWidget::expandAll);
QAction* collapse_all = new QAction(tr("Collapse All"));
menu->addAction(collapse_all);
connect(collapse_all, &QAction::triggered, ui->patch_tree, &QTreeWidget::collapseAll);
menu->exec(ui->patch_tree->viewport()->mapToGlobal(pos));
}
bool patch_manager_dialog::is_valid_file(const QMimeData& md, QStringList* drop_paths)
{
const QList<QUrl> list = md.urls(); // Get list of all the dropped file urls
if (list.size() != 1) // We only accept one file for now
{
return false;
}
for (auto&& url : list) // Check each file in url list for valid type
{
const QString path = url.toLocalFile(); // Convert url to filepath
const QFileInfo info(path);
if (!info.fileName().endsWith("patch.yml"))
{
return false;
}
if (drop_paths)
{
drop_paths->append(path);
}
}
return true;
}
void patch_manager_dialog::dropEvent(QDropEvent* event)
{
QStringList drop_paths;
if (!is_valid_file(*event->mimeData(), &drop_paths))
{
return;
}
QMessageBox box(QMessageBox::Icon::Question, tr("Patch Manager"), tr("What do you want to do with the patch file?"), QMessageBox::StandardButton::Cancel, this);
QPushButton* button_yes = box.addButton(tr("Import"), QMessageBox::YesRole);
QPushButton* button_no = box.addButton(tr("Validate"), QMessageBox::NoRole);
box.setDefaultButton(button_yes);
box.exec();
const bool do_import = box.clickedButton() == button_yes;
const bool do_validate = do_import || box.clickedButton() == button_no;
if (!do_validate)
{
return;
}
for (const QString& drop_path : drop_paths)
{
const auto path = drop_path.toStdString();
patch_engine::patch_map patches;
std::stringstream log_message;
if (patch_engine::load(patches, path, "", true, &log_message))
{
patch_log.success("Successfully validated patch file %s", path);
if (do_import)
{
static const std::string imported_patch_yml_path = patch_engine::get_imported_patch_path();
log_message.clear();
usz count = 0;
usz total = 0;
if (patch_engine::import_patches(patches, imported_patch_yml_path, count, total, &log_message))
{
refresh();
const std::string message = log_message.str();
const QString msg = message.empty() ? "" : tr("\n\nLog:\n%0").arg(QString::fromStdString(message));
if (count == 0)
{
QMessageBox::warning(this, tr("Nothing to import"), tr("None of the found %0 patches were imported.%1")
.arg(total).arg(msg));
}
else
{
QMessageBox::information(this, tr("Import successful"), tr("Imported %0/%1 patches to:\n%2%3")
.arg(count).arg(total).arg(QString::fromStdString(imported_patch_yml_path)).arg(msg));
}
}
else
{
QMessageBox::critical(this, tr("Import failed"), tr("The patch file could not be imported.\n\nLog:\n%0").arg(QString::fromStdString(log_message.str())));
}
}
else
{
QMessageBox::information(this, tr("Validation successful"), tr("The patch file passed the validation."));
}
}
else
{
patch_log.error("Errors found in patch file %s", path);
QString summary = QString::fromStdString(log_message.str());
if (summary.count(QLatin1Char('\n')) < 5)
{
QMessageBox::critical(this, tr("Validation failed"), tr("Errors were found in the patch file.\n\nLog:\n%0").arg(summary));
}
else
{
QString message = tr("Errors were found in the patch file.");
QMessageBox* mb = new QMessageBox(QMessageBox::Icon::Critical, tr("Validation failed"), message, QMessageBox::Ok, this);
mb->setInformativeText(tr("To see the error log, please click \"Show Details\"."));
mb->setDetailedText(tr("%0").arg(summary));
mb->setAttribute(Qt::WA_DeleteOnClose);
// Smartass hack to make the unresizeable message box wide enough for the changelog
const int log_width = QLabel(summary).sizeHint().width();
while (QLabel(message).sizeHint().width() < log_width)
{
message += " ";
}
mb->setText(message);
mb->show();
}
}
}
}
void patch_manager_dialog::handle_show_owned_games_only(Qt::CheckState state)
{
m_show_owned_games_only = state == Qt::CheckState::Checked;
m_gui_settings->SetValue(gui::pm_show_owned, m_show_owned_games_only);
filter_patches(ui->patch_filter->text());
}
void patch_manager_dialog::dragEnterEvent(QDragEnterEvent* event)
{
if (is_valid_file(*event->mimeData()))
{
event->accept();
}
}
void patch_manager_dialog::dragMoveEvent(QDragMoveEvent* event)
{
if (is_valid_file(*event->mimeData()))
{
event->accept();
}
}
void patch_manager_dialog::dragLeaveEvent(QDragLeaveEvent* event)
{
event->accept();
}
void patch_manager_dialog::download_update(bool automatic, bool auto_accept)
{
patch_log.notice("Patch download triggered (automatic=%d, auto_accept=%d)", automatic, auto_accept);
ui->buttonBox->button(QDialogButtonBox::RestoreDefaults)->setEnabled(false);
m_download_automatic = automatic;
m_download_auto_accept = auto_accept;
const std::string path = patch_engine::get_patches_path() + "patch.yml";
std::string url = "https://rpcs3.net/compatibility?patch&api=v1&v=" + patch_engine_version;
if (fs::is_file(path))
{
if (const fs::file patch_file{path})
{
const std::string hash = sha256_get_hash(patch_file.to_string().c_str(), patch_file.size(), true);
url += "&sha256=" + hash;
}
else
{
patch_log.error("Could not open patch file: %s (%s)", path, fs::g_tls_error);
return;
}
}
m_downloader->start(url, true, !m_download_automatic, tr("Downloading latest patches"));
}
bool patch_manager_dialog::handle_json(const QByteArray& data)
{
const QJsonObject json_data = QJsonDocument::fromJson(data).object();
const int return_code = json_data["return_code"].toInt(-255);
if (return_code < 0)
{
std::string error_message;
switch (return_code)
{
case -1: error_message = "No patches found for the specified version"; break;
case -2: error_message = "Server Error - Maintenance Mode"; break;
case -3: error_message = "Server Error - Illegal Search"; break;
case -255: error_message = "Server Error - Return code not found"; break;
default: error_message = "Server Error - Unknown Error"; break;
}
if (return_code != -1)
patch_log.error("Patch download error: %s return code: %d", error_message, return_code);
else
patch_log.warning("Patch download error: %s return code: %d", error_message, return_code);
return false;
}
if (return_code == 1)
{
patch_log.notice("Patch download: No newer patches found");
if (!m_download_automatic)
{
QMessageBox::information(this, tr("Download successful"), tr("Your patch file is already up to date."));
}
return true;
}
if (return_code != 0)
{
patch_log.error("Patch download error: unknown return code: %d", return_code);
return false;
}
// TODO: check for updates first instead of loading the whole file immediately
if (!m_download_auto_accept)
{
const QMessageBox::StandardButton answer = QMessageBox::question(this, tr("Update patches?"), tr("New patches are available.\n\nDo you want to update?"));
if (answer != QMessageBox::StandardButton::Yes)
{
return true;
}
}
const QJsonValue& version_obj = json_data["version"];
if (!version_obj.isString())
{
patch_log.error("JSON doesn't contain version");
return false;
}
if (const std::string version = version_obj.toString().toStdString();
version != patch_engine_version)
{
patch_log.error("JSON contains wrong version: %s (needed: %s)", version, patch_engine_version);
return false;
}
const QJsonValue& hash_obj = json_data["sha256"];
if (!hash_obj.isString())
{
patch_log.error("JSON doesn't contain sha256");
return false;
}
const QJsonValue& patch = json_data["patch"];
if (!patch.isString() || patch.toString().isEmpty())
{
patch_log.error("JSON doesn't contain patch");
return false;
}
patch_engine::patch_map patches;
std::stringstream log_message;
const std::string content = patch.toString().toStdString();
if (hash_obj.toString().toStdString() != sha256_get_hash(content.c_str(), content.size(), true))
{
patch_log.error("JSON content does not match the provided checksum");
return false;
}
if (patch_engine::load(patches, "From Download", content, true, &log_message))
{
patch_log.notice("Successfully validated downloaded patch file");
const std::string path = patch_engine::get_patches_path() + "patch.yml";
// Back up current patch file if possible
if (fs::is_file(path))
{
if (const std::string back_up_path = path + ".old";
!fs::rename(path, back_up_path, true))
{
patch_log.error("Could not back up current patches to %s (%s)", back_up_path, fs::g_tls_error);
return false;
}
}
// Overwrite current patch file
fs::pending_file patch_file(path);
if (!patch_file.file || (patch_file.file.write(content), !patch_file.commit()))
{
patch_log.error("Could not save new patches to %s (error=%s)", path, fs::g_tls_error);
return false;
}
refresh();
patch_log.success("Successfully downloaded latest patch file");
QMessageBox::information(this, tr("Download successful"), tr("Your patch file is now up to date"));
}
else
{
patch_log.error("Errors found in downloaded patch file");
QString summary = QString::fromStdString(log_message.str());
if (summary.count(QLatin1Char('\n')) < 5)
{
QMessageBox::critical(this, tr("Validation failed"), tr("Errors were found in the downloaded patch file.\n\nLog:\n%0").arg(summary));
}
else
{
QString message = tr("Errors were found in the downloaded patch file.");
QMessageBox* mb = new QMessageBox(QMessageBox::Icon::Critical, tr("Validation failed"), message, QMessageBox::Ok, this);
mb->setInformativeText(tr("To see the error log, please click \"Show Details\"."));
mb->setDetailedText(tr("%0").arg(summary));
mb->setAttribute(Qt::WA_DeleteOnClose);
// Smartass hack to make the unresizeable message box wide enough for the changelog
const int log_width = QLabel(message).sizeHint().width();
while (QLabel(message).sizeHint().width() < log_width)
{
message += " ";
}
mb->setText(message);
mb->show();
}
}
return true;
}
| 42,415
|
C++
|
.cpp
| 1,100
| 35.019091
| 233
| 0.702613
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,057
|
main_window.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/main_window.cpp
|
#include "main_window.h"
#include "qt_utils.h"
#include "vfs_dialog.h"
#include "save_manager_dialog.h"
#include "trophy_manager_dialog.h"
#include "user_manager_dialog.h"
#include "screenshot_manager_dialog.h"
#include "kernel_explorer.h"
#include "game_list_frame.h"
#include "debugger_frame.h"
#include "log_frame.h"
#include "settings_dialog.h"
#include "rpcn_settings_dialog.h"
#include "auto_pause_settings_dialog.h"
#include "cg_disasm_window.h"
#include "log_viewer.h"
#include "memory_viewer_panel.h"
#include "rsx_debugger.h"
#include "about_dialog.h"
#include "pad_settings_dialog.h"
#include "progress_dialog.h"
#include "skylander_dialog.h"
#include "infinity_dialog.h"
#include "dimensions_dialog.h"
#include "cheat_manager.h"
#include "patch_manager_dialog.h"
#include "patch_creator_dialog.h"
#include "pkg_install_dialog.h"
#include "category.h"
#include "gui_settings.h"
#include "input_dialog.h"
#include "camera_settings_dialog.h"
#include "ipc_settings_dialog.h"
#include "shortcut_utils.h"
#include "config_checker.h"
#include "shortcut_dialog.h"
#include "system_cmd_dialog.h"
#include "emulated_pad_settings_dialog.h"
#include "basic_mouse_settings_dialog.h"
#include "raw_mouse_settings_dialog.h"
#include "vfs_tool_dialog.h"
#include "welcome_dialog.h"
#include <thread>
#include <charconv>
#include <unordered_set>
#include <QScreen>
#include <QDirIterator>
#include <QMimeData>
#include <QMessageBox>
#include <QFileDialog>
#include <QFontDatabase>
#include <QBuffer>
#include <QTemporaryFile>
#include <QDesktopServices>
#include "rpcs3_version.h"
#include "Emu/IdManager.h"
#include "Emu/VFS.h"
#include "Emu/vfs_config.h"
#include "Emu/System.h"
#include "Emu/system_utils.hpp"
#include "Emu/system_config.h"
#include "Crypto/unpkg.h"
#include "Crypto/unself.h"
#include "Crypto/unzip.h"
#include "Crypto/decrypt_binaries.h"
#include "Loader/PUP.h"
#include "Loader/TAR.h"
#include "Loader/PSF.h"
#include "Loader/mself.hpp"
#include "Utilities/Thread.h"
#include "util/sysinfo.hpp"
#include "util/serialization_ext.hpp"
#include "Input/gui_pad_thread.h"
#include "ui_main_window.h"
#if QT_CONFIG(permissions)
#include <QGuiApplication>
#include <QPermissions>
#endif
LOG_CHANNEL(gui_log, "GUI");
extern atomic_t<bool> g_user_asked_for_frame_capture;
class CPUDisAsm;
std::shared_ptr<CPUDisAsm> make_basic_ppu_disasm();
inline std::string sstr(const QString& _in) { return _in.toStdString(); }
extern void process_qt_events()
{
if (thread_ctrl::is_main())
{
// NOTE:
// I noticed that calling this from an Emu callback can cause the
// caller to get stuck for a while during newly opened Qt dialogs.
// Adding a timeout here doesn't seem to do anything in that case.
QApplication::processEvents();
}
}
extern void check_microphone_permissions()
{
#if QT_CONFIG(permissions)
Emu.BlockingCallFromMainThread([]()
{
const QMicrophonePermission permission;
switch (qApp->checkPermission(permission))
{
case Qt::PermissionStatus::Undetermined:
gui_log.notice("Requesting microphone permission");
qApp->requestPermission(permission, []()
{
check_microphone_permissions();
});
break;
case Qt::PermissionStatus::Denied:
gui_log.error("RPCS3 has no permissions to access microphones on this device.");
break;
case Qt::PermissionStatus::Granted:
gui_log.notice("Microphone permission granted");
break;
}
});
#endif
}
main_window::main_window(std::shared_ptr<gui_settings> gui_settings, std::shared_ptr<emu_settings> emu_settings, std::shared_ptr<persistent_settings> persistent_settings, QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::main_window)
, m_gui_settings(gui_settings)
, m_emu_settings(std::move(emu_settings))
, m_persistent_settings(std::move(persistent_settings))
, m_updater(nullptr, gui_settings)
{
Q_INIT_RESOURCE(resources);
// We have to setup the ui before using a translation
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
}
main_window::~main_window()
{
}
/* An init method is used so that RPCS3App can create the necessary connects before calling init (specifically the stylesheet connect).
* Simplifies logic a bit.
*/
bool main_window::Init([[maybe_unused]] bool with_cli_boot)
{
setAcceptDrops(true);
// add toolbar widgets (crappy Qt designer is not able to)
ui->toolBar->setObjectName("mw_toolbar");
ui->sizeSlider->setRange(0, gui::gl_max_slider_pos);
ui->toolBar->addWidget(ui->sizeSliderContainer);
ui->toolBar->addWidget(ui->mw_searchbar);
CreateActions();
CreateDockWindows();
CreateConnects();
setMinimumSize(350, minimumSizeHint().height()); // seems fine on win 10
setWindowTitle(QString::fromStdString("RPCS3 " + rpcs3::get_verbose_version()));
Q_EMIT RequestGlobalStylesheetChange();
ConfigureGuiFromSettings();
m_shortcut_handler = new shortcut_handler(gui::shortcuts::shortcut_handler_id::main_window, this, m_gui_settings);
connect(m_shortcut_handler, &shortcut_handler::shortcut_activated, this, &main_window::handle_shortcut);
show(); // needs to be done before creating the thumbnail toolbar
// enable play options if a recent game exists
const bool enable_play_last = !m_recent_game_acts.isEmpty() && m_recent_game_acts.first();
const QString start_tooltip = enable_play_last ? tr("Play %0").arg(m_recent_game_acts.first()->text()) : tr("Play");
if (enable_play_last)
{
ui->sysPauseAct->setText(tr("&Play last played game"));
ui->sysPauseAct->setIcon(m_icon_play);
ui->toolbar_start->setToolTip(start_tooltip);
}
ui->sysPauseAct->setEnabled(enable_play_last);
ui->toolbar_start->setEnabled(enable_play_last);
// create tool buttons for the taskbar thumbnail
#ifdef HAS_QT_WIN_STUFF
m_thumb_bar = new QWinThumbnailToolBar(this);
m_thumb_bar->setWindow(windowHandle());
m_thumb_playPause = new QWinThumbnailToolButton(m_thumb_bar);
m_thumb_playPause->setToolTip(start_tooltip);
m_thumb_playPause->setIcon(m_icon_thumb_play);
m_thumb_playPause->setEnabled(enable_play_last);
m_thumb_stop = new QWinThumbnailToolButton(m_thumb_bar);
m_thumb_stop->setToolTip(tr("Stop"));
m_thumb_stop->setIcon(m_icon_thumb_stop);
m_thumb_stop->setEnabled(false);
m_thumb_restart = new QWinThumbnailToolButton(m_thumb_bar);
m_thumb_restart->setToolTip(tr("Restart"));
m_thumb_restart->setIcon(m_icon_thumb_restart);
m_thumb_restart->setEnabled(false);
m_thumb_bar->addButton(m_thumb_playPause);
m_thumb_bar->addButton(m_thumb_stop);
m_thumb_bar->addButton(m_thumb_restart);
RepaintThumbnailIcons();
connect(m_thumb_stop, &QWinThumbnailToolButton::clicked, this, []()
{
gui_log.notice("User clicked the stop button on thumbnail toolbar");
Emu.GracefulShutdown(false, true);
});
connect(m_thumb_restart, &QWinThumbnailToolButton::clicked, this, []()
{
gui_log.notice("User clicked the restart button on thumbnail toolbar");
Emu.Restart();
});
connect(m_thumb_playPause, &QWinThumbnailToolButton::clicked, this, [this]()
{
gui_log.notice("User clicked the playPause button on thumbnail toolbar");
OnPlayOrPause();
});
#endif
// RPCS3 Updater
QMenu* download_menu = new QMenu(tr("Update Available!"));
QAction* download_action = new QAction(tr("Download Update"), download_menu);
connect(download_action, &QAction::triggered, this, [this]
{
m_updater.update(false);
});
download_menu->addAction(download_action);
#ifdef _WIN32
// Use a menu at the top right corner to indicate the new version.
QMenuBar *corner_bar = new QMenuBar(ui->menuBar);
m_download_menu_action = corner_bar->addMenu(download_menu);
ui->menuBar->setCornerWidget(corner_bar);
ui->menuBar->cornerWidget()->setVisible(false);
#else
// Append a menu to the right of the regular menus to indicate the new version.
// Some distros just can't handle corner widgets at the moment.
m_download_menu_action = ui->menuBar->addMenu(download_menu);
#endif
ensure(m_download_menu_action);
m_download_menu_action->setVisible(false);
connect(&m_updater, &update_manager::signal_update_available, this, [this](bool update_available)
{
if (m_download_menu_action)
{
m_download_menu_action->setVisible(update_available);
}
if (ui->menuBar && ui->menuBar->cornerWidget())
{
ui->menuBar->cornerWidget()->setVisible(update_available);
}
});
#if (!defined(ARCH_ARM64) || defined(__APPLE__)) && (defined(_WIN32) || defined(__linux__) || defined(__APPLE__))
if (const auto update_value = m_gui_settings->GetValue(gui::m_check_upd_start).toString(); update_value != gui::update_off)
{
const bool in_background = with_cli_boot || update_value == gui::update_bkg;
const bool auto_accept = !in_background && update_value == gui::update_auto;
m_updater.check_for_updates(true, in_background, auto_accept, this);
}
#endif
// Disable vsh if not present.
ui->bootVSHAct->setEnabled(fs::is_file(g_cfg_vfs.get_dev_flash() + "vsh/module/vsh.self"));
// Focus to search bar by default
ui->mw_searchbar->setFocus();
// Refresh gamelist last
m_game_list_frame->Refresh(true);
update_gui_pad_thread();
return true;
}
void main_window::update_gui_pad_thread()
{
const bool enabled = m_gui_settings->GetValue(gui::nav_enabled).toBool();
if (enabled && Emu.IsStopped())
{
#if defined(_WIN32) || defined(__linux__) || defined(__APPLE__)
if (!m_gui_pad_thread)
{
m_gui_pad_thread = std::make_unique<gui_pad_thread>();
}
m_gui_pad_thread->update_settings(m_gui_settings);
#endif
}
else
{
m_gui_pad_thread.reset();
}
}
QString main_window::GetCurrentTitle()
{
QString title = qstr(Emu.GetTitleAndTitleID());
if (title.isEmpty())
{
title = qstr(Emu.GetLastBoot());
}
return title;
}
// returns appIcon
QIcon main_window::GetAppIcon() const
{
return m_app_icon;
}
bool main_window::OnMissingFw()
{
const QString title = tr("Missing Firmware Detected!");
const QString message = tr("Commercial games require the firmware (PS3UPDAT.PUP file) to be installed."
"\n<br>For information about how to obtain the required firmware read the <a %0 href=\"https://rpcs3.net/quickstart\">quickstart guide</a>.").arg(gui::utils::get_link_style());
QMessageBox mb(QMessageBox::Question, title, message, QMessageBox::Ok | QMessageBox::Cancel, this, Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowStaysOnTopHint);
mb.setTextFormat(Qt::RichText);
mb.button(QMessageBox::Ok)->setText(tr("Locate PS3UPDAT.PUP"));
if (mb.exec() == QMessageBox::Ok)
{
InstallPup();
return true;
}
return false;
}
void main_window::ResizeIcons(int index)
{
if (ui->sizeSlider->value() != index)
{
ui->sizeSlider->setSliderPosition(index);
return; // ResizeIcons will be triggered again by setSliderPosition, so return here
}
if (m_save_slider_pos)
{
m_save_slider_pos = false;
m_gui_settings->SetValue(m_is_list_mode ? gui::gl_iconSize : gui::gl_iconSizeGrid, index);
// this will also fire when we used the actions, but i didn't want to add another boolean member
SetIconSizeActions(index);
}
m_game_list_frame->ResizeIcons(index);
}
void main_window::handle_shortcut(gui::shortcuts::shortcut shortcut_key, const QKeySequence& key_sequence)
{
gui_log.notice("Main window registered shortcut: %s (%s)", shortcut_key, key_sequence.toString());
const system_state status = Emu.GetStatus();
switch (shortcut_key)
{
case gui::shortcuts::shortcut::mw_toggle_fullscreen:
{
ui->toolbar_fullscreen->trigger();
break;
}
case gui::shortcuts::shortcut::mw_exit_fullscreen:
{
if (isFullScreen())
ui->toolbar_fullscreen->trigger();
break;
}
case gui::shortcuts::shortcut::mw_refresh:
{
m_game_list_frame->Refresh(true);
break;
}
case gui::shortcuts::shortcut::mw_pause:
{
if (status == system_state::running)
Emu.Pause();
break;
}
case gui::shortcuts::shortcut::mw_start:
{
if (status == system_state::paused)
Emu.Resume();
else if (status == system_state::ready)
Emu.Run(true);
break;
}
case gui::shortcuts::shortcut::mw_restart:
{
if (!Emu.GetBoot().empty())
Emu.Restart();
break;
}
case gui::shortcuts::shortcut::mw_stop:
{
if (status != system_state::stopped)
Emu.GracefulShutdown(false, true);
break;
}
default:
{
break;
}
}
}
void main_window::OnPlayOrPause()
{
gui_log.notice("User triggered OnPlayOrPause");
switch (Emu.GetStatus())
{
case system_state::ready: Emu.Run(true); return;
case system_state::paused: Emu.Resume(); return;
case system_state::running: Emu.Pause(); return;
case system_state::stopped:
{
if (m_selected_game)
{
gui_log.notice("Booting from OnPlayOrPause...");
Boot(m_selected_game->info.path, m_selected_game->info.serial);
}
else if (const std::string path = Emu.GetLastBoot(); !path.empty())
{
if (const auto error = Emu.Load(); error != game_boot_result::no_errors)
{
gui_log.error("Boot failed: reason: %s, path: %s", error, path);
show_boot_error(error);
}
}
else if (!m_recent_game_acts.isEmpty())
{
BootRecentAction(m_recent_game_acts.first());
}
return;
}
case system_state::starting: break;
default: fmt::throw_exception("Unreachable");
}
}
void main_window::show_boot_error(game_boot_result status)
{
QString message;
switch (status)
{
case game_boot_result::nothing_to_boot:
message = tr("No bootable content was found.");
break;
case game_boot_result::wrong_disc_location:
message = tr("Disc could not be mounted properly. Make sure the disc is not in the dev_hdd0/game folder.");
break;
case game_boot_result::invalid_file_or_folder:
message = tr("The selected file or folder is invalid or corrupted.");
break;
case game_boot_result::invalid_bdvd_folder:
message = tr("The virtual dev_bdvd folder does not exist or is not empty.");
break;
case game_boot_result::install_failed:
message = tr("Additional content could not be installed.");
break;
case game_boot_result::decryption_error:
message = tr("Digital content could not be decrypted. This is usually caused by a missing or invalid license (RAP) file.");
break;
case game_boot_result::file_creation_error:
message = tr("The emulator could not create files required for booting.");
break;
case game_boot_result::unsupported_disc_type:
message = tr("This disc type is not supported yet.");
break;
case game_boot_result::savestate_corrupted:
message = tr("Savestate data is corrupted or it's not an RPCS3 savestate.");
break;
case game_boot_result::savestate_version_unsupported:
message = tr("Savestate versioning data differs from your RPCS3 build.");
break;
case game_boot_result::still_running:
message = tr("A game or PS3 application is still running or has yet to be fully stopped.");
break;
case game_boot_result::firmware_missing: // Handled elsewhere
case game_boot_result::already_added: // Handled elsewhere
case game_boot_result::no_errors:
return;
case game_boot_result::generic_error:
message = tr("Unknown error.");
break;
}
const QString link = tr("<br /><br />For information on setting up the emulator and dumping your PS3 games, read the <a %0 href=\"https://rpcs3.net/quickstart\">quickstart guide</a>.").arg(gui::utils::get_link_style());
QMessageBox msg;
msg.setWindowTitle(tr("Boot Failed"));
msg.setIcon(QMessageBox::Critical);
msg.setTextFormat(Qt::RichText);
msg.setStandardButtons(QMessageBox::Ok);
msg.setText(tr("Booting failed: %1 %2").arg(message).arg(link));
msg.exec();
}
void main_window::Boot(const std::string& path, const std::string& title_id, bool direct, bool refresh_list, cfg_mode config_mode, const std::string& config_path)
{
if (!m_gui_settings->GetBootConfirmation(this, gui::ib_confirm_boot))
{
return;
}
Emu.GracefulShutdown(false);
m_app_icon = gui::utils::get_app_icon_from_path(path, title_id);
if (const auto error = Emu.BootGame(path, title_id, direct, config_mode, config_path); error != game_boot_result::no_errors)
{
gui_log.error("Boot failed: reason: %s, path: %s", error, path);
show_boot_error(error);
}
else
{
gui_log.success("Boot successful.");
AddRecentAction(gui::Recent_Game(qstr(Emu.GetBoot()), qstr(Emu.GetTitleAndTitleID())));
if (refresh_list)
{
m_game_list_frame->Refresh(true);
}
}
}
void main_window::BootElf()
{
bool stopped = false;
if (Emu.IsRunning())
{
Emu.Pause();
stopped = true;
}
const QString path_last_elf = m_gui_settings->GetValue(gui::fd_boot_elf).toString();
const QString file_path = QFileDialog::getOpenFileName(this, tr("Select (S)ELF To Boot"), path_last_elf, tr(
"(S)ELF files (*BOOT.BIN *.elf *.self);;"
"ELF files (BOOT.BIN *.elf);;"
"SELF files (EBOOT.BIN *.self);;"
"BOOT files (*BOOT.BIN);;"
"BIN files (*.bin);;"
"All executable files (*.SAVESTAT.zst *.SAVESTAT.gz *.SAVESTAT *.sprx *.SPRX *.self *.SELF *.bin *.BIN *.prx *.PRX *.elf *.ELF *.o *.O);;"
"All files (*.*)"),
Q_NULLPTR, QFileDialog::DontResolveSymlinks);
if (file_path.isEmpty())
{
if (stopped)
{
Emu.Resume();
}
return;
}
// If we resolved the filepath earlier we would end up setting the last opened dir to the unwanted
// game folder in case of having e.g. a Game Folder with collected links to elf files.
// Don't set last path earlier in case of cancelled dialog
m_gui_settings->SetValue(gui::fd_boot_elf, file_path);
const std::string path = sstr(QFileInfo(file_path).absoluteFilePath());
gui_log.notice("Booting from BootElf...");
Boot(path, "", true, true);
}
void main_window::BootTest()
{
bool stopped = false;
if (Emu.IsRunning())
{
Emu.Pause();
stopped = true;
}
#ifdef _WIN32
const QString path_tests = QString::fromStdString(fs::get_config_dir()) + "/test/";
#elif defined(__linux__)
const QString path_tests = QCoreApplication::applicationDirPath() + "/../share/rpcs3/test/";
#else
const QString path_tests = QCoreApplication::applicationDirPath() + "/../Resources/test/";
#endif
const QString file_path = QFileDialog::getOpenFileName(this, tr("Select (S)ELF To Boot"), path_tests, tr(
"(S)ELF files (*.elf *.self);;"
"ELF files (*.elf);;"
"SELF files (*.self);;"
"All files (*.*)"),
Q_NULLPTR, QFileDialog::DontResolveSymlinks);
if (file_path.isEmpty())
{
if (stopped)
{
Emu.Resume();
}
return;
}
const std::string path = sstr(QFileInfo(file_path).absoluteFilePath());
gui_log.notice("Booting from BootTest...");
Boot(path, "", true);
}
void main_window::BootSavestate()
{
bool stopped = false;
if (Emu.IsRunning())
{
Emu.Pause();
stopped = true;
}
const QString file_path = QFileDialog::getOpenFileName(this, tr("Select Savestate To Boot"), qstr(fs::get_config_dir() + "savestates/"), tr(
"Savestate files (*.SAVESTAT *.SAVESTAT.zst *.SAVESTAT.gz);;"
"All files (*.*)"),
Q_NULLPTR, QFileDialog::DontResolveSymlinks);
if (file_path.isEmpty())
{
if (stopped)
{
Emu.Resume();
}
return;
}
const std::string path = sstr(QFileInfo(file_path).absoluteFilePath());
gui_log.notice("Booting from BootSavestate...");
Boot(path, "", true);
}
void main_window::BootGame()
{
bool stopped = false;
if (Emu.IsRunning())
{
Emu.Pause();
stopped = true;
}
const QString path_last_game = m_gui_settings->GetValue(gui::fd_boot_game).toString();
const QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Game Folder"), path_last_game, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (dir_path.isEmpty())
{
if (stopped)
{
Emu.Resume();
}
return;
}
m_gui_settings->SetValue(gui::fd_boot_game, QFileInfo(dir_path).path());
gui_log.notice("Booting from BootGame...");
Boot(sstr(dir_path), "", false, true);
}
void main_window::BootVSH()
{
gui_log.notice("Booting from BootVSH...");
Boot(g_cfg_vfs.get_dev_flash() + "/vsh/module/vsh.self");
}
void main_window::BootRsxCapture(std::string path)
{
if (path.empty())
{
bool is_stopped = false;
if (Emu.IsRunning())
{
Emu.Pause();
is_stopped = true;
}
const QString file_path = QFileDialog::getOpenFileName(this, tr("Select RSX Capture"), qstr(fs::get_config_dir() + "captures/"), tr("RRC files (*.rrc *.RRC *.rrc.gz *.RRC.GZ);;All files (*.*)"));
if (file_path.isEmpty())
{
if (is_stopped)
{
Emu.Resume();
}
return;
}
path = sstr(file_path);
}
if (!m_gui_settings->GetBootConfirmation(this))
{
return;
}
Emu.GracefulShutdown(false);
if (!Emu.BootRsxCapture(path))
{
gui_log.error("Capture Boot Failed. path: %s", path);
}
else
{
gui_log.success("Capture Boot Success. path: %s", path);
}
}
bool main_window::InstallFileInExData(const std::string& extension, const QString& path, const std::string& filename)
{
if (path.isEmpty() || filename.empty() || extension.empty())
{
return false;
}
// Copy file atomically with thread/process-safe error checking for file size
const std::string to_path = rpcs3::utils::get_hdd0_dir() + "/home/" + Emu.GetUsr() + "/exdata/" + filename.substr(0, filename.find_last_of('.'));
fs::pending_file to(to_path + "." + extension);
fs::file from(sstr(path));
if (!to.file || !from)
{
return false;
}
to.file.write(from.to_vector<u8>());
from.close();
if (to.file.size() < 0x10)
{
// Not a RAP file
return false;
}
#ifdef _WIN32
// In the case of an unexpected crash during the operation, the temporary file can be used as the deleted file
// See below
to.file.sync();
// In case we want to rename upper-case file to lower-case
// Windows will ignore such rename operation if the file exists
// So delete it
fs::remove_file(to_path + "." + fmt::to_upper(extension));
#endif
return to.commit();
}
bool main_window::InstallPackages(QStringList file_paths, bool from_boot)
{
if (file_paths.isEmpty())
{
ensure(!from_boot);
// If this function was called without a path, ask the user for files to install.
const QString path_last_pkg = m_gui_settings->GetValue(gui::fd_install_pkg).toString();
const QStringList paths = QFileDialog::getOpenFileNames(this, tr("Select packages and/or rap files to install"),
path_last_pkg, tr("All relevant (*.pkg *.PKG *.rap *.RAP *.edat *.EDAT);;Package files (*.pkg *.PKG);;Rap files (*.rap *.RAP);;Edat files (*.edat *.EDAT);;All files (*.*)"));
if (paths.isEmpty())
{
return true;
}
file_paths.append(paths);
const QFileInfo file_info(file_paths[0]);
m_gui_settings->SetValue(gui::fd_install_pkg, file_info.path());
}
if (file_paths.count() == 1)
{
const QString file_path = file_paths.front();
const QFileInfo file_info(file_path);
if (file_info.isDir())
{
gui_log.notice("PKG: Trying to install packages from dir: '%s'", file_path);
const QDir dir(file_path);
const QStringList dir_file_paths = gui::utils::get_dir_entries(dir, {}, true);
if (dir_file_paths.empty())
{
gui_log.notice("PKG: Could not find any files in dir: '%s'", file_path);
return true;
}
return InstallPackages(dir_file_paths, from_boot);
}
if (file_info.suffix().compare("pkg", Qt::CaseInsensitive) == 0)
{
compat::package_info info = game_compatibility::GetPkgInfo(file_path, m_game_list_frame ? m_game_list_frame->GetGameCompatibility() : nullptr);
if (!info.is_valid)
{
QMessageBox::warning(this, tr("Invalid package!"), tr("The selected package is invalid!\n\nPath:\n%0").arg(file_path));
return false;
}
if (info.type != compat::package_type::other)
{
if (info.type == compat::package_type::dlc)
{
info.local_cat = tr("\nDLC", "Block for package type (DLC)");
}
else
{
info.local_cat = tr("\nUpdate", "Block for package type (Update)");
}
}
else if (!info.local_cat.isEmpty())
{
info.local_cat = tr("\n%0", "Block for package type").arg(info.local_cat);
}
if (!info.title_id.isEmpty())
{
info.title_id = tr("\n%0", "Block for Title ID").arg(info.title_id);
}
if (!info.version.isEmpty())
{
info.version = tr("\nVersion %0", "Block for Version").arg(info.version);
}
if (!info.changelog.isEmpty())
{
info.changelog = tr("Changelog:\n%0", "Block for Changelog").arg(info.changelog);
}
const QString info_string = QStringLiteral("%0\n\n%1%2%3%4").arg(file_info.fileName()).arg(info.title).arg(info.local_cat).arg(info.title_id).arg(info.version);
QString message = tr("Do you want to install this package?\n\n%0").arg(info_string);
QMessageBox mb(QMessageBox::Icon::Question, tr("PKG Decrypter / Installer"), message, QMessageBox::Yes | QMessageBox::No, this);
mb.setDefaultButton(QMessageBox::No);
if (!info.changelog.isEmpty())
{
mb.setInformativeText(tr("To see the changelog, please click \"Show Details\"."));
mb.setDetailedText(tr("%0").arg(info.changelog));
// Smartass hack to make the unresizeable message box wide enough for the changelog
const int log_width = QLabel(info.changelog).sizeHint().width();
while (QLabel(message).sizeHint().width() < log_width)
{
message += " ";
}
mb.setText(message);
}
if (mb.exec() != QMessageBox::Yes)
{
gui_log.notice("PKG: Cancelled installation from drop.\n%s\n%s", info_string, info.changelog);
return true;
}
}
}
// Install rap files if available
int installed_rap_and_edat_count = 0;
const auto install_filetype = [&installed_rap_and_edat_count, &file_paths](const std::string extension)
{
const QString pattern = QString(".*\\.%1").arg(QString::fromStdString(extension));
for (const QString& file : file_paths.filter(QRegularExpression(pattern, QRegularExpression::PatternOption::CaseInsensitiveOption)))
{
const QFileInfo file_info(file);
const std::string filename = sstr(file_info.fileName());
if (InstallFileInExData(extension, file, filename))
{
gui_log.success("Successfully copied %s file: %s", extension, filename);
installed_rap_and_edat_count++;
}
else
{
gui_log.error("Could not copy %s file: %s", extension, filename);
}
}
};
if (!from_boot)
{
if (!m_gui_settings->GetBootConfirmation(this))
{
// Last chance to cancel the operation
return true;
}
if (!Emu.IsStopped())
{
Emu.GracefulShutdown(false);
}
install_filetype("rap");
install_filetype("edat");
}
if (installed_rap_and_edat_count > 0)
{
// Refresh game list since we probably unlocked some games now.
m_game_list_frame->Refresh(true);
}
// Find remaining package files
file_paths = file_paths.filter(QRegularExpression(".*\\.pkg", QRegularExpression::PatternOption::CaseInsensitiveOption));
if (file_paths.isEmpty())
{
return true;
}
if (from_boot)
{
return HandlePackageInstallation(file_paths, true);
}
// Handle further installations with a timeout. Otherwise the source explorer instance is not usable during the following file processing.
QTimer::singleShot(0, [this, paths = std::move(file_paths)]()
{
HandlePackageInstallation(paths, false);
});
return true;
}
bool main_window::HandlePackageInstallation(QStringList file_paths, bool from_boot)
{
if (file_paths.empty())
{
return false;
}
std::vector<compat::package_info> packages;
game_compatibility* compat = m_game_list_frame ? m_game_list_frame->GetGameCompatibility() : nullptr;
if (file_paths.size() > 1)
{
// Let the user choose the packages to install and select the order in which they shall be installed.
pkg_install_dialog dlg(file_paths, compat, this);
connect(&dlg, &QDialog::accepted, this, [&packages, &dlg]()
{
packages = dlg.GetPathsToInstall();
});
dlg.exec();
}
else
{
packages.push_back(game_compatibility::GetPkgInfo(file_paths.front(), compat));
}
if (packages.empty())
{
return true;
}
if (!from_boot)
{
if (!m_gui_settings->GetBootConfirmation(this))
{
return true;
}
Emu.GracefulShutdown(false);
}
std::vector<std::string> path_vec;
for (const compat::package_info& pkg : packages)
{
path_vec.push_back(pkg.path.toStdString());
}
gui_log.notice("About to install packages:\n%s", fmt::merge(path_vec, "\n"));
progress_dialog pdlg(tr("RPCS3 Package Installer"), tr("Installing package, please wait..."), tr("Cancel"), 0, 1000, false, this);
pdlg.setAutoClose(false);
pdlg.show();
package_install_result result = {};
auto get_app_info = [](compat::package_info& package)
{
QString app_info = package.title; // This should always be non-empty
if (!package.title_id.isEmpty() || !package.version.isEmpty())
{
app_info += QStringLiteral("\n");
if (!package.title_id.isEmpty())
{
app_info += package.title_id;
}
if (!package.version.isEmpty())
{
if (!package.title_id.isEmpty())
{
app_info += " ";
}
app_info += tr("v.%0", "Package version for install progress dialog").arg(package.version);
}
}
return app_info;
};
bool cancelled = false;
std::deque<package_reader> readers;
for (const compat::package_info& info : packages)
{
readers.emplace_back(sstr(info.path));
}
std::deque<std::string> bootable_paths;
// Run PKG unpacking asynchronously
named_thread worker("PKG Installer", [&readers, &result, &bootable_paths]
{
result = package_reader::extract_data(readers, bootable_paths);
return result.error == package_install_result::error_type::no_error;
});
pdlg.show();
// Wait for the completion
for (usz i = 0, set_text = umax; i < readers.size() && result.error == package_install_result::error_type::no_error;)
{
std::this_thread::sleep_for(5ms);
if (pdlg.wasCanceled())
{
cancelled = true;
for (package_reader& reader : readers)
{
reader.abort_extract();
}
break;
}
// Update progress window
const int progress = readers[i].get_progress(pdlg.maximum());
pdlg.SetValue(progress);
if (set_text != i)
{
pdlg.setLabelText(tr("Installing package (%0/%1), please wait...\n\n%2").arg(i + 1).arg(readers.size()).arg(get_app_info(packages[i])));
set_text = i;
}
QCoreApplication::processEvents();
if (progress == pdlg.maximum())
{
i++;
}
}
const bool success = worker();
if (success)
{
pdlg.SetValue(pdlg.maximum());
const u64 start_time = get_system_time();
for (usz i = 0; i < packages.size(); i++)
{
const compat::package_info& package = ::at32(packages, i);
const package_reader& reader = ::at32(readers, i);
switch (reader.get_result())
{
case package_reader::result::success:
{
gui_log.success("Successfully installed %s (title_id=%s, title=%s, version=%s).", package.path, package.title_id, package.title, package.version);
break;
}
case package_reader::result::not_started:
case package_reader::result::started:
case package_reader::result::aborted:
{
gui_log.notice("Aborted installation of %s (title_id=%s, title=%s, version=%s).", package.path, package.title_id, package.title, package.version);
break;
}
case package_reader::result::error:
{
gui_log.error("Failed to install %s (title_id=%s, title=%s, version=%s).", package.path, package.title_id, package.title, package.version);
break;
}
case package_reader::result::aborted_dirty:
case package_reader::result::error_dirty:
{
gui_log.error("Partially installed %s (title_id=%s, title=%s, version=%s).", package.path, package.title_id, package.title, package.version);
break;
}
}
}
std::map<std::string, QString> bootable_paths_installed; // -> title id
for (usz index = 0; index < bootable_paths.size(); index++)
{
if (bootable_paths[index].empty())
{
continue;
}
bootable_paths_installed[bootable_paths[index]] = packages[index].title_id;
}
// Need to test here due to potential std::move later
const bool installed_a_whole_package_without_new_software = bootable_paths_installed.empty() && !cancelled;
if (!bootable_paths_installed.empty())
{
m_game_list_frame->AddRefreshedSlot([this, paths = std::move(bootable_paths_installed)](std::set<std::string>& claimed_paths) mutable
{
// Try to claim operaions on ID
for (auto it = paths.begin(); it != paths.end();)
{
std::string resolved_path = Emu.GetCallbacks().resolve_path(it->first);
if (resolved_path.empty() || claimed_paths.count(resolved_path))
{
it = paths.erase(it);
}
else
{
claimed_paths.emplace(std::move(resolved_path));
it++;
}
}
ShowOptionalGamePreparations(tr("Success!"), tr("Successfully installed software from package(s)!"), std::move(paths));
});
}
m_game_list_frame->Refresh(true);
std::this_thread::sleep_for(std::chrono::microseconds(100'000 - std::min<usz>(100'000, get_system_time() - start_time)));
pdlg.hide();
if (installed_a_whole_package_without_new_software)
{
m_gui_settings->ShowInfoBox(tr("Success!"), tr("Successfully installed software from package(s)!"), gui::ib_pkg_success, this);
}
}
else
{
pdlg.hide();
pdlg.SignalFailure();
if (!cancelled)
{
const compat::package_info* package = nullptr;
for (usz i = 0; i < readers.size() && !package; i++)
{
// Figure out what package failed the installation
switch (readers[i].get_result())
{
case package_reader::result::success:
case package_reader::result::not_started:
case package_reader::result::started:
case package_reader::result::aborted:
case package_reader::result::aborted_dirty:
break;
case package_reader::result::error:
case package_reader::result::error_dirty:
package = &packages[i];
break;
}
}
ensure(package);
if (result.error == package_install_result::error_type::app_version)
{
gui_log.error("Cannot install %s.", package->path);
const bool has_expected = !result.version.expected.empty();
const bool has_found = !result.version.found.empty();
if (has_expected && has_found)
{
QMessageBox::warning(this, tr("Warning!"), tr("Package cannot be installed on top of the current data.\nUpdate is for version %1, but you have version %2.\n\nTried to install: %3")
.arg(QString::fromStdString(result.version.expected)).arg(QString::fromStdString(result.version.found)).arg(package->path));
}
else if (has_expected)
{
QMessageBox::warning(this, tr("Warning!"), tr("Package cannot be installed on top of the current data.\nUpdate is for version %1, but you don't have any data installed.\n\nTried to install: %2")
.arg(QString::fromStdString(result.version.expected)).arg(package->path));
}
else
{
// probably unreachable
const QString found = has_found ? tr("version %1").arg(QString::fromStdString(result.version.found)) : tr("no data installed");
QMessageBox::warning(this, tr("Warning!"), tr("Package cannot be installed on top of the current data.\nUpdate is for unknown version, but you have version %1.\n\nTried to install: %2")
.arg(QString::fromStdString(result.version.expected)).arg(found).arg(package->path));
}
}
else
{
gui_log.error("Failed to install %s.", package->path);
QMessageBox::critical(this, tr("Failure!"), tr("Failed to install software from package:\n%1!"
"\nThis is very likely caused by external interference from a faulty anti-virus software."
"\nPlease add RPCS3 to your anti-virus\' whitelist or use better anti-virus software.").arg(package->path));
}
}
}
return success;
}
void main_window::ExtractMSELF()
{
const QString path_last_mself = m_gui_settings->GetValue(gui::fd_ext_mself).toString();
const QString file_path = QFileDialog::getOpenFileName(this, tr("Select MSELF To extract"), path_last_mself, tr("All mself files (*.mself *.MSELF);;All files (*.*)"));
if (file_path.isEmpty())
{
return;
}
const QString dir = QFileDialog::getExistingDirectory(this, tr("Extraction Directory"), QString{}, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (!dir.isEmpty())
{
m_gui_settings->SetValue(gui::fd_ext_mself, QFileInfo(file_path).path());
extract_mself(sstr(file_path), sstr(dir) + '/');
}
}
void main_window::InstallPup(QString file_path)
{
if (file_path.isEmpty())
{
const QString path_last_pup = m_gui_settings->GetValue(gui::fd_install_pup).toString();
file_path = QFileDialog::getOpenFileName(this, tr("Select PS3UPDAT.PUP To Install"), path_last_pup, tr("PS3 update file (PS3UPDAT.PUP);;All pup files (*.pup *.PUP);;All files (*.*)"));
}
else
{
if (QMessageBox::question(this, tr("RPCS3 Firmware Installer"), tr("Install firmware: %1?").arg(file_path),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
{
gui_log.notice("Firmware: Cancelled installation from drop. File: %s", file_path);
return;
}
}
if (!file_path.isEmpty())
{
// Handle the actual installation with a timeout. Otherwise the source explorer instance is not usable during the following file processing.
QTimer::singleShot(0, [this, file_path]()
{
HandlePupInstallation(file_path);
});
}
}
void main_window::ExtractPup()
{
const QString path_last_pup = m_gui_settings->GetValue(gui::fd_install_pup).toString();
const QString file_path = QFileDialog::getOpenFileName(this, tr("Select PS3UPDAT.PUP To extract"), path_last_pup, tr("PS3 update file (PS3UPDAT.PUP);;All pup files (*.pup *.PUP);;All files (*.*)"));
if (file_path.isEmpty())
{
return;
}
const QString dir = QFileDialog::getExistingDirectory(this, tr("Extraction Directory"), QString{}, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (!dir.isEmpty())
{
HandlePupInstallation(file_path, dir);
}
}
void main_window::ExtractTar()
{
if (!m_gui_settings->GetBootConfirmation(this))
{
return;
}
Emu.GracefulShutdown(false);
const QString path_last_tar = m_gui_settings->GetValue(gui::fd_ext_tar).toString();
QStringList files = QFileDialog::getOpenFileNames(this, tr("Select TAR To extract"), path_last_tar, tr("All tar files (*.tar *.TAR *.tar.aa.* *.TAR.AA.*);;All files (*.*)"));
if (files.isEmpty())
{
return;
}
const QString dir = QFileDialog::getExistingDirectory(this, tr("Extraction Directory"), QString{}, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (dir.isEmpty())
{
return;
}
m_gui_settings->SetValue(gui::fd_ext_tar, QFileInfo(files[0]).path());
progress_dialog pdlg(tr("TAR Extraction"), tr("Extracting encrypted TARs\nPlease wait..."), tr("Cancel"), 0, files.size(), false, this);
pdlg.show();
QString error;
for (const QString& file : files)
{
if (pdlg.wasCanceled())
{
break;
}
// Do not abort on failure here, in case the user selected a wrong file in multi-selection while the rest are valid
if (!extract_tar(sstr(file), sstr(dir) + '/'))
{
if (error.isEmpty())
{
error = tr("The following TAR file(s) could not be extracted:");
}
error += "\n";
error += file;
}
pdlg.SetValue(pdlg.value() + 1);
QApplication::processEvents();
}
if (!error.isEmpty())
{
pdlg.hide();
QMessageBox::critical(this, tr("TAR extraction failed"), error);
}
}
void main_window::HandlePupInstallation(const QString& file_path, const QString& dir_path)
{
const auto critical = [this](QString str)
{
Emu.CallFromMainThread([this, str = std::move(str)]()
{
QMessageBox::critical(this, tr("Firmware Installation Failed"), str);
}, nullptr, false);
};
if (file_path.isEmpty())
{
gui_log.error("Error while installing firmware: provided path is empty.");
critical(tr("Firmware installation failed: The provided path is empty."));
return;
}
if (!m_gui_settings->GetBootConfirmation(this))
{
return;
}
Emu.GracefulShutdown(false);
m_gui_settings->SetValue(gui::fd_install_pup, QFileInfo(file_path).path());
const std::string path = sstr(file_path);
fs::file pup_f(path);
if (!pup_f)
{
gui_log.error("Error opening PUP file %s (%s)", path, fs::g_tls_error);
critical(tr("Firmware installation failed: The selected firmware file couldn't be opened."));
return;
}
pup_object pup(std::move(pup_f));
switch (pup.operator pup_error())
{
case pup_error::header_read:
{
gui_log.error("%s", pup.get_formatted_error());
critical(tr("Firmware installation failed: The provided file is empty."));
return;
}
case pup_error::header_magic:
{
gui_log.error("Error while installing firmware: provided file is not a PUP file.");
critical(tr("Firmware installation failed: The provided file is not a PUP file."));
return;
}
case pup_error::expected_size:
{
gui_log.error("%s", pup.get_formatted_error());
critical(tr("Firmware installation failed: The provided file is incomplete. Try redownloading it."));
return;
}
case pup_error::header_file_count:
case pup_error::file_entries:
case pup_error::stream:
{
std::string error = "Error while installing firmware: PUP file is invalid.";
if (!pup.get_formatted_error().empty())
{
fmt::append(error, "\n%s", pup.get_formatted_error());
}
gui_log.error("%s", error);
critical(tr("Firmware installation failed: The provided file is corrupted."));
return;
}
case pup_error::hash_mismatch:
{
gui_log.error("Error while installing firmware: Hash check failed.");
critical(tr("Firmware installation failed: The provided file's contents are corrupted."));
return;
}
case pup_error::ok: break;
}
fs::file update_files_f = pup.get_file(0x300);
const usz update_files_size = update_files_f ? update_files_f.size() : 0;
if (!update_files_size)
{
gui_log.error("Error while installing firmware: Couldn't find installation packages database.");
critical(tr("Firmware installation failed: The provided file's contents are corrupted."));
return;
}
fs::device_stat dev_stat{};
if (!fs::statfs(g_cfg_vfs.get_dev_flash(), dev_stat))
{
gui_log.error("Error while installing firmware: Couldn't retrieve available disk space. ('%s')", g_cfg_vfs.get_dev_flash());
critical(tr("Firmware installation failed: Couldn't retrieve available disk space."));
return;
}
if (dev_stat.avail_free < update_files_size)
{
gui_log.error("Error while installing firmware: Out of disk space. ('%s', needed: %d bytes)", g_cfg_vfs.get_dev_flash(), update_files_size - dev_stat.avail_free);
critical(tr("Firmware installation failed: Out of disk space."));
return;
}
tar_object update_files(update_files_f);
if (!dir_path.isEmpty())
{
// Extract only mode, extract direct TAR entries to a user directory
if (!vfs::mount("/pup_extract", sstr(dir_path) + '/'))
{
gui_log.error("Error while extracting firmware: Failed to mount '%s'", dir_path);
critical(tr("Firmware extraction failed: VFS mounting failed."));
return;
}
if (!update_files.extract("/pup_extract", true))
{
gui_log.error("Error while installing firmware: TAR contents are invalid.");
critical(tr("Firmware installation failed: Firmware contents could not be extracted."));
}
gui_log.success("Extracted PUP file to %s", dir_path);
return;
}
// In regular installation we select specfic entries from the main TAR which are prefixed with "dev_flash_"
// Those entries are TAR as well, we extract their packed files from them and that's what installed in /dev_flash
auto update_filenames = update_files.get_filenames();
update_filenames.erase(std::remove_if(
update_filenames.begin(), update_filenames.end(), [](const std::string& s) { return s.find("dev_flash_") == umax; }),
update_filenames.end());
if (update_filenames.empty())
{
gui_log.error("Error while installing firmware: No dev_flash_* packages were found.");
critical(tr("Firmware installation failed: The provided file's contents are corrupted."));
return;
}
static constexpr std::string_view cur_version = "4.91";
std::string version_string;
if (fs::file version = pup.get_file(0x100))
{
version_string = version.to_string();
}
if (const usz version_pos = version_string.find('\n'); version_pos != umax)
{
version_string.erase(version_pos);
}
if (version_string.empty())
{
gui_log.error("Error while installing firmware: No version data was found.");
critical(tr("Firmware installation failed: The provided file's contents are corrupted."));
return;
}
if (version_string < cur_version &&
QMessageBox::question(this, tr("RPCS3 Firmware Installer"), tr("Old firmware detected.\nThe newest firmware version is %1 and you are trying to install version %2\nContinue installation?").arg(QString::fromUtf8(cur_version.data(), ::size32(cur_version)), qstr(version_string)),
QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::No)
{
return;
}
if (const std::string installed = utils::get_firmware_version(); !installed.empty())
{
gui_log.warning("Reinstalling firmware: old=%s, new=%s", installed, version_string);
if (QMessageBox::question(this, tr("RPCS3 Firmware Installer"), tr("Firmware of version %1 has already been installed.\nOverwrite current installation with version %2?").arg(qstr(installed), qstr(version_string)),
QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::No)
{
gui_log.warning("Reinstallation of firmware aborted.");
return;
}
}
// Remove possibly PS3 fonts from database
QFontDatabase::removeAllApplicationFonts();
progress_dialog pdlg(tr("RPCS3 Firmware Installer"), tr("Installing firmware version %1\nPlease wait...").arg(qstr(version_string)), tr("Cancel"), 0, static_cast<int>(update_filenames.size()), false, this);
pdlg.show();
// Used by tar_object::extract() as destination directory
vfs::mount("/dev_flash", g_cfg_vfs.get_dev_flash());
// Synchronization variable
atomic_t<uint> progress(0);
{
// Run asynchronously
named_thread worker("Firmware Installer", [&]
{
for (const auto& update_filename : update_filenames)
{
auto update_file_stream = update_files.get_file(update_filename);
if (update_file_stream->m_file_handler)
{
// Forcefully read all the data
update_file_stream->m_file_handler->handle_file_op(*update_file_stream, 0, update_file_stream->get_size(umax), nullptr);
}
fs::file update_file = fs::make_stream(std::move(update_file_stream->data));
SCEDecrypter self_dec(update_file);
self_dec.LoadHeaders();
self_dec.LoadMetadata(SCEPKG_ERK, SCEPKG_RIV);
self_dec.DecryptData();
auto dev_flash_tar_f = self_dec.MakeFile();
if (dev_flash_tar_f.size() < 3)
{
gui_log.error("Error while installing firmware: PUP contents are invalid.");
critical(tr("Firmware installation failed: Firmware could not be decompressed"));
progress = -1;
return;
}
tar_object dev_flash_tar(dev_flash_tar_f[2]);
if (!dev_flash_tar.extract())
{
gui_log.error("Error while installing firmware: TAR contents are invalid. (package=%s)", update_filename);
critical(tr("The firmware contents could not be extracted."
"\nThis is very likely caused by external interference from a faulty anti-virus software."
"\nPlease add RPCS3 to your anti-virus\' whitelist or use better anti-virus software."));
progress = -1;
return;
}
if (!progress.try_inc(::narrow<uint>(update_filenames.size())))
{
// Installation was cancelled
return;
}
}
});
// Wait for the completion
for (uint value = progress.load(); value < update_filenames.size(); std::this_thread::sleep_for(5ms), value = progress)
{
if (pdlg.wasCanceled())
{
progress = -1;
break;
}
// Update progress window
pdlg.SetValue(static_cast<int>(value));
QCoreApplication::processEvents();
}
// Join thread
worker();
}
update_files_f.close();
if (progress == update_filenames.size())
{
pdlg.SetValue(pdlg.maximum());
std::this_thread::sleep_for(100ms);
}
// Update with newly installed PS3 fonts
Q_EMIT RequestGlobalStylesheetChange();
// Unmount
Emu.Init();
if (progress == update_filenames.size())
{
ui->bootVSHAct->setEnabled(fs::is_file(g_cfg_vfs.get_dev_flash() + "/vsh/module/vsh.self"));
gui_log.success("Successfully installed PS3 firmware version %s.", version_string);
m_gui_settings->ShowInfoBox(tr("Success!"), tr("Successfully installed PS3 firmware and LLE Modules!"), gui::ib_pup_success, this);
CreateFirmwareCache();
}
}
void main_window::DecryptSPRXLibraries()
{
QString path_last_sprx = m_gui_settings->GetValue(gui::fd_decrypt_sprx).toString();
if (!fs::is_dir(sstr(path_last_sprx)))
{
// Default: redirect to userland firmware SPRX directory
path_last_sprx = qstr(g_cfg_vfs.get_dev_flash() + "sys/external");
}
const QStringList modules = QFileDialog::getOpenFileNames(this, tr("Select binary files"), path_last_sprx, tr("All Binaries (*.bin *.BIN *.self *.SELF *.sprx *.SPRX *.sdat *.SDAT *.edat *.EDAT);;"
"BIN files (*.bin *.BIN);;SELF files (*.self *.SELF);;SPRX files (*.sprx *.SPRX);;SDAT/EDAT files (*.sdat *.SDAT *.edat *.EDAT);;All files (*.*)"));
if (modules.isEmpty())
{
return;
}
m_gui_settings->SetValue(gui::fd_decrypt_sprx, QFileInfo(modules.first()).path());
std::vector<std::string> vec_modules;
for (const QString& mod : modules)
{
vec_modules.push_back(mod.toStdString());
}
auto iterate = std::make_shared<std::function<void(usz, usz)>>();
const auto decrypter = std::make_shared<decrypt_binaries_t>(std::move(vec_modules));
*iterate = [this, iterate, decrypter](usz mod_index, usz repeat_count)
{
const std::string& path = (*decrypter)[mod_index];
const std::string filename = path.substr(path.find_last_of(fs::delim) + 1);
const QString hint = tr("Hint: KLIC (KLicense key) is a 16-byte long string. (32 hexadecimal characters, can be prefixed with \"KLIC=0x\" from the log message)"
"\nAnd is logged with some sceNpDrm* functions when the game/application which owns \"%0\" is running.").arg(qstr(filename));
if (repeat_count >= 2)
{
gui_log.error("Failed to decrypt %s with specified KLIC, retrying.\n%s", path, hint);
}
input_dialog* dlg = new input_dialog(39, "", tr("Enter KLIC of %0").arg(qstr(filename)),
repeat_count >= 2 ? tr("Decryption failed with provided KLIC.\n%0").arg(hint) : tr("Hexadecimal value."), "KLIC=0x00000000000000000000000000000000", this);
QFont mono = QFontDatabase::systemFont(QFontDatabase::FixedFont);
mono.setPointSize(8);
dlg->set_input_font(mono, true, '0');
dlg->set_clear_button_enabled(false);
dlg->set_button_enabled(QDialogButtonBox::StandardButton::Ok, false);
dlg->set_validator(new QRegularExpressionValidator(QRegularExpression("^((((((K?L)?I)?C)?=)?0)?x)?[a-fA-F0-9]{0,32}$"), this)); // HEX only (with additional KLIC=0x prefix for convenience)
dlg->setAttribute(Qt::WA_DeleteOnClose);
connect(dlg, &input_dialog::text_changed, dlg, [dlg](const QString& text)
{
dlg->set_button_enabled(QDialogButtonBox::StandardButton::Ok, text.size() - (text.indexOf('x') + 1) == 32);
});
connect(dlg, &QDialog::accepted, this, [this, iterate, dlg, mod_index, decrypter, repeat_count]()
{
std::string text = sstr(dlg->get_input_text());
if (usz new_index = decrypter->decrypt(std::move(text)); !decrypter->done())
{
QTimer::singleShot(0, [iterate, mod_index, repeat_count, new_index]()
{
// Increase repeat count if "stuck" on the same file
(*iterate)(new_index, new_index == mod_index ? repeat_count + 1 : 0);
});
}
});
connect(dlg, &QDialog::rejected, this, []()
{
gui_log.notice("User has cancelled entering KLIC.");
});
dlg->show();
};
if (usz new_index = decrypter->decrypt(); !decrypter->done())
{
(*iterate)(new_index, new_index == 0 ? 1 : 0);
}
}
/** Needed so that when a backup occurs of window state in gui_settings, the state is current.
* Also, so that on close, the window state is preserved.
*/
void main_window::SaveWindowState() const
{
// Save gui settings
m_gui_settings->SetValue(gui::mw_geometry, saveGeometry(), false);
m_gui_settings->SetValue(gui::mw_windowState, saveState(), false);
m_gui_settings->SetValue(gui::mw_mwState, m_mw->saveState(), true);
// Save column settings
m_game_list_frame->SaveSettings();
// Save splitter state
m_debugger_frame->SaveSettings();
}
void main_window::RepaintThumbnailIcons()
{
const QColor color = gui::utils::get_foreground_color();
[[maybe_unused]] const QColor new_color = gui::utils::get_label_color("thumbnail_icon_color", color, color);
[[maybe_unused]] const auto icon = [&new_color](const QString& path)
{
return gui::utils::get_colorized_icon(QPixmap::fromImage(gui::utils::get_opaque_image_area(path)), Qt::black, new_color);
};
#ifdef HAS_QT_WIN_STUFF
if (!m_thumb_bar) return;
m_icon_thumb_play = icon(":/Icons/play.png");
m_icon_thumb_pause = icon(":/Icons/pause.png");
m_icon_thumb_stop = icon(":/Icons/stop.png");
m_icon_thumb_restart = icon(":/Icons/restart.png");
m_thumb_playPause->setIcon(Emu.IsRunning() || Emu.IsStarting() ? m_icon_thumb_pause : m_icon_thumb_play);
m_thumb_stop->setIcon(m_icon_thumb_stop);
m_thumb_restart->setIcon(m_icon_thumb_restart);
#endif
}
void main_window::RepaintToolBarIcons()
{
const QColor color = gui::utils::get_foreground_color();
std::map<QIcon::Mode, QColor> new_colors{};
new_colors[QIcon::Normal] = gui::utils::get_label_color("toolbar_icon_color", color, color);
new_colors[QIcon::Disabled] = gui::utils::get_label_color("toolbar_icon_color_disabled", Qt::gray, Qt::lightGray);
new_colors[QIcon::Active] = gui::utils::get_label_color("toolbar_icon_color_active", color, color);
new_colors[QIcon::Selected] = gui::utils::get_label_color("toolbar_icon_color_selected", color, color);
const auto icon = [&new_colors](const QString& path)
{
return gui::utils::get_colorized_icon(QIcon(path), Qt::black, new_colors);
};
m_icon_play = icon(":/Icons/play.png");
m_icon_pause = icon(":/Icons/pause.png");
m_icon_restart = icon(":/Icons/restart.png");
m_icon_fullscreen_on = icon(":/Icons/fullscreen.png");
m_icon_fullscreen_off = icon(":/Icons/exit_fullscreen.png");
ui->toolbar_config ->setIcon(icon(":/Icons/configure.png"));
ui->toolbar_controls->setIcon(icon(":/Icons/controllers.png"));
ui->toolbar_open ->setIcon(icon(":/Icons/open.png"));
ui->toolbar_grid ->setIcon(icon(":/Icons/grid.png"));
ui->toolbar_list ->setIcon(icon(":/Icons/list.png"));
ui->toolbar_refresh ->setIcon(icon(":/Icons/refresh.png"));
ui->toolbar_stop ->setIcon(icon(":/Icons/stop.png"));
ui->sysStopAct->setIcon(icon(":/Icons/stop.png"));
ui->sysRebootAct->setIcon(m_icon_restart);
if (Emu.IsRunning())
{
ui->toolbar_start->setIcon(m_icon_pause);
ui->sysPauseAct->setIcon(m_icon_pause);
}
else if (Emu.IsStopped() && !Emu.GetBoot().empty())
{
ui->toolbar_start->setIcon(m_icon_restart);
ui->sysPauseAct->setIcon(m_icon_restart);
}
else
{
ui->toolbar_start->setIcon(m_icon_play);
ui->sysPauseAct->setIcon(m_icon_play);
}
if (isFullScreen())
{
ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_off);
}
else
{
ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_on);
}
const QColor& new_color = new_colors[QIcon::Normal];
ui->sizeSlider->setStyleSheet(ui->sizeSlider->styleSheet().append("QSlider::handle:horizontal{ background: rgba(%1, %2, %3, %4); }")
.arg(new_color.red()).arg(new_color.green()).arg(new_color.blue()).arg(new_color.alpha()));
// resize toolbar elements
const int tool_bar_height = ui->toolBar->sizeHint().height();
for (const auto& act : ui->toolBar->actions())
{
if (act->isSeparator())
{
continue;
}
ui->toolBar->widgetForAction(act)->setMinimumWidth(tool_bar_height);
}
ui->sizeSliderContainer->setFixedWidth(tool_bar_height * 4);
ui->mw_searchbar->setFixedWidth(tool_bar_height * 5);
}
void main_window::OnEmuRun(bool /*start_playtime*/)
{
const QString title = GetCurrentTitle();
const QString restart_tooltip = tr("Restart %0").arg(title);
const QString pause_tooltip = tr("Pause %0").arg(title);
const QString stop_tooltip = tr("Stop %0").arg(title);
m_debugger_frame->EnableButtons(true);
#ifdef HAS_QT_WIN_STUFF
m_thumb_stop->setToolTip(stop_tooltip);
m_thumb_restart->setToolTip(restart_tooltip);
m_thumb_playPause->setToolTip(pause_tooltip);
m_thumb_playPause->setIcon(m_icon_thumb_pause);
#endif
ui->sysPauseAct->setText(tr("&Pause"));
ui->sysPauseAct->setIcon(m_icon_pause);
ui->toolbar_start->setIcon(m_icon_pause);
ui->toolbar_start->setText(tr("Pause"));
ui->toolbar_start->setToolTip(pause_tooltip);
ui->toolbar_stop->setToolTip(stop_tooltip);
EnableMenus(true);
update_gui_pad_thread();
}
void main_window::OnEmuResume() const
{
const QString title = GetCurrentTitle();
const QString restart_tooltip = tr("Restart %0").arg(title);
const QString pause_tooltip = tr("Pause %0").arg(title);
const QString stop_tooltip = tr("Stop %0").arg(title);
#ifdef HAS_QT_WIN_STUFF
m_thumb_stop->setToolTip(stop_tooltip);
m_thumb_restart->setToolTip(restart_tooltip);
m_thumb_playPause->setToolTip(pause_tooltip);
m_thumb_playPause->setIcon(m_icon_thumb_pause);
#endif
ui->sysPauseAct->setText(tr("&Pause"));
ui->sysPauseAct->setIcon(m_icon_pause);
ui->toolbar_start->setIcon(m_icon_pause);
ui->toolbar_start->setText(tr("Pause"));
ui->toolbar_start->setToolTip(pause_tooltip);
ui->toolbar_stop->setToolTip(stop_tooltip);
}
void main_window::OnEmuPause() const
{
const QString title = GetCurrentTitle();
const QString resume_tooltip = tr("Resume %0").arg(title);
#ifdef HAS_QT_WIN_STUFF
m_thumb_playPause->setToolTip(resume_tooltip);
m_thumb_playPause->setIcon(m_icon_thumb_play);
#endif
ui->sysPauseAct->setText(tr("&Resume"));
ui->sysPauseAct->setIcon(m_icon_play);
ui->toolbar_start->setIcon(m_icon_play);
ui->toolbar_start->setText(tr("Play"));
ui->toolbar_start->setToolTip(resume_tooltip);
// Refresh game list in order to update time played
if (m_game_list_frame)
{
m_game_list_frame->Refresh();
}
}
void main_window::OnEmuStop()
{
const QString title = GetCurrentTitle();
const QString play_tooltip = tr("Play %0").arg(title);
ui->sysPauseAct->setText(tr("&Play"));
ui->sysPauseAct->setIcon(m_icon_play);
#ifdef HAS_QT_WIN_STUFF
m_thumb_playPause->setToolTip(play_tooltip);
m_thumb_playPause->setIcon(m_icon_thumb_play);
#endif
EnableMenus(false);
if (title.isEmpty())
{
ui->toolbar_start->setIcon(m_icon_play);
ui->toolbar_start->setText(tr("Play"));
ui->toolbar_start->setToolTip(play_tooltip);
}
else
{
const QString restart_tooltip = tr("Restart %0").arg(title);
ui->toolbar_start->setEnabled(true);
ui->toolbar_start->setIcon(m_icon_restart);
ui->toolbar_start->setText(tr("Restart"));
ui->toolbar_start->setToolTip(restart_tooltip);
ui->sysRebootAct->setEnabled(true);
#ifdef HAS_QT_WIN_STUFF
m_thumb_restart->setToolTip(restart_tooltip);
m_thumb_restart->setEnabled(true);
#endif
}
ui->batchRemoveShaderCachesAct->setEnabled(true);
ui->batchRemovePPUCachesAct->setEnabled(true);
ui->batchRemoveSPUCachesAct->setEnabled(true);
ui->removeHDD1CachesAct->setEnabled(true);
ui->removeAllCachesAct->setEnabled(true);
ui->removeSavestatesAct->setEnabled(true);
ui->cleanUpGameListAct->setEnabled(true);
ui->actionManage_Users->setEnabled(true);
ui->confCamerasAct->setEnabled(true);
// Refresh game list in order to update time played
if (m_game_list_frame && m_is_list_mode)
{
m_game_list_frame->Refresh();
}
// Close kernel explorer if running
if (m_kernel_explorer)
{
m_kernel_explorer->close();
}
// Close systen command dialog if running
if (m_system_cmd_dialog)
{
m_system_cmd_dialog->close();
}
update_gui_pad_thread();
}
void main_window::OnEmuReady() const
{
const QString title = GetCurrentTitle();
const QString play_tooltip = tr("Play %0").arg(title);
m_debugger_frame->EnableButtons(true);
#ifdef HAS_QT_WIN_STUFF
m_thumb_playPause->setToolTip(play_tooltip);
m_thumb_playPause->setIcon(m_icon_thumb_play);
#endif
ui->sysPauseAct->setText(tr("&Play"));
ui->sysPauseAct->setIcon(m_icon_play);
ui->toolbar_start->setIcon(m_icon_play);
ui->toolbar_start->setText(tr("Play"));
ui->toolbar_start->setToolTip(play_tooltip);
EnableMenus(true);
ui->actionManage_Users->setEnabled(false);
ui->confCamerasAct->setEnabled(false);
ui->batchRemoveShaderCachesAct->setEnabled(false);
ui->batchRemovePPUCachesAct->setEnabled(false);
ui->batchRemoveSPUCachesAct->setEnabled(false);
ui->removeHDD1CachesAct->setEnabled(false);
ui->removeAllCachesAct->setEnabled(false);
ui->removeSavestatesAct->setEnabled(false);
ui->cleanUpGameListAct->setEnabled(false);
}
void main_window::EnableMenus(bool enabled) const
{
// Thumbnail Buttons
#ifdef HAS_QT_WIN_STUFF
m_thumb_playPause->setEnabled(enabled);
m_thumb_stop->setEnabled(enabled);
m_thumb_restart->setEnabled(enabled);
#endif
// Toolbar
ui->toolbar_start->setEnabled(enabled);
ui->toolbar_stop->setEnabled(enabled);
// Emulation
ui->sysPauseAct->setEnabled(enabled);
ui->sysStopAct->setEnabled(enabled);
ui->sysRebootAct->setEnabled(enabled);
// Tools
ui->toolskernel_explorerAct->setEnabled(enabled);
ui->toolsmemory_viewerAct->setEnabled(enabled);
ui->toolsRsxDebuggerAct->setEnabled(enabled);
ui->toolsSystemCommandsAct->setEnabled(enabled);
ui->actionCreate_RSX_Capture->setEnabled(enabled);
ui->actionCreate_Savestate->setEnabled(enabled);
}
void main_window::OnAddBreakpoint(u32 addr) const
{
if (m_debugger_frame)
{
m_debugger_frame->PerformAddBreakpointRequest(addr);
}
}
void main_window::OnEnableDiscEject(bool enabled) const
{
ui->ejectDiscAct->setEnabled(enabled);
}
void main_window::OnEnableDiscInsert(bool enabled) const
{
ui->insertDiscAct->setEnabled(enabled);
}
void main_window::BootRecentAction(const QAction* act)
{
if (Emu.IsRunning())
{
return;
}
const QString pth = act->data().toString();
const std::string path = sstr(pth);
QString name;
bool contains_path = false;
int idx = -1;
for (int i = 0; i < m_rg_entries.count(); i++)
{
if (::at32(m_rg_entries, i).first == pth)
{
idx = i;
contains_path = true;
name = ::at32(m_rg_entries, idx).second;
break;
}
}
// path is invalid: remove action from list return
if ((contains_path && name.isEmpty()) || (!QFileInfo(pth).isDir() && !QFileInfo(pth).isFile()))
{
if (contains_path)
{
// clear menu of actions
for (QAction* action : m_recent_game_acts)
{
ui->bootRecentMenu->removeAction(action);
}
// remove action from list
m_rg_entries.removeAt(idx);
m_recent_game_acts.removeAt(idx);
m_gui_settings->SetValue(gui::rg_entries, gui_settings::List2Var(m_rg_entries));
gui_log.error("Recent Game not valid, removed from Boot Recent list: %s", path);
// refill menu with actions
for (int i = 0; i < m_recent_game_acts.count(); i++)
{
m_recent_game_acts[i]->setShortcut(tr("Ctrl+%1").arg(i + 1));
m_recent_game_acts[i]->setToolTip(::at32(m_rg_entries, i).second);
ui->bootRecentMenu->addAction(m_recent_game_acts[i]);
}
gui_log.warning("Boot Recent list refreshed");
return;
}
gui_log.error("Path invalid and not in m_rg_paths: %s", path);
return;
}
gui_log.notice("Booting from recent games list...");
Boot(path, "", true);
}
QAction* main_window::CreateRecentAction(const q_string_pair& entry, const uint& sc_idx)
{
// if path is not valid remove from list
if (entry.second.isEmpty() || (!QFileInfo(entry.first).isDir() && !QFileInfo(entry.first).isFile()))
{
if (m_rg_entries.contains(entry))
{
gui_log.warning("Recent Game not valid, removing from Boot Recent list: %s", entry.first);
const int idx = m_rg_entries.indexOf(entry);
m_rg_entries.removeAt(idx);
m_gui_settings->SetValue(gui::rg_entries, gui_settings::List2Var(m_rg_entries));
}
return nullptr;
}
// if name is a path get filename
QString shown_name = entry.second;
if (QFileInfo(entry.second).isFile())
{
shown_name = entry.second.section('/', -1);
}
// create new action
QAction* act = new QAction(shown_name, this);
act->setData(entry.first);
act->setToolTip(entry.second);
act->setShortcut(tr("Ctrl+%1").arg(sc_idx));
// truncate if too long
if (shown_name.length() > 60)
{
act->setText(shown_name.left(27) + "(....)" + shown_name.right(27));
}
// connect boot
connect(act, &QAction::triggered, this, [act, this]() {BootRecentAction(act); });
return act;
}
void main_window::AddRecentAction(const q_string_pair& entry)
{
// don't change list on freeze
if (ui->freezeRecentAct->isChecked())
{
return;
}
// create new action, return if not valid
QAction* act = CreateRecentAction(entry, 1);
if (!act)
{
return;
}
// clear menu of actions
for (QAction* action : m_recent_game_acts)
{
ui->bootRecentMenu->removeAction(action);
}
// If path already exists, remove it in order to get it to beginning. Also remove duplicates.
for (int i = m_rg_entries.count() - 1; i >= 0; --i)
{
if (m_rg_entries[i].first == entry.first)
{
m_rg_entries.removeAt(i);
m_recent_game_acts.removeAt(i);
}
}
// remove oldest action at the end if needed
if (m_rg_entries.count() == 9)
{
m_rg_entries.removeLast();
m_recent_game_acts.removeLast();
}
else if (m_rg_entries.count() > 9)
{
gui_log.error("Recent games entrylist too big");
}
if (m_rg_entries.count() < 9)
{
// add new action at the beginning
m_rg_entries.prepend(entry);
m_recent_game_acts.prepend(act);
}
// refill menu with actions
for (int i = 0; i < m_recent_game_acts.count(); i++)
{
m_recent_game_acts[i]->setShortcut(tr("Ctrl+%1").arg(i + 1));
m_recent_game_acts[i]->setToolTip(::at32(m_rg_entries, i).second);
ui->bootRecentMenu->addAction(m_recent_game_acts[i]);
}
m_gui_settings->SetValue(gui::rg_entries, gui_settings::List2Var(m_rg_entries));
}
void main_window::UpdateLanguageActions(const QStringList& language_codes, const QString& language_code)
{
ui->languageMenu->clear();
for (const auto& code : language_codes)
{
const QLocale locale = QLocale(code);
const QString locale_name = QLocale::languageToString(locale.language());
// create new action
QAction* act = new QAction(locale_name, this);
act->setData(code);
act->setToolTip(locale_name);
act->setCheckable(true);
act->setChecked(code == language_code);
// connect to language changer
connect(act, &QAction::triggered, this, [this, code]()
{
RequestLanguageChange(code);
});
ui->languageMenu->addAction(act);
}
}
void main_window::UpdateFilterActions()
{
ui->showCatHDDGameAct->setChecked(m_gui_settings->GetCategoryVisibility(Category::HDD_Game, m_is_list_mode));
ui->showCatDiscGameAct->setChecked(m_gui_settings->GetCategoryVisibility(Category::Disc_Game, m_is_list_mode));
ui->showCatPS1GamesAct->setChecked(m_gui_settings->GetCategoryVisibility(Category::PS1_Game, m_is_list_mode));
ui->showCatPS2GamesAct->setChecked(m_gui_settings->GetCategoryVisibility(Category::PS2_Game, m_is_list_mode));
ui->showCatPSPGamesAct->setChecked(m_gui_settings->GetCategoryVisibility(Category::PSP_Game, m_is_list_mode));
ui->showCatHomeAct->setChecked(m_gui_settings->GetCategoryVisibility(Category::Home, m_is_list_mode));
ui->showCatAudioVideoAct->setChecked(m_gui_settings->GetCategoryVisibility(Category::Media, m_is_list_mode));
ui->showCatGameDataAct->setChecked(m_gui_settings->GetCategoryVisibility(Category::Data, m_is_list_mode));
ui->showCatUnknownAct->setChecked(m_gui_settings->GetCategoryVisibility(Category::Unknown_Cat, m_is_list_mode));
ui->showCatOtherAct->setChecked(m_gui_settings->GetCategoryVisibility(Category::Others, m_is_list_mode));
}
void main_window::RepaintGui()
{
if (m_game_list_frame)
{
m_game_list_frame->RepaintIcons(true);
}
if (m_log_frame)
{
m_log_frame->RepaintTextColors();
}
if (m_debugger_frame)
{
m_debugger_frame->ChangeColors();
}
RepaintToolBarIcons();
RepaintThumbnailIcons();
Q_EMIT RequestDialogRepaint();
}
void main_window::RetranslateUI(const QStringList& language_codes, const QString& language)
{
UpdateLanguageActions(language_codes, language);
ui->retranslateUi(this);
if (m_game_list_frame)
{
m_game_list_frame->Refresh(true);
}
}
void main_window::ShowTitleBars(bool show) const
{
m_game_list_frame->SetTitleBarVisible(show);
m_debugger_frame->SetTitleBarVisible(show);
m_log_frame->SetTitleBarVisible(show);
}
void main_window::ShowOptionalGamePreparations(const QString& title, const QString& message, std::map<std::string, QString> bootable_paths)
{
if (bootable_paths.empty())
{
m_gui_settings->ShowInfoBox(title, message, gui::ib_pkg_success, this);
return;
}
QDialog* dlg = new QDialog(this);
dlg->setObjectName("game_prepare_window");
dlg->setWindowTitle(title);
QVBoxLayout* vlayout = new QVBoxLayout(dlg);
QCheckBox* desk_check = new QCheckBox(tr("Add desktop shortcut(s)"));
#ifdef _WIN32
QCheckBox* quick_check = new QCheckBox(tr("Add Start menu shortcut(s)"));
#elif defined(__APPLE__)
QCheckBox* quick_check = new QCheckBox(tr("Add dock shortcut(s)"));
#else
QCheckBox* quick_check = new QCheckBox(tr("Add launcher shortcut(s)"));
#endif
QCheckBox* precompile_check = new QCheckBox(tr("Precompile caches"));
QLabel* label = new QLabel(tr("%1\nWould you like to install shortcuts to the installed software and precompile caches? (%2 new software detected)\n\n").arg(message).arg(bootable_paths.size()), dlg);
vlayout->addWidget(label);
vlayout->addStretch(10);
vlayout->addWidget(desk_check);
vlayout->addStretch(3);
vlayout->addWidget(quick_check);
vlayout->addStretch(3);
vlayout->addWidget(precompile_check);
vlayout->addStretch(3);
precompile_check->setToolTip(tr("Spend time building data needed for game boot now instead of at launch."));
QDialogButtonBox* btn_box = new QDialogButtonBox(QDialogButtonBox::Ok);
vlayout->addWidget(btn_box);
dlg->setLayout(vlayout);
connect(btn_box, &QDialogButtonBox::accepted, this, [=, this, paths = std::move(bootable_paths)]()
{
const bool create_desktop_shortcuts = desk_check->isChecked();
const bool create_app_shortcut = quick_check->isChecked();
const bool create_caches = precompile_check->isChecked();
dlg->hide();
dlg->accept();
std::set<gui::utils::shortcut_location> locations;
#ifdef _WIN32
locations.insert(gui::utils::shortcut_location::rpcs3_shortcuts);
#endif
if (create_desktop_shortcuts)
{
locations.insert(gui::utils::shortcut_location::desktop);
}
if (create_app_shortcut)
{
locations.insert(gui::utils::shortcut_location::applications);
}
std::vector<game_info> game_data;
for (const auto& [boot_path, title_id] : paths)
{
for (const game_info& gameinfo : m_game_list_frame->GetGameInfo())
{
if (gameinfo && gameinfo->info.serial == sstr(title_id))
{
if (Emu.IsPathInsideDir(boot_path, gameinfo->info.path))
{
m_game_list_frame->CreateShortcuts(gameinfo, locations);
if (create_caches)
{
game_data.push_back(gameinfo);
}
}
break;
}
}
}
if (!game_data.empty())
{
m_game_list_frame->BatchCreateCPUCaches(game_data);
}
});
dlg->setAttribute(Qt::WA_DeleteOnClose);
dlg->open();
}
void main_window::CreateActions()
{
ui->exitAct->setShortcuts(QKeySequence::Quit);
ui->toolbar_start->setEnabled(false);
ui->toolbar_stop->setEnabled(false);
m_category_visible_act_group = new QActionGroup(this);
m_category_visible_act_group->addAction(ui->showCatHDDGameAct);
m_category_visible_act_group->addAction(ui->showCatDiscGameAct);
m_category_visible_act_group->addAction(ui->showCatPS1GamesAct);
m_category_visible_act_group->addAction(ui->showCatPS2GamesAct);
m_category_visible_act_group->addAction(ui->showCatPSPGamesAct);
m_category_visible_act_group->addAction(ui->showCatHomeAct);
m_category_visible_act_group->addAction(ui->showCatAudioVideoAct);
m_category_visible_act_group->addAction(ui->showCatGameDataAct);
m_category_visible_act_group->addAction(ui->showCatUnknownAct);
m_category_visible_act_group->addAction(ui->showCatOtherAct);
m_category_visible_act_group->setExclusive(false);
m_icon_size_act_group = new QActionGroup(this);
m_icon_size_act_group->addAction(ui->setIconSizeTinyAct);
m_icon_size_act_group->addAction(ui->setIconSizeSmallAct);
m_icon_size_act_group->addAction(ui->setIconSizeMediumAct);
m_icon_size_act_group->addAction(ui->setIconSizeLargeAct);
m_list_mode_act_group = new QActionGroup(this);
m_list_mode_act_group->addAction(ui->setlistModeListAct);
m_list_mode_act_group->addAction(ui->setlistModeGridAct);
}
void main_window::CreateConnects()
{
connect(ui->bootElfAct, &QAction::triggered, this, &main_window::BootElf);
connect(ui->bootTestAct, &QAction::triggered, this, &main_window::BootTest);
connect(ui->bootGameAct, &QAction::triggered, this, &main_window::BootGame);
connect(ui->bootVSHAct, &QAction::triggered, this, &main_window::BootVSH);
connect(ui->actionopen_rsx_capture, &QAction::triggered, this, [this](){ BootRsxCapture(); });
connect(ui->actionCreate_RSX_Capture, &QAction::triggered, this, []()
{
g_user_asked_for_frame_capture = true;
});
connect(ui->actionCreate_Savestate, &QAction::triggered, this, []()
{
gui_log.notice("User triggered savestate creation from utilities.");
if (!g_cfg.savestate.suspend_emu)
{
Emu.after_kill_callback = []()
{
Emu.Restart();
};
}
Emu.Kill(false, true);
});
connect(ui->actionCreate_Savestate_And_Exit, &QAction::triggered, this, []()
{
gui_log.notice("User triggered savestate creation and emulation stop from utilities.");
Emu.Kill(false, true);
});
connect(ui->bootSavestateAct, &QAction::triggered, this, &main_window::BootSavestate);
connect(ui->addGamesAct, &QAction::triggered, this, [this]()
{
if (!m_gui_settings->GetBootConfirmation(this))
{
return;
}
// Only select one folder for now
QString dir = QFileDialog::getExistingDirectory(this, tr("Select a folder containing one or more games"), qstr(fs::get_config_dir()), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (dir.isEmpty())
{
return;
}
QStringList paths;
paths << dir;
AddGamesFromDirs(std::move(paths));
});
connect(ui->bootRecentMenu, &QMenu::aboutToShow, this, [this]()
{
// Enable/Disable Recent Games List
const bool stopped = Emu.IsStopped();
for (QAction* act : ui->bootRecentMenu->actions())
{
if (act != ui->freezeRecentAct && act != ui->clearRecentAct)
{
act->setEnabled(stopped);
}
}
});
connect(ui->clearRecentAct, &QAction::triggered, this, [this]()
{
if (ui->freezeRecentAct->isChecked())
{
return;
}
m_rg_entries.clear();
for (QAction* act : m_recent_game_acts)
{
ui->bootRecentMenu->removeAction(act);
}
m_recent_game_acts.clear();
m_gui_settings->SetValue(gui::rg_entries, gui_settings::List2Var(q_pair_list()));
});
connect(ui->freezeRecentAct, &QAction::triggered, this, [this](bool checked)
{
m_gui_settings->SetValue(gui::rg_freeze, checked);
});
connect(ui->bootInstallPkgAct, &QAction::triggered, this, [this] {InstallPackages(); });
connect(ui->bootInstallPupAct, &QAction::triggered, this, [this] {InstallPup(); });
connect(this, &main_window::NotifyWindowCloseEvent, this, [this](bool closed)
{
if (!closed)
{
// Cancel the request
m_requested_show_logs_on_exit = false;
return;
}
if (!m_requested_show_logs_on_exit)
{
// Not requested
return;
}
const std::string archived_path = fs::get_cache_dir() + "RPCS3.log.gz";
const std::string raw_file_path = fs::get_cache_dir() + "RPCS3.log";
fs::stat_t raw_stat{};
fs::stat_t archived_stat{};
if ((!fs::get_stat(raw_file_path, raw_stat) || raw_stat.is_directory) || (!fs::get_stat(archived_path, archived_stat) || archived_stat.is_directory) || (raw_stat.size == 0 && archived_stat.size == 0))
{
QMessageBox::warning(this, tr("Failed to locate log"), tr("Failed to locate log files.\nMake sure that RPCS3.log and RPCS3.log.gz are writable and can be created without permission issues."));
return;
}
// Get new filename from title and title ID but simplified
QString log_filename_q = qstr(Emu.GetTitleID().empty() ? "RPCS3" : Emu.GetTitleAndTitleID());
ensure(!log_filename_q.isEmpty());
// Replace unfitting characters
std::replace_if(log_filename_q.begin(), log_filename_q.end(), [](QChar c){ return !c.isLetterOrNumber() && c != QChar::Space && c != '[' && c != ']'; }, QChar::Space);
log_filename_q = log_filename_q.simplified();
const std::string log_filename = log_filename_q.toStdString();
QString path_last_log = m_gui_settings->GetValue(gui::fd_save_log).toString();
auto move_log = [](const std::string& from, const std::string& to)
{
if (from == to)
{
return false;
}
// Test writablity here to avoid closing the log with no *chance* of success
if (fs::file test_writable{to, fs::write + fs::create}; !test_writable)
{
return false;
}
// Close and flush log file handle (!)
// Cannot rename the file due to file management design
logs::listener::close_all_prematurely();
// Try to move it
if (fs::rename(from, to, true))
{
return true;
}
// Try to copy it if fails
if (fs::copy_file(from, to, true))
{
if (fs::file sync_fd{to, fs::write})
{
// Prevent data loss (expensive)
sync_fd.sync();
}
fs::remove_file(from);
return true;
}
return false;
};
if (archived_stat.size)
{
const QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select RPCS3's log saving location (saving %0)").arg(qstr(log_filename + ".log.gz")), path_last_log, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (dir_path.isEmpty())
{
// Aborted - view the current location
gui::utils::open_dir(archived_path);
return;
}
const std::string dest_archived_path = dir_path.toStdString() + "/" + log_filename + ".log.gz";
if (!Emu.GetTitleID().empty() && !dest_archived_path.empty() && move_log(archived_path, dest_archived_path))
{
m_gui_settings->SetValue(gui::fd_save_log, dir_path);
gui_log.success("Moved log file to '%s'!", dest_archived_path);
gui::utils::open_dir(dest_archived_path);
return;
}
gui::utils::open_dir(archived_path);
return;
}
const QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select RPCS3's log saving location (saving %0)").arg(qstr(log_filename + ".log")), path_last_log, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (dir_path.isEmpty())
{
// Aborted - view the current location
gui::utils::open_dir(raw_file_path);
return;
}
const std::string dest_raw_file_path = dir_path.toStdString() + "/" + log_filename + ".log";
if (!Emu.GetTitleID().empty() && !dest_raw_file_path.empty() && move_log(raw_file_path, dest_raw_file_path))
{
m_gui_settings->SetValue(gui::fd_save_log, dir_path);
gui_log.success("Moved log file to '%s'!", dest_raw_file_path);
gui::utils::open_dir(dest_raw_file_path);
return;
}
gui::utils::open_dir(raw_file_path);
});
connect(ui->exitAndSaveLogAct, &QAction::triggered, this, [this]()
{
m_requested_show_logs_on_exit = true;
close();
});
connect(ui->exitAct, &QAction::triggered, this, &QWidget::close);
connect(ui->batchCreateCPUCachesAct, &QAction::triggered, m_game_list_frame, [list = m_game_list_frame]() { list->BatchCreateCPUCaches(); });
connect(ui->batchRemoveCustomConfigurationsAct, &QAction::triggered, m_game_list_frame, &game_list_frame::BatchRemoveCustomConfigurations);
connect(ui->batchRemoveCustomPadConfigurationsAct, &QAction::triggered, m_game_list_frame, &game_list_frame::BatchRemoveCustomPadConfigurations);
connect(ui->batchRemoveShaderCachesAct, &QAction::triggered, m_game_list_frame, &game_list_frame::BatchRemoveShaderCaches);
connect(ui->batchRemovePPUCachesAct, &QAction::triggered, m_game_list_frame, &game_list_frame::BatchRemovePPUCaches);
connect(ui->batchRemoveSPUCachesAct, &QAction::triggered, m_game_list_frame, &game_list_frame::BatchRemoveSPUCaches);
connect(ui->removeHDD1CachesAct, &QAction::triggered, this, &main_window::RemoveHDD1Caches);
connect(ui->removeAllCachesAct, &QAction::triggered, this, &main_window::RemoveAllCaches);
connect(ui->removeSavestatesAct, &QAction::triggered, this, &main_window::RemoveSavestates);
connect(ui->cleanUpGameListAct, &QAction::triggered, this, &main_window::CleanUpGameList);
connect(ui->removeFirmwareCacheAct, &QAction::triggered, this, &main_window::RemoveFirmwareCache);
connect(ui->createFirmwareCacheAct, &QAction::triggered, this, &main_window::CreateFirmwareCache);
connect(ui->sysPauseAct, &QAction::triggered, this, &main_window::OnPlayOrPause);
connect(ui->sysStopAct, &QAction::triggered, this, []()
{
gui_log.notice("User triggered stop action in menu bar");
Emu.GracefulShutdown(false, true);
});
connect(ui->sysRebootAct, &QAction::triggered, this, []()
{
gui_log.notice("User triggered restart action in menu bar");
Emu.Restart();
});
connect(ui->ejectDiscAct, &QAction::triggered, this, []()
{
gui_log.notice("User triggered eject disc action in menu bar");
Emu.EjectDisc();
});
connect(ui->insertDiscAct, &QAction::triggered, this, [this]()
{
gui_log.notice("User triggered insert disc action in menu bar");
const QString path_last_game = m_gui_settings->GetValue(gui::fd_insert_disc).toString();
const QString dir_path = QFileDialog::getExistingDirectory(this, tr("Select Disc Game Folder"), path_last_game, QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
if (dir_path.isEmpty())
{
return;
}
const game_boot_result result = Emu.InsertDisc(dir_path.toStdString());
if (result != game_boot_result::no_errors)
{
QMessageBox::warning(this, tr("Failed to insert disc"), tr("Make sure that the emulation is running and that the selected path belongs to a valid disc game."));
return;
}
m_gui_settings->SetValue(gui::fd_insert_disc, QFileInfo(dir_path).path());
});
const auto open_settings = [this](int tabIndex)
{
settings_dialog dlg(m_gui_settings, m_emu_settings, tabIndex, this);
connect(&dlg, &settings_dialog::GuiStylesheetRequest, this, &main_window::RequestGlobalStylesheetChange);
connect(&dlg, &settings_dialog::GuiRepaintRequest, this, &main_window::RepaintGui);
connect(&dlg, &settings_dialog::EmuSettingsApplied, this, &main_window::NotifyEmuSettingsChange);
connect(&dlg, &settings_dialog::EmuSettingsApplied, this, &main_window::update_gui_pad_thread);
connect(&dlg, &settings_dialog::EmuSettingsApplied, m_log_frame, &log_frame::LoadSettings);
dlg.exec();
};
connect(ui->confCPUAct, &QAction::triggered, this, [open_settings]() { open_settings(0); });
connect(ui->confGPUAct, &QAction::triggered, this, [open_settings]() { open_settings(1); });
connect(ui->confAudioAct, &QAction::triggered, this, [open_settings]() { open_settings(2); });
connect(ui->confIOAct, &QAction::triggered, this, [open_settings]() { open_settings(3); });
connect(ui->confSystemAct, &QAction::triggered, this, [open_settings]() { open_settings(4); });
connect(ui->confAdvAct, &QAction::triggered, this, [open_settings]() { open_settings(6); });
connect(ui->confEmuAct, &QAction::triggered, this, [open_settings]() { open_settings(7); });
connect(ui->confGuiAct, &QAction::triggered, this, [open_settings]() { open_settings(8); });
connect(ui->confShortcutsAct, &QAction::triggered, [this]()
{
shortcut_dialog dlg(m_gui_settings, this);
connect(&dlg, &shortcut_dialog::saved, this, [this]()
{
m_shortcut_handler->update();
NotifyShortcutHandlers();
});
dlg.exec();
});
const auto open_pad_settings = [this]
{
pad_settings_dialog dlg(m_gui_settings, this);
dlg.exec();
};
connect(ui->confPadsAct, &QAction::triggered, this, open_pad_settings);
connect(ui->confBuzzAct, &QAction::triggered, this, [this]
{
emulated_pad_settings_dialog* dlg = new emulated_pad_settings_dialog(emulated_pad_settings_dialog::pad_type::buzz, this);
dlg->show();
});
connect(ui->confGHLtarAct, &QAction::triggered, this, [this]
{
emulated_pad_settings_dialog* dlg = new emulated_pad_settings_dialog(emulated_pad_settings_dialog::pad_type::ghltar, this);
dlg->show();
});
connect(ui->confTurntableAct, &QAction::triggered, this, [this]
{
emulated_pad_settings_dialog* dlg = new emulated_pad_settings_dialog(emulated_pad_settings_dialog::pad_type::turntable, this);
dlg->show();
});
connect(ui->confUSIOAct, &QAction::triggered, this, [this]
{
emulated_pad_settings_dialog* dlg = new emulated_pad_settings_dialog(emulated_pad_settings_dialog::pad_type::usio, this);
dlg->show();
});
connect(ui->confPSMoveDS3Act, &QAction::triggered, this, [this]
{
emulated_pad_settings_dialog* dlg = new emulated_pad_settings_dialog(emulated_pad_settings_dialog::pad_type::ds3gem, this);
dlg->show();
});
connect(ui->confGunCon3Act, &QAction::triggered, this, [this]
{
emulated_pad_settings_dialog* dlg = new emulated_pad_settings_dialog(emulated_pad_settings_dialog::pad_type::guncon3, this);
dlg->show();
});
connect(ui->confTopShotEliteAct, &QAction::triggered, this, [this]
{
emulated_pad_settings_dialog* dlg = new emulated_pad_settings_dialog(emulated_pad_settings_dialog::pad_type::topshotelite, this);
dlg->show();
});
connect(ui->confTopShotFearmasterAct, &QAction::triggered, this, [this]
{
emulated_pad_settings_dialog* dlg = new emulated_pad_settings_dialog(emulated_pad_settings_dialog::pad_type::topshotfearmaster, this);
dlg->show();
});
connect(ui->actionBasic_Mouse, &QAction::triggered, this, [this]
{
basic_mouse_settings_dialog* dlg = new basic_mouse_settings_dialog(this);
dlg->show();
});
#ifndef _WIN32
ui->actionRaw_Mouse->setVisible(false);
#else
connect(ui->actionRaw_Mouse, &QAction::triggered, this, [this]
{
raw_mouse_settings_dialog* dlg = new raw_mouse_settings_dialog(this);
dlg->show();
});
#endif
connect(ui->confCamerasAct, &QAction::triggered, this, [this]()
{
camera_settings_dialog dlg(this);
dlg.exec();
});
connect(ui->confRPCNAct, &QAction::triggered, this, [this]()
{
rpcn_settings_dialog dlg(this);
dlg.exec();
});
connect(ui->confIPCAct, &QAction::triggered, this, [this]()
{
ipc_settings_dialog dlg(this);
dlg.exec();
});
connect(ui->confAutopauseManagerAct, &QAction::triggered, this, [this]()
{
auto_pause_settings_dialog dlg(this);
dlg.exec();
});
connect(ui->confVFSDialogAct, &QAction::triggered, this, [this]()
{
vfs_dialog dlg(m_gui_settings, this);
dlg.exec();
ui->bootVSHAct->setEnabled(fs::is_file(g_cfg_vfs.get_dev_flash() + "vsh/module/vsh.self")); // dev_flash may have changed. Disable vsh if not present.
m_game_list_frame->Refresh(true); // dev_hdd0 may have changed. Refresh just in case.
});
connect(ui->confSavedataManagerAct, &QAction::triggered, this, [this]
{
save_manager_dialog* save_manager = new save_manager_dialog(m_gui_settings, m_persistent_settings);
connect(this, &main_window::RequestDialogRepaint, save_manager, &save_manager_dialog::HandleRepaintUiRequest);
save_manager->show();
});
connect(ui->actionManage_Trophy_Data, &QAction::triggered, this, [this]
{
trophy_manager_dialog* trop_manager = new trophy_manager_dialog(m_gui_settings);
connect(this, &main_window::RequestDialogRepaint, trop_manager, &trophy_manager_dialog::HandleRepaintUiRequest);
trop_manager->show();
});
connect(ui->actionManage_Skylanders_Portal, &QAction::triggered, this, [this]
{
skylander_dialog* sky_diag = skylander_dialog::get_dlg(this);
sky_diag->show();
});
connect(ui->actionManage_Infinity_Base, &QAction::triggered, this, [this]
{
infinity_dialog* inf_dlg = infinity_dialog::get_dlg(this);
inf_dlg->show();
});
connect(ui->actionManage_Dimensions_ToyPad, &QAction::triggered, this, [this]
{
dimensions_dialog* dim_dlg = dimensions_dialog::get_dlg(this);
dim_dlg->show();
});
connect(ui->actionManage_Cheats, &QAction::triggered, this, [this]
{
cheat_manager_dialog* cheat_manager = cheat_manager_dialog::get_dlg(this);
cheat_manager->show();
});
connect(ui->actionManage_Game_Patches, &QAction::triggered, this, [this]
{
std::unordered_map<std::string, std::set<std::string>> games;
if (m_game_list_frame)
{
for (const game_info& game : m_game_list_frame->GetGameInfo())
{
if (game)
{
games[game->info.serial].insert(game_list::GetGameVersion(game));
}
}
}
patch_manager_dialog patch_manager(m_gui_settings, games, "", "", this);
patch_manager.exec();
});
connect(ui->patchCreatorAct, &QAction::triggered, this, [this]
{
patch_creator_dialog patch_creator(this);
patch_creator.exec();
});
connect(ui->actionManage_Users, &QAction::triggered, this, [this]
{
user_manager_dialog user_manager(m_gui_settings, m_persistent_settings, this);
user_manager.exec();
m_game_list_frame->Refresh(true); // New user may have different games unlocked.
});
connect(ui->actionManage_Screenshots, &QAction::triggered, this, [this]
{
screenshot_manager_dialog* screenshot_manager = new screenshot_manager_dialog();
screenshot_manager->show();
});
connect(ui->toolsCgDisasmAct, &QAction::triggered, this, [this]
{
cg_disasm_window* cgdw = new cg_disasm_window(m_gui_settings);
cgdw->show();
});
connect(ui->actionLog_Viewer, &QAction::triggered, this, [this]
{
log_viewer* viewer = new log_viewer(m_gui_settings);
viewer->show();
viewer->show_log();
});
connect(ui->toolsCheckConfigAct, &QAction::triggered, this, [this]
{
const QString path_last_cfg = m_gui_settings->GetValue(gui::fd_cfg_check).toString();
const QString file_path = QFileDialog::getOpenFileName(this, tr("Select rpcs3.log or config.yml"), path_last_cfg, tr("Log or Config files (*.log *.gz *.txt *.yml);;Log files (*.log *.gz);;Config Files (*.yml);;Text Files (*.txt);;All files (*.*)"));
if (file_path.isEmpty())
{
// Aborted
return;
}
const QFileInfo file_info(file_path);
if (file_info.isExecutable() || !(file_path.endsWith(".log") || file_path.endsWith(".log.gz") || file_path.endsWith(".txt") || file_path.endsWith(".yml")))
{
if (QMessageBox::question(this, tr("Weird file!"), tr("This file seems to have an unexpected type:\n%0\n\nCheck anyway?").arg(file_path)) != QMessageBox::Yes)
{
return;
}
}
bool failed = false;
QString content;
if (file_path.endsWith(".gz"))
{
if (fs::file file{file_path.toStdString()})
{
const std::vector<u8> decompressed = unzip(file.to_vector<u8>());
content = QString::fromUtf8(reinterpret_cast<const char*>(decompressed.data()), decompressed.size());
}
else
{
failed = true;
}
}
else if (QFile file(file_path); file.exists() && file.open(QIODevice::ReadOnly))
{
content = file.readAll();
}
else
{
failed = true;
}
if (failed)
{
QMessageBox::warning(this, tr("Failed to open file"), tr("The file could not be opened:\n%0").arg(file_path));
return;
}
m_gui_settings->SetValue(gui::fd_cfg_check, file_info.path());
config_checker* dlg = new config_checker(this, content, file_path.endsWith(".log") || file_path.endsWith(".log.gz"));
dlg->open();
});
connect(ui->toolskernel_explorerAct, &QAction::triggered, this, [this]
{
if (!m_kernel_explorer)
{
m_kernel_explorer = new kernel_explorer(this);
connect(m_kernel_explorer, &QDialog::finished, this, [this]() { m_kernel_explorer = nullptr; });
}
m_kernel_explorer->show();
});
connect(ui->toolsmemory_viewerAct, &QAction::triggered, this, [this]
{
if (!Emu.IsStopped())
idm::make<memory_viewer_handle>(this, make_basic_ppu_disasm());
});
connect(ui->toolsRsxDebuggerAct, &QAction::triggered, this, [this]
{
rsx_debugger* rsx = new rsx_debugger(m_gui_settings);
rsx->show();
});
connect(ui->toolsSystemCommandsAct, &QAction::triggered, this, [this]
{
if (Emu.IsStopped()) return;
if (!m_system_cmd_dialog)
{
m_system_cmd_dialog = new system_cmd_dialog(this);
connect(m_system_cmd_dialog, &QDialog::finished, this, [this]() { m_system_cmd_dialog = nullptr; });
}
m_system_cmd_dialog->show();
});
connect(ui->toolsDecryptSprxLibsAct, &QAction::triggered, this, &main_window::DecryptSPRXLibraries);
connect(ui->toolsExtractMSELFAct, &QAction::triggered, this, &main_window::ExtractMSELF);
connect(ui->toolsExtractPUPAct, &QAction::triggered, this, &main_window::ExtractPup);
connect(ui->toolsExtractTARAct, &QAction::triggered, this, &main_window::ExtractTar);
connect(ui->toolsVfsDialogAct, &QAction::triggered, this, [this]()
{
vfs_tool_dialog* dlg = new vfs_tool_dialog(this);
dlg->show();
});
connect(ui->showDebuggerAct, &QAction::triggered, this, [this](bool checked)
{
checked ? m_debugger_frame->show() : m_debugger_frame->hide();
m_gui_settings->SetValue(gui::mw_debugger, checked);
});
connect(ui->showLogAct, &QAction::triggered, this, [this](bool checked)
{
checked ? m_log_frame->show() : m_log_frame->hide();
m_gui_settings->SetValue(gui::mw_logger, checked);
});
connect(ui->showGameListAct, &QAction::triggered, this, [this](bool checked)
{
checked ? m_game_list_frame->show() : m_game_list_frame->hide();
m_gui_settings->SetValue(gui::mw_gamelist, checked);
});
connect(ui->showTitleBarsAct, &QAction::triggered, this, [this](bool checked)
{
ShowTitleBars(checked);
m_gui_settings->SetValue(gui::mw_titleBarsVisible, checked);
});
connect(ui->showToolBarAct, &QAction::triggered, this, [this](bool checked)
{
ui->toolBar->setVisible(checked);
m_gui_settings->SetValue(gui::mw_toolBarVisible, checked);
});
connect(ui->showHiddenEntriesAct, &QAction::triggered, this, [this](bool checked)
{
m_gui_settings->SetValue(gui::gl_show_hidden, checked);
m_game_list_frame->SetShowHidden(checked);
m_game_list_frame->Refresh();
});
connect(ui->showCompatibilityInGridAct, &QAction::triggered, m_game_list_frame, &game_list_frame::SetShowCompatibilityInGrid);
connect(ui->refreshGameListAct, &QAction::triggered, this, [this]
{
m_game_list_frame->Refresh(true);
});
const auto get_cats = [this](QAction* act, int& id) -> QStringList
{
QStringList categories;
if (act == ui->showCatHDDGameAct) { categories += cat::cat_hdd_game; id = Category::HDD_Game; }
else if (act == ui->showCatDiscGameAct) { categories += cat::cat_disc_game; id = Category::Disc_Game; }
else if (act == ui->showCatPS1GamesAct) { categories += cat::cat_ps1_game; id = Category::PS1_Game; }
else if (act == ui->showCatPS2GamesAct) { categories += cat::ps2_games; id = Category::PS2_Game; }
else if (act == ui->showCatPSPGamesAct) { categories += cat::psp_games; id = Category::PSP_Game; }
else if (act == ui->showCatHomeAct) { categories += cat::cat_home; id = Category::Home; }
else if (act == ui->showCatAudioVideoAct) { categories += cat::media; id = Category::Media; }
else if (act == ui->showCatGameDataAct) { categories += cat::data; id = Category::Data; }
else if (act == ui->showCatUnknownAct) { categories += cat::cat_unknown; id = Category::Unknown_Cat; }
else if (act == ui->showCatOtherAct) { categories += cat::others; id = Category::Others; }
else { gui_log.warning("categoryVisibleActGroup: category action not found"); }
return categories;
};
connect(m_category_visible_act_group, &QActionGroup::triggered, this, [this, get_cats](QAction* act)
{
int id = 0;
const QStringList categories = get_cats(act, id);
if (!categories.isEmpty())
{
const bool checked = act->isChecked();
m_game_list_frame->ToggleCategoryFilter(categories, checked);
m_gui_settings->SetCategoryVisibility(id, checked, m_is_list_mode);
}
});
connect(ui->menuGame_Categories, &QMenu::aboutToShow, ui->menuGame_Categories, [this, get_cats]()
{
const auto set_cat_count = [&](QAction* act, const QString& text)
{
int count = 0;
int id = 0; // Unused
const QStringList categories = get_cats(act, id);
for (const game_info& game : m_game_list_frame->GetGameInfo())
{
if (game && categories.contains(qstr(game->info.category))) count++;
}
act->setText(QString("%0 (%1)").arg(text).arg(count));
};
set_cat_count(ui->showCatHDDGameAct, tr("HDD Games"));
set_cat_count(ui->showCatDiscGameAct, tr("Disc Games"));
set_cat_count(ui->showCatPS1GamesAct, tr("PS1 Games"));
set_cat_count(ui->showCatPS2GamesAct, tr("PS2 Games"));
set_cat_count(ui->showCatPSPGamesAct, tr("PSP Games"));
set_cat_count(ui->showCatHomeAct, tr("Home"));
set_cat_count(ui->showCatAudioVideoAct, tr("Audio/Video"));
set_cat_count(ui->showCatGameDataAct, tr("Game Data"));
set_cat_count(ui->showCatUnknownAct, tr("Unknown"));
set_cat_count(ui->showCatOtherAct, tr("Other"));
});
connect(ui->updateAct, &QAction::triggered, this, [this]()
{
#if (!defined(_WIN32) && !defined(__linux__) && !defined(__APPLE__)) || (defined(ARCH_ARM64) && !defined(__APPLE__))
QMessageBox::warning(this, tr("Auto-updater"), tr("The auto-updater isn't available for your OS currently."));
return;
#endif
m_updater.check_for_updates(false, false, false, this);
});
connect(ui->welcomeAct, &QAction::triggered, this, [this]()
{
welcome_dialog* welcome = new welcome_dialog(m_gui_settings, true, this);
welcome->open();
});
connect(ui->supportAct, &QAction::triggered, this, [this]
{
QDesktopServices::openUrl(QUrl("https://rpcs3.net/patreon"));
});
connect(ui->aboutAct, &QAction::triggered, this, [this]
{
about_dialog dlg(this);
dlg.exec();
});
connect(ui->aboutQtAct, &QAction::triggered, qApp, &QApplication::aboutQt);
connect(m_icon_size_act_group, &QActionGroup::triggered, this, [this](QAction* act)
{
static const int index_small = gui::get_Index(gui::gl_icon_size_small);
static const int index_medium = gui::get_Index(gui::gl_icon_size_medium);
int index;
if (act == ui->setIconSizeTinyAct)
index = 0;
else if (act == ui->setIconSizeSmallAct)
index = index_small;
else if (act == ui->setIconSizeMediumAct)
index = index_medium;
else
index = gui::gl_max_slider_pos;
m_save_slider_pos = true;
ResizeIcons(index);
});
connect(ui->showCustomIconsAct, &QAction::triggered, m_game_list_frame, &game_list_frame::SetShowCustomIcons);
connect(ui->playHoverGifsAct, &QAction::triggered, m_game_list_frame, &game_list_frame::SetPlayHoverGifs);
connect(m_game_list_frame, &game_list_frame::RequestIconSizeChange, this, [this](const int& val)
{
const int idx = ui->sizeSlider->value() + val;
m_save_slider_pos = true;
ResizeIcons(idx);
});
connect(m_list_mode_act_group, &QActionGroup::triggered, this, [this](QAction* act)
{
const bool is_list_act = act == ui->setlistModeListAct;
if (is_list_act == m_is_list_mode)
return;
const int slider_pos = ui->sizeSlider->sliderPosition();
ui->sizeSlider->setSliderPosition(m_other_slider_pos);
SetIconSizeActions(m_other_slider_pos);
m_other_slider_pos = slider_pos;
m_is_list_mode = is_list_act;
m_game_list_frame->SetListMode(m_is_list_mode);
UpdateFilterActions();
});
connect(ui->toolbar_open, &QAction::triggered, this, &main_window::BootGame);
connect(ui->toolbar_refresh, &QAction::triggered, this, [this]() { m_game_list_frame->Refresh(true); });
connect(ui->toolbar_stop, &QAction::triggered, this, []()
{
gui_log.notice("User triggered stop action in toolbar");
Emu.GracefulShutdown(false);
});
connect(ui->toolbar_start, &QAction::triggered, this, &main_window::OnPlayOrPause);
connect(ui->toolbar_fullscreen, &QAction::triggered, this, [this]
{
if (isFullScreen())
{
showNormal();
ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_on);
}
else
{
showFullScreen();
ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_off);
}
});
connect(ui->toolbar_controls, &QAction::triggered, this, open_pad_settings);
connect(ui->toolbar_config, &QAction::triggered, this, [=]() { open_settings(0); });
connect(ui->toolbar_list, &QAction::triggered, this, [this]() { ui->setlistModeListAct->trigger(); });
connect(ui->toolbar_grid, &QAction::triggered, this, [this]() { ui->setlistModeGridAct->trigger(); });
connect(ui->sizeSlider, &QSlider::valueChanged, this, &main_window::ResizeIcons);
connect(ui->sizeSlider, &QSlider::sliderReleased, this, [this]
{
const int index = ui->sizeSlider->value();
m_gui_settings->SetValue(m_is_list_mode ? gui::gl_iconSize : gui::gl_iconSizeGrid, index);
SetIconSizeActions(index);
});
connect(ui->sizeSlider, &QSlider::actionTriggered, this, [this](int action)
{
if (action != QAbstractSlider::SliderNoAction && action != QAbstractSlider::SliderMove)
{ // we only want to save on mouseclicks or slider release (the other connect handles this)
m_save_slider_pos = true; // actionTriggered happens before the value was changed
}
});
connect(ui->mw_searchbar, &QLineEdit::textChanged, m_game_list_frame, &game_list_frame::SetSearchText);
connect(ui->mw_searchbar, &QLineEdit::returnPressed, m_game_list_frame, &game_list_frame::FocusAndSelectFirstEntryIfNoneIs);
connect(m_game_list_frame, &game_list_frame::FocusToSearchBar, this, [this]() { ui->mw_searchbar->setFocus(); });
}
void main_window::CreateDockWindows()
{
// new mainwindow widget because existing seems to be bugged for now
m_mw = new QMainWindow();
m_mw->setContextMenuPolicy(Qt::PreventContextMenu);
m_game_list_frame = new game_list_frame(m_gui_settings, m_emu_settings, m_persistent_settings, m_mw);
m_game_list_frame->setObjectName("gamelist");
m_debugger_frame = new debugger_frame(m_gui_settings, m_mw);
m_debugger_frame->setObjectName("debugger");
m_log_frame = new log_frame(m_gui_settings, m_mw);
m_log_frame->setObjectName("logger");
m_mw->addDockWidget(Qt::LeftDockWidgetArea, m_game_list_frame);
m_mw->addDockWidget(Qt::LeftDockWidgetArea, m_log_frame);
m_mw->addDockWidget(Qt::RightDockWidgetArea, m_debugger_frame);
m_mw->setDockNestingEnabled(true);
m_mw->resizeDocks({ m_log_frame }, { m_mw->sizeHint().height() / 10 }, Qt::Orientation::Vertical);
setCentralWidget(m_mw);
connect(m_log_frame, &log_frame::LogFrameClosed, this, [this]()
{
if (ui->showLogAct->isChecked())
{
ui->showLogAct->setChecked(false);
m_gui_settings->SetValue(gui::mw_logger, false);
}
});
connect(m_log_frame, &log_frame::PerformGoToOnDebugger, this, [this](const QString& text_argument, bool is_address, bool test_only, std::shared_ptr<bool> signal_accepted)
{
if (m_debugger_frame && m_debugger_frame->isVisible())
{
if (signal_accepted)
{
*signal_accepted = true;
}
if (!test_only)
{
if (is_address)
{
m_debugger_frame->PerformGoToRequest(text_argument);
}
else
{
m_debugger_frame->PerformGoToThreadRequest(text_argument);
}
}
}
});
connect(m_debugger_frame, &debugger_frame::DebugFrameClosed, this, [this]()
{
if (ui->showDebuggerAct->isChecked())
{
ui->showDebuggerAct->setChecked(false);
m_gui_settings->SetValue(gui::mw_debugger, false);
}
});
connect(m_game_list_frame, &game_list_frame::GameListFrameClosed, this, [this]()
{
if (ui->showGameListAct->isChecked())
{
ui->showGameListAct->setChecked(false);
m_gui_settings->SetValue(gui::mw_gamelist, false);
}
});
connect(m_game_list_frame, &game_list_frame::NotifyGameSelection, this, [this](const game_info& game)
{
// Only change the button logic while the emulator is stopped.
if (Emu.IsStopped())
{
QString tooltip;
bool enable_play_buttons = true;
if (game) // A game was selected
{
const std::string title_and_title_id = game->info.name + " [" + game->info.serial + "]";
if (title_and_title_id == Emu.GetTitleAndTitleID()) // This should usually not cause trouble, but feel free to improve.
{
tooltip = tr("Restart %0").arg(qstr(title_and_title_id));
ui->toolbar_start->setIcon(m_icon_restart);
ui->toolbar_start->setText(tr("Restart"));
}
else
{
tooltip = tr("Play %0").arg(qstr(title_and_title_id));
ui->toolbar_start->setIcon(m_icon_play);
ui->toolbar_start->setText(tr("Play"));
}
}
else if (m_selected_game) // No game was selected. Check if a game was selected before.
{
if (Emu.IsReady()) // Prefer games that are about to be booted ("Automatically start games" was set to off)
{
tooltip = tr("Play %0").arg(GetCurrentTitle());
ui->toolbar_start->setIcon(m_icon_play);
}
else if (const std::string& path = Emu.GetLastBoot(); !path.empty()) // Restartable games
{
tooltip = tr("Restart %0").arg(GetCurrentTitle());
ui->toolbar_start->setIcon(m_icon_restart);
ui->toolbar_start->setText(tr("Restart"));
}
else if (!m_recent_game_acts.isEmpty()) // Get last played game
{
tooltip = tr("Play %0").arg(m_recent_game_acts.first()->text());
}
else
{
enable_play_buttons = false;
}
}
else
{
enable_play_buttons = false;
}
ui->toolbar_start->setEnabled(enable_play_buttons);
ui->sysPauseAct->setEnabled(enable_play_buttons);
#ifdef HAS_QT_WIN_STUFF
m_thumb_playPause->setEnabled(enable_play_buttons);
#endif
if (!tooltip.isEmpty())
{
ui->toolbar_start->setToolTip(tooltip);
#ifdef HAS_QT_WIN_STUFF
m_thumb_playPause->setToolTip(tooltip);
#endif
}
}
m_selected_game = game;
});
connect(m_game_list_frame, &game_list_frame::RequestBoot, this, [this](const game_info& game, cfg_mode config_mode, const std::string& config_path, const std::string& savestate)
{
Boot(savestate.empty() ? game->info.path : savestate, game->info.serial, false, false, config_mode, config_path);
});
connect(m_game_list_frame, &game_list_frame::NotifyEmuSettingsChange, this, &main_window::NotifyEmuSettingsChange);
}
void main_window::ConfigureGuiFromSettings()
{
// Restore GUI state if needed. We need to if they exist.
if (!restoreGeometry(m_gui_settings->GetValue(gui::mw_geometry).toByteArray()))
{
// By default, set the window to 70% of the screen and the debugger frame is hidden.
m_debugger_frame->hide();
resize(QGuiApplication::primaryScreen()->availableSize() * 0.7);
}
restoreState(m_gui_settings->GetValue(gui::mw_windowState).toByteArray());
m_mw->restoreState(m_gui_settings->GetValue(gui::mw_mwState).toByteArray());
ui->freezeRecentAct->setChecked(m_gui_settings->GetValue(gui::rg_freeze).toBool());
m_rg_entries = gui_settings::Var2List(m_gui_settings->GetValue(gui::rg_entries));
// clear recent games menu of actions
for (QAction* act : m_recent_game_acts)
{
ui->bootRecentMenu->removeAction(act);
}
m_recent_game_acts.clear();
// Fill the recent games menu
for (int i = 0; i < m_rg_entries.count(); i++)
{
// adjust old unformatted entries (avoid duplication)
m_rg_entries[i] = gui::Recent_Game(m_rg_entries[i].first, m_rg_entries[i].second);
// create new action
QAction* act = CreateRecentAction(m_rg_entries[i], i + 1);
// add action to menu
if (act)
{
m_recent_game_acts.append(act);
ui->bootRecentMenu->addAction(act);
}
else
{
i--; // list count is now an entry shorter so we have to repeat the same index in order to load all other entries
}
}
ui->showLogAct->setChecked(m_gui_settings->GetValue(gui::mw_logger).toBool());
ui->showGameListAct->setChecked(m_gui_settings->GetValue(gui::mw_gamelist).toBool());
ui->showDebuggerAct->setChecked(m_gui_settings->GetValue(gui::mw_debugger).toBool());
ui->showToolBarAct->setChecked(m_gui_settings->GetValue(gui::mw_toolBarVisible).toBool());
ui->showTitleBarsAct->setChecked(m_gui_settings->GetValue(gui::mw_titleBarsVisible).toBool());
m_debugger_frame->setVisible(ui->showDebuggerAct->isChecked());
m_log_frame->setVisible(ui->showLogAct->isChecked());
m_game_list_frame->setVisible(ui->showGameListAct->isChecked());
ui->toolBar->setVisible(ui->showToolBarAct->isChecked());
ShowTitleBars(ui->showTitleBarsAct->isChecked());
ui->showHiddenEntriesAct->setChecked(m_gui_settings->GetValue(gui::gl_show_hidden).toBool());
m_game_list_frame->SetShowHidden(ui->showHiddenEntriesAct->isChecked()); // prevent GetValue in m_game_list_frame->LoadSettings
ui->showCompatibilityInGridAct->setChecked(m_gui_settings->GetValue(gui::gl_draw_compat).toBool());
ui->showCustomIconsAct->setChecked(m_gui_settings->GetValue(gui::gl_custom_icon).toBool());
ui->playHoverGifsAct->setChecked(m_gui_settings->GetValue(gui::gl_hover_gifs).toBool());
m_is_list_mode = m_gui_settings->GetValue(gui::gl_listMode).toBool();
UpdateFilterActions();
// handle icon size options
if (m_is_list_mode)
ui->setlistModeListAct->setChecked(true);
else
ui->setlistModeGridAct->setChecked(true);
const int icon_size_index = m_gui_settings->GetValue(m_is_list_mode ? gui::gl_iconSize : gui::gl_iconSizeGrid).toInt();
m_other_slider_pos = m_gui_settings->GetValue(!m_is_list_mode ? gui::gl_iconSize : gui::gl_iconSizeGrid).toInt();
ui->sizeSlider->setSliderPosition(icon_size_index);
SetIconSizeActions(icon_size_index);
// Handle log settings
m_log_frame->LoadSettings();
// Gamelist
m_game_list_frame->LoadSettings();
}
void main_window::SetIconSizeActions(int idx) const
{
static const int threshold_tiny = gui::get_Index((gui::gl_icon_size_small + gui::gl_icon_size_min) / 2);
static const int threshold_small = gui::get_Index((gui::gl_icon_size_medium + gui::gl_icon_size_small) / 2);
static const int threshold_medium = gui::get_Index((gui::gl_icon_size_max + gui::gl_icon_size_medium) / 2);
if (idx < threshold_tiny)
ui->setIconSizeTinyAct->setChecked(true);
else if (idx < threshold_small)
ui->setIconSizeSmallAct->setChecked(true);
else if (idx < threshold_medium)
ui->setIconSizeMediumAct->setChecked(true);
else
ui->setIconSizeLargeAct->setChecked(true);
}
void main_window::RemoveHDD1Caches()
{
if (fs::remove_all(rpcs3::utils::get_hdd1_dir() + "caches", false))
{
QMessageBox::information(this, tr("HDD1 Caches Removed"), tr("HDD1 caches successfully removed"));
}
else
{
QMessageBox::warning(this, tr("Error"), tr("Could not remove HDD1 caches"));
}
}
void main_window::RemoveAllCaches()
{
if (QMessageBox::question(this, tr("Confirm Removal"), tr("Remove all caches?")) != QMessageBox::Yes)
return;
const std::string cache_base_dir = rpcs3::utils::get_cache_dir();
u64 caches_count = 0;
u64 caches_removed = 0;
for (const game_info& game : m_game_list_frame->GetGameInfo()) // Loop on detected games
{
if (game && qstr(game->info.category) != cat::cat_ps3_os && fs::exists(cache_base_dir + game->info.serial)) // If not OS category and cache exists
{
caches_count++;
if (fs::remove_all(cache_base_dir + game->info.serial))
{
caches_removed++;
}
}
}
if (caches_count == caches_removed)
{
QMessageBox::information(this, tr("Caches Removed"), tr("%0 cache(s) successfully removed").arg(caches_removed));
}
else
{
QMessageBox::warning(this, tr("Error"), tr("Could not remove %0 of %1 cache(s)").arg(caches_count - caches_removed).arg(caches_count));
}
RemoveHDD1Caches();
}
void main_window::RemoveSavestates()
{
if (QMessageBox::question(this, tr("Confirm Removal"), tr("Remove savestates?")) != QMessageBox::Yes)
return;
if (fs::remove_all(fs::get_config_dir() + "savestates", false))
{
QMessageBox::information(this, tr("Savestates Removed"), tr("Savestates successfully removed"));
}
else
{
QMessageBox::warning(this, tr("Error"), tr("Could not remove savestates"));
}
}
void main_window::CleanUpGameList()
{
if (QMessageBox::question(this, tr("Confirm Removal"), tr("Remove invalid game paths from game list?\n"
"Undetectable games (zombies) as well as corrupted games will be removed from the game list file (games.yml)")) != QMessageBox::Yes)
{
return;
}
// List of serials (title id) to remove in "games.yml" file (if any)
std::vector<std::string> serials_to_remove_from_yml{};
for (const auto& [serial, path] : Emu.GetGamesConfig().get_games()) // Loop on game list file
{
bool found = false;
for (const game_info& game : m_game_list_frame->GetGameInfo()) // Loop on detected games
{
// If Disc Game and its serial is found in game list file
if (game && qstr(game->info.category) == cat::cat_disc_game && game->info.serial == serial)
{
found = true;
break;
}
}
if (!found) // If serial not found, add it to the removal list
{
serials_to_remove_from_yml.push_back(serial);
}
}
// Remove the found serials (title id) in "games.yml" file (if any)
QMessageBox::information(this, tr("Summary"), tr("%0 game(s) removed from game list").arg(Emu.RemoveGames(serials_to_remove_from_yml)));
}
void main_window::RemoveFirmwareCache()
{
const std::string cache_dir = rpcs3::utils::get_cache_dir();
if (!fs::is_dir(cache_dir))
return;
if (QMessageBox::question(this, tr("Confirm Removal"), tr("Remove firmware cache?")) != QMessageBox::Yes)
return;
u32 caches_removed = 0;
u32 caches_total = 0;
const QStringList filter{ QStringLiteral("ppu-*-lib*.sprx")};
QDirIterator dir_iter(qstr(cache_dir), filter, QDir::Dirs | QDir::NoDotAndDotDot);
while (dir_iter.hasNext())
{
const QString path = dir_iter.next();
if (QDir(path).removeRecursively())
{
++caches_removed;
gui_log.notice("Removed firmware cache: %s", path);
}
else
{
gui_log.warning("Could not remove firmware cache: %s", path);
}
++caches_total;
}
const bool success = caches_total == caches_removed;
if (success)
gui_log.success("Removed firmware cache in %s", cache_dir);
else
gui_log.fatal("Only %d/%d firmware caches could be removed in %s", caches_removed, caches_total, cache_dir);
return;
}
void main_window::CreateFirmwareCache()
{
if (!m_gui_settings->GetBootConfirmation(this))
{
return;
}
Emu.GracefulShutdown(false);
Emu.SetForceBoot(true);
if (const game_boot_result error = Emu.BootGame(g_cfg_vfs.get_dev_flash() + "sys", "", true);
error != game_boot_result::no_errors)
{
gui_log.error("Creating firmware cache failed: reason: %s", error);
}
}
void main_window::mouseDoubleClickEvent(QMouseEvent *event)
{
if (isFullScreen())
{
if (event->button() == Qt::LeftButton)
{
showNormal();
ui->toolbar_fullscreen->setIcon(m_icon_fullscreen_on);
}
}
}
/** Override the Qt close event to have the emulator stop and the application die.
*/
void main_window::closeEvent(QCloseEvent* closeEvent)
{
if (!m_gui_settings->GetBootConfirmation(this, gui::ib_confirm_exit))
{
Q_EMIT NotifyWindowCloseEvent(false);
closeEvent->ignore();
return;
}
// Cleanly stop and quit the emulator.
if (!Emu.IsStopped())
{
Emu.GracefulShutdown(false);
}
SaveWindowState();
// Flush logs here as well
logs::listener::sync_all();
Q_EMIT NotifyWindowCloseEvent(true);
Emu.Quit(true);
}
/**
Add valid disc games to gamelist (games.yml)
@param paths = dir paths to scan for game
*/
void main_window::AddGamesFromDirs(QStringList&& paths)
{
if (paths.isEmpty())
{
return;
}
// Obtain list of previously existing entries under the specificied parent paths for comparison
std::unordered_set<std::string> existing;
for (const game_info& game : m_game_list_frame->GetGameInfo())
{
if (game)
{
for (const auto& dir_path : paths)
{
if (dir_path.startsWith(game->info.path.c_str()) && fs::exists(game->info.path))
{
existing.insert(game->info.path);
break;
}
}
}
}
u32 games_added = 0;
for (const QString& path : paths)
{
games_added += Emu.AddGamesFromDir(sstr(path));
}
if (games_added)
{
gui_log.notice("AddGamesFromDirs added %d new entries", games_added);
}
m_game_list_frame->AddRefreshedSlot([this, paths = std::move(paths), existing = std::move(existing)](std::set<std::string>& claimed_paths)
{
// Execute followup operations only for newly added entries under the specified paths
std::map<std::string, QString> paths_added; // -> title id
for (const game_info& game : m_game_list_frame->GetGameInfo())
{
if (game && !existing.contains(game->info.path))
{
for (const auto& dir_path : paths)
{
if (Emu.IsPathInsideDir(game->info.path, sstr(dir_path)))
{
// Try to claim operation on directory path
std::string resolved_path = Emu.GetCallbacks().resolve_path(game->info.path);
if (!resolved_path.empty() && !claimed_paths.count(resolved_path))
{
claimed_paths.emplace(game->info.path);
paths_added.emplace(game->info.path, qstr(game->info.serial));
}
break;
}
}
}
}
if (paths_added.empty())
{
QMessageBox::information(this, tr("Nothing to add!"), tr("Could not find any new software."));
}
else
{
ShowOptionalGamePreparations(tr("Success!"), tr("Successfully added software to game list from path(s)!"), std::move(paths_added));
}
});
m_game_list_frame->Refresh(true);
}
/**
Check data for valid file types and cache their paths if necessary
@param md = data containing file urls
@param drop_paths = flag for path caching
@returns validity of file type
*/
main_window::drop_type main_window::IsValidFile(const QMimeData& md, QStringList* drop_paths)
{
if (drop_paths)
{
drop_paths->clear();
}
drop_type type = drop_type::drop_error;
QList<QUrl> list = md.urls(); // get list of all the dropped file urls
// Try to cache the data for half a second
if (m_drop_file_timestamp != umax && m_drop_file_url_list == list && get_system_time() - m_drop_file_timestamp < 500'000)
{
if (drop_paths)
{
for (auto&& url : m_drop_file_url_list)
{
drop_paths->append(url.toLocalFile());
}
}
return m_drop_file_cached_drop_type;
}
m_drop_file_url_list = std::move(list);
auto set_result = [this](drop_type type)
{
m_drop_file_timestamp = get_system_time();
m_drop_file_cached_drop_type = type;
return type;
};
for (auto&& url : m_drop_file_url_list) // check each file in url list for valid type
{
const QString path = url.toLocalFile(); // convert url to filepath
const QFileInfo info(path);
const QString suffix_lo = info.suffix().toLower();
// check for directories first, only valid if all other paths led to directories until now.
if (info.isDir())
{
if (type != drop_type::drop_dir && type != drop_type::drop_error)
{
return set_result(drop_type::drop_error);
}
type = drop_type::drop_dir;
}
else if (!info.exists())
{
// If does not exist (anymore), ignore it
continue;
}
else if (info.size() < 0x4)
{
return set_result(drop_type::drop_error);
}
else if (info.suffix() == "PUP")
{
if (m_drop_file_url_list.size() != 1)
{
return set_result(drop_type::drop_error);
}
type = drop_type::drop_pup;
}
else if (info.fileName().toLower() == "param.sfo")
{
if (type != drop_type::drop_psf && type != drop_type::drop_error)
{
return set_result(drop_type::drop_error);
}
type = drop_type::drop_psf;
}
else if (suffix_lo == "pkg")
{
if (type != drop_type::drop_rap_edat_pkg && type != drop_type::drop_error)
{
return set_result(drop_type::drop_error);
}
type = drop_type::drop_rap_edat_pkg;
}
else if (suffix_lo == "rap" || suffix_lo == "edat")
{
if (info.size() < 0x10 || (type != drop_type::drop_rap_edat_pkg && type != drop_type::drop_error))
{
return set_result(drop_type::drop_error);
}
type = drop_type::drop_rap_edat_pkg;
}
else if (m_drop_file_url_list.size() == 1)
{
if (suffix_lo == "rrc" || path.toLower().endsWith(".rrc.gz"))
{
type = drop_type::drop_rrc;
}
// The emulator allows to execute ANY filetype, just not from drag-and-drop because it is confusing to users
else if (path.toLower().endsWith(".savestat.gz") || path.toLower().endsWith(".savestat.zst") || suffix_lo == "savestat" || suffix_lo == "sprx" || suffix_lo == "self" || suffix_lo == "bin" || suffix_lo == "prx" || suffix_lo == "elf" || suffix_lo == "o")
{
type = drop_type::drop_game;
}
else
{
return set_result(drop_type::drop_error);
}
}
else
{
return set_result(drop_type::drop_error);
}
if (drop_paths) // we only need to know the paths on drop
{
drop_paths->append(path);
}
}
return set_result(type);
}
void main_window::dropEvent(QDropEvent* event)
{
event->accept();
QStringList drop_paths;
switch (IsValidFile(*event->mimeData(), &drop_paths)) // get valid file paths and drop type
{
case drop_type::drop_error:
{
event->ignore();
break;
}
case drop_type::drop_rap_edat_pkg: // install the packages
{
InstallPackages(drop_paths);
break;
}
case drop_type::drop_pup: // install the firmware
{
InstallPup(drop_paths.first());
break;
}
case drop_type::drop_psf: // Display PARAM.SFO content
{
for (const auto& psf : drop_paths)
{
const std::string psf_path = sstr(psf);
std::string info = fmt::format("Dropped PARAM.SFO '%s':\n\n%s", psf_path, psf::load(psf_path).sfo);
gui_log.success("%s", info);
info.erase(info.begin(), info.begin() + info.find_first_of('\''));
QMessageBox mb(QMessageBox::Information, tr("PARAM.SFO Information"), qstr(info), QMessageBox::Ok, this);
mb.setTextInteractionFlags(Qt::TextSelectableByMouse);
mb.exec();
}
break;
}
case drop_type::drop_dir: // import valid games to gamelist (games.yaml)
{
AddGamesFromDirs(std::move(drop_paths));
break;
}
case drop_type::drop_game: // import valid games to gamelist (games.yaml)
{
if (!m_gui_settings->GetBootConfirmation(this))
{
return;
}
Emu.GracefulShutdown(false);
if (const auto error = Emu.BootGame(sstr(drop_paths.first()), "", true); error != game_boot_result::no_errors)
{
gui_log.error("Boot failed: reason: %s, path: %s", error, drop_paths.first());
show_boot_error(error);
}
else
{
gui_log.success("Elf Boot from drag and drop done: %s", drop_paths.first());
m_game_list_frame->Refresh(true);
}
break;
}
case drop_type::drop_rrc: // replay a rsx capture file
{
BootRsxCapture(sstr(drop_paths.first()));
break;
}
}
}
void main_window::dragEnterEvent(QDragEnterEvent* event)
{
event->setAccepted(IsValidFile(*event->mimeData()) != drop_type::drop_error);
}
void main_window::dragMoveEvent(QDragMoveEvent* event)
{
event->setAccepted(IsValidFile(*event->mimeData()) != drop_type::drop_error);
}
void main_window::dragLeaveEvent(QDragLeaveEvent* event)
{
event->accept();
}
| 122,450
|
C++
|
.cpp
| 3,375
| 33.390222
| 279
| 0.708326
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,058
|
raw_mouse_settings_dialog.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/raw_mouse_settings_dialog.cpp
|
#include "stdafx.h"
#include "raw_mouse_settings_dialog.h"
#include "localized_emu.h"
#include "gui_application.h"
#include "Input/raw_mouse_config.h"
#include "Input/raw_mouse_handler.h"
#include "util/asm.hpp"
#include <QAbstractItemView>
#include <QGroupBox>
#include <QMessageBox>
#include <QVBoxLayout>
constexpr u32 button_count = 8;
raw_mouse_settings_dialog::raw_mouse_settings_dialog(QWidget* parent)
: QDialog(parent)
{
setObjectName("raw_mouse_settings_dialog");
setWindowTitle(tr("Configure Raw Mouse Handler"));
setAttribute(Qt::WA_DeleteOnClose);
setAttribute(Qt::WA_StyledBackground);
setModal(true);
QVBoxLayout* v_layout = new QVBoxLayout(this);
m_tab_widget = new QTabWidget();
m_tab_widget->setUsesScrollButtons(false);
m_button_box = new QDialogButtonBox(this);
m_button_box->setStandardButtons(QDialogButtonBox::Apply | QDialogButtonBox::Cancel | QDialogButtonBox::Save | QDialogButtonBox::RestoreDefaults);
connect(m_button_box, &QDialogButtonBox::clicked, this, [this](QAbstractButton* button)
{
if (button == m_button_box->button(QDialogButtonBox::Apply))
{
g_cfg_raw_mouse.save();
}
else if (button == m_button_box->button(QDialogButtonBox::Save))
{
g_cfg_raw_mouse.save();
accept();
}
else if (button == m_button_box->button(QDialogButtonBox::RestoreDefaults))
{
if (QMessageBox::question(this, tr("Confirm Reset"), tr("Reset settings of all players?")) != QMessageBox::Yes)
return;
reset_config();
}
else if (button == m_button_box->button(QDialogButtonBox::Cancel))
{
// Restore config
if (!g_cfg_raw_mouse.load())
{
cfg_log.notice("Could not restore raw mouse config. Using defaults.");
}
reject();
}
});
if (!g_cfg_raw_mouse.load())
{
cfg_log.notice("Could not load raw mouse config. Using defaults.");
}
constexpr u32 max_devices = 16;
g_raw_mouse_handler = std::make_unique<raw_mouse_handler>();
g_raw_mouse_handler->SetIsForGui(true);
g_raw_mouse_handler->Init(std::max(max_devices, ::size32(g_cfg_raw_mouse.players)));
g_raw_mouse_handler->set_mouse_press_callback([this](const std::string& device_name, s32 cell_code, bool pressed)
{
mouse_press(device_name, cell_code, pressed);
});
m_buttons = new QButtonGroup(this);
connect(m_buttons, &QButtonGroup::idClicked, this, &raw_mouse_settings_dialog::on_button_click);
connect(&m_update_timer, &QTimer::timeout, this, &raw_mouse_settings_dialog::on_enumeration);
connect(&m_remap_timer, &QTimer::timeout, this, [this]()
{
auto button = m_buttons->button(m_button_id);
if (--m_seconds <= 0)
{
if (button)
{
if (const int button_id = m_buttons->id(button); button_id >= 0)
{
auto& config = ::at32(g_cfg_raw_mouse.players, m_tab_widget->currentIndex());
const std::string name = config->get_button_by_index(button_id % button_count).to_string();
button->setText(name.empty() ? QStringLiteral("-") : QString::fromStdString(name));
}
}
reactivate_buttons();
return;
}
if (button)
{
button->setText(tr("[ Waiting %1 ]").arg(m_seconds));
}
});
connect(&m_mouse_release_timer, &QTimer::timeout, this, [this]()
{
m_mouse_release_timer.stop();
m_disable_mouse_release_event = false;
});
add_tabs(m_tab_widget);
v_layout->addWidget(m_tab_widget);
v_layout->addWidget(m_button_box);
setLayout(v_layout);
m_palette = m_push_buttons[0][CELL_MOUSE_BUTTON_1]->palette(); // save normal palette
connect(m_tab_widget, &QTabWidget::currentChanged, this, [this](int index)
{
handle_device_change(get_current_device_name(index));
});
on_enumeration();
handle_device_change(get_current_device_name(0));
m_update_timer.start(1000ms);
}
raw_mouse_settings_dialog::~raw_mouse_settings_dialog()
{
g_raw_mouse_handler.reset();
}
void raw_mouse_settings_dialog::update_combo_box(usz player)
{
auto& config = ::at32(g_cfg_raw_mouse.players, player);
const std::string device_name = config->device.to_string();
const QString current_device = QString::fromStdString(device_name);
bool found_device = false;
QComboBox* combo = ::at32(m_device_combos, player);
combo->blockSignals(true);
combo->clear();
combo->addItem(tr("Disabled"), QString());
{
std::lock_guard lock(g_raw_mouse_handler->m_raw_mutex);
const auto& mice = g_raw_mouse_handler->get_mice();
for (const auto& [handle, mouse] : mice)
{
const QString name = QString::fromStdString(mouse.device_name());
const QString& pretty_name = name; // Same ugly device path for now
combo->addItem(pretty_name, name);
if (current_device == name)
{
found_device = true;
}
}
}
// Keep configured device in list even if it is not connected
if (!found_device && !current_device.isEmpty())
{
const QString& pretty_name = current_device; // Same ugly device path for now
combo->addItem(pretty_name, current_device);
}
// Select index
combo->setCurrentIndex(std::max(0, combo->findData(current_device)));
combo->blockSignals(false);
if (static_cast<int>(player) == m_tab_widget->currentIndex())
{
handle_device_change(device_name);
}
}
void raw_mouse_settings_dialog::add_tabs(QTabWidget* tabs)
{
ensure(!!tabs);
constexpr u32 max_items_per_column = 6;
int rows = button_count;
for (u32 cols = 1; utils::aligned_div(button_count, cols) > max_items_per_column;)
{
rows = utils::aligned_div(button_count, ++cols);
}
constexpr usz players = g_cfg_raw_mouse.players.size();
m_push_buttons.resize(players);
ensure(g_raw_mouse_handler);
const auto insert_button = [this](int id, QPushButton* button)
{
m_buttons->addButton(button, id);
button->installEventFilter(this);
};
for (usz player = 0; player < players; player++)
{
QWidget* widget = new QWidget(this);
QGridLayout* grid_layout = new QGridLayout(this);
auto& config = ::at32(g_cfg_raw_mouse.players, player);
QHBoxLayout* h_layout = new QHBoxLayout(this);
QGroupBox* gb = new QGroupBox(tr("Device"), this);
QComboBox* combo = new QComboBox(this);
m_device_combos.push_back(combo);
update_combo_box(player);
connect(combo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this, player, combo](int index)
{
if (index < 0 || !combo)
return;
const QVariant data = combo->itemData(index);
if (!data.isValid() || !data.canConvert<QString>())
return;
const std::string device_name = data.toString().toStdString();
auto& config = ::at32(g_cfg_raw_mouse.players, player)->device;
config.from_string(device_name);
handle_device_change(device_name);
});
h_layout->addWidget(combo);
gb->setLayout(h_layout);
grid_layout->addWidget(gb, 0, 0, 1, 2);
const int first_row = grid_layout->rowCount();
for (int i = 0, row = first_row, col = 0; i < static_cast<int>(button_count); i++, row++)
{
const int cell_code = get_mouse_button_code(i);
const QString translated_cell_button = localized_emu::translated_mouse_button(cell_code);
QHBoxLayout* h_layout = new QHBoxLayout(this);
QGroupBox* gb = new QGroupBox(translated_cell_button, this);
QPushButton* pb = new QPushButton;
insert_button(static_cast<int>(player * button_count + i), pb);
const std::string saved_btn = config->get_button(cell_code);
pb->setText(saved_btn.empty() ? QStringLiteral("-") : QString::fromStdString(saved_btn));
if (row >= rows + first_row)
{
row = first_row;
col++;
}
m_push_buttons[player][cell_code] = pb;
h_layout->addWidget(pb);
gb->setLayout(h_layout);
grid_layout->addWidget(gb, row, col);
}
h_layout = new QHBoxLayout(this);
gb = new QGroupBox(tr("Mouse Acceleration"), this);
QDoubleSpinBox* mouse_acceleration_spin_box = new QDoubleSpinBox(this);
m_accel_spin_boxes.push_back(mouse_acceleration_spin_box);
mouse_acceleration_spin_box->setRange(0.1, 10.0);
mouse_acceleration_spin_box->setValue(config->mouse_acceleration.get() / 100.0);
connect(mouse_acceleration_spin_box, QOverload<double>::of(&QDoubleSpinBox::valueChanged), this, [player](double value)
{
auto& config = ::at32(g_cfg_raw_mouse.players, player)->mouse_acceleration;
config.set(std::clamp(value * 100.0, config.min, config.max));
});
h_layout->addWidget(mouse_acceleration_spin_box);
gb->setLayout(h_layout);
grid_layout->addWidget(gb, grid_layout->rowCount(), 0);
widget->setLayout(grid_layout);
tabs->addTab(widget, tr("Player %0").arg(player + 1));
}
}
void raw_mouse_settings_dialog::on_enumeration()
{
if (!g_raw_mouse_handler)
{
return;
}
const int player = m_tab_widget->currentIndex();
QComboBox* combo = ::at32(m_device_combos, player);
// Don't enumerate while the current dropdown is open
if (combo && combo->view()->isVisible())
{
return;
}
g_raw_mouse_handler->update_devices();
// Update all dropdowns
for (usz player = 0; player < g_cfg_raw_mouse.players.size(); player++)
{
update_combo_box(player);
}
}
void raw_mouse_settings_dialog::reset_config()
{
g_cfg_raw_mouse.from_default();
for (usz player = 0; player < m_push_buttons.size(); player++)
{
auto& config = ::at32(g_cfg_raw_mouse.players, player);
for (auto& [cell_code, pb] : m_push_buttons[player])
{
if (!pb)
continue;
const QString text = QString::fromStdString(config->get_button(cell_code).def);
pb->setText(text.isEmpty() ? QStringLiteral("-") : text);
}
if (QComboBox* combo = ::at32(m_device_combos, player))
{
combo->setCurrentIndex(combo->findData(QString::fromStdString(config->device.to_string())));
}
if (QDoubleSpinBox* sb = ::at32(m_accel_spin_boxes, player))
{
sb->setValue(config->mouse_acceleration.get() / 100.0);
}
}
}
void raw_mouse_settings_dialog::mouse_press(const std::string& device_name, s32 cell_code, bool pressed)
{
if (m_button_id < 0 || pressed) // Let's only react to mouse releases
{
return;
}
const int player = m_tab_widget->currentIndex();
const std::string current_device_name = get_current_device_name(player);
if (device_name != current_device_name)
{
return;
}
auto& config = ::at32(g_cfg_raw_mouse.players, m_tab_widget->currentIndex());
config->get_button_by_index(m_button_id % button_count).from_string(mouse_button_id(cell_code));
if (auto button = m_buttons->button(m_button_id))
{
button->setText(localized_emu::translated_mouse_button(cell_code));
}
reactivate_buttons();
}
void raw_mouse_settings_dialog::handle_device_change(const std::string& device_name)
{
if (is_device_active(device_name))
{
reactivate_buttons();
}
else
{
for (auto but : m_buttons->buttons())
{
but->setEnabled(false);
}
}
}
bool raw_mouse_settings_dialog::is_device_active(const std::string& device_name)
{
if (!g_raw_mouse_handler || device_name.empty())
{
return false;
}
std::lock_guard lock(g_raw_mouse_handler->m_raw_mutex);
const auto& mice = g_raw_mouse_handler->get_mice();
return std::any_of(mice.cbegin(), mice.cend(), [&device_name](const auto& entry){ return entry.second.device_name() == device_name; });
}
std::string raw_mouse_settings_dialog::get_current_device_name(int player)
{
if (player < 0)
return {};
const QVariant data = ::at32(m_device_combos, player)->currentData();
if (!data.canConvert<QString>())
return {};
return data.toString().toStdString();
}
bool raw_mouse_settings_dialog::eventFilter(QObject* object, QEvent* event)
{
switch (event->type())
{
case QEvent::MouseButtonRelease:
{
// On right click clear binding if we are not remapping pad button
if (m_button_id < 0 && !m_disable_mouse_release_event)
{
QMouseEvent* mouse_event = static_cast<QMouseEvent*>(event);
if (const auto button = qobject_cast<QPushButton*>(object); button && button->isEnabled() && mouse_event->button() == Qt::RightButton)
{
if (const int button_id = m_buttons->id(button); button_id >= 0)
{
button->setText(QStringLiteral("-"));
auto& config = ::at32(g_cfg_raw_mouse.players, m_tab_widget->currentIndex());
config->get_button_by_index(button_id % button_count).from_string("");
return true;
}
}
}
// Disabled buttons should not absorb mouseclicks
event->ignore();
break;
}
default:
{
break;
}
}
return QDialog::eventFilter(object, event);
}
void raw_mouse_settings_dialog::on_button_click(int id)
{
if (id < 0)
{
return;
}
m_update_timer.stop();
for (auto sb : m_accel_spin_boxes)
{
sb->setEnabled(false);
sb->setFocusPolicy(Qt::ClickFocus);
}
for (auto cb : m_device_combos)
{
cb->setEnabled(false);
cb->setFocusPolicy(Qt::ClickFocus);
}
for (auto but : m_buttons->buttons())
{
but->setEnabled(false);
but->setFocusPolicy(Qt::ClickFocus);
}
m_button_box->setEnabled(false);
for (auto but : m_button_box->buttons())
{
but->setFocusPolicy(Qt::ClickFocus);
}
m_button_id = id;
if (auto button = m_buttons->button(m_button_id))
{
button->setText(tr("[ Waiting %1 ]").arg(MAX_SECONDS));
button->setPalette(QPalette(Qt::blue));
button->grabMouse();
}
m_tab_widget->setEnabled(false);
m_remap_timer.start(1000);
// We need to disable the mouse release event filter or we will clear the button if the raw mouse does a right click
m_mouse_release_timer.stop();
m_disable_mouse_release_event = true;
}
void raw_mouse_settings_dialog::reactivate_buttons()
{
m_remap_timer.stop();
m_seconds = MAX_SECONDS;
if (m_button_id >= 0)
{
if (auto button = m_buttons->button(m_button_id))
{
button->setPalette(m_palette);
button->releaseMouse();
}
m_button_id = -1;
}
// Enable all buttons
m_button_box->setEnabled(true);
for (auto but : m_button_box->buttons())
{
but->setFocusPolicy(Qt::StrongFocus);
}
for (auto sb : m_accel_spin_boxes)
{
sb->setEnabled(true);
sb->setFocusPolicy(Qt::StrongFocus);
}
for (auto cb : m_device_combos)
{
cb->setEnabled(true);
cb->setFocusPolicy(Qt::StrongFocus);
}
for (auto but : m_buttons->buttons())
{
but->setEnabled(true);
but->setFocusPolicy(Qt::StrongFocus);
}
m_tab_widget->setEnabled(true);
m_mouse_release_timer.start(100ms);
m_update_timer.start(1000ms);
}
| 14,089
|
C++
|
.cpp
| 436
| 29.477064
| 147
| 0.704718
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,059
|
flow_widget.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/flow_widget.cpp
|
#include "stdafx.h"
#include "flow_widget.h"
#include <QScrollArea>
#include <QVBoxLayout>
#include <QStyleOption>
#include <QPainter>
flow_widget::flow_widget(QWidget* parent)
: QWidget(parent)
{
m_flow_layout = new flow_layout();
QWidget* widget = new QWidget(this);
widget->setLayout(m_flow_layout);
widget->setObjectName("flow_widget_content");
widget->setFocusProxy(this);
m_scroll_area = new QScrollArea(this);
m_scroll_area->setWidget(widget);
m_scroll_area->setWidgetResizable(true);
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(m_scroll_area);
layout->setContentsMargins(0, 0, 0, 0);
setLayout(layout);
}
flow_widget::~flow_widget()
{
}
void flow_widget::add_widget(flow_widget_item* widget)
{
if (widget)
{
m_widgets.push_back(widget);
m_flow_layout->addWidget(widget);
connect(widget, &flow_widget_item::navigate, this, &flow_widget::on_navigate);
connect(widget, &flow_widget_item::focused, this, &flow_widget::on_item_focus);
}
}
void flow_widget::clear()
{
m_widgets.clear();
m_flow_layout->clear();
}
flow_widget_item* flow_widget::selected_item() const
{
if (m_selected_index >= 0 && static_cast<usz>(m_selected_index) < m_widgets.size())
{
return ::at32(m_widgets, m_selected_index);
}
return nullptr;
}
void flow_widget::paintEvent(QPaintEvent* /*event*/)
{
// Needed for stylesheets to apply to QWidgets
QStyleOption option;
option.initFrom(this);
QPainter painter(this);
style()->drawPrimitive(QStyle::PE_Widget, &option, &painter, this);
}
s64 flow_widget::find_item(const flow_layout::position& pos)
{
if (pos.row < 0 || pos.col < 0)
{
return -1;
}
const auto& positions = m_flow_layout->positions();
for (s64 i = 0; i < positions.size(); i++)
{
if (const auto& other = ::at32(positions, i); other.row == pos.row && other.col == pos.col)
{
return i;
}
}
return -1;
}
flow_layout::position flow_widget::find_item(flow_widget_item* item)
{
if (item)
{
const auto& item_list = m_flow_layout->item_list();
const auto& positions = m_flow_layout->positions();
ensure(item_list.size() == positions.size());
for (s64 i = 0; i < item_list.size(); i++)
{
if (const auto& layout_item = ::at32(item_list, i); layout_item && layout_item->widget() == item)
{
return ::at32(positions, i);
}
}
}
return flow_layout::position{ .row = -1, .col = - 1};
}
flow_layout::position flow_widget::find_next_item(flow_layout::position current_pos, flow_navigation value)
{
if (current_pos.row >= 0 && current_pos.col >= 0 && m_flow_layout->rows() > 0 && m_flow_layout->cols() > 0)
{
switch (value)
{
case flow_navigation::up:
// Go up one row.
if (current_pos.row > 0)
{
current_pos.row--;
}
break;
case flow_navigation::down:
// Go down one row. Beware of last row which might have less columns.
for (const auto& pos : m_flow_layout->positions())
{;
if (pos.col != current_pos.col) continue;
if (pos.row == current_pos.row + 1)
{
current_pos.row = pos.row;
break;
}
}
break;
case flow_navigation::left:
// Go left one column.
if (current_pos.col > 0)
{
current_pos.col--;
}
break;
case flow_navigation::right:
// Go right one column. Beware of last row which might have less columns.
for (const auto& pos : m_flow_layout->positions())
{
if (pos.row > current_pos.row) break;
if (pos.row < current_pos.row) continue;
if (pos.col == current_pos.col + 1)
{
current_pos.col = pos.col;
break;
}
}
break;
case flow_navigation::home:
// Go to leftmost column.
current_pos.col = 0;
break;
case flow_navigation::end:
// Go to last column. Beware of last row which might have less columns.
for (const auto& pos : m_flow_layout->positions())
{
if (pos.row > current_pos.row) break;
if (pos.row < current_pos.row) continue;
current_pos.col = std::max(current_pos.col, pos.col);
}
break;
case flow_navigation::page_up:
// Go to top row.
current_pos.row = 0;
break;
case flow_navigation::page_down:
// Go to bottom row. Beware of last row which might have less columns.
for (const auto& pos : m_flow_layout->positions())
{
if (pos.col != current_pos.col) continue;
current_pos.row = std::max(current_pos.row, pos.row);
}
break;
}
}
return current_pos;
}
void flow_widget::select_item(flow_widget_item* item)
{
const flow_layout::position selected_pos = find_item(item);
const s64 selected_index = find_item(selected_pos);
if (selected_index < 0 || static_cast<usz>(selected_index) >= items().size())
{
m_selected_index = -1;
return;
}
m_selected_index = selected_index;
Q_EMIT ItemSelectionChanged(m_selected_index);
for (usz i = 0; i < items().size(); i++)
{
if (flow_widget_item* item = items().at(i))
{
// We need to polish the widgets in order to re-apply any stylesheet changes for the selected property.
item->selected = m_selected_index >= 0 && i == static_cast<usz>(m_selected_index);
item->polish_style();
}
}
// Make sure we see the focused widget
m_scroll_area->ensureWidgetVisible(::at32(items(), m_selected_index));
}
void flow_widget::on_item_focus()
{
select_item(static_cast<flow_widget_item*>(QObject::sender()));
}
void flow_widget::on_navigate(flow_navigation value)
{
const flow_layout::position selected_pos = find_next_item(find_item(static_cast<flow_widget_item*>(QObject::sender())), value);
const s64 selected_index = find_item(selected_pos);
if (selected_index < 0 || static_cast<usz>(selected_index) >= items().size())
{
return;
}
if (flow_widget_item* item = items().at(selected_index))
{
item->setFocus();
}
m_selected_index = selected_index;
}
void flow_widget::mouseDoubleClickEvent(QMouseEvent* ev)
{
if (!ev) return;
// Qt's itemDoubleClicked signal doesn't distinguish between mouse buttons and there is no simple way to get the pressed button.
// So we have to ignore this event when another button is pressed.
if (ev->button() != Qt::LeftButton)
{
ev->ignore();
return;
}
QWidget::mouseDoubleClickEvent(ev);
}
| 6,138
|
C++
|
.cpp
| 216
| 25.601852
| 129
| 0.684157
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,060
|
trophy_notification_frame.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/trophy_notification_frame.cpp
|
#include "trophy_notification_frame.h"
#include <QHBoxLayout>
#include <QLabel>
#include <QTimer>
static const int TROPHY_TIMEOUT_MS = 7500;
trophy_notification_frame::trophy_notification_frame(const std::vector<uchar>& imgBuffer, const SceNpTrophyDetails& trophy, int height) : QWidget()
{
setObjectName("trophy_notification_frame");
setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
setAttribute(Qt::WA_ShowWithoutActivating);
// Fill the background with black
QPalette black_background;
black_background.setColor(QPalette::Window, Qt::black);
black_background.setColor(QPalette::WindowText, Qt::white);
// Make the label
QLabel* trophyImgLabel = new QLabel;
trophyImgLabel->setAutoFillBackground(true);
trophyImgLabel->setPalette(black_background);
QImage trophyImg;
if (!imgBuffer.empty() && trophyImg.loadFromData(imgBuffer.data(), static_cast<int>(imgBuffer.size()), "PNG"))
{
trophyImg = trophyImg.scaledToHeight(height); // I might consider adding ability to change size since on hidpi this will be rather small.
trophyImgLabel->setPixmap(QPixmap::fromImage(trophyImg));
}
else
{
// This looks hideous, but it's a good placeholder.
trophyImgLabel->setPixmap(QPixmap::fromImage(QImage(":/rpcs3.ico")));
}
QLabel* trophyName = new QLabel;
trophyName->setWordWrap(true);
trophyName->setAlignment(Qt::AlignCenter);
QString trophy_string;
switch (trophy.trophyGrade)
{
case SCE_NP_TROPHY_GRADE_BRONZE: trophy_string = tr("You have earned the Bronze trophy.\n%1").arg(trophy.name); break;
case SCE_NP_TROPHY_GRADE_SILVER: trophy_string = tr("You have earned the Silver trophy.\n%1").arg(trophy.name); break;
case SCE_NP_TROPHY_GRADE_GOLD: trophy_string = tr("You have earned the Gold trophy.\n%1").arg(trophy.name); break;
case SCE_NP_TROPHY_GRADE_PLATINUM: trophy_string = tr("You have earned the Platinum trophy.\n%1").arg(trophy.name); break;
default: break;
}
trophyName->setText(trophy_string);
trophyName->setAutoFillBackground(true);
trophyName->setPalette(black_background);
QHBoxLayout* globalLayout = new QHBoxLayout;
globalLayout->addWidget(trophyImgLabel);
globalLayout->addWidget(trophyName);
setLayout(globalLayout);
setPalette(black_background);
// I may consider moving this code later to be done at a better location.
QTimer::singleShot(TROPHY_TIMEOUT_MS, [this]()
{
deleteLater();
});
}
| 2,404
|
C++
|
.cpp
| 55
| 41.563636
| 147
| 0.772027
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
5,061
|
ipc_settings_dialog.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/ipc_settings_dialog.cpp
|
#include <QMessageBox>
#include <QHBoxLayout>
#include <QPushButton>
#include <QDialogButtonBox>
#include <QGroupBox>
#include <QCheckBox>
#include <QLineEdit>
#include <QIntValidator>
#include "ipc_settings_dialog.h"
#include "Emu/IPC_config.h"
#include "Emu/IPC_socket.h"
#include "Emu/IdManager.h"
#include "Emu/System.h"
ipc_settings_dialog::ipc_settings_dialog(QWidget* parent)
: QDialog(parent)
{
setWindowTitle(tr("IPC Settings"));
setObjectName("ipc_settings_dialog");
setMinimumSize(QSize(200, 100));
QVBoxLayout* vbox_global = new QVBoxLayout();
QCheckBox* checkbox_server_enabled = new QCheckBox(tr("Enable IPC Server"));
QGroupBox* group_server_port = new QGroupBox(tr("IPC Server Port"));
QHBoxLayout* hbox_group_port = new QHBoxLayout();
QLineEdit* line_edit_server_port = new QLineEdit();
line_edit_server_port->setValidator(new QIntValidator(1025, 65535, this));
QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Cancel | QDialogButtonBox::Save);
buttons->button(QDialogButtonBox::Save)->setDefault(true);
hbox_group_port->addWidget(line_edit_server_port);
group_server_port->setLayout(hbox_group_port);
vbox_global->addWidget(checkbox_server_enabled);
vbox_global->addWidget(group_server_port);
vbox_global->addWidget(buttons);
setLayout(vbox_global);
connect(buttons, &QDialogButtonBox::accepted, this, [this, checkbox_server_enabled, line_edit_server_port]()
{
bool ok = true;
const bool server_enabled = checkbox_server_enabled->isChecked();
const int server_port = line_edit_server_port->text().toInt(&ok);
if (!ok || server_port < 1025 || server_port > 65535)
{
QMessageBox::critical(this, tr("Invalid port"), tr("The server port must be an integer in the range 1025 - 65535!"), QMessageBox::Ok);
return;
}
g_cfg_ipc.set_server_enabled(server_enabled);
g_cfg_ipc.set_port(server_port);
g_cfg_ipc.save();
if (auto manager = g_fxo->try_get<IPC_socket::IPC_server_manager>())
{
manager->set_server_enabled(server_enabled);
}
else if (server_enabled && Emu.IsRunning())
{
g_fxo->init<IPC_socket::IPC_server_manager>(true);
}
accept();
});
connect(buttons, &QDialogButtonBox::rejected, this, &QDialog::reject);
g_cfg_ipc.load();
checkbox_server_enabled->setChecked(g_cfg_ipc.get_server_enabled());
line_edit_server_port->setText(QString::number(g_cfg_ipc.get_port()));
}
| 2,413
|
C++
|
.cpp
| 61
| 36.786885
| 138
| 0.740471
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,062
|
trophy_notification_helper.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/trophy_notification_helper.cpp
|
#include "trophy_notification_helper.h"
#include "trophy_notification_frame.h"
#include "../Emu/IdManager.h"
#include "../Emu/System.h"
#include "../Emu/RSX/Overlays/overlay_manager.h"
#include "../Emu/RSX/Overlays/overlay_trophy_notification.h"
#include "Utilities/File.h"
s32 trophy_notification_helper::ShowTrophyNotification(const SceNpTrophyDetails& trophy, const std::vector<uchar>& trophy_icon_buffer)
{
if (auto manager = g_fxo->try_get<rsx::overlays::display_manager>())
{
// Allow adding more than one trophy notification. The notification class manages scheduling
auto popup = std::make_shared<rsx::overlays::trophy_notification>();
return manager->add(popup, false)->show(trophy, trophy_icon_buffer);
}
if (!Emu.HasGui())
{
return 0;
}
Emu.CallFromMainThread([=, this]
{
trophy_notification_frame* trophy_notification = new trophy_notification_frame(trophy_icon_buffer, trophy, m_game_window->frameGeometry().height() / 10);
// Move notification to upper lefthand corner
trophy_notification->move(m_game_window->mapToGlobal(QPoint(0, 0)));
trophy_notification->show();
Emu.GetCallbacks().play_sound(fs::get_config_dir() + "sounds/snd_trophy.wav");
});
return 0;
}
| 1,213
|
C++
|
.cpp
| 29
| 39.551724
| 155
| 0.751489
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,063
|
instruction_editor_dialog.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/instruction_editor_dialog.cpp
|
#include "instruction_editor_dialog.h"
#include "Emu/Cell/SPUThread.h"
#include "Emu/CPU/CPUThread.h"
#include "Emu/CPU/CPUDisAsm.h"
#include "Emu/Cell/lv2/sys_spu.h"
#include <QFontDatabase>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QPushButton>
#include <QCheckBox>
constexpr auto qstr = QString::fromStdString;
extern bool ppu_patch(u32 addr, u32 value);
extern std::string format_spu_func_info(u32 addr, cpu_thread* spu);
instruction_editor_dialog::instruction_editor_dialog(QWidget *parent, u32 _pc, CPUDisAsm* _disasm, std::function<cpu_thread*()> func)
: QDialog(parent)
, m_pc(_pc)
, m_disasm(_disasm->copy_type_erased())
, m_get_cpu(std::move(func))
{
setWindowTitle(tr("Edit instruction"));
setAttribute(Qt::WA_DeleteOnClose);
setMinimumSize(300, sizeHint().height());
const auto cpu = m_get_cpu();
m_cpu_offset = cpu && cpu->get_class() == thread_class::spu ? static_cast<spu_thread&>(*cpu).ls : vm::g_sudo_addr;
QVBoxLayout* vbox_panel(new QVBoxLayout());
QHBoxLayout* hbox_panel(new QHBoxLayout());
QVBoxLayout* vbox_left_panel(new QVBoxLayout());
QVBoxLayout* vbox_right_panel(new QVBoxLayout());
QHBoxLayout* hbox_b_panel(new QHBoxLayout());
QPushButton* button_ok(new QPushButton(tr("OK")));
QPushButton* button_cancel(new QPushButton(tr("Cancel")));
button_ok->setFixedWidth(80);
button_cancel->setFixedWidth(80);
m_instr = new QLineEdit(this);
m_instr->setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
m_instr->setMaxLength(8);
m_instr->setMaximumWidth(65);
m_disasm->change_mode(cpu_disasm_mode::normal);
m_disasm->disasm(m_pc);
m_preview = new QLabel(qstr(m_disasm->last_opcode), this);
// Layouts
vbox_left_panel->addWidget(new QLabel(tr("Address: ")));
vbox_left_panel->addWidget(new QLabel(tr("Instruction: ")));
vbox_left_panel->addWidget(new QLabel(tr("Preview: ")));
vbox_right_panel->addWidget(new QLabel(qstr(fmt::format("%08x", m_pc))));
vbox_right_panel->addWidget(m_instr);
vbox_right_panel->addWidget(m_preview);
if (cpu && cpu->get_class() == thread_class::spu)
{
// Print block information as if this instruction is its beginning
vbox_left_panel->addWidget(new QLabel(tr("Block Info: ")));
m_func_info = new QLabel("", this);
vbox_right_panel->addWidget(m_func_info);
m_func_info->setText(qstr(format_spu_func_info(m_pc, cpu)));
}
if (cpu && cpu->get_class() == thread_class::spu)
{
const auto& spu = static_cast<spu_thread&>(*cpu);
if (spu.group && spu.group->max_num > 1)
{
m_apply_for_spu_group = new QCheckBox(tr("For SPUs Group"));
vbox_left_panel->addWidget(m_apply_for_spu_group);
vbox_right_panel->addWidget(new QLabel("")); // For alignment
}
}
vbox_right_panel->setAlignment(Qt::AlignLeft);
hbox_b_panel->addWidget(button_ok);
hbox_b_panel->addWidget(button_cancel);
hbox_b_panel->setAlignment(Qt::AlignCenter);
// Main Layout
hbox_panel->addLayout(vbox_left_panel);
hbox_panel->addSpacing(10);
hbox_panel->addLayout(vbox_right_panel);
vbox_panel->addLayout(hbox_panel);
vbox_panel->addSpacing(10);
vbox_panel->addLayout(hbox_b_panel);
setLayout(vbox_panel);
// Events
connect(button_ok, &QAbstractButton::clicked, [this]()
{
const auto cpu = m_get_cpu();
if (!cpu)
{
close();
return;
}
bool ok;
const ulong opcode = m_instr->text().toULong(&ok, 16);
if (!ok || opcode > u32{umax})
{
QMessageBox::critical(this, tr("Error"), tr("Failed to parse PPU instruction."));
return;
}
const be_t<u32> swapped{static_cast<u32>(opcode)};
if (cpu->get_class() == thread_class::ppu)
{
if (!ppu_patch(m_pc, static_cast<u32>(opcode)))
{
QMessageBox::critical(this, tr("Error"), tr("Failed to patch PPU instruction."));
return;
}
}
else if (m_apply_for_spu_group && m_apply_for_spu_group->isChecked())
{
for (auto& spu : static_cast<spu_thread&>(*cpu).group->threads)
{
if (spu)
{
std::memcpy(spu->ls + m_pc, &swapped, 4);
}
}
}
else
{
std::memcpy(m_cpu_offset + m_pc, &swapped, 4);
}
accept();
});
connect(button_cancel, &QAbstractButton::clicked, this, &instruction_editor_dialog::reject);
connect(m_instr, &QLineEdit::textChanged, this, &instruction_editor_dialog::updatePreview);
updatePreview();
}
void instruction_editor_dialog::updatePreview() const
{
bool ok;
const be_t<u32> opcode{static_cast<u32>(m_instr->text().toULong(&ok, 16))};
m_disasm->change_ptr(reinterpret_cast<const u8*>(&opcode) - std::intptr_t{m_pc});
if (ok && m_disasm->disasm(m_pc))
{
m_preview->setText(qstr(m_disasm->last_opcode));
}
else
{
m_preview->setText(tr("Could not parse instruction."));
}
}
| 4,669
|
C++
|
.cpp
| 136
| 31.676471
| 133
| 0.702199
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,064
|
game_list_table.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/game_list_table.cpp
|
#include "stdafx.h"
#include "game_list_table.h"
#include "game_list_delegate.h"
#include "game_list_frame.h"
#include "gui_settings.h"
#include "localized.h"
#include "custom_table_widget_item.h"
#include "persistent_settings.h"
#include "qt_utils.h"
#include "Emu/vfs_config.h"
#include "Utilities/StrUtil.h"
#include <QHeaderView>
#include <QScrollBar>
#include <QStringBuilder>
game_list_table::game_list_table(game_list_frame* frame, std::shared_ptr<persistent_settings> persistent_settings)
: game_list(), m_game_list_frame(frame), m_persistent_settings(std::move(persistent_settings))
{
m_is_list_layout = true;
setShowGrid(false);
setItemDelegate(new game_list_delegate(this));
setEditTriggers(QAbstractItemView::NoEditTriggers);
setSelectionBehavior(QAbstractItemView::SelectRows);
setSelectionMode(QAbstractItemView::SingleSelection);
setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
verticalScrollBar()->setSingleStep(20);
horizontalScrollBar()->setSingleStep(20);
verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
verticalHeader()->setVisible(false);
horizontalHeader()->setHighlightSections(false);
horizontalHeader()->setSortIndicatorShown(true);
horizontalHeader()->setStretchLastSection(true);
horizontalHeader()->setDefaultSectionSize(150);
horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
setContextMenuPolicy(Qt::CustomContextMenu);
setAlternatingRowColors(true);
setColumnCount(static_cast<int>(gui::game_list_columns::count));
setMouseTracking(true);
connect(this, &game_list_table::size_on_disk_ready, this, [this](const game_info& game)
{
if (!game || !game->item) return;
if (QTableWidgetItem* size_item = item(static_cast<movie_item*>(game->item)->row(), static_cast<int>(gui::game_list_columns::dir_size)))
{
const u64& game_size = game->info.size_on_disk;
size_item->setText(game_size != umax ? gui::utils::format_byte_size(game_size) : tr("Unknown"));
size_item->setData(Qt::UserRole, QVariant::fromValue<qulonglong>(game_size));
}
});
connect(this, &game_list::IconReady, this, [this](const game_info& game)
{
if (!game || !game->item) return;
game->item->call_icon_func();
});
}
void game_list_table::restore_layout(const QByteArray& state)
{
// Resize to fit and get the ideal icon column width
resize_columns_to_contents();
const int icon_column_width = columnWidth(static_cast<int>(gui::game_list_columns::icon));
// Restore header layout from last session
if (!horizontalHeader()->restoreState(state) && rowCount())
{
// Nothing to do
}
// Make sure no columns are squished
fix_narrow_columns();
// Make sure that the icon column is large enough for the actual items.
// This is important if the list appeared as empty when closing the software before.
horizontalHeader()->resizeSection(static_cast<int>(gui::game_list_columns::icon), icon_column_width);
// Save new header state
horizontalHeader()->restoreState(horizontalHeader()->saveState());
}
void game_list_table::resize_columns_to_contents(int spacing)
{
verticalHeader()->resizeSections(QHeaderView::ResizeMode::ResizeToContents);
horizontalHeader()->resizeSections(QHeaderView::ResizeMode::ResizeToContents);
// Make non-icon columns slighty bigger for better visuals
for (int i = 1; i < columnCount(); i++)
{
if (isColumnHidden(i))
{
continue;
}
const int size = horizontalHeader()->sectionSize(i) + spacing;
horizontalHeader()->resizeSection(i, size);
}
}
void game_list_table::adjust_icon_column()
{
// Fixate vertical header and row height
verticalHeader()->setMinimumSectionSize(m_icon_size.height());
verticalHeader()->setMaximumSectionSize(m_icon_size.height());
// Resize the icon column
resizeColumnToContents(static_cast<int>(gui::game_list_columns::icon));
// Shorten the last section to remove horizontal scrollbar if possible
resizeColumnToContents(static_cast<int>(gui::game_list_columns::count) - 1);
}
void game_list_table::sort(usz game_count, int sort_column, Qt::SortOrder col_sort_order)
{
// Back-up old header sizes to handle unwanted column resize in case of zero search results
const int old_row_count = rowCount();
const usz old_game_count = game_count;
std::vector<int> column_widths(columnCount());
for (int i = 0; i < columnCount(); i++)
{
column_widths[i] = columnWidth(i);
}
// Sorting resizes hidden columns, so unhide them as a workaround
std::vector<int> columns_to_hide;
for (int i = 0; i < columnCount(); i++)
{
if (isColumnHidden(i))
{
setColumnHidden(i, false);
columns_to_hide.push_back(i);
}
}
// Sort the list by column and sort order
sortByColumn(sort_column, col_sort_order);
// Hide columns again
for (int col : columns_to_hide)
{
setColumnHidden(col, true);
}
// Don't resize the columns if no game is shown to preserve the header settings
if (!rowCount())
{
for (int i = 0; i < columnCount(); i++)
{
setColumnWidth(i, column_widths[i]);
}
horizontalHeader()->setSectionResizeMode(static_cast<int>(gui::game_list_columns::icon), QHeaderView::Fixed);
return;
}
// Fixate vertical header and row height
verticalHeader()->setMinimumSectionSize(m_icon_size.height());
verticalHeader()->setMaximumSectionSize(m_icon_size.height());
resizeRowsToContents();
// Resize columns if the game list was empty before
if (!old_row_count && !old_game_count)
{
resize_columns_to_contents();
}
else
{
resizeColumnToContents(static_cast<int>(gui::game_list_columns::icon));
}
// Fixate icon column
horizontalHeader()->setSectionResizeMode(static_cast<int>(gui::game_list_columns::icon), QHeaderView::Fixed);
// Shorten the last section to remove horizontal scrollbar if possible
resizeColumnToContents(static_cast<int>(gui::game_list_columns::count) - 1);
}
void game_list_table::set_custom_config_icon(const game_info& game)
{
if (!game)
{
return;
}
const QString serial = QString::fromStdString(game->info.serial);
for (int row = 0; row < rowCount(); ++row)
{
if (QTableWidgetItem* title_item = item(row, static_cast<int>(gui::game_list_columns::name)))
{
if (const QTableWidgetItem* serial_item = item(row, static_cast<int>(gui::game_list_columns::serial)); serial_item && serial_item->text() == serial)
{
title_item->setIcon(game_list_base::GetCustomConfigIcon(game));
}
}
}
}
void game_list_table::populate(
const std::vector<game_info>& game_data,
const std::map<QString, QString>& notes_map,
const std::map<QString, QString>& title_map,
const std::string& selected_item_id,
bool play_hover_movies)
{
clear_list();
setRowCount(::narrow<int>(game_data.size()));
// Default locale. Uses current Qt application language.
const QLocale locale{};
const Localized localized;
const QString game_icon_path = play_hover_movies ? QString::fromStdString(fs::get_config_dir() + "/Icons/game_icons/") : "";
const std::string dev_flash = g_cfg_vfs.get_dev_flash();
int row = 0;
int index = -1;
int selected_row = -1;
const auto get_title = [&title_map](const QString& serial, const std::string& name) -> QString
{
if (const auto it = title_map.find(serial); it != title_map.cend())
{
return it->second;
}
return QString::fromStdString(name);
};
for (const auto& game : game_data)
{
index++;
const QString serial = QString::fromStdString(game->info.serial);
const QString title = get_title(serial, game->info.name);
// Icon
custom_table_widget_item* icon_item = new custom_table_widget_item;
game->item = icon_item;
icon_item->set_icon_func([this, icon_item, game](const QVideoFrame& frame)
{
if (!icon_item || !game)
{
return;
}
if (const QPixmap pixmap = icon_item->get_movie_image(frame); icon_item->get_active() && !pixmap.isNull())
{
icon_item->setData(Qt::DecorationRole, pixmap.scaled(m_icon_size, Qt::KeepAspectRatio));
}
else
{
std::lock_guard lock(icon_item->pixmap_mutex);
icon_item->setData(Qt::DecorationRole, game->pxmap);
if (!game->has_hover_gif && !game->has_hover_pam)
{
game->pxmap = {};
}
icon_item->stop_movie();
}
});
icon_item->set_size_calc_func([this, game, cancel = icon_item->size_on_disk_loading_aborted(), dev_flash]()
{
if (game && game->info.size_on_disk == umax && (!cancel || !cancel->load()))
{
if (game->info.path.starts_with(dev_flash))
{
// Do not report size of apps inside /dev_flash (it does not make sense to do so)
game->info.size_on_disk = 0;
}
else
{
game->info.size_on_disk = fs::get_dir_size(game->info.path, 1, cancel.get());
}
if (!cancel || !cancel->load())
{
Q_EMIT size_on_disk_ready(game);
return;
}
}
});
if (play_hover_movies && game->has_hover_gif)
{
icon_item->set_movie_path(game_icon_path % serial % "/hover.gif");
}
else if (play_hover_movies && game->has_hover_pam)
{
icon_item->set_movie_path(QString::fromStdString(game->info.movie_path));
}
icon_item->setData(Qt::UserRole, index, true);
icon_item->setData(gui::custom_roles::game_role, QVariant::fromValue(game));
// Title
custom_table_widget_item* title_item = new custom_table_widget_item(title);
title_item->setIcon(game_list_base::GetCustomConfigIcon(game));
// Serial
custom_table_widget_item* serial_item = new custom_table_widget_item(game->info.serial);
if (const auto it = notes_map.find(serial); it != notes_map.cend() && !it->second.isEmpty())
{
const QString tool_tip = tr("%0 [%1]\n\nNotes:\n%2").arg(title).arg(serial).arg(it->second);
title_item->setToolTip(tool_tip);
serial_item->setToolTip(tool_tip);
}
// Move Support (http://www.psdevwiki.com/ps3/PARAM.SFO#ATTRIBUTE)
const bool supports_move = game->info.attr & 0x800000;
// Compatibility
custom_table_widget_item* compat_item = new custom_table_widget_item;
compat_item->setText(game->compat.text % (game->compat.date.isEmpty() ? QStringLiteral("") : " (" % game->compat.date % ")"));
compat_item->setData(Qt::UserRole, game->compat.index, true);
compat_item->setToolTip(game->compat.tooltip);
if (!game->compat.color.isEmpty())
{
compat_item->setData(Qt::DecorationRole, gui::utils::circle_pixmap(game->compat.color, devicePixelRatioF() * 2));
}
// Version
QString app_version = QString::fromStdString(game_list::GetGameVersion(game));
if (game->info.bootable && !game->compat.latest_version.isEmpty())
{
f64 top_ver = 0.0, app_ver = 0.0;
const bool unknown = app_version == localized.category.unknown;
const bool ok_app = !unknown && try_to_float(&app_ver, app_version.toStdString(), ::std::numeric_limits<s32>::min(), ::std::numeric_limits<s32>::max());
const bool ok_top = !unknown && try_to_float(&top_ver, game->compat.latest_version.toStdString(), ::std::numeric_limits<s32>::min(), ::std::numeric_limits<s32>::max());
// If the app is bootable and the compat database contains info about the latest patch version:
// add a hint for available software updates if the app version is unknown or lower than the latest version.
if (unknown || (ok_top && ok_app && top_ver > app_ver))
{
app_version = tr("%0 (Update available: %1)").arg(app_version, game->compat.latest_version);
}
}
// Playtimes
const quint64 elapsed_ms = m_persistent_settings->GetPlaytime(serial);
// Last played (support outdated values)
QDateTime last_played;
const QString last_played_str = m_persistent_settings->GetLastPlayed(serial);
if (!last_played_str.isEmpty())
{
last_played = QDateTime::fromString(last_played_str, gui::persistent::last_played_date_format);
if (!last_played.isValid())
{
last_played = QDateTime::fromString(last_played_str, gui::persistent::last_played_date_format_old);
}
}
const u64 game_size = game->info.size_on_disk;
setItem(row, static_cast<int>(gui::game_list_columns::icon), icon_item);
setItem(row, static_cast<int>(gui::game_list_columns::name), title_item);
setItem(row, static_cast<int>(gui::game_list_columns::serial), serial_item);
setItem(row, static_cast<int>(gui::game_list_columns::firmware), new custom_table_widget_item(game->info.fw));
setItem(row, static_cast<int>(gui::game_list_columns::version), new custom_table_widget_item(app_version));
setItem(row, static_cast<int>(gui::game_list_columns::category), new custom_table_widget_item(game->localized_category));
setItem(row, static_cast<int>(gui::game_list_columns::path), new custom_table_widget_item(game->info.path));
setItem(row, static_cast<int>(gui::game_list_columns::move), new custom_table_widget_item((supports_move ? tr("Supported") : tr("Not Supported")).toStdString(), Qt::UserRole, !supports_move));
setItem(row, static_cast<int>(gui::game_list_columns::resolution), new custom_table_widget_item(Localized::GetStringFromU32(game->info.resolution, localized.resolution.mode, true)));
setItem(row, static_cast<int>(gui::game_list_columns::sound), new custom_table_widget_item(Localized::GetStringFromU32(game->info.sound_format, localized.sound.format, true)));
setItem(row, static_cast<int>(gui::game_list_columns::parental), new custom_table_widget_item(Localized::GetStringFromU32(game->info.parental_lvl, localized.parental.level), Qt::UserRole, game->info.parental_lvl));
setItem(row, static_cast<int>(gui::game_list_columns::last_play), new custom_table_widget_item(locale.toString(last_played, last_played >= QDateTime::currentDateTime().addDays(-7) ? gui::persistent::last_played_date_with_time_of_day_format : gui::persistent::last_played_date_format_new), Qt::UserRole, last_played));
setItem(row, static_cast<int>(gui::game_list_columns::playtime), new custom_table_widget_item(elapsed_ms == 0 ? tr("Never played") : localized.GetVerboseTimeByMs(elapsed_ms), Qt::UserRole, elapsed_ms));
setItem(row, static_cast<int>(gui::game_list_columns::compat), compat_item);
setItem(row, static_cast<int>(gui::game_list_columns::dir_size), new custom_table_widget_item(game_size != umax ? gui::utils::format_byte_size(game_size) : tr("Unknown"), Qt::UserRole, QVariant::fromValue<qulonglong>(game_size)));
if (selected_item_id == game->info.path + game->info.icon_path)
{
selected_row = row;
}
row++;
}
selectRow(selected_row);
}
void game_list_table::repaint_icons(std::vector<game_info>& game_data, const QColor& icon_color, const QSize& icon_size, qreal device_pixel_ratio)
{
game_list_base::repaint_icons(game_data, icon_color, icon_size, device_pixel_ratio);
adjust_icon_column();
}
| 14,646
|
C++
|
.cpp
| 333
| 41.069069
| 320
| 0.720935
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,065
|
memory_string_searcher.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/memory_string_searcher.cpp
|
#include "memory_viewer_panel.h"
#include "Emu/Memory/vm.h"
#include "Emu/Memory/vm_reservation.h"
#include "Emu/CPU/CPUDisAsm.h"
#include "Emu/Cell/SPUDisAsm.h"
#include "Emu/IdManager.h"
#include "Utilities/Thread.h"
#include "Utilities/StrUtil.h"
#include <QCheckBox>
#include <charconv>
#include <unordered_map>
#include <regex>
#include "util/logs.hpp"
#include "util/sysinfo.hpp"
#include "util/asm.hpp"
LOG_CHANNEL(gui_log, "GUI");
template <>
void fmt_class_string<search_mode>::format(std::string& out, u64 arg)
{
if (!arg)
{
out += "No search modes have been selected";
}
for (u32 modes = static_cast<u32>(arg); modes; modes &= modes - 1)
{
const u32 mode = modes & ~(modes - 1);
auto mode_s = [&]() -> std::string_view
{
switch (mode)
{
case as_string: return "String";
case as_hex: return "HEX bytes/integer";
case as_f64: return "Double";
case as_f32: return "Float";
case as_inst: return "Instruction";
case as_regex_inst: return "Regex-Instruction";
case as_fake_spu_inst: return "SPU Instruction";
case as_regex_fake_spu_inst: return "SPU Regex-Instruction";
default: return "";
}
}();
if (mode_s.empty())
{
break;
}
if (modes != static_cast<u32>(arg))
{
out += ", ";
}
out += mode_s;
}
}
u64 memory_viewer_panel::OnSearch(std::string wstr, u32 mode)
{
if (m_rsx)
{
return 0;
}
bool case_insensitive = false;
// First characters for case insensitive search
const char first_chars[2]{ static_cast<char>(::tolower(wstr[0])), static_cast<char>(::toupper(wstr[0])) };
std::string_view insensitive_search{first_chars, 2};
if (insensitive_search[0] == insensitive_search[1])
{
// Optimization
insensitive_search.remove_suffix(1);
}
switch (mode)
{
case as_inst:
case as_string:
case as_regex_inst:
case as_fake_spu_inst:
case as_regex_fake_spu_inst:
{
case_insensitive = m_chkbox_case_insensitive->isChecked();
if (case_insensitive)
{
std::transform(wstr.begin(), wstr.end(), wstr.begin(), ::tolower);
}
break;
}
case as_hex:
{
constexpr std::string_view hex_chars = "0123456789ABCDEFabcdef";
// Split
std::vector<std::string> parts = fmt::split(wstr, {" ", ",", "0x", "0X", "\\x", "h", "H"});
// Pad zeroes
for (std::string& part : parts)
{
if (part.size() % 2)
{
gui_log.warning("Padding string part with '0' at front due to odd hexadecimal characters count.");
part.insert(part.begin(), '0');
}
}
// Concat strings
wstr.clear();
for (const std::string& part : parts)
{
wstr += part;
}
if (const usz pos = wstr.find_first_not_of(hex_chars); pos != umax)
{
gui_log.error("String '%s' cannot be interpreted as hexadecimal byte string due to unknown character '%c'.", m_search_line->text(), wstr[pos]);
return 0;
}
std::string dst;
dst.resize(wstr.size() / 2);
for (usz pos = 0; pos < wstr.size() / 2; pos++)
{
uchar value = 0;
std::from_chars(wstr.data() + pos * 2, wstr.data() + (pos + 1) * 2, value, 16);
std::memcpy(dst.data() + pos, &value, 1);
}
wstr = std::move(dst);
break;
}
case as_f64:
{
// Remove trailing 'f' letters
wstr = wstr.substr(0, wstr.find_last_not_of("Ff") + 1);
char* end{};
be_t<f64> value = std::strtod(wstr.data(), &end);
if (wstr.empty() || end != wstr.data() + wstr.size())
{
gui_log.error("String '%s' cannot be interpreted as double.", wstr);
return 0;
}
wstr.resize(sizeof(value));
std::memcpy(wstr.data(), &value, sizeof(value));
break;
}
case as_f32:
{
wstr = wstr.substr(0, wstr.find_last_not_of("Ff") + 1);
char* end{};
be_t<f32> value = std::strtof(wstr.data(), &end);
if (wstr.empty() || end != wstr.data() + wstr.size())
{
gui_log.error("String '%s' cannot be interpreted as float.", wstr);
return 0;
}
wstr.resize(sizeof(value));
std::memcpy(wstr.data(), &value, sizeof(value));
break;
}
default: ensure(false);
}
// Search the address space for the string
atomic_t<u32> found = 0;
atomic_t<u32> avail_addr = 0;
// There's no need for so many threads (except for instructions searching)
const u32 max_threads = utils::aligned_div(utils::get_thread_count(), mode < as_inst ? 2 : 1);
static constexpr u32 block_size = 0x2000000;
vm::writer_lock rlock;
const named_thread_group workers("Memory Searcher "sv, max_threads, [&]()
{
if (mode == as_inst || mode == as_fake_spu_inst || mode == as_regex_inst || mode == as_regex_fake_spu_inst)
{
auto disasm = m_disasm->copy_type_erased();
disasm->change_mode(cpu_disasm_mode::normal);
SPUDisAsm spu_dis(cpu_disasm_mode::normal, static_cast<const u8*>(m_ptr));
const usz limit = std::min(m_size, m_ptr == vm::g_sudo_addr ? 0xFFFF'0000 : m_size);
while (true)
{
u32 addr;
const bool ok = avail_addr.fetch_op([&](u32& val)
{
if (val < limit && val != umax)
{
while (m_ptr == vm::g_sudo_addr && !vm::check_addr(val, mode == as_inst ? vm::page_executable : 0))
{
// Skip unmapped memory
val = utils::align(val + 1, 0x10000);
if (!val)
{
return false;
}
}
addr = val;
// Iterate 16k instructions at a time
val += 0x10000;
if (!val)
{
// Overflow detection
val = -1;
}
return true;
}
return false;
}).second;
if (!ok)
{
return;
}
u32 spu_base_pc = 0;
if (mode == as_fake_spu_inst)
{
// Check if we can extend the limits of SPU decoder so it can use the previous 64k block
// For SPU instruction patterns
spu_base_pc = (addr >= 0x10000 && (m_ptr != vm::g_sudo_addr || vm::check_addr(addr - 0x10000, 0))) ? 0x10000 : 0;
// Set base for SPU decoder
spu_dis.change_ptr(static_cast<const u8*>(m_ptr) + addr - spu_base_pc);
}
for (u32 i = 0; i < 0x10000; i += 4)
{
if (mode == as_fake_spu_inst ? spu_dis.disasm(spu_base_pc + i) : disasm->disasm(addr + i))
{
auto& last = mode == as_fake_spu_inst ? spu_dis.last_opcode : disasm->last_opcode;
if (case_insensitive)
{
std::transform(last.begin(), last.end(), last.begin(), ::tolower);
}
std::smatch sm;
if (mode & (as_regex_inst | as_regex_fake_spu_inst) ? std::regex_search(last, sm, std::regex(wstr)) : last.find(wstr) != umax)
{
gui_log.success("Found instruction at 0x%08x: '%s'", addr + i, last);
found++;
}
}
}
}
return;
}
u32 local_found = 0;
u32 addr = 0;
bool ok = false;
const u64 addr_limit = (m_size >= block_size ? m_size - block_size : 0);
while (true)
{
if (!(addr % block_size))
{
std::tie(addr, ok) = avail_addr.fetch_op([&](u32& val)
{
if (val <= addr_limit)
{
// Iterate in 32MB blocks
val += block_size;
if (!val) val = -1; // Overflow detection
return true;
}
return false;
});
}
if (!ok)
{
break;
}
if (![&]()
{
if (m_ptr != vm::g_sudo_addr)
{
// Always valid
return true;
}
// Skip unmapped memory
for (const u32 end = utils::align(addr + 1, block_size) - 0x1000; !vm::check_addr(addr, 0); addr += 0x1000)
{
if (addr == end)
{
return false;
}
}
return true;
}())
{
if (addr == 0u - 0x1000)
{
break;
}
// The entire block is unmapped
addr += 0x1000;
continue;
}
const u64 end_mem = std::min<u64>(utils::align<u64>(addr + 1, block_size), m_size);
u64 addr_max = m_ptr == vm::g_sudo_addr ? addr : end_mem;
// Determine allocation size quickly
while (addr_max < end_mem && vm::check_addr(static_cast<u32>(addr_max), vm::page_1m_size))
{
addr_max += 0x100000;
}
while (addr_max < end_mem && vm::check_addr(static_cast<u32>(addr_max), vm::page_64k_size))
{
addr_max += 0x10000;
}
while (addr_max < end_mem && vm::check_addr(static_cast<u32>(addr_max), 0))
{
addr_max += 0x1000;
}
auto get_ptr = [&](u32 address)
{
return static_cast<const char*>(m_ptr) + address;
};
std::string_view section{get_ptr(addr), addr_max - addr};
usz first_char = 0;
auto log_occurance = [&](std::string_view& test_sv, bool always_log_str)
{
// Cut out a view which may or may not be suffixed by a single null character
// This view is a peek at the full string which resides in PS3 memory
test_sv = test_sv.substr(0, std::max<usz>(wstr.size(), 100));
const usz null_pos = test_sv.find_first_of("\n\0"sv, wstr.size());
test_sv = test_sv.substr(0, null_pos);
const usz start = test_sv.data() - get_ptr(0);
if (!always_log_str && test_sv.size() == wstr.size())
{
// Shorthand logging for identical strings
gui_log.success("Found at 0x%08x", start);
}
else if (null_pos != umax)
{
gui_log.success("Found at 0x%08x: '%s'", start, test_sv);
}
else
{
gui_log.success("Found at 0x%08x: '%s'..", start, test_sv);
}
};
if (case_insensitive)
{
while (first_char = section.find_first_of(insensitive_search, first_char), first_char != umax)
{
const u32 start = addr + ::narrow<u32>(first_char);
std::string_view test_sv{get_ptr(start), addr_max - start};
// Do not use allocating functions such as fmt::to_lower
if (test_sv.size() >= wstr.size() && std::all_of(wstr.begin(), wstr.end(), [&](const char& c) { return c == ::tolower(test_sv[&c - wstr.data()]); }))
{
// Force full logging if any character differs in case
log_occurance(test_sv, !test_sv.starts_with(wstr));
local_found++;
}
// Allow overlapping strings
first_char++;
}
}
else
{
while (first_char = section.find_first_of(wstr[0], first_char), first_char != umax)
{
const u32 start = addr + ::narrow<u32>(first_char);
std::string_view test_sv{get_ptr(start), addr_max - start};
if (test_sv.starts_with(wstr))
{
if (mode == as_string)
{
log_occurance(test_sv, false);
}
else
{
gui_log.success("Found at 0x%08x", start);
}
local_found++;
}
first_char++;
}
}
// Check if at last page
if (addr_max >= m_size - 0x1000)
{
break;
}
addr = addr_max;
}
found += local_found;
});
workers.join();
return found;
}
| 10,423
|
C++
|
.cpp
| 368
| 23.921196
| 154
| 0.605881
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,066
|
screenshot_item.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/screenshot_item.cpp
|
#include "screenshot_item.h"
#include "qt_utils.h"
#include <QVBoxLayout>
screenshot_item::screenshot_item(QWidget* parent)
: flow_widget_item(parent)
{
cb_on_first_visibility = [this]()
{
m_thread.reset(QThread::create([this]()
{
const QPixmap pixmap = gui::utils::get_centered_pixmap(icon_path, icon_size, 0, 0, 1.0, Qt::SmoothTransformation);
Q_EMIT signal_icon_update(pixmap);
}));
m_thread->start();
};
label = new QLabel(this);
QVBoxLayout* layout = new QVBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->addWidget(label);
setLayout(layout);
}
screenshot_item::~screenshot_item()
{
if (m_thread && m_thread->isRunning())
{
m_thread->wait();
}
}
| 699
|
C++
|
.cpp
| 28
| 22.821429
| 117
| 0.707646
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,067
|
progress_indicator.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/progress_indicator.cpp
|
#include "progress_indicator.h"
#ifdef HAS_QT_WIN_STUFF
#include <QCoreApplication>
#include <QWinTaskbarProgress>
#elif HAVE_QTDBUS
#include <QtDBus/QDBusMessage>
#include <QtDBus/QDBusConnection>
#endif
progress_indicator::progress_indicator(int minimum, int maximum)
{
#ifdef HAS_QT_WIN_STUFF
m_tb_button = std::make_unique<QWinTaskbarButton>();
m_tb_button->progress()->setRange(minimum, maximum);
m_tb_button->progress()->setVisible(false);
#else
m_minimum = minimum;
m_maximum = maximum;
#if HAVE_QTDBUS
update_progress(0, true, false);
#endif
#endif
}
progress_indicator::~progress_indicator()
{
#ifdef HAS_QT_WIN_STUFF
// QWinTaskbarProgress::hide() will crash if the application is already about to close, even if the object is not null.
if (!QCoreApplication::closingDown())
{
m_tb_button->progress()->hide();
}
#elif HAVE_QTDBUS
update_progress(0, false, false);
#endif
}
void progress_indicator::show(QWindow* window)
{
#ifdef HAS_QT_WIN_STUFF
m_tb_button->setWindow(window);
m_tb_button->progress()->show();
#else
Q_UNUSED(window);
#endif
}
void progress_indicator::hide()
{
#ifdef HAS_QT_WIN_STUFF
m_tb_button->progress()->hide();
#endif
}
int progress_indicator::value() const
{
#ifdef HAS_QT_WIN_STUFF
return m_tb_button->progress()->value();
#else
return m_value;
#endif
}
void progress_indicator::set_value(int value)
{
#ifdef HAS_QT_WIN_STUFF
m_tb_button->progress()->setValue(std::clamp(value, m_tb_button->progress()->minimum(), m_tb_button->progress()->maximum()));
#else
m_value = std::clamp(value, m_minimum, m_maximum);
#if HAVE_QTDBUS
update_progress(m_value, true, false);
#endif
#endif
}
void progress_indicator::set_range(int minimum, int maximum)
{
#ifdef HAS_QT_WIN_STUFF
m_tb_button->progress()->setRange(minimum, maximum);
#else
m_minimum = minimum;
m_maximum = maximum;
#endif
}
void progress_indicator::reset()
{
#ifdef HAS_QT_WIN_STUFF
m_tb_button->progress()->reset();
#else
m_value = m_minimum;
#if HAVE_QTDBUS
update_progress(m_value, false, false);
#endif
#endif
}
void progress_indicator::signal_failure()
{
#ifdef HAS_QT_WIN_STUFF
m_tb_button->progress()->stop();
#elif HAVE_QTDBUS
update_progress(0, false, true);
#endif
}
#if HAVE_QTDBUS
void progress_indicator::update_progress(int progress, bool progress_visible, bool urgent)
{
QVariantMap properties;
properties.insert(QStringLiteral("urgent"), urgent);
if (!urgent)
{
// Progress takes a value from 0.0 to 0.1
properties.insert(QStringLiteral("progress"), 1. * progress / m_maximum);
properties.insert(QStringLiteral("progress-visible"), progress_visible);
}
QDBusMessage message = QDBusMessage::createSignal(
QStringLiteral("/"),
QStringLiteral("com.canonical.Unity.LauncherEntry"),
QStringLiteral("Update"));
message << QStringLiteral("application://rpcs3.desktop") << properties;
QDBusConnection::sessionBus().send(message);
}
#endif
| 2,901
|
C++
|
.cpp
| 115
| 23.66087
| 126
| 0.757849
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,068
|
qt_music_handler.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/qt_music_handler.cpp
|
#include "qt_music_handler.h"
#include "Emu/Cell/Modules/cellMusic.h"
#include "Emu/System.h"
#include "util/logs.hpp"
#include <QAudioOutput>
#include <QUrl>
LOG_CHANNEL(music_log, "Music");
template <>
void fmt_class_string<QMediaPlayer::Error>::format(std::string& out, u64 arg)
{
format_enum(out, arg, [](QMediaPlayer::Error value)
{
switch (value)
{
case QMediaPlayer::Error::NoError: return "NoError";
case QMediaPlayer::Error::ResourceError: return "ResourceError";
case QMediaPlayer::Error::FormatError: return "FormatError";
case QMediaPlayer::Error::NetworkError: return "NetworkError";
case QMediaPlayer::Error::AccessDeniedError: return "AccessDeniedError";
}
return unknown;
});
}
template <>
void fmt_class_string<QMediaPlayer::MediaStatus>::format(std::string& out, u64 arg)
{
format_enum(out, arg, [](QMediaPlayer::MediaStatus value)
{
switch (value)
{
case QMediaPlayer::MediaStatus::NoMedia: return "NoMedia";
case QMediaPlayer::MediaStatus::LoadingMedia: return "LoadingMedia";
case QMediaPlayer::MediaStatus::LoadedMedia: return "LoadedMedia";
case QMediaPlayer::MediaStatus::StalledMedia: return "StalledMedia";
case QMediaPlayer::MediaStatus::BufferingMedia: return "BufferingMedia";
case QMediaPlayer::MediaStatus::BufferedMedia: return "BufferedMedia";
case QMediaPlayer::MediaStatus::EndOfMedia: return "EndOfMedia";
case QMediaPlayer::MediaStatus::InvalidMedia: return "InvalidMedia";
}
return unknown;
});
}
template <>
void fmt_class_string<QMediaPlayer::PlaybackState>::format(std::string& out, u64 arg)
{
format_enum(out, arg, [](QMediaPlayer::PlaybackState value)
{
switch (value)
{
case QMediaPlayer::PlaybackState::StoppedState: return "StoppedState";
case QMediaPlayer::PlaybackState::PlayingState: return "PlayingState";
case QMediaPlayer::PlaybackState::PausedState: return "PausedState";
}
return unknown;
});
}
qt_music_handler::qt_music_handler()
{
music_log.notice("Constructing Qt music handler...");
m_media_player = std::make_shared<QMediaPlayer>();
m_media_player->setAudioOutput(new QAudioOutput());
connect(m_media_player.get(), &QMediaPlayer::mediaStatusChanged, this, &qt_music_handler::handle_media_status);
connect(m_media_player.get(), &QMediaPlayer::playbackStateChanged, this, &qt_music_handler::handle_music_state);
connect(m_media_player.get(), &QMediaPlayer::errorOccurred, this, &qt_music_handler::handle_music_error);
}
qt_music_handler::~qt_music_handler()
{
Emu.BlockingCallFromMainThread([this]()
{
music_log.notice("Destroying Qt music handler...");
m_media_player->stop();
m_media_player.reset();
});
}
void qt_music_handler::stop()
{
std::lock_guard lock(m_mutex);
Emu.BlockingCallFromMainThread([this]()
{
music_log.notice("Stopping music...");
m_media_player->stop();
});
m_state = CELL_MUSIC_PB_STATUS_STOP;
}
void qt_music_handler::pause()
{
std::lock_guard lock(m_mutex);
Emu.BlockingCallFromMainThread([this]()
{
music_log.notice("Pausing music...");
m_media_player->pause();
});
m_state = CELL_MUSIC_PB_STATUS_PAUSE;
}
void qt_music_handler::play(const std::string& path)
{
std::lock_guard lock(m_mutex);
Emu.BlockingCallFromMainThread([&path, this]()
{
if (m_path != path)
{
m_path = path;
m_media_player->setSource(QUrl::fromLocalFile(QString::fromStdString(path)));
}
music_log.notice("Playing music: %s", path);
m_media_player->setPlaybackRate(1.0);
m_media_player->play();
});
m_state = CELL_MUSIC_PB_STATUS_PLAY;
}
void qt_music_handler::fast_forward(const std::string& path)
{
std::lock_guard lock(m_mutex);
Emu.BlockingCallFromMainThread([&path, this]()
{
if (m_path != path)
{
m_path = path;
m_media_player->setSource(QUrl::fromLocalFile(QString::fromStdString(path)));
}
music_log.notice("Fast-forwarding music...");
m_media_player->setPlaybackRate(2.0);
m_media_player->play();
});
m_state = CELL_MUSIC_PB_STATUS_FASTFORWARD;
}
void qt_music_handler::fast_reverse(const std::string& path)
{
std::lock_guard lock(m_mutex);
Emu.BlockingCallFromMainThread([&path, this]()
{
if (m_path != path)
{
m_path = path;
m_media_player->setSource(QUrl::fromLocalFile(QString::fromStdString(path)));
}
music_log.notice("Fast-reversing music...");
m_media_player->setPlaybackRate(-2.0);
m_media_player->play();
});
m_state = CELL_MUSIC_PB_STATUS_FASTREVERSE;
}
void qt_music_handler::set_volume(f32 volume)
{
std::lock_guard lock(m_mutex);
Emu.BlockingCallFromMainThread([&volume, this]()
{
const int new_volume = std::max<int>(0, std::min<int>(volume * 100, 100));
music_log.notice("Setting volume to %d%%", new_volume);
m_media_player->audioOutput()->setVolume(new_volume);
});
}
f32 qt_music_handler::get_volume() const
{
std::lock_guard lock(m_mutex);
f32 volume = 0.0f;
Emu.BlockingCallFromMainThread([&volume, this]()
{
volume = std::max(0.f, std::min(m_media_player->audioOutput()->volume(), 1.f));
music_log.notice("Getting volume: %d%%", volume);
});
return volume;
}
void qt_music_handler::handle_media_status(QMediaPlayer::MediaStatus status)
{
music_log.notice("New media status: %s (status=%d)", status, static_cast<int>(status));
if (!m_status_callback)
{
return;
}
switch (status)
{
case QMediaPlayer::MediaStatus::NoMedia:
case QMediaPlayer::MediaStatus::LoadingMedia:
case QMediaPlayer::MediaStatus::LoadedMedia:
case QMediaPlayer::MediaStatus::StalledMedia:
case QMediaPlayer::MediaStatus::BufferingMedia:
case QMediaPlayer::MediaStatus::BufferedMedia:
case QMediaPlayer::MediaStatus::InvalidMedia:
break;
case QMediaPlayer::MediaStatus::EndOfMedia:
m_status_callback(player_status::end_of_media);
break;
default:
music_log.error("Ignoring unknown status %d", static_cast<int>(status));
break;
}
}
void qt_music_handler::handle_music_state(QMediaPlayer::PlaybackState state)
{
music_log.notice("New playback state: %s (state=%d)", state, static_cast<int>(state));
}
void qt_music_handler::handle_music_error(QMediaPlayer::Error error, const QString& errorString)
{
music_log.error("Error event: \"%s\" (error=%s)", errorString, error);
}
| 6,180
|
C++
|
.cpp
| 196
| 29.219388
| 113
| 0.740242
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,069
|
_discord_utils.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/_discord_utils.cpp
|
#ifdef WITH_DISCORD_RPC
#include "_discord_utils.h"
#include "discord_rpc.h"
#include <string>
#include <ctime>
namespace discord
{
void initialize(const std::string& application_id)
{
DiscordEventHandlers handlers = {};
Discord_Initialize(application_id.c_str(), &handlers, 1, nullptr);
}
void shutdown()
{
Discord_Shutdown();
}
void update_presence(const std::string& state, const std::string& details, bool reset_timer)
{
DiscordRichPresence discordPresence = {};
discordPresence.details = details.c_str();
discordPresence.state = state.c_str();
discordPresence.largeImageKey = "rpcs3_logo";
discordPresence.largeImageText = "RPCS3 is the world's first PlayStation 3 emulator.";
if (reset_timer)
{
discordPresence.startTimestamp = std::time(nullptr);
}
Discord_UpdatePresence(&discordPresence);
}
}
#endif
| 851
|
C++
|
.cpp
| 31
| 25.096774
| 93
| 0.755528
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
5,070
|
qt_camera_video_sink.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/qt_camera_video_sink.cpp
|
#include "stdafx.h"
#include "qt_camera_video_sink.h"
#include "Emu/Cell/Modules/cellCamera.h"
#include "Emu/system_config.h"
#include <QtConcurrent>
LOG_CHANNEL(camera_log, "Camera");
qt_camera_video_sink::qt_camera_video_sink(bool front_facing, QObject *parent)
: QVideoSink(parent), m_front_facing(front_facing)
{
connect(this, &QVideoSink::videoFrameChanged, this, &qt_camera_video_sink::present);
}
qt_camera_video_sink::~qt_camera_video_sink()
{
}
bool qt_camera_video_sink::present(const QVideoFrame& frame)
{
if (!frame.isValid())
{
camera_log.error("Received invalid video frame");
return false;
}
// Get video image. Map frame for faster read operations.
QVideoFrame tmp(frame);
if (!tmp.map(QVideoFrame::ReadOnly))
{
camera_log.error("Failed to map video frame");
return false;
}
// Get image. This usually also converts the image to ARGB32.
QImage image = frame.toImage();
if (image.isNull())
{
camera_log.warning("Image is invalid: pixel_format=%s, format=%d", tmp.pixelFormat(), static_cast<int>(QVideoFrameFormat::imageFormatFromPixelFormat(tmp.pixelFormat())));
}
else
{
// Scale image if necessary
if (m_width > 0 && m_height > 0 && m_width != static_cast<u32>(image.width()) && m_height != static_cast<u32>(image.height()))
{
image = image.scaled(m_width, m_height, Qt::AspectRatioMode::IgnoreAspectRatio, Qt::SmoothTransformation);
}
// Determine image flip
const camera_flip flip_setting = g_cfg.io.camera_flip_option;
bool flip_horizontally = m_front_facing; // Front facing cameras are flipped already
if (flip_setting == camera_flip::horizontal || flip_setting == camera_flip::both)
{
flip_horizontally = !flip_horizontally;
}
if (m_mirrored) // Set by the game
{
flip_horizontally = !flip_horizontally;
}
bool flip_vertically = false;
if (flip_setting == camera_flip::vertical || flip_setting == camera_flip::both)
{
flip_vertically = !flip_vertically;
}
// Flip image if necessary
if (flip_horizontally || flip_vertically)
{
image = image.mirrored(flip_horizontally, flip_vertically);
}
if (image.format() != QImage::Format_RGBA8888)
{
image.convertTo(QImage::Format_RGBA8888);
}
}
const u64 new_size = m_bytesize;
image_buffer& image_buffer = m_image_buffer[m_write_index];
// Reset buffer if necessary
if (image_buffer.data.size() != new_size)
{
image_buffer.data.clear();
}
// Create buffer if necessary
if (image_buffer.data.empty() && new_size > 0)
{
image_buffer.data.resize(new_size);
image_buffer.width = m_width;
image_buffer.height = m_height;
}
if (!image_buffer.data.empty() && !image.isNull())
{
// Convert image to proper layout
// TODO: check if pixel format and bytes per pixel match and convert if necessary
// TODO: implement or improve more conversions
const u32 width = std::min<u32>(image_buffer.width, image.width());
const u32 height = std::min<u32>(image_buffer.height, image.height());
switch (m_format)
{
case CELL_CAMERA_RAW8: // The game seems to expect BGGR
{
// Let's use a very simple algorithm to convert the image to raw BGGR
const auto convert_to_bggr = [&image_buffer, &image, width, height](u32 y_begin, u32 y_end)
{
u8* dst = &image_buffer.data[image_buffer.width * y_begin];
for (u32 y = y_begin; y < height && y < y_end; y++)
{
const u8* src = image.constScanLine(y);
const bool is_top_pixel = (y % 2) == 0;
// Split loops (roughly twice the performance by removing one condition)
if (is_top_pixel)
{
for (u32 x = 0; x < width; x++, dst++, src += 4)
{
const bool is_left_pixel = (x % 2) == 0;
if (is_left_pixel)
{
*dst = src[2]; // Blue
}
else
{
*dst = src[1]; // Green
}
}
}
else
{
for (u32 x = 0; x < width; x++, dst++, src += 4)
{
const bool is_left_pixel = (x % 2) == 0;
if (is_left_pixel)
{
*dst = src[1]; // Green
}
else
{
*dst = src[0]; // Red
}
}
}
}
};
// Use a multithreaded workload. The faster we get this done, the better.
constexpr u32 thread_count = 4;
const u32 lines_per_thread = std::ceil(image_buffer.height / static_cast<double>(thread_count));
u32 y_begin = 0;
u32 y_end = lines_per_thread;
QFutureSynchronizer<void> synchronizer;
for (u32 i = 0; i < thread_count; i++)
{
synchronizer.addFuture(QtConcurrent::run(convert_to_bggr, y_begin, y_end));
y_begin = y_end;
y_end += lines_per_thread;
}
synchronizer.waitForFinished();
break;
}
//case CELL_CAMERA_YUV422:
case CELL_CAMERA_Y0_U_Y1_V:
case CELL_CAMERA_V_Y1_U_Y0:
{
// Simple RGB to Y0_U_Y1_V conversion from stackoverflow.
const auto convert_to_yuv422 = [&image_buffer, &image, width, height, format = m_format](u32 y_begin, u32 y_end)
{
constexpr int yuv_bytes_per_pixel = 2;
const int yuv_pitch = image_buffer.width * yuv_bytes_per_pixel;
const int y0_offset = (format == CELL_CAMERA_Y0_U_Y1_V) ? 0 : 3;
const int u_offset = (format == CELL_CAMERA_Y0_U_Y1_V) ? 1 : 2;
const int y1_offset = (format == CELL_CAMERA_Y0_U_Y1_V) ? 2 : 1;
const int v_offset = (format == CELL_CAMERA_Y0_U_Y1_V) ? 3 : 0;
for (u32 y = y_begin; y < height && y < y_end; y++)
{
const u8* src = image.constScanLine(y);
u8* yuv_row_ptr = &image_buffer.data[y * yuv_pitch];
for (u32 x = 0; x < width - 1; x += 2, src += 8)
{
const float r1 = src[0];
const float g1 = src[1];
const float b1 = src[2];
const float r2 = src[4];
const float g2 = src[5];
const float b2 = src[6];
const int y0 = (0.257f * r1) + (0.504f * g1) + (0.098f * b1) + 16.0f;
const int u = -(0.148f * r1) - (0.291f * g1) + (0.439f * b1) + 128.0f;
const int v = (0.439f * r1) - (0.368f * g1) - (0.071f * b1) + 128.0f;
const int y1 = (0.257f * r2) + (0.504f * g2) + (0.098f * b2) + 16.0f;
const int yuv_index = x * yuv_bytes_per_pixel;
yuv_row_ptr[yuv_index + y0_offset] = static_cast<u8>(std::clamp(y0, 0, 255));
yuv_row_ptr[yuv_index + u_offset] = static_cast<u8>(std::clamp( u, 0, 255));
yuv_row_ptr[yuv_index + y1_offset] = static_cast<u8>(std::clamp(y1, 0, 255));
yuv_row_ptr[yuv_index + v_offset] = static_cast<u8>(std::clamp( v, 0, 255));
}
}
};
// Use a multithreaded workload. The faster we get this done, the better.
constexpr u32 thread_count = 4;
const u32 lines_per_thread = std::ceil(image_buffer.height / static_cast<double>(thread_count));
u32 y_begin = 0;
u32 y_end = lines_per_thread;
QFutureSynchronizer<void> synchronizer;
for (u32 i = 0; i < thread_count; i++)
{
synchronizer.addFuture(QtConcurrent::run(convert_to_yuv422, y_begin, y_end));
y_begin = y_end;
y_end += lines_per_thread;
}
synchronizer.waitForFinished();
break;
}
case CELL_CAMERA_JPG:
case CELL_CAMERA_RGBA:
case CELL_CAMERA_RAW10:
case CELL_CAMERA_YUV420:
case CELL_CAMERA_FORMAT_UNKNOWN:
default:
std::memcpy(image_buffer.data.data(), image.constBits(), std::min<usz>(image_buffer.data.size(), image.height() * image.bytesPerLine()));
break;
}
}
// Unmap frame memory
tmp.unmap();
camera_log.trace("Wrote image to video surface. index=%d, m_frame_number=%d, width=%d, height=%d, bytesize=%d",
m_write_index, m_frame_number.load(), m_width, m_height, m_bytesize);
// Toggle write/read index
std::lock_guard lock(m_mutex);
image_buffer.frame_number = m_frame_number++;
m_write_index = read_index();
return true;
}
void qt_camera_video_sink::set_format(s32 format, u32 bytesize)
{
camera_log.notice("Setting format: format=%d, bytesize=%d", format, bytesize);
m_format = format;
m_bytesize = bytesize;
}
void qt_camera_video_sink::set_resolution(u32 width, u32 height)
{
camera_log.notice("Setting resolution: width=%d, height=%d", width, height);
m_width = width;
m_height = height;
}
void qt_camera_video_sink::set_mirrored(bool mirrored)
{
camera_log.notice("Setting mirrored: mirrored=%d", mirrored);
m_mirrored = mirrored;
}
u64 qt_camera_video_sink::frame_number() const
{
return m_frame_number.load();
}
void qt_camera_video_sink::get_image(u8* buf, u64 size, u32& width, u32& height, u64& frame_number, u64& bytes_read)
{
// Lock read buffer
std::lock_guard lock(m_mutex);
const image_buffer& image_buffer = m_image_buffer[read_index()];
width = image_buffer.width;
height = image_buffer.height;
frame_number = image_buffer.frame_number;
// Copy to out buffer
if (buf && !image_buffer.data.empty())
{
bytes_read = std::min<u64>(image_buffer.data.size(), size);
std::memcpy(buf, image_buffer.data.data(), bytes_read);
if (image_buffer.data.size() != size)
{
camera_log.error("Buffer size mismatch: in=%d, out=%d. Cropping to incoming size. Please contact a developer.", size, image_buffer.data.size());
}
}
else
{
bytes_read = 0;
}
}
u32 qt_camera_video_sink::read_index() const
{
// The read buffer index cannot be the same as the write index
return (m_write_index + 1u) % ::narrow<u32>(m_image_buffer.size());
}
| 9,251
|
C++
|
.cpp
| 269
| 30.583643
| 172
| 0.656442
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,071
|
log_frame.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/log_frame.cpp
|
#include "log_frame.h"
#include "qt_utils.h"
#include "gui_settings.h"
#include "rpcs3_version.h"
#include "Utilities/mutex.h"
#include "Utilities/lockless.h"
#include "util/asm.hpp"
#include <QMenu>
#include <QActionGroup>
#include <QScrollBar>
#include <QVBoxLayout>
#include <QTimer>
#include <QStringBuilder>
#include <sstream>
#include <deque>
#include <mutex>
extern fs::file g_tty;
extern atomic_t<s64> g_tty_size;
extern std::array<std::deque<std::string>, 16> g_tty_input;
extern std::mutex g_tty_mutex;
extern bool g_log_all_errors;
struct gui_listener : logs::listener
{
atomic_t<logs::level> enabled{logs::level{0xff}};
struct packet_t
{
logs::level sev{};
std::string msg;
};
lf_queue_slice<packet_t> pending;
lf_queue<packet_t> queue;
atomic_t<bool> show_prefix{false};
gui_listener()
: logs::listener()
{
// Self-registration
logs::listener::add(this);
}
~gui_listener()
{
}
void log(u64 stamp, const logs::message& msg, const std::string& prefix, const std::string& text) override
{
Q_UNUSED(stamp)
if (msg <= enabled)
{
packet_t p,* _new = &p;
_new->sev = msg;
if ((msg == logs::level::fatal || show_prefix) && !prefix.empty())
{
_new->msg += "{";
_new->msg += prefix;
_new->msg += "} ";
}
if (msg->name && '\0' != *msg->name)
{
_new->msg += msg->name;
_new->msg += msg == logs::level::todo ? " TODO: " : ": ";
}
else if (msg == logs::level::todo)
{
_new->msg += "TODO: ";
}
_new->msg += text;
queue.push<false>(std::move(p));
}
}
void pop()
{
pending.pop_front();
}
packet_t* get()
{
if (packet_t* _head = pending.get())
{
return _head;
}
pending = queue.pop_all();
return pending.get();
}
void clear()
{
pending = lf_queue_slice<packet_t>();
queue.pop_all();
}
};
// GUI Listener instance
static gui_listener s_gui_listener;
log_frame::log_frame(std::shared_ptr<gui_settings> _gui_settings, QWidget* parent)
: custom_dock_widget(tr("Log"), parent), m_gui_settings(std::move(_gui_settings))
{
const int max_block_count_log = m_gui_settings->GetValue(gui::l_limit).toInt();
const int max_block_count_tty = m_gui_settings->GetValue(gui::l_limit_tty).toInt();
m_tabWidget = new QTabWidget;
m_tabWidget->setObjectName(QStringLiteral("tab_widget_log"));
m_tabWidget->tabBar()->setObjectName(QStringLiteral("tab_bar_log"));
m_log = new QPlainTextEdit(m_tabWidget);
m_log->setObjectName(QStringLiteral("log_frame"));
m_log->setReadOnly(true);
m_log->setContextMenuPolicy(Qt::CustomContextMenu);
m_log->document()->setMaximumBlockCount(max_block_count_log);
m_log->installEventFilter(this);
m_tty = new QPlainTextEdit(m_tabWidget);
m_tty->setObjectName(QStringLiteral("tty_frame"));
m_tty->setReadOnly(true);
m_tty->setContextMenuPolicy(Qt::CustomContextMenu);
m_tty->document()->setMaximumBlockCount(max_block_count_tty);
m_tty->installEventFilter(this);
m_tty_input = new QLineEdit();
if (m_tty_channel >= 0)
{
m_tty_input->setPlaceholderText(tr("Channel %0").arg(m_tty_channel));
}
else
{
m_tty_input->setPlaceholderText(tr("All user channels"));
}
QVBoxLayout* tty_layout = new QVBoxLayout();
tty_layout->addWidget(m_tty);
tty_layout->addWidget(m_tty_input);
tty_layout->setContentsMargins(0, 0, 0, 0);
m_tty_container = new QWidget();
m_tty_container->setLayout(tty_layout);
m_tabWidget->addTab(m_log, tr("Log"));
m_tabWidget->addTab(m_tty_container, tr("TTY"));
setWidget(m_tabWidget);
// Open or create TTY.log
m_tty_file.open(fs::get_cache_dir() + "TTY.log", fs::read + fs::create);
CreateAndConnectActions();
LoadSettings();
m_timer = new QTimer(this);
connect(m_timer, &QTimer::timeout, this, &log_frame::UpdateUI);
}
void log_frame::SetLogLevel(logs::level lev) const
{
switch (lev)
{
case logs::level::always:
case logs::level::fatal:
{
m_fatal_act->trigger();
break;
}
case logs::level::error:
{
m_error_act->trigger();
break;
}
case logs::level::todo:
{
m_todo_act->trigger();
break;
}
case logs::level::success:
{
m_success_act->trigger();
break;
}
case logs::level::warning:
{
m_warning_act->trigger();
break;
}
case logs::level::notice:
{
m_notice_act->trigger();
break;
}
case logs::level::trace:
{
m_trace_act->trigger();
break;
}
}
}
void log_frame::SetTTYLogging(bool val) const
{
m_tty_act->setChecked(val);
}
void log_frame::CreateAndConnectActions()
{
// I, for one, welcome our lambda overlord
// It's either this or a signal mapper
// Then, probably making a list of these actions so that it's easier to iterate to generate the mapper.
auto l_initAct = [this](QAction* act, logs::level logLevel)
{
act->setCheckable(true);
// This sets the log level properly when the action is triggered.
connect(act, &QAction::triggered, [this, logLevel]()
{
s_gui_listener.enabled = std::max(logLevel, logs::level::fatal);
m_gui_settings->SetValue(gui::l_level, static_cast<uint>(logLevel));
});
};
m_clear_act = new QAction(tr("Clear"), this);
connect(m_clear_act, &QAction::triggered, [this]()
{
m_old_log_text.clear();
m_log->clear();
s_gui_listener.clear();
});
m_clear_tty_act = new QAction(tr("Clear"), this);
connect(m_clear_tty_act, &QAction::triggered, [this]()
{
m_old_tty_text.clear();
m_tty->clear();
});
m_perform_goto_on_debugger = new QAction(tr("Go-To On The Debugger"), this);
connect(m_perform_goto_on_debugger, &QAction::triggered, [this]()
{
QPlainTextEdit* pte = (m_tabWidget->currentIndex() == 1 ? m_tty : m_log);
Q_EMIT PerformGoToOnDebugger(pte->textCursor().selectedText(), true);
});
m_perform_goto_thread_on_debugger = new QAction(tr("Show Thread On The Debugger"), this);
connect(m_perform_goto_thread_on_debugger, &QAction::triggered, [this]()
{
QPlainTextEdit* pte = (m_tabWidget->currentIndex() == 1 ? m_tty : m_log);
Q_EMIT PerformGoToOnDebugger(pte->textCursor().selectedText(), false);
});
m_stack_act_tty = new QAction(tr("Stack Mode (TTY)"), this);
m_stack_act_tty->setCheckable(true);
connect(m_stack_act_tty, &QAction::toggled, [this](bool checked)
{
m_gui_settings->SetValue(gui::l_stack_tty, checked);
m_stack_tty = checked;
});
m_ansi_act_tty = new QAction(tr("ANSI Code (TTY)"), this);
m_ansi_act_tty->setCheckable(true);
connect(m_ansi_act_tty, &QAction::toggled, [this](bool checked)
{
m_gui_settings->SetValue(gui::l_ansi_code, checked);
m_ansi_tty = checked;
});
m_tty_channel_acts = new QActionGroup(this);
// Special Channel: All
QAction* all_channels_act = new QAction(tr("All user channels"), m_tty_channel_acts);
all_channels_act->setCheckable(true);
all_channels_act->setChecked(m_tty_channel == -1);
connect(all_channels_act, &QAction::triggered, [this]()
{
m_tty_channel = -1;
m_tty_input->setPlaceholderText(tr("All user channels"));
});
for (int i = 3; i < 16; i++)
{
QAction* act = new QAction(tr("Channel %0").arg(i), m_tty_channel_acts);
act->setCheckable(true);
act->setChecked(i == m_tty_channel);
connect(act, &QAction::triggered, [this, i]()
{
m_tty_channel = i;
m_tty_input->setPlaceholderText(tr("Channel %0").arg(m_tty_channel));
});
}
// Action groups make these actions mutually exclusive.
m_log_level_acts = new QActionGroup(this);
m_nothing_act = new QAction(tr("Nothing"), m_log_level_acts);
m_nothing_act->setVisible(false);
m_fatal_act = new QAction(tr("Fatal"), m_log_level_acts);
m_error_act = new QAction(tr("Error"), m_log_level_acts);
m_todo_act = new QAction(tr("Todo"), m_log_level_acts);
m_success_act = new QAction(tr("Success"), m_log_level_acts);
m_warning_act = new QAction(tr("Warning"), m_log_level_acts);
m_notice_act = new QAction(tr("Notice"), m_log_level_acts);
m_trace_act = new QAction(tr("Trace"), m_log_level_acts);
m_stack_act_log = new QAction(tr("Stack Mode (Log)"), this);
m_stack_act_log->setCheckable(true);
connect(m_stack_act_log, &QAction::toggled, [this](bool checked)
{
m_gui_settings->SetValue(gui::l_stack, checked);
m_stack_log = checked;
});
m_stack_act_err = new QAction(tr("Stack Cell Errors"), this);
m_stack_act_err->setCheckable(true);
connect(m_stack_act_err, &QAction::toggled, [this](bool checked)
{
m_gui_settings->SetValue(gui::l_stack_err, checked);
g_log_all_errors = !checked;
});
m_show_prefix_act = new QAction(tr("Show Thread Prefix"), this);
m_show_prefix_act->setCheckable(true);
connect(m_show_prefix_act, &QAction::toggled, [this](bool checked)
{
m_gui_settings->SetValue(gui::l_prefix, checked);
s_gui_listener.show_prefix = checked;
});
m_tty_act = new QAction(tr("Enable TTY"), this);
m_tty_act->setCheckable(true);
connect(m_tty_act, &QAction::triggered, [this](bool checked)
{
m_gui_settings->SetValue(gui::l_tty, checked);
});
l_initAct(m_nothing_act, logs::level::fatal);
l_initAct(m_fatal_act, logs::level::fatal);
l_initAct(m_error_act, logs::level::error);
l_initAct(m_todo_act, logs::level::todo);
l_initAct(m_success_act, logs::level::success);
l_initAct(m_warning_act, logs::level::warning);
l_initAct(m_notice_act, logs::level::notice);
l_initAct(m_trace_act, logs::level::trace);
connect(m_log, &QWidget::customContextMenuRequested, [this](const QPoint& pos)
{
QMenu* menu = m_log->createStandardContextMenu();
menu->addAction(m_clear_act);
menu->addAction(m_perform_goto_on_debugger);
menu->addAction(m_perform_goto_thread_on_debugger);
std::shared_ptr<bool> goto_signal_accepted = std::make_shared<bool>(false);
Q_EMIT PerformGoToOnDebugger("", true, true, goto_signal_accepted);
m_perform_goto_on_debugger->setEnabled(m_log->textCursor().hasSelection() && *goto_signal_accepted);
m_perform_goto_thread_on_debugger->setEnabled(m_log->textCursor().hasSelection() && *goto_signal_accepted);
m_perform_goto_on_debugger->setToolTip(tr("Jump to the selected hexadecimal address from the log text on the debugger."));
m_perform_goto_thread_on_debugger->setToolTip(tr("Show the thread that corresponds to the thread ID from lthe log text on the debugger."));
menu->addSeparator();
menu->addActions(m_log_level_acts->actions());
menu->addSeparator();
menu->addAction(m_stack_act_log);
menu->addAction(m_stack_act_err);
menu->addAction(m_show_prefix_act);
menu->exec(m_log->viewport()->mapToGlobal(pos));
});
connect(m_tty, &QWidget::customContextMenuRequested, [this](const QPoint& pos)
{
QMenu* menu = m_tty->createStandardContextMenu();
menu->addAction(m_clear_tty_act);
menu->addAction(m_perform_goto_on_debugger);
std::shared_ptr<bool> goto_signal_accepted = std::make_shared<bool>(false);
Q_EMIT PerformGoToOnDebugger("", false, true, goto_signal_accepted);
m_perform_goto_on_debugger->setEnabled(m_tty->textCursor().hasSelection() && *goto_signal_accepted);
m_perform_goto_on_debugger->setToolTip(tr("Jump to the selected hexadecimal address from the TTY text on the debugger."));
menu->addSeparator();
menu->addAction(m_tty_act);
menu->addAction(m_stack_act_tty);
menu->addAction(m_ansi_act_tty);
menu->addSeparator();
menu->addActions(m_tty_channel_acts->actions());
menu->exec(m_tty->viewport()->mapToGlobal(pos));
});
connect(m_tabWidget, &QTabWidget::currentChanged, [this](int/* index*/)
{
if (m_find_dialog)
m_find_dialog->close();
});
connect(m_tty_input, &QLineEdit::returnPressed, [this]()
{
std::string text = m_tty_input->text().toStdString();
{
std::lock_guard lock(g_tty_mutex);
if (m_tty_channel == -1)
{
for (int i = 3; i < 16; i++)
{
g_tty_input[i].push_back(text + "\n");
}
}
else
{
g_tty_input[m_tty_channel].push_back(text + "\n");
}
}
// Write to tty
if (m_tty_channel == -1)
{
text = "All channels > " + text + "\n";
}
else
{
text = fmt::format("Ch.%d > %s\n", m_tty_channel, text);
}
if (g_tty)
{
g_tty_size -= (1ll << 48);
g_tty.write(text.c_str(), text.size());
g_tty_size += (1ll << 48) + text.size();
}
m_tty_input->clear();
});
}
void log_frame::LoadSettings()
{
SetLogLevel(m_gui_settings->GetLogLevel());
SetTTYLogging(m_gui_settings->GetValue(gui::l_tty).toBool());
m_stack_log = m_gui_settings->GetValue(gui::l_stack).toBool();
m_stack_tty = m_gui_settings->GetValue(gui::l_stack_tty).toBool();
m_ansi_tty = m_gui_settings->GetValue(gui::l_ansi_code).toBool();
g_log_all_errors = !m_gui_settings->GetValue(gui::l_stack_err).toBool();
m_stack_act_log->setChecked(m_stack_log);
m_stack_act_tty->setChecked(m_stack_tty);
m_ansi_act_tty->setChecked(m_ansi_tty);
m_stack_act_err->setChecked(!g_log_all_errors);
s_gui_listener.show_prefix = m_gui_settings->GetValue(gui::l_prefix).toBool();
m_show_prefix_act->setChecked(s_gui_listener.show_prefix);
if (m_log)
{
m_log->document()->setMaximumBlockCount(m_gui_settings->GetValue(gui::l_limit).toInt());
}
if (m_tty)
{
m_tty->document()->setMaximumBlockCount(m_gui_settings->GetValue(gui::l_limit_tty).toInt());
}
// Note: There's an issue where the scrollbar value won't be set to max if we start the log frame too early,
// so let's delay the timer until we load the settings from the main window for the first time.
if (m_timer && !m_timer->isActive())
{
// Check for updates every ~10 ms
m_timer->start(10);
}
}
void log_frame::RepaintTextColors()
{
// Backup old colors
std::vector<QColor> old_colors = m_color;
QColor old_stack_color = m_color_stack;
const QColor color = gui::utils::get_foreground_color();
// Get text color. Do this once to prevent possible slowdown
m_color.clear();
m_color.push_back(gui::utils::get_label_color("log_level_always", Qt::darkCyan, Qt::cyan));
m_color.push_back(gui::utils::get_label_color("log_level_fatal", Qt::darkMagenta, Qt::magenta));
m_color.push_back(gui::utils::get_label_color("log_level_error", Qt::red, Qt::red));
m_color.push_back(gui::utils::get_label_color("log_level_todo", Qt::darkYellow, Qt::darkYellow));
m_color.push_back(gui::utils::get_label_color("log_level_success", Qt::darkGreen, Qt::green));
m_color.push_back(gui::utils::get_label_color("log_level_warning", Qt::darkYellow, Qt::darkYellow));
m_color.push_back(gui::utils::get_label_color("log_level_notice", color, color));
m_color.push_back(gui::utils::get_label_color("log_level_trace", color, color));
m_color_stack = gui::utils::get_label_color("log_stack", color, color);
// Use new colors if the old colors weren't set yet
if (old_colors.empty())
{
old_colors = m_color;
}
if (!old_stack_color.isValid())
{
old_stack_color = m_color_stack;
}
// Repaint TTY with new colors
QTextCursor tty_cursor = m_tty->textCursor();
QTextCharFormat text_format = tty_cursor.charFormat();
text_format.setForeground(gui::utils::get_label_color("tty_text", color, color));
tty_cursor.setCharFormat(text_format);
m_tty->setTextCursor(tty_cursor);
// Repaint log with new colors
QString html = m_log->document()->toHtml();
const QHash<int, QChar> log_chars
{
{ static_cast<int>(logs::level::always), '-' },
{ static_cast<int>(logs::level::fatal), 'F' },
{ static_cast<int>(logs::level::error), 'E' },
{ static_cast<int>(logs::level::todo), 'U' },
{ static_cast<int>(logs::level::success), 'S' },
{ static_cast<int>(logs::level::warning), 'W' },
{ static_cast<int>(logs::level::notice), '!' },
{ static_cast<int>(logs::level::trace), 'T' }
};
const auto replace_color = [&](logs::level lvl)
{
const QString old_style = QStringLiteral("color:") + old_colors[static_cast<int>(lvl)].name() + QStringLiteral(";\">") + log_chars[static_cast<int>(lvl)];
const QString new_style = QStringLiteral("color:") + m_color[static_cast<int>(lvl)].name() + QStringLiteral(";\">") + log_chars[static_cast<int>(lvl)];
html.replace(old_style, new_style);
};
replace_color(logs::level::always);
replace_color(logs::level::fatal);
replace_color(logs::level::error);
replace_color(logs::level::todo);
replace_color(logs::level::success);
replace_color(logs::level::warning);
replace_color(logs::level::notice);
replace_color(logs::level::trace);
// Special case: stack
const QString old_style = QStringLiteral("color:") + old_stack_color.name() + QStringLiteral(";\"> x");
const QString new_style = QStringLiteral("color:") + m_color_stack.name() + QStringLiteral(";\"> x");
html.replace(old_style, new_style);
m_log->document()->setHtml(html);
}
void log_frame::UpdateUI()
{
const std::chrono::time_point start = steady_clock::now();
const std::chrono::time_point tty_timeout = start + 4ms;
const std::chrono::time_point log_timeout = start + 7ms;
// Check TTY logs
if (u64 size = std::max<s64>(0, m_tty_file ? (g_tty_size.load() - m_tty_file.pos()) : 0))
{
if (m_tty_act->isChecked())
{
m_tty_buf.resize(std::min<u64>(size, m_tty_limited_read ? m_tty_limited_read : usz{umax}));
m_tty_buf.resize(m_tty_file.read(&m_tty_buf.front(), m_tty_buf.size()));
m_tty_limited_read = 0;
usz str_index = 0;
std::string buf_line;
while (str_index < m_tty_buf.size())
{
buf_line.assign(std::string_view(m_tty_buf).substr(str_index, m_tty_buf.find_first_of('\n', str_index) - str_index));
str_index += buf_line.size() + 1;
// Ignore control characters and greater/equal to 0x80
buf_line.erase(std::remove_if(buf_line.begin(), buf_line.end(), [](s8 c) { return c <= 0x8 || c == 0x7F || (c >= 0xE && c <= 0x1F); }), buf_line.end());
// save old scroll bar state
QScrollBar* sb = m_tty->verticalScrollBar();
const int sb_pos = sb->value();
const bool is_max = sb_pos == sb->maximum();
// save old selection
QTextCursor text_cursor{ m_tty->document() };
const int sel_pos = text_cursor.position();
int sel_start = text_cursor.selectionStart();
int sel_end = text_cursor.selectionEnd();
// clear selection or else it will get colorized as well
text_cursor.clearSelection();
QString tty_text;
if (m_ansi_tty)
{
tty_text = QString::fromStdString(buf_line);
}
else
{
// Strip ANSI color code
static const QRegularExpression ansi_color_code("\\[\\d+;\\d+(;\\d+)?m|\\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]");
tty_text = QString::fromStdString(buf_line).remove(ansi_color_code);
}
// create counter suffix and remove recurring line if needed
if (m_stack_tty)
{
text_cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
if (tty_text == m_old_tty_text)
{
text_cursor.movePosition(QTextCursor::StartOfBlock, QTextCursor::KeepAnchor);
text_cursor.insertText(tty_text % QStringLiteral(" x") % QString::number(++m_tty_counter));
}
else
{
m_tty_counter = 1;
m_old_tty_text = tty_text;
// write text to the end
m_tty->setTextCursor(text_cursor);
m_tty->appendPlainText(tty_text);
}
}
else
{
// write text to the end
m_tty->setTextCursor(text_cursor);
m_tty->appendPlainText(tty_text);
}
// if we mark text from right to left we need to swap sides (start is always smaller than end)
if (sel_pos < sel_end)
{
std::swap(sel_start, sel_end);
}
// reset old text cursor and selection
text_cursor.setPosition(sel_start);
text_cursor.setPosition(sel_end, QTextCursor::KeepAnchor);
m_tty->setTextCursor(text_cursor);
// set scrollbar to max means auto-scroll
sb->setValue(is_max ? sb->maximum() : sb_pos);
// Limit processing time
if (steady_clock::now() >= tty_timeout)
{
const s64 back = ::narrow<s64>(str_index) - ::narrow<s64>(m_tty_buf.size());
ensure(back <= 1);
if (back < 0)
{
// If more than two thirds of the buffer are unprocessed make the next fs::file::read read only that
// This is because reading is also costly on performance, and if we already know half of that takes more time than our limit..
const usz third_size = utils::aligned_div(m_tty_buf.size(), 3);
if (back <= -16384 && static_cast<usz>(0 - back) >= third_size * 2)
{
// This only really works if there is a newline somewhere
const usz known_term = std::string_view(m_tty_buf).substr(str_index, str_index * 2).find_last_of('\n', str_index * 2 - 4096);
if (known_term != umax)
{
m_tty_limited_read = known_term + 1 - str_index;
}
}
// Revert unprocessed reads
m_tty_file.seek(back, fs::seek_cur);
}
break;
}
}
}
else
{
// Advance in position without printing
m_tty_file.seek(size, fs::seek_cur);
m_tty_limited_read = 0;
}
}
const auto font_start_tag = [](const QColor& color) -> const QString { return QStringLiteral("<font color = \"") % color.name() % QStringLiteral("\">"); };
const QString font_start_tag_stack = "<font color = \"" % m_color_stack.name() % "\">";
static const QString font_end_tag = QStringLiteral("</font>");
static constexpr auto escaped = [](const QString& text, QString&& storage) -> const QString&
{
const qsizetype nline = text.indexOf(QChar('\n'));
const qsizetype spaces = text.indexOf(QStringLiteral(" "));
const qsizetype html = std::max<qsizetype>({ text.indexOf(QChar('<')), text.indexOf(QChar('>')), text.indexOf(QChar('&')), text.indexOf(QChar('\"')) });
const qsizetype pos = std::max<qsizetype>({ html, nline, spaces });
if (pos < 0)
{
// Nothing to change, do not create copies of the string
return text;
}
// Allow to return reference of new string by using temporary storage provided by argument
storage = html < 0 ? text : text.toHtmlEscaped();
if (nline >= 0)
{
storage.replace(QChar('\n'), QStringLiteral("<br/>"));
}
if (spaces >= 0)
{
storage.replace(QChar::Space, QChar::Nbsp);
}
return storage;
};
// Preserve capacity
m_log_text.resize(0);
// Handle a common case in which we may need to override the previous repetition count
bool is_first_rep = m_stack_log;
usz first_rep_counter = m_log_counter;
// Batch output of multiple lines if possible (optimization)
auto flush = [&]()
{
if (m_log_text.isEmpty() && !is_first_rep)
{
return;
}
// save old log state
QScrollBar* sb = m_log->verticalScrollBar();
const bool is_max = sb->value() == sb->maximum();
const int sb_pos = sb->value();
QTextCursor text_cursor = m_log->textCursor();
const int sel_pos = text_cursor.position();
int sel_start = text_cursor.selectionStart();
int sel_end = text_cursor.selectionEnd();
// clear selection or else it will get colorized as well
text_cursor.clearSelection();
m_log->setTextCursor(text_cursor);
if (is_first_rep)
{
// Overwrite existing repetition counter in our text document.
ensure(first_rep_counter > m_log_counter); // Anything else is a bug
text_cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
if (m_log_counter > 1)
{
constexpr int size_of_x = 2; // " x"
const int size_of_number = static_cast<int>(QString::number(m_log_counter).size());
text_cursor.movePosition(QTextCursor::PreviousCharacter, QTextCursor::KeepAnchor, size_of_x + size_of_number);
}
text_cursor.insertHtml(font_start_tag_stack % QStringLiteral(" x") % QString::number(first_rep_counter) % font_end_tag);
}
else
{
// Insert both messages and repetition prefix (append is more optimized than concatenation)
m_log_text += font_end_tag;
if (m_log_counter > 1)
{
m_log_text += font_start_tag_stack;
m_log_text += QStringLiteral(" x");
m_log_text += QString::number(m_log_counter);
m_log_text += font_end_tag;
}
m_log->appendHtml(m_log_text);
}
// if we mark text from right to left we need to swap sides (start is always smaller than end)
if (sel_pos < sel_end)
{
std::swap(sel_start, sel_end);
}
// reset old text cursor and selection
text_cursor.setPosition(sel_start);
text_cursor.setPosition(sel_end, QTextCursor::KeepAnchor);
m_log->setTextCursor(text_cursor);
// set scrollbar to max means auto-scroll
sb->setValue(is_max ? sb->maximum() : sb_pos);
m_log_text.clear();
};
const auto patch_first_stacked_message = [&]() -> bool
{
if (is_first_rep)
{
const bool needs_update = first_rep_counter > m_log_counter;
if (needs_update)
{
// Update the existing stack suffix.
flush();
}
is_first_rep = false;
m_log_counter = first_rep_counter;
return needs_update;
}
return false;
};
// Check main logs
while (auto* packet = s_gui_listener.get())
{
// Confirm log level
if (packet->sev <= s_gui_listener.enabled)
{
// Check if we can stack this log message.
if (m_stack_log && m_old_log_level == packet->sev && packet->msg == m_old_log_text)
{
if (is_first_rep)
{
// Keep tracking the old stack suffix count as long as the last known message keeps repeating.
first_rep_counter++;
}
else
{
m_log_counter++;
}
s_gui_listener.pop();
if (steady_clock::now() >= log_timeout)
{
// Must break eventually
break;
}
continue;
}
// Add/update counter suffix if needed. Try not to hold too much data at a time so the frame content will be updated frequently.
if (!patch_first_stacked_message() && (m_log_counter > 1 || m_log_text.size() > 0x1000))
{
flush();
}
if (m_log_text.isEmpty())
{
m_old_log_level = packet->sev;
m_log_text += font_start_tag(m_color[static_cast<int>(m_old_log_level)]);
}
else
{
if (packet->sev != m_old_log_level)
{
flush();
m_old_log_level = packet->sev;
m_log_text += font_start_tag(m_color[static_cast<int>(m_old_log_level)]);
}
else
{
m_log_text += QStringLiteral("<br/>");
}
}
switch (packet->sev)
{
case logs::level::always: m_log_text += QStringLiteral("- "); break;
case logs::level::fatal: m_log_text += QStringLiteral("F "); break;
case logs::level::error: m_log_text += QStringLiteral("E "); break;
case logs::level::todo: m_log_text += QStringLiteral("U "); break;
case logs::level::success: m_log_text += QStringLiteral("S "); break;
case logs::level::warning: m_log_text += QStringLiteral("W "); break;
case logs::level::notice: m_log_text += QStringLiteral("! "); break;
case logs::level::trace: m_log_text += QStringLiteral("T "); break;
}
// Print UTF-8 text.
m_log_text += escaped(QString::fromStdString(packet->msg), QString{});
if (m_stack_log)
{
m_log_counter = 1;
m_old_log_text = std::move(packet->msg);
}
}
// Drop packet
s_gui_listener.pop();
// Limit processing time
if (steady_clock::now() >= log_timeout) break;
}
if (!patch_first_stacked_message())
{
flush();
}
}
void log_frame::closeEvent(QCloseEvent *event)
{
QDockWidget::closeEvent(event);
Q_EMIT LogFrameClosed();
}
bool log_frame::eventFilter(QObject* object, QEvent* event)
{
if (object != m_log && object != m_tty)
{
return QDockWidget::eventFilter(object, event);
}
if (event->type() == QEvent::KeyPress)
{
QKeyEvent* e = static_cast<QKeyEvent*>(event);
if (e && !e->isAutoRepeat() && e->modifiers() == Qt::ControlModifier && e->key() == Qt::Key_F)
{
if (m_find_dialog && m_find_dialog->isVisible())
m_find_dialog->close();
m_find_dialog.reset(new find_dialog(static_cast<QPlainTextEdit*>(object), this));
}
}
return QDockWidget::eventFilter(object, event);
}
| 27,453
|
C++
|
.cpp
| 788
| 31.582487
| 156
| 0.674084
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,072
|
shortcut_dialog.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/shortcut_dialog.cpp
|
#include "shortcut_dialog.h"
#include "ui_shortcut_dialog.h"
#include "shortcut_settings.h"
#include <QDialogButtonBox>
#include <QPushButton>
#include <QKeySequenceEdit>
#include <QLabel>
#include <QHBoxLayout>
shortcut_dialog::shortcut_dialog(const std::shared_ptr<gui_settings> gui_settings, QWidget* parent)
: QDialog(parent), ui(new Ui::shortcut_dialog), m_gui_settings(gui_settings)
{
ui->setupUi(this);
connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &shortcut_dialog::reject);
connect(ui->buttonBox, &QDialogButtonBox::clicked, [this](QAbstractButton* button)
{
if (button == ui->buttonBox->button(QDialogButtonBox::Save))
{
save();
accept();
}
else if (button == ui->buttonBox->button(QDialogButtonBox::Apply))
{
save();
}
});
shortcut_settings sc_settings{};
for (const auto& [shortcut_key, shortcut] : sc_settings.shortcut_map)
{
const QKeySequence key_sequence = sc_settings.get_key_sequence(shortcut, gui_settings);
QLabel* label = new QLabel(shortcut.localized_name);
QKeySequenceEdit* key_sequence_edit = new QKeySequenceEdit;
key_sequence_edit->setObjectName(shortcut.name);
key_sequence_edit->setMinimumWidth(label->sizeHint().width());
key_sequence_edit->setKeySequence(key_sequence);
m_values[shortcut.name] = key_sequence.toString();
connect(key_sequence_edit, &QKeySequenceEdit::keySequenceChanged, this, &shortcut_dialog::handle_change);
QHBoxLayout* shortcut_layout = new QHBoxLayout;
shortcut_layout->addWidget(label);
shortcut_layout->addWidget(key_sequence_edit);
shortcut_layout->setStretch(0, 1);
shortcut_layout->setStretch(1, 1);
const auto add_layout = [](QVBoxLayout* layout, QHBoxLayout* shortcut_layout)
{
layout->insertLayout(layout->count() - 1, shortcut_layout); // count() - 1 to ignore the vertical spacer
};
switch (shortcut.handler_id)
{
case gui::shortcuts::shortcut_handler_id::game_window:
{
add_layout(ui->game_window_layout, shortcut_layout);
break;
}
case gui::shortcuts::shortcut_handler_id::main_window:
{
add_layout(ui->main_window_layout, shortcut_layout);
break;
}
}
}
const int min_width = std::max(
{
ui->main_window_group_box->sizeHint().width(),
ui->game_window_group_box->sizeHint().width(),
});
ui->main_window_group_box->setMinimumWidth(min_width);
ui->game_window_group_box->setMinimumWidth(min_width);
}
shortcut_dialog::~shortcut_dialog()
{
delete ui;
}
void shortcut_dialog::save()
{
shortcut_settings sc_settings{};
for (const auto& entry : m_values)
{
m_gui_settings->SetValue(sc_settings.get_shortcut_gui_save(entry.first), entry.second, false);
}
m_gui_settings->sync();
Q_EMIT saved();
}
void shortcut_dialog::handle_change(const QKeySequence& keySequence)
{
m_values[sender()->objectName()] = keySequence.toString();
}
| 2,832
|
C++
|
.cpp
| 85
| 30.741176
| 107
| 0.741569
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,073
|
movie_item.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/movie_item.cpp
|
#include "stdafx.h"
#include "movie_item.h"
movie_item::movie_item() : QTableWidgetItem(), movie_item_base()
{
}
movie_item::movie_item(const QString& text, int type) : QTableWidgetItem(text, type), movie_item_base()
{
}
movie_item::movie_item(const QIcon& icon, const QString& text, int type) : QTableWidgetItem(icon, text, type), movie_item_base()
{
}
| 357
|
C++
|
.cpp
| 11
| 31.181818
| 128
| 0.734694
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,074
|
update_manager.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/update_manager.cpp
|
#include "update_manager.h"
#include "progress_dialog.h"
#include "localized.h"
#include "rpcs3_version.h"
#include "downloader.h"
#include "gui_settings.h"
#include "Utilities/StrUtil.h"
#include "Utilities/File.h"
#include "Emu/System.h"
#include "Emu/system_utils.hpp"
#include "Crypto/utils.h"
#include "util/logs.hpp"
#include "util/types.hpp"
#include <QApplication>
#include <QDateTime>
#include <QMessageBox>
#include <QLabel>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QThread>
#if defined(_WIN32) || defined(__APPLE__)
#include <7z.h>
#include <7zAlloc.h>
#include <7zCrc.h>
#include <7zFile.h>
#endif
#if defined(_WIN32)
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <CpuArch.h>
#ifndef PATH_MAX
#define PATH_MAX MAX_PATH
#endif
#else
#include <unistd.h>
#include <sys/stat.h>
#endif
#if defined(__APPLE__)
// sysinfo_darwin.mm
namespace Darwin_Version
{
extern int getNSmajorVersion();
extern int getNSminorVersion();
extern int getNSpatchVersion();
}
#endif
LOG_CHANNEL(update_log, "UPDATER");
update_manager::update_manager(QObject* parent, std::shared_ptr<gui_settings> gui_settings)
: QObject(parent), m_gui_settings(std::move(gui_settings))
{
}
void update_manager::check_for_updates(bool automatic, bool check_only, bool auto_accept, QWidget* parent)
{
update_log.notice("Checking for updates: automatic=%d, check_only=%d, auto_accept=%d", automatic, check_only, auto_accept);
m_update_message.clear();
m_changelog.clear();
if (automatic)
{
// Don't check for updates on local builds
if (rpcs3::is_local_build())
{
update_log.notice("Skipped automatic update check: this is a local build");
return;
}
#ifdef __linux__
// Don't check for updates on startup if RPCS3 is not running from an AppImage.
if (!::getenv("APPIMAGE"))
{
update_log.notice("Skipped automatic update check: this is not an AppImage");
return;
}
#endif
}
m_parent = parent;
m_downloader = new downloader(parent);
connect(m_downloader, &downloader::signal_download_error, this, [this, automatic](const QString& /*error*/)
{
if (!automatic)
{
QMessageBox::warning(m_parent, tr("Auto-updater"), tr("An error occurred during the auto-updating process.\nCheck the log for more information."));
}
});
connect(m_downloader, &downloader::signal_download_finished, this, [this, automatic, check_only, auto_accept](const QByteArray& data)
{
const bool result_json = handle_json(automatic, check_only, auto_accept, data);
if (!result_json)
{
// The progress dialog is configured to stay open, so we need to close it manually if the download succeeds.
m_downloader->close_progress_dialog();
if (!automatic)
{
QMessageBox::warning(m_parent, tr("Auto-updater"), tr("An error occurred during the auto-updating process.\nCheck the log for more information."));
}
}
Q_EMIT signal_update_available(result_json && !m_update_message.isEmpty());
});
#if defined(__APPLE__)
const std::string url = fmt::format("https://update.rpcs3.net/"
"?api=v3"
"&c=%s"
"&os_type=macos"
"&os_arch="
#if defined(ARCH_X64)
"x64"
#elif defined(ARCH_ARM64)
"arm64"
#endif
"&os_version=%i.%i.%i",
rpcs3::get_commit_and_hash().second,
Darwin_Version::getNSmajorVersion(),
Darwin_Version::getNSminorVersion(),
Darwin_Version::getNSpatchVersion());
#else
const std::string url = "https://update.rpcs3.net/?api=v2&c=" + rpcs3::get_commit_and_hash().second;
#endif
m_downloader->start(url, true, !automatic, tr("Checking For Updates"), true);
}
bool update_manager::handle_json(bool automatic, bool check_only, bool auto_accept, const QByteArray& data)
{
update_log.notice("Download of update info finished. automatic=%d, check_only=%d, auto_accept=%d", automatic, check_only, auto_accept);
const QJsonObject json_data = QJsonDocument::fromJson(data).object();
const int return_code = json_data["return_code"].toInt(-255);
bool hash_found = true;
if (return_code < 0)
{
std::string error_message;
switch (return_code)
{
case -1: error_message = "Hash not found(Custom/PR build)"; break;
case -2: error_message = "Server Error - Maintenance Mode"; break;
case -3: error_message = "Server Error - Illegal Search"; break;
case -255: error_message = "Server Error - Return code not found"; break;
default: error_message = "Server Error - Unknown Error"; break;
}
if (return_code != -1)
update_log.error("Update error: %s return code: %d", error_message, return_code);
else
update_log.warning("Update error: %s return code: %d", error_message, return_code);
// If a user clicks "Check for Updates" with a custom build ask him if he's sure he wants to update to latest version
if (!automatic && return_code == -1)
{
hash_found = false;
}
else
{
return false;
}
}
const auto& current = json_data["current_build"];
const auto& latest = json_data["latest_build"];
if (!latest.isObject())
{
update_log.error("JSON doesn't contain latest_build section");
return false;
}
QString os;
#ifdef _WIN32
os = "windows";
#elif defined(__linux__)
os = "linux";
#elif defined(__APPLE__)
os = "mac";
#else
update_log.error("Your OS isn't currently supported by the auto-updater");
return false;
#endif
// Check that every bit of info we need is there
if (!latest[os].isObject() || !latest[os]["download"].isString() || !latest[os]["size"].isDouble() || !latest[os]["checksum"].isString() || !latest["version"].isString() ||
!latest["datetime"].isString() ||
(hash_found && (!current.isObject() || !current["version"].isString() || !current["datetime"].isString())))
{
update_log.error("Some information seems unavailable");
return false;
}
if (hash_found && return_code == 0)
{
update_log.success("RPCS3 is up to date!");
m_downloader->close_progress_dialog();
if (!automatic)
QMessageBox::information(m_parent, tr("Auto-updater"), tr("Your version is already up to date!"));
return true;
}
// Calculate how old the build is
const QString date_fmt = QStringLiteral("yyyy-MM-dd hh:mm:ss");
const QDateTime cur_date = hash_found ? QDateTime::fromString(current["datetime"].toString(), date_fmt) : QDateTime::currentDateTimeUtc();
const QDateTime lts_date = QDateTime::fromString(latest["datetime"].toString(), date_fmt);
const QString cur_str = cur_date.toString(date_fmt);
const QString lts_str = lts_date.toString(date_fmt);
const qint64 diff_msec = cur_date.msecsTo(lts_date);
update_log.notice("Current: %s, latest: %s, difference: %lld ms", cur_str, lts_str, diff_msec);
const Localized localized;
m_new_version = latest["version"].toString().toStdString();
const QString support_message = tr("<br>You can empower our project at <a href=\"https://rpcs3.net/patreon\">RPCS3 Patreon</a>.<br>");
if (hash_found)
{
m_old_version = current["version"].toString().toStdString();
if (diff_msec < 0)
{
// This usually means that the current version was marked as broken and won't be shipped anymore, so we need to downgrade to avoid certain bugs.
m_update_message = tr("A better version of RPCS3 is available!<br><br>Current version: %0 (%1)<br>Better version: %2 (%3)<br>%4<br>Do you want to update?")
.arg(current["version"].toString())
.arg(cur_str)
.arg(latest["version"].toString())
.arg(lts_str)
.arg(support_message);
}
else
{
m_update_message = tr("A new version of RPCS3 is available!<br><br>Current version: %0 (%1)<br>Latest version: %2 (%3)<br>Your version is %4 behind.<br>%5<br>Do you want to update?")
.arg(current["version"].toString())
.arg(cur_str)
.arg(latest["version"].toString())
.arg(lts_str)
.arg(localized.GetVerboseTimeByMs(diff_msec, true))
.arg(support_message);
}
}
else
{
m_old_version = fmt::format("%s-%s-%s", rpcs3::get_full_branch(), rpcs3::get_branch(), rpcs3::get_version().to_string());
m_update_message = tr("You're currently using a custom or PR build.<br><br>Latest version: %0 (%1)<br>The latest version is %2 old.<br>%3<br>Do you want to update to the latest official RPCS3 version?")
.arg(latest["version"].toString())
.arg(lts_str)
.arg(localized.GetVerboseTimeByMs(std::abs(diff_msec), true))
.arg(support_message);
}
m_request_url = latest[os]["download"].toString().toStdString();
m_expected_hash = latest[os]["checksum"].toString().toStdString();
m_expected_size = latest[os]["size"].toInt();
if (!m_request_url.starts_with("https://github.com/RPCS3/rpcs3"))
{
update_log.fatal("Bad url: %s", m_request_url);
return false;
}
update_log.notice("Update found: %s", m_request_url);
if (!auto_accept)
{
const auto& changelog = json_data["changelog"];
if (changelog.isArray())
{
for (const QJsonValue& changelog_entry : changelog.toArray())
{
if (changelog_entry.isObject())
{
changelog_data entry;
if (QJsonValue version = changelog_entry["version"]; version.isString())
{
entry.version = version.toString();
}
else
{
entry.version = tr("N/A");
update_log.notice("JSON changelog entry does not contain a version string.");
}
if (QJsonValue title = changelog_entry["title"]; title.isString())
{
entry.title = title.toString();
}
else
{
entry.title = tr("N/A");
update_log.notice("JSON changelog entry does not contain a title string.");
}
m_changelog.push_back(entry);
}
else
{
update_log.error("JSON changelog entry is not an object.");
}
}
}
else if (changelog.isObject())
{
update_log.error("JSON changelog is not an array.");
}
else
{
update_log.notice("JSON does not contain a changelog section.");
}
}
if (check_only)
{
update_log.notice("Update postponed. Check only is active");
m_downloader->close_progress_dialog();
return true;
}
update(auto_accept);
return true;
}
void update_manager::update(bool auto_accept)
{
update_log.notice("Updating with auto_accept=%d", auto_accept);
ensure(m_downloader);
if (!auto_accept)
{
if (m_update_message.isEmpty())
{
// This can happen if we abort the check_for_updates download. Just check again in this case.
update_log.notice("Aborting update: Update message is empty. Trying again...");
m_downloader->close_progress_dialog();
check_for_updates(false, false, false, m_parent);
return;
}
QString changelog_content;
for (const changelog_data& entry : m_changelog)
{
if (!changelog_content.isEmpty())
changelog_content.append('\n');
changelog_content.append(tr("• %0: %1").arg(entry.version, entry.title));
}
QMessageBox mb(QMessageBox::Icon::Question, tr("Update Available"), m_update_message, QMessageBox::Yes | QMessageBox::No, m_downloader->get_progress_dialog() ? m_downloader->get_progress_dialog() : m_parent);
mb.setTextFormat(Qt::RichText);
if (!changelog_content.isEmpty())
{
mb.setInformativeText(tr("To see the changelog, please click \"Show Details\"."));
mb.setDetailedText(tr("Changelog:\n\n%0").arg(changelog_content));
// Smartass hack to make the unresizeable message box wide enough for the changelog
const int changelog_width = QLabel(changelog_content).sizeHint().width();
if (QLabel(m_update_message).sizeHint().width() < changelog_width)
{
m_update_message += " ";
while (QLabel(m_update_message).sizeHint().width() < changelog_width)
{
m_update_message += " ";
}
}
mb.setText(m_update_message);
}
update_log.notice("Asking user for permission to update...");
if (mb.exec() == QMessageBox::No)
{
update_log.notice("Aborting update: User declined update");
m_downloader->close_progress_dialog();
return;
}
}
if (!Emu.IsStopped())
{
update_log.notice("Aborting update: Emulation is running...");
m_downloader->close_progress_dialog();
QMessageBox::warning(m_parent, tr("Auto-updater"), tr("Please stop the emulation before trying to update."));
return;
}
m_downloader->disconnect();
connect(m_downloader, &downloader::signal_download_error, this, [this](const QString& /*error*/)
{
QMessageBox::warning(m_parent, tr("Auto-updater"), tr("An error occurred during the auto-updating process.\nCheck the log for more information."));
});
connect(m_downloader, &downloader::signal_download_finished, this, [this, auto_accept](const QByteArray& data)
{
const bool result_json = handle_rpcs3(data, auto_accept);
if (!result_json)
{
// The progress dialog is configured to stay open, so we need to close it manually if the download succeeds.
m_downloader->close_progress_dialog();
QMessageBox::warning(m_parent, tr("Auto-updater"), tr("An error occurred during the auto-updating process.\nCheck the log for more information."));
}
Q_EMIT signal_update_available(false);
});
update_log.notice("Downloading update...");
m_downloader->start(m_request_url, true, true, tr("Downloading Update"), true, m_expected_size);
}
bool update_manager::handle_rpcs3(const QByteArray& data, bool auto_accept)
{
update_log.notice("Download of update file finished. Updating rpcs3 with auto_accept=%d", auto_accept);
m_downloader->update_progress_dialog(tr("Updating RPCS3"));
if (m_expected_size != static_cast<u64>(data.size()))
{
update_log.error("Download size mismatch: %d expected: %d", data.size(), m_expected_size);
return false;
}
if (const std::string res_hash_string = sha256_get_hash(data.data(), data.size(), false);
m_expected_hash != res_hash_string)
{
update_log.error("Hash mismatch: %s expected: %s", res_hash_string, m_expected_hash);
return false;
}
#if defined(_WIN32) || defined(__APPLE__)
// Get executable path
const std::string exe_dir = fs::get_executable_dir();
const std::string orig_path = fs::get_executable_path();
#ifdef _WIN32
const std::wstring wchar_orig_path = utf8_to_wchar(orig_path);
const std::string tmpfile_path = fs::get_temp_dir() + "\\rpcs3_update.7z";
#else
const std::string tmpfile_path = fs::get_temp_dir() + "rpcs3_update.7z";
#endif
update_log.notice("Writing temporary update file: %s", tmpfile_path);
fs::file tmpfile(tmpfile_path, fs::read + fs::write + fs::create + fs::trunc);
if (!tmpfile)
{
update_log.error("Failed to create temporary file: %s", tmpfile_path);
return false;
}
if (tmpfile.write(data.data(), data.size()) != static_cast<u64>(data.size()))
{
update_log.error("Failed to write temporary file: %s", tmpfile_path);
return false;
}
tmpfile.close();
update_log.notice("Unpacking update file: %s", tmpfile_path);
// 7z stuff (most of this stuff is from 7z Util sample and has been reworked to be more stl friendly)
CFileInStream archiveStream{};
CLookToRead2 lookStream{};
CSzArEx db;
UInt16 temp_u16[PATH_MAX];
u8 temp_u8[PATH_MAX];
const usz kInputBufSize = static_cast<usz>(1u << 18u);
const ISzAlloc g_Alloc = {SzAlloc, SzFree};
ISzAlloc allocImp = g_Alloc;
ISzAlloc allocTempImp = g_Alloc;
if (InFile_Open(&archiveStream.file, tmpfile_path.c_str()))
{
update_log.error("Failed to open temporary storage file: %s", tmpfile_path);
return false;
}
FileInStream_CreateVTable(&archiveStream);
LookToRead2_CreateVTable(&lookStream, False);
SRes res = SZ_OK;
lookStream.buf = static_cast<Byte*>(ISzAlloc_Alloc(&allocImp, kInputBufSize));
if (!lookStream.buf)
{
res = SZ_ERROR_MEM;
}
else
{
lookStream.bufSize = kInputBufSize;
lookStream.realStream = &archiveStream.vt;
}
CrcGenerateTable();
SzArEx_Init(&db);
auto error_free7z = [&]()
{
SzArEx_Free(&db, &allocImp);
ISzAlloc_Free(&allocImp, lookStream.buf);
File_Close(&archiveStream.file);
switch (res)
{
case SZ_OK: break;
case SZ_ERROR_UNSUPPORTED: update_log.error("7z decoder doesn't support this archive"); break;
case SZ_ERROR_MEM: update_log.error("7z decoder failed to allocate memory"); break;
case SZ_ERROR_CRC: update_log.error("7z decoder CRC error"); break;
default: update_log.error("7z decoder error: %d", static_cast<u64>(res)); break;
}
};
if (res != SZ_OK)
{
error_free7z();
return false;
}
res = SzArEx_Open(&db, &lookStream.vt, &allocImp, &allocTempImp);
if (res != SZ_OK)
{
error_free7z();
return false;
}
UInt32 blockIndex = 0xFFFFFFFF;
Byte* outBuffer = nullptr;
usz outBufferSize = 0;
#ifdef _WIN32
// Create temp folder for moving active files
const std::string tmp_folder = exe_dir + "rpcs3_old/";
#else
// Create temp folder for extracting the new app
const std::string tmp_folder = fs::get_temp_dir() + "rpcs3_new/";
#endif
fs::create_dir(tmp_folder);
for (UInt32 i = 0; i < db.NumFiles; i++)
{
usz offset = 0;
usz outSizeProcessed = 0;
const bool isDir = SzArEx_IsDir(&db, i);
[[maybe_unused]] const DWORD attribs = SzBitWithVals_Check(&db.Attribs, i) ? db.Attribs.Vals[i] : 0;
#ifdef _WIN32
// This is commented out for now as we shouldn't need it and symlinks
// aren't well supported on Windows. Left in case it is needed in the future.
// const bool is_symlink = (attribs & FILE_ATTRIBUTE_REPARSE_POINT) != 0;
const bool is_symlink = false;
#else
const DWORD permissions = (attribs >> 16) & (S_IRWXU | S_IRWXG | S_IRWXO);
const bool is_symlink = (attribs & FILE_ATTRIBUTE_UNIX_EXTENSION) != 0 && S_ISLNK(attribs >> 16);
#endif
const usz len = SzArEx_GetFileNameUtf16(&db, i, nullptr);
if (len >= PATH_MAX)
{
update_log.error("7z decoder error: filename longer or equal to PATH_MAX");
error_free7z();
return false;
}
SzArEx_GetFileNameUtf16(&db, i, temp_u16);
memset(temp_u8, 0, sizeof(temp_u8));
// Simplistic conversion to UTF-8
for (usz index = 0; index < len; index++)
{
if (temp_u16[index] > 0xFF)
{
update_log.error("7z decoder error: Failed to convert UTF-16 to UTF-8");
error_free7z();
return false;
}
temp_u8[index] = static_cast<u8>(temp_u16[index]);
}
temp_u8[len] = 0;
const std::string archived_name = std::string(reinterpret_cast<char*>(temp_u8));
#ifdef __APPLE__
const std::string name = tmp_folder + archived_name;
#else
const std::string name = exe_dir + archived_name;
#endif
if (!isDir)
{
res = SzArEx_Extract(&db, &lookStream.vt, i, &blockIndex, &outBuffer, &outBufferSize, &offset, &outSizeProcessed, &allocImp, &allocTempImp);
if (res != SZ_OK)
break;
}
if (const usz pos = name.find_last_of(fs::delim); pos != umax)
{
update_log.trace("Creating path: %s", name.substr(0, pos));
fs::create_path(name.substr(0, pos));
}
if (isDir)
{
update_log.trace("Creating dir: %s", name);
fs::create_dir(name);
continue;
}
if (is_symlink)
{
const std::string link_target(reinterpret_cast<const char*>(outBuffer + offset), outSizeProcessed);
update_log.trace("Creating symbolic link: %s -> %s", name, link_target);
fs::create_symlink(name, link_target);
continue;
}
fs::file outfile(name, fs::read + fs::write + fs::create + fs::trunc);
if (!outfile)
{
// File failed to open, probably because in use, rename existing file and try again
const auto pos = name.find_last_of(fs::delim);
std::string filename;
if (pos == umax)
filename = name;
else
filename = name.substr(pos + 1);
// Moving to temp is not an option on windows as it will fail if the disk is different
// So we create a folder in config dir and move stuff there
const std::string rename_target = tmp_folder + filename;
update_log.trace("Renaming %s to %s", name, rename_target);
if (!fs::rename(name, rename_target, true))
{
update_log.error("Failed to rename %s to %s", name, rename_target);
res = SZ_ERROR_FAIL;
break;
}
outfile.open(name, fs::read + fs::write + fs::create + fs::trunc);
if (!outfile)
{
update_log.error("Can not open output file %s", name);
res = SZ_ERROR_FAIL;
break;
}
}
if (outfile.write(outBuffer + offset, outSizeProcessed) != outSizeProcessed)
{
update_log.error("Can not write output file: %s", name);
res = SZ_ERROR_FAIL;
break;
}
outfile.close();
#ifndef _WIN32
// Apply correct file permissions.
chmod(name.c_str(), permissions);
#endif
}
error_free7z();
if (res)
return false;
update_log.success("Update successful!");
#else
std::string replace_path = fs::get_executable_path();
if (replace_path.empty())
{
return false;
}
// Move the appimage/exe and replace with new appimage
const std::string move_dest = replace_path + "_old";
if (!fs::rename(replace_path, move_dest, true))
{
// Simply log error for now
update_log.error("Failed to move old AppImage file: %s (%s)", replace_path, fs::g_tls_error);
}
fs::file new_appimage(replace_path, fs::read + fs::write + fs::create + fs::trunc);
if (!new_appimage)
{
update_log.error("Failed to create new AppImage file: %s (%s)", replace_path, fs::g_tls_error);
return false;
}
if (new_appimage.write(data.data(), data.size()) != data.size() + 0ull)
{
update_log.error("Failed to write new AppImage file: %s", replace_path);
return false;
}
if (fchmod(new_appimage.get_handle(), S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == -1)
{
update_log.error("Failed to chmod rwxrxrx %s (%s)", replace_path, strerror(errno));
return false;
}
new_appimage.close();
update_log.success("Successfully updated %s!", replace_path);
#endif
m_downloader->close_progress_dialog();
// Add new version to log file
if (fs::file update_file{fs::get_config_dir() + "update_history.log", fs::create + fs::write + fs::append})
{
const std::string update_time = QDateTime::currentDateTime().toString("yyyy/MM/dd hh:mm:ss").toStdString();
const std::string entry = fmt::format("%s: Updated from \"%s\" to \"%s\"", update_time, m_old_version, m_new_version);
update_file.write(fmt::format("%s\n", entry));
update_log.notice("Added entry '%s' to update_history.log", entry);
}
else
{
update_log.error("Failed to append version to update_history.log");
}
if (!auto_accept)
{
m_gui_settings->ShowInfoBox(tr("Auto-updater"), tr("Update successful!<br>RPCS3 will now restart.<br>"), gui::ib_restart_hint, m_parent);
m_gui_settings->sync(); // Make sure to sync before terminating RPCS3
}
Emu.GracefulShutdown(false);
Emu.CleanUp();
#ifdef _WIN32
update_log.notice("Relaunching %s with _wexecl", wchar_to_utf8(wchar_orig_path));
const int ret = _wexecl(wchar_orig_path.data(), wchar_orig_path.data(), L"--updating", nullptr);
#elif defined(__APPLE__)
// Execute helper script to replace the app and relaunch
const std::string helper_script = fmt::format("%s/Contents/Resources/update_helper.sh", orig_path);
const std::string extracted_app = fmt::format("%s/RPCS3.app", tmp_folder);
update_log.notice("Executing update helper script: '%s %s %s'", helper_script, extracted_app, orig_path);
const int ret = execl(helper_script.c_str(), helper_script.c_str(), extracted_app.c_str(), orig_path.c_str(), nullptr);
#else
// execv is used for compatibility with checkrt
update_log.notice("Relaunching %s with execv", replace_path);
const char * const params[3] = { replace_path.c_str(), "--updating", nullptr };
const int ret = execv(replace_path.c_str(), const_cast<char * const *>(¶ms[0]));
#endif
if (ret == -1)
{
update_log.error("Relaunching failed with result: %d(%s)", ret, strerror(errno));
return false;
}
return true;
}
| 23,488
|
C++
|
.cpp
| 654
| 32.995413
| 210
| 0.698164
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,075
|
call_stack_list.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/call_stack_list.cpp
|
#include "call_stack_list.h"
#include "Utilities/StrFmt.h"
#include <QKeyEvent>
#include <QMouseEvent>
call_stack_list::call_stack_list(QWidget* parent) : QListWidget(parent)
{
setEditTriggers(QAbstractItemView::NoEditTriggers);
setContextMenuPolicy(Qt::CustomContextMenu);
setSelectionMode(QAbstractItemView::ExtendedSelection);
// connects
connect(this, &QListWidget::itemDoubleClicked, this, &call_stack_list::ShowItemAddress);
// Hide until used in order to allow as much space for registers panel as possible
hide();
}
void call_stack_list::keyPressEvent(QKeyEvent* event)
{
QListWidget::keyPressEvent(event);
event->ignore(); // Propagate the event to debugger_frame
if (!event->modifiers() && event->key() == Qt::Key_Return)
{
ShowItemAddress();
}
}
void call_stack_list::HandleUpdate(const std::vector<std::pair<u32, u32>>& call_stack)
{
clear();
for (const auto& addr : call_stack)
{
const QString text = QString::fromStdString(fmt::format("0x%08llx (sp=0x%08llx)", addr.first, addr.second));
QListWidgetItem* call_stack_item = new QListWidgetItem(text);
call_stack_item->setData(Qt::UserRole, { addr.first });
addItem(call_stack_item);
}
setVisible(!call_stack.empty());
}
void call_stack_list::ShowItemAddress()
{
if (QListWidgetItem* call_stack_item = currentItem())
{
const u32 address = call_stack_item->data(Qt::UserRole).value<u32>();
Q_EMIT RequestShowAddress(address);
}
}
void call_stack_list::mouseDoubleClickEvent(QMouseEvent* ev)
{
if (!ev) return;
// Qt's itemDoubleClicked signal doesn't distinguish between mouse buttons and there is no simple way to get the pressed button.
// So we have to ignore this event when another button is pressed.
if (ev->button() != Qt::LeftButton)
{
ev->ignore();
return;
}
QListWidget::mouseDoubleClickEvent(ev);
}
| 1,830
|
C++
|
.cpp
| 55
| 31.2
| 129
| 0.755253
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,076
|
debugger_list.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/debugger_list.cpp
|
#include "debugger_list.h"
#include "gui_settings.h"
#include "qt_utils.h"
#include "breakpoint_handler.h"
#include "Emu/Cell/SPUThread.h"
#include "Emu/Cell/PPUThread.h"
#include "Emu/CPU/CPUDisAsm.h"
#include "Emu/CPU/CPUThread.h"
#include "Emu/RSX/RSXDisAsm.h"
#include "Emu/RSX/RSXThread.h"
#include "Emu/System.h"
#include <QMouseEvent>
#include <QWheelEvent>
#include <QVBoxLayout>
#include <QLabel>
#include <memory>
constexpr auto qstr = QString::fromStdString;
debugger_list::debugger_list(QWidget* parent, std::shared_ptr<gui_settings> gui_settings, breakpoint_handler* handler)
: QListWidget(parent)
, m_gui_settings(std::move(gui_settings))
, m_ppu_breakpoint_handler(handler)
{
setWindowTitle(tr("ASM"));
for (uint i = 0; i < m_item_count; ++i)
{
insertItem(i, new QListWidgetItem(""));
}
setSizeAdjustPolicy(QListWidget::AdjustToContents);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
connect(this, &QListWidget::currentRowChanged, this, [this](int row)
{
if (row < 0)
{
m_selected_instruction = -1;
m_showing_selected_instruction = false;
return;
}
u32 pc = m_start_addr;
const auto cpu = m_disasm && !Emu.IsStopped() ? m_disasm->get_cpu() : nullptr;
for (; cpu && cpu->get_class() == thread_class::rsx && row; row--)
{
// If scrolling forwards (downwards), we can skip entire commands
pc += std::max<u32>(m_disasm->disasm(pc), 4);
}
m_selected_instruction = pc + row * 4;
});
}
void debugger_list::UpdateCPUData(std::shared_ptr<CPUDisAsm> disasm)
{
if ((!m_disasm) != (!disasm) || (m_disasm && disasm->get_cpu() != m_disasm->get_cpu()))
{
m_selected_instruction = -1;
m_showing_selected_instruction = false;
}
m_disasm = std::move(disasm);
}
u32 debugger_list::GetStartAddress(u32 address)
{
const auto cpu = m_disasm && !Emu.IsStopped() ? m_disasm->get_cpu() : nullptr;
const u32 steps = m_item_count / 3;
const u32 inst_count_jump_on_step = std::min<u32>(steps, 4);
const bool is_spu = IsSpu();
const u32 address_mask = (is_spu ? 0x3fffc : ~3);
u32 result = address & address_mask;
if (cpu && cpu->get_class() == thread_class::rsx)
{
if (auto [count, res] = static_cast<rsx::thread*>(cpu)->try_get_pc_of_x_cmds_backwards(steps, address); count == steps)
{
result = res;
}
}
else
{
result = (address - (steps * 4)) & address_mask;
}
u32 upper_bound = (m_start_addr + (steps * 4)) & address_mask;
if (cpu && cpu->get_class() == thread_class::rsx)
{
if (auto [count, res] = static_cast<rsx::thread*>(cpu)->try_get_pc_of_x_cmds_backwards(0 - steps, m_start_addr); count == steps)
{
upper_bound = res;
}
}
bool goto_addr = false;
if (upper_bound > m_start_addr)
{
goto_addr = address < m_start_addr || address >= upper_bound;
}
else
{
// Overflowing bounds case
goto_addr = address < m_start_addr && address >= upper_bound;
}
if (goto_addr)
{
m_pc = address;
if (address > upper_bound && address - upper_bound < inst_count_jump_on_step * 4)
{
m_start_addr = result + inst_count_jump_on_step * 4;
}
else
{
m_start_addr = result;
}
}
return m_start_addr;
}
bool debugger_list::IsSpu() const
{
const auto cpu = m_disasm && !Emu.IsStopped() ? m_disasm->get_cpu() : nullptr;
return (cpu && cpu->get_class() == thread_class::spu) || (m_disasm && !cpu);
}
void debugger_list::ShowAddress(u32 addr, bool select_addr, bool direct)
{
const auto cpu = m_disasm && !Emu.IsStopped() ? m_disasm->get_cpu() : nullptr;
const decltype(spu_thread::local_breakpoints)* spu_bps_list{};
if (cpu && cpu->get_class() == thread_class::spu)
{
spu_bps_list = &static_cast<spu_thread*>(cpu)->local_breakpoints;
}
auto IsBreakpoint = [&](u32 pc)
{
switch (cpu ? cpu->get_class() : thread_class::general)
{
case thread_class::ppu:
{
return m_ppu_breakpoint_handler->HasBreakpoint(pc);
}
case thread_class::spu:
{
const u32 pos_at = pc / 4;
const u32 pos_bit = 1u << (pos_at % 8);
return !!((*spu_bps_list)[pos_at / 8] & pos_bit);
}
default: return false;
}
};
if (select_addr || direct)
{
// The user wants to survey a specific memory location, do not interfere from this point forth
m_follow_thread = false;
}
m_dirty_flag = false;
u32 pc = m_start_addr;
if (!direct && (m_follow_thread || select_addr))
{
pc = GetStartAddress(addr);
}
const auto& default_foreground = palette().color(foregroundRole());
const auto& default_background = palette().color(backgroundRole());
m_showing_selected_instruction = false;
if (select_addr)
{
m_selected_instruction = addr;
}
for (uint i = 0; i < m_item_count; ++i)
{
if (auto list_item = item(i); list_item->isSelected())
{
list_item->setSelected(false);
}
}
if (!m_disasm || (cpu && cpu->state.all_of(cpu_flag::exit + cpu_flag::wait)))
{
for (uint i = 0; i < m_item_count; ++i)
{
QListWidgetItem* list_item = item(i);
list_item->setText(qstr(fmt::format(" [%08x] ?? ?? ?? ??:", 0)));
list_item->setForeground(default_foreground);
list_item->setBackground(default_background);
}
}
else
{
const bool is_spu = IsSpu();
const u32 address_limits = (is_spu ? 0x3fffc : ~3);
const u32 current_pc = (cpu ? cpu->get_pc() : 0);
m_start_addr &= address_limits;
pc = m_start_addr;
for (uint i = 0, count = 4; i < m_item_count; ++i, pc = (pc + count) & address_limits)
{
QListWidgetItem* list_item = item(i);
if (pc == current_pc)
{
list_item->setForeground(m_text_color_pc);
list_item->setBackground(m_color_pc);
}
else if (pc == m_selected_instruction)
{
// setSelected may invoke a resize event which causes stack overflow, terminate recursion
if (!list_item->isSelected())
{
list_item->setSelected(true);
}
m_showing_selected_instruction = true;
}
else if (IsBreakpoint(pc))
{
list_item->setForeground(m_text_color_bp);
list_item->setBackground(m_color_bp);
}
else
{
list_item->setForeground(default_foreground);
list_item->setBackground(default_background);
}
if (cpu && cpu->get_class() == thread_class::ppu && !vm::check_addr(pc, 0))
{
list_item->setText((IsBreakpoint(pc) ? ">> " : " ") + qstr(fmt::format("[%08x] ?? ?? ?? ??:", pc)));
count = 4;
continue;
}
if (cpu && cpu->get_class() == thread_class::ppu && !vm::check_addr(pc, vm::page_executable))
{
const u32 data = *vm::get_super_ptr<atomic_be_t<u32>>(pc);
list_item->setText((IsBreakpoint(pc) ? ">> " : " ") + qstr(fmt::format("[%08x] %02x %02x %02x %02x:", pc,
static_cast<u8>(data >> 24),
static_cast<u8>(data >> 16),
static_cast<u8>(data >> 8),
static_cast<u8>(data >> 0))));
count = 4;
continue;
}
count = m_disasm->disasm(pc);
if (!count)
{
list_item->setText((IsBreakpoint(pc) ? ">> " : " ") + qstr(fmt::format("[%08x] ??? ?? ??", pc)));
count = 4;
continue;
}
list_item->setText((IsBreakpoint(pc) ? ">> " : " ") + qstr(m_disasm->last_opcode));
}
}
setLineWidth(-1);
}
void debugger_list::RefreshView()
{
const bool old = std::exchange(m_follow_thread, false);
ShowAddress(0, false);
m_follow_thread = old;
}
void debugger_list::EnableThreadFollowing(bool enable)
{
m_follow_thread = enable;
}
void debugger_list::scroll(s32 steps)
{
const auto cpu = m_disasm && !Emu.IsStopped() ? m_disasm->get_cpu() : nullptr;
for (; cpu && cpu->get_class() == thread_class::rsx && steps > 0; steps--)
{
// If scrolling forwards (downwards), we can skip entire commands
m_start_addr += std::max<u32>(m_disasm->disasm(m_start_addr), 4);
}
if (cpu && cpu->get_class() == thread_class::rsx && steps < 0)
{
// If scrolling backwards (upwards), try to obtain the start of commands tail
if (auto [count, res] = static_cast<rsx::thread*>(cpu)->try_get_pc_of_x_cmds_backwards(-steps, m_start_addr); count == 0u - steps)
{
steps = 0;
m_start_addr = res;
}
}
EnableThreadFollowing(false);
m_start_addr += steps * 4;
ShowAddress(0, false, true);
}
void debugger_list::keyPressEvent(QKeyEvent* event)
{
const auto cpu = m_disasm && !Emu.IsStopped() ? m_disasm->get_cpu() : nullptr;
// Always accept event (so it would not bubble upwards, debugger_frame already sees it)
struct accept_event_t
{
QKeyEvent* event;
~accept_event_t() noexcept
{
event->accept();
}
} accept_event{event};
if (!isActiveWindow())
{
QListWidget::keyPressEvent(event);
return;
}
if (event->modifiers())
{
QListWidget::keyPressEvent(event);
return;
}
switch (event->key())
{
case Qt::Key_PageUp: scroll(0 - m_item_count); return;
case Qt::Key_PageDown: scroll(m_item_count); return;
case Qt::Key_Up: scroll(-1); return;
case Qt::Key_Down: scroll(1); return;
case Qt::Key_I:
{
if (event->isAutoRepeat())
{
QListWidget::keyPressEvent(event);
return;
}
if (cpu && cpu->get_class() == thread_class::rsx)
{
create_rsx_command_detail(m_showing_selected_instruction ? m_selected_instruction : m_pc);
return;
}
break;
}
default: break;
}
QListWidget::keyPressEvent(event);
}
void debugger_list::showEvent(QShowEvent* event)
{
if (m_cmd_detail) m_cmd_detail->show();
QListWidget::showEvent(event);
}
void debugger_list::hideEvent(QHideEvent* event)
{
if (m_cmd_detail) m_cmd_detail->hide();
QListWidget::hideEvent(event);
}
void debugger_list::create_rsx_command_detail(u32 pc)
{
RSXDisAsm rsx_dis = static_cast<RSXDisAsm&>(*m_disasm);
rsx_dis.change_mode(cpu_disasm_mode::list);
// Either invalid or not a method
if (rsx_dis.disasm(pc) <= 4) return;
if (m_cmd_detail)
{
// Edit the existing dialog
m_detail_label->setText(QString::fromStdString(rsx_dis.last_opcode));
m_cmd_detail->setFixedSize(m_cmd_detail->sizeHint());
return;
}
m_cmd_detail = new QDialog(this);
m_cmd_detail->setWindowTitle(tr("RSX Command Detail"));
m_detail_label = new QLabel(QString::fromStdString(rsx_dis.last_opcode), this);
m_detail_label->setFont(font());
gui::utils::set_font_size(*m_detail_label, 10);
m_detail_label->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(m_detail_label);
m_cmd_detail->setLayout(layout);
m_cmd_detail->setFixedSize(m_cmd_detail->sizeHint());
m_cmd_detail->show();
connect(m_cmd_detail, &QDialog::finished, [this](int)
{
// Cleanup
std::exchange(m_cmd_detail, nullptr)->deleteLater();
});
}
void debugger_list::mouseDoubleClickEvent(QMouseEvent* event)
{
if (event->button() == Qt::LeftButton)
{
int i = currentRow();
if (i < 0) return;
u32 pc = m_start_addr;
const auto cpu = m_disasm && !Emu.IsStopped() ? m_disasm->get_cpu() : nullptr;
for (; cpu && cpu->get_class() == thread_class::rsx && i; i--)
{
// If scrolling forwards (downwards), we can skip entire commands
pc += std::max<u32>(m_disasm->disasm(pc), 4);
}
pc += i * 4;
m_selected_instruction = pc;
// Let debugger_frame know about breakpoint.
// Other option is to add to breakpoint manager directly and have a signal there instead.
// Either the flow goes from debugger_list->breakpoint_manager->debugger_frame, or it goes debugger_list->debugger_frame, and I felt this was easier to read for now.
Q_EMIT BreakpointRequested(pc);
}
}
void debugger_list::wheelEvent(QWheelEvent* event)
{
const QPoint numSteps = event->angleDelta() / 8 / 15; // http://doc.qt.io/qt-5/qwheelevent.html#pixelDelta
const int value = numSteps.y();
const auto direction = (event->modifiers() == Qt::ControlModifier);
scroll(direction ? value : -value);
}
void debugger_list::resizeEvent(QResizeEvent* event)
{
QListWidget::resizeEvent(event);
if (count() < 1 || visualItemRect(item(0)).height() < 1)
{
return;
}
const u32 old_size = m_item_count;
// It is fine if the QWidgetList is a tad bit larger than the frame
m_item_count = utils::aligned_div<u32>(rect().height() - frameWidth() * 2, visualItemRect(item(0)).height());
if (old_size <= m_item_count)
{
for (u32 i = old_size; i < m_item_count; ++i)
{
insertItem(i, new QListWidgetItem(""));
m_dirty_flag = true;
}
}
else
{
for (u32 i = old_size - 1; i >= m_item_count; --i)
{
delete takeItem(i);
}
}
}
| 12,286
|
C++
|
.cpp
| 406
| 27.475369
| 167
| 0.667967
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,077
|
dimensions_dialog.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/dimensions_dialog.cpp
|
#include "stdafx.h"
#include "Utilities/File.h"
#include "dimensions_dialog.h"
#include "Emu/Io/Dimensions.h"
#include "util/asm.hpp"
#include <locale>
#include <QLabel>
#include <QGroupBox>
#include <QFileDialog>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QComboBox>
#include <QPushButton>
#include <QStringList>
#include <QCompleter>
#include <QGridLayout>
dimensions_dialog* dimensions_dialog::inst = nullptr;
std::array<std::optional<u32>, 7> figure_slots = {};
static QString s_last_figure_path;
LOG_CHANNEL(dimensions_log, "dimensions");
const std::map<const u32, const std::string> list_minifigs = {
{0, "Blank Tag"},
{1, "Batman"},
{2, "Gandalf"},
{3, "Wyldstyle"},
{4, "Aquaman"},
{5, "Bad Cop"},
{6, "Bane"},
{7, "Bart Simpson"},
{8, "Benny"},
{9, "Chell"},
{10, "Cole"},
{11, "Cragger"},
{12, "Cyborg"},
{13, "Cyberman"},
{14, "Doc Brown"},
{15, "The Doctor"},
{16, "Emmet"},
{17, "Eris"},
{18, "Gimli"},
{19, "Gollum"},
{20, "Harley Quinn"},
{21, "Homer Simpson"},
{22, "Jay"},
{23, "Joker"},
{24, "Kai"},
{25, "ACU Trooper"},
{26, "Gamer Kid"},
{27, "Krusty the Clown"},
{28, "Laval"},
{29, "Legolas"},
{30, "Lloyd"},
{31, "Marty McFly"},
{32, "Nya"},
{33, "Owen Grady"},
{34, "Peter Venkman"},
{35, "Slimer"},
{36, "Scooby-Doo"},
{37, "Sensei Wu"},
{38, "Shaggy"},
{39, "Stay Puft"},
{40, "Superman"},
{41, "Unikitty"},
{42, "Wicked Witch of the West"},
{43, "Wonder Woman"},
{44, "Zane"},
{45, "Green Arrow"},
{46, "Supergirl"},
{47, "Abby Yates"},
{48, "Finn the Human"},
{49, "Ethan Hunt"},
{50, "Lumpy Space Princess"},
{51, "Jake the Dog"},
{52, "Harry Potter"},
{53, "Lord Voldemort"},
{54, "Michael Knight"},
{55, "B.A. Baracus"},
{56, "Newt Scamander"},
{57, "Sonic the Hedgehog"},
{58, "Future Update (unreleased)"},
{59, "Gizmo"},
{60, "Stripe"},
{61, "E.T."},
{62, "Tina Goldstein"},
{63, "Marceline the Vampire Queen"},
{64, "Batgirl"},
{65, "Robin"},
{66, "Sloth"},
{67, "Hermione Granger"},
{68, "Chase McCain"},
{69, "Excalibur Batman"},
{70, "Raven"},
{71, "Beast Boy"},
{72, "Betelgeuse"},
{73, "Lord Vortech (unreleased)"},
{74, "Blossom"},
{75, "Bubbles"},
{76, "Buttercup"},
{77, "Starfire"},
{78, "World 15 (unreleased)"},
{79, "World 16 (unreleased)"},
{80, "World 17 (unreleased)"},
{81, "World 18 (unreleased)"},
{82, "World 19 (unreleased)"},
{83, "World 20 (unreleased)"},
{768, "Unknown 768"},
{769, "Supergirl Red Lantern"},
{770, "Unknown 770"}};
const std::map<const u32, const std::string> list_tokens = {
{1000, "Police Car"},
{1001, "Aerial Squad Car"},
{1002, "Missile Striker"},
{1003, "Gravity Sprinter"},
{1004, "Street Shredder"},
{1005, "Sky Clobberer"},
{1006, "Batmobile"},
{1007, "Batblaster"},
{1008, "Sonic Batray"},
{1009, "Benny's Spaceship"},
{1010, "Lasercraft"},
{1011, "The Annihilator"},
{1012, "DeLorean Time Machine"},
{1013, "Electric Time Machine"},
{1014, "Ultra Time Machine"},
{1015, "Hoverboard"},
{1016, "Cyclone Board"},
{1017, "Ultimate Hoverjet"},
{1018, "Eagle Interceptor"},
{1019, "Eagle Sky Blazer"},
{1020, "Eagle Swoop Diver"},
{1021, "Swamp Skimmer"},
{1022, "Cragger's Fireship"},
{1023, "Croc Command Sub"},
{1024, "Cyber-Guard"},
{1025, "Cyber-Wrecker"},
{1026, "Laser Robot Walker"},
{1027, "K-9"},
{1028, "K-9 Ruff Rover"},
{1029, "K-9 Laser Cutter"},
{1030, "TARDIS"},
{1031, "Laser-Pulse TARDIS"},
{1032, "Energy-Burst TARDIS"},
{1033, "Emmet's Excavator"},
{1034, "Destroy Dozer"},
{1035, "Destruct-o-Mech"},
{1036, "Winged Monkey"},
{1037, "Battle Monkey"},
{1038, "Commander Monkey"},
{1039, "Axe Chariot"},
{1040, "Axe Hurler"},
{1041, "Soaring Chariot"},
{1042, "Shelob the Great"},
{1043, "8-Legged Stalker"},
{1044, "Poison Slinger"},
{1045, "Homer's Car"},
{1047, "The SubmaHomer"},
{1046, "The Homercraft"},
{1048, "Taunt-o-Vision"},
{1050, "The MechaHomer"},
{1049, "Blast Cam"},
{1051, "Velociraptor"},
{1053, "Venom Raptor"},
{1052, "Spike Attack Raptor"},
{1054, "Gyrosphere"},
{1055, "Sonic Beam Gyrosphere"},
{1056, " Gyrosphere"},
{1057, "Clown Bike"},
{1058, "Cannon Bike"},
{1059, "Anti-Gravity Rocket Bike"},
{1060, "Mighty Lion Rider"},
{1061, "Lion Blazer"},
{1062, "Fire Lion"},
{1063, "Arrow Launcher"},
{1064, "Seeking Shooter"},
{1065, "Triple Ballista"},
{1066, "Mystery Machine"},
{1067, "Mystery Tow & Go"},
{1068, "Mystery Monster"},
{1069, "Boulder Bomber"},
{1070, "Boulder Blaster"},
{1071, "Cyclone Jet"},
{1072, "Storm Fighter"},
{1073, "Lightning Jet"},
{1074, "Electro-Shooter"},
{1075, "Blade Bike"},
{1076, "Flight Fire Bike"},
{1077, "Blades of Fire"},
{1078, "Samurai Mech"},
{1079, "Samurai Shooter"},
{1080, "Soaring Samurai Mech"},
{1081, "Companion Cube"},
{1082, "Laser Deflector"},
{1083, "Gold Heart Emitter"},
{1084, "Sentry Turret"},
{1085, "Turret Striker"},
{1086, "Flight Turret Carrier"},
{1087, "Scooby Snack"},
{1088, "Scooby Fire Snack"},
{1089, "Scooby Ghost Snack"},
{1090, "Cloud Cuckoo Car"},
{1091, "X-Stream Soaker"},
{1092, "Rainbow Cannon"},
{1093, "Invisible Jet"},
{1094, "Laser Shooter"},
{1095, "Torpedo Bomber"},
{1096, "NinjaCopter"},
{1097, "Glaciator"},
{1098, "Freeze Fighter"},
{1099, "Travelling Time Train"},
{1100, "Flight Time Train"},
{1101, "Missile Blast Time Train"},
{1102, "Aqua Watercraft"},
{1103, "Seven Seas Speeder"},
{1104, "Trident of Fire"},
{1105, "Drill Driver"},
{1106, "Bane Dig 'n' Drill"},
{1107, "Bane Drill 'n' Blast"},
{1108, "Quinn Mobile"},
{1109, "Quinn Ultra Racer"},
{1110, "Missile Launcher"},
{1111, "The Joker's Chopper"},
{1112, "Mischievous Missile Blaster"},
{1113, "Lock 'n' Laser Jet"},
{1114, "Hover Pod"},
{1115, "Krypton Striker"},
{1116, "Super Stealth Pod"},
{1117, "Dalek"},
{1118, "Fire 'n' Ride Dalek"},
{1119, "Silver Shooter Dalek"},
{1120, "Ecto-1"},
{1121, "Ecto-1 Blaster"},
{1122, "Ecto-1 Water Diver"},
{1123, "Ghost Trap"},
{1124, "Ghost Stun 'n' Trap"},
{1125, "Proton Zapper"},
{1126, "Unknown"},
{1127, "Unknown"},
{1128, "Unknown"},
{1129, "Unknown"},
{1130, "Unknown"},
{1131, "Unknown"},
{1132, "Lloyd's Golden Dragon"},
{1133, "Sword Projector Dragon"},
{1134, "Unknown"},
{1135, "Unknown"},
{1136, "Unknown"},
{1137, "Unknown"},
{1138, "Unknown"},
{1139, "Unknown"},
{1140, "Unknown"},
{1141, "Unknown"},
{1142, "Unknown"},
{1143, "Unknown"},
{1144, "Mega Flight Dragon"},
{1145, "Unknown"},
{1146, "Unknown"},
{1147, "Unknown"},
{1148, "Unknown"},
{1149, "Unknown"},
{1150, "Unknown"},
{1151, "Unknown"},
{1152, "Unknown"},
{1153, "Unknown"},
{1154, "Unknown"},
{1155, "Flying White Dragon"},
{1156, "Golden Fire Dragon"},
{1157, "Ultra Destruction Dragon"},
{1158, "Arcade Machine"},
{1159, "8-Bit Shooter"},
{1160, "The Pixelator"},
{1161, "G-6155 Spy Hunter"},
{1162, "Interdiver"},
{1163, "Aerial Spyhunter"},
{1164, "Slime Shooter"},
{1165, "Slime Exploder"},
{1166, "Slime Streamer"},
{1167, "Terror Dog"},
{1168, "Terror Dog Destroyer"},
{1169, "Soaring Terror Dog"},
{1170, "Ancient Psychic Tandem War Elephant"},
{1171, "Cosmic Squid"},
{1172, "Psychic Submarine"},
{1173, "BMO"},
{1174, "DOGMO"},
{1175, "SNAKEMO"},
{1176, "Jakemobile"},
{1177, "Snail Dude Jake"},
{1178, "Hover Jake"},
{1179, "Lumpy Car"},
{1181, "Lumpy Land Whale"},
{1180, "Lumpy Truck"},
{1182, "Lunatic Amp"},
{1183, "Shadow Scorpion"},
{1184, "Heavy Metal Monster"},
{1185, "B.A.'s Van"},
{1186, "Fool Smasher"},
{1187, "Pain Plane"},
{1188, "Phone Home"},
{1189, "Mobile Uplink"},
{1190, "Super-Charged Satellite"},
{1191, "Niffler"},
{1192, "Sinister Scorpion"},
{1193, "Vicious Vulture"},
{1194, "Swooping Evil"},
{1195, "Brutal Bloom"},
{1196, "Crawling Creeper"},
{1197, "Ecto-1 (2016)"},
{1198, "Ectozer"},
{1199, "PerfEcto"},
{1200, "Flash 'n' Finish"},
{1201, "Rampage Record Player"},
{1202, "Stripe's Throne"},
{1203, "R.C. Racer"},
{1204, "Gadget-O-Matic"},
{1205, "Scarlet Scorpion"},
{1206, "Hogwarts Express"},
{1208, "Steam Warrior"},
{1207, "Soaring Steam Plane"},
{1209, "Enchanted Car"},
{1210, "Shark Sub"},
{1211, "Monstrous Mouth"},
{1212, "IMF Scrambler"},
{1213, "Shock Cycle"},
{1214, "IMF Covert Jet"},
{1215, "IMF Sports Car"},
{1216, "IMF Tank"},
{1217, "IMF Splorer"},
{1218, "Sonic Speedster"},
{1219, "Blue Typhoon"},
{1220, "Moto Bug"},
{1221, "The Tornado"},
{1222, "Crabmeat"},
{1223, "Eggcatcher"},
{1224, "K.I.T.T."},
{1225, "Goliath Armored Semi"},
{1226, "K.I.T.T. Jet"},
{1227, "Police Helicopter"},
{1228, "Police Hovercraft"},
{1229, "Police Plane"},
{1230, "Bionic Steed"},
{1231, "Bat-Raptor"},
{1232, "Ultrabat"},
{1233, "Batwing"},
{1234, "The Black Thunder"},
{1235, "Bat-Tank"},
{1236, "Skeleton Organ"},
{1237, "Skeleton Jukebox"},
{1238, "Skele-Turkey"},
{1239, "One-Eyed Willy's Pirate Ship"},
{1240, "Fanged Fortune"},
{1241, "Inferno Cannon"},
{1242, "Buckbeak"},
{1243, "Giant Owl"},
{1244, "Fierce Falcon"},
{1245, "Saturn's Sandworm"},
{1247, "Haunted Vacuum"},
{1246, "Spooky Spider"},
{1248, "PPG Smartphone"},
{1249, "PPG Hotline"},
{1250, "Powerpuff Mag-Net"},
{1253, "Mega Blast Bot"},
{1251, "Ka-Pow Cannon"},
{1252, "Slammin' Guitar"},
{1254, "Octi"},
{1255, "Super Skunk"},
{1256, "Sonic Squid"},
{1257, "T-Car"},
{1258, "T-Forklift"},
{1259, "T-Plane"},
{1260, "Spellbook of Azarath"},
{1261, "Raven Wings"},
{1262, "Giant Hand"},
{1263, "Titan Robot"},
{1264, "T-Rocket"},
{1265, "Robot Retriever"}};
minifig_creator_dialog::minifig_creator_dialog(QWidget* parent)
: QDialog(parent)
{
setWindowTitle(tr("Figure Creator"));
setObjectName("figure_creator");
setMinimumSize(QSize(500, 150));
QVBoxLayout* vbox_panel = new QVBoxLayout();
QComboBox* combo_figlist = new QComboBox();
QStringList filterlist;
for (const auto& [figure, figure_name] : list_minifigs)
{
QString name = QString::fromStdString(figure_name);
combo_figlist->addItem(name, QVariant(figure));
filterlist << std::move(name);
}
combo_figlist->addItem(tr("--Unknown--"), QVariant(0xFFFF));
combo_figlist->setEditable(true);
combo_figlist->setInsertPolicy(QComboBox::NoInsert);
combo_figlist->model()->sort(0, Qt::AscendingOrder);
QCompleter* co_compl = new QCompleter(filterlist, this);
co_compl->setCaseSensitivity(Qt::CaseInsensitive);
co_compl->setCompletionMode(QCompleter::PopupCompletion);
co_compl->setFilterMode(Qt::MatchContains);
combo_figlist->setCompleter(co_compl);
vbox_panel->addWidget(combo_figlist);
QFrame* line = new QFrame();
line->setFrameShape(QFrame::HLine);
line->setFrameShadow(QFrame::Sunken);
vbox_panel->addWidget(line);
QHBoxLayout* hbox_number = new QHBoxLayout();
QLabel* label_number = new QLabel(tr("Figure Number:"));
QLineEdit* edit_number = new QLineEdit(QString::fromStdString(std::to_string(0)));
QRegularExpressionValidator* rxv = new QRegularExpressionValidator(QRegularExpression("\\d*"), this);
edit_number->setValidator(rxv);
hbox_number->addWidget(label_number);
hbox_number->addWidget(edit_number);
vbox_panel->addLayout(hbox_number);
QHBoxLayout* hbox_buttons = new QHBoxLayout();
QPushButton* btn_create = new QPushButton(tr("Create"), this);
QPushButton* btn_cancel = new QPushButton(tr("Cancel"), this);
hbox_buttons->addStretch();
hbox_buttons->addWidget(btn_create);
hbox_buttons->addWidget(btn_cancel);
vbox_panel->addLayout(hbox_buttons);
setLayout(vbox_panel);
connect(combo_figlist, QOverload<int>::of(&QComboBox::currentIndexChanged), [=](int index)
{
const u16 fig_info = combo_figlist->itemData(index).toUInt();
if (fig_info != 0xFFFF)
{
edit_number->setText(QString::number(fig_info));
}
});
connect(btn_create, &QAbstractButton::clicked, this, [=, this]()
{
bool ok_num = false;
const u16 fig_num = edit_number->text().toUInt(&ok_num) & 0xFFFF;
if (!ok_num)
{
QMessageBox::warning(this, tr("Error converting value"), tr("Figure number entered is invalid!"), QMessageBox::Ok);
return;
}
const auto found_figure = list_minifigs.find(fig_num);
if (found_figure != list_minifigs.cend())
{
s_last_figure_path += QString::fromStdString(found_figure->second + ".bin");
}
else
{
s_last_figure_path += QString("Unknown(%1).bin").arg(fig_num);
}
m_file_path = QFileDialog::getSaveFileName(this, tr("Create Figure File"), s_last_figure_path, tr("Dimensions Figure (*.bin);;"));
if (m_file_path.isEmpty())
{
return;
}
fs::file dim_file(m_file_path.toStdString(), fs::read + fs::write + fs::create);
if (!dim_file)
{
QMessageBox::warning(this, tr("Failed to create minifig file!"), tr("Failed to create minifig file:\n%1").arg(m_file_path), QMessageBox::Ok);
return;
}
std::array<u8, 0x2D * 0x04> file_data{};
g_dimensionstoypad.create_blank_character(file_data, fig_num);
dim_file.write(file_data.data(), file_data.size());
dim_file.close();
s_last_figure_path = QFileInfo(m_file_path).absolutePath() + "/";
accept();
});
connect(btn_cancel, &QAbstractButton::clicked, this, &QDialog::reject);
connect(co_compl, QOverload<const QString&>::of(&QCompleter::activated), [=](const QString& text)
{
combo_figlist->setCurrentIndex(combo_figlist->findText(text));
});
}
QString minifig_creator_dialog::get_file_path() const
{
return m_file_path;
}
minifig_move_dialog::minifig_move_dialog(QWidget* parent, u8 old_index)
: QDialog(parent)
{
setWindowTitle(tr("Figure Mover"));
setObjectName("figure_mover");
setMinimumSize(QSize(500, 150));
auto* grid_panel = new QGridLayout();
add_minifig_position(grid_panel, 0, 0, 0, old_index);
grid_panel->addWidget(new QLabel(tr("")), 0, 1);
add_minifig_position(grid_panel, 1, 0, 2, old_index);
grid_panel->addWidget(new QLabel(tr(""), this), 0, 3);
add_minifig_position(grid_panel, 2, 0, 4, old_index);
add_minifig_position(grid_panel, 3, 1, 0, old_index);
add_minifig_position(grid_panel, 4, 1, 1, old_index);
grid_panel->addWidget(new QLabel(tr("")), 1, 2);
add_minifig_position(grid_panel, 5, 1, 3, old_index);
add_minifig_position(grid_panel, 6, 1, 4, old_index);
setLayout(grid_panel);
}
void minifig_move_dialog::add_minifig_position(QGridLayout* grid_panel, u8 index, u8 row, u8 column, u8 old_index)
{
ensure(index < figure_slots.size());
auto* vbox_panel = new QVBoxLayout();
if (figure_slots[index])
{
const auto found_figure = list_minifigs.find(figure_slots[index].value());
if (found_figure != list_minifigs.cend())
{
vbox_panel->addWidget(new QLabel(tr(found_figure->second.c_str())));
}
}
else
{
vbox_panel->addWidget(new QLabel(tr("None")));
}
auto* btn_move = new QPushButton(tr("Move Here"), this);
if (old_index == index)
{
btn_move->setText(tr("Pick up and Place"));
}
vbox_panel->addWidget(btn_move);
connect(btn_move, &QAbstractButton::clicked, this, [this, index]
{
m_index = index;
m_pad = index == 1 ? 1 :
index == 0 || index == 3 || index == 4 ? 2 :
3;
accept();
});
grid_panel->addLayout(vbox_panel, row, column);
}
u8 minifig_move_dialog::get_new_pad() const
{
return m_pad;
}
u8 minifig_move_dialog::get_new_index() const
{
return m_index;
}
dimensions_dialog::dimensions_dialog(QWidget* parent)
: QDialog(parent)
{
setWindowTitle(tr("Dimensions Manager"));
setObjectName("dimensions_manager");
setAttribute(Qt::WA_DeleteOnClose);
setMinimumSize(QSize(800, 200));
QVBoxLayout* vbox_panel = new QVBoxLayout();
QVBoxLayout* vbox_group = new QVBoxLayout();
QHBoxLayout* hbox_group_1 = new QHBoxLayout();
QHBoxLayout* hbox_group_2 = new QHBoxLayout();
QGroupBox* group_figures = new QGroupBox(tr("Active Dimensions Figures:"));
add_minifig_slot(hbox_group_1, 2, 0);
hbox_group_1->addSpacerItem(new QSpacerItem(50, 0, QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding));
add_minifig_slot(hbox_group_1, 1, 1);
hbox_group_1->addSpacerItem(new QSpacerItem(50, 0, QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding));
add_minifig_slot(hbox_group_1, 3, 2);
add_minifig_slot(hbox_group_2, 2, 3);
add_minifig_slot(hbox_group_2, 2, 4);
hbox_group_2->addSpacerItem(new QSpacerItem(50, 0, QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding));
add_minifig_slot(hbox_group_2, 3, 5);
add_minifig_slot(hbox_group_2, 3, 6);
vbox_group->addLayout(hbox_group_1);
vbox_group->addSpacerItem(new QSpacerItem(0, 20, QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding));
vbox_group->addLayout(hbox_group_2);
group_figures->setLayout(vbox_group);
vbox_panel->addWidget(group_figures);
setLayout(vbox_panel);
}
dimensions_dialog::~dimensions_dialog()
{
inst = nullptr;
}
dimensions_dialog* dimensions_dialog::get_dlg(QWidget* parent)
{
if (inst == nullptr)
inst = new dimensions_dialog(parent);
return inst;
}
void dimensions_dialog::add_minifig_slot(QHBoxLayout* layout, u8 pad, u8 index)
{
ensure(index < figure_slots.size());
QVBoxLayout* vbox_layout = new QVBoxLayout();
QHBoxLayout* hbox_name_move = new QHBoxLayout();
QHBoxLayout* hbox_actions = new QHBoxLayout();
QPushButton* clear_btn = new QPushButton(tr("Clear"));
QPushButton* create_btn = new QPushButton(tr("Create"));
QPushButton* load_btn = new QPushButton(tr("Load"));
QPushButton* move_btn = new QPushButton(tr("Move"));
m_edit_figures[index] = new QLineEdit();
m_edit_figures[index]->setEnabled(false);
if (figure_slots[index])
{
const auto found_figure = list_minifigs.find(figure_slots[index].value());
if (found_figure != list_minifigs.cend())
{
m_edit_figures[index]->setText(QString::fromStdString(found_figure->second));
}
else
{
m_edit_figures[index]->setText(tr("Unknown Figure"));
}
}
else
{
m_edit_figures[index]->setText(tr("None"));
}
connect(clear_btn, &QAbstractButton::clicked, this, [this, pad, index]
{
clear_figure(pad, index);
});
connect(create_btn, &QAbstractButton::clicked, this, [this, pad, index]
{
create_figure(pad, index);
});
connect(load_btn, &QAbstractButton::clicked, this, [this, pad, index]
{
load_figure(pad, index);
});
connect(move_btn, &QAbstractButton::clicked, this, [this, pad, index]
{
if (figure_slots[index])
{
move_figure(pad, index);
}
});
hbox_name_move->addWidget(m_edit_figures[index]);
hbox_name_move->addWidget(move_btn);
hbox_actions->addWidget(clear_btn);
hbox_actions->addWidget(create_btn);
hbox_actions->addWidget(load_btn);
vbox_layout->addLayout(hbox_name_move);
vbox_layout->addLayout(hbox_actions);
layout->addLayout(vbox_layout);
}
void dimensions_dialog::clear_figure(u8 pad, u8 index)
{
ensure(index < figure_slots.size());
if (figure_slots[index])
{
g_dimensionstoypad.remove_figure(pad, index, true, true);
figure_slots[index] = std::nullopt;
m_edit_figures[index]->setText(tr("None"));
}
}
void dimensions_dialog::create_figure(u8 pad, u8 index)
{
ensure(index < figure_slots.size());
minifig_creator_dialog create_dlg(this);
if (create_dlg.exec() == Accepted)
{
load_figure_path(pad, index, create_dlg.get_file_path());
}
}
void dimensions_dialog::load_figure(u8 pad, u8 index)
{
ensure(index < figure_slots.size());
const QString file_path = QFileDialog::getOpenFileName(this, tr("Select Dimensions File"), s_last_figure_path, tr("Dimensions Figure (*.bin);;"));
if (file_path.isEmpty())
{
return;
}
s_last_figure_path = QFileInfo(file_path).absolutePath() + "/";
load_figure_path(pad, index, file_path);
}
void dimensions_dialog::move_figure(u8 pad, u8 index)
{
ensure(index < figure_slots.size());
minifig_move_dialog move_dlg(this, index);
g_dimensionstoypad.temp_remove(index);
if (move_dlg.exec() == Accepted)
{
g_dimensionstoypad.move_figure(move_dlg.get_new_pad(), move_dlg.get_new_index(), pad, index);
if (index != move_dlg.get_new_index())
{
figure_slots[move_dlg.get_new_index()] = figure_slots[index];
m_edit_figures[move_dlg.get_new_index()]->setText(m_edit_figures[index]->text());
figure_slots[index] = std::nullopt;
m_edit_figures[index]->setText(tr("None"));
}
}
else
{
g_dimensionstoypad.cancel_remove(index);
}
}
void dimensions_dialog::load_figure_path(u8 pad, u8 index, const QString& path)
{
fs::file dim_file(path.toStdString(), fs::read + fs::write + fs::lock);
if (!dim_file)
{
QMessageBox::warning(this, tr("Failed to open the figure file!"), tr("Failed to open the figure file(%1)!\nFile may already be in use on the base.").arg(path), QMessageBox::Ok);
return;
}
std::array<u8, 0x2D * 0x04> data;
if (dim_file.read(data.data(), data.size()) != data.size())
{
QMessageBox::warning(this, tr("Failed to read the figure file!"), tr("Failed to read the figure file(%1)!\nFile was too small.").arg(path), QMessageBox::Ok);
return;
}
clear_figure(pad, index);
const u32 fig_num = g_dimensionstoypad.load_figure(data, std::move(dim_file), pad, index, true);
figure_slots[index] = fig_num;
const auto name = list_minifigs.find(fig_num);
if (name != list_minifigs.cend())
{
m_edit_figures[index]->setText(QString::fromStdString(name->second));
}
else
{
const auto blank_name = list_tokens.find(fig_num);
if (blank_name != list_tokens.cend())
{
m_edit_figures[index]->setText(QString::fromStdString(blank_name->second));
}
else
{
m_edit_figures[index]->setText(tr("Blank Tag"));
}
}
}
| 21,508
|
C++
|
.cpp
| 714
| 27.773109
| 179
| 0.673727
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,078
|
localized_emu.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/localized_emu.cpp
|
#include "stdafx.h"
#include "localized_emu.h"
#include "Emu/Io/MouseHandler.h"
QString localized_emu::translated_pad_button(pad_button btn)
{
switch (btn)
{
case pad_button::dpad_up: return tr("D-Pad Up");
case pad_button::dpad_down: return tr("D-Pad Down");
case pad_button::dpad_left: return tr("D-Pad Left");
case pad_button::dpad_right: return tr("D-Pad Right");
case pad_button::select: return tr("Select");
case pad_button::start: return tr("Start");
case pad_button::ps: return tr("PS");
case pad_button::triangle: return tr("Triangle");
case pad_button::circle: return tr("Circle");
case pad_button::square: return tr("Square");
case pad_button::cross: return tr("Cross");
case pad_button::L1: return tr("L1");
case pad_button::R1: return tr("R1");
case pad_button::L2: return tr("L2");
case pad_button::R2: return tr("R2");
case pad_button::L3: return tr("L3");
case pad_button::R3: return tr("R3");
case pad_button::ls_up: return tr("Left Stick Up");
case pad_button::ls_down: return tr("Left Stick Down");
case pad_button::ls_left: return tr("Left Stick Left");
case pad_button::ls_right: return tr("Left Stick Right");
case pad_button::ls_x: return tr("Left Stick X-Axis");
case pad_button::ls_y: return tr("Left Stick Y-Axis");
case pad_button::rs_up: return tr("Right Stick Up");
case pad_button::rs_down: return tr("Right Stick Down");
case pad_button::rs_left: return tr("Right Stick Left");
case pad_button::rs_right: return tr("Right Stick Right");
case pad_button::rs_x: return tr("Right Stick X-Axis");
case pad_button::rs_y: return tr("Right Stick Y-Axis");
case pad_button::pad_button_max_enum: return "";
case pad_button::mouse_button_1: return tr("Mouse Button 1");
case pad_button::mouse_button_2: return tr("Mouse Button 2");
case pad_button::mouse_button_3: return tr("Mouse Button 3");
case pad_button::mouse_button_4: return tr("Mouse Button 4");
case pad_button::mouse_button_5: return tr("Mouse Button 5");
case pad_button::mouse_button_6: return tr("Mouse Button 6");
case pad_button::mouse_button_7: return tr("Mouse Button 7");
case pad_button::mouse_button_8: return tr("Mouse Button 8");
}
return "";
}
QString localized_emu::translated_mouse_button(int btn)
{
switch (btn)
{
case CELL_MOUSE_BUTTON_1: return tr("Button 1");
case CELL_MOUSE_BUTTON_2: return tr("Button 2");
case CELL_MOUSE_BUTTON_3: return tr("Button 3");
case CELL_MOUSE_BUTTON_4: return tr("Button 4");
case CELL_MOUSE_BUTTON_5: return tr("Button 5");
case CELL_MOUSE_BUTTON_6: return tr("Button 6");
case CELL_MOUSE_BUTTON_7: return tr("Button 7");
case CELL_MOUSE_BUTTON_8: return tr("Button 8");
}
return "";
}
| 2,676
|
C++
|
.cpp
| 63
| 40.587302
| 62
| 0.70969
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,079
|
progress_dialog.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/progress_dialog.cpp
|
#include "progress_dialog.h"
#include <QApplication>
#include <QLabel>
progress_dialog::progress_dialog(const QString& windowTitle, const QString& labelText, const QString& cancelButtonText, int minimum, int maximum, bool delete_on_close, QWidget* parent, Qt::WindowFlags flags)
: QProgressDialog(labelText, cancelButtonText, minimum, maximum, parent, flags)
{
setWindowTitle(windowTitle);
setMinimumSize(QLabel("This is the very length of the progressdialog due to hidpi reasons.").sizeHint().width(), sizeHint().height());
setValue(0);
setWindowModality(Qt::WindowModal);
if (delete_on_close)
{
SetDeleteOnClose();
}
m_progress_indicator = std::make_unique<progress_indicator>(minimum, maximum);
}
progress_dialog::~progress_dialog()
{
}
void progress_dialog::SetRange(int min, int max)
{
m_progress_indicator->set_range(min, max);
setRange(min, max);
}
void progress_dialog::SetValue(int progress)
{
const int value = std::clamp(progress, minimum(), maximum());
m_progress_indicator->set_value(value);
setValue(value);
}
void progress_dialog::SetDeleteOnClose()
{
setAttribute(Qt::WA_DeleteOnClose);
connect(this, &QProgressDialog::canceled, this, &QProgressDialog::close, Qt::UniqueConnection);
}
void progress_dialog::SignalFailure() const
{
m_progress_indicator->signal_failure();
QApplication::beep();
}
void progress_dialog::show_progress_indicator()
{
// Try to find a window handle first
QWindow* handle = windowHandle();
for (QWidget* ancestor = this; !handle && ancestor;)
{
ancestor = static_cast<QWidget*>(ancestor->parent());
if (ancestor) handle = ancestor->windowHandle();
}
m_progress_indicator->show(handle);
}
void progress_dialog::setVisible(bool visible)
{
if (visible)
{
if (!isVisible())
{
show_progress_indicator();
}
}
else if (isVisible())
{
m_progress_indicator->hide();
}
QProgressDialog::setVisible(visible);
}
| 1,907
|
C++
|
.cpp
| 66
| 26.893939
| 207
| 0.75864
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,080
|
save_manager_dialog.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/save_manager_dialog.cpp
|
#include "save_manager_dialog.h"
#include "custom_table_widget_item.h"
#include "qt_utils.h"
#include "gui_settings.h"
#include "persistent_settings.h"
#include "game_list_delegate.h"
#include "progress_dialog.h"
#include "Emu/System.h"
#include "Emu/system_utils.hpp"
#include "Loader/PSF.h"
#include <QtConcurrent>
#include <QDateTime>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QLineEdit>
#include <QMenu>
#include <QMessageBox>
#include <QGuiApplication>
#include <QDesktopServices>
#include <QPainter>
#include <QScreen>
#include <QScrollBar>
#include "Utilities/File.h"
#include "Utilities/mutex.h"
LOG_CHANNEL(gui_log, "GUI");
namespace
{
// Helper converters
QString FormatTimestamp(s64 time)
{
QDateTime dateTime;
dateTime.setSecsSinceEpoch(time);
return dateTime.toString("yyyy-MM-dd HH:mm:ss");
}
}
enum SaveColumns
{
Icon = 0,
Name = 1,
Time = 2,
Dir = 3,
Note = 4,
Count
};
enum SaveUserRole
{
Pixmap = Qt::UserRole,
PixmapLoaded
};
save_manager_dialog::save_manager_dialog(std::shared_ptr<gui_settings> gui_settings, std::shared_ptr<persistent_settings> persistent_settings, std::string dir, QWidget* parent)
: QDialog(parent)
, m_dir(std::move(dir))
, m_gui_settings(std::move(gui_settings))
, m_persistent_settings(std::move(persistent_settings))
{
setWindowTitle(tr("Save Manager"));
setMinimumSize(QSize(400, 400));
setAttribute(Qt::WA_DeleteOnClose);
Init();
}
/*
* Future proofing. Makes it easier in future if I add ability to change directories
*/
void save_manager_dialog::Init()
{
// Table
m_list = new QTableWidget(this);
m_list->setItemDelegate(new game_list_delegate(m_list));
m_list->setSelectionMode(QAbstractItemView::SelectionMode::ExtendedSelection);
m_list->setSelectionBehavior(QAbstractItemView::SelectRows);
m_list->setContextMenuPolicy(Qt::CustomContextMenu);
m_list->setColumnCount(SaveColumns::Count);
m_list->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
m_list->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
m_list->verticalScrollBar()->setSingleStep(20);
m_list->horizontalScrollBar()->setSingleStep(10);
m_list->setHorizontalHeaderLabels(QStringList() << tr("Icon") << tr("Title & Subtitle") << tr("Last Modified") << tr("Save ID") << tr("Notes"));
m_list->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Fixed);
m_list->horizontalHeader()->setStretchLastSection(true);
// Bottom bar
const int icon_size = m_gui_settings->GetValue(gui::sd_icon_size).toInt();
m_icon_size = QSize(icon_size, icon_size * 176 / 320);
QLabel* label_icon_size = new QLabel(tr("Icon size:"), this);
QSlider* slider_icon_size = new QSlider(Qt::Horizontal, this);
slider_icon_size->setMinimum(60);
slider_icon_size->setMaximum(225);
slider_icon_size->setValue(icon_size);
QLabel* label_search_bar = new QLabel(tr("Search:"), this);
QLineEdit* search_bar = new QLineEdit(this);
QPushButton* push_close = new QPushButton(tr("&Close"), this);
push_close->setAutoDefault(true);
// Details
m_details_icon = new QLabel(this);
m_details_icon->setMinimumSize(320, 176);
m_details_title = new QLabel(tr("Select an item to view details"), this);
m_details_title->setWordWrap(true);
m_details_subtitle = new QLabel(this);
m_details_subtitle->setWordWrap(true);
m_details_modified = new QLabel(this);
m_details_modified->setWordWrap(true);
m_details_details = new QLabel(this);
m_details_details->setWordWrap(true);
m_details_note = new QLabel(this);
m_details_note->setWordWrap(true);
m_button_delete = new QPushButton(tr("Delete Selection"), this);
m_button_delete->setDisabled(true);
m_button_folder = new QPushButton(tr("View Folder"), this);
m_button_delete->setDisabled(true);
// Details layout
QVBoxLayout *vbox_details = new QVBoxLayout();
vbox_details->addWidget(m_details_icon);
vbox_details->addWidget(m_details_title);
vbox_details->addWidget(m_details_subtitle);
vbox_details->addWidget(m_details_modified);
vbox_details->addWidget(m_details_details);
vbox_details->addWidget(m_details_note);
vbox_details->addStretch();
vbox_details->addWidget(m_button_delete);
vbox_details->setAlignment(m_button_delete, Qt::AlignHCenter);
vbox_details->addWidget(m_button_folder);
vbox_details->setAlignment(m_button_folder, Qt::AlignHCenter);
// List + Details
QHBoxLayout *hbox_content = new QHBoxLayout();
hbox_content->addWidget(m_list);
hbox_content->addLayout(vbox_details);
// Items below list
QHBoxLayout* hbox_buttons = new QHBoxLayout();
hbox_buttons->addWidget(label_search_bar);
hbox_buttons->addWidget(search_bar);
hbox_buttons->addWidget(label_icon_size);
hbox_buttons->addWidget(slider_icon_size);
hbox_buttons->addStretch();
hbox_buttons->addWidget(push_close);
// main layout
QVBoxLayout* vbox_main = new QVBoxLayout();
vbox_main->setAlignment(Qt::AlignCenter);
vbox_main->addLayout(hbox_content);
vbox_main->addLayout(hbox_buttons);
setLayout(vbox_main);
UpdateList();
m_list->sortByColumn(1, Qt::AscendingOrder);
if (restoreGeometry(m_gui_settings->GetValue(gui::sd_geometry).toByteArray()))
resize(size().expandedTo(QGuiApplication::primaryScreen()->availableSize() * 0.5));
// Connects and events
connect(push_close, &QAbstractButton::clicked, this, &save_manager_dialog::close);
connect(m_button_delete, &QAbstractButton::clicked, this, &save_manager_dialog::OnEntriesRemove);
connect(m_button_folder, &QAbstractButton::clicked, [this]()
{
const int idx = m_list->currentRow();
QTableWidgetItem* item = m_list->item(idx, SaveColumns::Name);
if (!item)
{
return;
}
const int idx_real = item->data(Qt::UserRole).toInt();
const QString path = QString::fromStdString(m_dir + ::at32(m_save_entries, idx_real).dirName + "/");
gui::utils::open_dir(path);
});
connect(slider_icon_size, &QAbstractSlider::valueChanged, this, &save_manager_dialog::SetIconSize);
connect(m_list->horizontalHeader(), &QHeaderView::sectionClicked, this, &save_manager_dialog::OnSort);
connect(m_list, &QTableWidget::customContextMenuRequested, this, &save_manager_dialog::ShowContextMenu);
connect(m_list, &QTableWidget::cellChanged, [&](int row, int col)
{
if (col != SaveColumns::Note)
{
return;
}
QTableWidgetItem* user_item = m_list->item(row, SaveColumns::Name);
QTableWidgetItem* text_item = m_list->item(row, SaveColumns::Note);
if (!user_item || !text_item)
{
return;
}
const int original_index = user_item->data(Qt::UserRole).toInt();
const SaveDataEntry originalEntry = ::at32(m_save_entries, original_index);
const QString original_dir_name = QString::fromStdString(originalEntry.dirName);
QVariantMap notes = m_persistent_settings->GetValue(gui::persistent::save_notes).toMap();
notes[original_dir_name] = text_item->text();
m_persistent_settings->SetValue(gui::persistent::save_notes, notes);
});
connect(m_list, &QTableWidget::itemSelectionChanged, this, &save_manager_dialog::UpdateDetails);
connect(this, &save_manager_dialog::IconReady, this, [this](int index, const QPixmap& pixmap)
{
if (QTableWidgetItem* icon_item = m_list->item(index, SaveColumns::Icon))
{
icon_item->setData(Qt::DecorationRole, pixmap);
}
});
connect(search_bar, &QLineEdit::textChanged, this, &save_manager_dialog::text_changed);
}
/**
* This certainly isn't ideal for this code, as it essentially copies cellSaveData. But, I have no other choice without adding public methods to cellSaveData.
*/
std::vector<SaveDataEntry> save_manager_dialog::GetSaveEntries(const std::string& base_dir)
{
std::vector<SaveDataEntry> save_entries;
std::vector<fs::dir_entry> dir_list;
qRegisterMetaType<QVector<int>>("QVector<int>");
QList<int> indices;
for (const auto& entry : fs::dir(base_dir))
{
if (!entry.is_directory || entry.name == "." || entry.name == "..")
{
continue;
}
indices.append(static_cast<int>(dir_list.size()));
dir_list.emplace_back(entry);
}
if (dir_list.empty())
{
return save_entries;
}
QFutureWatcher<void> future_watcher;
progress_dialog progress_dialog(tr("Loading save data"), tr("Loading save data, please wait..."), tr("Cancel"), 0, 1, false, this, Qt::Dialog | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
connect(&future_watcher, &QFutureWatcher<void>::progressRangeChanged, &progress_dialog, &QProgressDialog::setRange);
connect(&future_watcher, &QFutureWatcher<void>::progressValueChanged, &progress_dialog, &QProgressDialog::setValue);
connect(&progress_dialog, &QProgressDialog::canceled, this, [this, &future_watcher]()
{
future_watcher.cancel();
close(); // It's pointless to show an empty window
});
shared_mutex mutex;
future_watcher.setFuture(QtConcurrent::map(indices, [&](int index)
{
const fs::dir_entry& entry = ::at32(dir_list, index);
gui_log.trace("Loading trophy dir: %s", entry.name);
// PSF parameters
const auto [psf, errc] = psf::load(base_dir + entry.name + "/PARAM.SFO");
if (psf.empty())
{
gui_log.error("Failed to load savedata: %s (%s)", base_dir + "/" + entry.name, errc);
return;
}
SaveDataEntry save_entry2;
save_entry2.dirName = psf::get_string(psf, "SAVEDATA_DIRECTORY");
save_entry2.listParam = psf::get_string(psf, "SAVEDATA_LIST_PARAM");
save_entry2.title = psf::get_string(psf, "TITLE");
save_entry2.subtitle = psf::get_string(psf, "SUB_TITLE");
save_entry2.details = psf::get_string(psf, "DETAIL");
save_entry2.size = 0;
for (const auto& entry2 : fs::dir(base_dir + entry.name))
{
save_entry2.size += entry2.size;
}
save_entry2.atime = entry.atime;
save_entry2.mtime = entry.mtime;
save_entry2.ctime = entry.ctime;
save_entry2.isNew = false;
std::scoped_lock lock(mutex);
save_entries.emplace_back(save_entry2);
}));
progress_dialog.exec();
future_watcher.waitForFinished();
return save_entries;
}
void save_manager_dialog::UpdateList()
{
WaitForRepaintThreads(true);
if (m_dir.empty())
{
m_dir = rpcs3::utils::get_hdd0_dir() + "home/" + Emu.GetUsr() + "/savedata/";
}
m_save_entries = GetSaveEntries(m_dir);
m_list->setSortingEnabled(false); // Disable sorting before using setItem calls
m_list->clearContents();
m_list->setRowCount(static_cast<int>(m_save_entries.size()));
const QVariantMap notes = m_persistent_settings->GetValue(gui::persistent::save_notes).toMap();
if (m_gui_settings->GetValue(gui::m_enableUIColors).toBool())
{
m_icon_color = m_gui_settings->GetValue(gui::sd_icon_color).value<QColor>();
}
else
{
m_icon_color = gui::utils::get_label_color("save_manager_icon_background_color", Qt::transparent, Qt::transparent);
}
QPixmap placeholder(320, 176);
placeholder.fill(Qt::transparent);
for (int i = 0; i < static_cast<int>(m_save_entries.size()); ++i)
{
const SaveDataEntry& entry = ::at32(m_save_entries, i);
const QString title = QString::fromStdString(entry.title) + QStringLiteral("\n") + QString::fromStdString(entry.subtitle);
const QString dir_name = QString::fromStdString(entry.dirName);
custom_table_widget_item* iconItem = new custom_table_widget_item;
iconItem->setData(Qt::DecorationRole, placeholder);
iconItem->setData(SaveUserRole::Pixmap, placeholder);
iconItem->setData(SaveUserRole::PixmapLoaded, false);
iconItem->setFlags(iconItem->flags() & ~Qt::ItemIsEditable);
m_list->setItem(i, SaveColumns::Icon, iconItem);
QTableWidgetItem* titleItem = new QTableWidgetItem(title);
titleItem->setData(Qt::UserRole, i); // For sorting to work properly
titleItem->setFlags(titleItem->flags() & ~Qt::ItemIsEditable);
m_list->setItem(i, SaveColumns::Name, titleItem);
QTableWidgetItem* timeItem = new QTableWidgetItem(FormatTimestamp(entry.mtime));
timeItem->setFlags(timeItem->flags() & ~Qt::ItemIsEditable);
m_list->setItem(i, SaveColumns::Time, timeItem);
QTableWidgetItem* dirNameItem = new QTableWidgetItem(dir_name);
dirNameItem->setFlags(dirNameItem->flags() & ~Qt::ItemIsEditable);
m_list->setItem(i, SaveColumns::Dir, dirNameItem);
QTableWidgetItem* noteItem = new QTableWidgetItem();
noteItem->setFlags(noteItem->flags() | Qt::ItemIsEditable);
if (notes.contains(dir_name))
{
noteItem->setText(notes[dir_name].toString());
}
m_list->setItem(i, SaveColumns::Note, noteItem);
}
m_list->setSortingEnabled(true); // Enable sorting only after using setItem calls
m_list->horizontalHeader()->resizeSections(QHeaderView::ResizeToContents);
m_list->verticalHeader()->resizeSections(QHeaderView::ResizeToContents);
const QSize tableSize(
m_list->verticalHeader()->width() + m_list->horizontalHeader()->length() + m_list->frameWidth() * 2,
m_list->horizontalHeader()->height() + m_list->verticalHeader()->length() + m_list->frameWidth() * 2);
const QSize preferredSize = minimumSize().expandedTo(sizeHint() - m_list->sizeHint() + tableSize);
const QSize maxSize(preferredSize.width(), static_cast<int>(QGuiApplication::primaryScreen()->geometry().height() * 0.6));
resize(preferredSize.boundedTo(maxSize));
UpdateIcons();
}
void save_manager_dialog::HandleRepaintUiRequest()
{
const QSize window_size = size();
const Qt::SortOrder sort_order = m_sort_ascending ? Qt::AscendingOrder : Qt::DescendingOrder;
UpdateList();
m_list->sortByColumn(m_sort_column, sort_order);
resize(window_size);
}
void save_manager_dialog::UpdateIcons()
{
WaitForRepaintThreads(true);
const qreal dpr = devicePixelRatioF();
QPixmap placeholder(m_icon_size);
placeholder.fill(Qt::transparent);
for (int i = 0; i < m_list->rowCount(); ++i)
{
if (movie_item* icon_item = static_cast<movie_item*>(m_list->item(i, SaveColumns::Icon)))
{
icon_item->setData(Qt::DecorationRole, placeholder);
}
}
m_list->resizeRowsToContents();
m_list->resizeColumnToContents(SaveColumns::Icon);
for (int i = 0; i < m_list->rowCount(); ++i)
{
if (movie_item* icon_item = static_cast<movie_item*>(m_list->item(i, SaveColumns::Icon)))
{
icon_item->set_icon_load_func([this, cancel = icon_item->icon_loading_aborted(), dpr](int index)
{
if (cancel && cancel->load())
{
return;
}
QPixmap icon;
if (movie_item* item = static_cast<movie_item*>(m_list->item(index, SaveColumns::Icon)))
{
if (!item->data(SaveUserRole::PixmapLoaded).toBool())
{
// Load game icon
if (QTableWidgetItem* user_item = m_list->item(index, SaveColumns::Name))
{
const int idx_real = user_item->data(Qt::UserRole).toInt();
const SaveDataEntry& entry = ::at32(m_save_entries, idx_real);
if (!icon.load(QString::fromStdString(m_dir + entry.dirName + "/ICON0.PNG")))
{
gui_log.warning("Loading icon for save %s failed", entry.dirName);
icon = QPixmap(320, 176);
icon.fill(m_icon_color);
}
item->setData(SaveUserRole::PixmapLoaded, true);
item->setData(SaveUserRole::Pixmap, icon);
}
else
{
gui_log.error("Loading icon for save failed (table item is null)");
}
}
else
{
icon = item->data(SaveUserRole::Pixmap).value<QPixmap>();
}
}
if (cancel && cancel->load())
{
return;
}
QPixmap new_icon(icon.size() * dpr);
new_icon.setDevicePixelRatio(dpr);
new_icon.fill(m_icon_color);
if (!icon.isNull())
{
QPainter painter(&new_icon);
painter.setRenderHint(QPainter::SmoothPixmapTransform);
painter.drawPixmap(QPoint(0, 0), icon);
painter.end();
}
new_icon = new_icon.scaled(m_icon_size * dpr, Qt::KeepAspectRatio, Qt::TransformationMode::SmoothTransformation);
if (!cancel || !cancel->load())
{
Q_EMIT IconReady(index, new_icon);
}
});
}
}
}
/**
* Copied method to do sort from save_data_list_dialog
*/
void save_manager_dialog::OnSort(int logicalIndex)
{
if (logicalIndex >= 0)
{
WaitForRepaintThreads(false);
if (logicalIndex == m_sort_column)
{
m_sort_ascending ^= true;
}
else
{
m_sort_ascending = true;
}
m_sort_column = logicalIndex;
const Qt::SortOrder sort_order = m_sort_ascending ? Qt::AscendingOrder : Qt::DescendingOrder;
m_list->sortByColumn(m_sort_column, sort_order);
}
}
// Remove a save file, need to be confirmed.
void save_manager_dialog::OnEntryRemove(int row, bool user_interaction)
{
if (QTableWidgetItem* item = m_list->item(row, SaveColumns::Name))
{
const int idx_real = item->data(Qt::UserRole).toInt();
const SaveDataEntry& entry = ::at32(m_save_entries, idx_real);
if (!user_interaction || QMessageBox::question(this, tr("Delete Confirmation"), tr("Are you sure you want to delete:\n%1?").arg(QString::fromStdString(entry.title)), QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes)
{
fs::remove_all(m_dir + entry.dirName + "/");
m_list->removeRow(row);
}
}
}
void save_manager_dialog::OnEntriesRemove()
{
QModelIndexList selection(m_list->selectionModel()->selectedRows());
if (selection.empty())
{
return;
}
WaitForRepaintThreads(false);
if (selection.size() == 1)
{
OnEntryRemove(selection.first().row(), true);
return;
}
if (QMessageBox::question(this, tr("Delete Confirmation"), tr("Are you sure you want to delete these %n items?", "", selection.size()), QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes)
{
std::sort(selection.rbegin(), selection.rend());
for (const QModelIndex& index : selection)
{
OnEntryRemove(index.row(), false);
}
}
}
// Pop-up a small context-menu, being a replacement for save_data_manage_dialog
void save_manager_dialog::ShowContextMenu(const QPoint &pos)
{
const int idx = m_list->currentRow();
if (idx == -1)
{
return;
}
WaitForRepaintThreads(false);
const bool selectedItems = m_list->selectionModel()->selectedRows().size() > 1;
QAction* removeAct = new QAction(tr("&Remove"), this);
QAction* showDirAct = new QAction(tr("&Open Save Directory"), this);
QMenu* menu = new QMenu();
menu->addAction(removeAct);
menu->addAction(showDirAct);
showDirAct->setEnabled(!selectedItems);
// Events
connect(removeAct, &QAction::triggered, this, &save_manager_dialog::OnEntriesRemove); // entriesremove handles case of one as well
connect(showDirAct, &QAction::triggered, [this, idx]()
{
QTableWidgetItem* item = m_list->item(idx, SaveColumns::Name);
if (!item)
{
return;
}
const int idx_real = item->data(Qt::UserRole).toInt();
const QString path = QString::fromStdString(m_dir + ::at32(m_save_entries, idx_real).dirName + "/");
gui::utils::open_dir(path);
});
menu->exec(m_list->viewport()->mapToGlobal(pos));
}
void save_manager_dialog::SetIconSize(int size)
{
m_icon_size = QSize(size, size * 176 / 320);
UpdateIcons();
m_gui_settings->SetValue(gui::sd_icon_size, size, false); // Don't sync while sliding
}
void save_manager_dialog::closeEvent(QCloseEvent *event)
{
m_gui_settings->SetValue(gui::sd_geometry, saveGeometry());
QDialog::closeEvent(event);
}
void save_manager_dialog::UpdateDetails()
{
if (const int selected = m_list->selectionModel()->selectedRows().size(); selected != 1)
{
m_details_icon->setPixmap(QPixmap());
m_details_subtitle->setText("");
m_details_modified->setText("");
m_details_details->setText("");
m_details_note->setText("");
if (selected > 1)
{
m_button_delete->setDisabled(false);
m_details_title->setText(tr("%1 items selected").arg(selected));
}
else
{
m_button_delete->setDisabled(true);
m_details_title->setText(tr("Select an item to view details"));
}
m_button_folder->setDisabled(true);
}
else
{
WaitForRepaintThreads(false);
const int row = m_list->currentRow();
QTableWidgetItem* item = m_list->item(row, SaveColumns::Name);
QTableWidgetItem* icon_item = m_list->item(row, SaveColumns::Icon);
if (!item || !icon_item)
{
return;
}
const int idx = item->data(Qt::UserRole).toInt();
const SaveDataEntry& save = ::at32(m_save_entries, idx);
m_details_icon->setPixmap(icon_item->data(Qt::UserRole).value<QPixmap>());
m_details_title->setText(QString::fromStdString(save.title));
m_details_subtitle->setText(QString::fromStdString(save.subtitle));
m_details_modified->setText(tr("Last modified: %1").arg(FormatTimestamp(save.mtime)));
m_details_details->setText(tr("Details:\n").append(QString::fromStdString(save.details)));
QString note = tr("Note:\n");
const QString dir_name = QString::fromStdString(save.dirName);
if (const QVariantMap map = m_persistent_settings->GetValue(gui::persistent::save_notes).toMap();
map.contains(dir_name))
{
note.append(map[dir_name].toString());
}
m_details_note->setText(note);
m_button_delete->setDisabled(false);
m_button_folder->setDisabled(false);
}
}
void save_manager_dialog::WaitForRepaintThreads(bool abort)
{
for (int i = 0; i < m_list->rowCount(); i++)
{
if (movie_item* item = static_cast<movie_item*>(m_list->item(i, SaveColumns::Icon)))
{
item->wait_for_icon_loading(abort);
}
}
}
void save_manager_dialog::text_changed(const QString& text)
{
const auto check_text = [&](int row)
{
if (text.isEmpty())
return true;
for (int col = SaveColumns::Name; col < SaveColumns::Count; col++)
{
const QTableWidgetItem* item = m_list->item(row, col);
if (item && item->text().contains(text, Qt::CaseInsensitive))
return true;
}
return false;
};
bool new_row_visible = false;
for (int i = 0; i < m_list->rowCount(); i++)
{
// only show items filtered for search text
const bool is_hidden = m_list->isRowHidden(i);
const bool hide = !check_text(i);
if (is_hidden != hide)
{
m_list->setRowHidden(i, hide);
new_row_visible = !hide;
}
}
if (new_row_visible)
{
UpdateIcons();
}
}
| 21,622
|
C++
|
.cpp
| 592
| 33.702703
| 223
| 0.72035
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,081
|
rpcn_settings_dialog.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/rpcn_settings_dialog.cpp
|
#include <QMessageBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QRegularExpressionValidator>
#include <QInputDialog>
#include <QGroupBox>
#include <QMenu>
#include <QDialogButtonBox>
#include <thread>
#include "qt_utils.h"
#include "rpcn_settings_dialog.h"
#include "Emu/System.h"
#include "Emu/NP/rpcn_config.h"
#include <wolfssl/ssl.h>
#include <wolfssl/openssl/evp.h>
LOG_CHANNEL(rpcn_settings_log, "rpcn settings dlg");
bool validate_rpcn_username(std::string_view username)
{
if (username.length() < 3 || username.length() > 16)
return false;
return std::all_of(username.cbegin(), username.cend(), [](const char c)
{
return std::isalnum(static_cast<unsigned char>(c)) || c == '-' || c == '_';
});
}
bool validate_email(std::string_view email)
{
const QRegularExpressionValidator simple_email_validator(QRegularExpression("^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$"));
QString qstr_email = QString::fromStdString(std::string(email));
int pos = 0;
if (qstr_email.isEmpty() || qstr_email.contains(' ') || qstr_email.contains('\t') || simple_email_validator.validate(qstr_email, pos) != QValidator::Acceptable)
return false;
return true;
}
bool validate_token(std::string_view token)
{
return token.size() == 16 && std::all_of(token.cbegin(), token.cend(), [](const char c) { return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z'); });
}
std::string derive_password(std::string_view user_password)
{
std::string_view salt_str = "No matter where you go, everybody's connected.";
u8 derived_password_digest[SHA3_256_DIGEST_LENGTH];
ensure(!wc_PBKDF2(derived_password_digest, reinterpret_cast<const u8*>(user_password.data()), ::narrow<s32>(user_password.size()), reinterpret_cast<const u8*>(salt_str.data()), ::narrow<s32>(salt_str.size()), 200'000, SHA3_256_DIGEST_LENGTH, WC_SHA3_256));
std::string derived_password("0000000000000000000000000000000000000000000000000000000000000000");
for (u32 i = 0; i < SHA3_256_DIGEST_LENGTH; i++)
{
constexpr auto pal = "0123456789ABCDEF";
derived_password[i * 2] = pal[derived_password_digest[i] >> 4];
derived_password[(i * 2) + 1] = pal[derived_password_digest[i] & 15];
}
return derived_password;
}
rpcn_settings_dialog::rpcn_settings_dialog(QWidget* parent)
: QDialog(parent)
{
g_cfg_rpcn.load();
const auto set_title = [this]()
{
if (const std::string npid = g_cfg_rpcn.get_npid(); !npid.empty())
{
setWindowTitle(tr("RPCN - %0").arg(QString::fromStdString(npid)));
return;
}
setWindowTitle(tr("RPCN"));
};
set_title();
setObjectName("rpcn_settings_dialog");
setMinimumSize(QSize(400, 100));
QVBoxLayout* vbox_global = new QVBoxLayout();
QGroupBox* group_btns = new QGroupBox(tr("RPCN"));
QHBoxLayout* hbox_group = new QHBoxLayout();
QPushButton* btn_account = new QPushButton(tr("Account"));
QPushButton* btn_friends = new QPushButton(tr("Friends"));
hbox_group->addWidget(btn_account);
hbox_group->addWidget(btn_friends);
group_btns->setLayout(hbox_group);
vbox_global->addWidget(group_btns);
setLayout(vbox_global);
connect(btn_account, &QPushButton::clicked, this, [this, set_title]()
{
if (!Emu.IsStopped())
{
QMessageBox::critical(this, tr("Error: Emulation Running"), tr("You need to stop the emulator before editing RPCN account information!"), QMessageBox::Ok);
return;
}
rpcn_account_dialog dlg(this);
dlg.exec();
set_title();
});
connect(btn_friends, &QPushButton::clicked, this, [this]()
{
rpcn_friends_dialog dlg(this);
if (dlg.is_ok())
dlg.exec();
});
}
rpcn_account_dialog::rpcn_account_dialog(QWidget* parent)
: QDialog(parent)
{
setWindowTitle(tr("RPCN: Account"));
setObjectName("rpcn_account_dialog");
QVBoxLayout* vbox_global = new QVBoxLayout();
QGroupBox* grp_server = new QGroupBox(tr("Server:"));
QVBoxLayout* vbox_server = new QVBoxLayout();
QHBoxLayout* hbox_lbl_combo = new QHBoxLayout();
QLabel* lbl_server = new QLabel(tr("Server:"));
cbx_servers = new QComboBox();
refresh_combobox();
hbox_lbl_combo->addWidget(lbl_server);
hbox_lbl_combo->addWidget(cbx_servers);
QHBoxLayout* hbox_buttons = new QHBoxLayout();
QPushButton* btn_add_server = new QPushButton(tr("Add"));
QPushButton* btn_del_server = new QPushButton(tr("Del"));
hbox_buttons->addStretch();
hbox_buttons->addWidget(btn_add_server);
hbox_buttons->addWidget(btn_del_server);
vbox_server->addLayout(hbox_lbl_combo);
vbox_server->addLayout(hbox_buttons);
grp_server->setLayout(vbox_server);
vbox_global->addWidget(grp_server);
QGroupBox* grp_buttons = new QGroupBox(tr("Account:"));
QVBoxLayout* vbox_buttons = new QVBoxLayout();
QPushButton* btn_create = new QPushButton(tr("Create Account"));
QPushButton* btn_edit = new QPushButton(tr("Edit Account"));
QPushButton* btn_test = new QPushButton(tr("Test Account"));
QLabel* label_npid = new QLabel();
const auto update_npid_label = [label_npid]()
{
const std::string npid = g_cfg_rpcn.get_npid();
label_npid->setText(tr("Current ID: %0").arg(npid.empty() ? "-" : QString::fromStdString(npid)));
};
update_npid_label();
vbox_buttons->addWidget(label_npid);
vbox_buttons->addSpacing(10);
vbox_buttons->addWidget(btn_create);
vbox_buttons->addSpacing(10);
vbox_buttons->addWidget(btn_edit);
vbox_buttons->addSpacing(10);
vbox_buttons->addWidget(btn_test);
vbox_buttons->addSpacing(10);
grp_buttons->setLayout(vbox_buttons);
vbox_global->addWidget(grp_buttons);
setLayout(vbox_global);
connect(cbx_servers, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int index)
{
if (index < 0)
return;
QVariant host = cbx_servers->itemData(index);
if (!host.isValid() || !host.canConvert<QString>())
return;
g_cfg_rpcn.set_host(host.toString().toStdString());
g_cfg_rpcn.save();
});
connect(btn_add_server, &QAbstractButton::clicked, this, [this]()
{
rpcn_add_server_dialog dlg(this);
dlg.exec();
const auto& new_server = dlg.get_new_server();
if (new_server)
{
if (!g_cfg_rpcn.add_host(new_server->first, new_server->second))
{
QMessageBox::critical(this, tr("Existing Server"), tr("You already have a server with this description & hostname in the list."), QMessageBox::Ok);
return;
}
g_cfg_rpcn.save();
refresh_combobox();
}
});
connect(btn_del_server, &QAbstractButton::clicked, this, [this]()
{
const int index = cbx_servers->currentIndex();
if (index < 0)
return;
const std::string desc = cbx_servers->itemText(index).toStdString();
const std::string host = cbx_servers->itemData(index).toString().toStdString();
ensure(g_cfg_rpcn.del_host(desc, host));
g_cfg_rpcn.save();
refresh_combobox();
});
connect(btn_create, &QAbstractButton::clicked, this, [this, update_npid_label]()
{
rpcn_ask_username_dialog dlg_username(this, tr("Please enter your username.\n\n"
"Note that these restrictions apply:\n"
"- Username must be between 3 and 16 characters\n"
"- Username can only contain a-z A-Z 0-9 '-' '_'\n"
"- Username is case sensitive\n"));
dlg_username.exec();
const auto& username = dlg_username.get_username();
if (!username)
return;
rpcn_ask_password_dialog dlg_password(this, tr("Please choose your password:\n\n"));
dlg_password.exec();
const auto& password = dlg_password.get_password();
if (!password)
return;
rpcn_ask_email_dialog dlg_email(this, tr("An email address is required, please note:\n"
"- A valid email is needed to receive the token that validates your account.\n"
"- Your email won't be used for anything beyond sending you this token or the password reset token.\n\n"));
dlg_email.exec();
const auto& email = dlg_email.get_email();
if (!email)
return;
if (QMessageBox::question(this, tr("RPCN: Account Creation"), tr("You are about to create an account with:\n-Username:%0\n-Email:%1\n\nIs this correct?").arg(QString::fromStdString(*username)).arg(QString::fromStdString(*email))) != QMessageBox::Yes)
return;
{
const auto rpcn = rpcn::rpcn_client::get_instance();
const auto avatar_url = "https://rpcs3.net/cdn/netplay/DefaultAvatar.png";
if (auto result = rpcn->wait_for_connection(); result != rpcn::rpcn_state::failure_no_failure)
{
const QString error_message = tr("Failed to connect to RPCN server:\n%0").arg(QString::fromStdString(rpcn::rpcn_state_to_string(result)));
QMessageBox::critical(this, tr("Error Connecting"), error_message, QMessageBox::Ok);
return;
}
if (auto error = rpcn->create_user(*username, *password, *username, avatar_url, *email); error != rpcn::ErrorType::NoError)
{
QString error_message;
switch (error)
{
case rpcn::ErrorType::CreationExistingUsername: error_message = tr("An account with that username already exists!"); break;
case rpcn::ErrorType::CreationBannedEmailProvider: error_message = tr("This email provider is banned!"); break;
case rpcn::ErrorType::CreationExistingEmail: error_message = tr("An account with that email already exists!"); break;
case rpcn::ErrorType::CreationError: error_message = tr("Unknown creation error!"); break;
default: error_message = tr("Unknown error"); break;
}
QMessageBox::critical(this, tr("Error Creating Account!"), tr("Failed to create the account:\n%0").arg(error_message), QMessageBox::Ok);
return;
}
}
g_cfg_rpcn.set_npid(*username);
g_cfg_rpcn.set_password(*password);
g_cfg_rpcn.save();
rpcn_ask_token_dialog token_dlg(this, tr("Your account has been created successfully!\n"
"Your account authentification was saved.\n"
"Now all you need is to enter the token that was sent to your email.\n"
"You can skip this step by leaving it empty and entering it later in the Edit Account section too.\n"));
token_dlg.exec();
const auto& token = token_dlg.get_token();
if (!token)
return;
g_cfg_rpcn.set_token(*token);
g_cfg_rpcn.save();
update_npid_label();
});
connect(btn_edit, &QAbstractButton::clicked, this, [this, update_npid_label]()
{
rpcn_account_edit_dialog dlg_edit(this);
dlg_edit.exec();
update_npid_label();
});
connect(btn_test, &QAbstractButton::clicked, this, [this]()
{
auto rpcn = rpcn::rpcn_client::get_instance();
if (auto res = rpcn->wait_for_connection(); res != rpcn::rpcn_state::failure_no_failure)
{
const QString error_msg = tr("Failed to connect to RPCN:\n%0").arg(QString::fromStdString(rpcn::rpcn_state_to_string(res)));
QMessageBox::warning(this, tr("Error connecting to RPCN!"), error_msg, QMessageBox::Ok);
return;
}
if (auto res = rpcn->wait_for_authentified(); res != rpcn::rpcn_state::failure_no_failure)
{
const QString error_msg = tr("Failed to authentify to RPCN:\n%0").arg(QString::fromStdString(rpcn::rpcn_state_to_string(res)));
QMessageBox::warning(this, tr("Error authentifying to RPCN!"), error_msg, QMessageBox::Ok);
return;
}
QMessageBox::information(this, tr("RPCN Account Valid!"), tr("Your account is valid!"), QMessageBox::Ok);
});
}
void rpcn_account_dialog::refresh_combobox()
{
g_cfg_rpcn.load();
const auto vec_hosts = g_cfg_rpcn.get_hosts();
const auto cur_host = g_cfg_rpcn.get_host();
int i = 0, index = 0;
cbx_servers->clear();
for (const auto& [desc, host] : vec_hosts)
{
cbx_servers->addItem(QString::fromStdString(desc), QString::fromStdString(host));
if (cur_host == host)
index = i;
i++;
}
cbx_servers->setCurrentIndex(index);
}
rpcn_add_server_dialog::rpcn_add_server_dialog(QWidget* parent)
: QDialog(parent)
{
setWindowTitle(tr("RPCN: Add Server"));
setObjectName("rpcn_add_server_dialog");
setMinimumSize(QSize(400, 200));
QVBoxLayout* vbox_global = new QVBoxLayout();
QLabel* lbl_description = new QLabel(tr("Description:"));
QLineEdit* edt_description = new QLineEdit();
QLabel* lbl_host = new QLabel(tr("Host:"));
QLineEdit* edt_host = new QLineEdit();
QDialogButtonBox* btn_box = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
vbox_global->addWidget(lbl_description);
vbox_global->addWidget(edt_description);
vbox_global->addWidget(lbl_host);
vbox_global->addWidget(edt_host);
vbox_global->addWidget(btn_box);
setLayout(vbox_global);
connect(btn_box, &QDialogButtonBox::accepted, this, [this, edt_description, edt_host]()
{
const QString description = edt_description->text();
const QString host = edt_host->text();
if (description.isEmpty())
{
QMessageBox::critical(this, tr("Missing Description!"), tr("You must enter a description!"), QMessageBox::Ok);
return;
}
if (host.isEmpty())
{
QMessageBox::critical(this, tr("Missing Hostname!"), tr("You must enter a hostname for the server!"), QMessageBox::Ok);
return;
}
m_new_server = std::make_pair(description.toStdString(), host.toStdString());
QDialog::accept();
});
connect(btn_box, &QDialogButtonBox::rejected, this, &QDialog::reject);
}
const std::optional<std::pair<std::string, std::string>>& rpcn_add_server_dialog::get_new_server() const
{
return m_new_server;
}
rpcn_ask_username_dialog::rpcn_ask_username_dialog(QWidget* parent, const QString& description)
: QDialog(parent)
{
setWindowTitle(tr("RPCN: Username"));
setObjectName("rpcn_ask_username_dialog");
QVBoxLayout* vbox_global = new QVBoxLayout();
QLabel* lbl_username = new QLabel(description);
QGroupBox* grp_username = new QGroupBox(tr("Username:"));
QHBoxLayout* hbox_grp_username = new QHBoxLayout();
QLineEdit* edt_username = new QLineEdit(QString::fromStdString(g_cfg_rpcn.get_npid()));
edt_username->setMaxLength(16);
edt_username->setValidator(new QRegularExpressionValidator(QRegularExpression("^[a-zA-Z0-9_\\-]*$"), this));
hbox_grp_username->addWidget(edt_username);
grp_username->setLayout(hbox_grp_username);
QDialogButtonBox* btn_box = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
vbox_global->addWidget(lbl_username);
vbox_global->addWidget(grp_username);
vbox_global->addWidget(btn_box);
setLayout(vbox_global);
connect(btn_box, &QDialogButtonBox::accepted, this, [this, edt_username]()
{
const auto username = edt_username->text().toStdString();
if (username.empty())
{
QMessageBox::critical(this, tr("Missing Username!"), tr("You must enter a username!"), QMessageBox::Ok);
return;
}
if (!validate_rpcn_username(username))
{
QMessageBox::critical(this, tr("Invalid Username!"), tr("Please enter a valid username!"), QMessageBox::Ok);
}
m_username = username;
QDialog::accept();
});
connect(btn_box, &QDialogButtonBox::rejected, this, &QDialog::reject);
}
const std::optional<std::string>& rpcn_ask_username_dialog::get_username() const
{
return m_username;
}
rpcn_ask_password_dialog::rpcn_ask_password_dialog(QWidget* parent, const QString& description)
: QDialog(parent)
{
setWindowTitle(tr("RPCN: Password"));
setObjectName("rpcn_ask_password_dialog");
QVBoxLayout* vbox_global = new QVBoxLayout();
QLabel* lbl_description = new QLabel(description);
QGroupBox* gbox_password = new QGroupBox();
QVBoxLayout* vbox_gbox = new QVBoxLayout();
QLabel* lbl_pass1 = new QLabel(tr("Enter your password:"));
QLineEdit* m_edit_pass1 = new QLineEdit();
m_edit_pass1->setEchoMode(QLineEdit::Password);
QLabel* lbl_pass2 = new QLabel(tr("Enter your password a second time:"));
QLineEdit* m_edit_pass2 = new QLineEdit();
m_edit_pass2->setEchoMode(QLineEdit::Password);
vbox_gbox->addWidget(lbl_pass1);
vbox_gbox->addWidget(m_edit_pass1);
vbox_gbox->addWidget(lbl_pass2);
vbox_gbox->addWidget(m_edit_pass2);
gbox_password->setLayout(vbox_gbox);
QDialogButtonBox* btn_box = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
vbox_global->addWidget(lbl_description);
vbox_global->addWidget(gbox_password);
vbox_global->addWidget(btn_box);
setLayout(vbox_global);
connect(btn_box, &QDialogButtonBox::accepted, this, [this, m_edit_pass1, m_edit_pass2]()
{
if (m_edit_pass1->text() != m_edit_pass2->text())
{
QMessageBox::critical(this, tr("Wrong Input"), tr("The two passwords you entered don't match!"), QMessageBox::Ok);
return;
}
if (m_edit_pass1->text().isEmpty())
{
QMessageBox::critical(this, tr("Missing Password"), tr("You need to enter a password!"), QMessageBox::Ok);
return;
}
m_password = derive_password(m_edit_pass1->text().toStdString());
QDialog::accept();
});
connect(btn_box, &QDialogButtonBox::rejected, this, &QDialog::reject);
}
const std::optional<std::string>& rpcn_ask_password_dialog::get_password() const
{
return m_password;
}
rpcn_ask_email_dialog::rpcn_ask_email_dialog(QWidget* parent, const QString& description)
: QDialog(parent)
{
setWindowTitle(tr("RPCN: Email"));
setObjectName("rpcn_ask_email_dialog");
QVBoxLayout* vbox_global = new QVBoxLayout();
QLabel* lbl_emailinfo = new QLabel(description);
QGroupBox* gbox_password = new QGroupBox();
QVBoxLayout* vbox_gbox = new QVBoxLayout();
QLabel* lbl_pass1 = new QLabel(tr("Enter your email:"));
QLineEdit* m_edit_pass1 = new QLineEdit();
QLabel* lbl_pass2 = new QLabel(tr("Enter your email a second time:"));
QLineEdit* m_edit_pass2 = new QLineEdit();
vbox_gbox->addWidget(lbl_pass1);
vbox_gbox->addWidget(m_edit_pass1);
vbox_gbox->addWidget(lbl_pass2);
vbox_gbox->addWidget(m_edit_pass2);
gbox_password->setLayout(vbox_gbox);
QDialogButtonBox* btn_box = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
vbox_global->addWidget(lbl_emailinfo);
vbox_global->addWidget(gbox_password);
vbox_global->addWidget(btn_box);
setLayout(vbox_global);
connect(btn_box, &QDialogButtonBox::accepted, this, [this, m_edit_pass1, m_edit_pass2]()
{
if (m_edit_pass1->text() != m_edit_pass2->text())
{
QMessageBox::critical(this, tr("Wrong Input"), tr("The two emails you entered don't match!"), QMessageBox::Ok);
return;
}
if (m_edit_pass1->text().isEmpty())
{
QMessageBox::critical(this, tr("Missing Email"), tr("You need to enter an email!"), QMessageBox::Ok);
return;
}
std::string email = m_edit_pass1->text().toStdString();
if (!validate_email(email))
{
QMessageBox::critical(this, tr("Invalid Email"), tr("You need to enter a valid email!"), QMessageBox::Ok);
return;
}
m_email = std::move(email);
QDialog::accept();
});
connect(btn_box, &QDialogButtonBox::rejected, this, &QDialog::reject);
}
const std::optional<std::string>& rpcn_ask_email_dialog::get_email() const
{
return m_email;
}
rpcn_ask_token_dialog::rpcn_ask_token_dialog(QWidget* parent, const QString& description)
: QDialog(parent)
{
setWindowTitle(tr("RPCN: Username"));
setObjectName("rpcn_ask_token_dialog");
QVBoxLayout* vbox_global = new QVBoxLayout();
QLabel* lbl_token = new QLabel(description);
QGroupBox* grp_token = new QGroupBox(tr("Token:"));
QHBoxLayout* hbox_grp_token = new QHBoxLayout();
QLineEdit* edt_token = new QLineEdit();
edt_token->setMaxLength(16);
hbox_grp_token->addWidget(edt_token);
grp_token->setLayout(hbox_grp_token);
QDialogButtonBox* btn_box = new QDialogButtonBox(QDialogButtonBox::Ok);
vbox_global->addWidget(lbl_token);
vbox_global->addWidget(grp_token);
vbox_global->addWidget(btn_box);
setLayout(vbox_global);
connect(btn_box, &QDialogButtonBox::accepted, this, [this, edt_token]()
{
std::string token = edt_token->text().toStdString();
if (!token.empty())
{
if (!validate_token(token))
{
QMessageBox::critical(this, tr("Invalid Token"), tr("The token appears to be invalid:\n"
"-Token should be 16 characters long\n"
"-Token should only contain 0-9 and A-F"),
QMessageBox::Ok);
return;
}
m_token = std::move(token);
}
QDialog::accept();
return;
});
}
const std::optional<std::string>& rpcn_ask_token_dialog::get_token() const
{
return m_token;
}
rpcn_account_edit_dialog::rpcn_account_edit_dialog(QWidget* parent)
: QDialog(parent)
{
setWindowTitle(tr("RPCN: Edit Account"));
setObjectName("rpcn_account_edit_dialog");
setMinimumSize(QSize(400, 200));
QVBoxLayout* vbox_global = new QVBoxLayout();
QHBoxLayout* hbox_labels_and_edits = new QHBoxLayout();
QVBoxLayout* vbox_labels = new QVBoxLayout();
QVBoxLayout* vbox_edits = new QVBoxLayout();
QHBoxLayout* hbox_buttons = new QHBoxLayout();
QLabel* lbl_username = new QLabel(tr("Username:"));
m_edit_username = new QLineEdit();
m_edit_username->setMaxLength(16);
m_edit_username->setValidator(new QRegularExpressionValidator(QRegularExpression("^[a-zA-Z0-9_\\-]*$"), this));
QLabel* lbl_pass = new QLabel(tr("Password:"));
QPushButton* btn_chg_pass = new QPushButton(tr("Set Password"));
QLabel* lbl_token = new QLabel(tr("Token:"));
m_edit_token = new QLineEdit();
m_edit_token->setMaxLength(16);
QPushButton* btn_resendtoken = new QPushButton(tr("Resend Token"), this);
QPushButton* btn_change_password = new QPushButton(tr("Change Password"), this);
QPushButton* btn_save = new QPushButton(tr("Save"), this);
vbox_labels->addWidget(lbl_username);
vbox_labels->addWidget(lbl_pass);
vbox_labels->addWidget(lbl_token);
vbox_edits->addWidget(m_edit_username);
vbox_edits->addWidget(btn_chg_pass);
vbox_edits->addWidget(m_edit_token);
hbox_buttons->addWidget(btn_resendtoken);
hbox_buttons->addWidget(btn_change_password);
hbox_buttons->addStretch();
hbox_buttons->addWidget(btn_save);
hbox_labels_and_edits->addLayout(vbox_labels);
hbox_labels_and_edits->addLayout(vbox_edits);
vbox_global->addLayout(hbox_labels_and_edits);
vbox_global->addLayout(hbox_buttons);
setLayout(vbox_global);
connect(btn_chg_pass, &QAbstractButton::clicked, this, [this]()
{
rpcn_ask_password_dialog ask_pass(this, tr("Please enter your password:"));
ask_pass.exec();
const auto& password = ask_pass.get_password();
if (!password)
return;
g_cfg_rpcn.set_password(*password);
g_cfg_rpcn.save();
QMessageBox::information(this, tr("RPCN Password Saved"), tr("Your password was saved successfully!"), QMessageBox::Ok);
});
connect(btn_save, &QAbstractButton::clicked, this, [this]()
{
if (save_config())
close();
});
connect(btn_resendtoken, &QAbstractButton::clicked, this, &rpcn_account_edit_dialog::resend_token);
connect(btn_change_password, &QAbstractButton::clicked, this, &rpcn_account_edit_dialog::change_password);
g_cfg_rpcn.load();
m_edit_username->setText(QString::fromStdString(g_cfg_rpcn.get_npid()));
m_edit_token->setText(QString::fromStdString(g_cfg_rpcn.get_token()));
}
bool rpcn_account_edit_dialog::save_config()
{
const std::string username = m_edit_username->text().toStdString();
const std::string token = m_edit_token->text().toStdString();
if (username.empty() || g_cfg_rpcn.get_password().empty())
{
QMessageBox::critical(this, tr("Missing Input"), tr("You need to enter a username and a password!"), QMessageBox::Ok);
return false;
}
if (!validate_rpcn_username(username))
{
QMessageBox::critical(this, tr("Invalid Username"), tr("Username must be between 3 and 16 characters and can only contain '-', '_' or alphanumeric characters."), QMessageBox::Ok);
return false;
}
if (!token.empty() && !validate_token(token))
{
QMessageBox::critical(this, tr("Invalid Token"), tr("The token you have received should be 16 characters long and contain only 0-9 A-F."), QMessageBox::Ok);
return false;
}
g_cfg_rpcn.set_npid(username);
g_cfg_rpcn.set_token(token);
g_cfg_rpcn.save();
return true;
}
void rpcn_account_edit_dialog::resend_token()
{
if (!save_config())
return;
const auto rpcn = rpcn::rpcn_client::get_instance();
const std::string npid = g_cfg_rpcn.get_npid();
const std::string password = g_cfg_rpcn.get_password();
if (auto result = rpcn->wait_for_connection(); result != rpcn::rpcn_state::failure_no_failure)
{
const QString error_message = tr("Failed to connect to RPCN server:\n%0").arg(QString::fromStdString(rpcn::rpcn_state_to_string(result)));
QMessageBox::critical(this, tr("Error Connecting!"), error_message, QMessageBox::Ok);
return;
}
if (auto error = rpcn->resend_token(npid, password); error != rpcn::ErrorType::NoError)
{
QString error_message;
switch (error)
{
case rpcn::ErrorType::Invalid: error_message = tr("The server has no email verification and doesn't need a token!"); break;
case rpcn::ErrorType::DbFail: error_message = tr("A database related error happened on the server!"); break;
case rpcn::ErrorType::TooSoon: error_message = tr("You can only ask for a token mail once every 24 hours!"); break;
case rpcn::ErrorType::EmailFail: error_message = tr("The mail couldn't be sent successfully!"); break;
case rpcn::ErrorType::LoginError: error_message = tr("The username/password pair is invalid!"); break;
default: error_message = tr("Unknown error"); break;
}
QMessageBox::critical(this, tr("Error Sending Token!"), tr("Failed to send the token:\n%0").arg(error_message), QMessageBox::Ok);
return;
}
QMessageBox::information(this, tr("Token Sent!"), tr("Your token was successfully resent to the email associated with your account!"), QMessageBox::Ok);
}
void rpcn_account_edit_dialog::change_password()
{
rpcn_ask_username_dialog dlg_username(this, tr("Please confirm your username:"));
dlg_username.exec();
const auto& username = dlg_username.get_username();
if (!username)
return;
switch (QMessageBox::question(this, tr("RPCN: Change Password"), tr("Do you already have a reset password token?\n"
"Note that the reset password token is different from the email verification token.")))
{
case QMessageBox::No:
{
rpcn_ask_email_dialog dlg_email(this, tr("Please enter the email you used to create the account:"));
dlg_email.exec();
const auto& email = dlg_email.get_email();
if (!email)
return;
{
const auto rpcn = rpcn::rpcn_client::get_instance();
if (auto result = rpcn->wait_for_connection(); result != rpcn::rpcn_state::failure_no_failure)
{
const QString error_message = tr("Failed to connect to RPCN server:\n%0").arg(QString::fromStdString(rpcn::rpcn_state_to_string(result)));
QMessageBox::critical(this, tr("Error Connecting!"), error_message, QMessageBox::Ok);
return;
}
if (auto error = rpcn->send_reset_token(*username, *email); error != rpcn::ErrorType::NoError)
{
QString error_message;
switch (error)
{
case rpcn::ErrorType::Invalid: error_message = tr("The server has no email verification and doesn't support password changes!"); break;
case rpcn::ErrorType::DbFail: error_message = tr("A database related error happened on the server!"); break;
case rpcn::ErrorType::TooSoon: error_message = tr("You can only ask for a reset password token once every 24 hours!"); break;
case rpcn::ErrorType::EmailFail: error_message = tr("The mail couldn't be sent successfully!"); break;
case rpcn::ErrorType::LoginError: error_message = tr("The username/email pair is invalid!"); break;
default: error_message = tr("Unknown error!"); break;
}
QMessageBox::critical(this, tr("Error Sending Password Reset Token!"), tr("Failed to send the password reset token:\n%0").arg(error_message), QMessageBox::Ok);
return;
}
QMessageBox::information(this, tr("Password Reset Token Sent!"), tr("The reset password token has successfully been sent!"), QMessageBox::Ok);
}
[[fallthrough]];
}
case QMessageBox::Yes:
{
rpcn_ask_token_dialog dlg_token(this, tr("Please enter the password reset token you received:"));
dlg_token.exec();
const auto& token = dlg_token.get_token();
if (!token)
return;
rpcn_ask_password_dialog dlg_password(this, tr("Please enter your new password:"));
dlg_password.exec();
const auto& password = dlg_password.get_password();
if (!password)
return;
{
const auto rpcn = rpcn::rpcn_client::get_instance();
if (auto result = rpcn->wait_for_connection(); result != rpcn::rpcn_state::failure_no_failure)
{
const QString error_message = tr("Failed to connect to RPCN server:\n%0").arg(QString::fromStdString(rpcn::rpcn_state_to_string(result)));
QMessageBox::critical(this, tr("Error Connecting!"), error_message, QMessageBox::Ok);
return;
}
if (auto error = rpcn->reset_password(*username, *token, *password); error != rpcn::ErrorType::NoError)
{
QString error_message;
switch (error)
{
case rpcn::ErrorType::Invalid: error_message = tr("The server has no email verification and doesn't support password changes!"); break;
case rpcn::ErrorType::DbFail: error_message = tr("A database related error happened on the server!"); break;
case rpcn::ErrorType::TooSoon: error_message = tr("You can only ask for a reset password token once every 24 hours!"); break;
case rpcn::ErrorType::EmailFail: error_message = tr("The mail couldn't be sent successfully!"); break;
case rpcn::ErrorType::LoginError: error_message = tr("The username/token pair is invalid!"); break;
default: error_message = tr("Unknown error"); break;
}
QMessageBox::critical(this, tr("Error Sending Password Reset Token"), tr("Failed to change the password:\n%0").arg(error_message), QMessageBox::Ok);
return;
}
QMessageBox::information(this, tr("Password Successfully Changed!"), tr("Your password has been successfully changed!"), QMessageBox::Ok);
}
break;
}
default:
return;
}
}
void friend_callback(void* param, rpcn::NotificationType ntype, const std::string& username, bool status)
{
auto* dlg = static_cast<rpcn_friends_dialog*>(param);
dlg->callback_handler(ntype, username, status);
}
// Avoid including np_handler.h
namespace np
{
struct player_history
{
u64 timestamp{};
std::set<std::string> communication_ids;
std::string description;
};
std::map<std::string, player_history> load_players_history();
}
rpcn_friends_dialog::rpcn_friends_dialog(QWidget* parent)
: QDialog(parent)
{
const qreal pixel_ratio = devicePixelRatioF();
// Create colored circle pixmaps
gui::utils::circle_pixmap online_pixmap(QColorConstants::Svg::green, pixel_ratio * 2);
gui::utils::circle_pixmap offline_pixmap(QColorConstants::Svg::red, pixel_ratio * 2);
gui::utils::circle_pixmap blocked_pixmap(QColorConstants::Svg::red, pixel_ratio * 2);
gui::utils::circle_pixmap req_rcvd_pixmap(QColorConstants::Svg::yellow, pixel_ratio * 2);
gui::utils::circle_pixmap req_sent_pixmap(QColorConstants::Svg::orange, pixel_ratio * 2);
// Reset device pixel ratios for further painting
online_pixmap.setDevicePixelRatio(1.0);
offline_pixmap.setDevicePixelRatio(1.0);
blocked_pixmap.setDevicePixelRatio(1.0);
req_rcvd_pixmap.setDevicePixelRatio(1.0);
req_sent_pixmap.setDevicePixelRatio(1.0);
// The width and height are identical for all pixmaps
const int w = online_pixmap.width();
const int h = online_pixmap.height();
const QPen pen1(QBrush(Qt::black), w * 0.1, Qt::SolidLine, Qt::RoundCap, Qt::MiterJoin);
const QPen pen2(QBrush(Qt::black), w * 0.15, Qt::SolidLine, Qt::RoundCap, Qt::MiterJoin);
QPainter painter;
painter.setRenderHint(QPainter::Antialiasing);
// Render a bar into the offline pixmap
{
painter.begin(&offline_pixmap);
painter.setPen(pen2);
painter.drawLine(QPointF(w * 0.25, h * 0.5), QPointF(w * 0.75, h * 0.5));
painter.end();
}
// Render a cross into the blocked pixmap
{
painter.begin(&blocked_pixmap);
painter.setPen(pen1);
painter.drawLine(QPointF(w * 0.25, h * 0.25), QPointF(w * 0.75, h * 0.75));
painter.drawLine(QPointF(w * 0.25, h * 0.75), QPointF(w * 0.75, h * 0.25));
painter.end();
}
// Render a downward arrow into the request received pixmap
{
painter.begin(&req_rcvd_pixmap);
painter.setPen(pen1);
painter.drawLine(QPointF(w * 0.5, h * 0.25), QPointF(w * 0.5, h * 0.75));
painter.drawLines({ QLineF(w * 0.5, h * 0.75, w * 0.25, h * 0.5), QLineF(w * 0.5, h * 0.75, w * 0.75, h * 0.5) });
painter.end();
}
// Render an upward arrow into the request sent pixmap
{
painter.begin(&req_sent_pixmap);
painter.setPen(pen1);
painter.drawLine(QPointF(w * 0.5, h * 0.25), QPointF(w * 0.5, h * 0.75));
painter.drawLines({ QLineF(w * 0.5, h * 0.25, w * 0.25, h * 0.5), QLineF(w * 0.5, h * 0.25, w * 0.75, h * 0.5) });
painter.end();
}
m_icon_online = online_pixmap;
m_icon_offline = offline_pixmap;
m_icon_blocked = blocked_pixmap;
m_icon_request_received = req_rcvd_pixmap;
m_icon_request_sent = req_sent_pixmap;
const auto set_title = [this]()
{
if (const std::string npid = g_cfg_rpcn.get_npid(); !npid.empty())
{
if (m_rpcn && m_rpcn->is_connected() && m_rpcn->is_authentified())
{
setWindowTitle(tr("RPCN: Friends - Logged in as %0").arg(QString::fromStdString(npid)));
return;
}
setWindowTitle(tr("RPCN: Friends - %0 (Not logged in)").arg(QString::fromStdString(npid)));
return;
}
setWindowTitle(tr("RPCN: Friends"));
};
set_title();
setObjectName("rpcn_friends_dialog");
setMinimumSize(QSize(400, 100));
QVBoxLayout* vbox_global = new QVBoxLayout();
QHBoxLayout* hbox_groupboxes = new QHBoxLayout();
QGroupBox* grp_list_friends = new QGroupBox(tr("Friends"));
QVBoxLayout* vbox_lst_friends = new QVBoxLayout();
m_lst_friends = new QListWidget(this);
m_lst_friends->setContextMenuPolicy(Qt::CustomContextMenu);
vbox_lst_friends->addWidget(m_lst_friends);
QPushButton* btn_addfriend = new QPushButton(tr("Add Friend"));
vbox_lst_friends->addWidget(btn_addfriend);
grp_list_friends->setLayout(vbox_lst_friends);
hbox_groupboxes->addWidget(grp_list_friends);
QGroupBox* grp_list_requests = new QGroupBox(tr("Friend Requests"));
QVBoxLayout* vbox_lst_requests = new QVBoxLayout();
m_lst_requests = new QListWidget(this);
m_lst_requests->setContextMenuPolicy(Qt::CustomContextMenu);
vbox_lst_requests->addWidget(m_lst_requests);
QHBoxLayout* hbox_request_btns = new QHBoxLayout();
vbox_lst_requests->addLayout(hbox_request_btns);
grp_list_requests->setLayout(vbox_lst_requests);
hbox_groupboxes->addWidget(grp_list_requests);
QGroupBox* grp_list_blocks = new QGroupBox(tr("Blocked Users"));
QVBoxLayout* vbox_lst_blocks = new QVBoxLayout();
m_lst_blocks = new QListWidget(this);
vbox_lst_blocks->addWidget(m_lst_blocks);
grp_list_blocks->setLayout(vbox_lst_blocks);
hbox_groupboxes->addWidget(grp_list_blocks);
QGroupBox* grp_list_history = new QGroupBox(tr("Recent Players"));
QVBoxLayout* vbox_lst_history = new QVBoxLayout();
m_lst_history = new QListWidget(this);
m_lst_history->setContextMenuPolicy(Qt::CustomContextMenu);
vbox_lst_history->addWidget(m_lst_history);
grp_list_history->setLayout(vbox_lst_history);
hbox_groupboxes->addWidget(grp_list_history);
vbox_global->addLayout(hbox_groupboxes);
setLayout(vbox_global);
// Tries to connect to RPCN
m_rpcn = rpcn::rpcn_client::get_instance();
if (auto res = m_rpcn->wait_for_connection(); res != rpcn::rpcn_state::failure_no_failure)
{
const QString error_msg = tr("Failed to connect to RPCN:\n%0").arg(QString::fromStdString(rpcn::rpcn_state_to_string(res)));
QMessageBox::warning(parent, tr("Error connecting to RPCN!"), error_msg, QMessageBox::Ok);
return;
}
if (auto res = m_rpcn->wait_for_authentified(); res != rpcn::rpcn_state::failure_no_failure)
{
const QString error_msg = tr("Failed to authentify to RPCN:\n%0").arg(QString::fromStdString(rpcn::rpcn_state_to_string(res)));
QMessageBox::warning(parent, tr("Error authentifying to RPCN!"), error_msg, QMessageBox::Ok);
return;
}
set_title();
// Get friends, setup callback and setup comboboxes
rpcn::friend_data data;
m_rpcn->get_friends_and_register_cb(data, friend_callback, this);
for (const auto& [username, data] : data.friends)
{
add_update_list(m_lst_friends, QString::fromStdString(username), data.online ? m_icon_online : m_icon_offline, data.online);
}
for (const auto& fr_req : data.requests_sent)
{
add_update_list(m_lst_requests, QString::fromStdString(fr_req), m_icon_request_sent, QVariant(false));
}
for (const auto& fr_req : data.requests_received)
{
add_update_list(m_lst_requests, QString::fromStdString(fr_req), m_icon_request_received, QVariant(true));
}
for (const auto& blck : data.blocked)
{
add_update_list(m_lst_blocks, QString::fromStdString(blck), m_icon_blocked, QVariant(false));
}
auto history = np::load_players_history();
std::map<u64, std::pair<std::string, std::string>, std::greater<u64>> sorted_history;
for (auto& [username, user_info] : history)
{
if (!data.friends.contains(username) && !data.requests_sent.contains(username) && !data.requests_received.contains(username))
sorted_history.insert(std::make_pair(user_info.timestamp, std::make_pair(username, std::move(user_info.description))));
}
for (const auto& [_, username_and_description] : sorted_history)
{
const auto& [username, description] = username_and_description;
QListWidgetItem* item = new QListWidgetItem(QString::fromStdString(username));
if (!description.empty())
item->setToolTip(QString::fromStdString(description));
m_lst_history->addItem(item);
}
connect(this, &rpcn_friends_dialog::signal_add_update_friend, this, &rpcn_friends_dialog::add_update_friend);
connect(this, &rpcn_friends_dialog::signal_remove_friend, this, &rpcn_friends_dialog::remove_friend);
connect(this, &rpcn_friends_dialog::signal_add_query, this, &rpcn_friends_dialog::add_query);
connect(m_lst_friends, &QListWidget::customContextMenuRequested, this, [this](const QPoint& pos)
{
if (!m_lst_friends->itemAt(pos) || m_lst_friends->selectedItems().count() != 1)
{
return;
}
QListWidgetItem* selected_item = m_lst_friends->selectedItems().first();
std::string str_sel_friend = selected_item->text().toStdString();
QMenu* context_menu = new QMenu();
QAction* remove_friend_action = context_menu->addAction(tr("&Remove Friend"));
connect(remove_friend_action, &QAction::triggered, this, [this, str_sel_friend]()
{
if (!m_rpcn->remove_friend(str_sel_friend))
{
QMessageBox::critical(this, tr("Error removing a friend!"), tr("An error occurred while trying to remove a friend!"), QMessageBox::Ok);
}
else
{
QMessageBox::information(this, tr("Friend removed!"), tr("You've successfully removed a friend!"), QMessageBox::Ok);
}
});
context_menu->exec(m_lst_friends->viewport()->mapToGlobal(pos));
context_menu->deleteLater();
});
connect(m_lst_requests, &QListWidget::customContextMenuRequested, this, [this](const QPoint& pos)
{
if (!m_lst_requests->itemAt(pos) || m_lst_requests->selectedItems().count() != 1)
{
return;
}
QListWidgetItem* selected_item = m_lst_requests->selectedItems().first();
std::string str_sel_friend = selected_item->text().toStdString();
QMenu* context_menu = new QMenu();
// Presents different context based on role
if (selected_item->data(Qt::UserRole) == false)
{
QAction* cancel_friend_request = context_menu->addAction(tr("&Cancel Request"));
connect(cancel_friend_request, &QAction::triggered, this, [this, str_sel_friend]()
{
if (!m_rpcn->remove_friend(str_sel_friend))
{
QMessageBox::critical(this, tr("Error cancelling friend request!"), tr("An error occurred while trying to cancel friend request!"), QMessageBox::Ok);
}
else
{
QMessageBox::information(this, tr("Friend request cancelled!"), tr("You've successfully cancelled the friend request!"), QMessageBox::Ok);
}
});
context_menu->exec(m_lst_requests->viewport()->mapToGlobal(pos));
context_menu->deleteLater();
return;
}
QAction* accept_request_action = context_menu->addAction(tr("&Accept Request"));
QAction* reject_friend_request = context_menu->addAction(tr("&Reject Request"));
connect(accept_request_action, &QAction::triggered, this, [this, str_sel_friend]()
{
if (!m_rpcn->add_friend(str_sel_friend))
{
QMessageBox::critical(this, tr("Error adding a friend!"), tr("An error occurred while trying to add a friend!"), QMessageBox::Ok);
}
else
{
QMessageBox::information(this, tr("Friend added!"), tr("You've successfully added a friend!"), QMessageBox::Ok);
}
});
connect(reject_friend_request, &QAction::triggered, this, [this, str_sel_friend]()
{
if (!m_rpcn->remove_friend(str_sel_friend))
{
QMessageBox::critical(this, tr("Error rejecting friend request!"), tr("An error occurred while trying to reject the friend request!"), QMessageBox::Ok);
}
else
{
QMessageBox::information(this, tr("Friend request cancelled!"), tr("You've successfully rejected the friend request!"), QMessageBox::Ok);
}
});
context_menu->exec(m_lst_requests->viewport()->mapToGlobal(pos));
context_menu->deleteLater();
});
connect(m_lst_history, &QListWidget::customContextMenuRequested, this, [this](const QPoint& pos)
{
if (!m_lst_history->itemAt(pos) || m_lst_history->selectedItems().count() != 1)
{
return;
}
QListWidgetItem* selected_item = m_lst_history->selectedItems().first();
std::string str_sel_friend = selected_item->text().toStdString();
QMenu* context_menu = new QMenu();
QAction* send_friend_request_action = context_menu->addAction(tr("&Send Friend Request"));
connect(send_friend_request_action, &QAction::triggered, this, [this, str_sel_friend]()
{
if (!m_rpcn->add_friend(str_sel_friend))
{
QMessageBox::critical(this, tr("Error sending a friend request!"), tr("An error occurred while trying to send a friend request!"), QMessageBox::Ok);
return;
}
QString qstr_friend = QString::fromStdString(str_sel_friend);
add_update_list(m_lst_requests, qstr_friend, m_icon_request_sent, QVariant(false));
remove_list(m_lst_history, qstr_friend);
});
context_menu->exec(m_lst_history->viewport()->mapToGlobal(pos));
context_menu->deleteLater();
});
connect(btn_addfriend, &QAbstractButton::clicked, this, [this]()
{
std::string str_friend_username;
while (true)
{
bool ok = false;
QString friend_username = QInputDialog::getText(this, tr("Add a friend"), tr("Friend's username:"), QLineEdit::Normal, "", &ok);
if (!ok)
{
return;
}
str_friend_username = friend_username.toStdString();
if (validate_rpcn_username(str_friend_username))
{
break;
}
QMessageBox::critical(this, tr("Error validating username!"), tr("The username you entered is invalid!"), QMessageBox::Ok);
}
if (!m_rpcn->add_friend(str_friend_username))
{
QMessageBox::critical(this, tr("Error adding friend!"), tr("An error occurred while adding a friend!"), QMessageBox::Ok);
}
else
{
add_update_list(m_lst_requests, QString::fromStdString(str_friend_username), m_icon_request_sent, QVariant(false));
QMessageBox::information(this, tr("Friend added!"), tr("Friend was successfully added!"), QMessageBox::Ok);
}
});
m_rpcn_ok = true;
}
rpcn_friends_dialog::~rpcn_friends_dialog()
{
m_rpcn->remove_friend_cb(friend_callback, this);
}
bool rpcn_friends_dialog::is_ok() const
{
return m_rpcn_ok;
}
void rpcn_friends_dialog::add_update_list(QListWidget* list, const QString& name, const QIcon& icon, const QVariant& data)
{
QListWidgetItem* item = nullptr;
if (auto found = list->findItems(name, Qt::MatchExactly); !found.empty())
{
item = found[0];
item->setData(Qt::UserRole, data);
item->setIcon(icon);
}
else
{
item = new QListWidgetItem(name);
item->setIcon(icon);
item->setData(Qt::UserRole, data);
list->addItem(item);
}
}
void rpcn_friends_dialog::remove_list(QListWidget* list, const QString& name)
{
if (auto found = list->findItems(name, Qt::MatchExactly); !found.empty())
{
delete list->takeItem(list->row(found[0]));
}
}
void rpcn_friends_dialog::add_update_friend(const QString& name, bool status)
{
add_update_list(m_lst_friends, name, status ? m_icon_online : m_icon_offline, status);
remove_list(m_lst_requests, name);
}
void rpcn_friends_dialog::remove_friend(const QString& name)
{
remove_list(m_lst_friends, name);
remove_list(m_lst_requests, name);
}
void rpcn_friends_dialog::add_query(const QString& name)
{
add_update_list(m_lst_requests, name, m_icon_request_received, QVariant(true));
remove_list(m_lst_history, name);
}
void rpcn_friends_dialog::callback_handler(rpcn::NotificationType ntype, const std::string& username, bool status)
{
const QString qtr_username = QString::fromStdString(username);
switch (ntype)
{
case rpcn::NotificationType::FriendQuery: // Other user sent a friend request
{
Q_EMIT signal_add_query(qtr_username);
break;
}
case rpcn::NotificationType::FriendNew: // Add a friend to the friendlist(either accepted a friend request or friend accepted it)
{
Q_EMIT signal_add_update_friend(qtr_username, status);
break;
}
case rpcn::NotificationType::FriendLost: // Remove friend from the friendlist(user removed friend or friend removed friend)
{
Q_EMIT signal_remove_friend(qtr_username);
break;
}
case rpcn::NotificationType::FriendStatus: // Set status of friend to Offline or Online
{
Q_EMIT signal_add_update_friend(qtr_username, status);
break;
}
case rpcn::NotificationType::FriendPresenceChanged:
{
break;
}
default:
{
rpcn_settings_log.fatal("An unhandled notification type was received by the RPCN friends dialog callback!");
break;
}
}
}
| 46,555
|
C++
|
.cpp
| 1,099
| 38.657871
| 257
| 0.699659
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,082
|
rsx_debugger.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/rsx_debugger.cpp
|
#include "rsx_debugger.h"
#include "gui_settings.h"
#include "qt_utils.h"
#include "table_item_delegate.h"
#include "Emu/RSX/RSXThread.h"
#include "Emu/RSX/gcm_printing.h"
#include "util/asm.hpp"
#include <QHBoxLayout>
#include <QHeaderView>
#include <QFont>
#include <QFontDatabase>
#include <QPixmap>
#include <QPushButton>
#include <QFileDialog>
#include <QKeyEvent>
#include <QTimer>
#include <QMenu>
#include <QBuffer>
#include <span>
enum GCMEnumTypes
{
CELL_GCM_ENUM,
CELL_GCM_PRIMITIVE_ENUM,
};
constexpr auto qstr = QString::fromStdString;
LOG_CHANNEL(rsx_debugger, "RSX Debugger");
namespace utils
{
template <typename T, typename U>
[[nodiscard]] auto bless(const std::span<U>& span)
{
return std::span<T>(bless<T>(span.data()), sizeof(U) * span.size() / sizeof(T));
}
}
rsx_debugger::rsx_debugger(std::shared_ptr<gui_settings> gui_settings, QWidget* parent)
: QDialog(parent)
, m_gui_settings(std::move(gui_settings))
{
setWindowTitle(tr("RSX Debugger"));
setObjectName("rsx_debugger");
setAttribute(Qt::WA_DeleteOnClose);
setWindowFlags(Qt::Window);
// Fonts and Colors
QFont mono = QFontDatabase::systemFont(QFontDatabase::FixedFont);
mono.setPointSize(8);
QLabel l("000000000"); // hacky way to get the lineedit to resize properly
l.setFont(mono);
// Controls: Breaks
QPushButton* b_break_frame = new QPushButton(tr("Frame"));
QPushButton* b_break_text = new QPushButton(tr("Texture"));
QPushButton* b_break_draw = new QPushButton(tr("Draw"));
QPushButton* b_break_prim = new QPushButton(tr("Primitive"));
QPushButton* b_break_inst = new QPushButton(tr("Command"));
b_break_frame->setAutoDefault(false);
b_break_text->setAutoDefault(false);
b_break_draw->setAutoDefault(false);
b_break_prim->setAutoDefault(false);
b_break_inst->setAutoDefault(false);
QHBoxLayout* hbox_controls_breaks = new QHBoxLayout();
hbox_controls_breaks->addWidget(b_break_frame);
hbox_controls_breaks->addWidget(b_break_text);
hbox_controls_breaks->addWidget(b_break_draw);
hbox_controls_breaks->addWidget(b_break_prim);
hbox_controls_breaks->addWidget(b_break_inst);
QGroupBox* gb_controls_breaks = new QGroupBox(tr("Break on:"));
gb_controls_breaks->setLayout(hbox_controls_breaks);
// TODO: This feature is not yet implemented
b_break_frame->setEnabled(false);
b_break_text->setEnabled(false);
b_break_draw->setEnabled(false);
b_break_prim->setEnabled(false);
b_break_inst->setEnabled(false);
QHBoxLayout* hbox_controls = new QHBoxLayout();
hbox_controls->addWidget(gb_controls_breaks);
hbox_controls->addStretch(1);
m_tw_rsx = new QTabWidget();
// adds a tab containing a list to the tabwidget
const auto add_rsx_tab = [this, &mono](const QString& tabname, int columns)
{
QTableWidget* table = new QTableWidget();
table->setItemDelegate(new table_item_delegate);
table->setFont(mono);
table->setGridStyle(Qt::NoPen);
table->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents);
table->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
table->setEditTriggers(QAbstractItemView::NoEditTriggers);
table->setSelectionBehavior(QAbstractItemView::SelectRows);
table->verticalHeader()->setVisible(false);
table->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
table->verticalHeader()->setDefaultSectionSize(16);
table->horizontalHeader()->setStretchLastSection(true);
table->setColumnCount(columns);
m_tw_rsx->addTab(table, tabname);
return table;
};
m_list_captured_frame = add_rsx_tab(tr("Captured Frame"), 1);
m_list_captured_draw_calls = add_rsx_tab(tr("Captured Draw Calls"), 1);
m_list_captured_frame->setHorizontalHeaderLabels(QStringList() << tr("Column"));
m_list_captured_frame->setColumnWidth(0, 540);
m_list_captured_draw_calls->setHorizontalHeaderLabels(QStringList() << tr("Draw calls"));
m_list_captured_draw_calls->setColumnWidth(0, 540);
// Tools: Tools = Controls + Notebook Tabs
QVBoxLayout* vbox_tools = new QVBoxLayout();
vbox_tools->addLayout(hbox_controls);
vbox_tools->addWidget(m_tw_rsx);
// State explorer
m_text_transform_program = new QLabel();
m_text_transform_program->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
m_text_transform_program->setFont(mono);
m_text_transform_program->setText("");
m_text_shader_program = new QLabel();
m_text_shader_program->setTextInteractionFlags(Qt::TextSelectableByMouse | Qt::TextSelectableByKeyboard);
m_text_shader_program->setFont(mono);
m_text_shader_program->setText("");
m_list_index_buffer = new QListWidget();
m_list_index_buffer->setFont(mono);
// Panels for displaying the buffers
m_buffer_colorA = new Buffer(false, 0, tr("Color Buffer A"), this);
m_buffer_colorB = new Buffer(false, 1, tr("Color Buffer B"), this);
m_buffer_colorC = new Buffer(false, 2, tr("Color Buffer C"), this);
m_buffer_colorD = new Buffer(false, 3, tr("Color Buffer D"), this);
m_buffer_depth = new Buffer(false, 4, tr("Depth Buffer"), this);
m_buffer_stencil = new Buffer(false, 4, tr("Stencil Buffer"), this);
m_buffer_tex = new Buffer(true, 4, tr("Texture"), this);
for (Buffer* buf :
{
m_buffer_colorA, m_buffer_colorB, m_buffer_colorC, m_buffer_colorD
, m_buffer_depth, m_buffer_stencil, m_buffer_tex
})
{
buf->setContextMenuPolicy(Qt::CustomContextMenu);
connect(buf, &QWidget::customContextMenuRequested, buf, &Buffer::ShowContextMenu);
}
QGroupBox* tex_idx_group = new QGroupBox(tr("Texture Index or Address / Format Override"));
QVBoxLayout* vlayout_tex_idx = new QVBoxLayout(this);
QHBoxLayout* hbox_idx_line = new QHBoxLayout(this);
QLineEdit* tex_idx_line = new QLineEdit(this);
tex_idx_line->setPlaceholderText("00000000");
tex_idx_line->setFont(mono);
tex_idx_line->setMaxLength(18);
tex_idx_line->setFixedWidth(75);
tex_idx_line->setFocus();
tex_idx_line->setValidator(new QRegularExpressionValidator(QRegularExpression("^(0[xX])?0*[a-fA-F0-9]{0,8}$"), this));
QLineEdit* tex_fmt_override_line = new QLineEdit(this);
tex_fmt_override_line->setPlaceholderText("00");
tex_fmt_override_line->setFont(mono);
tex_fmt_override_line->setMaxLength(18);
tex_fmt_override_line->setFixedWidth(75);
tex_fmt_override_line->setFocus();
tex_fmt_override_line->setValidator(new QRegularExpressionValidator(QRegularExpression("^(0[xX])?0*[a-fA-F0-9]{0,2}$"), this));
hbox_idx_line->addWidget(tex_idx_line);
hbox_idx_line->addWidget(tex_fmt_override_line);
vlayout_tex_idx->addLayout(hbox_idx_line);
m_enabled_textures_label = new QLabel(enabled_textures_text, this);
vlayout_tex_idx->addWidget(m_enabled_textures_label);
tex_idx_group->setLayout(vlayout_tex_idx);
// Merge and display everything
QVBoxLayout* vbox_buffers1 = new QVBoxLayout();
vbox_buffers1->addWidget(m_buffer_colorA);
vbox_buffers1->addWidget(m_buffer_colorC);
vbox_buffers1->addWidget(m_buffer_depth);
vbox_buffers1->addWidget(m_buffer_tex);
vbox_buffers1->addStretch();
QVBoxLayout* vbox_buffers2 = new QVBoxLayout();
vbox_buffers2->addWidget(m_buffer_colorB);
vbox_buffers2->addWidget(m_buffer_colorD);
vbox_buffers2->addWidget(m_buffer_stencil);
vbox_buffers2->addWidget(tex_idx_group);
vbox_buffers2->addStretch();
QHBoxLayout* buffer_layout = new QHBoxLayout();
buffer_layout->addLayout(vbox_buffers1);
buffer_layout->addLayout(vbox_buffers2);
buffer_layout->addStretch();
QWidget* buffers = new QWidget();
buffers->setLayout(buffer_layout);
QTabWidget* state_rsx = new QTabWidget();
state_rsx->addTab(buffers, tr("RTTs and DS"));
state_rsx->addTab(m_text_transform_program, tr("Transform program"));
state_rsx->addTab(m_text_shader_program, tr("Shader program"));
state_rsx->addTab(m_list_index_buffer, tr("Index buffer"));
QHBoxLayout* main_layout = new QHBoxLayout();
main_layout->addLayout(vbox_tools, 1);
main_layout->addWidget(state_rsx, 1);
setLayout(main_layout);
connect(m_list_captured_draw_calls, &QTableWidget::itemClicked, this, &rsx_debugger::OnClickDrawCalls);
connect(tex_idx_line, &QLineEdit::textChanged, [this](const QString& text)
{
bool ok = false;
const u32 addr = (text.startsWith("0x", Qt::CaseInsensitive) ? text.right(text.size() - 2) : text).toULong(&ok, 16);
if (ok)
{
m_cur_texture = addr;
}
});
connect(tex_fmt_override_line, &QLineEdit::textChanged, [this](const QString& text)
{
bool ok = false;
const u32 fmt = (text.startsWith("0x", Qt::CaseInsensitive) ? text.right(text.size() - 2) : text).toULong(&ok, 16);
if (ok)
{
m_texture_format_override = fmt;
}
});
// Restore header states
QVariantMap states = m_gui_settings->GetValue(gui::rsx_states).toMap();
for (int i = 0; i < m_tw_rsx->count(); i++)
(static_cast<QTableWidget*>(m_tw_rsx->widget(i)))->horizontalHeader()->restoreState(states[QString::number(i)].toByteArray());
// Fill the frame
for (u32 i = 0; i < frame_debug.command_queue.size(); i++)
m_list_captured_frame->insertRow(i);
restoreGeometry(m_gui_settings->GetValue(gui::rsx_geometry).toByteArray());
// Check for updates every ~100 ms
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &rsx_debugger::UpdateInformation);
timer->start(100);
}
void rsx_debugger::closeEvent(QCloseEvent* event)
{
// Save header states and window geometry
QVariantMap states;
for (int i = 0; i < m_tw_rsx->count(); i++)
states[QString::number(i)] = (static_cast<QTableWidget*>(m_tw_rsx->widget(i)))->horizontalHeader()->saveState();
m_gui_settings->SetValue(gui::rsx_states, states, false);
m_gui_settings->SetValue(gui::rsx_geometry, saveGeometry(), true);
QDialog::closeEvent(event);
}
void rsx_debugger::keyPressEvent(QKeyEvent* event)
{
if (isActiveWindow() && !event->isAutoRepeat())
{
switch (event->key())
{
case Qt::Key_F5: UpdateInformation(); break;
default: break;
}
}
QDialog::keyPressEvent(event);
}
bool rsx_debugger::eventFilter(QObject* object, QEvent* event)
{
if (Buffer* buffer = qobject_cast<Buffer*>(object))
{
switch (event->type())
{
case QEvent::MouseButtonDblClick:
{
buffer->ShowWindowed();
break;
}
default:
break;
}
}
return QDialog::eventFilter(object, event);
}
Buffer::Buffer(bool isTex, u32 id, const QString& name, QWidget* parent)
: QGroupBox(name, parent)
, m_id(id)
, m_isTex(isTex)
{
m_image_size = isTex ? Texture_Size : Panel_Size;
m_canvas = new QLabel();
m_canvas->setFixedSize(m_image_size);
QHBoxLayout* layout = new QHBoxLayout();
layout->setContentsMargins(1, 1, 1, 1);
layout->addWidget(m_canvas);
setLayout(layout);
installEventFilter(parent);
}
// Draws a formatted and buffered <image> inside the Buffer Widget
void Buffer::showImage(QImage&& image)
{
if (image.isNull())
{
m_canvas->clear();
return;
}
m_image = std::move(image);
const QImage scaled = m_image.scaled(m_image_size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
m_canvas->setPixmap(QPixmap::fromImage(scaled));
QHBoxLayout* new_layout = new QHBoxLayout();
new_layout->setContentsMargins(1, 1, 1, 1);
new_layout->addWidget(m_canvas);
delete layout();
setLayout(new_layout);
}
void Buffer::ShowWindowed()
{
//const auto render = rsx::get_current_renderer();
if (m_image.isNull())
return;
// TODO: Is there any better way to choose the color buffers
//if (0 <= m_id && m_id < 4)
//{
// const auto buffers = render->display_buffers;
// u32 addr = rsx::constants::local_mem_base + buffers[m_id].offset;
// if (vm::check_addr(addr) && buffers[m_id].width && buffers[m_id].height)
// memory_viewer_panel::ShowImage(this, addr, 3, buffers[m_id].width, buffers[m_id].height, true);
// return;
//}
gui::utils::show_windowed_image(m_image.copy(), QString("%1 #%2").arg(title()).arg(m_window_counter++));
//if (m_isTex)
//{
// u8 location = render->textures[m_cur_texture].location();
// if (location <= 1 && vm::check_addr(rsx::get_address(render->textures[m_cur_texture].offset(), location))
// && render->textures[m_cur_texture].width() && render->textures[m_cur_texture].height())
// memory_viewer_panel::ShowImage(this,
// rsx::get_address(render->textures[m_cur_texture].offset(), location), 1,
// render->textures[m_cur_texture].width(),
// render->textures[m_cur_texture].height(), false);
//}
}
void Buffer::ShowContextMenu(const QPoint& pos)
{
if (m_image.isNull())
return;
QMenu context_menu(this);
QAction action(tr("Save Image At"), this);
connect(&action, &QAction::triggered, this, [&]()
{
if (m_image.isNull())
return;
const QString path = QFileDialog::getSaveFileName(this, tr("Save Image"), "", "Image (*.png)");
if (path.isEmpty())
return;
if (m_image.save(path, "PNG", 100))
{
rsx_debugger.success("Saved image to '%s'", path);
}
else
{
rsx_debugger.error("Failure to save image to '%s'", path);
}
});
context_menu.addAction(&action);
context_menu.exec(mapToGlobal(pos));
}
namespace
{
f32 f16_to_f32(f16 val)
{
// See http://stackoverflow.com/a/26779139
// The conversion doesn't handle NaN/Inf
const u16 _u16 = static_cast<u16>(val);
const u32 raw = ((_u16 & 0x8000) << 16) | // Sign (just moved)
(((_u16 & 0x7c00) + 0x1C000) << 13) | // Exponent ( exp - 15 + 127)
((_u16 & 0x03FF) << 13); // Mantissa
return std::bit_cast<f32>(raw);
}
std::array<u8, 3> get_value(std::span<const std::byte> orig_buffer, rsx::surface_color_format format, usz idx)
{
switch (format)
{
case rsx::surface_color_format::b8:
{
const u8 value = read_from_ptr<u8>(orig_buffer, idx);
return{ value, value, value };
}
case rsx::surface_color_format::x32:
{
const be_t<u32> stored_val = read_from_ptr<be_t<u32>>(orig_buffer, idx);
const u32 swapped_val = stored_val;
const f32 float_val = std::bit_cast<f32>(swapped_val);
const u8 val = float_val * 255.f;
return{ val, val, val };
}
case rsx::surface_color_format::a8b8g8r8:
case rsx::surface_color_format::x8b8g8r8_o8b8g8r8:
case rsx::surface_color_format::x8b8g8r8_z8b8g8r8:
{
const auto ptr = reinterpret_cast<const u8*>(orig_buffer.data());
return{ ptr[1 + idx * 4], ptr[2 + idx * 4], ptr[3 + idx * 4] };
}
case rsx::surface_color_format::a8r8g8b8:
case rsx::surface_color_format::x8r8g8b8_o8r8g8b8:
case rsx::surface_color_format::x8r8g8b8_z8r8g8b8:
{
const auto ptr = reinterpret_cast<const u8*>(orig_buffer.data());
return{ ptr[3 + idx * 4], ptr[2 + idx * 4], ptr[1 + idx * 4] };
}
case rsx::surface_color_format::w16z16y16x16:
{
const auto ptr = utils::bless<const u16>(orig_buffer);
const f16 h0 = static_cast<f16>(ptr[4 * idx]);
const f16 h1 = static_cast<f16>(ptr[4 * idx + 1]);
const f16 h2 = static_cast<f16>(ptr[4 * idx + 2]);
const f32 f0 = f16_to_f32(h0);
const f32 f1 = f16_to_f32(h1);
const f32 f2 = f16_to_f32(h2);
const u8 val0 = f0 * 255.f;
const u8 val1 = f1 * 255.f;
const u8 val2 = f2 * 255.f;
return{ val0, val1, val2 };
}
case rsx::surface_color_format::g8b8:
case rsx::surface_color_format::r5g6b5:
case rsx::surface_color_format::x1r5g5b5_o1r5g5b5:
case rsx::surface_color_format::x1r5g5b5_z1r5g5b5:
case rsx::surface_color_format::w32z32y32x32:
default:
fmt::throw_exception("Unsupported format for display");
}
}
/**
* Fill a buffer that can be passed to QImage.
*/
void convert_to_QImage_buffer(rsx::surface_color_format format, std::span<const std::byte> orig_buffer, std::vector<u8>& buffer, usz width, usz height) noexcept
{
buffer.resize(width * height * 4);
if (buffer.empty())
{
return;
}
for (u32 i = 0; i < width * height; i++)
{
// depending on original buffer, the colors may need to be reversed
const auto &colors = get_value(orig_buffer, format, i);
buffer[0 + i * 4] = colors[0];
buffer[1 + i * 4] = colors[1];
buffer[2 + i * 4] = colors[2];
buffer[3 + i * 4] = 255;
}
}
}
void rsx_debugger::OnClickDrawCalls()
{
const usz draw_id = m_list_captured_draw_calls->currentRow();
const auto& draw_call = frame_debug.draw_calls[draw_id];
Buffer* buffers[] =
{
m_buffer_colorA,
m_buffer_colorB,
m_buffer_colorC,
m_buffer_colorD,
};
const u32 width = draw_call.state.surface_clip_width();
const u32 height = draw_call.state.surface_clip_height();
for (usz i = 0; i < 4; i++)
{
if (width && height && !draw_call.color_buffer[i].empty())
{
std::vector<u8>& buffer = buffers[i]->cache;
convert_to_QImage_buffer(draw_call.state.surface_color(), draw_call.color_buffer[i], buffer, width, height);
buffers[i]->showImage(QImage(buffer.data(), static_cast<int>(width), static_cast<int>(height), QImage::Format_RGB32));
}
}
// Buffer Z
{
if (width && height && !draw_call.depth_stencil[0].empty())
{
const std::span<const std::byte> orig_buffer = draw_call.depth_stencil[0];
m_buffer_depth->cache.resize(4ULL * width * height);
const auto buffer = m_buffer_depth->cache.data();
if (draw_call.state.surface_depth_fmt() == rsx::surface_depth_format::z24s8)
{
for (u32 row = 0; row < height; row++)
{
for (u32 col = 0; col < width; col++)
{
const u32 depth_val = utils::bless<const u32>(orig_buffer)[row * width + col];
const u8 displayed_depth_val = 255 * depth_val / 0xFFFFFF;
buffer[4 * col + 0 + width * row * 4] = displayed_depth_val;
buffer[4 * col + 1 + width * row * 4] = displayed_depth_val;
buffer[4 * col + 2 + width * row * 4] = displayed_depth_val;
buffer[4 * col + 3 + width * row * 4] = 255;
}
}
}
else
{
for (u32 row = 0; row < height; row++)
{
for (u32 col = 0; col < width; col++)
{
const u16 depth_val = utils::bless<const u16>(orig_buffer)[row * width + col];
const u8 displayed_depth_val = 255 * depth_val / 0xFFFF;
buffer[4 * col + 0 + width * row * 4] = displayed_depth_val;
buffer[4 * col + 1 + width * row * 4] = displayed_depth_val;
buffer[4 * col + 2 + width * row * 4] = displayed_depth_val;
buffer[4 * col + 3 + width * row * 4] = 255;
}
}
}
m_buffer_depth->showImage(QImage(buffer, static_cast<int>(width), static_cast<int>(height), QImage::Format_RGB32));
}
}
// Buffer S
{
if (width && height && !draw_call.depth_stencil[1].empty())
{
const std::span<const std::byte> orig_buffer = draw_call.depth_stencil[1];
std::vector<u8>& buffer = m_buffer_stencil->cache;
buffer.resize(4ULL * width * height);
for (u32 row = 0; row < height; row++)
{
for (u32 col = 0; col < width; col++)
{
const u8 stencil_val = reinterpret_cast<const u8*>(orig_buffer.data())[row * width + col];
buffer[4 * col + 0 + width * row * 4] = stencil_val;
buffer[4 * col + 1 + width * row * 4] = stencil_val;
buffer[4 * col + 2 + width * row * 4] = stencil_val;
buffer[4 * col + 3 + width * row * 4] = 255;
}
}
m_buffer_stencil->showImage(QImage(buffer.data(), static_cast<int>(width), static_cast<int>(height), QImage::Format_RGB32));
}
}
// Programs
m_text_transform_program->clear();
m_text_transform_program->setText(qstr(frame_debug.draw_calls[draw_id].programs.first));
m_text_shader_program->clear();
m_text_shader_program->setText(qstr(frame_debug.draw_calls[draw_id].programs.second));
m_list_index_buffer->clear();
//m_list_index_buffer->insertColumn(0, "Index", 0, 700);
if (frame_debug.draw_calls[draw_id].state.index_type() == rsx::index_array_type::u16)
{
auto index_buffer = ref_ptr<u16[]>(frame_debug.draw_calls[draw_id].index);
for (u32 i = 0; i < frame_debug.draw_calls[draw_id].vertex_count; ++i)
{
m_list_index_buffer->insertItem(i, qstr(std::to_string(index_buffer[i])));
}
}
if (frame_debug.draw_calls[draw_id].state.index_type() == rsx::index_array_type::u32)
{
auto index_buffer = ref_ptr<u32[]>(frame_debug.draw_calls[draw_id].index);
for (u32 i = 0; i < frame_debug.draw_calls[draw_id].vertex_count; ++i)
{
m_list_index_buffer->insertItem(i, qstr(std::to_string(index_buffer[i])));
}
}
}
void rsx_debugger::UpdateInformation() const
{
GetMemory();
GetBuffers();
}
void rsx_debugger::GetMemory() const
{
std::string dump;
u32 cmd_i = 0;
std::string str;
for (const auto& command : frame_debug.command_queue)
{
str.clear();
rsx::get_pretty_printing_function(command.first)(str, command.first, command.second);
m_list_captured_frame->setItem(cmd_i++, 0, new QTableWidgetItem(qstr(str)));
dump += str;
dump += '\n';
}
if (!dump.empty())
{
fs::write_file(fs::get_cache_dir() + "command_dump.log", fs::rewrite, dump);
}
for (u32 i = 0; i < frame_debug.draw_calls.size(); i++)
m_list_captured_draw_calls->setItem(i, 0, new QTableWidgetItem(qstr(frame_debug.draw_calls[i].name)));
}
void rsx_debugger::GetBuffers() const
{
const auto render = rsx::get_current_renderer();
if (!render || !render->is_initialized || !render->local_mem_size || !render->is_paused())
{
return;
}
const auto addrs = render->get_color_surface_addresses();
// Color buffers
for (u32 buffer_it = 0; buffer_it < addrs.size(); buffer_it++)
{
const u32 rsx_buffer_addr = addrs[buffer_it];
const u32 width = rsx::method_registers.surface_clip_width();
const u32 pitch = rsx::method_registers.surface_pitch(buffer_it);
const u32 height = rsx::method_registers.surface_clip_height();
Buffer* panel{};
switch (buffer_it)
{
case 0: panel = m_buffer_colorA; break;
case 1: panel = m_buffer_colorB; break;
case 2: panel = m_buffer_colorC; break;
default: panel = m_buffer_colorD; break;
}
if (!height || !pitch)
{
panel->showImage(QImage());
continue;
}
u32 bpp = 4;
QImage::Format format = QImage::Format_RGB32;
const auto fmt = rsx::method_registers.surface_color();
bool bswap = true;
u32 dst_bpp = 0;
switch (fmt)
{
//case rsx::surface_color_format::x1r5g5b5_z1r5g5b5:
//case rsx::surface_color_format::x1r5g5b5_o1r5g5b5:
case rsx::surface_color_format::r5g6b5:
{
format = QImage::Format_RGB16;
bpp = 2;
break;
}
//case rsx::surface_color_format::x8r8g8b8_z8r8g8b8:
//case rsx::surface_color_format::x8r8g8b8_o8r8g8b8:
case rsx::surface_color_format::a8r8g8b8:
{
// For now ignore alpha channel because it has a tendency of being 0
//format = QImage::Format_ARGB32;
break;
}
case rsx::surface_color_format::b8:
{
format = QImage::Format_Grayscale8;
bpp = 1;
break;
}
case rsx::surface_color_format::g8b8:
{
bpp = 2;
dst_bpp = 4;
format = QImage::Format_RGBA8888;
bswap = false;
break;
}
//case rsx::surface_color_format::w16z16y16x16,
//case rsx::surface_color_format::w32z32y32x32,
//case rsx::surface_color_format::x32,
//case rsx::surface_color_format::x8b8g8r8_z8b8g8r8,
//case rsx::surface_color_format::x8b8g8r8_o8b8g8r8,
case rsx::surface_color_format::a8b8g8r8:
{
format = QImage::Format_RGBA8888;
break;
}
default:
{
break;
}
}
// PS3 buffer size (for memory validation)
const u32 src_mem_size = pitch * (height - 1) + width * bpp;
if ((height > 1 && pitch < width * bpp) || !src_mem_size || !vm::check_addr(rsx_buffer_addr, vm::page_readable, src_mem_size))
{
panel->showImage(QImage());
continue;
}
// Touch RSX memory to potentially flush GPU memory (must occur in named_thread)
[[maybe_unused]] auto buffer_touch_1 = named_thread("RSX Buffer Touch"sv, [&]()
{
for (u32 page_start = rsx_buffer_addr & -4096; page_start < rsx_buffer_addr + src_mem_size; page_start += 4096)
{
static_cast<void>(vm::_ref<atomic_t<u8>>(page_start).load());
}
});
bswap ^= std::endian::native == std::endian::big;
if (!dst_bpp)
{
dst_bpp = bpp;
}
const auto rsx_buffer = vm::get_super_ptr<const u8>(rsx_buffer_addr);
panel->cache.resize(std::max<usz>(panel->cache.size(), width * height * 16));
const auto buffer = panel->cache.data();
if (dst_bpp == bpp && pitch == width * bpp)
{
std::memcpy(buffer, rsx_buffer, src_mem_size);
}
else
{
for (u32 y = 0; y < height; y++)
{
const usz line_start = y * pitch;
std::memcpy(buffer + y * width * dst_bpp, rsx_buffer + line_start, width * bpp);
}
}
switch (fmt)
{
case rsx::surface_color_format::g8b8:
{
for (u32 y = 0; y < height; y++)
{
for (u32 x = 0; x < std::max(pitch, 1u) - 1; x += 2)
{
const usz line_start = y * pitch;
std::memcpy(buffer + line_start * 2 + x * 2 + 1, buffer + line_start * 2 + x, 2);
buffer[line_start * 2 + x * 2 + 0] = 0;
buffer[line_start * 2 + x * 2 + 3] = 0xff;
}
}
break;
}
case rsx::surface_color_format::a8b8g8r8:
{
format = QImage::Format_RGBA8888;
bswap = true;
break;
}
case rsx::surface_color_format::a8r8g8b8:
{
break;
}
default:
{
break;
}
}
if (bswap && bpp != 1)
{
if (bpp == 2)
{
for (u32 i = 0; i < panel->cache.size(); i += 2)
{
u16 res{};
std::memcpy(&res, buffer + i, 2);
res = stx::se_storage<u16>::swap(res);
std::memcpy(buffer + i, &res, 2);
}
}
else if (ensure(bpp == 4))
{
for (u32 i = 0; i < panel->cache.size(); i += 4)
{
u32 res{};
std::memcpy(&res, buffer + i, 4);
res = stx::se_storage<u32>::swap(res);
std::memcpy(buffer + i, &res, 4);
}
}
}
panel->showImage(QImage(panel->cache.data(), width, height, format));
}
// One iteration for depth, second for stencil
for (u32 buffer_it = 0; buffer_it < 2; buffer_it++)
{
const u32 rsx_buffer_addr = render->get_zeta_surface_address();
const u32 width = rsx::method_registers.surface_clip_width();
const u32 height = rsx::method_registers.surface_clip_height();
const u32 pitch = rsx::method_registers.surface_z_pitch();
u32 bpp = 4;
QImage::Format format = QImage::Format_Grayscale16;
const auto fmt = rsx::method_registers.surface_depth_fmt();
bool has_stencil = false;
bool is_stencil = buffer_it == 1;
bool is_float = false;
switch (fmt)
{
case rsx::surface_depth_format2::z16_float:
{
is_float = true;
[[fallthrough]];
}
case rsx::surface_depth_format2::z16_uint:
{
if (is_stencil)
{
continue;
}
bpp = 2;
break;
}
case rsx::surface_depth_format2::z24s8_float:
{
is_float = true;
[[fallthrough]];
}
case rsx::surface_depth_format2::z24s8_uint:
{
format = QImage::Format_RGB16;
has_stencil = true;
break;
}
default:
{
fmt::throw_exception("Unreachable!");
break;
}
}
// PS3 buffer size (for memory validation)
const u32 src_mem_size = pitch * (height - 1) + width * bpp;
Buffer* panel{};
switch (buffer_it)
{
case 0: panel = m_buffer_depth; break;
default: panel = m_buffer_stencil; break;
}
if ((height > 1 && pitch < width * bpp) || !height || !src_mem_size || !vm::check_addr(rsx_buffer_addr, vm::page_readable, src_mem_size))
{
panel->showImage(QImage());
continue;
}
// Touch RSX memory to potentially flush GPU memory (must occur in named_thread)
[[maybe_unused]] auto buffer_touch_2 = named_thread("RSX Buffer Touch"sv, [&]()
{
for (u32 page_start = rsx_buffer_addr & -4096; page_start < rsx_buffer_addr + src_mem_size; page_start += 4096)
{
static_cast<void>(vm::_ref<atomic_t<u8>>(page_start).load());
}
});
const auto rsx_buffer = vm::get_super_ptr<const u8>(rsx_buffer_addr);
panel->cache.resize(std::max<usz>(panel->cache.size(), width * height * 4));
const auto buffer = panel->cache.data();
if (is_stencil)
{
format = QImage::Format_Grayscale8;
for (u32 y = 0; y < height; y++)
{
for (u32 x = 0; x < width; x++)
{
const usz line_start = y * pitch;
std::memcpy(buffer + y * width + x, rsx_buffer + line_start + x * 4 + 3, 1);
}
}
}
else if (has_stencil)
{
format = QImage::Format_Grayscale16;
if (false && is_float)
{
// TODO
}
else
{
for (u32 y = 0; y < height; y++)
{
for (u32 x = 0; x < width; x++)
{
const usz line_start = y * pitch;
be_t<u32> data{};
std::memcpy(&data, rsx_buffer + line_start + x * 4, 4);
const u16 res = static_cast<u16>(u64{data / 256} * 0xFFFF / 0xFFFFFF);
std::memcpy(buffer + y * width * 2 + x * 2, &res, 2);
}
}
}
}
else
{
format = QImage::Format_Grayscale16;
for (u32 y = 0; y < height; y++)
{
for (u32 x = 0; x < width; x++)
{
be_t<u16> data{};
std::memcpy(&data, rsx_buffer + pitch * y + x * 2, 2);
const u16 res = is_float ? static_cast<u16>(f16_to_f32(static_cast<f16>(+data))) : +data;
std::memcpy(buffer + y * width * 2 + x * 2, &res, 2);
}
}
}
panel->showImage(QImage(panel->cache.data(), width, height, format));
}
auto& textures = rsx::method_registers.fragment_textures;
u32 texture_addr = m_cur_texture;
u32 tex_fmt_raw = 0;
u32 tex_fmt = 0;
u32 width = 1280;
u32 height = 720;
u32 pitch = 0;
if (texture_addr < 16)
{
if (textures[texture_addr].enabled())
{
width = textures[texture_addr].width();
height = textures[texture_addr].height();
pitch = textures[texture_addr].pitch();
tex_fmt_raw = textures[texture_addr].format();
tex_fmt = tex_fmt_raw & ~(CELL_GCM_TEXTURE_LN | CELL_GCM_TEXTURE_UN); // TOOD: Support these flags
texture_addr = rsx::get_address(textures[texture_addr].offset(), textures[texture_addr].location(), 1);
}
}
QString text;
for (u32 i = 0; i < textures.size(); i++)
{
// Technically it can also check if used by shader but idk
if (textures[i].enabled() && textures[i].width())
{
if (!text.isEmpty())
{
text += QStringLiteral(", ");
}
text += QStringLiteral("%0").arg(i);
}
}
m_enabled_textures_label->setText(enabled_textures_text + text);
if (m_texture_format_override)
{
tex_fmt = m_texture_format_override;
}
u32 bytes_per_block = 4;
u32 pixels_per_block = 1;
bool bswap = true;
// Naturally only a handful of common formats are implemented at the moment
switch (tex_fmt)
{
case CELL_GCM_TEXTURE_B8:
{
bytes_per_block = 1;
break;
}
case CELL_GCM_TEXTURE_COMPRESSED_DXT1:
{
bytes_per_block = 8;
pixels_per_block = 16;
break;
}
default:
{
break;
}
}
const u32 line_bytes_count = width * bytes_per_block / pixels_per_block;
if (!pitch)
{
pitch = line_bytes_count;
}
// PS3 buffer size (for memory validation)
const u32 src_mem_size = pitch * (height - 1) + line_bytes_count;
if (!src_mem_size || !height || !vm::check_addr(texture_addr, vm::page_readable, src_mem_size))
{
m_buffer_tex->showImage(QImage());
return;
}
[[maybe_unused]] auto buffer_touch_3 = named_thread("RSX Buffer Touch"sv, [&]()
{
// Must touch every page
for (u32 i = texture_addr & -4096; i < texture_addr + src_mem_size; i += 4096)
{
static_cast<void>(vm::_ref<atomic_t<u8>>(i).load());
}
});
const auto rsx_buffer = vm::get_super_ptr<const u8>(texture_addr);
m_buffer_tex->cache.resize(std::max<usz>(m_buffer_tex->cache.size(), width * height * 16 + pitch));
const auto buffer = m_buffer_tex->cache.data();
if (pixels_per_block != 1 || pitch == line_bytes_count)
{
std::memcpy(buffer, rsx_buffer, src_mem_size);
}
else
{
for (u32 y = 0; y < height; y++)
{
std::memcpy(buffer + y * line_bytes_count, rsx_buffer + y * pitch, line_bytes_count);
}
}
switch (tex_fmt)
{
case CELL_GCM_TEXTURE_COMPRESSED_DXT1:
{
bswap = false;
// Compressed texture to RGB
for (usz i = 0; i < width * height / 16; i++)
{
le_t<u16> color0{}, color1{};
std::memcpy(&color0, rsx_buffer + i * 8, 2);
std::memcpy(&color1, rsx_buffer + i * 8 + 2, 2);
be_t<u32> control{};
std::memcpy(&control, rsx_buffer + i * 8 + 4, 4);
for (u32 sub = 0; sub < 16; sub++)
{
const u32 code = (+control >> (sub * 2)) & 3;
auto convert_to_rgb888 = [](u32 input) -> std::tuple<u32, u32, u32>
{
u32 r = ((input >> 11) % 32) * 255 / 32;
u32 g = ((input >> 5) % 64) * 255 / 64;
u32 b = (input % 32) * 255 / 32;
return std::make_tuple(r, g, b);
};
const auto [r0, g0, b0] = convert_to_rgb888(color0);
const auto [r1, g1, b1] = convert_to_rgb888(color1);
auto compute_color = [&](u32 a0, u32 a1, u8 shift) -> u32
{
u32 a0_portion = 1;
u32 a1_portion = 1;
switch (code)
{
case 0:
{
return a0; // Color0 only
}
case 1:
{
return a1; // Color1 only
}
case 2:
case 3:
{
if (a0 > a1)
{
if (code == 3)
{
a1_portion = 2;
}
else
{
a0_portion = 2;
}
}
else if (code == 3)
{
return 0;
} // otherwise is the default values
break;
}
default:
{
fmt::throw_exception("Unreachable!");
break;
}
}
return ((a1 * a1_portion + a0 * a0_portion) / (a0_portion + a1_portion)) << shift;
};
const le_t<u32> dest_color = compute_color(r0, r1, 0) + compute_color(g0, g1, 8) + compute_color(b0, b1, 16) + (255 << 24);
std::memcpy(buffer + ((i % (width / 4) * 4 + sub % 4) + ((i / (width / 4) * 4 + sub / 4) * width)) * sizeof(u32), &dest_color, 4);
}
}
break;
}
default:
{
break;
}
}
if (bswap && bytes_per_block != 1 && pixels_per_block == 1)
{
if (bytes_per_block == 2)
{
for (u32 i = 0; i < m_buffer_tex->cache.size(); i += 2)
{
u16 res{};
std::memcpy(&res, buffer + i, 2);
res = stx::se_storage<u16>::swap(res);
std::memcpy(buffer + i, &res, 2);
}
}
else if (ensure(bytes_per_block == 4))
{
for (u32 i = 0; i < m_buffer_tex->cache.size(); i += 4)
{
u32 res{};
std::memcpy(&res, buffer + i, 4);
res = stx::se_storage<u32>::swap(res);
std::memcpy(buffer + i, &res, 4);
}
}
}
m_buffer_tex->showImage(QImage(m_buffer_tex->cache.data(), width, height, QImage::Format_RGB32));
}
| 33,923
|
C++
|
.cpp
| 1,043
| 29.232982
| 161
| 0.663132
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,083
|
settings.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/settings.cpp
|
#include "settings.h"
#include "qt_utils.h"
#include "Utilities/File.h"
settings::settings(QObject* parent) : QObject(parent),
m_settings_dir(ComputeSettingsDir())
{
}
settings::~settings()
{
sync();
}
void settings::sync()
{
if (m_settings)
{
m_settings->sync();
}
}
QString settings::GetSettingsDir() const
{
return m_settings_dir.absolutePath();
}
QString settings::ComputeSettingsDir()
{
return QString::fromStdString(fs::get_config_dir()) + "/GuiConfigs/";
}
void settings::RemoveValue(const QString& key, const QString& name, bool sync) const
{
if (m_settings)
{
m_settings->beginGroup(key);
m_settings->remove(name);
m_settings->endGroup();
if (sync)
{
m_settings->sync();
}
}
}
void settings::RemoveValue(const gui_save& entry, bool sync) const
{
RemoveValue(entry.key, entry.name, sync);
}
QVariant settings::GetValue(const QString& key, const QString& name, const QVariant& def) const
{
return m_settings ? m_settings->value(key + "/" + name, def) : def;
}
QVariant settings::GetValue(const gui_save& entry) const
{
return GetValue(entry.key, entry.name, entry.def);
}
QVariant settings::List2Var(const q_pair_list& list)
{
QByteArray ba;
QDataStream stream(&ba, QIODevice::WriteOnly);
stream << list;
return QVariant(ba);
}
q_pair_list settings::Var2List(const QVariant& var)
{
q_pair_list list;
QByteArray ba = var.toByteArray();
QDataStream stream(&ba, QIODevice::ReadOnly);
stream >> list;
return list;
}
void settings::SetValue(const gui_save& entry, const QVariant& value, bool sync) const
{
SetValue(entry.key, entry.name, value, sync);
}
void settings::SetValue(const QString& key, const QVariant& value, bool sync) const
{
if (m_settings)
{
m_settings->setValue(key, value);
if (sync)
{
m_settings->sync();
}
}
}
void settings::SetValue(const QString& key, const QString& name, const QVariant& value, bool sync) const
{
if (m_settings)
{
m_settings->beginGroup(key);
m_settings->setValue(name, value);
m_settings->endGroup();
if (sync)
{
m_settings->sync();
}
}
}
| 2,074
|
C++
|
.cpp
| 94
| 20.095745
| 104
| 0.72769
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,084
|
vfs_dialog_tab.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/vfs_dialog_tab.cpp
|
#include "vfs_dialog_tab.h"
#include "Utilities/Config.h"
vfs_dialog_tab::vfs_dialog_tab(const QString& name, gui_save list_location, cfg::string* cfg_node, std::shared_ptr<gui_settings> _gui_settings, QWidget* parent)
: vfs_dialog_path_widget(name, QString::fromStdString(cfg_node->to_string()), QString::fromStdString(cfg_node->def), std::move(list_location), std::move(_gui_settings), parent)
, m_cfg_node(cfg_node)
{
}
void vfs_dialog_tab::set_settings() const
{
m_gui_settings->SetValue(m_list_location, get_dir_list());
m_cfg_node->from_string(get_selected_path());
}
| 580
|
C++
|
.cpp
| 12
| 46.833333
| 177
| 0.740283
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,085
|
welcome_dialog.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/welcome_dialog.cpp
|
#include "welcome_dialog.h"
#include "ui_welcome_dialog.h"
#include "gui_settings.h"
#include "shortcut_utils.h"
#include "qt_utils.h"
#include "Utilities/File.h"
#include <QPushButton>
#include <QCheckBox>
#include <QSvgWidget>
welcome_dialog::welcome_dialog(std::shared_ptr<gui_settings> gui_settings, bool is_manual_show, QWidget* parent)
: QDialog(parent)
, ui(new Ui::welcome_dialog)
, m_gui_settings(std::move(gui_settings))
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
setWindowFlag(Qt::WindowCloseButtonHint, is_manual_show);
ui->okay->setEnabled(is_manual_show);
ui->i_have_read->setChecked(is_manual_show);
ui->i_have_read->setEnabled(!is_manual_show);
ui->do_not_show->setEnabled(!is_manual_show);
ui->do_not_show->setChecked(!m_gui_settings->GetValue(gui::ib_show_welcome).toBool());
ui->use_dark_theme->setChecked(gui::utils::dark_mode_active());
ui->icon_label->load(QStringLiteral(":/rpcs3.svg"));
ui->label_3->setText(tr(
R"(
<p style="white-space: nowrap;">
RPCS3 is an open-source Sony PlayStation 3 emulator and debugger.<br>
It is written in C++ for Windows, Linux, FreeBSD and MacOS funded with <a %0 href="https://rpcs3.net/patreon">Patreon</a>.<br>
Our developers and contributors are always working hard to ensure this project is the best that it can be.<br>
There are still plenty of implementations to make and optimizations to do.
</p>
)"
).arg(gui::utils::get_link_style()));
ui->label_info->setText(tr(
R"(
<p style="white-space: nowrap;">
To get started, you must first install the <span style="font-weight:600;">PlayStation 3 firmware</span>.<br>
Please refer to the <a %0 href="https://rpcs3.net/quickstart">Quickstart</a> guide found on the official website for further information.<br>
If you have any further questions, please refer to the <a %0 href="https://rpcs3.net/faq">FAQ</a>.<br>
Otherwise, further discussion and support can be found on the <a %0 href="https://forums.rpcs3.net">Forums</a> or on our <a %0 href="https://discord.me/RPCS3">Discord</a> server.
</p>
)"
).arg(gui::utils::get_link_style()));
if (!is_manual_show)
{
connect(ui->i_have_read, &QCheckBox::clicked, this, [this](bool checked)
{
ui->okay->setEnabled(checked);
});
connect(ui->do_not_show, &QCheckBox::clicked, this, [this](bool checked)
{
m_gui_settings->SetValue(gui::ib_show_welcome, QVariant(!checked));
});
}
connect(ui->okay, &QPushButton::clicked, this, &QDialog::accept);
#ifdef _WIN32
ui->create_applications_menu_shortcut->setText(tr("&Create Start Menu shortcut"));
#elif defined(__APPLE__)
ui->create_applications_menu_shortcut->setText(tr("&Create Launchpad shortcut"));
ui->use_dark_theme->setVisible(false);
#else
ui->create_applications_menu_shortcut->setText(tr("&Create Application Menu shortcut"));
#endif
layout()->setSizeConstraint(QLayout::SetFixedSize);
connect(this, &QDialog::finished, this, [this]()
{
if (ui->create_desktop_shortcut->isChecked())
{
gui::utils::create_shortcut("RPCS3", "", "", "RPCS3", ":/rpcs3.svg", fs::get_temp_dir(), gui::utils::shortcut_location::desktop);
}
if (ui->create_applications_menu_shortcut->isChecked())
{
gui::utils::create_shortcut("RPCS3", "", "", "RPCS3", ":/rpcs3.svg", fs::get_temp_dir(), gui::utils::shortcut_location::applications);
}
m_user_wants_dark_theme = ui->use_dark_theme->isChecked();
});
}
welcome_dialog::~welcome_dialog()
{
}
| 3,469
|
C++
|
.cpp
| 81
| 40.160494
| 182
| 0.712337
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,086
|
game_list_frame.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/game_list_frame.cpp
|
#include "game_list_frame.h"
#include "qt_utils.h"
#include "settings_dialog.h"
#include "pad_settings_dialog.h"
#include "custom_table_widget_item.h"
#include "input_dialog.h"
#include "localized.h"
#include "progress_dialog.h"
#include "persistent_settings.h"
#include "emu_settings.h"
#include "gui_settings.h"
#include "game_list_delegate.h"
#include "game_list_table.h"
#include "game_list_grid.h"
#include "game_list_grid_item.h"
#include "patch_manager_dialog.h"
#include "Emu/Memory/vm.h"
#include "Emu/System.h"
#include "Emu/vfs_config.h"
#include "Emu/system_utils.hpp"
#include "Loader/PSF.h"
#include "util/types.hpp"
#include "Utilities/File.h"
#include "Utilities/mutex.h"
#include "util/yaml.hpp"
#include "util/sysinfo.hpp"
#include "Input/pad_thread.h"
#include <algorithm>
#include <memory>
#include <set>
#include <regex>
#include <unordered_map>
#include <unordered_set>
#include <QtConcurrent>
#include <QDesktopServices>
#include <QHeaderView>
#include <QMenuBar>
#include <QMessageBox>
#include <QScrollBar>
#include <QInputDialog>
#include <QApplication>
#include <QClipboard>
#include <QFileDialog>
LOG_CHANNEL(game_list_log, "GameList");
LOG_CHANNEL(sys_log, "SYS");
extern atomic_t<bool> g_system_progress_canceled;
std::string get_savestate_file(std::string_view title_id, std::string_view boot_pat, s64 abs_id, s64 rel_id);
game_list_frame::game_list_frame(std::shared_ptr<gui_settings> gui_settings, std::shared_ptr<emu_settings> emu_settings, std::shared_ptr<persistent_settings> persistent_settings, QWidget* parent)
: custom_dock_widget(tr("Game List"), parent)
, m_gui_settings(std::move(gui_settings))
, m_emu_settings(std::move(emu_settings))
, m_persistent_settings(std::move(persistent_settings))
{
m_icon_size = gui::gl_icon_size_min; // ensure a valid size
m_is_list_layout = m_gui_settings->GetValue(gui::gl_listMode).toBool();
m_margin_factor = m_gui_settings->GetValue(gui::gl_marginFactor).toReal();
m_text_factor = m_gui_settings->GetValue(gui::gl_textFactor).toReal();
m_icon_color = m_gui_settings->GetValue(gui::gl_iconColor).value<QColor>();
m_col_sort_order = m_gui_settings->GetValue(gui::gl_sortAsc).toBool() ? Qt::AscendingOrder : Qt::DescendingOrder;
m_sort_column = m_gui_settings->GetValue(gui::gl_sortCol).toInt();
m_hidden_list = gui::utils::list_to_set(m_gui_settings->GetValue(gui::gl_hidden_list).toStringList());
m_old_layout_is_list = m_is_list_layout;
// Save factors for first setup
m_gui_settings->SetValue(gui::gl_iconColor, m_icon_color, false);
m_gui_settings->SetValue(gui::gl_marginFactor, m_margin_factor, false);
m_gui_settings->SetValue(gui::gl_textFactor, m_text_factor, true);
m_game_dock = new QMainWindow(this);
m_game_dock->setWindowFlags(Qt::Widget);
setWidget(m_game_dock);
m_game_grid = new game_list_grid();
m_game_grid->installEventFilter(this);
m_game_grid->scroll_area()->verticalScrollBar()->installEventFilter(this);
m_game_list = new game_list_table(this, m_persistent_settings);
m_game_list->installEventFilter(this);
m_game_list->verticalScrollBar()->installEventFilter(this);
m_game_compat = new game_compatibility(m_gui_settings, this);
m_central_widget = new QStackedWidget(this);
m_central_widget->addWidget(m_game_list);
m_central_widget->addWidget(m_game_grid);
if (m_is_list_layout)
{
m_central_widget->setCurrentWidget(m_game_list);
}
else
{
m_central_widget->setCurrentWidget(m_game_grid);
}
m_game_dock->setCentralWidget(m_central_widget);
// Actions regarding showing/hiding columns
auto add_column = [this](gui::game_list_columns col, const QString& header_text, const QString& action_text)
{
m_game_list->setHorizontalHeaderItem(static_cast<int>(col), new QTableWidgetItem(header_text));
m_columnActs.append(new QAction(action_text, this));
};
add_column(gui::game_list_columns::icon, tr("Icon"), tr("Show Icons"));
add_column(gui::game_list_columns::name, tr("Name"), tr("Show Names"));
add_column(gui::game_list_columns::serial, tr("Serial"), tr("Show Serials"));
add_column(gui::game_list_columns::firmware, tr("Firmware"), tr("Show Firmwares"));
add_column(gui::game_list_columns::version, tr("Version"), tr("Show Versions"));
add_column(gui::game_list_columns::category, tr("Category"), tr("Show Categories"));
add_column(gui::game_list_columns::path, tr("Path"), tr("Show Paths"));
add_column(gui::game_list_columns::move, tr("PlayStation Move"), tr("Show PlayStation Move"));
add_column(gui::game_list_columns::resolution, tr("Supported Resolutions"), tr("Show Supported Resolutions"));
add_column(gui::game_list_columns::sound, tr("Sound Formats"), tr("Show Sound Formats"));
add_column(gui::game_list_columns::parental, tr("Parental Level"), tr("Show Parental Levels"));
add_column(gui::game_list_columns::last_play, tr("Last Played"), tr("Show Last Played"));
add_column(gui::game_list_columns::playtime, tr("Time Played"), tr("Show Time Played"));
add_column(gui::game_list_columns::compat, tr("Compatibility"), tr("Show Compatibility"));
add_column(gui::game_list_columns::dir_size, tr("Space On Disk"), tr("Show Space On Disk"));
m_progress_dialog = new progress_dialog(tr("Loading games"), tr("Loading games, please wait..."), tr("Cancel"), 0, 0, false, this, Qt::Dialog | Qt::WindowTitleHint | Qt::CustomizeWindowHint);
m_progress_dialog->setMinimumDuration(200); // Only show the progress dialog after some time has passed
// Events
connect(m_progress_dialog, &QProgressDialog::canceled, this, [this]()
{
gui::utils::stop_future_watcher(m_parsing_watcher, true);
gui::utils::stop_future_watcher(m_refresh_watcher, true);
m_path_entries.clear();
m_path_list.clear();
m_serials.clear();
m_game_data.clear();
m_notes.clear();
m_games.pop_all();
});
connect(&m_parsing_watcher, &QFutureWatcher<void>::finished, this, &game_list_frame::OnParsingFinished);
connect(&m_parsing_watcher, &QFutureWatcher<void>::canceled, this, [this]()
{
WaitAndAbortSizeCalcThreads();
WaitAndAbortRepaintThreads();
m_path_entries.clear();
m_path_list.clear();
m_game_data.clear();
m_serials.clear();
m_games.pop_all();
});
connect(&m_refresh_watcher, &QFutureWatcher<void>::finished, this, &game_list_frame::OnRefreshFinished);
connect(&m_refresh_watcher, &QFutureWatcher<void>::canceled, this, [this]()
{
WaitAndAbortSizeCalcThreads();
WaitAndAbortRepaintThreads();
m_path_entries.clear();
m_path_list.clear();
m_game_data.clear();
m_serials.clear();
m_games.pop_all();
if (m_progress_dialog)
{
m_progress_dialog->accept();
}
});
connect(&m_refresh_watcher, &QFutureWatcher<void>::progressRangeChanged, this, [this](int minimum, int maximum)
{
if (m_progress_dialog)
{
m_progress_dialog->SetRange(minimum, maximum);
}
});
connect(&m_refresh_watcher, &QFutureWatcher<void>::progressValueChanged, this, [this](int value)
{
if (m_progress_dialog)
{
m_progress_dialog->SetValue(value);
}
});
connect(m_game_list, &QTableWidget::customContextMenuRequested, this, &game_list_frame::ShowContextMenu);
connect(m_game_list, &QTableWidget::itemSelectionChanged, this, &game_list_frame::ItemSelectionChangedSlot);
connect(m_game_list, &QTableWidget::itemDoubleClicked, this, QOverload<QTableWidgetItem*>::of(&game_list_frame::doubleClickedSlot));
connect(m_game_list->horizontalHeader(), &QHeaderView::sectionClicked, this, &game_list_frame::OnColClicked);
connect(m_game_grid, &QWidget::customContextMenuRequested, this, &game_list_frame::ShowContextMenu);
connect(m_game_grid, &game_list_grid::ItemSelectionChanged, this, &game_list_frame::NotifyGameSelection);
connect(m_game_grid, &game_list_grid::ItemDoubleClicked, this, QOverload<const game_info&>::of(&game_list_frame::doubleClickedSlot));
connect(m_game_compat, &game_compatibility::DownloadStarted, this, [this]()
{
for (const auto& game : m_game_data)
{
game->compat = m_game_compat->GetStatusData("Download");
}
Refresh();
});
connect(m_game_compat, &game_compatibility::DownloadFinished, this, &game_list_frame::OnCompatFinished);
connect(m_game_compat, &game_compatibility::DownloadCanceled, this, &game_list_frame::OnCompatFinished);
connect(m_game_compat, &game_compatibility::DownloadError, this, [this](const QString& error)
{
OnCompatFinished();
QMessageBox::warning(this, tr("Warning!"), tr("Failed to retrieve the online compatibility database!\nFalling back to local database.\n\n%0").arg(error));
});
connect(m_game_list, &game_list::FocusToSearchBar, this, &game_list_frame::FocusToSearchBar);
connect(m_game_grid, &game_list_grid::FocusToSearchBar, this, &game_list_frame::FocusToSearchBar);
m_game_list->create_header_actions(m_columnActs,
[this](int col) { return m_gui_settings->GetGamelistColVisibility(static_cast<gui::game_list_columns>(col)); },
[this](int col, bool visible) { m_gui_settings->SetGamelistColVisibility(static_cast<gui::game_list_columns>(col), visible); });
}
void game_list_frame::LoadSettings()
{
m_col_sort_order = m_gui_settings->GetValue(gui::gl_sortAsc).toBool() ? Qt::AscendingOrder : Qt::DescendingOrder;
m_sort_column = m_gui_settings->GetValue(gui::gl_sortCol).toInt();
m_category_filters = m_gui_settings->GetGameListCategoryFilters(true);
m_grid_category_filters = m_gui_settings->GetGameListCategoryFilters(false);
m_draw_compat_status_to_grid = m_gui_settings->GetValue(gui::gl_draw_compat).toBool();
m_show_custom_icons = m_gui_settings->GetValue(gui::gl_custom_icon).toBool();
m_play_hover_movies = m_gui_settings->GetValue(gui::gl_hover_gifs).toBool();
m_game_list->sync_header_actions(m_columnActs, [this](int col) { return m_gui_settings->GetGamelistColVisibility(static_cast<gui::game_list_columns>(col)); });
}
game_list_frame::~game_list_frame()
{
WaitAndAbortSizeCalcThreads();
WaitAndAbortRepaintThreads();
gui::utils::stop_future_watcher(m_parsing_watcher, true);
gui::utils::stop_future_watcher(m_refresh_watcher, true);
}
void game_list_frame::OnColClicked(int col)
{
if (col == static_cast<int>(gui::game_list_columns::icon)) return; // Don't "sort" icons.
if (col == m_sort_column)
{
m_col_sort_order = (m_col_sort_order == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder;
}
else
{
m_col_sort_order = Qt::AscendingOrder;
}
m_sort_column = col;
m_gui_settings->SetValue(gui::gl_sortAsc, m_col_sort_order == Qt::AscendingOrder, false);
m_gui_settings->SetValue(gui::gl_sortCol, col, true);
m_game_list->sort(m_game_data.size(), m_sort_column, m_col_sort_order);
}
// Get visibility of entries
bool game_list_frame::IsEntryVisible(const game_info& game, bool search_fallback) const
{
const auto matches_category = [&]()
{
if (m_is_list_layout)
{
return m_category_filters.contains(qstr(game->info.category));
}
return m_grid_category_filters.contains(qstr(game->info.category));
};
const QString serial = qstr(game->info.serial);
const bool is_visible = m_show_hidden || !m_hidden_list.contains(serial);
return is_visible && matches_category() && SearchMatchesApp(qstr(game->info.name), serial, search_fallback);
}
bool game_list_frame::RemoveContentPath(const std::string& path, const std::string& desc)
{
if (!fs::exists(path))
{
return true;
}
if (fs::is_dir(path))
{
if (fs::remove_all(path))
{
game_list_log.notice("Removed '%s' directory: '%s'", desc, path);
}
else
{
game_list_log.error("Could not remove '%s' directory: '%s' (%s)", desc, path, fs::g_tls_error);
return false;
}
}
else // If file
{
if (fs::remove_file(path))
{
game_list_log.notice("Removed '%s' file: '%s'", desc, path);
}
else
{
game_list_log.error("Could not remove '%s' file: '%s' (%s)", desc, path, fs::g_tls_error);
return false;
}
}
return true;
}
u32 game_list_frame::RemoveContentPathList(const std::vector<std::string>& path_list, const std::string& desc)
{
u32 paths_removed = 0;
for (const std::string& path : path_list)
{
if (RemoveContentPath(path, desc))
{
paths_removed++;
}
}
return paths_removed;
}
bool game_list_frame::RemoveContentBySerial(const std::string& base_dir, const std::string& serial, const std::string& desc)
{
bool success = true;
for (const auto& entry : fs::dir(base_dir))
{
// Search for any path starting with serial (e.g. BCES01118_BCES01118)
if (!entry.name.starts_with(serial))
{
continue;
}
if (!RemoveContentPath(base_dir + entry.name, desc))
{
success = false; // Mark as failed if there is at least one failure
}
}
return success;
}
std::vector<std::string> game_list_frame::GetDirListBySerial(const std::string& base_dir, const std::string& serial)
{
std::vector<std::string> dir_list;
for (const auto& entry : fs::dir(base_dir))
{
// Check for sub folder starting with serial (e.g. BCES01118_BCES01118)
if (entry.is_directory && entry.name.starts_with(serial))
{
dir_list.push_back(base_dir + entry.name);
}
}
return dir_list;
}
std::string game_list_frame::GetCacheDirBySerial(const std::string& serial)
{
return rpcs3::utils::get_cache_dir() + (serial == "vsh.self" ? "vsh" : serial);
}
std::string game_list_frame::GetDataDirBySerial(const std::string& serial)
{
return fs::get_config_dir() + "data/" + serial;
}
void game_list_frame::push_path(const std::string& path, std::vector<std::string>& legit_paths)
{
{
std::lock_guard lock(m_path_mutex);
if (!m_path_list.insert(path).second)
{
return;
}
}
legit_paths.push_back(path);
}
void game_list_frame::Refresh(const bool from_drive, const std::vector<std::string>& serials_to_remove_from_yml, const bool scroll_after)
{
if (from_drive)
{
WaitAndAbortSizeCalcThreads();
}
WaitAndAbortRepaintThreads();
gui::utils::stop_future_watcher(m_parsing_watcher, from_drive);
gui::utils::stop_future_watcher(m_refresh_watcher, from_drive);
if (m_progress_dialog && m_progress_dialog->isVisible())
{
m_progress_dialog->SetValue(m_progress_dialog->maximum());
m_progress_dialog->accept();
}
if (from_drive)
{
m_path_entries.clear();
m_path_list.clear();
m_serials.clear();
m_game_data.clear();
m_notes.clear();
m_games.pop_all();
if (m_progress_dialog)
{
m_progress_dialog->SetValue(0);
}
const std::string games_dir = rpcs3::utils::get_games_dir();
// List of serials (title id) to remove in "games.yml" file (if any)
std::vector<std::string> serials_to_remove = serials_to_remove_from_yml; // Initialize the list with the specified serials (if any)
// Scan game list to detect the titles belonging to auto-detection "games" folder
for (const auto& [serial, path] : Emu.GetGamesConfig().get_games()) // Loop on game list file
{
// NOTE: Used starts_with(games_dir) instead of Emu.IsPathInsideDir(path, games_dir) due the latter would check also the existence of the paths
//
if (path.starts_with(games_dir)) // If game path belongs to auto-detection "games" folder, add the serial to the removal list
{
serials_to_remove.push_back(serial);
}
}
// Remove the specified and detected serials (title id) only from the game list in memory (not yet in "games.yml" file)
Emu.RemoveGames(serials_to_remove, false);
// Scan auto-detection "games" folder adding the detected titles to the game list plus flushing also all the other changes in "games.yml" file
if (const u32 games_added = Emu.AddGamesFromDir(games_dir); games_added != 0)
{
game_list_log.notice("Refresh added %d new entries found in %s", games_added, games_dir);
}
const std::string _hdd = Emu.GetCallbacks().resolve_path(rpcs3::utils::get_hdd0_dir()) + '/';
m_parsing_watcher.setFuture(QtConcurrent::map(m_parsing_threads, [this, _hdd](int index)
{
if (index > 0)
{
game_list_log.error("Unexpected thread index: %d", index);
return;
}
const auto add_dir = [this](const std::string& path, bool is_disc)
{
for (const auto& entry : fs::dir(path))
{
if (m_parsing_watcher.isCanceled())
{
break;
}
if (!entry.is_directory || entry.name == "." || entry.name == "..")
{
continue;
}
std::lock_guard lock(m_path_mutex);
m_path_entries.emplace_back(path_entry{path + entry.name, is_disc, false});
}
};
const std::string hdd0_game = _hdd + "game/";
add_dir(hdd0_game, false);
add_dir(_hdd + "disc/", true); // Deprecated
for (const auto& [serial, path] : Emu.GetGamesConfig().get_games())
{
if (m_parsing_watcher.isCanceled())
{
break;
}
std::string game_dir = path;
game_dir.resize(game_dir.find_last_not_of('/') + 1);
if (game_dir.empty() || path.starts_with(hdd0_game))
{
continue;
}
// Don't use the C00 subdirectory in our game list
if (game_dir.ends_with("/C00") || game_dir.ends_with("\\C00"))
{
game_dir = game_dir.substr(0, game_dir.size() - 4);
}
std::lock_guard lock(m_path_mutex);
m_path_entries.emplace_back(path_entry{game_dir, false, true});
}
}));
return;
}
// Fill Game List / Game Grid
const std::string selected_item = CurrentSelectionPath();
// Release old data
for (const auto& game : m_game_data)
{
game->item = nullptr;
}
// Get list of matching apps
std::vector<game_info> matching_apps;
for (const auto& app : m_game_data)
{
if (IsEntryVisible(app))
{
matching_apps.push_back(app);
}
}
// Fallback is not needed when at least one entry is visible
if (matching_apps.empty())
{
for (const auto& app : m_game_data)
{
if (IsEntryVisible(app, true))
{
matching_apps.push_back(app);
}
}
}
if (m_is_list_layout)
{
m_game_grid->clear_list();
const int scroll_position = m_game_list->verticalScrollBar()->value();
m_game_list->populate(matching_apps, m_notes, m_titles, selected_item, m_play_hover_movies);
m_game_list->sort(m_game_data.size(), m_sort_column, m_col_sort_order);
RepaintIcons();
if (scroll_after)
{
m_game_list->scrollTo(m_game_list->currentIndex(), QAbstractItemView::PositionAtCenter);
}
else
{
m_game_list->verticalScrollBar()->setValue(scroll_position);
}
}
else
{
m_game_list->clear_list();
m_game_grid->populate(matching_apps, m_notes, m_titles, selected_item, m_play_hover_movies);
RepaintIcons();
}
}
void game_list_frame::OnParsingFinished()
{
const Localized localized;
const std::string dev_flash = g_cfg_vfs.get_dev_flash();
const std::string _hdd = rpcs3::utils::get_hdd0_dir();
m_path_entries.emplace_back(path_entry{dev_flash + "vsh/module/vsh.self", false, false});
// Remove duplicates
sort(m_path_entries.begin(), m_path_entries.end(), [](const path_entry& l, const path_entry& r){return l.path < r.path;});
m_path_entries.erase(unique(m_path_entries.begin(), m_path_entries.end(), [](const path_entry& l, const path_entry& r){return l.path == r.path;}), m_path_entries.end());
const std::string game_icon_path = fs::get_config_dir() + "/Icons/game_icons/";
const auto add_game = [this, dev_flash, cat_unknown_localized = localized.category.unknown.toStdString(), cat_unknown = cat::cat_unknown.toStdString(), game_icon_path, _hdd, play_hover_movies = m_play_hover_movies, show_custom_icons = m_show_custom_icons](const std::string& dir_or_elf)
{
GameInfo game{};
game.path = dir_or_elf;
const Localized thread_localized;
const std::string sfo_dir = rpcs3::utils::get_sfo_dir_from_game_path(dir_or_elf);
const psf::registry psf = psf::load_object(sfo_dir + "/PARAM.SFO");
const std::string_view title_id = psf::get_string(psf, "TITLE_ID", "");
if (title_id.empty())
{
if (!fs::is_file(dir_or_elf))
{
// Do not care about invalid entries
return;
}
game.serial = dir_or_elf.substr(dir_or_elf.find_last_of(fs::delim) + 1);
game.category = cat::cat_ps3_os.toStdString(); // Key for operating system executables
game.version = utils::get_firmware_version();
game.app_ver = game.version;
game.fw = game.version;
game.bootable = 1;
game.icon_path = dev_flash + "vsh/resource/explore/icon/icon_home.png";
if (dir_or_elf.starts_with(dev_flash))
{
std::string path_vfs = dir_or_elf.substr(dev_flash.size());
if (const usz pos = path_vfs.find_first_not_of(fs::delim); pos != umax && pos != 0)
{
path_vfs = path_vfs.substr(pos);
}
if (const auto it = thread_localized.title.titles.find(path_vfs); it != thread_localized.title.titles.cend())
{
game.name = it->second.toStdString();
}
}
if (game.name.empty())
{
game.name = game.serial;
}
}
else
{
game.serial = std::string(title_id);
game.name = std::string(psf::get_string(psf, "TITLE", cat_unknown_localized));
game.app_ver = std::string(psf::get_string(psf, "APP_VER", cat_unknown_localized));
game.version = std::string(psf::get_string(psf, "VERSION", cat_unknown_localized));
game.category = std::string(psf::get_string(psf, "CATEGORY", cat_unknown));
game.fw = std::string(psf::get_string(psf, "PS3_SYSTEM_VER", cat_unknown_localized));
game.parental_lvl = psf::get_integer(psf, "PARENTAL_LEVEL", 0);
game.resolution = psf::get_integer(psf, "RESOLUTION", 0);
game.sound_format = psf::get_integer(psf, "SOUND_FORMAT", 0);
game.bootable = psf::get_integer(psf, "BOOTABLE", 0);
game.attr = psf::get_integer(psf, "ATTRIBUTE", 0);
game.icon_path = sfo_dir + "/ICON0.PNG";
game.movie_path = sfo_dir + "/ICON1.PAM";
if (game.category == "DG")
{
const std::string game_data_dir = _hdd + "game/" + game.serial;
if (std::string latest_icon = game_data_dir + "/ICON0.PNG"; fs::is_file(latest_icon))
{
game.icon_path = std::move(latest_icon);
}
if (std::string latest_movie = game_data_dir + "/ICON1.PAM"; fs::is_file(latest_movie))
{
game.movie_path = std::move(latest_movie);
}
}
}
if (show_custom_icons)
{
if (std::string icon_path = game_icon_path + game.serial + "/ICON0.PNG"; fs::is_file(icon_path))
{
game.icon_path = std::move(icon_path);
}
}
const QString serial = qstr(game.serial);
m_games_mutex.lock();
// Read persistent_settings values
const QString last_played = m_persistent_settings->GetValue(gui::persistent::last_played, serial, "").toString();
const quint64 playtime = m_persistent_settings->GetValue(gui::persistent::playtime, serial, 0).toULongLong();
// Set persistent_settings values if values exist
if (!last_played.isEmpty())
{
m_persistent_settings->SetLastPlayed(serial, last_played, false); // No need to sync here. It would slow down the refresh anyway.
}
if (playtime > 0)
{
m_persistent_settings->SetPlaytime(serial, playtime, false); // No need to sync here. It would slow down the refresh anyway.
}
m_serials.insert(serial);
if (QString note = m_persistent_settings->GetValue(gui::persistent::notes, serial, "").toString(); !note.isEmpty())
{
m_notes.insert_or_assign(serial, std::move(note));
}
if (QString title = m_persistent_settings->GetValue(gui::persistent::titles, serial, "").toString().simplified(); !title.isEmpty())
{
m_titles.insert_or_assign(serial, std::move(title));
}
m_games_mutex.unlock();
QString qt_cat = qstr(game.category);
if (const auto boot_cat = thread_localized.category.cat_boot.find(qt_cat); boot_cat != thread_localized.category.cat_boot.cend())
{
qt_cat = boot_cat->second;
}
else if (const auto data_cat = thread_localized.category.cat_data.find(qt_cat); data_cat != thread_localized.category.cat_data.cend())
{
qt_cat = data_cat->second;
}
else if (game.category == cat_unknown)
{
qt_cat = thread_localized.category.unknown;
}
else
{
qt_cat = thread_localized.category.other;
}
gui_game_info info{};
info.info = std::move(game);
info.localized_category = std::move(qt_cat);
info.compat = m_game_compat->GetCompatibility(info.info.serial);
info.hasCustomConfig = fs::is_file(rpcs3::utils::get_custom_config_path(info.info.serial));
info.hasCustomPadConfig = fs::is_file(rpcs3::utils::get_custom_input_config_path(info.info.serial));
info.has_hover_gif = fs::is_file(game_icon_path + info.info.serial + "/hover.gif");
info.has_hover_pam = fs::is_file(info.info.movie_path);
// Free some memory
if (!info.has_hover_pam)
{
info.info.movie_path.clear();
}
m_games.push(std::make_shared<gui_game_info>(std::move(info)));
};
const auto add_disc_dir = [this](const std::string& path, std::vector<std::string>& legit_paths)
{
for (const auto& entry : fs::dir(path))
{
if (m_refresh_watcher.isCanceled())
{
break;
}
if (!entry.is_directory || entry.name == "." || entry.name == "..")
{
continue;
}
if (entry.name == "PS3_GAME" || std::regex_match(entry.name, std::regex("^PS3_GM[[:digit:]]{2}$")))
{
push_path(path + "/" + entry.name, legit_paths);
}
}
};
m_refresh_watcher.setFuture(QtConcurrent::map(m_path_entries, [this, _hdd, add_disc_dir, add_game](const path_entry& entry)
{
std::vector<std::string> legit_paths;
if (entry.is_from_yml)
{
if (fs::is_file(entry.path + "/PARAM.SFO"))
{
push_path(entry.path, legit_paths);
}
else if (fs::is_file(entry.path + "/PS3_DISC.SFB"))
{
// Check if a path loaded from games.yml is already registered in add_dir(_hdd + "disc/");
if (entry.path.starts_with(_hdd))
{
std::string_view frag = std::string_view(entry.path).substr(_hdd.size());
if (frag.starts_with("disc/"))
{
// Our path starts from _hdd + 'disc/'
frag.remove_prefix(5);
// Check if the remaining part is the only path component
if (frag.find_first_of('/') + 1 == 0)
{
game_list_log.trace("Removed duplicate: %s", entry.path);
if (static std::unordered_set<std::string> warn_once_list; warn_once_list.emplace(entry.path).second)
{
game_list_log.todo("Game at '%s' is using deprecated directory '/dev_hdd0/disc/'.\nConsider moving into '%s'.", entry.path, rpcs3::utils::get_games_dir());
}
return;
}
}
}
add_disc_dir(entry.path, legit_paths);
}
else
{
game_list_log.trace("Invalid game path registered: %s", entry.path);
return;
}
}
else if (fs::is_file(entry.path + "/PS3_DISC.SFB"))
{
if (!entry.is_disc)
{
game_list_log.error("Invalid game path found in %s", entry.path);
return;
}
add_disc_dir(entry.path, legit_paths);
}
else
{
if (entry.is_disc)
{
game_list_log.error("Invalid disc path found in %s", entry.path);
return;
}
push_path(entry.path, legit_paths);
}
for (const std::string& path : legit_paths)
{
add_game(path);
}
}));
}
void game_list_frame::OnRefreshFinished()
{
WaitAndAbortSizeCalcThreads();
WaitAndAbortRepaintThreads();
for (auto&& g : m_games.pop_all())
{
m_game_data.push_back(g);
}
const Localized localized;
const std::string cat_unknown_localized = localized.category.unknown.toStdString();
// Try to update the app version for disc games if there is a patch
for (const auto& entry : m_game_data)
{
if (entry->info.category == "DG")
{
for (const auto& other : m_game_data)
{
// The patch is game data and must have the same serial and an app version
static constexpr auto version_is_bigger = [](const std::string& v0, const std::string& v1, const std::string& serial, bool is_fw)
{
std::add_pointer_t<char> ev0, ev1;
const double ver0 = std::strtod(v0.c_str(), &ev0);
const double ver1 = std::strtod(v1.c_str(), &ev1);
if (v0.c_str() + v0.size() == ev0 && v1.c_str() + v1.size() == ev1)
{
return ver0 > ver1;
}
game_list_log.error("Failed to update the displayed %s numbers for title ID %s\n'%s'-'%s'", is_fw ? "firmware version" : "version", serial, v0, v1);
return false;
};
if (entry->info.serial == other->info.serial && other->info.category != "DG" && other->info.app_ver != cat_unknown_localized)
{
// Update the app version if it's higher than the disc's version (old games may not have an app version)
if (entry->info.app_ver == cat_unknown_localized || version_is_bigger(other->info.app_ver, entry->info.app_ver, entry->info.serial, true))
{
entry->info.app_ver = other->info.app_ver;
}
// Update the firmware version if possible and if it's higher than the disc's version
if (other->info.fw != cat_unknown_localized && version_is_bigger(other->info.fw, entry->info.fw, entry->info.serial, false))
{
entry->info.fw = other->info.fw;
}
// Update the parental level if possible and if it's higher than the disc's level
if (other->info.parental_lvl != 0 && other->info.parental_lvl > entry->info.parental_lvl)
{
entry->info.parental_lvl = other->info.parental_lvl;
}
}
}
}
}
// Sort by name at the very least.
std::sort(m_game_data.begin(), m_game_data.end(), [&](const game_info& game1, const game_info& game2)
{
const QString serial1 = QString::fromStdString(game1->info.serial);
const QString serial2 = QString::fromStdString(game2->info.serial);
const QString& title1 = m_titles.contains(serial1) ? m_titles.at(serial1) : QString::fromStdString(game1->info.name);
const QString& title2 = m_titles.contains(serial2) ? m_titles.at(serial2) : QString::fromStdString(game2->info.name);
return title1.toLower() < title2.toLower();
});
// clean up hidden games list
m_hidden_list.intersect(m_serials);
m_gui_settings->SetValue(gui::gl_hidden_list, QStringList(m_hidden_list.values()));
m_serials.clear();
m_path_list.clear();
m_path_entries.clear();
Refresh();
if (!std::exchange(m_initial_refresh_done, true))
{
m_game_list->restore_layout(m_gui_settings->GetValue(gui::gl_state).toByteArray());
m_game_list->sync_header_actions(m_columnActs, [this](int col) { return m_gui_settings->GetGamelistColVisibility(static_cast<gui::game_list_columns>(col)); });
}
// Emit signal and remove slots
Q_EMIT Refreshed();
m_refresh_funcs_manage_type.reset();
m_refresh_funcs_manage_type.emplace();
}
void game_list_frame::OnCompatFinished()
{
for (const auto& game : m_game_data)
{
game->compat = m_game_compat->GetCompatibility(game->info.serial);
}
Refresh();
}
void game_list_frame::ToggleCategoryFilter(const QStringList& categories, bool show)
{
QStringList& filters = m_is_list_layout ? m_category_filters : m_grid_category_filters;
if (show)
{
filters.append(categories);
}
else
{
for (const QString& cat : categories)
{
filters.removeAll(cat);
}
}
Refresh();
}
void game_list_frame::SaveSettings()
{
for (int col = 0; col < m_columnActs.count(); ++col)
{
m_gui_settings->SetGamelistColVisibility(static_cast<gui::game_list_columns>(col), m_columnActs[col]->isChecked());
}
m_gui_settings->SetValue(gui::gl_sortCol, m_sort_column, false);
m_gui_settings->SetValue(gui::gl_sortAsc, m_col_sort_order == Qt::AscendingOrder, false);
m_gui_settings->SetValue(gui::gl_state, m_game_list->horizontalHeader()->saveState(), true);
}
void game_list_frame::doubleClickedSlot(QTableWidgetItem* item)
{
if (!item)
{
return;
}
doubleClickedSlot(GetGameInfoByMode(item));
}
void game_list_frame::doubleClickedSlot(const game_info& game)
{
if (!game)
{
return;
}
sys_log.notice("Booting from gamelist per doubleclick...");
Q_EMIT RequestBoot(game);
}
void game_list_frame::ItemSelectionChangedSlot()
{
game_info game = nullptr;
if (m_is_list_layout)
{
if (const auto item = m_game_list->item(m_game_list->currentRow(), static_cast<int>(gui::game_list_columns::icon)); item && item->isSelected())
{
game = GetGameInfoByMode(item);
}
}
Q_EMIT NotifyGameSelection(game);
}
void game_list_frame::CreateShortcuts(const game_info& gameinfo, const std::set<gui::utils::shortcut_location>& locations)
{
if (locations.empty())
{
game_list_log.error("Failed to create shortcuts for %s. No locations selected.", qstr(gameinfo->info.name).simplified());
return;
}
std::string gameid_token_value;
const std::string dev_flash = g_cfg_vfs.get_dev_flash();
if (gameinfo->info.category == "DG" && !fs::is_file(rpcs3::utils::get_hdd0_dir() + "/game/" + gameinfo->info.serial + "/USRDIR/EBOOT.BIN"))
{
const usz ps3_game_dir_pos = fs::get_parent_dir(gameinfo->info.path).size();
std::string relative_boot_dir = gameinfo->info.path.substr(ps3_game_dir_pos);
if (usz char_pos = relative_boot_dir.find_first_not_of(fs::delim); char_pos != umax)
{
relative_boot_dir = relative_boot_dir.substr(char_pos);
}
else
{
relative_boot_dir.clear();
}
if (!relative_boot_dir.empty())
{
if (relative_boot_dir != "PS3_GAME")
{
gameid_token_value = gameinfo->info.serial + "/" + relative_boot_dir;
}
else
{
gameid_token_value = gameinfo->info.serial;
}
}
}
else
{
gameid_token_value = gameinfo->info.serial;
}
#ifdef __linux__
const std::string target_cli_args = gameinfo->info.path.starts_with(dev_flash) ? fmt::format("--no-gui \"%%%%RPCS3_VFS%%%%:dev_flash/%s\"", gameinfo->info.path.substr(dev_flash.size()))
: fmt::format("--no-gui \"%%%%RPCS3_GAMEID%%%%:%s\"", gameid_token_value);
#else
const std::string target_cli_args = gameinfo->info.path.starts_with(dev_flash) ? fmt::format("--no-gui \"%%RPCS3_VFS%%:dev_flash/%s\"", gameinfo->info.path.substr(dev_flash.size()))
: fmt::format("--no-gui \"%%RPCS3_GAMEID%%:%s\"", gameid_token_value);
#endif
const std::string target_icon_dir = fmt::format("%sIcons/game_icons/%s/", fs::get_config_dir(), gameinfo->info.serial);
if (!fs::create_path(target_icon_dir))
{
game_list_log.error("Failed to create shortcut path %s (%s)", qstr(gameinfo->info.name).simplified(), target_icon_dir, fs::g_tls_error);
return;
}
bool success = true;
for (const gui::utils::shortcut_location& location : locations)
{
std::string destination;
switch (location)
{
case gui::utils::shortcut_location::desktop:
destination = "desktop";
break;
case gui::utils::shortcut_location::applications:
destination = "application menu";
break;
#ifdef _WIN32
case gui::utils::shortcut_location::rpcs3_shortcuts:
destination = "/games/shortcuts/";
break;
#endif
}
if (!gameid_token_value.empty() && gui::utils::create_shortcut(gameinfo->info.name, gameinfo->info.serial, target_cli_args, gameinfo->info.name, gameinfo->info.icon_path, target_icon_dir, location))
{
game_list_log.success("Created %s shortcut for %s", destination, qstr(gameinfo->info.name).simplified());
}
else
{
game_list_log.error("Failed to create %s shortcut for %s", destination, qstr(gameinfo->info.name).simplified());
success = false;
}
}
#ifdef _WIN32
if (locations.size() > 1 || !locations.contains(gui::utils::shortcut_location::rpcs3_shortcuts))
#endif
{
if (success)
{
QMessageBox::information(this, tr("Success!"), tr("Successfully created shortcut(s)."));
}
else
{
QMessageBox::warning(this, tr("Warning!"), tr("Failed to create shortcut(s)!"));
}
}
}
void game_list_frame::ShowContextMenu(const QPoint &pos)
{
QPoint global_pos;
game_info gameinfo;
if (m_is_list_layout)
{
QTableWidgetItem* item = m_game_list->item(m_game_list->indexAt(pos).row(), static_cast<int>(gui::game_list_columns::icon));
global_pos = m_game_list->viewport()->mapToGlobal(pos);
gameinfo = GetGameInfoFromItem(item);
}
else if (game_list_grid_item* item = static_cast<game_list_grid_item*>(m_game_grid->selected_item()))
{
gameinfo = item->game();
global_pos = m_game_grid->mapToGlobal(pos);
}
if (!gameinfo)
{
return;
}
GameInfo current_game = gameinfo->info;
const QString serial = qstr(current_game.serial);
const QString name = qstr(current_game.name).simplified();
const std::string cache_base_dir = GetCacheDirBySerial(current_game.serial);
const std::string config_data_base_dir = GetDataDirBySerial(current_game.serial);
// Make Actions
QMenu menu;
static const auto is_game_running = [](const std::string& serial)
{
return Emu.GetStatus(false) != system_state::stopped && (serial == Emu.GetTitleID() || (serial == "vsh.self" && Emu.IsVsh()));
};
const bool is_current_running_game = is_game_running(current_game.serial);
QAction* boot = new QAction(gameinfo->hasCustomConfig
? (is_current_running_game
? tr("&Reboot with global configuration")
: tr("&Boot with global configuration"))
: (is_current_running_game
? tr("&Reboot")
: tr("&Boot")));
QFont font = boot->font();
font.setBold(true);
if (gameinfo->hasCustomConfig)
{
QAction* boot_custom = menu.addAction(is_current_running_game
? tr("&Reboot with custom configuration")
: tr("&Boot with custom configuration"));
boot_custom->setFont(font);
connect(boot_custom, &QAction::triggered, [this, gameinfo]
{
sys_log.notice("Booting from gamelist per context menu...");
Q_EMIT RequestBoot(gameinfo);
});
}
else
{
boot->setFont(font);
}
menu.addAction(boot);
{
QAction* boot_default = menu.addAction(is_current_running_game
? tr("&Reboot with default configuration")
: tr("&Boot with default configuration"));
connect(boot_default, &QAction::triggered, [this, gameinfo]
{
sys_log.notice("Booting from gamelist per context menu...");
Q_EMIT RequestBoot(gameinfo, cfg_mode::default_config);
});
QAction* boot_manual = menu.addAction(is_current_running_game
? tr("&Reboot with manually selected configuration")
: tr("&Boot with manually selected configuration"));
connect(boot_manual, &QAction::triggered, [this, gameinfo]
{
if (const std::string file_path = QFileDialog::getOpenFileName(this, "Select Config File", "", tr("Config Files (*.yml);;All files (*.*)")).toStdString(); !file_path.empty())
{
sys_log.notice("Booting from gamelist per context menu...");
Q_EMIT RequestBoot(gameinfo, cfg_mode::custom_selection, file_path);
}
else
{
sys_log.notice("Manual config selection aborted.");
}
});
}
extern bool is_savestate_compatible(fs::file&& file, std::string_view filepath);
if (const std::string sstate = get_savestate_file(current_game.serial, current_game.path, 0, 0); is_savestate_compatible(fs::file(sstate), sstate))
{
QAction* boot_state = menu.addAction(is_current_running_game
? tr("&Reboot with savestate")
: tr("&Boot with savestate"));
connect(boot_state, &QAction::triggered, [this, gameinfo, sstate]
{
sys_log.notice("Booting savestate from gamelist per context menu...");
Q_EMIT RequestBoot(gameinfo, cfg_mode::custom, "", sstate);
});
}
menu.addSeparator();
QAction* configure = menu.addAction(gameinfo->hasCustomConfig
? tr("&Change Custom Configuration")
: tr("&Create Custom Configuration From Global Settings"));
QAction* create_game_default_config = gameinfo->hasCustomConfig ? nullptr
: menu.addAction(tr("&Create Custom Configuration From Default Settings"));
QAction* pad_configure = menu.addAction(gameinfo->hasCustomPadConfig
? tr("&Change Custom Gamepad Configuration")
: tr("&Create Custom Gamepad Configuration"));
QAction* configure_patches = menu.addAction(tr("&Manage Game Patches"));
menu.addSeparator();
QAction* create_cpu_cache = menu.addAction(tr("&Create LLVM Cache"));
// Remove menu
QMenu* remove_menu = menu.addMenu(tr("&Remove"));
if (gameinfo->hasCustomConfig)
{
QAction* remove_custom_config = remove_menu->addAction(tr("&Remove Custom Configuration"));
connect(remove_custom_config, &QAction::triggered, [this, current_game, gameinfo]()
{
if (RemoveCustomConfiguration(current_game.serial, gameinfo, true))
{
ShowCustomConfigIcon(gameinfo);
}
});
}
if (gameinfo->hasCustomPadConfig)
{
QAction* remove_custom_pad_config = remove_menu->addAction(tr("&Remove Custom Gamepad Configuration"));
connect(remove_custom_pad_config, &QAction::triggered, [this, current_game, gameinfo]()
{
if (RemoveCustomPadConfiguration(current_game.serial, gameinfo, true))
{
ShowCustomConfigIcon(gameinfo);
}
});
}
const bool has_cache_dir = fs::is_dir(cache_base_dir);
if (has_cache_dir)
{
remove_menu->addSeparator();
QAction* remove_shaders_cache = remove_menu->addAction(tr("&Remove Shaders Cache"));
remove_shaders_cache->setEnabled(!is_current_running_game);
connect(remove_shaders_cache, &QAction::triggered, [this, cache_base_dir]()
{
RemoveShadersCache(cache_base_dir, true);
});
QAction* remove_ppu_cache = remove_menu->addAction(tr("&Remove PPU Cache"));
remove_ppu_cache->setEnabled(!is_current_running_game);
connect(remove_ppu_cache, &QAction::triggered, [this, cache_base_dir]()
{
RemovePPUCache(cache_base_dir, true);
});
QAction* remove_spu_cache = remove_menu->addAction(tr("&Remove SPU Cache"));
remove_spu_cache->setEnabled(!is_current_running_game);
connect(remove_spu_cache, &QAction::triggered, [this, cache_base_dir]()
{
RemoveSPUCache(cache_base_dir, true);
});
}
const std::string hdd1_cache_base_dir = rpcs3::utils::get_hdd1_dir() + "caches/";
const bool has_hdd1_cache_dir = !GetDirListBySerial(hdd1_cache_base_dir, current_game.serial).empty();
if (has_hdd1_cache_dir)
{
QAction* remove_hdd1_cache = remove_menu->addAction(tr("&Remove HDD1 Cache"));
remove_hdd1_cache->setEnabled(!is_current_running_game);
connect(remove_hdd1_cache, &QAction::triggered, [this, hdd1_cache_base_dir, serial = current_game.serial]()
{
RemoveHDD1Cache(hdd1_cache_base_dir, serial, true);
});
}
if (has_cache_dir || has_hdd1_cache_dir)
{
QAction* remove_all_caches = remove_menu->addAction(tr("&Remove All Caches"));
remove_all_caches->setEnabled(!is_current_running_game);
connect(remove_all_caches, &QAction::triggered, [this, current_game, cache_base_dir, hdd1_cache_base_dir]()
{
if (is_game_running(current_game.serial))
return;
if (QMessageBox::question(this, tr("Confirm Removal"), tr("Remove all caches?")) != QMessageBox::Yes)
return;
RemoveContentPath(cache_base_dir, "cache");
RemoveHDD1Cache(hdd1_cache_base_dir, current_game.serial);
});
}
const std::string savestate_dir = fs::get_config_dir() + "savestates/" + current_game.serial;
if (fs::is_dir(savestate_dir))
{
remove_menu->addSeparator();
QAction* remove_savestate = remove_menu->addAction(tr("&Remove Savestate"));
remove_savestate->setEnabled(!is_current_running_game);
connect(remove_savestate, &QAction::triggered, [this, current_game, savestate_dir]()
{
if (is_game_running(current_game.serial))
return;
if (QMessageBox::question(this, tr("Confirm Removal"), tr("Remove savestate?")) != QMessageBox::Yes)
return;
RemoveContentPath(savestate_dir, "savestate");
});
}
// Disable the Remove menu if empty
remove_menu->setEnabled(!remove_menu->isEmpty());
menu.addSeparator();
// Manage Game menu
QMenu* manage_game_menu = menu.addMenu(tr("&Manage Game"));
// Create game shortcuts
QAction* create_desktop_shortcut = manage_game_menu->addAction(tr("&Create Desktop Shortcut"));
connect(create_desktop_shortcut, &QAction::triggered, this, [this, gameinfo]()
{
CreateShortcuts(gameinfo, {gui::utils::shortcut_location::desktop});
});
#ifdef _WIN32
QAction* create_start_menu_shortcut = manage_game_menu->addAction(tr("&Create Start Menu Shortcut"));
#elif defined(__APPLE__)
QAction* create_start_menu_shortcut = manage_game_menu->addAction(tr("&Create Launchpad Shortcut"));
#else
QAction* create_start_menu_shortcut = manage_game_menu->addAction(tr("&Create Application Menu Shortcut"));
#endif
connect(create_start_menu_shortcut, &QAction::triggered, this, [this, gameinfo]()
{
CreateShortcuts(gameinfo, {gui::utils::shortcut_location::applications});
});
manage_game_menu->addSeparator();
// Hide/rename game in game list
QAction* hide_serial = manage_game_menu->addAction(tr("&Hide From Game List"));
hide_serial->setCheckable(true);
hide_serial->setChecked(m_hidden_list.contains(serial));
QAction* rename_title = manage_game_menu->addAction(tr("&Rename In Game List"));
// Edit tooltip notes/reset time played
QAction* edit_notes = manage_game_menu->addAction(tr("&Edit Tooltip Notes"));
QAction* reset_time_played = manage_game_menu->addAction(tr("&Reset Time Played"));
manage_game_menu->addSeparator();
// Remove game
QAction* remove_game = manage_game_menu->addAction(tr("&Remove %1").arg(gameinfo->localized_category));
remove_game->setEnabled(!is_current_running_game);
// Custom Images menu
QMenu* icon_menu = menu.addMenu(tr("&Custom Images"));
const std::array<QAction*, 3> custom_icon_actions =
{
icon_menu->addAction(tr("&Import Custom Icon")),
icon_menu->addAction(tr("&Replace Custom Icon")),
icon_menu->addAction(tr("&Remove Custom Icon"))
};
icon_menu->addSeparator();
const std::array<QAction*, 3> custom_gif_actions =
{
icon_menu->addAction(tr("&Import Hover Gif")),
icon_menu->addAction(tr("&Replace Hover Gif")),
icon_menu->addAction(tr("&Remove Hover Gif"))
};
icon_menu->addSeparator();
const std::array<QAction*, 3> custom_shader_icon_actions =
{
icon_menu->addAction(tr("&Import Custom Shader Loading Background")),
icon_menu->addAction(tr("&Replace Custom Shader Loading Background")),
icon_menu->addAction(tr("&Remove Custom Shader Loading Background"))
};
if (const std::string custom_icon_dir_path = fs::get_config_dir() + "/Icons/game_icons/" + current_game.serial;
fs::create_path(custom_icon_dir_path))
{
enum class icon_action
{
add,
replace,
remove
};
enum class icon_type
{
game_list,
hover_gif,
shader_load
};
const auto handle_icon = [this, serial](const QString& game_icon_path, const QString& suffix, icon_action action, icon_type type)
{
QString icon_path;
if (action != icon_action::remove)
{
QString msg;
switch (type)
{
case icon_type::game_list:
msg = tr("Select Custom Icon");
break;
case icon_type::hover_gif:
msg = tr("Select Custom Hover Gif");
break;
case icon_type::shader_load:
msg = tr("Select Custom Shader Loading Background");
break;
}
icon_path = QFileDialog::getOpenFileName(this, msg, "", tr("%0 (*.%0);;All files (*.*)").arg(suffix));
}
if (action == icon_action::remove || !icon_path.isEmpty())
{
bool refresh = false;
QString msg;
switch (type)
{
case icon_type::game_list:
msg = tr("Remove Custom Icon of %0?").arg(serial);
break;
case icon_type::hover_gif:
msg = tr("Remove Custom Hover Gif of %0?").arg(serial);
break;
case icon_type::shader_load:
msg = tr("Remove Custom Shader Loading Background of %0?").arg(serial);
break;
}
if (action == icon_action::replace || (action == icon_action::remove &&
QMessageBox::question(this, tr("Confirm Removal"), msg) == QMessageBox::Yes))
{
if (QFile file(game_icon_path); file.exists() && !file.remove())
{
game_list_log.error("Could not remove old file: '%s'", game_icon_path, file.errorString());
QMessageBox::warning(this, tr("Warning!"), tr("Failed to remove the old file!"));
return;
}
game_list_log.success("Removed file: '%s'", game_icon_path);
if (action == icon_action::remove)
{
refresh = true;
}
}
if (action != icon_action::remove)
{
if (!QFile::copy(icon_path, game_icon_path))
{
game_list_log.error("Could not import file '%s' to '%s'.", icon_path, game_icon_path);
QMessageBox::warning(this, tr("Warning!"), tr("Failed to import the new file!"));
}
else
{
game_list_log.success("Imported file '%s' to '%s'", icon_path, game_icon_path);
refresh = true;
}
}
if (refresh)
{
Refresh(true);
}
}
};
const std::vector<std::tuple<icon_type, QString, QString, const std::array<QAction*, 3>&>> icon_map =
{
{icon_type::game_list, "/ICON0.PNG", "png", custom_icon_actions},
{icon_type::hover_gif, "/hover.gif", "gif", custom_gif_actions},
{icon_type::shader_load, "/PIC1.PNG", "png", custom_shader_icon_actions},
};
for (const auto& [type, icon_name, suffix, actions] : icon_map)
{
const QString icon_path = qstr(custom_icon_dir_path) + icon_name;
if (QFile::exists(icon_path))
{
actions[static_cast<int>(icon_action::add)]->setVisible(false);
connect(actions[static_cast<int>(icon_action::replace)], &QAction::triggered, this, [handle_icon, icon_path, t = type, s = suffix] { handle_icon(icon_path, s, icon_action::replace, t); });
connect(actions[static_cast<int>(icon_action::remove)], &QAction::triggered, this, [handle_icon, icon_path, t = type, s = suffix] { handle_icon(icon_path, s, icon_action::remove, t); });
}
else
{
connect(actions[static_cast<int>(icon_action::add)], &QAction::triggered, this, [handle_icon, icon_path, t = type, s = suffix] { handle_icon(icon_path, s, icon_action::add, t); });
actions[static_cast<int>(icon_action::replace)]->setVisible(false);
actions[static_cast<int>(icon_action::remove)]->setEnabled(false);
}
}
}
else
{
game_list_log.error("Could not create path '%s'", custom_icon_dir_path);
icon_menu->setEnabled(false);
}
menu.addSeparator();
// Open Folder menu
QMenu* open_folder_menu = menu.addMenu(tr("&Open Folder"));
const bool is_disc_game = qstr(current_game.category) == cat::cat_disc_game;
const std::string captures_dir = fs::get_config_dir() + "/captures/";
const std::string recordings_dir = fs::get_config_dir() + "/recordings/" + current_game.serial;
const std::string screenshots_dir = fs::get_config_dir() + "/screenshots/" + current_game.serial;
std::vector<std::string> data_dir_list;
if (is_disc_game)
{
QAction* open_disc_game_folder = open_folder_menu->addAction(tr("&Open Disc Game Folder"));
connect(open_disc_game_folder, &QAction::triggered, [current_game]()
{
gui::utils::open_dir(current_game.path);
});
data_dir_list = GetDirListBySerial(rpcs3::utils::get_hdd0_dir() + "game/", current_game.serial); // It could be absent for a disc game
}
else
{
data_dir_list.push_back(current_game.path);
}
if (!data_dir_list.empty()) // "true" if data path is present (it could be absent for a disc game)
{
QAction* open_data_folder = open_folder_menu->addAction(tr("&Open %0 Folder").arg(is_disc_game ? tr("Game Data") : gameinfo->localized_category));
connect(open_data_folder, &QAction::triggered, [data_dir_list]()
{
for (const std::string& data_dir : data_dir_list)
{
gui::utils::open_dir(data_dir);
}
});
}
if (gameinfo->hasCustomConfig)
{
QAction* open_config_dir = open_folder_menu->addAction(tr("&Open Custom Config Folder"));
connect(open_config_dir, &QAction::triggered, [current_game]()
{
const std::string config_path = rpcs3::utils::get_custom_config_path(current_game.serial);
if (fs::is_file(config_path))
gui::utils::open_dir(config_path);
});
}
// This is a debug feature, let's hide it by reusing debug tab protection
if (m_gui_settings->GetValue(gui::m_showDebugTab).toBool() && has_cache_dir)
{
QAction* open_cache_folder = open_folder_menu->addAction(tr("&Open Cache Folder"));
connect(open_cache_folder, &QAction::triggered, [cache_base_dir]()
{
gui::utils::open_dir(cache_base_dir);
});
}
if (fs::is_dir(config_data_base_dir))
{
QAction* open_config_data_dir = open_folder_menu->addAction(tr("&Open Config Data Folder"));
connect(open_config_data_dir, &QAction::triggered, [config_data_base_dir]()
{
gui::utils::open_dir(config_data_base_dir);
});
}
if (fs::is_dir(savestate_dir))
{
QAction* open_savestate_dir = open_folder_menu->addAction(tr("&Open Savestate Folder"));
connect(open_savestate_dir, &QAction::triggered, [savestate_dir]()
{
gui::utils::open_dir(savestate_dir);
});
}
QAction* open_captures_dir = open_folder_menu->addAction(tr("&Open Captures Folder"));
connect(open_captures_dir, &QAction::triggered, [captures_dir]()
{
gui::utils::open_dir(captures_dir);
});
if (fs::is_dir(recordings_dir))
{
QAction* open_recordings_dir = open_folder_menu->addAction(tr("&Open Recordings Folder"));
connect(open_recordings_dir, &QAction::triggered, [recordings_dir]()
{
gui::utils::open_dir(recordings_dir);
});
}
if (fs::is_dir(screenshots_dir))
{
QAction* open_screenshots_dir = open_folder_menu->addAction(tr("&Open Screenshots Folder"));
connect(open_screenshots_dir, &QAction::triggered, [screenshots_dir]()
{
gui::utils::open_dir(screenshots_dir);
});
}
// Copy Info menu
QMenu* info_menu = menu.addMenu(tr("&Copy Info"));
QAction* copy_info = info_menu->addAction(tr("&Copy Name + Serial"));
QAction* copy_name = info_menu->addAction(tr("&Copy Name"));
QAction* copy_serial = info_menu->addAction(tr("&Copy Serial"));
menu.addSeparator();
QAction* check_compat = menu.addAction(tr("&Check Game Compatibility"));
QAction* download_compat = menu.addAction(tr("&Download Compatibility Database"));
connect(boot, &QAction::triggered, this, [this, gameinfo]()
{
sys_log.notice("Booting from gamelist per context menu...");
Q_EMIT RequestBoot(gameinfo, cfg_mode::global);
});
auto configure_l = [this, current_game, gameinfo](bool create_cfg_from_global_cfg)
{
settings_dialog dlg(m_gui_settings, m_emu_settings, 0, this, ¤t_game, create_cfg_from_global_cfg);
connect(&dlg, &settings_dialog::EmuSettingsApplied, [this, gameinfo]()
{
if (!gameinfo->hasCustomConfig)
{
gameinfo->hasCustomConfig = true;
ShowCustomConfigIcon(gameinfo);
}
Q_EMIT NotifyEmuSettingsChange();
});
dlg.exec();
};
if (create_game_default_config)
{
connect(configure, &QAction::triggered, this, [configure_l]() { configure_l(true); });
connect(create_game_default_config, &QAction::triggered, this, [configure_l = std::move(configure_l)]() { configure_l(false); });
}
else
{
connect(configure, &QAction::triggered, this, [configure_l = std::move(configure_l)]() { configure_l(true); });
}
connect(pad_configure, &QAction::triggered, this, [this, current_game, gameinfo]()
{
pad_settings_dialog dlg(m_gui_settings, this, ¤t_game);
if (dlg.exec() == QDialog::Accepted && !gameinfo->hasCustomPadConfig)
{
gameinfo->hasCustomPadConfig = true;
ShowCustomConfigIcon(gameinfo);
}
});
connect(hide_serial, &QAction::triggered, this, [serial, this](bool checked)
{
if (checked)
m_hidden_list.insert(serial);
else
m_hidden_list.remove(serial);
m_gui_settings->SetValue(gui::gl_hidden_list, QStringList(m_hidden_list.values()));
Refresh();
});
connect(create_cpu_cache, &QAction::triggered, this, [gameinfo, this]
{
if (m_gui_settings->GetBootConfirmation(this))
{
CreateCPUCaches(gameinfo);
}
});
connect(remove_game, &QAction::triggered, this, [this, current_game, gameinfo, cache_base_dir, hdd1_cache_base_dir, name]
{
if (is_game_running(current_game.serial))
{
QMessageBox::critical(this, tr("Cannot Remove Game"), tr("The PS3 application is still running, it cannot be removed!"));
return;
}
const bool is_disc_game = qstr(current_game.category) == cat::cat_disc_game;
const bool is_in_games_dir = is_disc_game && Emu.IsPathInsideDir(current_game.path, rpcs3::utils::get_games_dir());
std::vector<std::string> data_dir_list;
if (is_disc_game)
{
data_dir_list = GetDirListBySerial(rpcs3::utils::get_hdd0_dir() + "game/", current_game.serial);
}
else
{
data_dir_list.push_back(current_game.path);
}
const bool has_data_dir = !data_dir_list.empty(); // "true" if data path is present (it could be absent for a disc game)
QString text = tr("%0 - %1\n").arg(qstr(current_game.serial)).arg(name);
if (is_disc_game)
{
text += tr("\nDisc Game Info:\nPath: %0\n").arg(qstr(current_game.path));
if (current_game.size_on_disk != umax) // If size was properly detected
{
text += tr("Size: %0\n").arg(gui::utils::format_byte_size(current_game.size_on_disk));
}
}
if (has_data_dir)
{
u64 total_data_size = 0;
text += tr("\n%0 Info:\n").arg(is_disc_game ? tr("Game Data") : gameinfo->localized_category);
for (const std::string& data_dir : data_dir_list)
{
text += tr("Path: %0\n").arg(qstr(data_dir));
if (const u64 data_size = fs::get_dir_size(data_dir, 1); data_size != umax) // If size was properly detected
{
total_data_size += data_size;
text += tr("Size: %0\n").arg(gui::utils::format_byte_size(data_size));
}
}
if (data_dir_list.size() > 1)
{
text += tr("Total size: %0\n").arg(gui::utils::format_byte_size(total_data_size));
}
}
if (fs::device_stat stat{}; fs::statfs(rpcs3::utils::get_hdd0_dir(), stat)) // Retrieve disk space info on data path's drive
{
text += tr("\nCurrent free disk space: %0\n").arg(gui::utils::format_byte_size(stat.avail_free));
}
if (has_data_dir)
{
text += tr("\nPermanently remove %0 and selected (optional) contents from drive?\n").arg(is_disc_game ? tr("Game Data") : gameinfo->localized_category);
}
else
{
text += tr("\nPermanently remove selected (optional) contents from drive?\n");
}
QMessageBox mb(QMessageBox::Question, tr("Confirm %0 Removal").arg(gameinfo->localized_category), text, QMessageBox::Yes | QMessageBox::No, this);
QCheckBox* disc = new QCheckBox(tr("Remove title from game list (Disc Game path is not removed!)"));
QCheckBox* caches = new QCheckBox(tr("Remove caches and custom configs"));
QCheckBox* icons = new QCheckBox(tr("Remove icons and shortcuts"));
QCheckBox* savestate = new QCheckBox(tr("Remove savestate"));
QCheckBox* captures = new QCheckBox(tr("Remove captures"));
QCheckBox* recordings = new QCheckBox(tr("Remove recordings"));
QCheckBox* screenshots = new QCheckBox(tr("Remove screenshots"));
if (is_disc_game)
{
if (is_in_games_dir)
{
disc->setToolTip(tr("Title located under auto-detection \"games\" folder cannot be removed"));
disc->setDisabled(true);
}
else
{
disc->setChecked(true);
}
}
else
{
disc->setVisible(false);
}
caches->setChecked(true);
icons->setChecked(true);
mb.setCheckBox(disc);
QGridLayout* grid = qobject_cast<QGridLayout*>(mb.layout());
int row, column, rowSpan, columnSpan;
grid->getItemPosition(grid->indexOf(disc), &row, &column, &rowSpan, &columnSpan);
grid->addWidget(caches, row + 3, column, rowSpan, columnSpan);
grid->addWidget(icons, row + 4, column, rowSpan, columnSpan);
grid->addWidget(savestate, row + 5, column, rowSpan, columnSpan);
grid->addWidget(captures, row + 6, column, rowSpan, columnSpan);
grid->addWidget(recordings, row + 7, column, rowSpan, columnSpan);
grid->addWidget(screenshots, row + 8, column, rowSpan, columnSpan);
if (mb.exec() == QMessageBox::Yes)
{
const bool remove_caches = caches->isChecked();
// Remove data path in "dev_hdd0/game" folder (if any)
if (has_data_dir && RemoveContentPathList(data_dir_list, gameinfo->localized_category.toStdString()) != data_dir_list.size())
{
QMessageBox::critical(this, tr("Failure!"), remove_caches
? tr("Failed to remove %0 from drive!\nPath: %1\nCaches and custom configs have been left intact.").arg(name).arg(qstr(data_dir_list[0]))
: tr("Failed to remove %0 from drive!\nPath: %1").arg(name).arg(qstr(data_dir_list[0])));
return;
}
// Remove lock file in "dev_hdd0/game/$locks" folder (if any)
RemoveContentBySerial(rpcs3::utils::get_hdd0_dir() + "game/$locks/", current_game.serial, "lock");
// Remove caches in "cache" and "dev_hdd1/caches" folders (if any) and custom configs in "config/custom_config" folder (if any)
if (remove_caches)
{
RemoveContentPath(cache_base_dir, "cache");
RemoveHDD1Cache(hdd1_cache_base_dir, current_game.serial);
RemoveCustomConfiguration(current_game.serial);
RemoveCustomPadConfiguration(current_game.serial);
}
// Remove icons in "Icons/game_icons" folder, shortcuts in "games/shortcuts" folder and from desktop/start menu
if (icons->isChecked())
{
RemoveContentBySerial(fs::get_config_dir() + "Icons/game_icons/", current_game.serial, "icons");
RemoveContentBySerial(fs::get_config_dir() + "games/shortcuts/", name.toStdString() + ".lnk", "link");
// TODO: Remove shortcuts from desktop/start menu
}
if (savestate->isChecked())
{
RemoveContentBySerial(fs::get_config_dir() + "savestates/", current_game.serial, "savestate");
}
if (captures->isChecked())
{
RemoveContentBySerial(fs::get_config_dir() + "captures/", current_game.serial, "captures");
}
if (recordings->isChecked())
{
RemoveContentBySerial(fs::get_config_dir() + "recordings/", current_game.serial, "recordings");
}
if (screenshots->isChecked())
{
RemoveContentBySerial(fs::get_config_dir() + "screenshots/", current_game.serial, "screenshots");
}
m_game_data.erase(std::remove(m_game_data.begin(), m_game_data.end(), gameinfo), m_game_data.end());
game_list_log.success("Removed %s - %s", gameinfo->localized_category, current_game.name);
std::vector<std::string> serials_to_remove_from_yml{};
// Prepare list of serials (title id) to remove in "games.yml" file (if any)
if (is_disc_game && disc->isChecked())
{
serials_to_remove_from_yml.push_back(current_game.serial);
}
// Finally, refresh the game list.
// Hidden list in "GuiConfigs/CurrentSettings.ini" file is also properly updated (title removed) if needed
Refresh(true, serials_to_remove_from_yml);
}
});
connect(configure_patches, &QAction::triggered, this, [this, gameinfo]()
{
std::unordered_map<std::string, std::set<std::string>> games;
for (const auto& game : m_game_data)
{
if (game)
{
games[game->info.serial].insert(game_list::GetGameVersion(game));
}
}
patch_manager_dialog patch_manager(m_gui_settings, games, gameinfo->info.serial, game_list::GetGameVersion(gameinfo), this);
patch_manager.exec();
});
connect(check_compat, &QAction::triggered, this, [serial]
{
const QString link = "https://rpcs3.net/compatibility?g=" + serial;
QDesktopServices::openUrl(QUrl(link));
});
connect(download_compat, &QAction::triggered, this, [this]
{
m_game_compat->RequestCompatibility(true);
});
connect(rename_title, &QAction::triggered, this, [this, name, serial, global_pos]
{
const QString custom_title = m_persistent_settings->GetValue(gui::persistent::titles, serial, "").toString();
const QString old_title = custom_title.isEmpty() ? name : custom_title;
input_dialog dlg(128, old_title, tr("Rename Title"), tr("%0\n%1\n\nYou can clear the line in order to use the original title.").arg(name).arg(serial), name, this);
dlg.move(global_pos);
if (dlg.exec() == QDialog::Accepted)
{
const QString new_title = dlg.get_input_text().simplified();
if (new_title.isEmpty() || new_title == name)
{
m_titles.erase(serial);
m_persistent_settings->RemoveValue(gui::persistent::titles, serial);
}
else
{
m_titles.insert_or_assign(serial, new_title);
m_persistent_settings->SetValue(gui::persistent::titles, serial, new_title);
}
Refresh(true); // full refresh in order to reliably sort the list
}
});
connect(edit_notes, &QAction::triggered, this, [this, name, serial]
{
bool accepted;
const QString old_notes = m_persistent_settings->GetValue(gui::persistent::notes, serial, "").toString();
const QString new_notes = QInputDialog::getMultiLineText(this, tr("Edit Tooltip Notes"), tr("%0\n%1").arg(name).arg(serial), old_notes, &accepted);
if (accepted)
{
if (new_notes.simplified().isEmpty())
{
m_notes.erase(serial);
m_persistent_settings->RemoveValue(gui::persistent::notes, serial);
}
else
{
m_notes.insert_or_assign(serial, new_notes);
m_persistent_settings->SetValue(gui::persistent::notes, serial, new_notes);
}
Refresh();
}
});
connect(reset_time_played, &QAction::triggered, this, [this, name, serial]
{
if (QMessageBox::question(this, tr("Confirm Reset"), tr("Reset time played?\n\n%0 [%1]").arg(name).arg(serial)) == QMessageBox::Yes)
{
m_persistent_settings->SetPlaytime(serial, 0, false);
m_persistent_settings->SetLastPlayed(serial, 0, true);
Refresh();
}
});
connect(copy_info, &QAction::triggered, this, [name, serial]
{
QApplication::clipboard()->setText(name % QStringLiteral(" [") % serial % QStringLiteral("]"));
});
connect(copy_name, &QAction::triggered, this, [name]
{
QApplication::clipboard()->setText(name);
});
connect(copy_serial, &QAction::triggered, this, [serial]
{
QApplication::clipboard()->setText(serial);
});
// Disable options depending on software category
const QString category = qstr(current_game.category);
if (category == cat::cat_ps3_os)
{
remove_game->setEnabled(false);
}
else if (category != cat::cat_disc_game && category != cat::cat_hdd_game)
{
check_compat->setEnabled(false);
}
menu.exec(global_pos);
}
bool game_list_frame::CreateCPUCaches(const std::string& path, const std::string& serial)
{
Emu.GracefulShutdown(false);
Emu.SetForceBoot(true);
if (const auto error = Emu.BootGame(fs::is_file(path) ? fs::get_parent_dir(path) : path, serial, true); error != game_boot_result::no_errors)
{
game_list_log.error("Could not create LLVM caches for %s, error: %s", path, error);
return false;
}
game_list_log.warning("Creating LLVM Caches for %s", path);
return true;
}
bool game_list_frame::CreateCPUCaches(const game_info& game)
{
return game && CreateCPUCaches(game->info.path, game->info.serial);
}
bool game_list_frame::RemoveCustomConfiguration(const std::string& title_id, const game_info& game, bool is_interactive)
{
const std::string path = rpcs3::utils::get_custom_config_path(title_id);
if (!fs::is_file(path))
return true;
if (is_interactive && QMessageBox::question(this, tr("Confirm Removal"), tr("Remove custom game configuration?")) != QMessageBox::Yes)
return true;
bool result = true;
if (fs::is_file(path))
{
if (fs::remove_file(path))
{
if (game)
{
game->hasCustomConfig = false;
}
game_list_log.success("Removed configuration file: %s", path);
}
else
{
game_list_log.fatal("Failed to remove configuration file: %s\nError: %s", path, fs::g_tls_error);
result = false;
}
}
if (is_interactive && !result)
{
QMessageBox::warning(this, tr("Warning!"), tr("Failed to remove configuration file!"));
}
return result;
}
bool game_list_frame::RemoveCustomPadConfiguration(const std::string& title_id, const game_info& game, bool is_interactive)
{
if (title_id.empty())
return true;
const std::string config_dir = rpcs3::utils::get_input_config_dir(title_id);
if (!fs::is_dir(config_dir))
return true;
if (is_interactive && QMessageBox::question(this, tr("Confirm Removal"), (!Emu.IsStopped() && Emu.GetTitleID() == title_id)
? tr("Remove custom pad configuration?\nYour configuration will revert to the global pad settings.")
: tr("Remove custom pad configuration?")) != QMessageBox::Yes)
return true;
g_cfg_input_configs.load();
g_cfg_input_configs.active_configs.erase(title_id);
g_cfg_input_configs.save();
game_list_log.notice("Removed active input configuration entry for key '%s'", title_id);
if (QDir(qstr(config_dir)).removeRecursively())
{
if (game)
{
game->hasCustomPadConfig = false;
}
if (!Emu.IsStopped() && Emu.GetTitleID() == title_id)
{
pad::set_enabled(false);
pad::reset(title_id);
pad::set_enabled(true);
}
game_list_log.notice("Removed pad configuration directory: %s", config_dir);
return true;
}
if (is_interactive)
{
QMessageBox::warning(this, tr("Warning!"), tr("Failed to completely remove pad configuration directory!"));
game_list_log.fatal("Failed to completely remove pad configuration directory: %s\nError: %s", config_dir, fs::g_tls_error);
}
return false;
}
bool game_list_frame::RemoveShadersCache(const std::string& base_dir, bool is_interactive)
{
if (!fs::is_dir(base_dir))
return true;
if (is_interactive && QMessageBox::question(this, tr("Confirm Removal"), tr("Remove shaders cache?")) != QMessageBox::Yes)
return true;
u32 caches_removed = 0;
u32 caches_total = 0;
const QStringList filter{ QStringLiteral("shaders_cache") };
const QString q_base_dir = qstr(base_dir);
QDirIterator dir_iter(q_base_dir, filter, QDir::Dirs | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
while (dir_iter.hasNext())
{
const QString filepath = dir_iter.next();
if (QDir(filepath).removeRecursively())
{
++caches_removed;
game_list_log.notice("Removed shaders cache dir: %s", filepath);
}
else
{
game_list_log.warning("Could not completely remove shaders cache dir: %s", filepath);
}
++caches_total;
}
const bool success = caches_total == caches_removed;
if (success)
game_list_log.success("Removed shaders cache in %s", base_dir);
else
game_list_log.fatal("Only %d/%d shaders cache dirs could be removed in %s", caches_removed, caches_total, base_dir);
if (QDir(q_base_dir).isEmpty())
{
if (fs::remove_dir(base_dir))
game_list_log.notice("Removed empty shader cache directory: %s", base_dir);
else
game_list_log.error("Could not remove empty shader cache directory: '%s' (%s)", base_dir, fs::g_tls_error);
}
return success;
}
bool game_list_frame::RemovePPUCache(const std::string& base_dir, bool is_interactive)
{
if (!fs::is_dir(base_dir))
return true;
if (is_interactive && QMessageBox::question(this, tr("Confirm Removal"), tr("Remove PPU cache?")) != QMessageBox::Yes)
return true;
u32 files_removed = 0;
u32 files_total = 0;
const QStringList filter{ QStringLiteral("v*.obj"), QStringLiteral("v*.obj.gz") };
const QString q_base_dir = qstr(base_dir);
QDirIterator dir_iter(q_base_dir, filter, QDir::Files | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
while (dir_iter.hasNext())
{
const QString filepath = dir_iter.next();
if (QFile::remove(filepath))
{
++files_removed;
game_list_log.notice("Removed PPU cache file: %s", filepath);
}
else
{
game_list_log.warning("Could not remove PPU cache file: %s", filepath);
}
++files_total;
}
const bool success = files_total == files_removed;
if (success)
game_list_log.success("Removed PPU cache in %s", base_dir);
else
game_list_log.fatal("Only %d/%d PPU cache files could be removed in %s", files_removed, files_total, base_dir);
if (QDir(q_base_dir).isEmpty())
{
if (fs::remove_dir(base_dir))
game_list_log.notice("Removed empty PPU cache directory: %s", base_dir);
else
game_list_log.error("Could not remove empty PPU cache directory: '%s' (%s)", base_dir, fs::g_tls_error);
}
return success;
}
bool game_list_frame::RemoveSPUCache(const std::string& base_dir, bool is_interactive)
{
if (!fs::is_dir(base_dir))
return true;
if (is_interactive && QMessageBox::question(this, tr("Confirm Removal"), tr("Remove SPU cache?")) != QMessageBox::Yes)
return true;
u32 files_removed = 0;
u32 files_total = 0;
const QStringList filter{ QStringLiteral("spu*.dat"), QStringLiteral("spu*.dat.gz"), QStringLiteral("spu*.obj"), QStringLiteral("spu*.obj.gz") };
const QString q_base_dir = qstr(base_dir);
QDirIterator dir_iter(q_base_dir, filter, QDir::Files | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);
while (dir_iter.hasNext())
{
const QString filepath = dir_iter.next();
if (QFile::remove(filepath))
{
++files_removed;
game_list_log.notice("Removed SPU cache file: %s", filepath);
}
else
{
game_list_log.warning("Could not remove SPU cache file: %s", filepath);
}
++files_total;
}
const bool success = files_total == files_removed;
if (success)
game_list_log.success("Removed SPU cache in %s", base_dir);
else
game_list_log.fatal("Only %d/%d SPU cache files could be removed in %s", files_removed, files_total, base_dir);
if (QDir(q_base_dir).isEmpty())
{
if (fs::remove_dir(base_dir))
game_list_log.notice("Removed empty SPU cache directory: %s", base_dir);
else
game_list_log.error("Could not remove empty SPU cache directory: '%s' (%s)", base_dir, fs::g_tls_error);
}
return success;
}
void game_list_frame::RemoveHDD1Cache(const std::string& base_dir, const std::string& title_id, bool is_interactive)
{
if (!fs::is_dir(base_dir))
return;
if (is_interactive && QMessageBox::question(this, tr("Confirm Removal"), tr("Remove HDD1 cache?")) != QMessageBox::Yes)
return;
u32 dirs_removed = 0;
u32 dirs_total = 0;
const QString q_base_dir = qstr(base_dir);
const QStringList filter{ qstr(title_id + "_*") };
QDirIterator dir_iter(q_base_dir, filter, QDir::Dirs | QDir::NoDotAndDotDot);
while (dir_iter.hasNext())
{
const QString filepath = dir_iter.next();
if (fs::remove_all(filepath.toStdString()))
{
++dirs_removed;
game_list_log.notice("Removed HDD1 cache directory: %s", filepath);
}
else
{
game_list_log.warning("Could not remove HDD1 cache directory: %s", filepath);
}
++dirs_total;
}
const bool success = dirs_removed == dirs_total;
if (success)
game_list_log.success("Removed HDD1 cache in %s (%s)", base_dir, title_id);
else
game_list_log.fatal("Only %d/%d HDD1 cache directories could be removed in %s (%s)", dirs_removed, dirs_total, base_dir, title_id);
}
void game_list_frame::BatchCreateCPUCaches(const std::vector<game_info>& game_data)
{
const std::string vsh_path = g_cfg_vfs.get_dev_flash() + "vsh/module/";
const bool vsh_exists = game_data.empty() && fs::is_file(vsh_path + "vsh.self");
const usz total = !game_data.empty() ? game_data.size() : (m_game_data.size() + (vsh_exists ? 1 : 0));
if (total == 0)
{
QMessageBox::information(this, tr("LLVM Cache Batch Creation"), tr("No titles found"), QMessageBox::Ok);
return;
}
if (!m_gui_settings->GetBootConfirmation(this))
{
return;
}
const QString main_label = tr("Creating all LLVM caches");
progress_dialog* pdlg = new progress_dialog(tr("LLVM Cache Batch Creation"), main_label, tr("Cancel"), 0, ::narrow<s32>(total), false, this);
pdlg->setWindowFlags(Qt::Window | Qt::WindowMinimizeButtonHint);
pdlg->setAutoClose(false);
pdlg->setAutoReset(false);
pdlg->show();
QApplication::processEvents();
u32 created = 0;
const auto wait_until_compiled = [pdlg]() -> bool
{
while (!Emu.IsStopped())
{
if (pdlg->wasCanceled())
{
return false;
}
QApplication::processEvents();
}
return true;
};
if (vsh_exists)
{
pdlg->setLabelText(tr("%0\nProgress: %1/%2. Compiling caches for VSH...", "Second line after main label").arg(main_label).arg(created).arg(total));
QApplication::processEvents();
if (CreateCPUCaches(vsh_path) && wait_until_compiled())
{
pdlg->SetValue(++created);
}
}
for (const auto& game : (game_data.empty() ? m_game_data : game_data))
{
if (pdlg->wasCanceled() || g_system_progress_canceled)
{
break;
}
pdlg->setLabelText(tr("%0\nProgress: %1/%2. Compiling caches for %3...", "Second line after main label").arg(main_label).arg(created).arg(total).arg(qstr(game->info.serial)));
QApplication::processEvents();
if (CreateCPUCaches(game) && wait_until_compiled())
{
pdlg->SetValue(++created);
}
}
if (pdlg->wasCanceled() || g_system_progress_canceled)
{
pdlg->deleteLater(); // We did not allow deletion earlier to prevent segfaults when canceling.
game_list_log.notice("LLVM Cache Batch Creation was canceled");
Emu.GracefulShutdown(false);
}
else
{
pdlg->SetDeleteOnClose();
pdlg->setLabelText(tr("Created LLVM Caches for %n title(s)", "", created));
pdlg->setCancelButtonText(tr("OK"));
QApplication::beep();
}
}
void game_list_frame::BatchRemovePPUCaches()
{
if (Emu.GetStatus(false) != system_state::stopped)
{
return;
}
std::set<std::string> serials;
serials.emplace("vsh");
for (const auto& game : m_game_data)
{
serials.emplace(game->info.serial);
}
const u32 total = ::size32(serials);
if (total == 0)
{
QMessageBox::information(this, tr("PPU Cache Batch Removal"), tr("No files found"), QMessageBox::Ok);
return;
}
progress_dialog* pdlg = new progress_dialog(tr("PPU Cache Batch Removal"), tr("Removing all PPU caches"), tr("Cancel"), 0, total, false, this);
pdlg->setAutoClose(false);
pdlg->setAutoReset(false);
pdlg->show();
u32 removed = 0;
for (const auto& serial : serials)
{
if (pdlg->wasCanceled())
{
break;
}
QApplication::processEvents();
if (RemovePPUCache(GetCacheDirBySerial(serial)))
{
pdlg->SetValue(++removed);
}
}
if (pdlg->wasCanceled())
{
pdlg->deleteLater(); // We did not allow deletion earlier to prevent segfaults when canceling.
game_list_log.notice("PPU Cache Batch Removal was canceled");
}
else
{
pdlg->SetDeleteOnClose();
pdlg->setLabelText(tr("%0/%1 caches cleared").arg(removed).arg(total));
pdlg->setCancelButtonText(tr("OK"));
QApplication::beep();
}
}
void game_list_frame::BatchRemoveSPUCaches()
{
if (Emu.GetStatus(false) != system_state::stopped)
{
return;
}
std::set<std::string> serials;
serials.emplace("vsh");
for (const auto& game : m_game_data)
{
serials.emplace(game->info.serial);
}
const u32 total = ::size32(serials);
if (total == 0)
{
QMessageBox::information(this, tr("SPU Cache Batch Removal"), tr("No files found"), QMessageBox::Ok);
return;
}
progress_dialog* pdlg = new progress_dialog(tr("SPU Cache Batch Removal"), tr("Removing all SPU caches"), tr("Cancel"), 0, total, false, this);
pdlg->setAutoClose(false);
pdlg->setAutoReset(false);
pdlg->show();
u32 removed = 0;
for (const auto& serial : serials)
{
if (pdlg->wasCanceled())
{
break;
}
QApplication::processEvents();
if (RemoveSPUCache(GetCacheDirBySerial(serial)))
{
pdlg->SetValue(++removed);
}
}
if (pdlg->wasCanceled())
{
pdlg->deleteLater(); // We did not allow deletion earlier to prevent segfaults when canceling.
game_list_log.notice("SPU Cache Batch Removal was canceled. %d/%d folders cleared", removed, total);
}
else
{
pdlg->SetDeleteOnClose();
pdlg->setLabelText(tr("%0/%1 caches cleared").arg(removed).arg(total));
pdlg->setCancelButtonText(tr("OK"));
QApplication::beep();
}
}
void game_list_frame::BatchRemoveCustomConfigurations()
{
std::set<std::string> serials;
for (const auto& game : m_game_data)
{
if (game->hasCustomConfig && !serials.count(game->info.serial))
{
serials.emplace(game->info.serial);
}
}
const u32 total = ::size32(serials);
if (total == 0)
{
QMessageBox::information(this, tr("Custom Configuration Batch Removal"), tr("No files found"), QMessageBox::Ok);
return;
}
progress_dialog* pdlg = new progress_dialog(tr("Custom Configuration Batch Removal"), tr("Removing all custom configurations"), tr("Cancel"), 0, total, false, this);
pdlg->setAutoClose(false);
pdlg->setAutoReset(false);
pdlg->show();
u32 removed = 0;
for (const auto& serial : serials)
{
if (pdlg->wasCanceled())
{
break;
}
QApplication::processEvents();
if (RemoveCustomConfiguration(serial))
{
pdlg->SetValue(++removed);
}
}
if (pdlg->wasCanceled())
{
pdlg->deleteLater(); // We did not allow deletion earlier to prevent segfaults when canceling.
game_list_log.notice("Custom Configuration Batch Removal was canceled. %d/%d custom configurations cleared", removed, total);
}
else
{
pdlg->SetDeleteOnClose();
pdlg->setLabelText(tr("%0/%1 custom configurations cleared").arg(removed).arg(total));
pdlg->setCancelButtonText(tr("OK"));
QApplication::beep();
}
Refresh(true);
}
void game_list_frame::BatchRemoveCustomPadConfigurations()
{
std::set<std::string> serials;
for (const auto& game : m_game_data)
{
if (game->hasCustomPadConfig && !serials.count(game->info.serial))
{
serials.emplace(game->info.serial);
}
}
const u32 total = ::size32(serials);
if (total == 0)
{
QMessageBox::information(this, tr("Custom Pad Configuration Batch Removal"), tr("No files found"), QMessageBox::Ok);
return;
}
progress_dialog* pdlg = new progress_dialog(tr("Custom Pad Configuration Batch Removal"), tr("Removing all custom pad configurations"), tr("Cancel"), 0, total, false, this);
pdlg->setAutoClose(false);
pdlg->setAutoReset(false);
pdlg->show();
u32 removed = 0;
for (const auto& serial : serials)
{
if (pdlg->wasCanceled())
{
break;
}
QApplication::processEvents();
if (RemoveCustomPadConfiguration(serial))
{
pdlg->SetValue(++removed);
}
}
if (pdlg->wasCanceled())
{
pdlg->deleteLater(); // We did not allow deletion earlier to prevent segfaults when canceling.
game_list_log.notice("Custom Pad Configuration Batch Removal was canceled. %d/%d custom pad configurations cleared", removed, total);
}
else
{
pdlg->SetDeleteOnClose();
pdlg->setLabelText(tr("%0/%1 custom pad configurations cleared").arg(removed).arg(total));
pdlg->setCancelButtonText(tr("OK"));
QApplication::beep();
}
Refresh(true);
}
void game_list_frame::BatchRemoveShaderCaches()
{
if (Emu.GetStatus(false) != system_state::stopped)
{
return;
}
std::set<std::string> serials;
serials.emplace("vsh");
for (const auto& game : m_game_data)
{
serials.emplace(game->info.serial);
}
const u32 total = ::size32(serials);
if (total == 0)
{
QMessageBox::information(this, tr("Shader Cache Batch Removal"), tr("No files found"), QMessageBox::Ok);
return;
}
progress_dialog* pdlg = new progress_dialog(tr("Shader Cache Batch Removal"), tr("Removing all shader caches"), tr("Cancel"), 0, total, false, this);
pdlg->setAutoClose(false);
pdlg->setAutoReset(false);
pdlg->show();
u32 removed = 0;
for (const auto& serial : serials)
{
if (pdlg->wasCanceled())
{
break;
}
QApplication::processEvents();
if (RemoveShadersCache(GetCacheDirBySerial(serial)))
{
pdlg->SetValue(++removed);
}
}
if (pdlg->wasCanceled())
{
pdlg->deleteLater(); // We did not allow deletion earlier to prevent segfaults when canceling.
game_list_log.notice("Shader Cache Batch Removal was canceled");
}
else
{
pdlg->SetDeleteOnClose();
pdlg->setLabelText(tr("%0/%1 shader caches cleared").arg(removed).arg(total));
pdlg->setCancelButtonText(tr("OK"));
QApplication::beep();
}
}
void game_list_frame::ShowCustomConfigIcon(const game_info& game)
{
if (!game)
{
return;
}
const std::string serial = game->info.serial;
const bool has_custom_config = game->hasCustomConfig;
const bool has_custom_pad_config = game->hasCustomPadConfig;
for (const auto& other_game : m_game_data)
{
if (other_game->info.serial == serial)
{
other_game->hasCustomConfig = has_custom_config;
other_game->hasCustomPadConfig = has_custom_pad_config;
}
}
m_game_list->set_custom_config_icon(game);
RepaintIcons();
}
void game_list_frame::ResizeIcons(const int& slider_pos)
{
m_icon_size_index = slider_pos;
m_icon_size = gui_settings::SizeFromSlider(slider_pos);
RepaintIcons();
}
void game_list_frame::RepaintIcons(const bool& from_settings)
{
gui::utils::stop_future_watcher(m_parsing_watcher, false);
gui::utils::stop_future_watcher(m_refresh_watcher, false);
WaitAndAbortRepaintThreads();
if (from_settings)
{
if (m_gui_settings->GetValue(gui::m_enableUIColors).toBool())
{
m_icon_color = m_gui_settings->GetValue(gui::gl_iconColor).value<QColor>();
}
else
{
m_icon_color = gui::utils::get_label_color("gamelist_icon_background_color", Qt::transparent, Qt::transparent);
}
}
if (m_is_list_layout)
{
m_game_list->repaint_icons(m_game_data, m_icon_color, m_icon_size, devicePixelRatioF());
}
else
{
m_game_grid->set_draw_compat_status_to_grid(m_draw_compat_status_to_grid);
m_game_grid->repaint_icons(m_game_data, m_icon_color, m_icon_size, devicePixelRatioF());
}
}
void game_list_frame::SetShowHidden(bool show)
{
m_show_hidden = show;
}
void game_list_frame::SetListMode(const bool& is_list)
{
m_old_layout_is_list = m_is_list_layout;
m_is_list_layout = is_list;
m_gui_settings->SetValue(gui::gl_listMode, is_list);
Refresh();
if (m_is_list_layout)
{
m_central_widget->setCurrentWidget(m_game_list);
}
else
{
m_central_widget->setCurrentWidget(m_game_grid);
}
}
void game_list_frame::SetSearchText(const QString& text)
{
m_search_text = text;
Refresh();
}
void game_list_frame::FocusAndSelectFirstEntryIfNoneIs()
{
if (m_is_list_layout)
{
if (m_game_list)
{
m_game_list->FocusAndSelectFirstEntryIfNoneIs();
}
}
else
{
if (m_game_grid)
{
m_game_grid->FocusAndSelectFirstEntryIfNoneIs();
}
}
}
void game_list_frame::closeEvent(QCloseEvent *event)
{
SaveSettings();
QDockWidget::closeEvent(event);
Q_EMIT GameListFrameClosed();
}
bool game_list_frame::eventFilter(QObject *object, QEvent *event)
{
// Zoom gamelist/gamegrid
if (event->type() == QEvent::Wheel && (object == m_game_list->verticalScrollBar() || object == m_game_grid->scroll_area()->verticalScrollBar()))
{
QWheelEvent* wheel_event = static_cast<QWheelEvent*>(event);
if (wheel_event->modifiers() & Qt::ControlModifier)
{
const QPoint num_steps = wheel_event->angleDelta() / 8 / 15; // http://doc.qt.io/qt-5/qwheelevent.html#pixelDelta
const int value = num_steps.y();
Q_EMIT RequestIconSizeChange(value);
return true;
}
}
else if (event->type() == QEvent::KeyPress && (object == m_game_list || object == m_game_grid))
{
QKeyEvent* key_event = static_cast<QKeyEvent*>(event);
if (key_event->modifiers() & Qt::ControlModifier)
{
if (key_event->key() == Qt::Key_Plus)
{
Q_EMIT RequestIconSizeChange(1);
return true;
}
if (key_event->key() == Qt::Key_Minus)
{
Q_EMIT RequestIconSizeChange(-1);
return true;
}
}
else if (!key_event->isAutoRepeat())
{
if (key_event->key() == Qt::Key_Enter || key_event->key() == Qt::Key_Return)
{
game_info gameinfo{};
if (object == m_game_list)
{
QTableWidgetItem* item = m_game_list->item(m_game_list->currentRow(), static_cast<int>(gui::game_list_columns::icon));
if (!item || !item->isSelected())
return false;
gameinfo = GetGameInfoFromItem(item);
}
else if (game_list_grid_item* item = static_cast<game_list_grid_item*>(m_game_grid->selected_item()))
{
gameinfo = item->game();
}
if (!gameinfo)
return false;
sys_log.notice("Booting from gamelist by pressing %s...", key_event->key() == Qt::Key_Enter ? "Enter" : "Return");
Q_EMIT RequestBoot(gameinfo);
return true;
}
}
}
return QDockWidget::eventFilter(object, event);
}
/**
* Returns false if the game should be hidden because it doesn't match search term in toolbar.
*/
bool game_list_frame::SearchMatchesApp(const QString& name, const QString& serial, bool fallback) const
{
if (!m_search_text.isEmpty())
{
QString search_text = m_search_text.toLower();
QString title_name;
if (const auto it = m_titles.find(serial); it != m_titles.cend())
{
title_name = it->second.toLower();
}
else
{
title_name = name.toLower();
}
// Ignore trademarks when no search results have been yielded by unmodified search
static const QRegularExpression s_ignored_on_fallback(reinterpret_cast<const char*>(u8"[:\\-®©™]+"));
if (fallback)
{
search_text = search_text.simplified();
title_name = title_name.simplified();
QString title_name_replaced_trademarks_with_spaces = title_name;
QString title_name_simplified = title_name;
search_text.remove(s_ignored_on_fallback);
title_name.remove(s_ignored_on_fallback);
title_name_replaced_trademarks_with_spaces.replace(s_ignored_on_fallback, " ");
// Before simplify to allow spaces in the beginning and end where ignored characters may have been
if (title_name_replaced_trademarks_with_spaces.contains(search_text))
{
return true;
}
title_name_replaced_trademarks_with_spaces = title_name_replaced_trademarks_with_spaces.simplified();
if (title_name_replaced_trademarks_with_spaces.contains(search_text))
{
return true;
}
// Initials-only search
if (search_text.size() >= 2 && search_text.count(QRegularExpression(QStringLiteral("[a-z0-9]"))) >= 2 && !search_text.contains(QRegularExpression(QStringLiteral("[^a-z0-9 ]"))))
{
QString initials = QStringLiteral("\\b");
for (auto it = search_text.begin(); it != search_text.end(); it++)
{
if (it->isSpace())
{
continue;
}
initials += *it;
initials += QStringLiteral("\\w*\\b ");
}
initials += QChar('?');
if (title_name_replaced_trademarks_with_spaces.contains(QRegularExpression(initials)))
{
return true;
}
}
}
return title_name.contains(search_text) || serial.toLower().contains(search_text);
}
return true;
}
std::string game_list_frame::CurrentSelectionPath()
{
std::string selection;
game_info game{};
if (m_old_layout_is_list)
{
if (!m_game_list->selectedItems().isEmpty())
{
if (QTableWidgetItem* item = m_game_list->item(m_game_list->currentRow(), 0))
{
if (const QVariant var = item->data(gui::game_role); var.canConvert<game_info>())
{
game = var.value<game_info>();
}
}
}
}
else if (m_game_grid)
{
if (game_list_grid_item* item = static_cast<game_list_grid_item*>(m_game_grid->selected_item()))
{
game = item->game();
}
}
if (game)
{
selection = game->info.path + game->info.icon_path;
}
m_old_layout_is_list = m_is_list_layout;
return selection;
}
game_info game_list_frame::GetGameInfoByMode(const QTableWidgetItem* item) const
{
if (!item)
{
return nullptr;
}
if (m_is_list_layout)
{
return GetGameInfoFromItem(m_game_list->item(item->row(), static_cast<int>(gui::game_list_columns::icon)));
}
return GetGameInfoFromItem(item);
}
game_info game_list_frame::GetGameInfoFromItem(const QTableWidgetItem* item)
{
if (!item)
{
return nullptr;
}
const QVariant var = item->data(gui::game_role);
if (!var.canConvert<game_info>())
{
return nullptr;
}
return var.value<game_info>();
}
void game_list_frame::SetShowCompatibilityInGrid(bool show)
{
m_draw_compat_status_to_grid = show;
RepaintIcons();
m_gui_settings->SetValue(gui::gl_draw_compat, show);
}
void game_list_frame::SetShowCustomIcons(bool show)
{
if (m_show_custom_icons != show)
{
m_show_custom_icons = show;
m_gui_settings->SetValue(gui::gl_custom_icon, show);
Refresh(true);
}
}
void game_list_frame::SetPlayHoverGifs(bool play)
{
if (m_play_hover_movies != play)
{
m_play_hover_movies = play;
m_gui_settings->SetValue(gui::gl_hover_gifs, play);
Refresh(true);
}
}
const std::vector<game_info>& game_list_frame::GetGameInfo() const
{
return m_game_data;
}
void game_list_frame::WaitAndAbortRepaintThreads()
{
for (const game_info& game : m_game_data)
{
if (game && game->item)
{
game->item->wait_for_icon_loading(true);
}
}
}
void game_list_frame::WaitAndAbortSizeCalcThreads()
{
for (const game_info& game : m_game_data)
{
if (game && game->item)
{
game->item->wait_for_size_on_disk_loading(true);
}
}
}
| 91,522
|
C++
|
.cpp
| 2,552
| 32.757445
| 287
| 0.696173
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,087
|
gs_frame.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/gs_frame.cpp
|
#include "gs_frame.h"
#include "gui_settings.h"
#include "Utilities/Config.h"
#include "Utilities/Timer.h"
#include "Utilities/date_time.h"
#include "Utilities/File.h"
#include "util/video_provider.h"
#include "Emu/System.h"
#include "Emu/system_config.h"
#include "Emu/system_progress.hpp"
#include "Emu/IdManager.h"
#include "Emu/Cell/Modules/cellScreenshot.h"
#include "Emu/Cell/Modules/cellVideoOut.h"
#include "Emu/Cell/Modules/cellAudio.h"
#include "Emu/Cell/lv2/sys_rsxaudio.h"
#include "Emu/RSX/rsx_utils.h"
#include "Emu/RSX/Overlays/overlay_message.h"
#include "Emu/Io/interception.h"
#include "Emu/Io/recording_config.h"
#include <QApplication>
#include <QDateTime>
#include <QKeyEvent>
#include <QMessageBox>
#include <QPainter>
#include <QScreen>
#include <string>
#include <thread>
#include "png.h"
#ifdef _WIN32
#include <windows.h>
#elif defined(__APPLE__)
//nothing
#else
#ifdef HAVE_WAYLAND
#include <QGuiApplication>
#include <qpa/qplatformnativeinterface.h>
#endif
#ifdef HAVE_X11
#include <X11/Xlib.h>
#endif
#endif
LOG_CHANNEL(screenshot_log, "SCREENSHOT");
LOG_CHANNEL(mark_log, "MARK");
LOG_CHANNEL(gui_log, "GUI");
extern atomic_t<bool> g_user_asked_for_recording;
extern atomic_t<bool> g_user_asked_for_screenshot;
extern atomic_t<bool> g_user_asked_for_frame_capture;
extern atomic_t<bool> g_disable_frame_limit;
extern atomic_t<recording_mode> g_recording_mode;
atomic_t<bool> g_game_window_focused = false;
namespace pad
{
extern atomic_t<bool> g_home_menu_requested;
}
bool is_input_allowed()
{
return g_game_window_focused || g_cfg.io.background_input_enabled;
}
gs_frame::gs_frame(QScreen* screen, const QRect& geometry, const QIcon& appIcon, std::shared_ptr<gui_settings> gui_settings, bool force_fullscreen)
: QWindow()
, m_initial_geometry(geometry)
, m_gui_settings(std::move(gui_settings))
, m_start_games_fullscreen(force_fullscreen)
{
load_gui_settings();
m_window_title = Emu.GetFormattedTitle(0);
if (!g_cfg_recording.load())
{
gui_log.notice("Could not load recording config. Using defaults.");
}
g_fxo->need<utils::video_provider>();
m_video_encoder = std::make_shared<utils::video_encoder>();
if (!appIcon.isNull())
{
setIcon(appIcon);
}
#ifdef __APPLE__
// Needed for MoltenVK to work properly on MacOS
if (g_cfg.video.renderer == video_renderer::vulkan)
setSurfaceType(QSurface::VulkanSurface);
#endif
// NOTE: You cannot safely create a wayland window that has hidden initial status and perform any changes on the window while it is still hidden.
// Doing this will create a surface with deferred commands that require a buffer. When binding to your session, this may assert in your compositor due to protocol restrictions.
Visibility startup_visibility = Hidden;
#ifndef _WIN32
if (const char* session_type = ::getenv("XDG_SESSION_TYPE"))
{
if (!strcasecmp(session_type, "wayland"))
{
// Start windowed. This is a featureless rectangle on-screen with no window decorations.
// It does not even resemble a window until the WM attaches later on.
// Fullscreen could technically work with some fiddling, but easily breaks depending on geometry input.
startup_visibility = Windowed;
}
}
#endif
setMinimumWidth(160);
setMinimumHeight(90);
setScreen(screen);
setGeometry(geometry);
setTitle(QString::fromStdString(m_window_title));
if (g_cfg.video.renderer != video_renderer::opengl)
{
// Do not display the window before OpenGL is configured!
// This works fine in windows and X11 but wayland-egl will crash later.
setVisibility(startup_visibility);
create();
}
m_shortcut_handler = new shortcut_handler(gui::shortcuts::shortcut_handler_id::game_window, this, m_gui_settings);
connect(m_shortcut_handler, &shortcut_handler::shortcut_activated, this, &gs_frame::handle_shortcut);
// Change cursor when in fullscreen.
connect(this, &QWindow::visibilityChanged, this, [this](QWindow::Visibility visibility)
{
handle_cursor(visibility, true, false, true);
});
// Change cursor when this window gets or loses focus.
connect(this, &QWindow::activeChanged, this, [this]()
{
g_game_window_focused = isActive();
handle_cursor(visibility(), false, true, true);
});
// Configure the mouse hide on idle timer
connect(&m_mousehide_timer, &QTimer::timeout, this, &gs_frame::mouse_hide_timeout);
m_mousehide_timer.setSingleShot(true);
m_progress_indicator = std::make_unique<progress_indicator>(0, 100);
}
gs_frame::~gs_frame()
{
g_user_asked_for_screenshot = false;
pad::g_home_menu_requested = false;
// Save active screen to gui settings
const QScreen* current_screen = screen();
const QList<QScreen*> screens = QGuiApplication::screens();
int screen_index = 0;
for (int i = 0; i < screens.count(); i++)
{
if (current_screen == ::at32(screens, i))
{
screen_index = i;
break;
}
}
m_gui_settings->SetValue(gui::gs_screen, screen_index);
}
void gs_frame::load_gui_settings()
{
m_disable_mouse = m_gui_settings->GetValue(gui::gs_disableMouse).toBool();
m_disable_kb_hotkeys = m_gui_settings->GetValue(gui::gs_disableKbHotkeys).toBool();
m_show_mouse_in_fullscreen = m_gui_settings->GetValue(gui::gs_showMouseFs).toBool();
m_lock_mouse_in_fullscreen = m_gui_settings->GetValue(gui::gs_lockMouseFs).toBool();
m_hide_mouse_after_idletime = m_gui_settings->GetValue(gui::gs_hideMouseIdle).toBool();
m_hide_mouse_idletime = m_gui_settings->GetValue(gui::gs_hideMouseIdleTime).toUInt();
}
void gs_frame::update_shortcuts()
{
if (m_shortcut_handler)
{
m_shortcut_handler->update();
}
}
void gs_frame::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
}
void gs_frame::showEvent(QShowEvent *event)
{
// We have to calculate new window positions, since the frame is only known once the window was created.
// We will try to find the originally requested dimensions if possible by moving the frame.
// NOTES: The parameter m_initial_geometry is not necessarily equal to our actual geometry() at this point.
// That's why we use m_initial_geometry instead of the frameGeometry() in some places.
// All of these values, including the screen geometry, can also be negative numbers.
const QRect available_geometry = screen()->availableGeometry(); // The available screen geometry
const QRect inner_geometry = geometry(); // The current inner geometry
const QRect outer_geometry = frameGeometry(); // The current outer geometry
// Calculate the left and top frame borders (this will include window handles)
const int left_border = inner_geometry.left() - outer_geometry.left();
const int top_border = inner_geometry.top() - outer_geometry.top();
// Calculate the initially expected frame origin
const QPoint expected_pos(m_initial_geometry.left() - left_border,
m_initial_geometry.top() - top_border);
// Make sure that the expected position is inside the screen (check left and top borders)
QPoint pos(std::max(expected_pos.x(), available_geometry.left()),
std::max(expected_pos.y(), available_geometry.top()));
// Find the maximum position that still ensures that the frame is completely visible inside the screen (check right and bottom borders)
QPoint max_pos(available_geometry.left() + available_geometry.width() - frameGeometry().width(),
available_geometry.top() + available_geometry.height() - frameGeometry().height());
// Make sure that the "maximum" position is inside the screen (check left and top borders)
max_pos.setX(std::max(max_pos.x(), available_geometry.left()));
max_pos.setY(std::max(max_pos.y(), available_geometry.top()));
// Adjust the expected position accordingly
pos.setX(std::min(pos.x(), max_pos.x()));
pos.setY(std::min(pos.y(), max_pos.y()));
// Set the new position
setFramePosition(pos);
QWindow::showEvent(event);
}
void gs_frame::handle_shortcut(gui::shortcuts::shortcut shortcut_key, const QKeySequence& key_sequence)
{
gui_log.notice("Game window registered shortcut: %s (%s)", shortcut_key, key_sequence.toString());
switch (shortcut_key)
{
case gui::shortcuts::shortcut::gw_toggle_fullscreen:
{
toggle_fullscreen();
break;
}
case gui::shortcuts::shortcut::gw_exit_fullscreen:
{
if (visibility() == FullScreen && !m_disable_kb_hotkeys)
{
toggle_fullscreen();
}
break;
}
case gui::shortcuts::shortcut::gw_log_mark:
{
static int count = 0;
mark_log.success("Made forced mark %d in log", ++count);
break;
}
case gui::shortcuts::shortcut::gw_mouse_lock:
{
toggle_mouselock();
break;
}
case gui::shortcuts::shortcut::gw_screenshot:
{
g_user_asked_for_screenshot = true;
break;
}
case gui::shortcuts::shortcut::gw_toggle_recording:
{
toggle_recording();
break;
}
case gui::shortcuts::shortcut::gw_pause_play:
{
if (!m_disable_kb_hotkeys)
{
switch (Emu.GetStatus())
{
case system_state::ready:
{
Emu.Run(true);
return;
}
case system_state::paused:
{
Emu.Resume();
return;
}
default:
{
Emu.Pause();
return;
}
}
}
break;
}
case gui::shortcuts::shortcut::gw_restart:
{
if (!m_disable_kb_hotkeys)
{
if (Emu.IsStopped())
{
Emu.Restart();
return;
}
extern bool boot_last_savestate(bool testing);
boot_last_savestate(false);
}
break;
}
case gui::shortcuts::shortcut::gw_savestate:
{
if (!m_disable_kb_hotkeys)
{
if (!g_cfg.savestate.suspend_emu)
{
Emu.after_kill_callback = []()
{
Emu.Restart();
};
}
Emu.Kill(false, true);
return;
}
break;
}
case gui::shortcuts::shortcut::gw_rsx_capture:
{
if (!m_disable_kb_hotkeys)
{
g_user_asked_for_frame_capture = true;
}
break;
}
case gui::shortcuts::shortcut::gw_frame_limit:
{
g_disable_frame_limit = !g_disable_frame_limit;
gui_log.warning("%s boost mode", g_disable_frame_limit.load() ? "Enabled" : "Disabled");
break;
}
case gui::shortcuts::shortcut::gw_toggle_mouse_and_keyboard:
{
input::toggle_mouse_and_keyboard();
break;
}
case gui::shortcuts::shortcut::gw_home_menu:
{
pad::g_home_menu_requested = true;
break;
}
default:
{
break;
}
}
}
void gs_frame::toggle_fullscreen()
{
Emu.CallFromMainThread([this]()
{
if (visibility() == FullScreen)
{
// Change to the last recorded visibility. Sanitize it just in case.
if (m_last_visibility != Visibility::Maximized && m_last_visibility != Visibility::Windowed)
{
m_last_visibility = Visibility::Windowed;
}
setVisibility(m_last_visibility);
}
else
{
// Backup visibility for exiting fullscreen mode later. Don't do this in the visibilityChanged slot,
// since entering fullscreen from maximized will first change the visibility to windowed.
m_last_visibility = visibility();
setVisibility(FullScreen);
}
});
}
void gs_frame::toggle_recording()
{
utils::video_provider& video_provider = g_fxo->get<utils::video_provider>();
if (g_recording_mode == recording_mode::cell)
{
gui_log.warning("A video recorder is already in use by cell. Regular recording can not proceed.");
m_video_encoder->stop();
return;
}
if (g_recording_mode.exchange(recording_mode::stopped) == recording_mode::rpcs3)
{
m_video_encoder->stop();
if (!video_provider.set_video_sink(nullptr, recording_mode::rpcs3))
{
gui_log.warning("The video provider could not release the video sink. A sink with higher priority must have been set.");
}
// Play a sound
if (const std::string sound_path = fs::get_config_dir() + "sounds/snd_recording.wav"; fs::is_file(sound_path))
{
Emu.GetCallbacks().play_sound(sound_path);
}
else
{
QApplication::beep();
}
ensure(m_video_encoder->path().starts_with(fs::get_config_dir()));
const std::string shortpath = m_video_encoder->path().substr(fs::get_config_dir().size() - 1); // -1 for /
rsx::overlays::queue_message(tr("Recording saved: %0").arg(QString::fromStdString(shortpath)).toStdString());
}
else
{
m_video_encoder->stop();
const std::string& id = Emu.GetTitleID();
std::string video_path = fs::get_config_dir() + "recordings/";
if (!id.empty())
{
video_path += id + "/";
}
if (!fs::create_path(video_path) && fs::g_tls_error != fs::error::exist)
{
screenshot_log.error("Failed to create recordings path \"%s\" : %s", video_path, fs::g_tls_error);
return;
}
if (!id.empty())
{
video_path += id + "_";
}
video_path += "recording_" + date_time::current_time_narrow<'_'>() + ".mp4";
utils::video_encoder::frame_format output_format{};
output_format.av_pixel_format = static_cast<AVPixelFormat>(g_cfg_recording.video.pixel_format.get());
output_format.width = g_cfg_recording.video.width;
output_format.height = g_cfg_recording.video.height;
output_format.pitch = g_cfg_recording.video.width * 4;
m_video_encoder->use_internal_audio = true;
m_video_encoder->use_internal_video = true;
m_video_encoder->set_path(video_path);
m_video_encoder->set_framerate(g_cfg_recording.video.framerate);
m_video_encoder->set_video_bitrate(g_cfg_recording.video.video_bps);
m_video_encoder->set_video_codec(g_cfg_recording.video.video_codec);
m_video_encoder->set_max_b_frames(g_cfg_recording.video.max_b_frames);
m_video_encoder->set_gop_size(g_cfg_recording.video.gop_size);
m_video_encoder->set_output_format(output_format);
switch (g_cfg.audio.provider)
{
case audio_provider::none:
{
// Disable audio recording
m_video_encoder->use_internal_audio = false;
break;
}
case audio_provider::cell_audio:
{
const cell_audio_config& cfg = g_fxo->get<cell_audio>().cfg;
m_video_encoder->set_sample_rate(cfg.audio_sampling_rate);
m_video_encoder->set_audio_channels(cfg.audio_channels);
break;
}
case audio_provider::rsxaudio:
{
const auto& rsx_audio = g_fxo->get<rsx_audio_backend>();
m_video_encoder->set_sample_rate(rsx_audio.get_sample_rate());
m_video_encoder->set_audio_channels(rsx_audio.get_channel_count());
break;
}
}
m_video_encoder->set_audio_bitrate(g_cfg_recording.audio.audio_bps);
m_video_encoder->set_audio_codec(g_cfg_recording.audio.audio_codec);
m_video_encoder->encode();
if (m_video_encoder->has_error)
{
rsx::overlays::queue_message(tr("Recording not possible").toStdString());
m_video_encoder->stop();
return;
}
if (!video_provider.set_video_sink(m_video_encoder, recording_mode::rpcs3))
{
gui_log.warning("The video provider could not set the video sink. A sink with higher priority must have been set.");
rsx::overlays::queue_message(tr("Recording not possible").toStdString());
m_video_encoder->stop();
return;
}
video_provider.set_pause_time_us(0);
g_recording_mode = recording_mode::rpcs3;
rsx::overlays::queue_message(tr("Recording started").toStdString());
}
}
void gs_frame::toggle_mouselock()
{
// first we toggle the value
m_mouse_hide_and_lock = !m_mouse_hide_and_lock;
// and update the cursor
handle_cursor(visibility(), false, false, true);
}
void gs_frame::update_cursor()
{
bool show_mouse;
if (!isActive())
{
// Show the mouse by default if this is not the active window
show_mouse = true;
}
else if (m_hide_mouse_after_idletime && !m_mousehide_timer.isActive())
{
// Hide the mouse if the idle timeout was reached (which means that the timer isn't running)
show_mouse = false;
}
else if (visibility() == QWindow::Visibility::FullScreen)
{
// Fullscreen: Show or hide the mouse depending on the settings.
show_mouse = m_show_mouse_in_fullscreen;
}
else
{
// Windowed: Hide the mouse if it was locked by the user
show_mouse = !m_mouse_hide_and_lock;
}
// Update Cursor if necessary
if (show_mouse != m_show_mouse.exchange(show_mouse))
{
setCursor(m_show_mouse ? Qt::ArrowCursor : Qt::BlankCursor);
}
}
bool gs_frame::get_mouse_lock_state()
{
handle_cursor(visibility(), false, false, true);
return isActive() && m_mouse_hide_and_lock;
}
void gs_frame::hide_on_close()
{
// Make sure not to save the hidden state, which is useless to us.
const Visibility current_visibility = visibility();
m_gui_settings->SetValue(gui::gs_visibility, current_visibility == Visibility::Hidden ? Visibility::AutomaticVisibility : current_visibility, false);
m_gui_settings->SetValue(gui::gs_geometry, geometry(), true);
if (!g_progr_text.load())
{
// Hide the dialog before stopping if no progress bar is being shown.
// Otherwise users might think that the game softlocked if stopping takes too long.
QWindow::hide();
}
}
void gs_frame::close()
{
if (m_is_closing.exchange(true))
{
gui_log.notice("Closing game window (ignored, already closing)");
return;
}
gui_log.notice("Closing game window");
Emu.CallFromMainThread([this]()
{
// Hide window if necessary
hide_on_close();
if (!Emu.IsStopped())
{
// Notify progress dialog cancellation
g_system_progress_canceled = true;
// Blocking shutdown request. Obsolete, but I'm keeping it here as last resort.
Emu.after_kill_callback = [this](){ deleteLater(); };
Emu.GracefulShutdown(true);
}
else
{
deleteLater();
}
});
}
bool gs_frame::shown()
{
return QWindow::isVisible();
}
void gs_frame::hide()
{
Emu.CallFromMainThread([this]() { QWindow::hide(); });
}
void gs_frame::show()
{
Emu.CallFromMainThread([this]()
{
QWindow::show();
if (g_cfg.misc.start_fullscreen || m_start_games_fullscreen)
{
setVisibility(FullScreen);
}
else if (const QVariant var = m_gui_settings->GetValue(gui::gs_visibility); var.canConvert<Visibility>())
{
// Restore saved visibility from last time. Make sure not to hide the window, or the user can't access it anymore.
if (const Visibility visibility = var.value<Visibility>(); visibility != Visibility::Hidden)
{
setVisibility(visibility);
}
}
});
// if we do this before show, the QWinTaskbarProgress won't show
m_progress_indicator->show(this);
}
display_handle_t gs_frame::handle() const
{
#ifdef _WIN32
return reinterpret_cast<HWND>(this->winId());
#elif defined(__APPLE__)
return reinterpret_cast<void*>(this->winId()); //NSView
#else
#ifdef HAVE_WAYLAND
QPlatformNativeInterface *native = QGuiApplication::platformNativeInterface();
struct wl_display *wl_dpy = static_cast<struct wl_display *>(
native->nativeResourceForWindow("display", NULL));
struct wl_surface *wl_surf = static_cast<struct wl_surface *>(
native->nativeResourceForWindow("surface", const_cast<QWindow*>(static_cast<const QWindow*>(this))));
if (wl_dpy != nullptr && wl_surf != nullptr)
{
return std::make_pair(wl_dpy, wl_surf);
}
else
#endif
#ifdef HAVE_X11
{
return std::make_pair(XOpenDisplay(0), static_cast<ulong>(this->winId()));
}
#else
fmt::throw_exception("Vulkan X11 support disabled at compile-time.");
#endif
#endif
}
draw_context_t gs_frame::make_context()
{
return nullptr;
}
void gs_frame::set_current(draw_context_t context)
{
Q_UNUSED(context)
}
void gs_frame::delete_context(draw_context_t context)
{
Q_UNUSED(context)
}
int gs_frame::client_width()
{
#ifdef _WIN32
RECT rect;
if (GetClientRect(reinterpret_cast<HWND>(winId()), &rect))
{
return rect.right - rect.left;
}
#endif // _WIN32
return width() * devicePixelRatio();
}
int gs_frame::client_height()
{
#ifdef _WIN32
RECT rect;
if (GetClientRect(reinterpret_cast<HWND>(winId()), &rect))
{
return rect.bottom - rect.top;
}
#endif // _WIN32
return height() * devicePixelRatio();
}
f64 gs_frame::client_display_rate()
{
f64 rate = 20.; // Minimum is 20
Emu.BlockingCallFromMainThread([this, &rate]()
{
const QList<QScreen*> screens = QGuiApplication::screens();
for (int i = 0; i < screens.count(); i++)
{
rate = std::fmax(rate, ::at32(screens, i)->refreshRate());
}
});
return rate;
}
void gs_frame::flip(draw_context_t, bool /*skip_frame*/)
{
static Timer fps_t;
if (!m_flip_showed_frame)
{
// Show on first flip
m_flip_showed_frame = true;
show();
fps_t.Start();
}
++m_frames;
if (fps_t.GetElapsedTimeInSec() >= 0.5)
{
std::string new_title = Emu.GetFormattedTitle(m_frames / fps_t.GetElapsedTimeInSec());
if (new_title != m_window_title)
{
m_window_title = new_title;
Emu.CallFromMainThread([this, title = std::move(new_title)]()
{
setTitle(QString::fromStdString(title));
});
}
m_frames = 0;
fps_t.Start();
}
if (g_user_asked_for_recording.exchange(false))
{
Emu.CallFromMainThread([this]()
{
toggle_recording();
});
}
}
bool gs_frame::can_consume_frame() const
{
utils::video_provider& video_provider = g_fxo->get<utils::video_provider>();
return video_provider.can_consume_frame();
}
void gs_frame::present_frame(std::vector<u8>& data, u32 pitch, u32 width, u32 height, bool is_bgra) const
{
utils::video_provider& video_provider = g_fxo->get<utils::video_provider>();
video_provider.present_frame(data, pitch, width, height, is_bgra);
}
void gs_frame::take_screenshot(std::vector<u8> data, u32 sshot_width, u32 sshot_height, bool is_bgra)
{
std::thread(
[sshot_width, sshot_height, is_bgra](std::vector<u8> sshot_data)
{
thread_base::set_name("Screenshot");
screenshot_log.notice("Taking screenshot (%dx%d)", sshot_width, sshot_height);
const std::string& id = Emu.GetTitleID();
std::string screen_path = fs::get_config_dir() + "screenshots/";
if (!id.empty())
{
screen_path += id + "/";
}
if (!fs::create_path(screen_path) && fs::g_tls_error != fs::error::exist)
{
screenshot_log.error("Failed to create screenshot path \"%s\" : %s", screen_path, fs::g_tls_error);
return;
}
std::string filename = screen_path;
if (!id.empty())
{
filename += id + "_";
}
filename += "screenshot_" + date_time::current_time_narrow<'_'>() + ".png";
fs::file sshot_file(filename, fs::open_mode::create + fs::open_mode::write + fs::open_mode::excl);
if (!sshot_file)
{
screenshot_log.error("Failed to save screenshot \"%s\" : %s", filename, fs::g_tls_error);
return;
}
std::vector<u8> sshot_data_alpha(sshot_data.size());
const u32* sshot_ptr = reinterpret_cast<const u32*>(sshot_data.data());
u32* alpha_ptr = reinterpret_cast<u32*>(sshot_data_alpha.data());
if (is_bgra) [[likely]]
{
for (usz index = 0; index < sshot_data.size() / sizeof(u32); index++)
{
alpha_ptr[index] = ((sshot_ptr[index] & 0xFF) << 16) | (sshot_ptr[index] & 0xFF00) | ((sshot_ptr[index] & 0xFF0000) >> 16) | 0xFF000000;
}
}
else
{
for (usz index = 0; index < sshot_data.size() / sizeof(u32); index++)
{
alpha_ptr[index] = sshot_ptr[index] | 0xFF000000;
}
}
screenshot_info manager;
{
auto& s = g_fxo->get<screenshot_manager>();
std::lock_guard lock(s.mutex);
manager = s;
}
struct scoped_png_ptrs
{
png_structp write_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
png_infop info_ptr = png_create_info_struct(write_ptr);
~scoped_png_ptrs()
{
png_free_data(write_ptr, info_ptr, PNG_FREE_ALL, -1);
png_destroy_write_struct(&write_ptr, &info_ptr);
}
};
png_text text[6] = {};
int num_text = 0;
const QDateTime date_time = QDateTime::currentDateTime();
const std::string creation_time = date_time.toString("yyyy:MM:dd hh:mm:ss").toStdString();
const std::string photo_title = manager.get_photo_title();
const std::string game_title = manager.get_game_title();
const std::string game_comment = manager.get_game_comment();
const std::string& title_id = Emu.GetTitleID();
// Write tEXt chunk
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = const_cast<char*>("Creation Time");
text[num_text].text = const_cast<char*>(creation_time.c_str());
++num_text;
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = const_cast<char*>("Source");
text[num_text].text = const_cast<char*>("RPCS3"); // Originally PlayStation(R)3
++num_text;
text[num_text].compression = PNG_TEXT_COMPRESSION_NONE;
text[num_text].key = const_cast<char*>("Title ID");
text[num_text].text = const_cast<char*>(title_id.c_str());
++num_text;
// Write tTXt chunk (they probably meant zTXt)
text[num_text].compression = PNG_TEXT_COMPRESSION_zTXt;
text[num_text].key = const_cast<char*>("Title");
text[num_text].text = const_cast<char*>(photo_title.c_str());
++num_text;
text[num_text].compression = PNG_TEXT_COMPRESSION_zTXt;
text[num_text].key = const_cast<char*>("Game Title");
text[num_text].text = const_cast<char*>(game_title.c_str());
++num_text;
text[num_text].compression = PNG_TEXT_COMPRESSION_zTXt;
text[num_text].key = const_cast<char*>("Comment");
text[num_text].text = const_cast<char*>(game_comment.c_str());
// Create image from data
QImage img(sshot_data_alpha.data(), sshot_width, sshot_height, sshot_width * 4, QImage::Format_RGBA8888);
// Scale image if necessary
const auto& avconf = g_fxo->get<rsx::avconf>();
auto new_size = avconf.aspect_convert_dimensions(size2u{ u32(img.width()), u32(img.height()) });
if (new_size.width != static_cast<u32>(img.width()) || new_size.height != static_cast<u32>(img.height()))
{
img = img.scaled(QSize(new_size.width, new_size.height), Qt::AspectRatioMode::IgnoreAspectRatio, Qt::TransformationMode::SmoothTransformation);
img.convertTo(QImage::Format_RGBA8888); // The current Qt version changes the image format during smooth scaling, so we have to change it back.
}
// Create row pointers for libpng
std::vector<u8*> rows(img.height());
for (int y = 0; y < img.height(); y++)
rows[y] = img.scanLine(y);
std::vector<u8> encoded_png;
const auto write_png = [&]()
{
const scoped_png_ptrs ptrs;
png_set_IHDR(ptrs.write_ptr, ptrs.info_ptr, img.width(), img.height(), 8, PNG_COLOR_TYPE_RGBA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
png_set_text(ptrs.write_ptr, ptrs.info_ptr, text, 6);
png_set_rows(ptrs.write_ptr, ptrs.info_ptr, &rows[0]);
png_set_write_fn(ptrs.write_ptr, &encoded_png, [](png_structp png_ptr, png_bytep data, png_size_t length)
{
std::vector<u8>* p = static_cast<std::vector<u8>*>(png_get_io_ptr(png_ptr));
p->insert(p->end(), data, data + length);
}, nullptr);
png_write_png(ptrs.write_ptr, ptrs.info_ptr, PNG_TRANSFORM_IDENTITY, nullptr);
};
write_png();
sshot_file.write(encoded_png.data(), encoded_png.size());
screenshot_log.success("Successfully saved screenshot to %s", filename);
if (manager.is_enabled)
{
const std::string cell_sshot_overlay_path = manager.get_overlay_path();
if (fs::is_file(cell_sshot_overlay_path))
{
screenshot_log.notice("Adding overlay to cell screenshot from %s", cell_sshot_overlay_path);
QImage overlay_img;
if (!overlay_img.load(QString::fromStdString(cell_sshot_overlay_path)))
{
screenshot_log.error("Failed to read cell screenshot overlay '%s' : %s", cell_sshot_overlay_path, fs::g_tls_error);
return;
}
// Games choose the overlay file and the offset based on the current video resolution.
// We need to scale the overlay if our resolution scaling causes the image to have a different size.
// Scale the resolution first (as seen before with the image)
new_size = avconf.aspect_convert_dimensions(size2u{ avconf.resolution_x, avconf.resolution_y });
if (new_size.width != static_cast<u32>(img.width()) || new_size.height != static_cast<u32>(img.height()))
{
const int scale = rsx::get_resolution_scale_percent();
const int x = (scale * manager.overlay_offset_x) / 100;
const int y = (scale * manager.overlay_offset_y) / 100;
const int width = (scale * overlay_img.width()) / 100;
const int height = (scale * overlay_img.height()) / 100;
screenshot_log.notice("Scaling overlay from %dx%d at offset (%d,%d) to %dx%d at offset (%d,%d)",
overlay_img.width(), overlay_img.height(), manager.overlay_offset_x, manager.overlay_offset_y, width, height, x, y);
manager.overlay_offset_x = x;
manager.overlay_offset_y = y;
overlay_img = overlay_img.scaled(QSize(width, height), Qt::AspectRatioMode::IgnoreAspectRatio, Qt::TransformationMode::SmoothTransformation);
}
if (manager.overlay_offset_x < static_cast<s64>(img.width()) &&
manager.overlay_offset_y < static_cast<s64>(img.height()) &&
manager.overlay_offset_x + overlay_img.width() > 0 &&
manager.overlay_offset_y + overlay_img.height() > 0)
{
QImage screenshot_img(rows[0], img.width(), img.height(), QImage::Format_RGBA8888);
QPainter painter(&screenshot_img);
painter.drawImage(manager.overlay_offset_x, manager.overlay_offset_y, overlay_img);
painter.end();
std::memcpy(rows[0], screenshot_img.constBits(), screenshot_img.sizeInBytes());
screenshot_log.success("Applied screenshot overlay '%s'", cell_sshot_overlay_path);
}
}
const std::string cell_sshot_filename = manager.get_screenshot_path(date_time.toString("yyyy/MM/dd").toStdString());
const std::string cell_sshot_dir = fs::get_parent_dir(cell_sshot_filename);
screenshot_log.notice("Saving cell screenshot to %s", cell_sshot_filename);
if (!fs::create_path(cell_sshot_dir) && fs::g_tls_error != fs::error::exist)
{
screenshot_log.error("Failed to create cell screenshot dir \"%s\" : %s", cell_sshot_dir, fs::g_tls_error);
return;
}
fs::file cell_sshot_file(cell_sshot_filename, fs::open_mode::create + fs::open_mode::write + fs::open_mode::excl);
if (!cell_sshot_file)
{
screenshot_log.error("Failed to save cell screenshot \"%s\" : %s", cell_sshot_filename, fs::g_tls_error);
return;
}
encoded_png.clear();
write_png();
cell_sshot_file.write(encoded_png.data(), encoded_png.size());
screenshot_log.success("Successfully saved cell screenshot to %s", cell_sshot_filename);
}
// Play a sound
Emu.CallFromMainThread([]()
{
if (const std::string sound_path = fs::get_config_dir() + "sounds/snd_screenshot.wav"; fs::is_file(sound_path))
{
Emu.GetCallbacks().play_sound(sound_path);
}
else
{
QApplication::beep();
}
});
ensure(filename.starts_with(fs::get_config_dir()));
const std::string shortpath = filename.substr(fs::get_config_dir().size() - 1); // -1 for /
rsx::overlays::queue_message(tr("Screenshot saved: %0").arg(QString::fromStdString(shortpath)).toStdString());
return;
},
std::move(data))
.detach();
}
void gs_frame::mouseDoubleClickEvent(QMouseEvent* ev)
{
if (m_disable_mouse)
{
return;
}
switch (g_cfg.io.move)
{
case move_handler::mouse:
case move_handler::raw_mouse:
#ifdef HAVE_LIBEVDEV
case move_handler::gun:
#endif
return;
default:
break;
}
if (ev->button() == Qt::LeftButton)
{
toggle_fullscreen();
}
}
void gs_frame::handle_cursor(QWindow::Visibility visibility, bool visibility_changed, bool active_changed, bool start_idle_timer)
{
// Let's reload the gui settings when the visibility or the active window changes.
if (visibility_changed || active_changed)
{
load_gui_settings();
// Update the mouse lock state if the visibility changed.
if (visibility_changed)
{
// In fullscreen we default to hiding and locking. In windowed mode we do not want the lock by default.
m_mouse_hide_and_lock = (visibility == QWindow::Visibility::FullScreen) && m_lock_mouse_in_fullscreen;
}
}
// Update the mouse hide timer
if (m_hide_mouse_after_idletime && start_idle_timer)
{
m_mousehide_timer.start(m_hide_mouse_idletime);
}
else
{
m_mousehide_timer.stop();
}
// Update the cursor visibility
update_cursor();
}
void gs_frame::mouse_hide_timeout()
{
// Our idle timeout occured, so we update the cursor
if (m_hide_mouse_after_idletime && m_show_mouse)
{
handle_cursor(visibility(), false, false, false);
}
}
bool gs_frame::event(QEvent* ev)
{
if (ev->type() == QEvent::Close)
{
if (m_gui_settings->GetValue(gui::ib_confirm_exit).toBool())
{
if (visibility() == FullScreen)
{
toggle_fullscreen();
}
int result = QMessageBox::Yes;
m_gui_settings->ShowConfirmationBox(tr("Exit Game?"),
tr("Do you really want to exit the game?<br><br>Any unsaved progress will be lost!<br>"),
gui::ib_confirm_exit, &result, nullptr);
if (result != QMessageBox::Yes)
{
return true;
}
}
gui_log.notice("Game window close event issued");
if (Emu.IsStopped())
{
// This should be unreachable, but never say never. Properly close the window anyway.
close();
}
else
{
// Notify progress dialog cancellation
g_system_progress_canceled = true;
// Issue async shutdown
Emu.GracefulShutdown(true, true);
// Hide window if necessary
hide_on_close();
// Do not propagate the close event. It will be closed by the rsx_thread.
return true;
}
}
else if (ev->type() == QEvent::MouseMove && (!m_show_mouse || m_mousehide_timer.isActive()))
{
// This will make the cursor visible again if it was hidden by the mouse idle timeout
handle_cursor(visibility(), false, false, true);
}
return QWindow::event(ev);
}
void gs_frame::progress_reset(bool reset_limit)
{
m_progress_indicator->reset();
if (reset_limit)
{
progress_set_limit(100);
}
}
void gs_frame::progress_set_value(int value)
{
m_progress_indicator->set_value(value);
}
void gs_frame::progress_increment(int delta)
{
if (delta != 0)
{
m_progress_indicator->set_value(m_progress_indicator->value() + delta);
}
}
void gs_frame::progress_set_limit(int limit)
{
m_progress_indicator->set_range(0, limit);
}
bool gs_frame::has_alpha()
{
return format().hasAlpha();
}
| 33,949
|
C++
|
.cpp
| 1,009
| 30.560951
| 177
| 0.698953
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,088
|
breakpoint_handler.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/breakpoint_handler.cpp
|
#include "breakpoint_handler.h"
extern bool ppu_breakpoint(u32 loc, bool is_adding);
bool breakpoint_handler::HasBreakpoint(u32 loc) const
{
return m_breakpoints.contains(loc);
}
bool breakpoint_handler::AddBreakpoint(u32 loc)
{
if (!ppu_breakpoint(loc, true))
{
return false;
}
ensure(m_breakpoints.insert(loc).second);
return true;
}
bool breakpoint_handler::RemoveBreakpoint(u32 loc)
{
if (m_breakpoints.erase(loc) == 0)
{
return false;
}
ensure(ppu_breakpoint(loc, false));
return true;
}
| 514
|
C++
|
.cpp
| 24
| 19.541667
| 53
| 0.764463
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
5,089
|
pad_led_settings_dialog.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/pad_led_settings_dialog.cpp
|
#include "pad_led_settings_dialog.h"
#include <QColorDialog>
#include <QPainter>
#include <QPixmap>
#include <QPainterPath>
pad_led_settings_dialog::pad_led_settings_dialog(QDialog* parent, int colorR, int colorG, int colorB, bool has_rgb, bool has_player_led, bool player_led_enabled, bool has_battery, bool has_battery_led, bool led_low_battery_blink, bool led_battery_indicator, int led_battery_indicator_brightness)
: QDialog(parent)
, ui(new Ui::pad_led_settings_dialog)
, m_initial{colorR, colorG, colorB, player_led_enabled, led_low_battery_blink, led_battery_indicator, led_battery_indicator_brightness}
{
ui->setupUi(this);
setModal(true);
m_new = m_initial;
ui->hs_indicator_brightness->setValue(m_new.battery_indicator_brightness);
ui->cb_led_blink->setChecked(m_new.low_battery_blink);
ui->cb_led_indicate->setChecked(m_new.battery_indicator);
ui->cb_player_led->setChecked(m_new.player_led_enabled);
update_slider_label(m_new.battery_indicator_brightness);
ui->gb_player_led->setEnabled(has_player_led);
ui->gb_led_color->setEnabled(has_rgb);
ui->gb_battery_status->setEnabled(has_battery && has_battery_led);
ui->gb_indicator_brightness->setEnabled(has_battery && has_battery_led && has_rgb); // Let's restrict this to rgb capable devices for now
connect(ui->bb_dialog_buttons, &QDialogButtonBox::clicked, [this](QAbstractButton* button)
{
if (button == ui->bb_dialog_buttons->button(QDialogButtonBox::Ok))
{
read_form_values();
accept();
}
else if (button == ui->bb_dialog_buttons->button(QDialogButtonBox::Cancel))
{
m_new = m_initial;
reject();
}
else if (button == ui->bb_dialog_buttons->button(QDialogButtonBox::Apply))
{
read_form_values();
}
Q_EMIT pass_led_settings(m_new);
});
if (has_rgb)
{
connect(ui->b_colorpicker, &QPushButton::clicked, [this]()
{
const QColor led_color(m_new.color_r, m_new.color_g, m_new.color_b);
QColorDialog dlg(led_color, this);
dlg.setWindowTitle(tr("LED Color"));
if (dlg.exec() == QColorDialog::Accepted)
{
const QColor new_color = dlg.selectedColor();
m_new.color_r = new_color.red();
m_new.color_g = new_color.green();
m_new.color_b = new_color.blue();
redraw_color_sample();
}
});
if (ui->gb_battery_status->isEnabled())
{
connect(ui->hs_indicator_brightness, &QAbstractSlider::valueChanged, this, &pad_led_settings_dialog::update_slider_label);
}
if (ui->cb_led_indicate->isEnabled())
{
connect(ui->cb_led_indicate, &QCheckBox::toggled, this, &pad_led_settings_dialog::battery_indicator_checked);
}
battery_indicator_checked(ui->cb_led_indicate->isChecked());
}
// Draw color sample after showing the dialog, in order to have proper dimensions
show();
redraw_color_sample();
setFixedSize(size());
}
pad_led_settings_dialog::~pad_led_settings_dialog()
{
}
void pad_led_settings_dialog::redraw_color_sample() const
{
const qreal dpr = devicePixelRatioF();
const qreal w = ui->w_color_sample->width();
const qreal h = ui->w_color_sample->height();
const qreal padding = 5;
const qreal radius = 5;
// Create the canvas for our color sample widget
QPixmap color_sample(w * dpr, h * dpr);
color_sample.setDevicePixelRatio(dpr);
color_sample.fill(Qt::transparent);
// Create the shape for our color sample widget
QPainterPath path;
path.addRoundedRect(QRectF(padding, padding, w - padding * 2, h - padding * 2), radius, radius);
// Get new LED color
const QColor led_color(m_new.color_r, m_new.color_g, m_new.color_b);
// Paint the shape with a black border and fill it with the LED color
QPainter painter(&color_sample);
painter.setRenderHint(QPainter::Antialiasing);
painter.setPen(QPen(Qt::black, 1));
painter.fillPath(path, led_color);
painter.drawPath(path);
painter.end();
// Update the color sample widget
ui->w_color_sample->setPixmap(color_sample.scaled(w * dpr, h * dpr, Qt::KeepAspectRatio, Qt::TransformationMode::SmoothTransformation));
}
void pad_led_settings_dialog::update_slider_label(int val) const
{
const QString label = QString::number(val) + QStringLiteral("%");
ui->l_indicator_brightness->setText(label);
}
void pad_led_settings_dialog::battery_indicator_checked(bool checked) const
{
ui->gb_indicator_brightness->setEnabled(checked);
}
void pad_led_settings_dialog::read_form_values()
{
m_new.player_led_enabled = ui->cb_player_led->isChecked();
m_new.low_battery_blink = ui->cb_led_blink->isChecked();
m_new.battery_indicator = ui->cb_led_indicate->isChecked();
m_new.battery_indicator_brightness = ui->hs_indicator_brightness->value();
}
| 4,600
|
C++
|
.cpp
| 116
| 37.068966
| 295
| 0.733587
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,090
|
syntax_highlighter.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/syntax_highlighter.cpp
|
#include "syntax_highlighter.h"
#include "qt_utils.h"
Highlighter::Highlighter(QTextDocument *parent) : QSyntaxHighlighter(parent)
{
}
void Highlighter::addRule(const QString &pattern, const QBrush &brush)
{
HighlightingRule rule;
rule.pattern = QRegularExpression(pattern);
rule.format.setForeground(brush);
highlightingRules.append(rule);
}
void Highlighter::highlightBlock(const QString &text)
{
for (const HighlightingRule& rule : highlightingRules)
{
QRegularExpressionMatchIterator matchIterator = rule.pattern.globalMatch(text);
while (matchIterator.hasNext())
{
QRegularExpressionMatch match = matchIterator.next();
setFormat(match.capturedStart(), match.capturedLength(), rule.format);
}
}
setCurrentBlockState(0);
if (commentStartExpression.pattern().isEmpty() || commentEndExpression.pattern().isEmpty())
return;
int startIndex = 0;
if (previousBlockState() != 1)
startIndex = text.indexOf(commentStartExpression);
while (startIndex >= 0)
{
const QRegularExpressionMatch match = commentEndExpression.match(text, startIndex);
const int endIndex = match.capturedStart();
int commentLength;
if (endIndex == -1)
{
setCurrentBlockState(1);
commentLength = text.length() - startIndex;
}
else
{
commentLength = endIndex - startIndex + match.capturedLength();
}
setFormat(startIndex, commentLength, multiLineCommentFormat);
startIndex = text.indexOf(commentStartExpression, startIndex + commentLength);
}
}
LogHighlighter::LogHighlighter(QTextDocument* parent) : Highlighter(parent)
{
const QColor color = gui::utils::get_foreground_color();
//addRule("^[^·].*$", gui::utils::get_label_color("log_level_always", Qt::darkCyan, Qt::cyan)); // unused for now
addRule("^·F.*$", gui::utils::get_label_color("log_level_fatal", Qt::darkMagenta, Qt::magenta));
addRule("^·E.*$", gui::utils::get_label_color("log_level_error", Qt::red, Qt::red));
addRule("^·U.*$", gui::utils::get_label_color("log_level_todo", Qt::darkYellow, Qt::darkYellow));
addRule("^·S.*$", gui::utils::get_label_color("log_level_success", Qt::darkGreen, Qt::green));
addRule("^·W.*$", gui::utils::get_label_color("log_level_warning", Qt::darkYellow, Qt::darkYellow));
addRule("^·!.*$", gui::utils::get_label_color("log_level_notice", color, color));
addRule("^·T.*$", gui::utils::get_label_color("log_level_trace", color, color));
}
AsmHighlighter::AsmHighlighter(QTextDocument *parent) : Highlighter(parent)
{
addRule("^\\b[A-Z0-9]+\\b", Qt::darkBlue); // Instructions
addRule("-?R\\d[^,;\\s]*", Qt::darkRed); // -R0.*
addRule("-?H\\d[^,;\\s]*", Qt::red); // -H1.*
addRule("-?v\\[\\d\\]*[^,;\\s]*", Qt::darkCyan); // -v[xyz].*
addRule("-?o\\[\\d\\]*[^,;\\s]*", Qt::darkMagenta); // -o[xyz].*
addRule("-?c\\[\\d\\]*[^,;\\s]*", Qt::darkYellow); // -c[xyz].*
addRule("#[^\\n]*", Qt::darkGreen); // Single line comment
}
GlslHighlighter::GlslHighlighter(QTextDocument *parent) : Highlighter(parent)
{
const QStringList keywordPatterns = QStringList()
// Selection-Iteration-Jump Statements:
<< "if" << "else" << "switch" << "case" << "default"
<< "for" << "while" << "do" << "foreach" //?
<< "return" << "break" << "continue" << "discard"
// Misc:
<< "void" << "char" << "short" << "long" << "template"
<< "class" << "struct" << "union" << "enum"
<< "static" << "virtual" << "inline" << "explicit"
<< "public" << "private" << "protected" << "namespace"
<< "typedef" << "typename" << "signed" << "unsigned"
<< "friend" << "operator" << "signals" << "slots"
// Qualifiers:
<< "in" << "packed" << "precision" << "const" << "smooth" << "sample"
<< "out" << "shared" << "highp" << "invariant" << "noperspective" << "centroid"
<< "inout" << "std140" << "mediump" << "uniform" << "flat" << "patch"
<< "buffer" << "std430" << "lowp"
<< "image"
// Removed Qualifiers?
<< "attribute" << "varying"
// Memory Qualifiers
<< "coherent" << "volatile" << "restrict" << "readonly" << "writeonly"
// Layout Qualifiers:
//<< "subroutine" << "layout" << "xfb_buffer" << "textureGrad" << "texture" << "dFdx" << "dFdy"
//<< "location" << "component" << "binding" << "offset"
//<< "xfb_offset" << "xfb_stride" << "vertices" << "max_vertices"
// Scalars and Vectors:
<< "bool" << "int" << "uint" << "float" << "double"
<< "bvec2" << "ivec2" << "uvec2" << "vec2" << "dvec2"
<< "bvec3" << "ivec3" << "uvec3" << "vec3" << "dvec3"
<< "bvec4" << "ivec4" << "uvec4" << "vec4" << "dvec4"
// Matrices:
<< "mat2" << "mat2x3" << "mat2x4"
<< "mat3" << "mat3x2" << "mat3x4"
<< "mat4" << "mat4x2" << "mat4x3"
// Sampler Types:
<< "sampler1D" << "isampler1D" << "usampler1D"
<< "sampler2D" << "isampler2D" << "usampler2D"
<< "sampler3D" << "isampler3D" << "usampler3D"
<< "samplerCube" << "isamplerCube" << "usamplerCube"
<< "sampler2DRect" << "isampler2DRect" << "usampler2DRect"
<< "sampler1DArray" << "isampler1DArray" << "usampler1DArray"
<< "sampler2DArray" << "isampler2DArray" << "usampler2DArray"
<< "samplerCubeArray" << "isamplerCubeArray" << "usamplerCubeArray"
<< "samplerBuffer" << "isamplerBuffer" << "usamplerBuffer"
<< "sampler2DMS" << "isampler2DMS" << "usampler2DMS"
<< "sampler2DMSArray" << "isampler2DMSArray" << "usampler2DMSArray"
// Shadow Samplers:
<< "sampler1DShadow"
<< "sampler2DShadow"
<< "samplerCubeShadow"
<< "sampler2DRectShadow"
<< "sampler1DArrayShadow"
<< "sampler2DArrayShadow"
<< "samplerCubeArrayShadow"
// Image Types:
<< "image1D" << "iimage1D" << "uimage1D"
<< "image2D" << "iimage2D" << "uimage2D"
<< "image3D" << "iimage3D" << "uimage3D"
<< "imageCube" << "iimageCube" << "uimageCube"
<< "image2DRect" << "iimage2DRect" << "uimage2DRect"
<< "image1DArray" << "iimage1DArray" << "uimage1DArray"
<< "image2DArray" << "iimage2DArray" << "uimage2DArray"
<< "imageCubeArray" << "iimageCubeArray" << "uimageCubeArray"
<< "imageBuffer" << "iimageBuffer" << "uimageBuffer"
<< "image2DMS" << "iimage2DMS" << "uimage2DMS"
<< "image2DMSArray" << "iimage2DMSArray" << "uimage2DMSArray"
// Image Formats:
// Floating-point: // Signed integer:
<< "rgba32f" << "rgba32i"
<< "rgba16f" << "rgba16i"
<< "rg32f" << "rgba8i"
<< "rg16f" << "rg32i"
<< "r11f_g11f_b10f" << "rg16i"
<< "r32f" << "rg8i"
<< "r16f" << "r32i"
<< "rgba16" << "r16i"
<< "rgb10_a2" << "r8i"
<< "rgba8" << "r8ui"
<< "rg16" // Unsigned integer:
<< "rg8" << "rgba32ui"
<< "r16" << "rgba16ui"
<< "r8" << "rgb10_a2ui"
<< "rgba16_snorm" << "rgba8ui"
<< "rgba8_snorm" << "rg32ui"
<< "rg16_snorm" << "rg16ui"
<< "rg8_snorm" << "rg8ui"
<< "r16_snorm" << "r32ui"
<< "r8_snorm" << "r16ui";
for (const QString& pattern : keywordPatterns)
addRule("\\b" + pattern + "\\b", Qt::darkBlue); // normal words like: soka, nani, or gomen
addRule("\\bGL_(?:[A-Z]|_)+\\b", Qt::darkMagenta); // constants like: GL_OMAE_WA_MOU_SHINDEIRU
addRule("\\bgl_(?:[A-Z]|[a-z]|_)+\\b", Qt::darkCyan); // reserved types like: gl_exploooooosion
addRule("\\B#[^\\s]+\\b", Qt::darkGray); // preprocessor instructions like: #waifu megumin
addRule("//[^\\n]*", Qt::darkGreen); // Single line comment
// Multi line comment
multiLineCommentFormat.setForeground(Qt::darkGreen);
commentStartExpression = QRegularExpression("/\\*");
commentEndExpression = QRegularExpression("\\*/");
}
| 7,877
|
C++
|
.cpp
| 171
| 43.374269
| 114
| 0.591098
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,091
|
kernel_explorer.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/kernel_explorer.cpp
|
#include <map>
#include <QVBoxLayout>
#include <QPushButton>
#include <QHeaderView>
#include <QTreeWidget>
#include <QTreeWidgetItem>
#include "Emu/IdManager.h"
#include "Emu/Cell/PPUThread.h"
#include "Emu/Cell/SPUThread.h"
#include "Emu/Cell/lv2/sys_lwmutex.h"
#include "Emu/Cell/lv2/sys_lwcond.h"
#include "Emu/Cell/lv2/sys_mutex.h"
#include "Emu/Cell/lv2/sys_cond.h"
#include "Emu/Cell/lv2/sys_semaphore.h"
#include "Emu/Cell/lv2/sys_event_flag.h"
#include "Emu/Cell/lv2/sys_rwlock.h"
#include "Emu/Cell/lv2/sys_prx.h"
#include "Emu/Cell/lv2/sys_overlay.h"
#include "Emu/Cell/lv2/sys_memory.h"
#include "Emu/Cell/lv2/sys_mmapper.h"
#include "Emu/Cell/lv2/sys_spu.h"
#include "Emu/Cell/lv2/sys_process.h"
#include "Emu/Cell/lv2/sys_timer.h"
#include "Emu/Cell/lv2/sys_rsx.h"
#include "Emu/Cell/lv2/sys_vm.h"
#include "Emu/Cell/lv2/sys_net.h"
#include "Emu/Cell/lv2/sys_net/lv2_socket.h"
#include "Emu/Cell/lv2/sys_fs.h"
#include "Emu/Cell/lv2/sys_interrupt.h"
#include "Emu/Cell/lv2/sys_rsxaudio.h"
#include "Emu/Cell/Modules/cellSpurs.h"
#include "Emu/RSX/RSXThread.h"
#include "kernel_explorer.h"
#include "qt_utils.h"
constexpr auto qstr = QString::fromStdString;
LOG_CHANNEL(sys_log, "SYS");
enum kernel_item_role
{
name_role = Qt::UserRole + 0,
expanded_role = Qt::UserRole + 1,
type_role = Qt::UserRole + 2,
id_role = Qt::UserRole + 3,
};
enum kernel_item_type : int
{
root,
node,
volatile_node,
solid_node,
leaf
};
static QTreeWidgetItem* add_child(QTreeWidgetItem* parent, const QString& text, int column, kernel_item_type type)
{
if (parent)
{
for (int i = 0; i < parent->childCount(); i++)
{
if (parent->child(i)->data(0, kernel_item_role::name_role).toString() == text)
{
return parent->child(i);
}
}
}
QTreeWidgetItem* item = gui::utils::add_child(parent, text, column);
if (item)
{
item->setData(0, kernel_item_role::name_role, text);
item->setData(0, kernel_item_role::type_role, type);
}
return item;
}
static QTreeWidgetItem* add_leaf(QTreeWidgetItem* parent, const QString& text, int column = 0)
{
return add_child(parent, text, column, kernel_item_type::leaf);
}
static QTreeWidgetItem* add_node(u32 id, QTreeWidgetItem* parent, const QString& text, int column = 0)
{
QTreeWidgetItem* node = add_child(parent, text, column, kernel_item_type::node);
if (node)
{
node->setData(0, kernel_item_role::id_role, id);
}
return node;
}
static QTreeWidgetItem* find_first_node(QTreeWidgetItem* parent, const QString& regexp)
{
if (parent)
{
const QRegularExpression re(regexp);
for (int i = 0; i < parent->childCount(); i++)
{
if (QTreeWidgetItem* item = parent->child(i); item &&
item->data(0, kernel_item_role::type_role).toInt() != kernel_item_type::leaf &&
re.match(item->data(0, kernel_item_role::name_role).toString()).hasMatch())
{
return item;
}
}
}
return nullptr;
}
// Find node with ID in selected node children
static QTreeWidgetItem* find_node(QTreeWidgetItem* root, u32 id)
{
if (root)
{
for (int i = 0; i < root->childCount(); i++)
{
if (QTreeWidgetItem* item = root->child(i); item &&
item->data(0, kernel_item_role::type_role).toInt() == kernel_item_type::node &&
item->data(0, kernel_item_role::id_role).toUInt() == id)
{
return item;
}
}
}
sys_log.fatal("find_node(root=%s, id=%d) failed", root ? root->text(0) : "?", id);
return nullptr;
}
static QTreeWidgetItem* add_volatile_node(QTreeWidgetItem* parent, const QString& base_text, const QString& text = "", int column = 0)
{
QTreeWidgetItem* node = find_first_node(parent, base_text + ".*");
if (!node)
{
node = add_child(parent, base_text, column, kernel_item_type::volatile_node);
}
if (node)
{
node->setText(0, text.isEmpty() ? base_text : text);
}
else
{
sys_log.fatal("add_volatile_node(parent=%s, regexp=%s) failed", parent ? parent->text(0) : "?", base_text + ".*");
}
return node;
}
static QTreeWidgetItem* add_solid_node(QTreeWidgetItem* parent, const QString& base_text, const QString& text = "", int column = 0)
{
QTreeWidgetItem* node = find_first_node(parent, base_text + ".*");
if (!node)
{
node = add_child(parent, base_text, column, kernel_item_type::solid_node);
}
if (node)
{
node->setText(0, text.isEmpty() ? base_text : text);
}
else
{
sys_log.fatal("add_solid_node(parent=%s, regexp=%s) failed", parent ? parent->text(0).toStdString() : "?", base_text.toStdString() + ".*");
}
return node;
}
kernel_explorer::kernel_explorer(QWidget* parent)
: QDialog(parent)
{
setWindowTitle(tr("Kernel Explorer | %1").arg(qstr(Emu.GetTitleAndTitleID())));
setObjectName("kernel_explorer");
setAttribute(Qt::WA_DeleteOnClose);
setMinimumSize(QSize(800, 600));
QVBoxLayout* vbox_panel = new QVBoxLayout();
QHBoxLayout* hbox_buttons = new QHBoxLayout();
QPushButton* button_refresh = new QPushButton(tr("Refresh"), this);
QPushButton* button_log = new QPushButton(tr("Log All"), this);
hbox_buttons->addWidget(button_refresh);
hbox_buttons->addSpacing(8);
hbox_buttons->addWidget(button_log);
hbox_buttons->addStretch();
m_tree = new QTreeWidget(this);
m_tree->setBaseSize(QSize(700, 450));
m_tree->setWindowTitle(tr("Kernel"));
m_tree->header()->close();
// Merge and display everything
vbox_panel->addSpacing(8);
vbox_panel->addLayout(hbox_buttons);
vbox_panel->addSpacing(8);
vbox_panel->addWidget(m_tree);
setLayout(vbox_panel);
// Events
connect(button_refresh, &QAbstractButton::clicked, this, &kernel_explorer::update);
connect(button_log, &QAbstractButton::clicked, this, [this]()
{
log();
m_log_buf.clear();
});
update();
}
void kernel_explorer::update()
{
const auto dct = g_fxo->try_get<lv2_memory_container>();
if (!dct)
{
m_tree->clear();
return;
}
const std::initializer_list<std::pair<u32, QString>> tree_item_names =
{
{ process_info , tr("Process Info")},
{ SYS_MEM_OBJECT , tr("Shared Memory")},
{ virtual_memory , tr("Virtual Memory")},
{ SYS_MUTEX_OBJECT , tr("Mutexes")},
{ SYS_COND_OBJECT , tr("Condition Variables")},
{ SYS_RWLOCK_OBJECT , tr("Reader Writer Locks")},
{ SYS_INTR_TAG_OBJECT , tr("Interrupt Tags")},
{ SYS_INTR_SERVICE_HANDLE_OBJECT , tr("Interrupt Service Handles")},
{ SYS_EVENT_QUEUE_OBJECT , tr("Event Queues")},
{ SYS_EVENT_PORT_OBJECT , tr("Event Ports")},
{ SYS_TRACE_OBJECT , tr("Traces")},
{ SYS_SPUIMAGE_OBJECT , tr("SPU Images")},
{ SYS_PRX_OBJECT , tr("PRX Modules")},
{ SYS_SPUPORT_OBJECT , tr("SPU Ports")},
{ SYS_OVERLAY_OBJECT , tr("Overlay Modules")},
{ SYS_LWMUTEX_OBJECT , tr("Light Weight Mutexes")},
{ SYS_TIMER_OBJECT , tr("Timers")},
{ SYS_SEMAPHORE_OBJECT , tr("Semaphores")},
{ SYS_FS_FD_OBJECT , tr("File Descriptors")},
{ SYS_LWCOND_OBJECT , tr("Light Weight Condition Variables")},
{ SYS_EVENT_FLAG_OBJECT , tr("Event Flags")},
{ SYS_RSXAUDIO_OBJECT , tr("RSXAudio Objects")},
{ memory_containers , tr("Memory Containers")},
{ ppu_threads , tr("PPU Threads")},
{ spu_threads , tr("SPU Threads")},
{ spu_thread_groups , tr("SPU Thread Groups")},
{ rsx_contexts , tr("RSX Contexts")},
{ sockets , tr("Sockets")},
{ file_descriptors , tr("File Descriptors")},
};
QTreeWidgetItem* root = m_tree->topLevelItem(0);
if (!root)
{
root = new QTreeWidgetItem();
root->setData(0, kernel_item_role::type_role, kernel_item_type::root);
m_tree->addTopLevelItem(root);
for (const auto& [key, name] : tree_item_names)
{
add_node(key, root, name);
}
}
else
{
std::function<void(QTreeWidgetItem*)> clean_up_tree;
clean_up_tree = [&clean_up_tree](QTreeWidgetItem* item)
{
if (item && item->data(0, kernel_item_role::type_role).toInt() != kernel_item_type::leaf)
{
item->setText(0, item->data(0, kernel_item_role::name_role).toString());
item->setData(0, kernel_item_role::expanded_role, item->isExpanded());
for (int i = item->childCount() - 1; i >= 0; i--)
{
switch (item->child(i)->data(0, kernel_item_role::type_role).toInt())
{
case kernel_item_type::leaf:
{
delete item->takeChild(i);
break;
}
case kernel_item_type::volatile_node:
{
if (item->child(i)->childCount() <= 0)
{
// Cleanup volatile node if it has no children
delete item->takeChild(i);
break;
}
[[fallthrough]];
}
case kernel_item_type::solid_node:
case kernel_item_type::node:
case kernel_item_type::root:
default:
{
clean_up_tree(item->child(i));
break;
}
}
}
}
};
clean_up_tree(root);
}
const u32 total_memory_usage = dct->used;
root->setText(0, qstr(fmt::format("Process 0x%08x: Total Memory Usage: 0x%x/0x%x (%0.2f/%0.2f MB)", process_getpid(), total_memory_usage, dct->size, 1. * total_memory_usage / (1024 * 1024)
, 1. * dct->size / (1024 * 1024))));
add_solid_node(find_node(root, additional_nodes::process_info), qstr(fmt::format("Process Info, Sdk Version: 0x%08x, PPC SEG: %#x, SFO Category: %s (Fake: %s)", g_ps3_process_info.sdk_ver, g_ps3_process_info.ppc_seg, Emu.GetCat(), Emu.GetFakeCat())));
auto display_program_segments = [this](QTreeWidgetItem* tree, const ppu_module& m)
{
for (usz i = 0; i < m.segs.size(); i++)
{
const u32 addr = m.segs[i].addr;
const u32 size = m.segs[i].size;
add_leaf(tree, qstr(fmt::format("Segment %u: (0x%08x...0x%08x), Flags: 0x%x"
, i, addr, addr + std::max<u32>(size, 1) - 1, m.segs[i].flags)));
}
};
idm::select<lv2_obj>([&](u32 id, lv2_obj& obj)
{
const auto node = find_node(root, id >> 24);
if (!node)
{
return;
}
auto show_waiters = [&](QTreeWidgetItem* tree, cpu_thread* cpu)
{
for (; cpu; cpu = cpu->get_next_cpu())
{
add_leaf(tree, qstr(fmt::format("Waiter: ID: 0x%x", cpu->get_class() == thread_class::spu ? static_cast<spu_thread*>(cpu)->lv2_id : cpu->id)));
}
};
switch (id >> 24)
{
case SYS_MEM_OBJECT:
{
auto& mem = static_cast<lv2_memory&>(obj);
const f64 size_mb = mem.size * 1. / (1024 * 1024);
if (mem.pshared)
{
add_leaf(node, qstr(fmt::format("Shared Mem 0x%08x: Size: 0x%x (%0.2f MB), Chunk: %s, Mappings: %u, Mem Container: %s, Key: %#llx", id, mem.size, size_mb, mem.align == 0x10000u ? "64K" : "1MB", +mem.counter, mem.ct->id, mem.key)));
break;
}
add_leaf(node, qstr(fmt::format("Shared Mem 0x%08x: Size: 0x%x (%0.2f MB), Chunk: %s, Mem Container: %s, Mappings: %u", id, mem.size, size_mb, mem.align == 0x10000u ? "64K" : "1MB", mem.ct->id, +mem.counter)));
break;
}
case SYS_MUTEX_OBJECT:
{
auto& mutex = static_cast<lv2_mutex&>(obj);
const auto control = mutex.control.load();
show_waiters(add_solid_node(node, qstr(fmt::format(u8"Mutex 0x%08x: “%s”", id, lv2_obj::name64(mutex.name))), qstr(fmt::format(u8"Mutex 0x%08x: “%s”, %s,%s Owner: %#x, Locks: %u, Key: %#llx, Conds: %u", id, lv2_obj::name64(mutex.name), mutex.protocol,
mutex.recursive == SYS_SYNC_RECURSIVE ? " Recursive," : "", control.owner, +mutex.lock_count, mutex.key, mutex.cond_count))), control.sq);
break;
}
case SYS_COND_OBJECT:
{
auto& cond = static_cast<lv2_cond&>(obj);
show_waiters(add_solid_node(node, qstr(fmt::format(u8"Cond 0x%08x: “%s”", id, lv2_obj::name64(cond.name))), qstr(fmt::format(u8"Cond 0x%08x: “%s”, %s, Mutex: 0x%08x, Key: %#llx", id, lv2_obj::name64(cond.name), cond.mutex->protocol, cond.mtx_id, cond.key))), cond.sq);
break;
}
case SYS_RWLOCK_OBJECT:
{
auto& rw = static_cast<lv2_rwlock&>(obj);
const s64 val = rw.owner;
auto tree = add_solid_node(node, qstr(fmt::format(u8"RW Lock 0x%08x: “%s”", id, lv2_obj::name64(rw.name))), qstr(fmt::format(u8"RW Lock 0x%08x: “%s”, %s, Owner: %#x(%d), Key: %#llx", id, lv2_obj::name64(rw.name), rw.protocol,
std::max<s64>(0, val >> 1), -std::min<s64>(0, val >> 1), rw.key)));
if (auto rq = +rw.rq)
{
show_waiters(add_solid_node(tree, "Reader Waiters"), rq);
}
if (auto wq = +rw.wq)
{
show_waiters(add_solid_node(tree, "Writer Waiters"), wq);
}
break;
}
case SYS_INTR_TAG_OBJECT:
{
auto& tag = static_cast<lv2_int_tag&>(obj);
const auto handler = tag.handler.get();
if (lv2_obj::check(handler))
{
add_leaf(node, qstr(fmt::format("Intr Tag 0x%08x, Handler: 0x%08x", id, handler->id)));
break;
}
add_leaf(node, qstr(fmt::format("Intr Tag 0x%08x, Handler: Unbound", id)));
break;
}
case SYS_INTR_SERVICE_HANDLE_OBJECT:
{
auto& serv = static_cast<lv2_int_serv&>(obj);
add_leaf(node, qstr(fmt::format("Intr Svc 0x%08x, PPU: 0x%07x, arg1: 0x%x, arg2: 0x%x", id, serv.thread->id, serv.arg1, serv.arg2)));
break;
}
case SYS_EVENT_QUEUE_OBJECT:
{
auto& eq = static_cast<lv2_event_queue&>(obj);
show_waiters(add_solid_node(node, qstr(fmt::format(u8"Event Queue 0x%08x: “%s”", id, lv2_obj::name64(eq.name))), qstr(fmt::format(u8"Event Queue 0x%08x: “%s”, %s, %s, Key: %#llx, Events: %zu/%d", id, lv2_obj::name64(eq.name), eq.protocol,
eq.type == SYS_SPU_QUEUE ? "SPU" : "PPU", eq.key, eq.events.size(), eq.size))), eq.type == SYS_SPU_QUEUE ? static_cast<cpu_thread*>(+eq.sq) : +eq.pq);
break;
}
case SYS_EVENT_PORT_OBJECT:
{
auto& ep = static_cast<lv2_event_port&>(obj);
const auto type = ep.type == SYS_EVENT_PORT_LOCAL ? "LOCAL"sv : "IPC"sv;
if (const auto queue = ep.queue.get(); lv2_obj::check(queue))
{
if (queue == idm::check_unlocked<lv2_obj, lv2_event_queue>(queue->id))
{
add_leaf(node, qstr(fmt::format("Event Port 0x%08x: %s, Name: %#llx, Event Queue (ID): 0x%08x", id, type, ep.name, queue->id)));
break;
}
// This code is unused until multi-process is implemented
if (queue == lv2_event_queue::find(queue->key).get())
{
add_leaf(node, qstr(fmt::format("Event Port 0x%08x: %s, Name: %#llx, Event Queue (IPC): %s", id, type, ep.name, queue->key)));
break;
}
}
add_leaf(node, qstr(fmt::format("Event Port 0x%08x: %s, Name: %#llx, Unbound", id, type, ep.name)));
break;
}
case SYS_TRACE_OBJECT:
{
add_leaf(node, qstr(fmt::format("Trace 0x%08x", id)));
break;
}
case SYS_SPUIMAGE_OBJECT:
{
auto& spi = static_cast<lv2_spu_image&>(obj);
add_leaf(node, qstr(fmt::format("SPU Image 0x%08x, Entry: 0x%x, Segs: *0x%x, Num Segs: %d", id, spi.e_entry, spi.segs, spi.nsegs)));
break;
}
case SYS_PRX_OBJECT:
{
auto& prx = static_cast<lv2_prx&>(obj);
if (prx.segs.empty())
{
add_leaf(node, qstr(fmt::format("PRX 0x%08x: '%s' (HLE)", id, prx.name)));
break;
}
const QString text = qstr(fmt::format("PRX 0x%08x: '%s', attr=0x%x, lib=%s", id, prx.name, prx.module_info_attributes, prx.module_info_name));
QTreeWidgetItem* prx_tree = add_solid_node(node, text, text);
display_program_segments(prx_tree, prx);
break;
}
case SYS_SPUPORT_OBJECT:
{
add_leaf(node, qstr(fmt::format("SPU Port 0x%08x", id)));
break;
}
case SYS_OVERLAY_OBJECT:
{
auto& ovl = static_cast<lv2_overlay&>(obj);
const QString text = qstr(fmt::format("OVL 0x%08x: '%s'", id, ovl.name));
QTreeWidgetItem* ovl_tree = add_solid_node(node, text, text);
display_program_segments(ovl_tree, ovl);
break;
}
case SYS_LWMUTEX_OBJECT:
{
auto& lwm = static_cast<lv2_lwmutex&>(obj);
std::string owner_str = "unknown"; // Either invalid state or the lwmutex control data was moved from
sys_lwmutex_t lwm_data{};
auto lv2_control = lwm.lv2_control.load();
if (lwm.control.try_read(lwm_data) && lwm_data.sleep_queue == id)
{
switch (const u32 owner = lwm_data.vars.owner)
{
case lwmutex_free: owner_str = "free"; break;
case lwmutex_dead: owner_str = "dead"; break;
case lwmutex_reserved: owner_str = "reserved"; break;
default:
{
if (idm::check_unlocked<named_thread<ppu_thread>>(owner))
{
owner_str = fmt::format("0x%x", owner);
}
else
{
fmt::append(owner_str, " (0x%x)", owner);
}
break;
}
}
}
else
{
show_waiters(add_solid_node(node, qstr(fmt::format(u8"LWMutex 0x%08x: “%s”", id, lv2_obj::name64(lwm.name))), qstr(fmt::format(u8"LWMutex 0x%08x: “%s”, %s, Signal: %#x (unmapped/invalid control data at *0x%x)", id, lv2_obj::name64(lwm.name), lwm.protocol, +lv2_control.signaled, lwm.control))), lv2_control.sq);
break;
}
show_waiters(add_solid_node(node, qstr(fmt::format(u8"LWMutex 0x%08x: “%s”", id, lv2_obj::name64(lwm.name))), qstr(fmt::format(u8"LWMutex 0x%08x: “%s”, %s,%s Owner: %s, Locks: %u, Signal: %#x, Control: *0x%x", id, lv2_obj::name64(lwm.name), lwm.protocol,
(lwm_data.attribute & SYS_SYNC_RECURSIVE) ? " Recursive," : "", owner_str, lwm_data.recursive_count, +lv2_control.signaled, lwm.control))), lv2_control.sq);
break;
}
case SYS_TIMER_OBJECT:
{
auto& timer = static_cast<lv2_timer&>(obj);
u32 timer_state{SYS_TIMER_STATE_STOP};
std::shared_ptr<lv2_event_queue> port;
u64 source = 0;
u64 data1 = 0;
u64 data2 = 0;
u64 expire = 0; // Next expiration time
u64 period = 0; // Period (oneshot if 0)
if (reader_lock r_lock(timer.mutex); true)
{
timer_state = timer.state;
port = timer.port;
source = timer.source;
data1 = timer.data1;
data2 = timer.data2;
expire = timer.expire; // Next expiration time
period = timer.period; // Period (oneshot if 0)
}
add_leaf(node, qstr(fmt::format("Timer 0x%08x: State: %s, Period: 0x%llx, Next Expire: 0x%llx, Queue ID: 0x%08x, Source: 0x%08x, Data1: 0x%08x, Data2: 0x%08x", id, timer_state ? "Running" : "Stopped"
, period, expire, port ? port->id : 0, source, data1, data2)));
break;
}
case SYS_SEMAPHORE_OBJECT:
{
auto& sema = static_cast<lv2_sema&>(obj);
const auto val = +sema.val;
show_waiters(add_solid_node(node, qstr(fmt::format(u8"Sema 0x%08x: “%s”", id, lv2_obj::name64(sema.name))), qstr(fmt::format(u8"Sema 0x%08x: “%s”, %s, Count: %d/%d, Key: %#llx", id, lv2_obj::name64(sema.name), sema.protocol,
std::max<s32>(val, 0), sema.max, sema.key, -std::min<s32>(val, 0)))), sema.sq);
break;
}
case SYS_LWCOND_OBJECT:
{
auto& lwc = static_cast<lv2_lwcond&>(obj);
show_waiters(add_solid_node(node, qstr(fmt::format(u8"LWCond 0x%08x: “%s”", id, lv2_obj::name64(lwc.name))), qstr(fmt::format(u8"LWCond 0x%08x: “%s”, %s, OG LWMutex: 0x%08x, Control: *0x%x", id, lv2_obj::name64(lwc.name), lwc.protocol, lwc.lwid, lwc.control))), lwc.sq);
break;
}
case SYS_EVENT_FLAG_OBJECT:
{
auto& ef = static_cast<lv2_event_flag&>(obj);
show_waiters(add_solid_node(node, qstr(fmt::format(u8"Event Flag 0x%08x: “%s”", id, lv2_obj::name64(ef.name))), qstr(fmt::format(u8"Event Flag 0x%08x: “%s”, %s, Type: 0x%x, Key: %#llx, Pattern: 0x%llx", id, lv2_obj::name64(ef.name), ef.protocol,
ef.type, ef.key, ef.pattern.load()))), ef.sq);
break;
}
case SYS_RSXAUDIO_OBJECT:
{
auto& rao = static_cast<lv2_rsxaudio&>(obj);
std::lock_guard lock(rao.mutex);
if (!rao.init)
{
break;
}
QTreeWidgetItem* rao_obj = add_solid_node(node, qstr(fmt::format(u8"RSXAudio 0x%08x: Shmem: 0x%08x", id, u32{rao.shmem})));
for (u64 q_idx = 0; q_idx < rao.event_queue.size(); q_idx++)
{
if (const auto& eq = rao.event_queue[q_idx])
{
add_leaf(rao_obj, qstr(fmt::format(u8"Event Queue %u: ID: 0x%08x", q_idx, eq->id)));
}
}
break;
}
default:
{
add_leaf(node, qstr(fmt::format("Unknown object 0x%08x", id)));
}
}
});
idm::select<sys_vm_t>([&](u32 /*id*/, sys_vm_t& vmo)
{
const u32 psize = vmo.psize;
add_leaf(find_node(root, additional_nodes::virtual_memory), qstr(fmt::format("Virtual Mem 0x%08x: Virtual Size: 0x%x (%0.2f MB), Physical Size: 0x%x (%0.2f MB), Mem Container: %s", vmo.addr
, vmo.size, vmo.size * 1. / (1024 * 1024), psize, psize * 1. / (1024 * 1024), vmo.ct->id)));
});
idm::select<lv2_socket>([&](u32 id, lv2_socket& sock)
{
add_leaf(find_node(root, additional_nodes::sockets), qstr(fmt::format("Socket %u: Type: %s, Family: %s, Wq: %zu", id, sock.get_type(), sock.get_family(), sock.get_queue_size())));
});
idm::select<lv2_memory_container>([&](u32 id, lv2_memory_container& container)
{
const u32 used = container.used;
add_leaf(find_node(root, additional_nodes::memory_containers), qstr(fmt::format("Memory Container 0x%08x: Used: 0x%x/0x%x (%0.2f/%0.2f MB)", id, used, container.size, used * 1. / (1024 * 1024), container.size * 1. / (1024 * 1024))));
});
std::optional<std::scoped_lock<shared_mutex, shared_mutex>> lock_idm_lv2(std::in_place, id_manager::g_mutex, lv2_obj::g_mutex);
// Postponed as much as possible for time accuracy
u64 current_time_storage = 0;
auto get_current_time = [¤t_time_storage]()
{
if (!current_time_storage)
{
// Evaluate on the first use for better consistency (this function can be quite slow)
// Yet once it is evaluated, keep it on the same value for consistency.
current_time_storage = get_guest_system_time();
}
return current_time_storage;
};
auto get_wait_time_str = [&](u64 start_time) -> std::string
{
if (!start_time)
{
return {};
}
if (start_time > get_current_time() && start_time - get_current_time() > 1'000'000)
{
return " (time underflow)";
}
const f64 wait_time = (get_current_time() >= start_time ? get_current_time() - start_time : 0) / 1000000.;
return fmt::format(" (%.1fs)", wait_time);
};
idm::select<named_thread<ppu_thread>>([&](u32 id, ppu_thread& ppu)
{
const auto func = ppu.last_function;
const ppu_thread_status status = lv2_obj::ppu_state(&ppu, false, false).first;
add_leaf(find_node(root, additional_nodes::ppu_threads), qstr(fmt::format(u8"PPU 0x%07x: “%s”, PRIO: %d, Joiner: %s, Status: %s, State: %s, %s func: “%s”%s", id, *ppu.ppu_tname.load(), ppu.prio.load().prio, ppu.joiner.load(), status, ppu.state.load()
, ppu.ack_suspend ? "After" : (ppu.current_function ? "In" : "Last"), func ? func : "", get_wait_time_str(ppu.start_time))));
}, idm::unlocked);
lock_idm_lv2.reset();
idm::select<named_thread<spu_thread>>([&](u32 /*id*/, spu_thread& spu)
{
const auto func = spu.current_func;
const u64 start_time = spu.start_time;
QTreeWidgetItem* spu_thread_tree = add_solid_node(find_node(root, additional_nodes::spu_threads), qstr(fmt::format(u8"SPU 0x%07x: “%s”", spu.lv2_id, *spu.spu_tname.load())), qstr(fmt::format(u8"SPU 0x%07x: “%s”, State: %s, Type: %s, Func: \"%s\"%s", spu.lv2_id, *spu.spu_tname.load(), spu.state.load(), spu.get_type(), start_time && func ? func : "", start_time ? get_wait_time_str(get_guest_system_time(start_time)) : "")));
if (spu.get_type() == spu_type::threaded)
{
reader_lock lock(spu.group->mutex);
bool has_connected_ports = false;
const auto first_spu = spu.group->threads[0].get();
// Always show information of the first thread in group
// Or if information differs from that thread
if (&spu == first_spu || std::any_of(std::begin(spu.spup), std::end(spu.spup), [&](const auto& port)
{
// Flag to avoid reporting information if no SPU ports are connected
has_connected_ports |= lv2_obj::check(port);
// Check if ports do not match with the first thread
return port != first_spu->spup[&port - spu.spup];
}))
{
for (const auto& port : spu.spup)
{
if (lv2_obj::check(port))
{
add_leaf(spu_thread_tree, qstr(fmt::format("SPU Port %u: Queue ID: 0x%08x", &port - spu.spup, port->id)));
}
}
}
else if (has_connected_ports)
{
// Avoid duplication of information between threads which is common
add_leaf(spu_thread_tree, qstr(fmt::format("SPU Ports: As SPU 0x%07x", first_spu->lv2_id)));
}
for (const auto& [key, queue] : spu.spuq)
{
if (lv2_obj::check(queue))
{
add_leaf(spu_thread_tree, qstr(fmt::format("SPU Queue: Queue ID: 0x%08x, Key: 0x%x", queue->id, key)));
}
}
}
else
{
for (const auto& ctrl : spu.int_ctrl)
{
if (lv2_obj::check(ctrl.tag))
{
add_leaf(spu_thread_tree, qstr(fmt::format("Interrupt Tag %u: ID: 0x%x, Mask: 0x%x, Status: 0x%x", &ctrl - spu.int_ctrl.data(), ctrl.tag->id, +ctrl.mask, +ctrl.stat)));
}
}
}
});
idm::select<lv2_spu_group>([&](u32 id, lv2_spu_group& tg)
{
QTreeWidgetItem* spu_tree = add_solid_node(find_node(root, additional_nodes::spu_thread_groups), qstr(fmt::format(u8"SPU Group 0x%07x: “%s”, Type = 0x%x", id, tg.name, tg.type)), qstr(fmt::format(u8"SPU Group 0x%07x: “%s”, Status = %s, Priority = %d, Type = 0x%x", id, tg.name, tg.run_state.load(), tg.prio.load().prio, tg.type)));
if (tg.name.ends_with("CellSpursKernelGroup"sv))
{
vm::ptr<CellSpurs> pspurs{};
for (const auto& thread : tg.threads)
{
if (thread)
{
// Find SPURS structure address
const u64 arg = tg.args[thread->index][1];
if (!pspurs)
{
if (arg < u32{umax} && arg % 0x80 == 0 && vm::check_addr(arg, vm::page_readable, pspurs.size()))
{
pspurs.set(static_cast<u32>(arg));
}
else
{
break;
}
}
else if (pspurs.addr() != arg)
{
pspurs = {};
break;
}
}
}
CellSpurs spurs{};
if (pspurs && pspurs.try_read(spurs))
{
const QString branch_name = tr("SPURS %1").arg(pspurs.addr());
const u32 wklEnabled = spurs.wklEnabled;
QTreeWidgetItem* spurs_tree = add_solid_node(spu_tree, branch_name, qstr(fmt::format("SPURS, Instance: *0x%x, LWMutex: 0x%x, LWCond: 0x%x, wklEnabled: 0x%x"
, pspurs, spurs.mutex.sleep_queue, spurs.cond.lwcond_queue, wklEnabled)));
const u32 signal_mask = u32{spurs.wklSignal1} << 16 | spurs.wklSignal2;
for (u32 wid = 0; wid < CELL_SPURS_MAX_WORKLOAD2; wid++)
{
if (!(wklEnabled & (0x80000000u >> wid)))
{
continue;
}
const auto state = spurs.wklState(wid).raw();
if (state == SPURS_WKL_STATE_NON_EXISTENT)
{
continue;
}
const u32 ready_count = spurs.readyCount(wid);
const auto& name = spurs.wklName(wid);
const u8 evt = spurs.wklEvent(wid);
const u8 status = spurs.wklStatus(wid);
const auto has_signal = (signal_mask & (0x80000000u >> wid)) ? "Signalled"sv : "No Signal"sv;
QTreeWidgetItem* wkl_tree = add_solid_node(spurs_tree, branch_name + qstr(fmt::format(" Work.%u", wid)), qstr(fmt::format("Work.%u, class: %s, %s, %s, Status: %#x, Event: %#x, %s, ReadyCnt: %u", wid, +name.nameClass, +name.nameInstance, state, status, evt, has_signal, ready_count)));
auto contention = [&](u8 v)
{
if (wid >= CELL_SPURS_MAX_WORKLOAD)
return (v >> 4);
else
return v & 0xf;
};
const auto& winfo = spurs.wklInfo(wid);
add_leaf(wkl_tree, qstr(fmt::format("Contention: %u/%u (pending: %u), Image: *0x%x (size: 0x%x, arg: 0x%x), Priority (BE64): %016x", contention(spurs.wklCurrentContention[wid % 16])
, contention(spurs.wklMaxContention[wid % 16]), contention(spurs.wklPendingContention[wid % 16]), +winfo.addr, winfo.size, winfo.arg, std::bit_cast<be_t<u64>>(winfo.priority))));
}
add_leaf(spurs_tree, qstr(fmt::format("Handler Info: PPU0: 0x%x, PPU1: 0x%x, DirtyState: %u, Waiting: %u, Exiting: %u", spurs.ppu0, spurs.ppu1
, +spurs.handlerDirty, +spurs.handlerWaiting, +spurs.handlerExiting)));
}
else
{
// TODO: Might be old CellSpurs structure which is smaller
}
}
});
QTreeWidgetItem* rsx_context_node = find_node(root, additional_nodes::rsx_contexts);
do
{
// Currently a single context is supported at a time
const auto rsx = rsx::get_current_renderer();
if (!rsx)
{
break;
}
const auto base = rsx->dma_address;
if (!base)
{
break;
}
const QString branch_name = "RSX Context 0x55555555";
QTreeWidgetItem* rsx_tree = add_solid_node(rsx_context_node, branch_name,
branch_name + qstr(fmt::format(u8", Local Size: %u MB, Base Addr: 0x%x, Device Addr: 0x%x, Handlers: 0x%x", rsx->local_mem_size >> 20, base, rsx->device_addr, +vm::_ref<RsxDriverInfo>(rsx->driver_info).handlers)));
QTreeWidgetItem* io_tree = add_volatile_node(rsx_tree, tr("IO-EA Table"));
QTreeWidgetItem* zc_tree = add_volatile_node(rsx_tree, tr("Zcull Bindings"));
QTreeWidgetItem* db_tree = add_volatile_node(rsx_tree, tr("Display Buffers"));
decltype(rsx->iomap_table) table;
decltype(rsx->display_buffers) dbs;
decltype(rsx->zculls) zcs;
{
reader_lock lock(rsx->sys_rsx_mtx);
std::memcpy(&table, &rsx->iomap_table, sizeof(table));
std::memcpy(&dbs, rsx->display_buffers, sizeof(dbs));
std::memcpy(&zcs, &rsx->zculls, sizeof(zcs));
}
for (u32 i = 0, size_block = 0, first_ea = 0, first_io = 0;;)
{
const auto addr = table.get_addr(i << 20);
if (addr == umax)
{
if (size_block)
{
// Print block
add_leaf(io_tree, qstr(fmt::format("IO: %08x, EA: %08x, Size: %uMB", first_io, first_ea, size_block)));
}
if (i >= 512u)
{
break;
}
size_block = 0;
i++;
continue;
}
const auto old_block_size = size_block++;
i++;
if (old_block_size)
{
if (first_ea + (old_block_size << 20) == addr)
{
continue;
}
else
{
// Print last block before we continue to a new one
add_leaf(io_tree, qstr(fmt::format("IO: %08x, EA: %08x, Size: %uMB", first_io, first_ea, old_block_size)));
size_block = 1;
first_ea = addr;
first_io = (i - 1) << 20;
continue;
}
}
else
{
first_ea = addr;
first_io = (i - 1) << 20;
}
}
for (const auto& zc : zcs)
{
if (zc.bound)
{
add_leaf(zc_tree, qstr(fmt::format("O: %07x, W: %u, H: %u, Zformat: 0x%x, AAformat: 0x%x, Dir: 0x%x, sFunc: 0x%x, sRef: %02x, sMask: %02x"
, zc.offset, zc.height, zc.width, zc.zFormat, zc.aaFormat, zc.zcullDir, zc.sFunc, zc.sRef, zc.sMask)));
}
}
for (const auto& db : dbs)
{
if (db.valid())
{
add_leaf(db_tree, qstr(fmt::format("Offset: %07x, Width: %u, Height: %u, Pitch: %u"
, db.offset, db.height, db.width, db.pitch)));
}
}
}
while (false);
idm::select<lv2_fs_object>([&](u32 id, lv2_fs_object& fo)
{
const std::string str = fmt::format("FD %u: %s", id, [&]() -> std::string
{
if (idm::check_unlocked<lv2_fs_object, lv2_file>(id))
{
return fmt::format("%s", static_cast<lv2_file&>(fo));
}
if (idm::check_unlocked<lv2_fs_object, lv2_dir>(id))
{
return fmt::format("%s", static_cast<lv2_dir&>(fo));
}
return "Unknown object!";
}());
add_leaf(find_node(root, additional_nodes::file_descriptors), qstr(str));
});
std::function<int(QTreeWidgetItem*)> final_touches;
final_touches = [&final_touches](QTreeWidgetItem* item) -> int
{
int visible_children = 0;
for (int i = 0; i < item->childCount(); i++)
{
auto node = item->child(i);
if (!node)
{
continue;
}
switch (const int type = node->data(0, kernel_item_role::type_role).toInt())
{
case kernel_item_type::leaf:
{
node->setHidden(false);
break;
}
case kernel_item_type::node:
case kernel_item_type::solid_node:
case kernel_item_type::volatile_node:
{
const int count = final_touches(node);
if (count > 0)
{
// Append count
node->setText(0, node->text(0) + qstr(fmt::format(" (%zu)", count)));
// Expand if necessary
node->setExpanded(node->data(0, kernel_item_role::expanded_role).toBool());
}
// Hide node if it has no children
node->setHidden(type != kernel_item_type::solid_node && count <= 0);
break;
}
case kernel_item_type::root:
default:
{
break;
}
}
if (!node->isHidden())
{
visible_children++;
}
}
return visible_children;
};
final_touches(root);
root->setExpanded(true);
}
void kernel_explorer::log(u32 level, QTreeWidgetItem* item)
{
if (!item)
{
item = m_tree->topLevelItem(0);
if (!item)
{
return;
}
m_log_buf = qstr(fmt::format("Kernel Explorer: %s\n", Emu.GetTitleAndTitleID()));
log(level + 1, item);
sys_log.success("%s", m_log_buf);
return;
}
for (u32 j = 0; j < level; j++)
{
m_log_buf += QChar::Space;
}
m_log_buf.append(item->text(0));
m_log_buf += '\n';
for (int i = 0; i < item->childCount(); i++)
{
if (auto node = item->child(i); node && !node->isHidden())
{
log(level + 1, node);
}
}
}
| 32,821
|
C++
|
.cpp
| 899
| 32.680756
| 427
| 0.633188
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,092
|
flow_layout.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/flow_layout.cpp
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtWidgets>
#include "flow_layout.h"
flow_layout::flow_layout(QWidget* parent, int margin, bool dynamic_spacing, int hSpacing, int vSpacing)
: QLayout(parent)
, m_dynamic_spacing(dynamic_spacing)
, m_h_space_initial(hSpacing)
, m_v_space_initial(vSpacing)
, m_h_space(hSpacing)
, m_v_space(vSpacing)
{
setContentsMargins(margin, margin, margin, margin);
}
flow_layout::flow_layout(int margin, bool dynamic_spacing, int hSpacing, int vSpacing)
: m_dynamic_spacing(dynamic_spacing)
, m_h_space_initial(hSpacing)
, m_v_space_initial(vSpacing)
, m_h_space(hSpacing)
, m_v_space(vSpacing)
{
setContentsMargins(margin, margin, margin, margin);
}
flow_layout::~flow_layout()
{
clear();
}
void flow_layout::clear()
{
while (QLayoutItem* item = takeAt(0))
{
delete item->widget();
delete item;
}
m_item_list.clear();
m_positions.clear();
}
void flow_layout::addItem(QLayoutItem* item)
{
m_positions.append(position{ .row = -1, .col = -1 });
m_item_list.append(item);
}
int flow_layout::horizontalSpacing() const
{
if (m_h_space >= 0)
{
return m_h_space;
}
return smartSpacing(QStyle::PM_LayoutHorizontalSpacing);
}
int flow_layout::verticalSpacing() const
{
if (m_v_space >= 0)
{
return m_v_space;
}
return smartSpacing(QStyle::PM_LayoutVerticalSpacing);
}
int flow_layout::count() const
{
return m_item_list.size();
}
QLayoutItem* flow_layout::itemAt(int index) const
{
return m_item_list.value(index);
}
QLayoutItem* flow_layout::takeAt(int index)
{
if (index >= 0 && index < m_item_list.size())
{
m_positions.takeAt(index);
return m_item_list.takeAt(index);
}
return nullptr;
}
Qt::Orientations flow_layout::expandingDirections() const
{
return {};
}
bool flow_layout::hasHeightForWidth() const
{
return true;
}
int flow_layout::heightForWidth(int width) const
{
return doLayout(QRect(0, 0, width, 0), true);
}
void flow_layout::setGeometry(const QRect& rect)
{
QLayout::setGeometry(rect);
doLayout(rect, false);
}
QSize flow_layout::sizeHint() const
{
return minimumSize();
}
QSize flow_layout::minimumSize() const
{
QSize size;
for (const QLayoutItem* item : m_item_list)
{
if (item)
{
size = size.expandedTo(item->minimumSize());
}
}
const QMargins margins = contentsMargins();
size += QSize(margins.left() + margins.right(), margins.top() + margins.bottom());
return size;
}
int flow_layout::doLayout(const QRect& rect, bool testOnly) const
{
int left, top, right, bottom;
getContentsMargins(&left, &top, &right, &bottom);
const QRect effectiveRect = rect.adjusted(+left, +top, -right, -bottom);
int x = effectiveRect.x();
int y = effectiveRect.y();
int lineHeight = 0;
int rows = 0;
int cols = 0;
if (m_dynamic_spacing)
{
const int available_width = effectiveRect.width();
const int min_spacing = smartSpacing(QStyle::PM_LayoutHorizontalSpacing);
bool fits_into_width = true;
int width = 0;
int index = 0;
for (; index < m_item_list.size(); index++)
{
if (QLayoutItem* item = m_item_list.at(index))
{
const int new_width = width + item->sizeHint().width() + (width > 0 ? min_spacing : 0);
if (new_width > effectiveRect.width())
{
fits_into_width = false;
break;
}
width = new_width;
}
}
// Try to evenly distribute the items across the width
m_h_space = (index == 0) ? -1 : ((available_width - width) / index);
if (fits_into_width)
{
// Make sure there aren't huge gaps between the items
m_h_space = smartSpacing(QStyle::PM_LayoutHorizontalSpacing);
}
}
else
{
m_h_space = m_h_space_initial;
}
for (int i = 0, row = 0, col = 0; i < m_item_list.size(); i++)
{
QLayoutItem* item = m_item_list.at(i);
if (!item)
continue;
const QWidget* wid = item->widget();
if (!wid)
continue;
int spaceX = horizontalSpacing();
if (spaceX == -1)
spaceX = wid->style()->layoutSpacing(QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Horizontal);
int spaceY = verticalSpacing();
if (spaceY == -1)
spaceY = wid->style()->layoutSpacing(QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Vertical);
int nextX = x + item->sizeHint().width() + spaceX;
if (nextX - spaceX > effectiveRect.right() && lineHeight > 0)
{
x = effectiveRect.x();
y = y + lineHeight + spaceY;
nextX = x + item->sizeHint().width() + spaceX;
lineHeight = 0;
col = 0;
row++;
}
position& pos = m_positions[i];
pos.row = row;
pos.col = col++;
rows = std::max(rows, pos.row + 1);
cols = std::max(cols, pos.col + 1);
if (!testOnly)
item->setGeometry(QRect(QPoint(x, y), item->sizeHint()));
x = nextX;
lineHeight = qMax(lineHeight, item->sizeHint().height());
}
m_rows = rows;
m_cols = cols;
return y + lineHeight - rect.y() + bottom;
}
int flow_layout::smartSpacing(QStyle::PixelMetric pm) const
{
const QObject* parent = this->parent();
if (!parent)
{
return -1;
}
if (parent->isWidgetType())
{
const QWidget* pw = static_cast<const QWidget*>(parent);
return pw->style()->pixelMetric(pm, nullptr, pw);
}
return static_cast<const QLayout*>(parent)->spacing();
}
| 7,566
|
C++
|
.cpp
| 251
| 27.984064
| 106
| 0.700811
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,093
|
system_cmd_dialog.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/system_cmd_dialog.cpp
|
#include "stdafx.h"
#include "system_cmd_dialog.h"
#include "Emu/System.h"
#include "Emu/Cell/Modules/cellSysutil.h"
#include "Emu/Cell/Modules/cellNetCtl.h"
#include "Emu/Cell/Modules/cellOskDialog.h"
#include <QPushButton>
#include <QFontDatabase>
#include <QRegularExpressionValidator>
#include <QGroupBox>
#include <QMessageBox>
#include <QVBoxLayout>
LOG_CHANNEL(gui_log, "GUI");
system_cmd_dialog::system_cmd_dialog(QWidget* parent)
: QDialog(parent)
{
setWindowTitle(tr("System Commands | %1").arg(QString::fromStdString(Emu.GetTitleAndTitleID())));
setObjectName("system_cmd_dialog");
setAttribute(Qt::WA_DeleteOnClose);
QPushButton* button_send = new QPushButton(tr("Send Command"), this);
connect(button_send, &QAbstractButton::clicked, this, &system_cmd_dialog::send_command);
QPushButton* button_send_custom = new QPushButton(tr("Send Custom Command"), this);
connect(button_send_custom, &QAbstractButton::clicked, this, &system_cmd_dialog::send_custom_command);
const QFont mono = QFontDatabase::systemFont(QFontDatabase::FixedFont);
m_value_input = new QLineEdit();
m_value_input->setFont(mono);
m_value_input->setMaxLength(18);
m_value_input->setValidator(new QRegularExpressionValidator(QRegularExpression("^(0[xX])?0*[a-fA-F0-9]{0,8}$"), this));
m_value_input->setPlaceholderText(QString("0x%1").arg(0, 16, 16, QChar('0')));
m_custom_command_input = new QLineEdit();
m_custom_command_input->setFont(mono);
m_custom_command_input->setMaxLength(18);
m_custom_command_input->setValidator(new QRegularExpressionValidator(QRegularExpression("^(0[xX])?0*[a-fA-F0-9]{0,8}$"), this));
m_custom_command_input->setPlaceholderText(QString("0x%1").arg(0, 16, 16, QChar('0')));
m_command_box = new QComboBox();
const std::map<u64, QString> commands
{
{ CELL_SYSUTIL_REQUEST_EXITGAME, "CELL_SYSUTIL_REQUEST_EXITGAME " },
{ CELL_SYSUTIL_DRAWING_BEGIN, "CELL_SYSUTIL_DRAWING_BEGIN" },
{ CELL_SYSUTIL_DRAWING_END, "CELL_SYSUTIL_DRAWING_END" },
{ CELL_SYSUTIL_SYSTEM_MENU_OPEN, "CELL_SYSUTIL_SYSTEM_MENU_OPEN" },
{ CELL_SYSUTIL_SYSTEM_MENU_CLOSE, "CELL_SYSUTIL_SYSTEM_MENU_CLOSE" },
{ CELL_SYSUTIL_BGMPLAYBACK_PLAY, "CELL_SYSUTIL_BGMPLAYBACK_PLAY" },
{ CELL_SYSUTIL_BGMPLAYBACK_STOP, "CELL_SYSUTIL_BGMPLAYBACK_STOP" },
{ CELL_SYSUTIL_NP_INVITATION_SELECTED, "CELL_SYSUTIL_NP_INVITATION_SELECTED" },
{ CELL_SYSUTIL_NP_DATA_MESSAGE_SELECTED, "CELL_SYSUTIL_NP_DATA_MESSAGE_SELECTED" },
{ CELL_SYSUTIL_SYSCHAT_START, "CELL_SYSUTIL_SYSCHAT_START" },
{ CELL_SYSUTIL_SYSCHAT_STOP, "CELL_SYSUTIL_SYSCHAT_STOP" },
{ CELL_SYSUTIL_SYSCHAT_VOICE_STREAMING_RESUMED, "CELL_SYSUTIL_SYSCHAT_VOICE_STREAMING_RESUMED" },
{ CELL_SYSUTIL_SYSCHAT_VOICE_STREAMING_PAUSED, "CELL_SYSUTIL_SYSCHAT_VOICE_STREAMING_PAUSED" },
{ CELL_SYSUTIL_NET_CTL_NETSTART_LOADED, "CELL_SYSUTIL_NET_CTL_NETSTART_LOADED" },
{ CELL_SYSUTIL_NET_CTL_NETSTART_FINISHED, "CELL_SYSUTIL_NET_CTL_NETSTART_FINISHED" },
{ CELL_SYSUTIL_NET_CTL_NETSTART_UNLOADED, "CELL_SYSUTIL_NET_CTL_NETSTART_UNLOADED" },
{ CELL_SYSUTIL_OSKDIALOG_LOADED, "CELL_SYSUTIL_OSKDIALOG_LOADED" },
{ CELL_SYSUTIL_OSKDIALOG_FINISHED, "CELL_SYSUTIL_OSKDIALOG_FINISHED" },
{ CELL_SYSUTIL_OSKDIALOG_UNLOADED, "CELL_SYSUTIL_OSKDIALOG_UNLOADED" },
{ CELL_SYSUTIL_OSKDIALOG_INPUT_ENTERED, "CELL_SYSUTIL_OSKDIALOG_INPUT_ENTERED" },
{ CELL_SYSUTIL_OSKDIALOG_INPUT_CANCELED, "CELL_SYSUTIL_OSKDIALOG_INPUT_CANCELED" },
{ CELL_SYSUTIL_OSKDIALOG_INPUT_DEVICE_CHANGED, "CELL_SYSUTIL_OSKDIALOG_INPUT_DEVICE_CHANGED" },
{ CELL_SYSUTIL_OSKDIALOG_DISPLAY_CHANGED, "CELL_SYSUTIL_OSKDIALOG_DISPLAY_CHANGED" },
};
for (const auto& [status, text] : commands)
{
m_command_box->addItem(text, static_cast<qulonglong>(status));
}
QGroupBox* commands_group = new QGroupBox(tr("Select Command"));
QHBoxLayout* hbox_commands = new QHBoxLayout();
hbox_commands->addWidget(m_command_box);
commands_group->setLayout(hbox_commands);
QGroupBox* custom_commands_group = new QGroupBox(tr("Select Custom Command"));
QHBoxLayout* hbox_custom_commands = new QHBoxLayout();
hbox_custom_commands->addWidget(m_custom_command_input);
custom_commands_group->setLayout(hbox_custom_commands);
QGroupBox* value_group = new QGroupBox(tr("Select Value"));
QHBoxLayout* hbox_value = new QHBoxLayout();
hbox_value->addWidget(m_value_input);
value_group->setLayout(hbox_value);
QHBoxLayout* hbox_buttons = new QHBoxLayout();
hbox_buttons->addWidget(button_send);
hbox_buttons->addWidget(button_send_custom);
QVBoxLayout* vbox_panel = new QVBoxLayout();
vbox_panel->addWidget(commands_group);
vbox_panel->addWidget(custom_commands_group);
vbox_panel->addWidget(value_group);
vbox_panel->addLayout(hbox_buttons);
setLayout(vbox_panel);
}
system_cmd_dialog::~system_cmd_dialog()
{
}
void system_cmd_dialog::send_command()
{
bool ok = false;
const qulonglong status = m_command_box->currentData().toULongLong(&ok);
if (!ok)
{
gui_log.error("system_cmd_dialog::send_command: command can not be converted to qulonglong: %s", m_command_box->currentText());
QMessageBox::warning(this, tr("Listen!"), tr("The selected command is bugged.\nPlease contact a developer."));
return;
}
const qulonglong param = hex_value(m_value_input->text(), ok);
if (!ok)
{
gui_log.error("system_cmd_dialog::send_command: value can not be converted to qulonglong: %s", m_value_input->text());
QMessageBox::information(this, tr("Listen!"), tr("Please select a proper value first."));
return;
}
send_cmd(status, param);
}
void system_cmd_dialog::send_custom_command()
{
bool ok = false;
const qulonglong status = hex_value(m_custom_command_input->text(), ok);
if (!ok)
{
gui_log.error("system_cmd_dialog::send_custom_command: command can not be converted to qulonglong: %s", m_custom_command_input->text());
QMessageBox::information(this, tr("Listen!"), tr("Please select a proper custom command first."));
return;
}
const qulonglong param = hex_value(m_value_input->text(), ok);
if (!ok)
{
gui_log.error("system_cmd_dialog::send_custom_command: value can not be converted to qulonglong: %s", m_value_input->text());
QMessageBox::information(this, tr("Listen!"), tr("Please select a proper value first."));
return;
}
send_cmd(status, param);
}
void system_cmd_dialog::send_cmd(qulonglong status, qulonglong param) const
{
if (Emu.IsStopped())
{
return;
}
gui_log.warning("User triggered sysutil_send_system_cmd(status=0x%x, param=0x%x) in system_cmd_dialog", status, param);
if (s32 ret = sysutil_send_system_cmd(status, param); ret < 0)
{
gui_log.error("sysutil_send_system_cmd(status=0x%x, param=0x%x) failed with 0x%x", status, param, ret);
}
}
qulonglong system_cmd_dialog::hex_value(QString text, bool& ok) const
{
if (!text.startsWith("0x")) text.prepend("0x");
return text.toULongLong(&ok, 16);
}
| 6,825
|
C++
|
.cpp
| 145
| 44.813793
| 138
| 0.747368
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,094
|
user_account.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/user_account.cpp
|
#include "user_account.h"
#include "Emu/system_utils.hpp"
#include "Utilities/File.h"
#include "util/logs.hpp"
LOG_CHANNEL(gui_log, "GUI");
user_account::user_account(const std::string& user_id)
{
// Setting userId.
m_user_id = user_id;
// Setting userDir.
m_user_dir = rpcs3::utils::get_hdd0_dir() + "home/" + m_user_id + "/";
// Setting userName.
if (fs::file file; file.open(m_user_dir + "localusername", fs::read))
{
m_username = file.to_string();
file.close();
if (m_username.length() > 16) // max of 16 chars on real PS3
{
m_username = m_username.substr(0, 16);
gui_log.warning("user_account: localusername of userId=%s was too long, cropped to: %s", m_user_id, m_username);
}
}
else
{
gui_log.error("user_account: localusername file read error (userId=%s, userDir=%s).", m_user_id, m_user_dir);
}
}
std::map<u32, user_account> user_account::GetUserAccounts(const std::string& base_dir)
{
std::map<u32, user_account> user_list;
// I believe this gets the folder list sorted alphabetically by default,
// but I can't find proof of this always being true.
for (const auto& user_folder : fs::dir(base_dir))
{
if (!user_folder.is_directory)
{
continue;
}
// Is the folder name exactly 8 all-numerical characters long?
const u32 key = rpcs3::utils::check_user(user_folder.name);
if (key == 0)
{
continue;
}
// Does the localusername file exist?
if (!fs::is_file(base_dir + "/" + user_folder.name + "/localusername"))
{
continue;
}
user_list.emplace(key, user_account(user_folder.name));
}
return user_list;
}
| 1,594
|
C++
|
.cpp
| 53
| 27.490566
| 115
| 0.684555
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
5,095
|
localized.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/localized.cpp
|
#include "localized.h"
#include "Loader/PSF.h"
QString Localized::GetVerboseTimeByMs(quint64 elapsed_ms, bool show_days) const
{
const quint64 elapsed_seconds = (elapsed_ms / 1000) + ((elapsed_ms % 1000) > 0 ? 1 : 0);
quint64 hours = elapsed_seconds / 3600;
quint64 days = 0;
if (show_days)
{
days = hours / 24;
hours = hours % 24;
}
const quint64 minutes = (elapsed_seconds % 3600) / 60;
const quint64 seconds = (elapsed_seconds % 3600) % 60;
QString str_days = tr("%Ln day(s)", "", days);
QString str_hours = tr("%Ln hour(s)", "", hours);
QString str_minutes = tr("%Ln minute(s)", "", minutes);
QString str_seconds = tr("%Ln second(s)", "", seconds);
if (days != 0)
{
if (hours == 0)
return str_days;
return tr("%0 and %1", "Days and hours").arg(str_days).arg(str_hours);
}
if (hours != 0)
{
if (minutes == 0)
return str_hours;
return tr("%0 and %1", "Hours and minutes").arg(str_hours).arg(str_minutes);
}
if (minutes != 0)
{
if (seconds != 0)
return tr("%0 and %1", "Minutes and seconds").arg(str_minutes).arg(str_seconds);
return str_minutes;
}
return str_seconds;
}
std::string Localized::GetStringFromU32(const u32& key, const std::map<u32, QString>& map, bool combined)
{
QStringList string;
if (combined)
{
for (const auto& item : map)
{
if (key & item.first)
{
string << item.second;
}
}
}
else
{
if (map.find(key) != map.end())
{
string << ::at32(map, key);
}
}
if (string.isEmpty())
{
string << tr("Unknown");
}
return string.join(", ").toStdString();
}
Localized::resolution::resolution()
: mode({
{ psf::resolution_flag::_480, tr("480") },
{ psf::resolution_flag::_576, tr("576") },
{ psf::resolution_flag::_720, tr("720") },
{ psf::resolution_flag::_1080, tr("1080") },
{ psf::resolution_flag::_480_16_9, tr("480 16:9") },
{ psf::resolution_flag::_576_16_9, tr("576 16:9") },
})
{
}
Localized::sound::sound()
: format({
{ psf::sound_format_flag::lpcm_2, tr("LPCM 2.0") },
{ psf::sound_format_flag::lpcm_5_1, tr("LPCM 5.1") },
{ psf::sound_format_flag::lpcm_7_1, tr("LPCM 7.1") },
{ psf::sound_format_flag::ac3, tr("Dolby Digital 5.1") },
{ psf::sound_format_flag::dts, tr("DTS 5.1") },
})
{
}
Localized::title_t::title_t()
: titles({
{ "vsh/module/vsh.self", tr("The PS3 Interface (XMB, or VSH)") },
})
{
}
| 2,393
|
C++
|
.cpp
| 91
| 23.813187
| 105
| 0.613567
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,096
|
vfs_tool_dialog.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/vfs_tool_dialog.cpp
|
#include "stdafx.h"
#include "vfs_tool_dialog.h"
#include "ui_vfs_tool_dialog.h"
#include "Emu/VFS.h"
#include "Emu/System.h"
vfs_tool_dialog::vfs_tool_dialog(QWidget *parent)
: QDialog(parent)
, ui(new Ui::vfs_tool_dialog)
{
setAttribute(Qt::WA_DeleteOnClose);
ui->setupUi(this);
connect(ui->pathEdit, &QLineEdit::textChanged, this, &vfs_tool_dialog::handle_vfs_path);
handle_vfs_path("");
}
vfs_tool_dialog::~vfs_tool_dialog()
{
}
void vfs_tool_dialog::handle_vfs_path(const QString& path)
{
// Initialize Emu if not yet initialized (e.g. Emu.Kill() was previously invoked) before using some of the following vfs:: functions (e.g. vfs::get())
if (Emu.IsStopped())
{
Emu.Init();
}
const std::string spath = path.toStdString();
const std::string vfs_get_path = vfs::get(spath);
const std::string vfs_retrieve_path = vfs::retrieve(spath);
const std::string vfs_escape_path = vfs::escape(spath);
const std::string vfs_unescape_path = vfs::unescape(spath);
const std::string result = fmt::format(
"Path:\n'%s'\n\n"
"vfs::get:\n'%s'\n\n"
"vfs::retrieve:\n'%s'\n\n"
"vfs::escape:\n'%s'\n\n"
"vfs::unescape:\n'%s'",
spath,
vfs_get_path,
vfs_retrieve_path,
vfs_escape_path,
vfs_unescape_path
);
ui->resultEdit->setPlainText(QString::fromStdString(result));
}
| 1,300
|
C++
|
.cpp
| 43
| 28.116279
| 151
| 0.706165
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,097
|
emulated_pad_settings_dialog.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/emulated_pad_settings_dialog.cpp
|
#include "stdafx.h"
#include "emulated_pad_settings_dialog.h"
#include "localized_emu.h"
#include "Emu/Io/buzz_config.h"
#include "Emu/Io/gem_config.h"
#include "Emu/Io/ghltar_config.h"
#include "Emu/Io/guncon3_config.h"
#include "Emu/Io/topshotelite_config.h"
#include "Emu/Io/topshotfearmaster_config.h"
#include "Emu/Io/turntable_config.h"
#include "Emu/Io/usio_config.h"
#include "util/asm.hpp"
#include <QDialogButtonBox>
#include <QGroupBox>
#include <QMessageBox>
#include <QPushButton>
#include <QVBoxLayout>
enum button_role
{
button = Qt::UserRole,
emulated_button
};
emulated_pad_settings_dialog::emulated_pad_settings_dialog(pad_type type, QWidget* parent)
: QDialog(parent), m_type(type)
{
setObjectName("emulated_pad_settings_dialog");
setAttribute(Qt::WA_DeleteOnClose);
setAttribute(Qt::WA_StyledBackground);
setModal(true);
QVBoxLayout* v_layout = new QVBoxLayout(this);
QTabWidget* tabs = new QTabWidget();
tabs->setUsesScrollButtons(false);
QDialogButtonBox* buttons = new QDialogButtonBox(this);
buttons->setStandardButtons(QDialogButtonBox::Apply | QDialogButtonBox::Cancel | QDialogButtonBox::Save | QDialogButtonBox::RestoreDefaults);
connect(buttons, &QDialogButtonBox::clicked, this, [this, buttons](QAbstractButton* button)
{
if (button == buttons->button(QDialogButtonBox::Apply))
{
save_config();
}
else if (button == buttons->button(QDialogButtonBox::Save))
{
save_config();
accept();
}
else if (button == buttons->button(QDialogButtonBox::RestoreDefaults))
{
if (QMessageBox::question(this, tr("Confirm Reset"), tr("Reset all buttons of all players?")) != QMessageBox::Yes)
return;
reset_config();
}
else if (button == buttons->button(QDialogButtonBox::Cancel))
{
// Restore config
load_config();
reject();
}
});
load_config();
switch (m_type)
{
case emulated_pad_settings_dialog::pad_type::buzz:
setWindowTitle(tr("Configure Emulated Buzz"));
add_tabs<buzz_btn>(tabs);
break;
case emulated_pad_settings_dialog::pad_type::turntable:
setWindowTitle(tr("Configure Emulated Turntable"));
add_tabs<turntable_btn>(tabs);
break;
case emulated_pad_settings_dialog::pad_type::ghltar:
setWindowTitle(tr("Configure Emulated GHLtar"));
add_tabs<ghltar_btn>(tabs);
break;
case emulated_pad_settings_dialog::pad_type::usio:
setWindowTitle(tr("Configure Emulated USIO"));
add_tabs<usio_btn>(tabs);
break;
case emulated_pad_settings_dialog::pad_type::ds3gem:
setWindowTitle(tr("Configure Emulated PS Move (Fake)"));
add_tabs<gem_btn>(tabs);
break;
case emulated_pad_settings_dialog::pad_type::guncon3:
setWindowTitle(tr("Configure Emulated GunCon 3"));
add_tabs<guncon3_btn>(tabs);
break;
case emulated_pad_settings_dialog::pad_type::topshotelite:
setWindowTitle(tr("Configure Emulated Top Shot Elite"));
add_tabs<topshotelite_btn>(tabs);
break;
case emulated_pad_settings_dialog::pad_type::topshotfearmaster:
setWindowTitle(tr("Configure Emulated Top Shot Fearmaster"));
add_tabs<topshotfearmaster_btn>(tabs);
break;
}
v_layout->addWidget(tabs);
v_layout->addWidget(buttons);
setLayout(v_layout);
}
template <typename T>
void emulated_pad_settings_dialog::add_tabs(QTabWidget* tabs)
{
ensure(!!tabs);
constexpr u32 max_items_per_column = 6;
int rows = static_cast<int>(T::count);
for (u32 cols = 1; utils::aligned_div(static_cast<u32>(T::count), cols) > max_items_per_column;)
{
rows = utils::aligned_div(static_cast<u32>(T::count), ++cols);
}
usz players = 0;
switch (m_type)
{
case pad_type::buzz:
players = g_cfg_buzz.players.size();
break;
case pad_type::turntable:
players = g_cfg_turntable.players.size();
break;
case pad_type::ghltar:
players = g_cfg_ghltar.players.size();
break;
case pad_type::usio:
players = g_cfg_usio.players.size();
break;
case pad_type::ds3gem:
players = g_cfg_gem.players.size();
break;
case pad_type::guncon3:
players = g_cfg_guncon3.players.size();
break;
case pad_type::topshotelite:
players = g_cfg_topshotelite.players.size();
break;
case pad_type::topshotfearmaster:
players = g_cfg_topshotfearmaster.players.size();
break;
}
m_combos.resize(players);
for (usz player = 0; player < players; player++)
{
QWidget* widget = new QWidget(this);
QGridLayout* grid_layout = new QGridLayout(this);
for (int i = 0, row = 0, col = 0; i < static_cast<int>(T::count); i++, row++)
{
const T id = static_cast<T>(i);
const QString name = QString::fromStdString(fmt::format("%s", id));
QHBoxLayout* h_layout = new QHBoxLayout(this);
QGroupBox* gb = new QGroupBox(name, this);
QComboBox* combo = new QComboBox;
for (int p = 0; p < static_cast<int>(pad_button::pad_button_max_enum); p++)
{
const QString translated = localized_emu::translated_pad_button(static_cast<pad_button>(p));
combo->addItem(translated);
const int index = combo->findText(translated);
combo->setItemData(index, p, button_role::button);
combo->setItemData(index, i, button_role::emulated_button);
}
if constexpr (std::is_same_v<T, guncon3_btn> || std::is_same_v<T, topshotelite_btn> || std::is_same_v<T, topshotfearmaster_btn>)
{
for (int p = static_cast<int>(pad_button::mouse_button_1); p <= static_cast<int>(pad_button::mouse_button_8); p++)
{
const QString translated = localized_emu::translated_pad_button(static_cast<pad_button>(p));
combo->addItem(translated);
const int index = combo->findText(translated);
combo->setItemData(index, p, button_role::button);
combo->setItemData(index, i, button_role::emulated_button);
}
}
pad_button saved_btn_id = pad_button::pad_button_max_enum;
switch (m_type)
{
case pad_type::buzz:
saved_btn_id = ::at32(g_cfg_buzz.players, player)->get_pad_button(static_cast<buzz_btn>(id));
break;
case pad_type::turntable:
saved_btn_id = ::at32(g_cfg_turntable.players, player)->get_pad_button(static_cast<turntable_btn>(id));
break;
case pad_type::ghltar:
saved_btn_id = ::at32(g_cfg_ghltar.players, player)->get_pad_button(static_cast<ghltar_btn>(id));
break;
case pad_type::usio:
saved_btn_id = ::at32(g_cfg_usio.players, player)->get_pad_button(static_cast<usio_btn>(id));
break;
case pad_type::ds3gem:
saved_btn_id = ::at32(g_cfg_gem.players, player)->get_pad_button(static_cast<gem_btn>(id));
break;
case pad_type::guncon3:
saved_btn_id = ::at32(g_cfg_guncon3.players, player)->get_pad_button(static_cast<guncon3_btn>(id));
break;
case pad_type::topshotelite:
saved_btn_id = ::at32(g_cfg_topshotelite.players, player)->get_pad_button(static_cast<topshotelite_btn>(id));
break;
case pad_type::topshotfearmaster:
saved_btn_id = ::at32(g_cfg_topshotfearmaster.players, player)->get_pad_button(static_cast<topshotfearmaster_btn>(id));
break;
}
combo->setCurrentIndex(combo->findData(static_cast<int>(saved_btn_id)));
connect(combo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this, player, id, combo](int index)
{
if (index < 0 || !combo)
return;
const QVariant data = combo->itemData(index, button_role::button);
if (!data.isValid() || !data.canConvert<int>())
return;
const pad_button btn_id = static_cast<pad_button>(data.toInt());
switch (m_type)
{
case pad_type::buzz:
::at32(g_cfg_buzz.players, player)->set_button(static_cast<buzz_btn>(id), btn_id);
break;
case pad_type::turntable:
::at32(g_cfg_turntable.players, player)->set_button(static_cast<turntable_btn>(id), btn_id);
break;
case pad_type::ghltar:
::at32(g_cfg_ghltar.players, player)->set_button(static_cast<ghltar_btn>(id), btn_id);
break;
case pad_type::usio:
::at32(g_cfg_usio.players, player)->set_button(static_cast<usio_btn>(id), btn_id);
break;
case pad_type::ds3gem:
::at32(g_cfg_gem.players, player)->set_button(static_cast<gem_btn>(id), btn_id);
break;
case pad_type::guncon3:
::at32(g_cfg_guncon3.players, player)->set_button(static_cast<guncon3_btn>(id), btn_id);
break;
case pad_type::topshotelite:
::at32(g_cfg_topshotelite.players, player)->set_button(static_cast<topshotelite_btn>(id), btn_id);
break;
case pad_type::topshotfearmaster:
::at32(g_cfg_topshotfearmaster.players, player)->set_button(static_cast<topshotfearmaster_btn>(id), btn_id);
break;
}
});
if (row >= rows)
{
row = 0;
col++;
}
::at32(m_combos, player).push_back(combo);
h_layout->addWidget(combo);
gb->setLayout(h_layout);
grid_layout->addWidget(gb, row, col);
}
widget->setLayout(grid_layout);
tabs->addTab(widget, tr("Player %0").arg(player + 1));
}
}
void emulated_pad_settings_dialog::load_config()
{
switch (m_type)
{
case emulated_pad_settings_dialog::pad_type::buzz:
if (!g_cfg_buzz.load())
{
cfg_log.notice("Could not load buzz config. Using defaults.");
}
break;
case emulated_pad_settings_dialog::pad_type::turntable:
if (!g_cfg_turntable.load())
{
cfg_log.notice("Could not load turntable config. Using defaults.");
}
break;
case emulated_pad_settings_dialog::pad_type::ghltar:
if (!g_cfg_ghltar.load())
{
cfg_log.notice("Could not load ghltar config. Using defaults.");
}
break;
case emulated_pad_settings_dialog::pad_type::usio:
if (!g_cfg_usio.load())
{
cfg_log.notice("Could not load usio config. Using defaults.");
}
break;
case emulated_pad_settings_dialog::pad_type::ds3gem:
if (!g_cfg_gem.load())
{
cfg_log.notice("Could not load gem config. Using defaults.");
}
break;
case emulated_pad_settings_dialog::pad_type::guncon3:
if (!g_cfg_guncon3.load())
{
cfg_log.notice("Could not load guncon3 config. Using defaults.");
}
break;
case emulated_pad_settings_dialog::pad_type::topshotelite:
if (!g_cfg_topshotelite.load())
{
cfg_log.notice("Could not load topshotelite config. Using defaults.");
}
break;
case emulated_pad_settings_dialog::pad_type::topshotfearmaster:
if (!g_cfg_topshotfearmaster.load())
{
cfg_log.notice("Could not load topshotfearmaster config. Using defaults.");
}
break;
}
}
void emulated_pad_settings_dialog::save_config()
{
switch (m_type)
{
case emulated_pad_settings_dialog::pad_type::buzz:
g_cfg_buzz.save();
break;
case emulated_pad_settings_dialog::pad_type::turntable:
g_cfg_turntable.save();
break;
case emulated_pad_settings_dialog::pad_type::ghltar:
g_cfg_ghltar.save();
break;
case emulated_pad_settings_dialog::pad_type::usio:
g_cfg_usio.save();
break;
case emulated_pad_settings_dialog::pad_type::ds3gem:
g_cfg_gem.save();
break;
case emulated_pad_settings_dialog::pad_type::guncon3:
g_cfg_guncon3.save();
break;
case emulated_pad_settings_dialog::pad_type::topshotelite:
g_cfg_topshotelite.save();
break;
case emulated_pad_settings_dialog::pad_type::topshotfearmaster:
g_cfg_topshotfearmaster.save();
break;
}
}
void emulated_pad_settings_dialog::reset_config()
{
switch (m_type)
{
case emulated_pad_settings_dialog::pad_type::buzz:
g_cfg_buzz.from_default();
break;
case emulated_pad_settings_dialog::pad_type::turntable:
g_cfg_turntable.from_default();
break;
case emulated_pad_settings_dialog::pad_type::ghltar:
g_cfg_ghltar.from_default();
break;
case emulated_pad_settings_dialog::pad_type::usio:
g_cfg_usio.from_default();
break;
case emulated_pad_settings_dialog::pad_type::ds3gem:
g_cfg_gem.from_default();
break;
case emulated_pad_settings_dialog::pad_type::guncon3:
g_cfg_guncon3.from_default();
break;
case emulated_pad_settings_dialog::pad_type::topshotelite:
g_cfg_topshotelite.from_default();
break;
case emulated_pad_settings_dialog::pad_type::topshotfearmaster:
g_cfg_topshotfearmaster.from_default();
break;
}
for (usz player = 0; player < m_combos.size(); player++)
{
for (QComboBox* combo : m_combos.at(player))
{
if (!combo)
continue;
const QVariant data = combo->itemData(0, button_role::emulated_button);
if (!data.isValid() || !data.canConvert<int>())
continue;
pad_button def_btn_id = pad_button::pad_button_max_enum;
switch (m_type)
{
case pad_type::buzz:
def_btn_id = ::at32(g_cfg_buzz.players, player)->default_pad_button(static_cast<buzz_btn>(data.toInt()));
break;
case pad_type::turntable:
def_btn_id = ::at32(g_cfg_turntable.players, player)->default_pad_button(static_cast<turntable_btn>(data.toInt()));
break;
case pad_type::ghltar:
def_btn_id = ::at32(g_cfg_ghltar.players, player)->default_pad_button(static_cast<ghltar_btn>(data.toInt()));
break;
case pad_type::usio:
def_btn_id = ::at32(g_cfg_usio.players, player)->default_pad_button(static_cast<usio_btn>(data.toInt()));
break;
case pad_type::ds3gem:
def_btn_id = ::at32(g_cfg_gem.players, player)->default_pad_button(static_cast<gem_btn>(data.toInt()));
break;
case pad_type::guncon3:
def_btn_id = ::at32(g_cfg_guncon3.players, player)->default_pad_button(static_cast<guncon3_btn>(data.toInt()));
break;
case pad_type::topshotelite:
def_btn_id = ::at32(g_cfg_topshotelite.players, player)->default_pad_button(static_cast<topshotelite_btn>(data.toInt()));
break;
case pad_type::topshotfearmaster:
def_btn_id = ::at32(g_cfg_topshotfearmaster.players, player)->default_pad_button(static_cast<topshotfearmaster_btn>(data.toInt()));
break;
}
combo->setCurrentIndex(combo->findData(static_cast<int>(def_btn_id)));
}
}
}
| 13,595
|
C++
|
.cpp
| 400
| 30.66
| 142
| 0.706969
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,098
|
render_creator.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/render_creator.cpp
|
#include "render_creator.h"
#include <QMessageBox>
#include "Utilities/Thread.h"
#if defined(HAVE_VULKAN)
#include "Emu/RSX/VK/vkutils/instance.hpp"
#endif
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <thread>
#include <util/logs.hpp>
LOG_CHANNEL(cfg_log, "CFG");
render_creator::render_creator(QObject *parent) : QObject(parent)
{
#if defined(HAVE_VULKAN)
// Some drivers can get stuck when checking for vulkan-compatible gpus, f.ex. if they're waiting for one to get
// plugged in. This whole contraption is for showing an error message in case that happens, so that user has
// some idea about why the emulator window isn't showing up.
static atomic_t<bool> was_called = false;
if (was_called.exchange(true))
fmt::throw_exception("Render_Creator cannot be created more than once");
static std::mutex mtx;
static std::condition_variable cond;
static bool work_done = false;
auto enum_thread_v = new named_thread("Vulkan Device Enumeration Thread"sv, [&, adapters = &this->vulkan_adapters]()
{
thread_ctrl::scoped_priority low_prio(-1);
vk::instance device_enum_context;
std::unique_lock lock(mtx, std::defer_lock);
if (device_enum_context.create("RPCS3", true))
{
device_enum_context.bind();
std::vector<vk::physical_device>& gpus = device_enum_context.enumerate_devices();
lock.lock();
if (!work_done) // The spawning thread gave up, do not attempt to modify vulkan_adapters
{
for (const auto& gpu : gpus)
{
adapters->append(QString::fromStdString(gpu.get_name()));
}
}
}
else
{
lock.lock();
}
work_done = true;
lock.unlock();
cond.notify_all();
});
std::unique_ptr<std::remove_pointer_t<decltype(enum_thread_v)>> enum_thread(enum_thread_v);
if ([&]()
{
std::unique_lock lck(mtx);
cond.wait_for(lck, std::chrono::seconds(10), [&] { return work_done; });
return !std::exchange(work_done, true); // If thread hasn't done its job yet, it won't anymore
}())
{
enum_thread.release(); // Detach thread (destructor is not called)
cfg_log.error("Vulkan device enumeration timed out");
const auto button = QMessageBox::critical(nullptr, tr("Vulkan Check Timeout"),
tr("Querying for Vulkan-compatible devices is taking too long. This is usually caused by malfunctioning "
"graphics drivers, reinstalling them could fix the issue.\n\n"
"Selecting ignore starts the emulator without Vulkan support."),
QMessageBox::Ignore | QMessageBox::Abort, QMessageBox::Abort);
if (button != QMessageBox::Ignore)
{
abort_requested = true;
return;
}
supports_vulkan = false;
}
else
{
supports_vulkan = !vulkan_adapters.isEmpty();
enum_thread.reset(); // Join thread
}
#endif
// Graphics Adapter
Vulkan = render_info(vulkan_adapters, supports_vulkan, emu_settings_type::VulkanAdapter, true);
OpenGL = render_info();
NullRender = render_info();
#ifdef __APPLE__
OpenGL.supported = false;
if (!Vulkan.supported)
{
QMessageBox::warning(nullptr,
tr("Warning"),
tr("Vulkan is not supported on this Mac.\n"
"No graphics will be rendered."));
}
#endif
renderers = { &Vulkan, &OpenGL, &NullRender };
}
void render_creator::update_names(const QStringList& names)
{
for (int i = 0; i < names.size(); i++)
{
if (static_cast<usz>(i) >= renderers.size() || !renderers[i])
{
cfg_log.error("render_creator::update_names could not update renderer %d", i);
return;
}
renderers[i]->name = names[i];
}
}
| 3,496
|
C++
|
.cpp
| 106
| 30.037736
| 117
| 0.709869
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,099
|
settings_dialog.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/settings_dialog.cpp
|
#include <QButtonGroup>
#include <QCameraDevice>
#include <QMediaDevices>
#include <QDialogButtonBox>
#include <QFontMetrics>
#include <QPushButton>
#include <QMessageBox>
#include <QInputDialog>
#include <QDesktopServices>
#include <QColorDialog>
#include <QSpinBox>
#include <QTimer>
#include <QScreen>
#include <QStyleFactory>
#include "gui_settings.h"
#include "display_sleep_control.h"
#include "qt_utils.h"
#include "uuid.h"
#include "settings_dialog.h"
#include "ui_settings_dialog.h"
#include "tooltips.h"
#include "input_dialog.h"
#include "emu_settings_type.h"
#include "render_creator.h"
#include "microphone_creator.h"
#include "Emu/NP/rpcn_countries.h"
#include "Emu/GameInfo.h"
#include "Emu/System.h"
#include "Emu/system_config.h"
#include "Emu/title.h"
#include "Emu/Audio/audio_device_enumerator.h"
#include "Loader/PSF.h"
#include <set>
#include <unordered_set>
#include <thread>
#include "util/sysinfo.hpp"
#include "util/asm.hpp"
#ifdef WITH_DISCORD_RPC
#include "_discord_utils.h"
#endif
LOG_CHANNEL(cfg_log, "CFG");
inline std::string sstr(const QString& _in) { return _in.toStdString(); }
inline std::string sstr(const QVariant& _in) { return sstr(_in.toString()); }
inline QString qsv(std::string_view sv) { return QString(sv.data()); }
std::pair<QString, int> get_data(const QComboBox* box, int index)
{
if (!box) return {};
const QVariantList var_list = box->itemData(index).toList();
ensure(var_list.size() == 2);
ensure(var_list[0].canConvert<QString>());
ensure(var_list[1].canConvert<int>());
return { var_list[0].toString(), var_list[1].toInt() };
}
int find_item(const QComboBox* box, int value)
{
for (int i = 0; box && i < box->count(); i++)
{
if (get_data(box, i).second == value)
{
return i;
}
}
return -1;
}
void remove_item(QComboBox* box, int data_value, int def_value)
{
if (!box) return;
const int index = find_item(box, data_value);
const bool was_selected = index == box->currentIndex();
box->removeItem(index);
if (was_selected)
{
box->setCurrentIndex(find_item(box, def_value));
}
}
extern const std::map<std::string_view, int> g_prx_list;
settings_dialog::settings_dialog(std::shared_ptr<gui_settings> gui_settings, std::shared_ptr<emu_settings> emu_settings, const int& tab_index, QWidget* parent, const GameInfo* game, bool create_cfg_from_global_cfg)
: QDialog(parent)
, m_tab_index(tab_index)
, ui(new Ui::settings_dialog)
, m_gui_settings(std::move(gui_settings))
, m_emu_settings(std::move(emu_settings))
{
ui->setupUi(this);
ui->buttonBox->button(QDialogButtonBox::StandardButton::Close)->setFocus();
ui->tab_widget_settings->setUsesScrollButtons(false);
ui->tab_widget_settings->tabBar()->setObjectName("tab_bar_settings");
if (!m_gui_settings->GetValue(gui::m_showDebugTab).toBool())
{
ui->tab_widget_settings->removeTab(9);
ui->audioDump->setVisible(false);
ui->audioDump->setChecked(false);
m_gui_settings->SetValue(gui::m_showDebugTab, false);
}
if (game)
{
ui->tab_widget_settings->removeTab(8);
ui->buttonBox->button(QDialogButtonBox::StandardButton::Save)->setText(tr("Save custom configuration", "Settings dialog"));
}
// Localized tooltips
const Tooltips tooltips;
// Add description labels
SubscribeDescription(ui->description_cpu);
SubscribeDescription(ui->description_gpu);
SubscribeDescription(ui->description_audio);
SubscribeDescription(ui->description_io);
SubscribeDescription(ui->description_system);
SubscribeDescription(ui->description_network);
SubscribeDescription(ui->description_advanced);
SubscribeDescription(ui->description_emulator);
if (!game)
{
SubscribeDescription(ui->description_gui);
}
SubscribeDescription(ui->description_debug);
if (game)
{
m_emu_settings->LoadSettings(game->serial, create_cfg_from_global_cfg);
setWindowTitle(tr("Settings: [%0] %1", "Settings dialog").arg(qstr(game->serial)).arg(qstr(game->name)));
}
else
{
m_emu_settings->LoadSettings();
setWindowTitle(tr("Settings", "Settings dialog"));
}
// Discord variables
m_use_discord = m_gui_settings->GetValue(gui::m_richPresence).toBool();
m_discord_state = m_gui_settings->GetValue(gui::m_discordState).toString();
// Various connects
const auto apply_configs = [this, use_discord_old = m_use_discord, discord_state_old = m_discord_state, game](bool do_exit)
{
u32 selected_audio_formats = 0;
for (int i = 0; i < ui->list_audio_formats->count(); ++i)
{
const auto& item = ui->list_audio_formats->item(i);
if (item->checkState() != Qt::CheckState::Unchecked)
{
selected_audio_formats |= item->data(Qt::UserRole).toUInt();
}
}
m_emu_settings->SetSetting(emu_settings_type::AudioFormats, std::to_string(selected_audio_formats));
std::set<std::string> selected;
for (int i = 0; i < ui->lleList->count(); ++i)
{
const auto& item = ui->lleList->item(i);
if (item->checkState() != Qt::CheckState::Unchecked)
{
// suffix indicates forced HLE mode
selected.emplace(sstr(item->text()) + ":hle");
}
}
for (int i = 0; i < ui->hleList->count(); ++i)
{
const auto& item = ui->hleList->item(i);
if (item->checkState() != Qt::CheckState::Unchecked)
{
// suffix indicates forced LLE mode
selected.emplace(sstr(item->text()) + ":lle");
}
}
const std::vector<std::string> selected_ls(selected.begin(), selected.end());
m_emu_settings->SaveSelectedLibraries(selected_ls);
m_emu_settings->SaveSettings();
if (do_exit)
{
accept();
}
Q_EMIT EmuSettingsApplied();
// Discord Settings can be saved regardless of WITH_DISCORD_RPC
m_gui_settings->SetValue(gui::m_richPresence, m_use_discord, false);
m_gui_settings->SetValue(gui::m_discordState, m_discord_state, true);
#ifdef WITH_DISCORD_RPC
if (m_use_discord != use_discord_old)
{
if (m_use_discord)
{
discord::initialize();
discord::update_presence(sstr(m_discord_state));
}
else
{
discord::shutdown();
}
}
else if (m_discord_state != discord_state_old && Emu.IsStopped())
{
discord::update_presence(sstr(m_discord_state), "Idle", false);
}
#endif
if (!game)
{
ApplyStylesheet(false);
}
};
connect(ui->buttonBox, &QDialogButtonBox::clicked, this, [apply_configs, this](QAbstractButton* button)
{
if (button == ui->buttonBox->button(QDialogButtonBox::Save))
{
apply_configs(true);
}
else if (button == ui->buttonBox->button(QDialogButtonBox::Apply))
{
apply_configs(false);
}
else if (button == ui->buttonBox->button(QDialogButtonBox::RestoreDefaults))
{
m_emu_settings->RestoreDefaults();
// Handle special restrictions after the settings were restored
Q_EMIT signal_restore_dependant_defaults();
}
});
connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QWidget::close);
connect(ui->tab_widget_settings, &QTabWidget::currentChanged, this, [this]()
{
ui->buttonBox->button(QDialogButtonBox::StandardButton::Close)->setFocus();
});
// _____ _____ _ _ _______ _
// / ____| __ \| | | | |__ __| | |
// | | | |__) | | | | | | __ _| |__
// | | | ___/| | | | | |/ _` | '_ \
// | |____| | | |__| | | | (_| | |_) |
// \_____|_| \____/ |_|\__,_|_.__/
// Checkboxes
m_emu_settings->EnhanceCheckBox(ui->spuLoopDetection, emu_settings_type::SPULoopDetection);
SubscribeTooltip(ui->spuLoopDetection, tooltips.settings.spu_loop_detection);
// Comboboxes
m_emu_settings->EnhanceComboBox(ui->xfloatAccuracy, emu_settings_type::XFloatAccuracy);
SubscribeTooltip(ui->gb_xfloat_accuracy, tooltips.settings.xfloat);
remove_item(ui->xfloatAccuracy, static_cast<int>(xfloat_accuracy::inaccurate), static_cast<int>(g_cfg.core.spu_xfloat_accuracy.def));
m_emu_settings->EnhanceComboBox(ui->spuBlockSize, emu_settings_type::SPUBlockSize);
SubscribeTooltip(ui->gb_spuBlockSize, tooltips.settings.spu_block_size);
m_emu_settings->EnhanceComboBox(ui->threadsched, emu_settings_type::ThreadSchedulerMode);
if (constexpr u32 min_thread_count = 12; utils::get_thread_count() < min_thread_count)
{
ui->gb_threadsched->setDisabled(true);
SubscribeTooltip(ui->gb_threadsched,
tr(
"Changing the thread scheduler is not supported on CPUs with less than %0 threads.\n"
"\n"
"Control how RPCS3 utilizes the threads of your system.\n"
"Each option heavily depends on the game and on your CPU, it's recommended to try each option to find out which performs the best."
).arg(min_thread_count));
}
else
{
SubscribeTooltip(ui->gb_threadsched, tooltips.settings.enable_thread_scheduler);
}
m_emu_settings->EnhanceComboBox(ui->preferredSPUThreads, emu_settings_type::PreferredSPUThreads, true);
SubscribeTooltip(ui->gb_spu_threads, tooltips.settings.preferred_spu_threads);
ui->preferredSPUThreads->setItemText(ui->preferredSPUThreads->findData(0), tr("Auto", "Preferred SPU threads"));
if (utils::has_rtm())
{
m_emu_settings->EnhanceComboBox(ui->enableTSX, emu_settings_type::EnableTSX);
SubscribeTooltip(ui->gb_tsx, tooltips.settings.enable_tsx);
if (!utils::has_mpx() || utils::has_tsx_force_abort())
{
remove_item(ui->enableTSX, static_cast<int>(tsx_usage::enabled), static_cast<int>(g_cfg.core.enable_TSX.def));
}
connect(ui->enableTSX, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int index)
{
if (index < 0) return;
if (const auto [text, value] = get_data(ui->enableTSX, index); value == static_cast<int>(tsx_usage::forced) &&
(!utils::has_mpx() || utils::has_tsx_force_abort()))
{
QString title;
QString message;
if (!utils::has_mpx())
{
title = tr("Haswell/Broadwell TSX Warning");
message = tr(
R"(
<p style="white-space: nowrap;">
RPCS3 has detected that you are using TSX functions on a Haswell or Broadwell CPU.<br>
Intel has deactivated these functions in newer Microcode revisions, since they can lead to unpredicted behaviour.<br>
That means using TSX may break games or even <font color="red"><b>damage</b></font> your data.<br>
We recommend to disable this feature and update your computer BIOS.<br><br>
Do you wish to use TSX anyway?
</p>
)");
}
else
{
title = tr("TSX-FA Warning");
message = tr(
R"(
<p style="white-space: nowrap;">
RPCS3 has detected your CPU only supports TSX-FA.<br>
That means using TSX may break games or even <font color="red"><b>damage</b></font> your data.<br>
We recommend to disable this feature.<br><br>
Do you wish to use TSX anyway?
</p>
)");
}
if (QMessageBox::No == QMessageBox::critical(this, title, message, QMessageBox::Yes, QMessageBox::No))
{
// Reset if the messagebox was answered with no. This prevents the currentIndexChanged signal in EnhanceComboBox
ui->enableTSX->setCurrentIndex(find_item(ui->enableTSX, static_cast<int>(g_cfg.core.enable_TSX.def)));
}
}
});
}
else
{
ui->enableTSX->setEnabled(false);
ui->enableTSX->setPlaceholderText(tr("Not supported", "Enable TSX"));
SubscribeTooltip(ui->enableTSX, tr("Unfortunately, your CPU model does not support this instruction set.", "Enable TSX"));
m_emu_settings->SetSetting(emu_settings_type::EnableTSX, fmt::format("%s", tsx_usage::disabled));
connect(this, &settings_dialog::signal_restore_dependant_defaults, [this]()
{
m_emu_settings->SetSetting(emu_settings_type::EnableTSX, fmt::format("%s", tsx_usage::disabled));
});
}
// PPU tool tips
SubscribeTooltip(ui->ppu__static, tooltips.settings.ppu__static);
SubscribeTooltip(ui->ppu_llvm, tooltips.settings.ppu_llvm);
QButtonGroup *ppu_bg = new QButtonGroup(this);
ppu_bg->addButton(ui->ppu__static, static_cast<int>(ppu_decoder_type::_static));
ppu_bg->addButton(ui->ppu_llvm, static_cast<int>(ppu_decoder_type::llvm));
connect(ppu_bg, &QButtonGroup::idToggled, [this](int id, bool checked)
{
if (!checked) return;
switch (id)
{
case static_cast<int>(ppu_decoder_type::_static):
ui->accuratePPUFPCC->setEnabled(true);
ui->accuratePPUNJ->setEnabled(true);
ui->accuratePPUVNAN->setEnabled(true);
break;
case static_cast<int>(ppu_decoder_type::llvm):
ui->accuratePPUFPCC->setEnabled(false);
ui->accuratePPUNJ->setEnabled(false);
ui->accuratePPUVNAN->setEnabled(false);
break;
default:
break;
}
});
m_emu_settings->EnhanceRadioButton(ppu_bg, emu_settings_type::PPUDecoder);
// SPU tool tips
SubscribeTooltip(ui->spu__static, tooltips.settings.spu__static);
SubscribeTooltip(ui->spu_dynamic, tooltips.settings.spu_dynamic);
SubscribeTooltip(ui->spu_asmjit, tooltips.settings.spu_asmjit);
SubscribeTooltip(ui->spu_llvm, tooltips.settings.spu_llvm);
QButtonGroup* spu_bg = new QButtonGroup(this);
spu_bg->addButton(ui->spu__static, static_cast<int>(spu_decoder_type::_static));
spu_bg->addButton(ui->spu_dynamic, static_cast<int>(spu_decoder_type::dynamic));
spu_bg->addButton(ui->spu_asmjit, static_cast<int>(spu_decoder_type::asmjit));
spu_bg->addButton(ui->spu_llvm, static_cast<int>(spu_decoder_type::llvm));
connect(spu_bg, &QButtonGroup::idToggled, [this](int id, bool checked)
{
if (!checked) return;
switch (id)
{
case static_cast<int>(spu_decoder_type::_static):
case static_cast<int>(spu_decoder_type::dynamic):
case static_cast<int>(spu_decoder_type::llvm):
ui->xfloatAccuracy->setEnabled(true);
break;
case static_cast<int>(spu_decoder_type::asmjit):
ui->xfloatAccuracy->setEnabled(false);
break;
default:
break;
}
});
m_emu_settings->EnhanceRadioButton(spu_bg, emu_settings_type::SPUDecoder);
#ifndef LLVM_AVAILABLE
ui->ppu_llvm->setEnabled(false);
ui->spu_llvm->setEnabled(false);
ui->spu_dynamic->setEnabled(false);
#endif
// _____ _____ _ _ _______ _
// / ____| __ \| | | | |__ __| | |
// | | __| |__) | | | | | | __ _| |__
// | | |_ | ___/| | | | | |/ _` | '_ \
// | |__| | | | |__| | | | (_| | |_) |
// \_____|_| \____/ |_|\__,_|_.__/
render_creator* r_creator = m_emu_settings->m_render_creator;
if (!r_creator)
{
fmt::throw_exception("settings_dialog::settings_dialog() render_creator is null");
}
r_creator->update_names(
{
m_emu_settings->GetLocalizedSetting(QString("Vulkan"), emu_settings_type::Renderer, static_cast<int>(video_renderer::vulkan), true),
m_emu_settings->GetLocalizedSetting(QString("OpenGl"), emu_settings_type::Renderer, static_cast<int>(video_renderer::opengl), true),
m_emu_settings->GetLocalizedSetting(QString("Null"), emu_settings_type::Renderer, static_cast<int>(video_renderer::null), true)
});
// Comboboxes
m_emu_settings->EnhanceComboBox(ui->renderBox, emu_settings_type::Renderer);
SubscribeTooltip(ui->gb_renderer, tooltips.settings.renderer);
SubscribeTooltip(ui->gb_graphicsAdapter, tooltips.settings.graphics_adapter);
m_emu_settings->EnhanceComboBox(ui->resBox, emu_settings_type::Resolution, false, false, 0, false, false);
SubscribeTooltip(ui->gb_default_resolution, tooltips.settings.resolution);
// remove unsupported resolutions from the dropdown
bool saved_index_removed = false;
//if (game && game->resolution > 0) // Add this line when interlaced resolutions are implemented
{
const std::map<video_resolution, u32> resolutions
{
{ video_resolution::_480p, psf::resolution_flag::_480 | psf::resolution_flag::_480_16_9 },
{ video_resolution::_480i, psf::resolution_flag::_480 | psf::resolution_flag::_480_16_9 },
{ video_resolution::_576p, psf::resolution_flag::_576 | psf::resolution_flag::_576_16_9 },
{ video_resolution::_576i, psf::resolution_flag::_576 | psf::resolution_flag::_576_16_9 },
{ video_resolution::_720p, psf::resolution_flag::_720 },
{ video_resolution::_1080p, psf::resolution_flag::_1080 },
{ video_resolution::_1080i, psf::resolution_flag::_1080 },
{ video_resolution::_1600x1080p, psf::resolution_flag::_1080 },
{ video_resolution::_1440x1080p, psf::resolution_flag::_1080 },
{ video_resolution::_1280x1080p, psf::resolution_flag::_1080 },
{ video_resolution::_960x1080p, psf::resolution_flag::_1080 },
};
const int saved_index = ui->resBox->currentIndex();
bool remove_720p = false;
for (int i = ui->resBox->count() - 1; i >= 0; i--)
{
const auto [text, value] = get_data(ui->resBox, i);
const video_resolution resolution = static_cast<video_resolution>(value);
// Remove interlaced resolutions until they are properly implemented
const bool is_interlaced = (resolution == video_resolution::_1080i ||
resolution == video_resolution::_480i ||
resolution == video_resolution::_576i);
const bool supported_by_game = !game || !game->resolution || (resolutions.contains(resolution) && (game->resolution & resolutions.at(resolution)));
if (!supported_by_game || is_interlaced)
{
// Don't remove 720p yet. We may need it as fallback if no other resolution is supported.
if (resolution == video_resolution::_720p)
{
remove_720p = true;
continue;
}
ui->resBox->removeItem(i);
if (i == saved_index)
{
saved_index_removed = true;
}
}
}
// Remove 720p if unsupported unless it's the only option
if (remove_720p && ui->resBox->count() > 1)
{
if (const int index = find_item(ui->resBox, static_cast<int>(video_resolution::_720p)); index >= 0)
{
ui->resBox->removeItem(index);
}
}
}
for (int i = 0; i < ui->resBox->count(); i++)
{
const auto [text, value] = get_data(ui->resBox, i);
if (static_cast<video_resolution>(value) == video_resolution::_720p)
{
// Rename the default resolution for users
ui->resBox->setItemText(i, tr("720p (Recommended)", "Resolution"));
// Set the current selection to the default if the original setting wasn't valid
if (saved_index_removed)
{
ui->resBox->setCurrentIndex(i);
}
break;
}
}
m_emu_settings->EnhanceComboBox(ui->aspectBox, emu_settings_type::AspectRatio, false, false, 0, false, false);
SubscribeTooltip(ui->gb_aspectRatio, tooltips.settings.aspect_ratio);
m_emu_settings->EnhanceComboBox(ui->frameLimitBox, emu_settings_type::FrameLimit);
SubscribeTooltip(ui->gb_frameLimit, tooltips.settings.frame_limit);
{
const QList<QScreen*> screens = QGuiApplication::screens();
f64 rate = 20.; // Minimum rate
for (int i = 0; i < screens.count(); i++)
{
rate = std::fmax(rate, ::at32(screens, i)->refreshRate());
}
for (int i = 0; i < ui->frameLimitBox->count(); i++)
{
const QVariantList var_list = ui->frameLimitBox->itemData(i).toList();
if (var_list.size() != 2 || !var_list[1].canConvert<int>())
{
fmt::throw_exception("Invalid data found in combobox entry %d (text='%s', listsize=%d, itemcount=%d)", i, ui->frameLimitBox->itemText(i), var_list.size(), ui->frameLimitBox->count());
}
if (static_cast<int>(frame_limit_type::display_rate) == var_list[1].toInt())
{
ui->frameLimitBox->setItemText(i, tr("Display (%1)", "Frame Limit").arg(std::round(rate)));
break;
}
}
}
m_emu_settings->EnhanceComboBox(ui->antiAliasing, emu_settings_type::MSAA);
SubscribeTooltip(ui->gb_antiAliasing, tooltips.settings.anti_aliasing);
m_emu_settings->EnhanceComboBox(ui->anisotropicFilterOverride, emu_settings_type::AnisotropicFilterOverride, true);
SubscribeTooltip(ui->gb_anisotropicFilter, tooltips.settings.anisotropic_filter);
// only allow values 0,2,4,8,16
for (int i = ui->anisotropicFilterOverride->count() - 1; i >= 0; i--)
{
switch (int val = ui->anisotropicFilterOverride->itemData(i).toInt())
{
case 0:
ui->anisotropicFilterOverride->setItemText(i, tr("Auto", "Anisotropic filter override"));
break;
case 2:
case 4:
case 8:
case 16:
ui->anisotropicFilterOverride->setItemText(i, tr("%1x", "Anisotropic filter override").arg(val));
break;
default:
ui->anisotropicFilterOverride->removeItem(i);
break;
}
}
m_emu_settings->EnhanceComboBox(ui->shaderPrecision, emu_settings_type::ShaderPrecisionQuality);
SubscribeTooltip(ui->gbShaderPrecision, tooltips.settings.shader_precision);
m_emu_settings->EnhanceComboBox(ui->shaderCompilerThreads, emu_settings_type::ShaderCompilerNumThreads, true);
SubscribeTooltip(ui->gb_shader_compiler_threads, tooltips.settings.shader_compiler_threads);
ui->shaderCompilerThreads->setItemText(ui->shaderCompilerThreads->findData(0), tr("Auto", "Number of Shader Compiler Threads"));
// Custom control that simplifies operation of two independent variables. Can probably be done better but this works.
ui->zcullPrecisionMode->addItem(tr("Precise (Slowest)"), static_cast<int>(zcull_precision_level::precise));
ui->zcullPrecisionMode->addItem(tr("Approximate (Fast)"), static_cast<int>(zcull_precision_level::approximate));
ui->zcullPrecisionMode->addItem(tr("Relaxed (Fastest)"), static_cast<int>(zcull_precision_level::relaxed));
const auto reset_zcull_options = [this]()
{
if (m_emu_settings->GetSetting(emu_settings_type::RelaxedZCULL) == "true")
{
ui->zcullPrecisionMode->setCurrentIndex(ui->zcullPrecisionMode->findData(static_cast<int>(zcull_precision_level::relaxed)));
}
else if (m_emu_settings->GetSetting(emu_settings_type::PreciseZCULL) == "true")
{
ui->zcullPrecisionMode->setCurrentIndex(ui->zcullPrecisionMode->findData(static_cast<int>(zcull_precision_level::precise)));
}
else
{
ui->zcullPrecisionMode->setCurrentIndex(ui->zcullPrecisionMode->findData(static_cast<int>(zcull_precision_level::approximate)));
}
};
reset_zcull_options();
connect(this, &settings_dialog::signal_restore_dependant_defaults, this, reset_zcull_options);
connect(ui->zcullPrecisionMode, QOverload<int>::of(&QComboBox::currentIndexChanged), [this](int index)
{
if (index < 0) return;
bool relaxed = false, precise = false;
switch (static_cast<zcull_precision_level>(ui->zcullPrecisionMode->itemData(index).toInt()))
{
case zcull_precision_level::precise: precise = true; break;
case zcull_precision_level::approximate: break;
case zcull_precision_level::relaxed: relaxed = true; break;
default: fmt::throw_exception("Unexpected selection");
}
m_emu_settings->SetSetting(emu_settings_type::RelaxedZCULL, relaxed ? "true" : "false");
m_emu_settings->SetSetting(emu_settings_type::PreciseZCULL, precise ? "true" : "false");
});
SubscribeTooltip(ui->gbZCULL, tooltips.settings.zcull_operation_mode);
m_emu_settings->EnhanceComboBox(ui->outputScalingMode, emu_settings_type::OutputScalingMode);
SubscribeTooltip(ui->outputScalingMode, tooltips.settings.output_scaling_mode);
// 3D
m_emu_settings->EnhanceComboBox(ui->stereoRenderMode, emu_settings_type::StereoRenderMode);
SubscribeTooltip(ui->gb_stereo, tooltips.settings.stereo_render_mode);
if (game)
{
const auto on_resolution = [this](int index)
{
const auto [text, value] = get_data(ui->resBox, index);
ui->stereoRenderMode->setEnabled(value == static_cast<int>(video_resolution::_720p));
};
connect(ui->resBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, on_resolution);
on_resolution(ui->resBox->currentIndex());
}
else
{
ui->stereoRenderMode->setCurrentIndex(find_item(ui->stereoRenderMode, static_cast<int>(g_cfg.video.stereo_render_mode.def)));
ui->stereoRenderMode->setEnabled(false);
}
// Checkboxes: main options
m_emu_settings->EnhanceCheckBox(ui->dumpColor, emu_settings_type::WriteColorBuffers);
SubscribeTooltip(ui->dumpColor, tooltips.settings.dump_color);
m_emu_settings->EnhanceCheckBox(ui->vsync, emu_settings_type::VSync);
SubscribeTooltip(ui->vsync, tooltips.settings.vsync);
m_emu_settings->EnhanceCheckBox(ui->stretchToDisplayArea, emu_settings_type::StretchToDisplayArea);
SubscribeTooltip(ui->stretchToDisplayArea, tooltips.settings.stretch_to_display_area);
m_emu_settings->EnhanceCheckBox(ui->multithreadedRSX, emu_settings_type::MultithreadedRSX);
SubscribeTooltip(ui->multithreadedRSX, tooltips.settings.multithreaded_rsx);
m_emu_settings->EnhanceCheckBox(ui->strictModeRendering, emu_settings_type::StrictRenderingMode);
SubscribeTooltip(ui->strictModeRendering, tooltips.settings.strict_rendering_mode);
const auto on_strict_rendering_mode = [this](bool checked)
{
ui->gb_resolutionScale->setEnabled(!checked);
ui->gb_minimumScalableDimension->setEnabled(!checked);
ui->gb_anisotropicFilter->setEnabled(!checked);
ui->vulkansched->setEnabled(!checked);
};
connect(ui->strictModeRendering, &QCheckBox::toggled, this, on_strict_rendering_mode);
m_emu_settings->EnhanceCheckBox(ui->asyncTextureStreaming, emu_settings_type::VulkanAsyncTextureUploads);
SubscribeTooltip(ui->asyncTextureStreaming, tooltips.settings.async_texture_streaming);
// Radio buttons
SubscribeTooltip(ui->rb_legacy_recompiler, tooltips.settings.legacy_shader_recompiler);
SubscribeTooltip(ui->rb_async_recompiler, tooltips.settings.async_shader_recompiler);
SubscribeTooltip(ui->rb_async_with_shader_interpreter, tooltips.settings.async_with_shader_interpreter);
SubscribeTooltip(ui->rb_shader_interpreter_only, tooltips.settings.shader_interpreter_only);
QButtonGroup *shader_mode_bg = new QButtonGroup(this);
shader_mode_bg->addButton(ui->rb_legacy_recompiler, static_cast<int>(shader_mode::recompiler));
shader_mode_bg->addButton(ui->rb_async_recompiler, static_cast<int>(shader_mode::async_recompiler));
shader_mode_bg->addButton(ui->rb_async_with_shader_interpreter, static_cast<int>(shader_mode::async_with_interpreter));
shader_mode_bg->addButton(ui->rb_shader_interpreter_only, static_cast<int>(shader_mode::interpreter_only));
m_emu_settings->EnhanceRadioButton(shader_mode_bg, emu_settings_type::ShaderMode);
// Sliders
m_emu_settings->EnhanceSlider(ui->resolutionScale, emu_settings_type::ResolutionScale);
SubscribeTooltip(ui->gb_resolutionScale, tooltips.settings.resolution_scale);
// rename label texts to fit current state of Resolution Scale
const int resolution_scale_def = stoi(m_emu_settings->GetSettingDefault(emu_settings_type::ResolutionScale));
const auto scaled_resolution = [resolution_scale_def](int percentage)
{
if (percentage == resolution_scale_def)
{
return tr("100% (1280x720) (Default)", "Resolution scale");
}
return tr("%1% (%2x%3)", "Resolution scale").arg(percentage).arg(1280 * percentage / 100).arg(720 * percentage / 100);
};
ui->resolutionScale->setPageStep(50);
ui->resolutionScaleMin->setText(QString::number(ui->resolutionScale->minimum()));
ui->resolutionScaleMin->setFixedWidth(gui::utils::get_label_width(QStringLiteral("00")));
ui->resolutionScaleMax->setText(QString::number(ui->resolutionScale->maximum()));
ui->resolutionScaleMax->setFixedWidth(gui::utils::get_label_width(QStringLiteral("0000")));
ui->resolutionScaleVal->setText(scaled_resolution(ui->resolutionScale->value()));
connect(ui->resolutionScale, &QSlider::valueChanged, [scaled_resolution, this](int value)
{
ui->resolutionScaleVal->setText(scaled_resolution(value));
});
connect(ui->resolutionScaleReset, &QAbstractButton::clicked, [resolution_scale_def, this]()
{
ui->resolutionScale->setValue(resolution_scale_def);
});
SnapSlider(ui->resolutionScale, 25);
m_emu_settings->EnhanceSlider(ui->minimumScalableDimension, emu_settings_type::MinimumScalableDimension);
SubscribeTooltip(ui->gb_minimumScalableDimension, tooltips.settings.minimum_scalable_dimension);
// rename label texts to fit current state of Minimum Scalable Dimension
const int minimum_scalable_dimension_def = stoi(m_emu_settings->GetSettingDefault(emu_settings_type::MinimumScalableDimension));
const auto min_scalable_dimension = [minimum_scalable_dimension_def](int dim)
{
if (dim == minimum_scalable_dimension_def)
{
return tr("%1x%1 (Default)", "Minimum scalable dimension").arg(dim);
}
return tr("%1x%1", "Minimum scalable dimension").arg(dim);
};
ui->minimumScalableDimension->setPageStep(64);
ui->minimumScalableDimensionMin->setText(QString::number(ui->minimumScalableDimension->minimum()));
ui->minimumScalableDimensionMin->setFixedWidth(gui::utils::get_label_width(QStringLiteral("00")));
ui->minimumScalableDimensionMax->setText(QString::number(ui->minimumScalableDimension->maximum()));
ui->minimumScalableDimensionMax->setFixedWidth(gui::utils::get_label_width(QStringLiteral("0000")));
ui->minimumScalableDimensionVal->setText(min_scalable_dimension(ui->minimumScalableDimension->value()));
connect(ui->minimumScalableDimension, &QSlider::valueChanged, [min_scalable_dimension, this](int value)
{
ui->minimumScalableDimensionVal->setText(min_scalable_dimension(value));
});
connect(ui->minimumScalableDimensionReset, &QAbstractButton::clicked, [minimum_scalable_dimension_def, this]()
{
ui->minimumScalableDimension->setValue(minimum_scalable_dimension_def);
});
const int fsr_sharpening_strength_def = stoi(m_emu_settings->GetSettingDefault(emu_settings_type::FsrSharpeningStrength));
const auto fmt_fsr_sharpening_strength = [fsr_sharpening_strength_def](int value)
{
if (value == fsr_sharpening_strength_def)
{
return tr("%1% (Default)").arg(value);
}
return tr("%1%").arg(value);
};
m_emu_settings->EnhanceSlider(ui->fsrSharpeningStrength, emu_settings_type::FsrSharpeningStrength);
SubscribeTooltip(ui->fsrSharpeningStrengthWidget, tooltips.settings.fsr_rcas_strength);
ui->fsrSharpeningStrengthVal->setText(fmt_fsr_sharpening_strength(ui->fsrSharpeningStrength->value()));
connect(ui->fsrSharpeningStrength, &QSlider::valueChanged, [fmt_fsr_sharpening_strength, this](int value)
{
ui->fsrSharpeningStrengthVal->setText(fmt_fsr_sharpening_strength(value));
});
connect(ui->fsrSharpeningStrengthReset, &QAbstractButton::clicked, [fsr_sharpening_strength_def, this]()
{
ui->fsrSharpeningStrength->setValue(fsr_sharpening_strength_def);
});
// DoubleSpinBoxes
m_emu_settings->EnhanceDoubleSpinBox(ui->TextureLODBias, emu_settings_type::TextureLodBias);
SubscribeTooltip(ui->gb_Level_of_Detail, tooltips.settings.texture_lod_bias);
connect(ui->TextureLODBiasReset, &QAbstractButton::clicked, [this]()
{
ui->TextureLODBias->setValue(stod(m_emu_settings->GetSettingDefault(emu_settings_type::TextureLodBias)));
});
// Remove renderers from the renderer Combobox if not supported
for (const auto& renderer : r_creator->renderers)
{
if (renderer->supported)
{
if (renderer->has_adapters)
{
renderer->old_adapter = qstr(m_emu_settings->GetSetting(renderer->type));
}
continue;
}
for (int i = 0; i < ui->renderBox->count(); i++)
{
if (ui->renderBox->itemText(i) == renderer->name)
{
ui->renderBox->removeItem(i);
break;
}
}
}
m_old_renderer = ui->renderBox->currentText();
const auto set_renderer = [r_creator, this](const QString& text)
{
if (text.isEmpty())
{
return;
}
const auto switchTo = [r_creator, text, this](const render_creator::render_info& renderer)
{
// Reset other adapters to old config
for (const auto& render : r_creator->renderers)
{
if (renderer.name != render->name && render->has_adapters && render->supported)
{
m_emu_settings->SetSetting(render->type, sstr(render->old_adapter));
}
}
// Enable/disable MSAA depending on renderer
ui->antiAliasing->setEnabled(renderer.has_msaa);
ui->antiAliasing->blockSignals(true);
ui->antiAliasing->setCurrentText(renderer.has_msaa ? qstr(m_emu_settings->GetSetting(emu_settings_type::MSAA)) : tr("Disabled", "MSAA"));
ui->antiAliasing->blockSignals(false);
ui->graphicsAdapterBox->clear();
// Fill combobox with placeholder if no adapters needed
if (!renderer.has_adapters)
{
ui->graphicsAdapterBox->clear();
ui->graphicsAdapterBox->setPlaceholderText(tr("Not needed for %0 renderer", "Graphics adapter").arg(text));
return;
}
// Fill combobox
ui->graphicsAdapterBox->clear();
ui->graphicsAdapterBox->addItems(renderer.adapters);
// Reset Adapter to old config
int idx = ui->graphicsAdapterBox->findText(renderer.old_adapter);
if (idx < 0)
{
idx = 0;
if (renderer.old_adapter.isEmpty())
{
rsx_log.warning("%s adapter config empty: setting to default!", renderer.name);
}
else
{
rsx_log.warning("Last used %s adapter not found: setting to default!", renderer.name);
}
}
ui->graphicsAdapterBox->setCurrentIndex(idx);
m_emu_settings->SetSetting(renderer.type, sstr(ui->graphicsAdapterBox->currentText()));
};
for (const auto& renderer : r_creator->renderers)
{
if (renderer->name == text)
{
switchTo(*renderer);
ui->graphicsAdapterBox->setEnabled(renderer->has_adapters);
}
}
};
const auto set_adapter = [r_creator, this](const QString& text)
{
if (text.isEmpty())
{
return;
}
// don't set adapter if signal was created by switching render
const QString new_renderer = ui->renderBox->currentText();
if (m_old_renderer != new_renderer)
{
m_old_renderer = new_renderer;
return;
}
for (const auto& render : r_creator->renderers)
{
if (render->name == new_renderer && render->has_adapters && render->adapters.contains(text))
{
m_emu_settings->SetSetting(render->type, sstr(text));
break;
}
}
};
// Init
set_renderer(ui->renderBox->currentText());
set_adapter(ui->graphicsAdapterBox->currentText());
// Events
connect(ui->graphicsAdapterBox, &QComboBox::currentTextChanged, set_adapter);
connect(ui->renderBox, &QComboBox::currentTextChanged, set_renderer);
const auto apply_renderer_specific_options = [r_creator, this](const QString& text)
{
// Vulkan-only
const bool is_vulkan = (text == r_creator->Vulkan.name);
ui->asyncTextureStreaming->setEnabled(is_vulkan);
ui->vulkansched->setEnabled(is_vulkan);
};
const auto apply_fsr_specific_options = [r_creator, this]()
{
const auto [text, value] = get_data(ui->outputScalingMode, ui->outputScalingMode->currentIndex());
const bool fsr_selected = static_cast<output_scaling_mode>(value) == output_scaling_mode::fsr;
ui->fsrSharpeningStrength->setEnabled(fsr_selected);
ui->fsrSharpeningStrengthReset->setEnabled(fsr_selected);
};
// Handle connects to disable specific checkboxes that depend on GUI state.
on_strict_rendering_mode(ui->strictModeRendering->isChecked());
apply_renderer_specific_options(ui->renderBox->currentText()); // Init
apply_fsr_specific_options();
connect(ui->renderBox, &QComboBox::currentTextChanged, apply_renderer_specific_options);
connect(ui->renderBox, &QComboBox::currentTextChanged, this, apply_fsr_specific_options);
connect(ui->outputScalingMode, QOverload<int>::of(&QComboBox::currentIndexChanged), this, apply_fsr_specific_options);
// _ _ _______ _
// /\ | (_) |__ __| | |
// / \ _ _ __| |_ ___ | | __ _| |__
// / /\ \| | | |/ _` | |/ _ \ | |/ _` | '_ \
// / ____ \ |_| | (_| | | (_) | | | (_| | |_) |
// /_/ \_\__,_|\__,_|_|\___/ |_|\__,_|_.__/
const QString mic_none = m_emu_settings->m_microphone_creator.get_none();
const auto change_microphone_type = [mic_none, this](int index)
{
if (index < 0)
{
return;
}
const auto [text, handler_id] = get_data(ui->microphoneBox, index);
int max = 0;
switch (static_cast<microphone_handler>(handler_id))
{
case microphone_handler::standard:
max = 4;
break;
case microphone_handler::singstar:
max = 2;
break;
case microphone_handler::real_singstar:
case microphone_handler::rocksmith:
max = 1;
break;
case microphone_handler::null:
break;
}
ui->microphone1Box->setEnabled(max > 0);
ui->microphone2Box->setEnabled(max > 1 && ui->microphone1Box->currentText() != mic_none);
ui->microphone3Box->setEnabled(max > 2 && ui->microphone2Box->currentText() != mic_none);
ui->microphone4Box->setEnabled(ui->microphone3Box->isEnabled() && ui->microphone3Box->currentText() != mic_none);
};
const auto propagate_used_devices = [mic_none, change_microphone_type, this]()
{
for (u32 index = 0; index < m_mics_combo.size(); index++)
{
const QString cur_item = m_mics_combo[index]->currentText();
QStringList cur_list = m_emu_settings->m_microphone_creator.get_microphone_list();
for (u32 subindex = 0; subindex < m_mics_combo.size(); subindex++)
{
if (subindex != index && m_mics_combo[subindex]->currentText() != mic_none)
cur_list.removeOne(m_mics_combo[subindex]->currentText());
}
m_mics_combo[index]->blockSignals(true);
m_mics_combo[index]->clear();
m_mics_combo[index]->addItems(cur_list);
m_mics_combo[index]->setCurrentText(cur_item);
m_mics_combo[index]->blockSignals(false);
}
change_microphone_type(ui->microphoneBox->currentIndex());
};
const auto change_microphone_device = [mic_none, propagate_used_devices, this](u32 index, const QString& text)
{
m_emu_settings->SetSetting(emu_settings_type::MicrophoneDevices, m_emu_settings->m_microphone_creator.set_device(index, text));
if (const u32 next_index = index + 1; next_index < m_mics_combo.size() && text == mic_none)
m_mics_combo[next_index]->setCurrentText(mic_none);
propagate_used_devices();
};
const auto get_audio_output_devices = [this](bool keep_old = true)
{
const auto [text, value] = get_data(ui->audioOutBox, ui->audioOutBox->currentIndex());
auto dev_enum = Emu.GetCallbacks().get_audio_enumerator(value);
std::vector<audio_device_enumerator::audio_device> dev_array = dev_enum->get_output_devices();
ui->audioDeviceBox->clear();
ui->audioDeviceBox->blockSignals(true);
ui->audioDeviceBox->addItem(tr("Default"), qsv(audio_device_enumerator::DEFAULT_DEV_ID));
const std::string selected_device = m_emu_settings->GetSetting(emu_settings_type::AudioDevice);
int device_index = 0;
for (const audio_device_enumerator::audio_device& dev : dev_array)
{
const QString cur_item = qstr(dev.id);
ui->audioDeviceBox->addItem(qstr(dev.name), cur_item);
if (selected_device == dev.id)
{
device_index = ui->audioDeviceBox->findData(cur_item);
}
}
if (device_index == 0 && keep_old && selected_device != audio_device_enumerator::DEFAULT_DEV_ID)
{
cfg_log.error("The selected audio device (%s) was not found", selected_device);
ui->audioDeviceBox->addItem(tr("Unknown device"), qsv(selected_device));
device_index = ui->audioDeviceBox->count() - 1;
}
ui->audioDeviceBox->blockSignals(false);
ui->audioDeviceBox->setCurrentIndex(std::max(device_index, 0));
};
const auto change_audio_output_device = [this](int index)
{
if (index < 0)
{
return;
}
const QVariant item_data = ui->audioDeviceBox->itemData(index);
m_emu_settings->SetSetting(emu_settings_type::AudioDevice, sstr(item_data.toString()));
ui->audioDeviceBox->setCurrentIndex(index);
};
// Comboboxes
m_emu_settings->EnhanceComboBox(ui->audioOutBox, emu_settings_type::AudioRenderer);
#ifdef WIN32
SubscribeTooltip(ui->gb_audio_out, tooltips.settings.audio_out);
#else
SubscribeTooltip(ui->gb_audio_out, tooltips.settings.audio_out_linux);
#endif
connect(ui->audioOutBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [change_audio_output_device, get_audio_output_devices](int)
{
get_audio_output_devices(false);
change_audio_output_device(0); // Set device to 'Default'
});
m_emu_settings->EnhanceComboBox(ui->combo_audio_channel_layout, emu_settings_type::AudioChannelLayout);
SubscribeTooltip(ui->gb_audio_channel_layout, tooltips.settings.audio_channel_layout);
connect(ui->combo_audio_format, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int index)
{
const auto [text, value] = get_data(ui->combo_audio_format, index);
ui->list_audio_formats->setEnabled(static_cast<audio_format>(value) == audio_format::manual);
});
m_emu_settings->EnhanceComboBox(ui->combo_audio_format, emu_settings_type::AudioFormat);
SubscribeTooltip(ui->gb_audio_format, tooltips.settings.audio_format);
// Manual audio format selection
const std::string audio_formats_str = m_emu_settings->GetSetting(emu_settings_type::AudioFormats);
u64 selected_audio_formats = 0;
if (!try_to_uint64(&selected_audio_formats, audio_formats_str, 0, 0xFFFFFFFF))
{
cfg_log.error("Can not interpret AudioFormats value '%s' as number", audio_formats_str);
}
const std::array<audio_format_flag, 5> audio_formats = {
audio_format_flag::lpcm_2_48khz,
audio_format_flag::lpcm_5_1_48khz,
audio_format_flag::lpcm_7_1_48khz,
audio_format_flag::ac3,
audio_format_flag::dts,
};
for (const audio_format_flag& audio_fmt : audio_formats)
{
const QString audio_format_name = m_emu_settings->GetLocalizedSetting(QString(), emu_settings_type::AudioFormats, static_cast<int>(audio_fmt), true);
QListWidgetItem* item = new QListWidgetItem(audio_format_name, ui->list_audio_formats);
item->setData(Qt::UserRole, static_cast<u32>(audio_fmt));
if (audio_fmt == audio_format_flag::lpcm_2_48khz)
{
item->setFlags(item->flags() & ~Qt::ItemIsEnabled);
item->setCheckState(Qt::Checked);
}
else
{
item->setFlags(item->flags() | Qt::ItemIsUserCheckable);
item->setCheckState(!!(selected_audio_formats & static_cast<u32>(audio_fmt)) ? Qt::Checked : Qt::Unchecked);
}
ui->list_audio_formats->addItem(item);
}
connect(this, &settings_dialog::signal_restore_dependant_defaults, this, [this]()
{
const u32 default_audio_formats = std::stoi(m_emu_settings->GetSettingDefault(emu_settings_type::AudioFormats));
for (int i = 0; i < ui->list_audio_formats->count(); ++i)
{
const auto& item = ui->list_audio_formats->item(i);
const u32 audio_fmt = item->data(Qt::UserRole).toUInt();
if (audio_fmt == static_cast<u32>(audio_format_flag::lpcm_2_48khz))
{
item->setCheckState(Qt::Checked);
}
else
{
item->setCheckState(!!(default_audio_formats & audio_fmt) ? Qt::Checked : Qt::Unchecked);
}
}
});
m_emu_settings->EnhanceComboBox(ui->audioProviderBox, emu_settings_type::AudioProvider);
SubscribeTooltip(ui->gb_audio_provider, tooltips.settings.audio_provider);
ui->gb_audio_provider->setVisible(false); // Hidden for now. This option is forced on boot.
m_emu_settings->EnhanceComboBox(ui->audioAvportBox, emu_settings_type::AudioAvport);
SubscribeTooltip(ui->gb_audio_avport, tooltips.settings.audio_avport);
SubscribeTooltip(ui->gb_audio_device, tooltips.settings.audio_device);
connect(ui->audioDeviceBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, change_audio_output_device);
connect(this, &settings_dialog::signal_restore_dependant_defaults, this, [change_audio_output_device]() { change_audio_output_device(0); }); // Set device to 'Default'
get_audio_output_devices();
// Microphone Comboboxes
m_mics_combo[0] = ui->microphone1Box;
m_mics_combo[1] = ui->microphone2Box;
m_mics_combo[2] = ui->microphone3Box;
m_mics_combo[3] = ui->microphone4Box;
for (u32 i = 0; i < m_mics_combo.size(); i++)
{
connect(m_mics_combo[i], &QComboBox::currentTextChanged, this, [change_microphone_device, i](const QString& text) { change_microphone_device(i, text); });
connect(this, &settings_dialog::signal_restore_dependant_defaults, this, [change_microphone_device, i, mic_none]() { change_microphone_device(i, mic_none); });
}
m_emu_settings->m_microphone_creator.refresh_list();
propagate_used_devices(); // Fills comboboxes list
m_emu_settings->m_microphone_creator.parse_devices(m_emu_settings->GetSetting(emu_settings_type::MicrophoneDevices));
const std::array<std::string, 4> mic_sel_list = m_emu_settings->m_microphone_creator.get_selection_list();
for (s32 index = static_cast<int>(mic_sel_list.size()) - 1; index >= 0; index--)
{
const QString qmic = qstr(mic_sel_list[index]);
if (qmic.isEmpty() || m_mics_combo[index]->findText(qmic) == -1)
{
m_mics_combo[index]->setCurrentText(mic_none);
change_microphone_device(index, mic_none); // Ensures the value is set in config
}
else
{
m_mics_combo[index]->setCurrentText(qmic);
}
}
m_emu_settings->EnhanceComboBox(ui->microphoneBox, emu_settings_type::MicrophoneType);
SubscribeTooltip(ui->microphoneBox, tooltips.settings.microphone);
connect(ui->microphoneBox, QOverload<int>::of(&QComboBox::currentIndexChanged), change_microphone_type);
propagate_used_devices(); // Enables/Disables comboboxes and checks values from config for sanity
// Checkboxes
m_emu_settings->EnhanceCheckBox(ui->audioDump, emu_settings_type::DumpToFile);
SubscribeTooltip(ui->audioDump, tooltips.settings.audio_dump);
m_emu_settings->EnhanceCheckBox(ui->convert, emu_settings_type::ConvertTo16Bit);
SubscribeTooltip(ui->convert, tooltips.settings.convert);
m_emu_settings->EnhanceCheckBox(ui->enableBuffering, emu_settings_type::EnableBuffering);
SubscribeTooltip(ui->enableBuffering, tooltips.settings.enable_buffering);
m_emu_settings->EnhanceCheckBox(ui->enableTimeStretching, emu_settings_type::EnableTimeStretching);
SubscribeTooltip(ui->enableTimeStretching, tooltips.settings.enable_time_stretching);
// Sliders
EnhanceSlider(emu_settings_type::MasterVolume, ui->masterVolume, ui->masterVolumeLabel, tr("Master: %0 %", "Master volume"));
SubscribeTooltip(ui->master_volume, tooltips.settings.master_volume);
EnhanceSlider(emu_settings_type::AudioBufferDuration, ui->audioBufferDuration, ui->audioBufferDurationLabel, tr("Audio Buffer Duration: %0 ms", "Audio buffer duration"));
SubscribeTooltip(ui->audio_buffer_duration, tooltips.settings.audio_buffer_duration);
EnhanceSlider(emu_settings_type::TimeStretchingThreshold, ui->timeStretchingThreshold, ui->timeStretchingThresholdLabel, tr("Time Stretching Threshold: %0 %", "Time stretching threshold"));
SubscribeTooltip(ui->time_stretching_threshold, tooltips.settings.time_stretching_threshold);
// _____ __ ____ _______ _
// |_ _| / / / __ \ |__ __| | |
// | | / / | | | | | | __ _| |__
// | | / / | | | | | |/ _` | '_ \
// _| |_ / / | |__| | | | (_| | |_) |
// |_____| /_/ \____/ |_|\__,_|_.__/
// Comboboxes
m_emu_settings->EnhanceComboBox(ui->keyboardHandlerBox, emu_settings_type::KeyboardHandler);
SubscribeTooltip(ui->gb_keyboard_handler, tooltips.settings.keyboard_handler);
m_emu_settings->EnhanceComboBox(ui->mouseHandlerBox, emu_settings_type::MouseHandler);
SubscribeTooltip(ui->gb_mouse_handler, tooltips.settings.mouse_handler);
m_emu_settings->EnhanceComboBox(ui->cameraTypeBox, emu_settings_type::CameraType);
SubscribeTooltip(ui->gb_camera_type, tooltips.settings.camera_type);
m_emu_settings->EnhanceComboBox(ui->cameraBox, emu_settings_type::Camera);
SubscribeTooltip(ui->gb_camera_setting, tooltips.settings.camera);
m_emu_settings->EnhanceComboBox(ui->cameraFlipBox, emu_settings_type::CameraFlip);
SubscribeTooltip(ui->gb_camera_flip, tooltips.settings.camera_flip);
{
const std::string default_camera = m_emu_settings->GetSettingDefault(emu_settings_type::CameraID);
const std::string selected_camera = m_emu_settings->GetSetting(emu_settings_type::CameraID);
ui->cameraIdBox->addItem(tr("None", "Camera Device"), "");
ui->cameraIdBox->addItem(tr("Default", "Camera Device"), qstr(default_camera));
for (const QCameraDevice& camera_info : QMediaDevices::videoInputs())
{
if (!camera_info.isNull())
{
ui->cameraIdBox->addItem(camera_info.description(), QString(camera_info.id()));
}
}
if (const int index = ui->cameraIdBox->findData(qstr(selected_camera)); index >= 0)
{
ui->cameraIdBox->setCurrentIndex(index);
}
else
{
cfg_log.error("The selected camera was not found. Selecting default camera as fallback.");
ui->cameraIdBox->setCurrentIndex(ui->cameraIdBox->findData(qstr(default_camera)));
}
connect(ui->cameraIdBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int index)
{
if (index >= 0) m_emu_settings->SetSetting(emu_settings_type::CameraID, ui->cameraIdBox->itemData(index).toString().toStdString());
});
connect(this, &settings_dialog::signal_restore_dependant_defaults, this, [this, default_camera]()
{
m_emu_settings->SetSetting(emu_settings_type::CameraID, default_camera);
ui->cameraIdBox->setCurrentIndex(ui->cameraIdBox->findData(qstr(default_camera)));
});
SubscribeTooltip(ui->gb_camera_id, tooltips.settings.camera_id);
}
m_emu_settings->EnhanceComboBox(ui->musicHandlerBox, emu_settings_type::MusicHandler);
SubscribeTooltip(ui->gb_music_handler, tooltips.settings.music_handler);
m_emu_settings->EnhanceComboBox(ui->padModeBox, emu_settings_type::PadHandlerMode);
SubscribeTooltip(ui->gb_pad_mode, tooltips.settings.pad_mode);
m_emu_settings->EnhanceComboBox(ui->moveBox, emu_settings_type::Move);
SubscribeTooltip(ui->gb_move_handler, tooltips.settings.move);
m_emu_settings->EnhanceComboBox(ui->buzzBox, emu_settings_type::Buzz);
SubscribeTooltip(ui->gb_buzz_emulated, tooltips.settings.buzz);
m_emu_settings->EnhanceComboBox(ui->turntableBox, emu_settings_type::Turntable);
SubscribeTooltip(ui->gb_turntable_emulated, tooltips.settings.turntable);
m_emu_settings->EnhanceComboBox(ui->ghltarBox, emu_settings_type::GHLtar);
SubscribeTooltip(ui->gb_ghltar_emulated, tooltips.settings.ghltar);
m_emu_settings->EnhanceCheckBox(ui->backgroundInputBox, emu_settings_type::BackgroundInput);
SubscribeTooltip(ui->backgroundInputBox, tooltips.settings.background_input);
m_emu_settings->EnhanceCheckBox(ui->padConnectionBox, emu_settings_type::PadConnection);
SubscribeTooltip(ui->padConnectionBox, tooltips.settings.pad_connection);
m_emu_settings->EnhanceCheckBox(ui->showMoveCursorBox, emu_settings_type::ShowMoveCursor);
SubscribeTooltip(ui->showMoveCursorBox, tooltips.settings.show_move_cursor);
m_emu_settings->EnhanceCheckBox(ui->lockOverlayInputToPlayerOne, emu_settings_type::LockOvlIptToP1);
SubscribeTooltip(ui->lockOverlayInputToPlayerOne, tooltips.settings.lock_overlay_input_to_player_one);
#if HAVE_SDL2
m_emu_settings->EnhanceCheckBox(ui->loadSdlMappings, emu_settings_type::SDLMappings);
SubscribeTooltip(ui->loadSdlMappings, tooltips.settings.sdl_mappings);
#else
ui->loadSdlMappings->setVisible(false);
#endif
#ifndef _WIN32
// Remove raw mouse handler
remove_item(ui->mouseHandlerBox, static_cast<int>(mouse_handler::raw), static_cast<int>(g_cfg.io.mouse.def));
remove_item(ui->moveBox, static_cast<int>(move_handler::raw_mouse), static_cast<int>(g_cfg.io.move.def));
#endif
// Midi
const QString midi_none = m_emu_settings->m_midi_creator.get_none();
const midi_device def_midi_device{ .type = midi_device_type::keyboard, .name = midi_none.toStdString() };
const std::vector<std::string> midi_device_types = cfg::try_to_enum_list(&fmt_class_string<midi_device_type>::format);
m_midi_type_combo[0] = ui->midiTypeBox1;
m_midi_type_combo[1] = ui->midiTypeBox2;
m_midi_type_combo[2] = ui->midiTypeBox3;
m_midi_device_combo[0] = ui->midiDeviceBox1;
m_midi_device_combo[1] = ui->midiDeviceBox2;
m_midi_device_combo[2] = ui->midiDeviceBox3;
SubscribeTooltip(ui->gb_midi_1, tooltips.settings.midi_devices);
SubscribeTooltip(ui->gb_midi_2, tooltips.settings.midi_devices);
SubscribeTooltip(ui->gb_midi_3, tooltips.settings.midi_devices);
const auto propagate_midi_devices = [midi_none, this]()
{
for (u32 index = 0; index < m_midi_device_combo.size(); index++)
{
const QString cur_item = m_midi_device_combo[index]->currentText();
QStringList cur_list = m_emu_settings->m_midi_creator.get_midi_list();
for (u32 subindex = 0; subindex < m_midi_device_combo.size(); subindex++)
{
if (subindex != index && m_midi_device_combo[subindex]->currentText() != midi_none)
cur_list.removeOne(m_midi_device_combo[subindex]->currentText());
}
m_midi_device_combo[index]->blockSignals(true);
m_midi_device_combo[index]->clear();
m_midi_device_combo[index]->addItems(cur_list);
m_midi_device_combo[index]->setCurrentText(cur_item);
m_midi_device_combo[index]->blockSignals(false);
}
};
const auto change_midi_device = [propagate_midi_devices, this](u32 index, const midi_device& device)
{
m_emu_settings->SetSetting(emu_settings_type::MidiDevices, m_emu_settings->m_midi_creator.set_device(index, device));
propagate_midi_devices();
};
for (u32 i = 0; i < m_midi_type_combo.size(); i++)
{
m_midi_type_combo[i]->blockSignals(true);
for (const std::string& type_str : midi_device_types)
{
midi_device_type type{};
if (u64 result; cfg::try_to_enum_value(&result, &fmt_class_string<midi_device_type>::format, type_str))
{
type = static_cast<midi_device_type>(static_cast<std::underlying_type_t<midi_device_type>>(result));
}
const QString type_name = m_emu_settings->GetLocalizedSetting(QString::fromStdString(fmt::format("%s", type)), emu_settings_type::MidiDevices, static_cast<int>(type), false);
m_midi_type_combo[i]->addItem(type_name, static_cast<int>(type));
}
m_midi_type_combo[i]->blockSignals(false);
connect(m_midi_type_combo[i], &QComboBox::currentTextChanged, this, [this, change_midi_device, i](const QString& /*text*/)
{
const midi_device device{ .type = static_cast<midi_device_type>(m_midi_type_combo[i]->currentData().toInt()), .name = m_midi_device_combo[i]->currentText().toStdString() };
change_midi_device(i, device);
});
connect(m_midi_device_combo[i], &QComboBox::currentTextChanged, this, [this, change_midi_device, i](const QString& text)
{
const midi_device device{ .type = static_cast<midi_device_type>(m_midi_type_combo[i]->currentData().toInt()), .name = text.toStdString() };
change_midi_device(i, device);
});
connect(this, &settings_dialog::signal_restore_dependant_defaults, this, [change_midi_device, i, def_midi_device]() { change_midi_device(i, def_midi_device); });
}
m_emu_settings->m_midi_creator.refresh_list();
propagate_midi_devices(); // Fills comboboxes list
m_emu_settings->m_midi_creator.parse_devices(m_emu_settings->GetSetting(emu_settings_type::MidiDevices));
const std::array<midi_device, max_midi_devices> midi_sel_list = m_emu_settings->m_midi_creator.get_selection_list();
for (s32 index = static_cast<int>(midi_sel_list.size()) - 1; index >= 0; index--)
{
const midi_device& device = midi_sel_list[index];
const QString qmidi = QString::fromStdString(device.name);
m_midi_type_combo[index]->setCurrentIndex(m_midi_type_combo[index]->findData(static_cast<int>(device.type)));
if (qmidi.isEmpty() || m_midi_device_combo[index]->findText(qmidi) == -1)
{
m_midi_device_combo[index]->setCurrentText(midi_none);
change_midi_device(index, def_midi_device); // Ensures the value is set in config
}
else
{
m_midi_device_combo[index]->setCurrentText(qmidi);
}
}
propagate_midi_devices(); // Enables/Disables comboboxes and checks values from config for sanity
// _____ _ _______ _
// / ____| | | |__ __| | |
// | (___ _ _ ___| |_ ___ _ __ ___ | | __ _| |__
// \___ \| | | / __| __/ _ \ '_ ` _ \ | |/ _` | '_ \
// ____) | |_| \__ \ || __/ | | | | | | | (_| | |_) |
// |_____/ \__, |___/\__\___|_| |_| |_| |_|\__,_|_.__/
// __/ |
// |___/
// Comboboxes
m_emu_settings->EnhanceComboBox(ui->sysLangBox, emu_settings_type::Language, false, false, 0, true);
SubscribeTooltip(ui->gb_sysLang, tooltips.settings.system_language);
m_emu_settings->EnhanceComboBox(ui->console_region, emu_settings_type::LicenseArea, false, false, 0, true);
SubscribeTooltip(ui->gb_console_region, tooltips.settings.license_area);
m_emu_settings->EnhanceComboBox(ui->keyboardType, emu_settings_type::KeyboardType, false, false, 0, true);
SubscribeTooltip(ui->gb_keyboardType, tooltips.settings.keyboard_type);
// Checkboxes
m_emu_settings->EnhanceCheckBox(ui->enableHostRoot, emu_settings_type::EnableHostRoot);
SubscribeTooltip(ui->enableHostRoot, tooltips.settings.enable_host_root);
m_emu_settings->EnhanceCheckBox(ui->enableCacheClearing, emu_settings_type::LimitCacheSize);
SubscribeTooltip(ui->gb_DiskCacheClearing, tooltips.settings.limit_cache_size);
if (game)
ui->gb_DiskCacheClearing->setDisabled(true);
else
connect(ui->enableCacheClearing, &QCheckBox::checkStateChanged, ui->maximumCacheSize, &QSlider::setEnabled);
// Date Time Edit Box
m_emu_settings->EnhanceDateTimeEdit(ui->console_time_edit, emu_settings_type::ConsoleTimeOffset, tr("dd MMM yyyy HH:mm"), true, true, 15000);
connect(ui->console_time_reset, &QAbstractButton::clicked, [this]()
{
ui->console_time_edit->setDateTime(QDateTime::currentDateTime());
});
SubscribeTooltip(ui->gb_console_time, tooltips.settings.console_time_offset);
// Sliders
EnhanceSlider(emu_settings_type::MaximumCacheSize, ui->maximumCacheSize, ui->maximumCacheSizeLabel, tr("Maximum size: %0 MB", "Maximum cache size"));
ui->maximumCacheSize->setEnabled(ui->enableCacheClearing->isChecked());
// Radio Buttons
// creating this in ui file keeps scrambling the order...
QButtonGroup *enter_button_assignment_bg = new QButtonGroup(this);
enter_button_assignment_bg->addButton(ui->enterButtonAssignCircle, 0);
enter_button_assignment_bg->addButton(ui->enterButtonAssignCross, 1);
m_emu_settings->EnhanceRadioButton(enter_button_assignment_bg, emu_settings_type::EnterButtonAssignment);
SubscribeTooltip(ui->gb_enterButtonAssignment, tooltips.settings.enter_button_assignment);
// _ _ _ _ _______ _
// | \ | | | | | | |__ __| | |
// | \| | ___| |___ _____ _ __| | __ | | __ _| |__
// | . ` |/ _ \ __\ \ /\ / / _ \| '__| |/ / | |/ _` | '_ \
// | |\ | __/ |_ \ V V / (_) | | | < | | (_| | |_) |
// |_| \_|\___|\__| \_/\_/ \___/|_| |_|\_\ |_|\__,_|_.__/
// Edits
m_emu_settings->EnhanceLineEdit(ui->edit_dns, emu_settings_type::DNSAddress);
SubscribeTooltip(ui->gb_edit_dns, tooltips.settings.dns);
m_emu_settings->EnhanceLineEdit(ui->edit_bind, emu_settings_type::BindAddress);
SubscribeTooltip(ui->gb_edit_bind, tooltips.settings.bind);
ui->gb_edit_bind->setEnabled(!!game);
m_emu_settings->EnhanceLineEdit(ui->edit_swaps, emu_settings_type::IpSwapList);
SubscribeTooltip(ui->gb_edit_swaps, tooltips.settings.dns_swap);
ui->gb_edit_swaps->setEnabled(!!game);
m_emu_settings->EnhanceCheckBox(ui->enable_upnp, emu_settings_type::EnableUpnp);
SubscribeTooltip(ui->enable_upnp, tooltips.settings.enable_upnp);
// Comboboxes
connect(ui->netStatusBox, QOverload<int>::of(&QComboBox::currentIndexChanged), [this](int index)
{
if (index < 0) return;
const auto [text, value] = get_data(ui->netStatusBox, index);
ui->gb_edit_dns->setEnabled(static_cast<np_internet_status>(value) != np_internet_status::disabled);
ui->enable_upnp->setEnabled(static_cast<np_internet_status>(value) != np_internet_status::disabled);
});
m_emu_settings->EnhanceComboBox(ui->netStatusBox, emu_settings_type::InternetStatus);
SubscribeTooltip(ui->gb_netStatusBox, tooltips.settings.net_status);
m_emu_settings->EnhanceComboBox(ui->psnStatusBox, emu_settings_type::PSNStatus);
SubscribeTooltip(ui->gb_psnStatusBox, tooltips.settings.psn_status);
settings_dialog::refresh_countrybox();
connect(ui->psnCountryBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this](int index)
{
if (index < 0)
return;
const QVariant country_code = ui->psnCountryBox->itemData(index);
if (!country_code.isValid() || !country_code.canConvert<QString>())
return;
m_emu_settings->SetSetting(emu_settings_type::PSNCountry, country_code.toString().toStdString());
});
SubscribeTooltip(ui->gb_psnCountryBox, tooltips.settings.psn_country);
if (!game)
{
remove_item(ui->psnStatusBox, static_cast<int>(np_psn_status::psn_fake), static_cast<int>(g_cfg.net.psn_status.def));
}
// _ _ _______ _
// /\ | | | | |__ __| | |
// / \ __| |_ ____ _ _ __ ___ ___ __| | | | __ _| |__
// / /\ \ / _` \ \ / / _` | '_ \ / __/ _ \/ _` | | |/ _` | '_ \
// / ____ \ (_| |\ V / (_| | | | | (_| __/ (_| | | | (_| | |_) |
// /_/ \_\__,_| \_/ \__,_|_| |_|\___\___|\__,_| |_|\__,_|_.__/
// Checkboxes
m_emu_settings->EnhanceCheckBox(ui->debugConsoleMode, emu_settings_type::DebugConsoleMode);
SubscribeTooltip(ui->debugConsoleMode, tooltips.settings.debug_console_mode);
m_emu_settings->EnhanceCheckBox(ui->accurateDFMA, emu_settings_type::AccurateDFMA);
SubscribeTooltip(ui->accurateDFMA, tooltips.settings.accurate_dfma);
ui->accurateDFMA->setDisabled(utils::has_fma3() || utils::has_fma4());
m_emu_settings->EnhanceCheckBox(ui->accurateRSXAccess, emu_settings_type::AccurateRSXAccess);
SubscribeTooltip(ui->accurateRSXAccess, tooltips.settings.accurate_rsx_access);
m_emu_settings->EnhanceCheckBox(ui->accurateSpuDMA, emu_settings_type::AccurateSpuDMA);
SubscribeTooltip(ui->accurateSpuDMA, tooltips.settings.accurate_spu_dma);
m_emu_settings->EnhanceCheckBox(ui->ppuNJFixup, emu_settings_type::PPUNJFixup);
SubscribeTooltip(ui->ppuNJFixup, tooltips.settings.fixup_ppunj);
m_emu_settings->EnhanceCheckBox(ui->fixupPPUVNAN, emu_settings_type::FixupPPUVNAN);
SubscribeTooltip(ui->fixupPPUVNAN, tooltips.settings.fixup_ppuvnan);
m_emu_settings->EnhanceCheckBox(ui->llvmPrecompilation, emu_settings_type::LLVMPrecompilation);
SubscribeTooltip(ui->llvmPrecompilation, tooltips.settings.llvm_precompilation);
m_emu_settings->EnhanceCheckBox(ui->antiCheatSavestates, emu_settings_type::SuspendEmulationSavestateMode);
SubscribeTooltip(ui->antiCheatSavestates, tooltips.settings.anti_cheat_savestates);
m_emu_settings->EnhanceCheckBox(ui->compatibleSavestates, emu_settings_type::CompatibleEmulationSavestateMode);
SubscribeTooltip(ui->compatibleSavestates, tooltips.settings.compatible_savestates);
m_emu_settings->EnhanceCheckBox(ui->spuProfiler, emu_settings_type::SPUProfiler);
SubscribeTooltip(ui->spuProfiler, tooltips.settings.spu_profiler);
m_emu_settings->EnhanceCheckBox(ui->silenceAllLogs, emu_settings_type::SilenceAllLogs);
SubscribeTooltip(ui->silenceAllLogs, tooltips.settings.silence_all_logs);
m_emu_settings->EnhanceCheckBox(ui->readColor, emu_settings_type::ReadColorBuffers);
SubscribeTooltip(ui->readColor, tooltips.settings.read_color);
m_emu_settings->EnhanceCheckBox(ui->readDepth, emu_settings_type::ReadDepthBuffer);
SubscribeTooltip(ui->readDepth, tooltips.settings.read_depth);
m_emu_settings->EnhanceCheckBox(ui->dumpDepth, emu_settings_type::WriteDepthBuffer);
SubscribeTooltip(ui->dumpDepth, tooltips.settings.dump_depth);
m_emu_settings->EnhanceCheckBox(ui->handleTiledMemory, emu_settings_type::HandleRSXTiledMemory);
SubscribeTooltip(ui->handleTiledMemory, tooltips.settings.handle_tiled_memory);
m_emu_settings->EnhanceCheckBox(ui->disableOnDiskShaderCache, emu_settings_type::DisableOnDiskShaderCache);
SubscribeTooltip(ui->disableOnDiskShaderCache, tooltips.settings.disable_on_disk_shader_cache);
m_emu_settings->EnhanceCheckBox(ui->vblankNTSCFixup, emu_settings_type::VBlankNTSCFixup);
ui->mfcDelayCommand->setChecked(m_emu_settings->GetSetting(emu_settings_type::MFCCommandsShuffling) == "1");
SubscribeTooltip(ui->mfcDelayCommand, tooltips.settings.mfc_delay_command);
connect(ui->mfcDelayCommand, &QCheckBox::checkStateChanged, [&](Qt::CheckState val)
{
const std::string str = val != Qt::Unchecked ? "1" : "0";
m_emu_settings->SetSetting(emu_settings_type::MFCCommandsShuffling, str);
});
m_emu_settings->EnhanceCheckBox(ui->disableMslFastMath, emu_settings_type::DisableMSLFastMath);
#ifdef __APPLE__
SubscribeTooltip(ui->disableMslFastMath, tooltips.settings.disable_msl_fast_math);
#else
ui->disableMslFastMath->setVisible(false);
#endif
// Comboboxes
m_emu_settings->EnhanceComboBox(ui->maxSPURSThreads, emu_settings_type::MaxSPURSThreads, true);
ui->maxSPURSThreads->setItemText(ui->maxSPURSThreads->findData(6), tr("Unlimited (Default)", "Max SPURS threads"));
SubscribeTooltip(ui->gb_max_spurs_threads, tooltips.settings.max_spurs_threads);
m_emu_settings->EnhanceComboBox(ui->exclusiveFullscreenMode, emu_settings_type::ExclusiveFullscreenMode);
SubscribeTooltip(ui->gb_exclusiveFullscreen, tooltips.settings.exclusive_fullscreen_mode);
m_emu_settings->EnhanceComboBox(ui->sleepTimersAccuracy, emu_settings_type::SleepTimersAccuracy);
SubscribeTooltip(ui->gb_sleep_timers_accuracy, tooltips.settings.sleep_timers_accuracy);
m_emu_settings->EnhanceComboBox(ui->FIFOAccuracy, emu_settings_type::FIFOAccuracy);
SubscribeTooltip(ui->gb_rsx_fifo_accuracy, tooltips.settings.rsx_fifo_accuracy);
// Hide a developers' setting
remove_item(ui->FIFOAccuracy, static_cast<int>(rsx_fifo_mode::as_ps3), static_cast<int>(g_cfg.core.rsx_fifo_accuracy.def));
m_emu_settings->EnhanceComboBox(ui->vulkansched, emu_settings_type::VulkanAsyncSchedulerDriver);
SubscribeTooltip(ui->gb_vulkansched, tooltips.settings.vulkan_async_scheduler);
// Sliders
EnhanceSlider(emu_settings_type::DriverWakeUpDelay, ui->wakeupDelay, ui->wakeupText, tr(reinterpret_cast<const char*>(u8"%0 µs"), "Driver wake up delay"));
SnapSlider(ui->wakeupDelay, 20);
ui->wakeupDelay->setMaximum(800); // Very large values must be entered with config.yml changes
ui->wakeupDelay->setPageStep(20);
const int wakeup_def = stoi(m_emu_settings->GetSettingDefault(emu_settings_type::DriverWakeUpDelay));
connect(ui->wakeupReset, &QAbstractButton::clicked, [wakeup_def, this]()
{
ui->wakeupDelay->setValue(wakeup_def);
});
EnhanceSlider(emu_settings_type::VBlankRate, ui->vblank, ui->vblankText, tr("%0 Hz", "VBlank rate"));
SnapSlider(ui->vblank, 30);
ui->vblank->setPageStep(60);
const int vblank_def = stoi(m_emu_settings->GetSettingDefault(emu_settings_type::VBlankRate));
connect(ui->vblankReset, &QAbstractButton::clicked, [vblank_def, this]()
{
ui->vblank->setValue(vblank_def);
});
EnhanceSlider(emu_settings_type::ClocksScale, ui->clockScale, ui->clockScaleText, tr("%0 %", "Clocks scale"));
SnapSlider(ui->clockScale, 10);
ui->clockScale->setPageStep(50);
const int clocks_scale_def = stoi(m_emu_settings->GetSettingDefault(emu_settings_type::ClocksScale));
connect(ui->clockScaleReset, &QAbstractButton::clicked, [clocks_scale_def, this]()
{
ui->clockScale->setValue(clocks_scale_def);
});
EnhanceSlider(emu_settings_type::MaxPreemptCount, ui->maxPreemptCount, ui->preemptText, tr(reinterpret_cast<const char*>(u8"%0"), "Max CPU preempt count"));
SubscribeTooltip(ui->gb_max_preempt_count, tooltips.settings.max_cpu_preempt);
#ifdef _WIN32
// Windows' thread execution slice is much larger than on other platforms
SnapSlider(ui->maxPreemptCount, 5);
ui->maxPreemptCount->setPageStep(20);
#else
SnapSlider(ui->maxPreemptCount, 10);
ui->maxPreemptCount->setPageStep(50);
#endif
const int preempt_def = stoi(m_emu_settings->GetSettingDefault(emu_settings_type::MaxPreemptCount));
connect(ui->preemptReset, &QAbstractButton::clicked, [preempt_def, this]()
{
ui->maxPreemptCount->setValue(preempt_def);
});
if (!game) // Prevent users from doing dumb things
{
ui->gb_vblank->setDisabled(true);
SubscribeTooltip(ui->gb_vblank, tooltips.settings.disabled_from_global);
ui->gb_clockScale->setDisabled(true);
SubscribeTooltip(ui->gb_clockScale, tooltips.settings.disabled_from_global);
ui->gb_wakeupDelay->setDisabled(true);
SubscribeTooltip(ui->gb_wakeupDelay, tooltips.settings.disabled_from_global);
}
else
{
SubscribeTooltip(ui->vblankNTSCFixup, tooltips.settings.vblank_ntsc_fixup);
SubscribeTooltip(ui->gb_vblank, tooltips.settings.vblank_rate);
SubscribeTooltip(ui->gb_clockScale, tooltips.settings.clocks_scale);
SubscribeTooltip(ui->gb_wakeupDelay, tooltips.settings.wake_up_delay);
}
std::vector<std::string> loadedLibs = m_emu_settings->GetLibrariesControl();
std::set<std::string_view> set(loadedLibs.begin(), loadedLibs.end());
for (const auto& lib : g_prx_list)
{
// -1: Override LLE
// 1: Override HLE
// 0: No override
const int res = static_cast<int>(set.count(std::string(lib.first) + ":hle") - set.count(std::string(lib.first) + ":lle"));
const auto list = (lib.second ? ui->hleList : ui->lleList);
QListWidgetItem* item = new QListWidgetItem(qsv(lib.first), list);
item->setFlags(item->flags() | Qt::ItemIsUserCheckable); // set checkable flag
// If no override selected (res=0), checkbox is unchecked
// Otherwise if the override does not match the default behaviour, checkbox is checked
item->setCheckState(res && res != (lib.second * 2 - 1) ? Qt::Checked : Qt::Unchecked); // AND initialize check state
item->setToolTip(!lib.second ? tooltips.settings.lib_default_lle :
(lib.first.starts_with("libsysutil") ? tr("Do not touch libsysutil libs, development purposes only, will cause game crashes.") : tooltips.settings.lib_default_hle));
list->addItem(item);
}
SubscribeTooltip(ui->lleList, tooltips.settings.lle_list);
SubscribeTooltip(ui->hleList, tooltips.settings.hle_list);
ui->searchBox->setPlaceholderText(tr("Search libraries", "Library search box"));
const auto on_lib_state_changed = [this](const QString& text)
{
const QString search_term = text.toLower();
std::vector<QListWidgetItem*> items, items2;
// Take current items
while (ui->lleList->count())
{
items.push_back(ui->lleList->takeItem(0));
}
while (ui->hleList->count())
{
items2.push_back(ui->hleList->takeItem(0));
}
// sort items: checked items first then alphabetical order
const auto func = [](QListWidgetItem *i1, QListWidgetItem *i2)
{
return (i1->checkState() != i2->checkState()) ? (i1->checkState() > i2->checkState()) : (i1->text() < i2->text());
};
std::sort(items.begin(), items.end(), func);
std::sort(items2.begin(), items2.end(), func);
for (uint i = 0; i < items.size(); i++)
{
ui->lleList->addItem(items[i]);
// only show items filtered for search text
ui->lleList->setRowHidden(i, !items[i]->text().contains(search_term));
}
for (uint i = 0; i < items2.size(); i++)
{
ui->hleList->addItem(items2[i]);
// only show items filtered for search text
ui->hleList->setRowHidden(i, !items2[i]->text().contains(search_term));
}
};
const auto reset_library_lists = [this, on_lib_state_changed]()
{
for (int i = 0; i < ui->lleList->count(); i++)
{
ui->lleList->item(i)->setCheckState(Qt::Unchecked);
}
for (int i = 0; i < ui->hleList->count(); i++)
{
ui->hleList->item(i)->setCheckState(Qt::Unchecked);
}
on_lib_state_changed(ui->searchBox->text());
};
// Sort libs
on_lib_state_changed({});
// Events
connect(ui->searchBox, &QLineEdit::textChanged, on_lib_state_changed);
connect(ui->resetLleList, &QAbstractButton::clicked, reset_library_lists);
// enable multiselection (there must be a better way)
connect(ui->lleList, &QListWidget::itemChanged, [this](QListWidgetItem* item)
{
for (auto cb : ui->lleList->selectedItems())
{
cb->setCheckState(item->checkState());
}
});
connect(ui->hleList, &QListWidget::itemChanged, [this](QListWidgetItem* item)
{
for (auto cb : ui->hleList->selectedItems())
{
cb->setCheckState(item->checkState());
}
});
connect(this, &settings_dialog::signal_restore_dependant_defaults, this, reset_library_lists);
// ______ _ _ _______ _
// | ____| | | | | |__ __| | |
// | |__ _ __ ___ _ _| | __ _| |_ ___ _ __ | | __ _| |__
// | __| | '_ ` _ \| | | | |/ _` | __/ _ \| '__| | |/ _` | '_ \
// | |____| | | | | | |_| | | (_| | || (_) | | | | (_| | |_) |
// |______|_| |_| |_|\__,_|_|\__,_|\__\___/|_| |_|\__,_|_.__/
// Comboboxes
m_emu_settings->EnhanceComboBox(ui->maxLLVMThreads, emu_settings_type::MaxLLVMThreads, true, true, utils::get_thread_count());
SubscribeTooltip(ui->gb_max_llvm, tooltips.settings.max_llvm_threads);
ui->maxLLVMThreads->setItemText(ui->maxLLVMThreads->findData(0), tr("All (%1)", "Max LLVM threads").arg(utils::get_thread_count()));
m_emu_settings->EnhanceComboBox(ui->perfOverlayDetailLevel, emu_settings_type::PerfOverlayDetailLevel);
SubscribeTooltip(ui->perf_overlay_detail_level, tooltips.settings.perf_overlay_detail_level);
m_emu_settings->EnhanceComboBox(ui->perfOverlayPosition, emu_settings_type::PerfOverlayPosition);
SubscribeTooltip(ui->perf_overlay_position, tooltips.settings.perf_overlay_position);
// Checkboxes
m_emu_settings->EnhanceCheckBox(ui->exitOnStop, emu_settings_type::ExitRPCS3OnFinish);
SubscribeTooltip(ui->exitOnStop, tooltips.settings.exit_on_stop);
m_emu_settings->EnhanceCheckBox(ui->pauseOnFocusLoss, emu_settings_type::PauseOnFocusLoss);
SubscribeTooltip(ui->pauseOnFocusLoss, tooltips.settings.pause_on_focus_loss);
m_emu_settings->EnhanceCheckBox(ui->startGameFullscreen, emu_settings_type::StartGameFullscreen);
SubscribeTooltip(ui->startGameFullscreen, tooltips.settings.start_game_fullscreen);
m_emu_settings->EnhanceCheckBox(ui->preventDisplaySleep, emu_settings_type::PreventDisplaySleep);
SubscribeTooltip(ui->preventDisplaySleep, tooltips.settings.prevent_display_sleep);
ui->preventDisplaySleep->setEnabled(display_sleep_control_supported());
m_emu_settings->EnhanceCheckBox(ui->showTrophyPopups, emu_settings_type::ShowTrophyPopups);
SubscribeTooltip(ui->showTrophyPopups, tooltips.settings.show_trophy_popups);
m_emu_settings->EnhanceCheckBox(ui->showRpcnPopups, emu_settings_type::ShowRpcnPopups);
SubscribeTooltip(ui->showRpcnPopups, tooltips.settings.show_rpcn_popups);
m_emu_settings->EnhanceCheckBox(ui->useNativeInterface, emu_settings_type::UseNativeInterface);
SubscribeTooltip(ui->useNativeInterface, tooltips.settings.use_native_interface);
m_emu_settings->EnhanceCheckBox(ui->showShaderCompilationHint, emu_settings_type::ShowShaderCompilationHint);
SubscribeTooltip(ui->showShaderCompilationHint, tooltips.settings.show_shader_compilation_hint);
m_emu_settings->EnhanceCheckBox(ui->showPPUCompilationHint, emu_settings_type::ShowPPUCompilationHint);
SubscribeTooltip(ui->showPPUCompilationHint, tooltips.settings.show_ppu_compilation_hint);
m_emu_settings->EnhanceCheckBox(ui->showPressureIntensityToggleHint, emu_settings_type::ShowPressureIntensityToggleHint);
SubscribeTooltip(ui->showPressureIntensityToggleHint, tooltips.settings.show_pressure_intensity_toggle_hint);
m_emu_settings->EnhanceCheckBox(ui->showAnalogLimiterToggleHint, emu_settings_type::ShowAnalogLimiterToggleHint);
SubscribeTooltip(ui->showAnalogLimiterToggleHint, tooltips.settings.show_analog_limiter_toggle_hint);
m_emu_settings->EnhanceCheckBox(ui->showMouseAndKeyboardToggleHint, emu_settings_type::ShowMouseAndKeyboardToggleHint);
SubscribeTooltip(ui->showMouseAndKeyboardToggleHint, tooltips.settings.show_mouse_and_keyboard_toggle_hint);
m_emu_settings->EnhanceCheckBox(ui->showAutosaveAutoloadHint, emu_settings_type::ShowAutosaveAutoloadHint);
SubscribeTooltip(ui->showAutosaveAutoloadHint, tooltips.settings.show_autosave_autoload_hint);
m_emu_settings->EnhanceCheckBox(ui->pauseDuringHomeMenu, emu_settings_type::PauseDuringHomeMenu);
SubscribeTooltip(ui->pauseDuringHomeMenu, tooltips.settings.pause_during_home_menu);
m_emu_settings->EnhanceCheckBox(ui->pausedSavestates, emu_settings_type::StartSavestatePaused);
SubscribeTooltip(ui->pausedSavestates, tooltips.settings.paused_savestates);
m_emu_settings->EnhanceCheckBox(ui->perfOverlayCenterX, emu_settings_type::PerfOverlayCenterX);
SubscribeTooltip(ui->perfOverlayCenterX, tooltips.settings.perf_overlay_center_x);
connect(ui->perfOverlayCenterX, &QCheckBox::toggled, [this](bool checked)
{
ui->perfOverlayMarginX->setEnabled(!checked);
});
ui->perfOverlayMarginX->setEnabled(!ui->perfOverlayCenterX->isChecked());
m_emu_settings->EnhanceCheckBox(ui->perfOverlayCenterY, emu_settings_type::PerfOverlayCenterY);
SubscribeTooltip(ui->perfOverlayCenterY, tooltips.settings.perf_overlay_center_y);
connect(ui->perfOverlayCenterY, &QCheckBox::toggled, [this](bool checked)
{
ui->perfOverlayMarginY->setEnabled(!checked);
});
ui->perfOverlayMarginY->setEnabled(!ui->perfOverlayCenterY->isChecked());
m_emu_settings->EnhanceCheckBox(ui->perfOverlayFramerateGraphEnabled, emu_settings_type::PerfOverlayFramerateGraphEnabled);
SubscribeTooltip(ui->perfOverlayFramerateGraphEnabled, tooltips.settings.perf_overlay_framerate_graph_enabled);
m_emu_settings->EnhanceCheckBox(ui->perfOverlayFrametimeGraphEnabled, emu_settings_type::PerfOverlayFrametimeGraphEnabled);
SubscribeTooltip(ui->perfOverlayFrametimeGraphEnabled, tooltips.settings.perf_overlay_frametime_graph_enabled);
m_emu_settings->EnhanceCheckBox(ui->perfOverlayEnabled, emu_settings_type::PerfOverlayEnabled);
SubscribeTooltip(ui->perfOverlayEnabled, tooltips.settings.perf_overlay_enabled);
const auto enable_perf_overlay_options = [this](bool enabled)
{
ui->label_detail_level->setEnabled(enabled);
ui->label_update_interval->setEnabled(enabled);
ui->label_font_size->setEnabled(enabled);
ui->label_position->setEnabled(enabled);
ui->label_opacity->setEnabled(enabled);
ui->label_margin_x->setEnabled(enabled);
ui->label_margin_y->setEnabled(enabled);
ui->perfOverlayDetailLevel->setEnabled(enabled);
ui->perfOverlayPosition->setEnabled(enabled);
ui->perfOverlayUpdateInterval->setEnabled(enabled);
ui->perfOverlayFontSize->setEnabled(enabled);
ui->perfOverlayOpacity->setEnabled(enabled);
ui->perfOverlayMarginX->setEnabled(enabled && !ui->perfOverlayCenterX->isChecked());
ui->perfOverlayMarginY->setEnabled(enabled && !ui->perfOverlayCenterY->isChecked());
ui->perfOverlayCenterX->setEnabled(enabled);
ui->perfOverlayCenterY->setEnabled(enabled);
ui->perfOverlayFramerateGraphEnabled->setEnabled(enabled);
ui->perfOverlayFrametimeGraphEnabled->setEnabled(enabled);
ui->perf_overlay_framerate_datapoints->setEnabled(enabled);
ui->perf_overlay_frametime_datapoints->setEnabled(enabled);
};
enable_perf_overlay_options(ui->perfOverlayEnabled->isChecked());
connect(ui->perfOverlayEnabled, &QCheckBox::toggled, enable_perf_overlay_options);
m_emu_settings->EnhanceCheckBox(ui->shaderLoadBgEnabled, emu_settings_type::ShaderLoadBgEnabled);
SubscribeTooltip(ui->shaderLoadBgEnabled, tooltips.settings.shader_load_bg_enabled);
const auto enable_shader_loader_options = [this](bool enabled)
{
ui->label_shaderLoadBgDarkening->setEnabled(enabled);
ui->label_shaderLoadBgBlur->setEnabled(enabled);
ui->shaderLoadBgDarkening->setEnabled(enabled);
ui->shaderLoadBgBlur->setEnabled(enabled);
};
enable_shader_loader_options(ui->shaderLoadBgEnabled->isChecked());
connect(ui->shaderLoadBgEnabled, &QCheckBox::toggled, enable_shader_loader_options);
// Sliders
EnhanceSlider(emu_settings_type::PerfOverlayUpdateInterval, ui->perfOverlayUpdateInterval, ui->label_update_interval, tr("Update Interval: %0 ms", "Performance overlay update interval"));
SubscribeTooltip(ui->perf_overlay_update_interval, tooltips.settings.perf_overlay_update_interval);
EnhanceSlider(emu_settings_type::PerfOverlayFontSize, ui->perfOverlayFontSize, ui->label_font_size, tr("Font Size: %0 px", "Performance overlay font size"));
SubscribeTooltip(ui->perf_overlay_font_size, tooltips.settings.perf_overlay_font_size);
EnhanceSlider(emu_settings_type::PerfOverlayOpacity, ui->perfOverlayOpacity, ui->label_opacity, tr("Opacity: %0 %", "Performance overlay opacity"));
SubscribeTooltip(ui->perf_overlay_opacity, tooltips.settings.perf_overlay_opacity);
EnhanceSlider(emu_settings_type::PerfOverlayFramerateDatapoints, ui->slider_framerate_datapoints, ui->label_framerate_datapoints, tr("Framerate datapoints: %0", "Framerate graph datapoints"));
SubscribeTooltip(ui->perf_overlay_framerate_datapoints, tooltips.settings.perf_overlay_framerate_datapoints);
EnhanceSlider(emu_settings_type::PerfOverlayFrametimeDatapoints, ui->slider_frametime_datapoints, ui->label_frametime_datapoints, tr("Frametime datapoints: %0", "Frametime graph datapoints"));
SubscribeTooltip(ui->perf_overlay_frametime_datapoints, tooltips.settings.perf_overlay_frametime_datapoints);
EnhanceSlider(emu_settings_type::ShaderLoadBgDarkening, ui->shaderLoadBgDarkening, ui->label_shaderLoadBgDarkening, tr("Background darkening: %0 %", "Shader load background darkening"));
SubscribeTooltip(ui->shaderLoadBgDarkening, tooltips.settings.shader_load_bg_darkening);
EnhanceSlider(emu_settings_type::ShaderLoadBgBlur, ui->shaderLoadBgBlur, ui->label_shaderLoadBgBlur, tr("Background blur: %0 %", "Shader load background blur"));
SubscribeTooltip(ui->shaderLoadBgBlur, tooltips.settings.shader_load_bg_blur);
// SpinBoxes
m_emu_settings->EnhanceSpinBox(ui->perfOverlayMarginX, emu_settings_type::PerfOverlayMarginX, "", tr("px", "Performance overlay margin x"));
SubscribeTooltip(ui->perfOverlayMarginX, tooltips.settings.perf_overlay_margin_x);
m_emu_settings->EnhanceSpinBox(ui->perfOverlayMarginY, emu_settings_type::PerfOverlayMarginY, "", tr("px", "Performance overlay margin y"));
SubscribeTooltip(ui->perfOverlayMarginY, tooltips.settings.perf_overlay_margin_y);
// Global settings (gui_settings)
if (!game)
{
SubscribeTooltip(ui->gs_resizeOnBoot_widget, tooltips.settings.resize_on_boot);
SubscribeTooltip(ui->gs_disableMouse, tooltips.settings.disable_mouse);
SubscribeTooltip(ui->gs_disableKbHotkeys, tooltips.settings.disable_kb_hotkeys);
SubscribeTooltip(ui->gs_showMouseInFullscreen, tooltips.settings.show_mouse_in_fullscreen);
SubscribeTooltip(ui->gs_lockMouseInFullscreen, tooltips.settings.lock_mouse_in_fullscreen);
SubscribeTooltip(ui->gs_hideMouseOnIdle_widget, tooltips.settings.hide_mouse_on_idle);
ui->gs_disableMouse->setChecked(m_gui_settings->GetValue(gui::gs_disableMouse).toBool());
connect(ui->gs_disableMouse, &QCheckBox::toggled, [this](bool checked)
{
m_gui_settings->SetValue(gui::gs_disableMouse, checked);
});
ui->gs_disableKbHotkeys->setChecked(m_gui_settings->GetValue(gui::gs_disableKbHotkeys).toBool());
connect(ui->gs_disableKbHotkeys, &QCheckBox::toggled, [this](bool checked)
{
m_gui_settings->SetValue(gui::gs_disableKbHotkeys, checked);
});
ui->gs_showMouseInFullscreen->setChecked(m_gui_settings->GetValue(gui::gs_showMouseFs).toBool());
connect(ui->gs_showMouseInFullscreen, &QCheckBox::toggled, [this](bool checked)
{
m_gui_settings->SetValue(gui::gs_showMouseFs, checked);
});
ui->gs_lockMouseInFullscreen->setChecked(m_gui_settings->GetValue(gui::gs_lockMouseFs).toBool());
connect(ui->gs_lockMouseInFullscreen, &QCheckBox::toggled, [this](bool checked)
{
m_gui_settings->SetValue(gui::gs_lockMouseFs, checked);
});
ui->gs_hideMouseOnIdle->setChecked(m_gui_settings->GetValue(gui::gs_hideMouseIdle).toBool());
connect(ui->gs_hideMouseOnIdle, &QCheckBox::toggled, [this](bool checked)
{
m_gui_settings->SetValue(gui::gs_hideMouseIdle, checked);
ui->gs_hideMouseOnIdleTime->setEnabled(checked);
});
ui->gs_hideMouseOnIdleTime->setEnabled(ui->gs_hideMouseOnIdle->checkState() == Qt::CheckState::Checked);
ui->gs_hideMouseOnIdleTime->setValue(m_gui_settings->GetValue(gui::gs_hideMouseIdleTime).toUInt());
connect(ui->gs_hideMouseOnIdleTime, &QSpinBox::editingFinished, [this]()
{
m_gui_settings->SetValue(gui::gs_hideMouseIdleTime, ui->gs_hideMouseOnIdleTime->value());
});
const bool enable_buttons = m_gui_settings->GetValue(gui::gs_resize).toBool();
const bool use_manual_resize = m_gui_settings->GetValue(gui::gs_resize_manual).toBool();
ui->gs_resizeOnBoot->setChecked(enable_buttons);
ui->gs_resizeOnBootManual->setChecked(use_manual_resize);
ui->gs_resizeOnBootManual->setEnabled(enable_buttons);
ui->gs_width->setEnabled(enable_buttons && use_manual_resize);
ui->gs_height->setEnabled(enable_buttons && use_manual_resize);
const QRect screen = QGuiApplication::primaryScreen()->geometry();
const int width = m_gui_settings->GetValue(gui::gs_width).toInt();
const int height = m_gui_settings->GetValue(gui::gs_height).toInt();
ui->gs_width->setValue(std::min(width, screen.width()));
ui->gs_height->setValue(std::min(height, screen.height()));
connect(ui->gs_resizeOnBoot, &QCheckBox::toggled, [this](bool checked)
{
const bool enabled = checked && ui->gs_resizeOnBootManual->isChecked();
m_gui_settings->SetValue(gui::gs_resize, checked);
ui->gs_resizeOnBootManual->setEnabled(checked);
ui->gs_width->setEnabled(enabled);
ui->gs_height->setEnabled(enabled);
});
connect(ui->gs_resizeOnBootManual, &QCheckBox::toggled, [this](bool checked)
{
const bool enabled = checked && ui->gs_resizeOnBoot->isChecked();
m_gui_settings->SetValue(gui::gs_resize_manual, checked);
ui->gs_width->setEnabled(enabled);
ui->gs_height->setEnabled(enabled);
});
connect(ui->gs_width, &QSpinBox::editingFinished, [this]()
{
ui->gs_width->setValue(std::min(ui->gs_width->value(), QGuiApplication::primaryScreen()->size().width()));
m_gui_settings->SetValue(gui::gs_width, ui->gs_width->value());
});
connect(ui->gs_height, &QSpinBox::editingFinished, [this]()
{
ui->gs_height->setValue(std::min(ui->gs_height->value(), QGuiApplication::primaryScreen()->size().height()));
m_gui_settings->SetValue(gui::gs_height, ui->gs_height->value());
});
}
else
{
ui->gb_viewport->setEnabled(false);
ui->gb_viewport->setVisible(false);
}
// Game window title builder
const auto get_game_window_title = [this, game](const QString& format)
{
rpcs3::title_format_data title_data;
title_data.format = sstr(format);
title_data.renderer = m_emu_settings->GetSetting(emu_settings_type::Renderer);
title_data.vulkan_adapter = m_emu_settings->GetSetting(emu_settings_type::VulkanAdapter);
title_data.fps = 60.;
if (game)
{
title_data.title = game->name;
title_data.title_id = game->serial;
}
else
{
title_data.title = sstr(tr("My Game", "Game window title"));
title_data.title_id = "ABCD12345";
}
const std::string game_window_title = rpcs3::get_formatted_title(title_data);
if (game_window_title.empty())
{
return QStringLiteral("RPCS3");
}
return qstr(game_window_title);
};
const auto set_game_window_title = [get_game_window_title, this](const std::string& format)
{
const QString game_window_title_format = qstr(format);
const QString game_window_title = get_game_window_title(game_window_title_format);
const int width = ui->label_game_window_title_format->sizeHint().width();
const QFontMetrics metrics = ui->label_game_window_title_format->fontMetrics();
const QString elided_text = metrics.elidedText(game_window_title_format, Qt::ElideRight, width);
const QString tooltip = game_window_title_format + QStringLiteral("\n\n") + game_window_title;
ui->label_game_window_title_format->setText(elided_text);
ui->label_game_window_title_format->setToolTip(tooltip);
};
connect(ui->edit_button_game_window_title_format, &QAbstractButton::clicked, [get_game_window_title, set_game_window_title, this]()
{
auto get_game_window_title_label = [get_game_window_title, set_game_window_title, this](const QString& format)
{
const QString game_window_title = get_game_window_title(format);
const std::vector<std::pair<const QString, const QString>> window_title_glossary =
{
{ "%G", tr("GPU Model", "Game window title") },
{ "%C", tr("CPU Model", "Game window title") },
{ "%c", tr("Thread Count", "Game window title") },
{ "%M", tr("System Memory", "Game window title") },
{ "%F", tr("Framerate", "Game window title") },
{ "%R", tr("Renderer", "Game window title") },
{ "%T", tr("Title", "Game window title") },
{ "%t", tr("Title ID", "Game window title") },
{ "%V", tr("RPCS3 Version", "Game window title") }
};
QString glossary;
for (const auto& entry : window_title_glossary)
{
glossary += entry.first + "\t = " + entry.second + "\n";
}
return tr("Glossary:\n\n%0\nPreview:\n\n%1\n", "Game window title").arg(glossary).arg(game_window_title);
};
const std::string game_title_format = m_emu_settings->GetSetting(emu_settings_type::WindowTitleFormat);
QString edited_format = qstr(game_title_format);
input_dialog dlg(-1, edited_format, tr("Game Window Title Format", "Game window title"), get_game_window_title_label(edited_format), "", this);
dlg.resize(width() * .75, dlg.height());
connect(&dlg, &input_dialog::text_changed, [&edited_format, &dlg, get_game_window_title_label](const QString& text)
{
edited_format = text.simplified();
dlg.set_label_text(get_game_window_title_label(edited_format));
});
if (dlg.exec() == QDialog::Accepted)
{
m_emu_settings->SetSetting(emu_settings_type::WindowTitleFormat, sstr(edited_format));
set_game_window_title(m_emu_settings->GetSetting(emu_settings_type::WindowTitleFormat));
}
});
const auto reset_game_window_title_format = [set_game_window_title, this]()
{
const std::string default_game_title_format = m_emu_settings->GetSettingDefault(emu_settings_type::WindowTitleFormat);
m_emu_settings->SetSetting(emu_settings_type::WindowTitleFormat, default_game_title_format);
set_game_window_title(default_game_title_format);
};
connect(ui->reset_button_game_window_title_format, &QAbstractButton::clicked, this, reset_game_window_title_format);
connect(this, &settings_dialog::signal_restore_dependant_defaults, this, reset_game_window_title_format);
// Load and apply the configured game window title format
set_game_window_title(m_emu_settings->GetSetting(emu_settings_type::WindowTitleFormat));
SubscribeTooltip(ui->gb_game_window_title, tooltips.settings.game_window_title_format);
// _____ _ _ _ _______ _
// / ____|| | | || | |__ __| | |
// | | __|| | | || | | | __ _| |__
// | | |_ || | | || | | |/ _` | '_ \
// | |__| || |__| || | | | (_| | |_) |
// \_____| \____/ |_| |_|\__,_|_.__/
if (!game)
{
SubscribeTooltip(ui->gb_stylesheets, tooltips.settings.stylesheets);
SubscribeTooltip(ui->cb_custom_colors, tooltips.settings.custom_colors);
SubscribeTooltip(ui->cb_show_welcome, tooltips.settings.show_welcome);
SubscribeTooltip(ui->cb_show_exit_game, tooltips.settings.show_exit_game);
SubscribeTooltip(ui->cb_show_boot_game, tooltips.settings.show_boot_game);
SubscribeTooltip(ui->cb_show_pkg_install, tooltips.settings.show_pkg_install);
SubscribeTooltip(ui->cb_show_pup_install, tooltips.settings.show_pup_install);
SubscribeTooltip(ui->cb_show_obsolete_cfg_dialog, tooltips.settings.show_obsolete_cfg);
SubscribeTooltip(ui->cb_show_same_buttons_dialog, tooltips.settings.show_same_buttons);
SubscribeTooltip(ui->cb_show_restart_hint, tooltips.settings.show_restart_hint);
SubscribeTooltip(ui->gb_updates, tooltips.settings.check_update_start);
SubscribeTooltip(ui->gb_uuid, tooltips.settings.uuid);
// Pad navigation
SubscribeTooltip(ui->cb_pad_navigation, tooltips.settings.pad_navigation);
SubscribeTooltip(ui->cb_global_pad_navigation, tooltips.settings.global_navigation);
ui->cb_pad_navigation->setChecked(m_gui_settings->GetValue(gui::nav_enabled).toBool());
ui->cb_global_pad_navigation->setChecked(m_gui_settings->GetValue(gui::nav_global).toBool());
#if defined(_WIN32) || defined(__linux__) || defined(__APPLE__)
connect(ui->cb_pad_navigation, &QCheckBox::toggled, [this](bool checked)
{
m_gui_settings->SetValue(gui::nav_enabled, checked);
});
connect(ui->cb_global_pad_navigation, &QCheckBox::toggled, [this](bool checked)
{
m_gui_settings->SetValue(gui::nav_global, checked);
});
#else
ui->gb_gui_pad_input->setEnabled(false);
#endif
// Discord:
SubscribeTooltip(ui->useRichPresence, tooltips.settings.use_rich_presence);
SubscribeTooltip(ui->discordState, tooltips.settings.discord_state);
ui->useRichPresence->setChecked(m_use_discord);
ui->label_discordState->setEnabled(m_use_discord);
ui->discordState->setEnabled(m_use_discord);
ui->discordState->setText(m_discord_state);
connect(ui->useRichPresence, &QCheckBox::toggled, [this](bool checked)
{
ui->discordState->setEnabled(checked);
ui->label_discordState->setEnabled(checked);
m_use_discord = checked;
});
connect(ui->discordState, &QLineEdit::editingFinished, [this]()
{
m_discord_state = ui->discordState->text();
});
connect(ui->pb_uuid, &QAbstractButton::clicked, [this]()
{
std::string uuid;
if (!gui::utils::create_new_uuid(uuid))
{
QMessageBox::critical(this, tr("Error"), tr("Failed to create new installation ID!"), QMessageBox::Ok);
return;
}
ui->label_uuid->setText(QString::fromStdString(uuid));
gui::utils::log_uuid();
});
ui->label_uuid->setText(QString::fromStdString(gui::utils::load_uuid()));
// Log and TTY:
SubscribeTooltip(ui->log_limit, tooltips.settings.log_limit);
SubscribeTooltip(ui->tty_limit, tooltips.settings.tty_limit);
ui->spinbox_log_limit->setValue(m_gui_settings->GetValue(gui::l_limit).toInt());
connect(ui->spinbox_log_limit, &QSpinBox::editingFinished, [this]()
{
m_gui_settings->SetValue(gui::l_limit, ui->spinbox_log_limit->value());
});
ui->spinbox_tty_limit->setValue(m_gui_settings->GetValue(gui::l_limit_tty).toInt());
connect(ui->spinbox_tty_limit, &QSpinBox::editingFinished, [this]()
{
m_gui_settings->SetValue(gui::l_limit_tty, ui->spinbox_tty_limit->value());
});
// colorize preview icons
const auto add_colored_icon = [this](QPushButton *button, const QColor& color, const QIcon& icon = QIcon(), const QColor& iconColor = QColor())
{
QLabel* text = new QLabel(button->text());
text->setObjectName("color_button");
text->setAlignment(Qt::AlignCenter);
text->setAttribute(Qt::WA_TransparentForMouseEvents, true);
delete button->layout();
if (icon.isNull())
{
QPixmap pixmap(100, 100);
pixmap.fill(color);
button->setIcon(pixmap);
}
else
{
button->setIcon(gui::utils::get_colorized_icon(icon, iconColor, color, true));
}
button->setText("");
button->setStyleSheet(styleSheet().append("text-align:left;"));
button->setLayout(new QGridLayout);
button->layout()->setContentsMargins(0, 0, 0, 0);
button->layout()->addWidget(text);
};
add_colored_icon(ui->pb_gl_icon_color, m_gui_settings->GetValue(gui::gl_iconColor).value<QColor>());
add_colored_icon(ui->pb_sd_icon_color, m_gui_settings->GetValue(gui::sd_icon_color).value<QColor>());
add_colored_icon(ui->pb_tr_icon_color, m_gui_settings->GetValue(gui::tr_icon_color).value<QColor>());
ui->cb_show_welcome->setChecked(m_gui_settings->GetValue(gui::ib_show_welcome).toBool());
ui->cb_show_exit_game->setChecked(m_gui_settings->GetValue(gui::ib_confirm_exit).toBool());
ui->cb_show_boot_game->setChecked(m_gui_settings->GetValue(gui::ib_confirm_boot).toBool());
ui->cb_show_pkg_install->setChecked(m_gui_settings->GetValue(gui::ib_pkg_success).toBool());
ui->cb_show_pup_install->setChecked(m_gui_settings->GetValue(gui::ib_pup_success).toBool());
ui->cb_show_obsolete_cfg_dialog->setChecked(m_gui_settings->GetValue(gui::ib_obsolete_cfg).toBool());
ui->cb_show_same_buttons_dialog->setChecked(m_gui_settings->GetValue(gui::ib_same_buttons).toBool());
ui->cb_show_restart_hint->setChecked(m_gui_settings->GetValue(gui::ib_restart_hint).toBool());
ui->combo_updates->addItem(tr("Yes", "Updates"), gui::update_on);
ui->combo_updates->addItem(tr("Background", "Updates"), gui::update_bkg);
ui->combo_updates->addItem(tr("Automatic", "Updates"), gui::update_auto);
ui->combo_updates->addItem(tr("No", "Updates"), gui::update_off);
ui->combo_updates->setCurrentIndex(ui->combo_updates->findData(m_gui_settings->GetValue(gui::m_check_upd_start).toString()));
connect(ui->combo_updates, QOverload<int>::of(&QComboBox::currentIndexChanged), [this](int index)
{
if (index >= 0) m_gui_settings->SetValue(gui::m_check_upd_start, ui->combo_updates->itemData(index));
});
const bool enable_ui_colors = m_gui_settings->GetValue(gui::m_enableUIColors).toBool();
ui->cb_custom_colors->setChecked(enable_ui_colors);
ui->pb_gl_icon_color->setEnabled(enable_ui_colors);
ui->pb_sd_icon_color->setEnabled(enable_ui_colors);
ui->pb_tr_icon_color->setEnabled(enable_ui_colors);
connect(ui->pb_apply_stylesheet, &QAbstractButton::clicked, this, [this]() { ApplyStylesheet(false); });
connect(ui->cb_show_welcome, &QCheckBox::toggled, [this](bool checked)
{
m_gui_settings->SetValue(gui::ib_show_welcome, checked);
});
connect(ui->cb_show_exit_game, &QCheckBox::toggled, [this](bool checked)
{
m_gui_settings->SetValue(gui::ib_confirm_exit, checked);
});
connect(ui->cb_show_boot_game, &QCheckBox::toggled, [this](bool checked)
{
m_gui_settings->SetValue(gui::ib_confirm_boot, checked);
});
connect(ui->cb_show_pkg_install, &QCheckBox::toggled, [this](bool checked)
{
m_gui_settings->SetValue(gui::ib_pkg_success, checked);
});
connect(ui->cb_show_pup_install, &QCheckBox::toggled, [this](bool checked)
{
m_gui_settings->SetValue(gui::ib_pup_success, checked);
});
connect(ui->cb_show_obsolete_cfg_dialog, &QCheckBox::toggled, [this](bool checked)
{
m_gui_settings->SetValue(gui::ib_obsolete_cfg, checked);
});
connect(ui->cb_show_same_buttons_dialog, &QCheckBox::toggled, [this](bool checked)
{
m_gui_settings->SetValue(gui::ib_same_buttons, checked);
});
connect(ui->cb_show_restart_hint, &QCheckBox::toggled, [this](bool checked)
{
m_gui_settings->SetValue(gui::ib_restart_hint, checked);
});
connect(ui->cb_custom_colors, &QCheckBox::toggled, [this](bool checked)
{
m_gui_settings->SetValue(gui::m_enableUIColors, checked);
ui->pb_gl_icon_color->setEnabled(checked);
ui->pb_sd_icon_color->setEnabled(checked);
ui->pb_tr_icon_color->setEnabled(checked);
Q_EMIT GuiRepaintRequest();
});
const auto color_dialog = [&](const gui_save& color, const QString& title, QPushButton *button)
{
const QColor old_color = m_gui_settings->GetValue(color).value<QColor>();
QColorDialog dlg(old_color, this);
dlg.setWindowTitle(title);
dlg.setOptions(QColorDialog::ShowAlphaChannel);
for (int i = 0; i < QColorDialog::customCount(); i++)
{
QColorDialog::setCustomColor(i, m_gui_settings->GetCustomColor(i));
}
if (dlg.exec() == QColorDialog::Accepted)
{
for (int i = 0; i < QColorDialog::customCount(); i++)
{
m_gui_settings->SetCustomColor(i, QColorDialog::customColor(i));
}
m_gui_settings->SetValue(color, dlg.selectedColor());
button->setIcon(gui::utils::get_colorized_icon(button->icon(), old_color, dlg.selectedColor(), true));
Q_EMIT GuiRepaintRequest();
}
};
connect(ui->pb_gl_icon_color, &QAbstractButton::clicked, [color_dialog, this]()
{
color_dialog(gui::gl_iconColor, tr("Choose gamelist icon color", "Settings: color dialog"), ui->pb_gl_icon_color);
});
connect(ui->pb_sd_icon_color, &QAbstractButton::clicked, [color_dialog, this]()
{
color_dialog(gui::sd_icon_color, tr("Choose save manager icon color", "Settings: color dialog"), ui->pb_sd_icon_color);
});
connect(ui->pb_tr_icon_color, &QAbstractButton::clicked, [color_dialog, this]()
{
color_dialog(gui::tr_icon_color, tr("Choose trophy manager icon color", "Settings: color dialog"), ui->pb_tr_icon_color);
});
AddStylesheets();
}
// _____ _ _______ _
// | __ \ | | |__ __| | |
// | | | | ___| |__ _ _ __ _ | | __ _| |__
// | | | |/ _ \ '_ \| | | |/ _` | | |/ _` | '_ \
// | |__| | __/ |_) | |_| | (_| | | | (_| | |_) |
// |_____/ \___|_.__/ \__,_|\__, | |_|\__,_|_.__/
// __/ |
// |___/
// Checkboxes: gpu debug options
m_emu_settings->EnhanceCheckBox(ui->renderdocCompatibility, emu_settings_type::RenderdocCompatibility);
SubscribeTooltip(ui->renderdocCompatibility, tooltips.settings.renderdoc_compatibility);
m_emu_settings->EnhanceCheckBox(ui->forceHighpZ, emu_settings_type::ForceHighpZ);
SubscribeTooltip(ui->forceHighpZ, tooltips.settings.force_high_pz);
m_emu_settings->EnhanceCheckBox(ui->debugOutput, emu_settings_type::DebugOutput);
SubscribeTooltip(ui->debugOutput, tooltips.settings.debug_output);
m_emu_settings->EnhanceCheckBox(ui->debugOverlay, emu_settings_type::DebugOverlay);
SubscribeTooltip(ui->debugOverlay, tooltips.settings.debug_overlay);
m_emu_settings->EnhanceCheckBox(ui->logProg, emu_settings_type::LogShaderPrograms);
SubscribeTooltip(ui->logProg, tooltips.settings.log_shader_programs);
m_emu_settings->EnhanceCheckBox(ui->disableHwOcclusionQueries, emu_settings_type::DisableOcclusionQueries);
SubscribeTooltip(ui->disableHwOcclusionQueries, tooltips.settings.disable_occlusion_queries);
m_emu_settings->EnhanceCheckBox(ui->disableVideoOutput, emu_settings_type::DisableVideoOutput);
SubscribeTooltip(ui->disableVideoOutput, tooltips.settings.disable_video_output);
m_emu_settings->EnhanceCheckBox(ui->forceCpuBlitEmulation, emu_settings_type::ForceCPUBlitEmulation);
SubscribeTooltip(ui->forceCpuBlitEmulation, tooltips.settings.force_cpu_blit_emulation);
m_emu_settings->EnhanceCheckBox(ui->disableVulkanMemAllocator, emu_settings_type::DisableVulkanMemAllocator);
SubscribeTooltip(ui->disableVulkanMemAllocator, tooltips.settings.disable_vulkan_mem_allocator);
m_emu_settings->EnhanceCheckBox(ui->disableFIFOReordering, emu_settings_type::DisableFIFOReordering);
SubscribeTooltip(ui->disableFIFOReordering, tooltips.settings.disable_fifo_reordering);
m_emu_settings->EnhanceCheckBox(ui->strictTextureFlushing, emu_settings_type::StrictTextureFlushing);
SubscribeTooltip(ui->strictTextureFlushing, tooltips.settings.strict_texture_flushing);
m_emu_settings->EnhanceCheckBox(ui->gpuTextureScaling, emu_settings_type::GPUTextureScaling);
SubscribeTooltip(ui->gpuTextureScaling, tooltips.settings.gpu_texture_scaling);
m_emu_settings->EnhanceCheckBox(ui->allowHostGPULabels, emu_settings_type::AllowHostGPULabels);
SubscribeTooltip(ui->allowHostGPULabels, tooltips.settings.allow_host_labels);
m_emu_settings->EnhanceCheckBox(ui->disableVertexCache, emu_settings_type::DisableVertexCache);
SubscribeTooltip(ui->disableVertexCache, tooltips.settings.disable_vertex_cache);
m_emu_settings->EnhanceCheckBox(ui->forceHwMSAAResolve, emu_settings_type::ForceHwMSAAResolve);
SubscribeTooltip(ui->forceHwMSAAResolve, tooltips.settings.force_hw_MSAA);
// Checkboxes: core debug options
m_emu_settings->EnhanceCheckBox(ui->alwaysStart, emu_settings_type::StartOnBoot);
SubscribeTooltip(ui->alwaysStart, tooltips.settings.start_on_boot);
m_emu_settings->EnhanceCheckBox(ui->ppuDebug, emu_settings_type::PPUDebug);
SubscribeTooltip(ui->ppuDebug, tooltips.settings.ppu_debug);
m_emu_settings->EnhanceCheckBox(ui->spuDebug, emu_settings_type::SPUDebug);
SubscribeTooltip(ui->spuDebug, tooltips.settings.spu_debug);
m_emu_settings->EnhanceCheckBox(ui->mfcDebug, emu_settings_type::MFCDebug);
SubscribeTooltip(ui->mfcDebug, tooltips.settings.mfc_debug);
m_emu_settings->EnhanceCheckBox(ui->setDAZandFTZ, emu_settings_type::SetDAZandFTZ);
SubscribeTooltip(ui->setDAZandFTZ, tooltips.settings.set_daz_and_ftz);
m_emu_settings->EnhanceCheckBox(ui->accuratePPUSAT, emu_settings_type::AccuratePPUSAT);
SubscribeTooltip(ui->accuratePPUSAT, tooltips.settings.accurate_ppusat);
m_emu_settings->EnhanceCheckBox(ui->accuratePPUNJ, emu_settings_type::AccuratePPUNJ);
SubscribeTooltip(ui->accuratePPUNJ, tooltips.settings.accurate_ppunj);
m_emu_settings->EnhanceCheckBox(ui->accuratePPUVNAN, emu_settings_type::AccuratePPUVNAN);
SubscribeTooltip(ui->accuratePPUVNAN, tooltips.settings.accurate_ppuvnan);
m_emu_settings->EnhanceCheckBox(ui->accuratePPUFPCC, emu_settings_type::AccuratePPUFPCC);
SubscribeTooltip(ui->accuratePPUFPCC, tooltips.settings.accurate_ppufpcc);
m_emu_settings->EnhanceCheckBox(ui->accurateClineStores, emu_settings_type::AccurateClineStores);
SubscribeTooltip(ui->accurateClineStores, tooltips.settings.accurate_cache_line_stores);
m_emu_settings->EnhanceCheckBox(ui->hookStFunc, emu_settings_type::HookStaticFuncs);
SubscribeTooltip(ui->hookStFunc, tooltips.settings.hook_static_functions);
m_emu_settings->EnhanceCheckBox(ui->perfReport, emu_settings_type::PerformanceReport);
SubscribeTooltip(ui->perfReport, tooltips.settings.enable_performance_report);
// Checkboxes: IO debug options
m_emu_settings->EnhanceCheckBox(ui->debugOverlayIO, emu_settings_type::IoDebugOverlay);
SubscribeTooltip(ui->debugOverlayIO, tooltips.settings.debug_overlay_io);
// Comboboxes
m_emu_settings->EnhanceComboBox(ui->combo_accurate_ppu_128, emu_settings_type::AccuratePPU128Loop, true);
SubscribeTooltip(ui->gb_accurate_ppu_128, tooltips.settings.accurate_ppu_128_loop);
ui->combo_accurate_ppu_128->setItemText(ui->combo_accurate_ppu_128->findData(-1), tr("Always Enabled", "Accurate PPU 128 Reservations"));
ui->combo_accurate_ppu_128->setItemText(ui->combo_accurate_ppu_128->findData(0), tr("Disabled", "Accurate PPU 128 Reservations"));
m_emu_settings->EnhanceComboBox(ui->combo_num_ppu_threads, emu_settings_type::NumPPUThreads, true);
SubscribeTooltip(ui->gb_num_ppu_threads, tooltips.settings.num_ppu_threads);
if (!restoreGeometry(m_gui_settings->GetValue(gui::cfg_geometry).toByteArray()))
{
// Ignore. This will most likely only fail if the setting doesn't contain any values
}
}
void settings_dialog::refresh_countrybox()
{
const auto& vec_countries = countries::g_countries;
const std::string cur_country = m_emu_settings->GetSetting(emu_settings_type::PSNCountry);
ui->psnCountryBox->clear();
for (const auto& [cnty, code] : vec_countries)
{
ui->psnCountryBox->addItem(QString::fromUtf8(cnty.data(), static_cast<int>(cnty.size())), QString::fromUtf8(code.data(), static_cast<int>(code.size())));
}
ui->psnCountryBox->setCurrentIndex(ui->psnCountryBox->findData(QString::fromStdString(cur_country)));
ui->psnCountryBox->model()->sort(0, Qt::AscendingOrder);
}
void settings_dialog::closeEvent([[maybe_unused]] QCloseEvent* event)
{
m_gui_settings->SetValue(gui::cfg_geometry, saveGeometry());
}
settings_dialog::~settings_dialog()
{
}
void settings_dialog::EnhanceSlider(emu_settings_type settings_type, QSlider* slider, QLabel* label, const QString& label_text) const
{
m_emu_settings->EnhanceSlider(slider, settings_type);
if (slider && label)
{
label->setText(label_text.arg(slider->value()));
connect(slider, &QSlider::valueChanged, [label, label_text](int value)
{
label->setText(label_text.arg(value));
});
}
}
void settings_dialog::SnapSlider(QSlider *slider, int interval)
{
if (!slider)
{
return;
}
// Snap the slider to the next best interval position if the slider is currently modified with the mouse.
connect(slider, &QSlider::valueChanged, [this, slider, interval](int value)
{
if (!slider || slider != m_current_slider)
{
return;
}
slider->setValue(utils::rounded_div(value, interval) * interval);
});
// Register the slider for the event filter which updates m_current_slider if a QSlider was pressed or released with the mouse.
// We can't just use sliderPressed and sliderReleased signals to update m_current_slider because those only trigger if the handle was clicked.
slider->installEventFilter(this);
m_snap_sliders.insert(slider);
}
void settings_dialog::AddStylesheets()
{
ui->combo_stylesheets->clear();
ui->combo_stylesheets->addItem(tr("None", "Stylesheets"), gui::NoStylesheet);
for (const QString& key : QStyleFactory::keys())
{
// Variant value: "native (<style>)"
ui->combo_stylesheets->addItem(tr("Native (%0)", "Stylesheets").arg(key), QString("%0 (%1)").arg(gui::NativeStylesheet, key));
}
ui->combo_stylesheets->addItem(tr("Default (Bright)", "Stylesheets"), gui::DefaultStylesheet);
for (const QString& entry : m_gui_settings->GetStylesheetEntries())
{
if (entry != gui::DefaultStylesheet)
{
ui->combo_stylesheets->addItem(entry, entry);
}
}
m_current_stylesheet = m_gui_settings->GetValue(gui::m_currentStylesheet).toString();
const int index = ui->combo_stylesheets->findData(m_current_stylesheet);
if (index >= 0)
{
ui->combo_stylesheets->setCurrentIndex(index);
}
else
{
cfg_log.warning("Trying to set an invalid stylesheets index: %d (%s)", index, m_current_stylesheet);
}
}
void settings_dialog::ApplyStylesheet(bool reset)
{
if (reset)
{
m_current_stylesheet = gui::DefaultStylesheet;
ui->combo_stylesheets->setCurrentIndex(0);
}
// NOTE: We're deliberately not using currentText() here. The actual stylesheet is stored in user data.
m_current_stylesheet = ui->combo_stylesheets->currentData().toString();
if (m_current_stylesheet != m_gui_settings->GetValue(gui::m_currentStylesheet).toString())
{
m_gui_settings->SetValue(gui::m_currentStylesheet, m_current_stylesheet);
Q_EMIT GuiStylesheetRequest();
}
}
int settings_dialog::exec()
{
// singleShot Hack to fix following bug:
// If we use setCurrentIndex now we will miraculously see a resize of the dialog as soon as we
// switch to the cpu tab after conjuring the settings_dialog with another tab opened first.
// Weirdly enough this won't happen if we change the tab order so that anything else is at index 0.
ui->tab_widget_settings->setCurrentIndex(0);
QTimer::singleShot(0, [this]{ ui->tab_widget_settings->setCurrentIndex(m_tab_index); });
// Open a dialog if your config file contained invalid entries
QTimer::singleShot(10, [this]
{
m_emu_settings->OpenCorrectionDialog(this);
if (!m_emu_settings->ValidateSettings(false))
{
int result = QMessageBox::No;
m_gui_settings->ShowConfirmationBox(
tr("Remove obsolete settings?"),
tr(
"Your config file contains one or more obsolete entries.<br>"
"Consider that a removal might render them invalid for other versions of RPCS3.<br>"
"<br>"
"Do you wish to let the program remove them for you now?<br>"
"This change will only be final when you save the config."
), gui::ib_obsolete_cfg, &result, this);
if (result == QMessageBox::Yes)
{
m_emu_settings->ValidateSettings(true);
}
}
});
return QDialog::exec();
}
void settings_dialog::SubscribeDescription(QLabel* description)
{
description->setFixedHeight(description->sizeHint().height());
m_description_labels.push_back(std::pair<QLabel*, QString>(description, description->text()));
}
void settings_dialog::SubscribeTooltip(QObject* object, const QString& tooltip)
{
m_descriptions[object] = tooltip;
object->installEventFilter(this);
}
// Thanks Dolphin
bool settings_dialog::eventFilter(QObject* object, QEvent* event)
{
if (m_snap_sliders.contains(object))
{
if (event->type() == QEvent::MouseButtonPress)
{
m_current_slider = static_cast<QSlider*>(object);
}
else if (event->type() == QEvent::MouseButtonRelease)
{
m_current_slider = nullptr;
}
}
if (!m_descriptions.contains(object))
{
return QDialog::eventFilter(object, event);
}
if (event->type() == QEvent::Enter || event->type() == QEvent::Leave)
{
const int i = ui->tab_widget_settings->currentIndex();
if (i >= 0 && static_cast<usz>(i) < m_description_labels.size())
{
if (QLabel* label = m_description_labels[i].first)
{
if (event->type() == QEvent::Enter)
{
label->setText(m_descriptions[object]);
}
else if (event->type() == QEvent::Leave)
{
label->setText(m_description_labels[i].second);
}
}
}
}
return QDialog::eventFilter(object, event);
}
| 111,931
|
C++
|
.cpp
| 2,244
| 46.863636
| 214
| 0.726392
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,100
|
skylander_dialog.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/skylander_dialog.cpp
|
#include "stdafx.h"
#include "Utilities/File.h"
#include "Crypto/md5.h"
#include "Crypto/aes.h"
#include "skylander_dialog.h"
#include "Emu/Io/Skylander.h"
#include "util/asm.hpp"
#include <QLabel>
#include <QGroupBox>
#include <QFileDialog>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QComboBox>
#include <QPushButton>
#include <QStringList>
#include <QCompleter>
skylander_dialog* skylander_dialog::inst = nullptr;
std::optional<std::tuple<u8, u16, u16>> skylander_dialog::sky_slots[UI_SKY_NUM];
QString last_skylander_path;
const std::map<const std::pair<const u16, const u16>, const std::string> list_skylanders = {
{{0, 0x0000}, "Whirlwind"},
{{0, 0x1801}, "Series 2 Whirlwind"},
{{0, 0x1C02}, "Polar Whirlwind"},
{{0, 0x2805}, "Horn Blast Whirlwind"},
{{0, 0x3810}, "Eon's Elite Whirlwind"},
{{1, 0x0000}, "Sonic Boom"},
{{1, 0x1801}, "Series 2 Sonic Boom"},
{{2, 0x0000}, "Warnado"},
{{2, 0x2206}, "LightCore Warnado"},
{{3, 0x0000}, "Lightning Rod"},
{{3, 0x1801}, "Series 2 Lightning Rod"},
{{4, 0x0000}, "Bash"},
{{4, 0x1801}, "Series 2 Bash"},
{{5, 0x0000}, "Terrafin"},
{{5, 0x1801}, "Series 2 Terrafin"},
{{5, 0x2805}, "Knockout Terrafin"},
{{5, 0x3810}, "Eon's Elite Terrafin"},
{{6, 0x0000}, "Dino Rang"},
{{6, 0x4810}, "Eon's Elite Dino Rang"},
{{7, 0x0000}, "Prism Break"},
{{7, 0x1801}, "Series 2 Prism Break"},
{{7, 0x2805}, "Hyper Beam Prism Break"},
{{7, 0x1206}, "LightCore Prism Break"},
{{8, 0x0000}, "Sunburn"},
{{9, 0x0000}, "Eruptor"},
{{9, 0x1801}, "Series 2 Eruptor"},
{{9, 0x2C02}, "Volcanic Eruptor"},
{{9, 0x2805}, "Lava Barf Eruptor"},
{{9, 0x1206}, "LightCore Eruptor"},
{{9, 0x3810}, "Eon's Elite Eruptor"},
{{10, 0x0000}, "Ignitor"},
{{10, 0x1801}, "Series 2 Ignitor"},
{{10, 0x1C03}, "Legendary Ignitor"},
{{11, 0x0000}, "Flameslinger"},
{{11, 0x1801}, "Series 2 Flameslinger"},
{{12, 0x0000}, "Zap"},
{{12, 0x1801}, "Series 2 Zap"},
{{13, 0x0000}, "Wham Shell"},
{{13, 0x2206}, "LightCore Wham Shell"},
{{14, 0x0000}, "Gill Grunt"},
{{14, 0x1801}, "Series 2 Gill Grunt"},
{{14, 0x2805}, "Anchors Away Gill Grunt"},
{{14, 0x3805}, "Tidal Wave Gill Grunt"},
{{14, 0x3810}, "Eon's Elite Gill Grunt"},
{{15, 0x0000}, "Slam Bam"},
{{15, 0x1801}, "Series 2 Slam Bam"},
{{15, 0x1C03}, "Legendary Slam Bam"},
{{15, 0x4810}, "Eon's Elite Slam Bam"},
{{16, 0x0000}, "Spyro"},
{{16, 0x1801}, "Series 2 Spyro"},
{{16, 0x2C02}, "Dark Mega Ram Spyro"},
{{16, 0x2805}, "Mega Ram Spyro"},
{{16, 0x3810}, "Eon's Elite Spyro"},
{{17, 0x0000}, "Voodood"},
{{17, 0x4810}, "Eon's Elite Voodood"},
{{18, 0x0000}, "Double Trouble"},
{{18, 0x1801}, "Series 2 Double Trouble"},
{{18, 0x1C02}, "Royal Double Trouble"},
{{19, 0x0000}, "Trigger Happy"},
{{19, 0x1801}, "Series 2 Trigger Happy"},
{{19, 0x2C02}, "Springtime Trigger Happy"},
{{19, 0x2805}, "Big Bang Trigger Happy"},
{{19, 0x3810}, "Eon's Elite Trigger Happy"},
{{20, 0x0000}, "Drobot"},
{{20, 0x1801}, "Series 2 Drobot"},
{{20, 0x1206}, "LightCore Drobot"},
{{21, 0x0000}, "Drill Sergeant"},
{{21, 0x1801}, "Series 2 Drill Sergeant"},
{{22, 0x0000}, "Boomer"},
{{22, 0x4810}, "Eon's Elite Boomer"},
{{23, 0x0000}, "Wrecking Ball"},
{{23, 0x1801}, "Series 2 Wrecking Ball"},
{{24, 0x0000}, "Camo"},
{{24, 0x2805}, "Thorn Horn Camo"},
{{25, 0x0000}, "Zook"},
{{25, 0x1801}, "Series 2 Zook"},
{{25, 0x4810}, "Eon's Elite Zook"},
{{26, 0x0000}, "Stealth Elf"},
{{26, 0x1801}, "Series 2 Stealth Elf"},
{{26, 0x2C02}, "Dark Stealth Elf"},
{{26, 0x1C03}, "Legendary Stealth Elf"},
{{26, 0x2805}, "Ninja Stealth Elf"},
{{26, 0x3810}, "Eon's Elite Stealth Elf"},
{{27, 0x0000}, "Stump Smash"},
{{27, 0x1801}, "Series 2 Stump Smash"},
{{28, 0x0000}, "Dark Spyro"},
{{29, 0x0000}, "Hex"},
{{29, 0x1801}, "Series 2 Hex"},
{{29, 0x1206}, "LightCore Hex"},
{{30, 0x0000}, "Chop Chop"},
{{30, 0x1801}, "Series 2 Chop Chop"},
{{30, 0x2805}, "Twin Blade Chop Chop"},
{{30, 0x3810}, "Eon's Elite Chop Chop"},
{{31, 0x0000}, "Ghost Roaster"},
{{31, 0x4810}, "Eon's Elite Ghost Roaster"},
{{32, 0x0000}, "Cynder"},
{{32, 0x1801}, "Series 2 Cynder"},
{{32, 0x2805}, "Phantom Cynder"},
{{100, 0x0000}, "Jet Vac"},
{{100, 0x1403}, "Legendary Jet Vac"},
{{100, 0x2805}, "Turbo Jet Vac"},
{{100, 0x3805}, "Full Blast Jet Vac"},
{{100, 0x1206}, "LightCore Jet Vac"},
{{101, 0x0000}, "Swarm"},
{{102, 0x0000}, "Crusher"},
{{102, 0x1602}, "Granite Crusher"},
{{103, 0x0000}, "Flashwing"},
{{103, 0x1402}, "Jade Flash Wing"},
{{103, 0x2206}, "LightCore Flashwing"},
{{104, 0x0000}, "Hot Head"},
{{105, 0x0000}, "Hot Dog"},
{{105, 0x1402}, "Molten Hot Dog"},
{{105, 0x2805}, "Fire Bone Hot Dog"},
{{106, 0x0000}, "Chill"},
{{106, 0x1603}, "Legendary Chill"},
{{106, 0x2805}, "Blizzard Chill"},
{{106, 0x1206}, "LightCore Chill"},
{{107, 0x0000}, "Thumpback"},
{{108, 0x0000}, "Pop Fizz"},
{{108, 0x1402}, "Punch Pop Fizz"},
{{108, 0x3C02}, "Love Potion Pop Fizz"},
{{108, 0x2805}, "Super Gulp Pop Fizz"},
{{108, 0x3805}, "Fizzy Frenzy Pop Fizz"},
{{108, 0x1206}, "LightCore Pop Fizz"},
{{109, 0x0000}, "Ninjini"},
{{109, 0x1602}, "Scarlet Ninjini"},
{{110, 0x0000}, "Bouncer"},
{{110, 0x1603}, "Legendary Bouncer"},
{{111, 0x0000}, "Sprocket"},
{{111, 0x2805}, "Heavy Duty Sprocket"},
{{112, 0x0000}, "Tree Rex"},
{{112, 0x1602}, "Gnarly Tree Rex"},
{{113, 0x0000}, "Shroomboom"},
{{113, 0x3805}, "Sure Shot Shroomboom"},
{{113, 0x1206}, "LightCore Shroomboom"},
{{114, 0x0000}, "Eye Brawl"},
{{115, 0x0000}, "Fright Rider"},
{{200, 0x0000}, "Anvil Rain"},
{{201, 0x0000}, "Hidden Treasure"},
{{201, 0x2000}, "Platinum Hidden Treasure"},
{{202, 0x0000}, "Healing Elixir"},
{{203, 0x0000}, "Ghost Pirate Swords"},
{{204, 0x0000}, "Time Twist Hourglass"},
{{205, 0x0000}, "Sky Iron Shield"},
{{206, 0x0000}, "Winged Boots"},
{{207, 0x0000}, "Sparx the Dragonfly"},
{{208, 0x0000}, "Dragonfire Cannon"},
{{208, 0x1602}, "Golden Dragonfire Cannon"},
{{209, 0x0000}, "Scorpion Striker"},
{{210, 0x3002}, "Biter's Bane"},
{{210, 0x3008}, "Sorcerous Skull"},
{{210, 0x300B}, "Axe of Illusion"},
{{210, 0x300E}, "Arcane Hourglass"},
{{210, 0x3012}, "Spell Slapper"},
{{210, 0x3014}, "Rune Rocket"},
{{211, 0x3001}, "Tidal Tiki"},
{{211, 0x3002}, "Wet Walter"},
{{211, 0x3006}, "Flood Flask"},
{{211, 0x3406}, "Legendary Flood Flask"},
{{211, 0x3007}, "Soaking Staff"},
{{211, 0x300B}, "Aqua Axe"},
{{211, 0x3016}, "Frost Helm"},
{{212, 0x3003}, "Breezy Bird"},
{{212, 0x3006}, "Drafty Decanter"},
{{212, 0x300D}, "Tempest Timer"},
{{212, 0x3010}, "Cloudy Cobra"},
{{212, 0x3011}, "Storm Warning"},
{{212, 0x3018}, "Cyclone Saber"},
{{213, 0x3004}, "Spirit Sphere"},
{{213, 0x3404}, "Legendary Spirit Sphere"},
{{213, 0x3008}, "Spectral Skull"},
{{213, 0x3408}, "Legendary Spectral Skull"},
{{213, 0x300B}, "Haunted Hatchet"},
{{213, 0x300C}, "Grim Gripper"},
{{213, 0x3010}, "Spooky Snake"},
{{213, 0x3017}, "Dream Piercer"},
{{214, 0x3000}, "Tech Totem"},
{{214, 0x3007}, "Automatic Angel"},
{{214, 0x3009}, "Factory Flower"},
{{214, 0x300C}, "Grabbing Gadget"},
{{214, 0x3016}, "Makers Mana"},
{{214, 0x301A}, "Topsy Techy"},
{{215, 0x3005}, "Eternal Flame"},
{{215, 0x3009}, "Fire Flower"},
{{215, 0x3011}, "Scorching Stopper"},
{{215, 0x3012}, "Searing Spinner"},
{{215, 0x3017}, "Spark Spear"},
{{215, 0x301B}, "Blazing Belch"},
{{216, 0x3000}, "Banded Boulder"},
{{216, 0x3003}, "Rock Hawk"},
{{216, 0x300A}, "Slag Hammer"},
{{216, 0x300E}, "Dust Of Time"},
{{216, 0x3013}, "Spinning Sandstorm"},
{{216, 0x301A}, "Rubble Trouble"},
{{217, 0x3003}, "Oak Eagle"},
{{217, 0x3005}, "Emerald Energy"},
{{217, 0x300A}, "Weed Whacker"},
{{217, 0x3010}, "Seed Serpent"},
{{217, 0x3018}, "Jade Blade"},
{{217, 0x301B}, "Shrub Shrieker"},
{{218, 0x3000}, "Dark Dagger"},
{{218, 0x3014}, "Shadow Spider"},
{{218, 0x301A}, "Ghastly Grimace"},
{{219, 0x3000}, "Shining Ship"},
{{219, 0x300F}, "Heavenly Hawk"},
{{219, 0x301B}, "Beam Scream"},
{{220, 0x301E}, "Kaos Trap"},
{{220, 0x351F}, "Ultimate Kaos Trap"},
{{230, 0x0000}, "Hand of Fate"},
{{230, 0x3403}, "Legendary Hand of Fate"},
{{231, 0x0000}, "Piggy Bank"},
{{232, 0x0000}, "Rocket Ram"},
{{233, 0x0000}, "Tiki Speaky"},
{{300, 0x0000}, "Dragon’s Peak"},
{{301, 0x0000}, "Empire of Ice"},
{{302, 0x0000}, "Pirate Seas"},
{{303, 0x0000}, "Darklight Crypt"},
{{304, 0x0000}, "Volcanic Vault"},
{{305, 0x0000}, "Mirror of Mystery"},
{{306, 0x0000}, "Nightmare Express"},
{{307, 0x0000}, "Sunscraper Spire"},
{{308, 0x0000}, "Midnight Museum"},
{{404, 0x0000}, "Legendary Bash"},
{{416, 0x0000}, "Legendary Spyro"},
{{419, 0x0000}, "Legendary Trigger Happy"},
{{430, 0x0000}, "Legendary Chop Chop"},
{{450, 0x0000}, "Gusto"},
{{451, 0x0000}, "Thunderbolt"},
{{452, 0x0000}, "Fling Kong"},
{{453, 0x0000}, "Blades"},
{{453, 0x3403}, "Legendary Blades"},
{{454, 0x0000}, "Wallop"},
{{455, 0x0000}, "Head Rush"},
{{455, 0x3402}, "Nitro Head Rush"},
{{456, 0x0000}, "Fist Bump"},
{{457, 0x0000}, "Rocky Roll"},
{{458, 0x0000}, "Wildfire"},
{{458, 0x3402}, "Dark Wildfire"},
{{459, 0x0000}, "Ka Boom"},
{{460, 0x0000}, "Trail Blazer"},
{{461, 0x0000}, "Torch"},
{{462, 0x0000}, "Snap Shot"},
{{462, 0x3402}, "Dark Snap Shot"},
{{463, 0x0000}, "Lob Star"},
{{463, 0x3402}, "Winterfest Lob-Star"},
{{464, 0x0000}, "Flip Wreck"},
{{465, 0x0000}, "Echo"},
{{466, 0x0000}, "Blastermind"},
{{467, 0x0000}, "Enigma"},
{{468, 0x0000}, "Deja Vu"},
{{468, 0x3403}, "Legendary Deja Vu"},
{{469, 0x0000}, "Cobra Candabra"},
{{469, 0x3402}, "King Cobra Cadabra"},
{{470, 0x0000}, "Jawbreaker"},
{{470, 0x3403}, "Legendary Jawbreaker"},
{{471, 0x0000}, "Gearshift"},
{{472, 0x0000}, "Chopper"},
{{473, 0x0000}, "Tread Head"},
{{474, 0x0000}, "Bushwack"},
{{474, 0x3403}, "Legendary Bushwack"},
{{475, 0x0000}, "Tuff Luck"},
{{476, 0x0000}, "Food Fight"},
{{476, 0x3402}, "Dark Food Fight"},
{{477, 0x0000}, "High Five"},
{{478, 0x0000}, "Krypt King"},
{{478, 0x3402}, "Nitro Krypt King"},
{{479, 0x0000}, "Short Cut"},
{{480, 0x0000}, "Bat Spin"},
{{481, 0x0000}, "Funny Bone"},
{{482, 0x0000}, "Knight Light"},
{{483, 0x0000}, "Spotlight"},
{{484, 0x0000}, "Knight Mare"},
{{485, 0x0000}, "Blackout"},
{{502, 0x0000}, "Bop"},
{{505, 0x0000}, "Terrabite"},
{{506, 0x0000}, "Breeze"},
{{508, 0x0000}, "Pet Vac"},
{{508, 0x3402}, "Power Punch Pet Vac"},
{{507, 0x0000}, "Weeruptor"},
{{507, 0x3402}, "Eggcellent Weeruptor"},
{{509, 0x0000}, "Small Fry"},
{{510, 0x0000}, "Drobit"},
{{519, 0x0000}, "Trigger Snappy"},
{{526, 0x0000}, "Whisper Elf"},
{{540, 0x0000}, "Barkley"},
{{540, 0x3402}, "Gnarly Barkley"},
{{541, 0x0000}, "Thumpling"},
{{514, 0x0000}, "Gill Runt"},
{{542, 0x0000}, "Mini-Jini"},
{{503, 0x0000}, "Spry"},
{{504, 0x0000}, "Hijinx"},
{{543, 0x0000}, "Eye Small"},
{{601, 0x0000}, "King Pen"},
{{602, 0x0000}, "Tri-Tip"},
{{603, 0x0000}, "Chopscotch"},
{{604, 0x0000}, "Boom Bloom"},
{{605, 0x0000}, "Pit Boss"},
{{606, 0x0000}, "Barbella"},
{{607, 0x0000}, "Air Strike"},
{{608, 0x0000}, "Ember"},
{{609, 0x0000}, "Ambush"},
{{610, 0x0000}, "Dr. Krankcase"},
{{611, 0x0000}, "Hood Sickle"},
{{612, 0x0000}, "Tae Kwon Crow"},
{{613, 0x0000}, "Golden Queen"},
{{614, 0x0000}, "Wolfgang"},
{{615, 0x0000}, "Pain-Yatta"},
{{616, 0x0000}, "Mysticat"},
{{617, 0x0000}, "Starcast"},
{{618, 0x0000}, "Buckshot"},
{{619, 0x0000}, "Aurora"},
{{620, 0x0000}, "Flare Wolf"},
{{621, 0x0000}, "Chompy Mage"},
{{622, 0x0000}, "Bad Juju"},
{{623, 0x0000}, "Grave Clobber"},
{{624, 0x0000}, "Blaster-Tron"},
{{625, 0x0000}, "Ro-Bow"},
{{626, 0x0000}, "Chain Reaction"},
{{627, 0x0000}, "Kaos"},
{{628, 0x0000}, "Wild Storm"},
{{629, 0x0000}, "Tidepool"},
{{630, 0x0000}, "Crash Bandicoot"},
{{631, 0x0000}, "Dr. Neo Cortex"},
{{1000, 0x0000}, "Boom Jet (Bottom)"},
{{1001, 0x0000}, "Free Ranger (Bottom)"},
{{1001, 0x2403}, "Legendary Free Ranger (Bottom)"},
{{1002, 0x0000}, "Rubble Rouser (Bottom)"},
{{1003, 0x0000}, "Doom Stone (Bottom)"},
{{1004, 0x0000}, "Blast Zone (Bottom)"},
{{1004, 0x2402}, "Dark Blast Zone (Bottom)"},
{{1005, 0x0000}, "Fire Kraken (Bottom)"},
{{1005, 0x2402}, "Jade Fire Kraken (Bottom)"},
{{1006, 0x0000}, "Stink Bomb (Bottom)"},
{{1007, 0x0000}, "Grilla Drilla (Bottom)"},
{{1008, 0x0000}, "Hoot Loop (Bottom)"},
{{1008, 0x2402}, "Enchanted Hoot Loop (Bottom)"},
{{1009, 0x0000}, "Trap Shadow (Bottom)"},
{{1010, 0x0000}, "Magna Charge (Bottom)"},
{{1010, 0x2402}, "Nitro Magna Charge (Bottom)"},
{{1011, 0x0000}, "Spy Rise (Bottom)"},
{{1012, 0x0000}, "Night Shift (Bottom)"},
{{1012, 0x2403}, "Legendary Night Shift (Bottom)"},
{{1013, 0x0000}, "Rattle Shake (Bottom)"},
{{1013, 0x2402}, "Quick Draw Rattle Shake (Bottom)"},
{{1014, 0x0000}, "Freeze Blade (Bottom)"},
{{1014, 0x2402}, "Nitro Freeze Blade (Bottom)"},
{{1015, 0x0000}, "Wash Buckler (Bottom)"},
{{1015, 0x2402}, "Dark Wash Buckler (Bottom)"},
{{2000, 0x0000}, "Boom Jet (Top)"},
{{2001, 0x0000}, "Free Ranger (Top)"},
{{2001, 0x2403}, "Legendary Free Ranger (Top)"},
{{2002, 0x0000}, "Rubble Rouser (Top)"},
{{2003, 0x0000}, "Doom Stone (Top)"},
{{2004, 0x0000}, "Blast Zone (Top)"},
{{2004, 0x2402}, "Dark Blast Zone (Top)"},
{{2005, 0x0000}, "Fire Kraken (Top)"},
{{2005, 0x2402}, "Jade Fire Kraken (Top)"},
{{2006, 0x0000}, "Stink Bomb (Top)"},
{{2007, 0x0000}, "Grilla Drilla (Top)"},
{{2008, 0x0000}, "Hoot Loop (Top)"},
{{2008, 0x2402}, "Enchanted Hoot Loop (Top)"},
{{2009, 0x0000}, "Trap Shadow (Top)"},
{{2010, 0x0000}, "Magna Charge (Top)"},
{{2010, 0x2402}, "Nitro Magna Charge (Top)"},
{{2011, 0x0000}, "Spy Rise (Top)"},
{{2012, 0x0000}, "Night Shift (Top)"},
{{2012, 0x2403}, "Legendary Night Shift (Top)"},
{{2013, 0x0000}, "Rattle Shake (Top)"},
{{2013, 0x2402}, "Quick Draw Rattle Shake (Top)"},
{{2014, 0x0000}, "Freeze Blade (Top)"},
{{2014, 0x2402}, "Nitro Freeze Blade (Top)"},
{{2015, 0x0000}, "Wash Buckler (Top)"},
{{2015, 0x2402}, "Dark Wash Buckler (Top)"},
{{3000, 0x0000}, "Scratch"},
{{3001, 0x0000}, "Pop Thorn"},
{{3002, 0x0000}, "Slobber Tooth"},
{{3002, 0x2402}, "Dark Slobber Tooth"},
{{3003, 0x0000}, "Scorp"},
{{3004, 0x0000}, "Fryno"},
{{3004, 0x3805}, "Hog Wild Fryno"},
{{3005, 0x0000}, "Smolderdash"},
{{3005, 0x2206}, "LightCore Smolderdash"},
{{3006, 0x0000}, "Bumble Blast"},
{{3006, 0x2402}, "Jolly Bumble Blast"},
{{3006, 0x2206}, "LightCore Bumble Blast"},
{{3007, 0x0000}, "Zoo Lou"},
{{3007, 0x2403}, "Legendary Zoo Lou"},
{{3008, 0x0000}, "Dune Bug"},
{{3009, 0x0000}, "Star Strike"},
{{3009, 0x2602}, "Enchanted Star Strike"},
{{3009, 0x2206}, "LightCore Star Strike"},
{{3010, 0x0000}, "Countdown"},
{{3010, 0x2402}, "Kickoff Countdown"},
{{3010, 0x2206}, "LightCore Countdown"},
{{3011, 0x0000}, "Wind Up"},
{{3012, 0x0000}, "Roller Brawl"},
{{3013, 0x0000}, "Grim Creeper"},
{{3013, 0x2603}, "Legendary Grim Creeper"},
{{3013, 0x2206}, "LightCore Grim Creeper"},
{{3014, 0x0000}, "Rip Tide"},
{{3015, 0x0000}, "Punk Shock"},
{{3200, 0x0000}, "Battle Hammer"},
{{3201, 0x0000}, "Sky Diamond"},
{{3202, 0x0000}, "Platinum Sheep"},
{{3203, 0x0000}, "Groove Machine"},
{{3204, 0x0000}, "UFO Hat"},
{{3300, 0x0000}, "Sheep Wreck Island"},
{{3301, 0x0000}, "Tower of Time"},
{{3302, 0x0000}, "Fiery Forge"},
{{3303, 0x0000}, "Arkeyan Crossbow"},
{{3220, 0x0000}, "Jet Stream"},
{{3221, 0x0000}, "Tomb Buggy"},
{{3222, 0x0000}, "Reef Ripper"},
{{3223, 0x0000}, "Burn Cycle"},
{{3224, 0x0000}, "Hot Streak"},
{{3224, 0x4402}, "Dark Hot Streak"},
{{3224, 0x4004}, "E3 Hot Streak"},
{{3224, 0x441E}, "Golden Hot Streak"},
{{3225, 0x0000}, "Shark Tank"},
{{3226, 0x0000}, "Thump Truck"},
{{3227, 0x0000}, "Crypt Crusher"},
{{3228, 0x0000}, "Stealth Stinger"},
{{3228, 0x4402}, "Nitro Stealth Stinger"},
{{3231, 0x0000}, "Dive Bomber"},
{{3231, 0x4402}, "Spring Ahead Dive Bomber"},
{{3232, 0x0000}, "Sky Slicer"},
//{{3233, 0x0000}, "Clown Cruiser (Nintendo Only)"},
//{{3233, 0x4402}, "Dark Clown Cruiser (Nintendo Only)"},
{{3234, 0x0000}, "Gold Rusher"},
{{3234, 0x4402}, "Power Blue Gold Rusher"},
{{3235, 0x0000}, "Shield Striker"},
{{3236, 0x0000}, "Sun Runner"},
{{3236, 0x4403}, "Legendary Sun Runner"},
{{3237, 0x0000}, "Sea Shadow"},
{{3237, 0x4402}, "Dark Sea Shadow"},
{{3238, 0x0000}, "Splatter Splasher"},
{{3238, 0x4402}, "Power Blue Splatter Splasher"},
{{3239, 0x0000}, "Soda Skimmer"},
{{3239, 0x4402}, "Nitro Soda Skimmer"},
//{{3240, 0x0000}, "Barrel Blaster (Nintendo Only)"},
//{{3240, 0x4402}, "Dark Barrel Blaster (Nintendo Only)"},
{{3241, 0x0000}, "Buzz Wing"},
{{3400, 0x0000}, "Fiesta"},
{{3400, 0x4515}, "Frightful Fiesta"},
{{3401, 0x0000}, "High Volt"},
{{3402, 0x0000}, "Splat"},
{{3402, 0x4502}, "Power Blue Splat"},
{{3406, 0x0000}, "Stormblade"},
{{3411, 0x0000}, "Smash Hit"},
{{3411, 0x4502}, "Steel Plated Smash Hit"},
{{3412, 0x0000}, "Spitfire"},
{{3412, 0x4502}, "Dark Spitfire"},
{{3413, 0x0000}, "Hurricane Jet Vac"},
{{3413, 0x4503}, "Legendary Hurricane Jet Vac"},
{{3414, 0x0000}, "Double Dare Trigger Happy"},
{{3414, 0x4502}, "Power Blue Double Dare Trigger Happy"},
{{3415, 0x0000}, "Super Shot Stealth Elf"},
{{3415, 0x4502}, "Dark Super Shot Stealth Elf"},
{{3416, 0x0000}, "Shark Shooter Terrafin"},
{{3417, 0x0000}, "Bone Bash Roller Brawl"},
{{3417, 0x4503}, "Legendary Bone Bash Roller Brawl"},
{{3420, 0x0000}, "Big Bubble Pop Fizz"},
{{3420, 0x450E}, "Birthday Bash Big Bubble Pop Fizz"},
{{3421, 0x0000}, "Lava Lance Eruptor"},
{{3422, 0x0000}, "Deep Dive Gill Grunt"},
//{{3423, 0x0000}, "Turbo Charge Donkey Kong (Nintendo Only)"},
//{{3423, 0x4502}, "Dark Turbo Charge Donkey Kong (Nintendo Only)"},
//{{3424, 0x0000}, "Hammer Slam Bowser (Nintendo Only)"},
//{{3424, 0x4502}, "Dark Hammer Slam Bowser (Nintendo Only)"},
{{3425, 0x0000}, "Dive-Clops"},
{{3425, 0x450E}, "Missile-Tow Dive-Clops"},
{{3426, 0x0000}, "Astroblast"},
{{3426, 0x4503}, "Legendary Astroblast"},
{{3427, 0x0000}, "Nightfall"},
{{3428, 0x0000}, "Thrillipede"},
{{3428, 0x450D}, "Eggcited Thrillipede"},
{{3500, 0x0000}, "Sky Trophy"},
{{3501, 0x0000}, "Land Trophy"},
{{3502, 0x0000}, "Sea Trophy"},
{{3503, 0x0000}, "Kaos Trophy"},
};
u16 skylander_crc16(u16 init_value, const u8* buffer, u32 size)
{
const unsigned short CRC_CCITT_TABLE[256] = {0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, 0x1231, 0x0210, 0x3273,
0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485, 0xA56A, 0xB54B, 0x8528,
0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, 0x48C4, 0x58E5, 0x6886,
0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, 0xDBFD, 0xCBDC, 0xFBBF,
0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A, 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, 0x7E97, 0x6EB6, 0x5ED5,
0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, 0x1080, 0x00A1, 0x30C2,
0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, 0xB5EA, 0xA5CB, 0x95A8,
0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, 0x26D3, 0x36F2, 0x0691,
0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, 0xCB7D, 0xDB5C, 0xEB3F,
0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, 0x7C26, 0x6C07, 0x5C64,
0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0};
u16 crc = init_value;
for (u32 i = 0; i < size; i++)
{
const u16 tmp = (crc >> 8) ^ buffer[i];
crc = (crc << 8) ^ CRC_CCITT_TABLE[tmp];
}
return crc;
}
skylander_creator_dialog::skylander_creator_dialog(QWidget* parent)
: QDialog(parent)
{
setWindowTitle(tr("Skylander Creator"));
setObjectName("skylanders_creator");
setMinimumSize(QSize(500, 150));
QVBoxLayout* vbox_panel = new QVBoxLayout();
QComboBox* combo_skylist = new QComboBox();
QStringList filterlist;
for (const auto& [entry, figure_name] : list_skylanders)
{
const uint qvar = (entry.first << 16) | entry.second;
QString name = QString::fromStdString(figure_name);
combo_skylist->addItem(name, QVariant(qvar));
filterlist << std::move(name);
}
combo_skylist->addItem(tr("--Unknown--"), QVariant(0xFFFFFFFF));
combo_skylist->setEditable(true);
combo_skylist->setInsertPolicy(QComboBox::NoInsert);
combo_skylist->model()->sort(0, Qt::AscendingOrder);
QCompleter* co_compl = new QCompleter(filterlist, this);
co_compl->setCaseSensitivity(Qt::CaseInsensitive);
co_compl->setCompletionMode(QCompleter::PopupCompletion);
co_compl->setFilterMode(Qt::MatchContains);
combo_skylist->setCompleter(co_compl);
vbox_panel->addWidget(combo_skylist);
QFrame* line = new QFrame();
line->setFrameShape(QFrame::HLine);
line->setFrameShadow(QFrame::Sunken);
vbox_panel->addWidget(line);
QHBoxLayout* hbox_idvar = new QHBoxLayout();
QLabel* label_id = new QLabel(tr("ID:"));
QLabel* label_var = new QLabel(tr("Variant:"));
QLineEdit* edit_id = new QLineEdit("0");
QLineEdit* edit_var = new QLineEdit("0");
QRegularExpressionValidator* rxv = new QRegularExpressionValidator(QRegularExpression("\\d*"), this);
edit_id->setValidator(rxv);
edit_var->setValidator(rxv);
hbox_idvar->addWidget(label_id);
hbox_idvar->addWidget(edit_id);
hbox_idvar->addWidget(label_var);
hbox_idvar->addWidget(edit_var);
vbox_panel->addLayout(hbox_idvar);
QHBoxLayout* hbox_buttons = new QHBoxLayout();
QPushButton* btn_create = new QPushButton(tr("Create"), this);
QPushButton* btn_cancel = new QPushButton(tr("Cancel"), this);
hbox_buttons->addStretch();
hbox_buttons->addWidget(btn_create);
hbox_buttons->addWidget(btn_cancel);
vbox_panel->addLayout(hbox_buttons);
setLayout(vbox_panel);
connect(combo_skylist, QOverload<int>::of(&QComboBox::currentIndexChanged), [=](int index)
{
const u32 sky_info = combo_skylist->itemData(index).toUInt();
if (sky_info != 0xFFFFFFFF)
{
const u16 sky_id = sky_info >> 16;
const u16 sky_var = sky_info & 0xFFFF;
edit_id->setText(QString::number(sky_id));
edit_var->setText(QString::number(sky_var));
}
});
connect(btn_create, &QAbstractButton::clicked, this, [=, this]()
{
bool ok_id = false, ok_var = false;
const u16 sky_id = edit_id->text().toUShort(&ok_id);
if (!ok_id)
{
QMessageBox::warning(this, tr("Error converting value"), tr("ID entered is invalid!"), QMessageBox::Ok);
return;
}
const u16 sky_var = edit_var->text().toUShort(&ok_var);
if (!ok_var)
{
QMessageBox::warning(this, tr("Error converting value"), tr("Variant entered is invalid!"), QMessageBox::Ok);
return;
}
QString predef_name = last_skylander_path;
const auto found_sky = list_skylanders.find(std::make_pair(sky_id, sky_var));
if (found_sky != list_skylanders.cend())
{
predef_name += QString::fromStdString(found_sky->second + ".sky");
}
else
{
predef_name += QString("Unknown(%1 %2).sky").arg(sky_id).arg(sky_var);
}
file_path = QFileDialog::getSaveFileName(this, tr("Create Skylander File"), predef_name, tr("Skylander Object (*.sky);;All Files (*)"));
if (file_path.isEmpty())
{
return;
}
fs::file sky_file(file_path.toStdString(), fs::read + fs::write + fs::create);
if (!sky_file)
{
QMessageBox::warning(this, tr("Failed to create skylander file!"), tr("Failed to create skylander file:\n%1").arg(file_path), QMessageBox::Ok);
return;
}
std::array<u8, 0x40 * 0x10> buf{};
const auto data = buf.data();
// Set the block permissions
write_to_ptr<le_t<u32>>(data, 0x36, 0x690F0F0F);
for (u32 index = 1; index < 0x10; index++)
{
write_to_ptr<le_t<u32>>(data, (index * 0x40) + 0x36, 0x69080F7F);
}
// Set the skylander infos
write_to_ptr<le_t<u16>>(data, (sky_id | sky_var) + 1);
write_to_ptr<le_t<u16>>(data, 0x10, sky_id);
write_to_ptr<le_t<u16>>(data, 0x1C, sky_var);
// Set checksum
write_to_ptr<le_t<u16>>(data, 0x1E, skylander_crc16(0xFFFF, data, 0x1E));
sky_file.write(buf.data(), buf.size());
sky_file.close();
last_skylander_path = QFileInfo(file_path).absolutePath() + "/";
accept();
});
connect(btn_cancel, &QAbstractButton::clicked, this, &QDialog::reject);
connect(co_compl, QOverload<const QString&>::of(&QCompleter::activated),[=](const QString& text)
{
combo_skylist->setCurrentText(text);
combo_skylist->setCurrentIndex(combo_skylist->findText(text));
});
}
QString skylander_creator_dialog::get_file_path() const
{
return file_path;
}
skylander_dialog::skylander_dialog(QWidget* parent)
: QDialog(parent)
{
setWindowTitle(tr("Skylanders Manager"));
setObjectName("skylanders_manager");
setAttribute(Qt::WA_DeleteOnClose);
setMinimumSize(QSize(700, 200));
QVBoxLayout* vbox_panel = new QVBoxLayout();
auto add_line = [](QVBoxLayout* vbox)
{
QFrame* line = new QFrame();
line->setFrameShape(QFrame::HLine);
line->setFrameShadow(QFrame::Sunken);
vbox->addWidget(line);
};
QGroupBox* group_skylanders = new QGroupBox(tr("Active Portal Skylanders:"));
QVBoxLayout* vbox_group = new QVBoxLayout();
for (auto i = 0; i < UI_SKY_NUM; i++)
{
if (i != 0)
{
add_line(vbox_group);
}
QHBoxLayout* hbox_skylander = new QHBoxLayout();
QLabel* label_skyname = new QLabel(QString(tr("Skylander %1")).arg(i + 1));
edit_skylanders[i] = new QLineEdit();
edit_skylanders[i]->setEnabled(false);
QPushButton* clear_btn = new QPushButton(tr("Clear"));
QPushButton* create_btn = new QPushButton(tr("Create"));
QPushButton* load_btn = new QPushButton(tr("Load"));
connect(clear_btn, &QAbstractButton::clicked, this, [this, i]() { clear_skylander(i); });
connect(create_btn, &QAbstractButton::clicked, this, [this, i]() { create_skylander(i); });
connect(load_btn, &QAbstractButton::clicked, this, [this, i]() { load_skylander(i); });
hbox_skylander->addWidget(label_skyname);
hbox_skylander->addWidget(edit_skylanders[i]);
hbox_skylander->addWidget(clear_btn);
hbox_skylander->addWidget(create_btn);
hbox_skylander->addWidget(load_btn);
vbox_group->addLayout(hbox_skylander);
}
group_skylanders->setLayout(vbox_group);
vbox_panel->addWidget(group_skylanders);
setLayout(vbox_panel);
update_edits();
}
skylander_dialog::~skylander_dialog()
{
inst = nullptr;
}
skylander_dialog* skylander_dialog::get_dlg(QWidget* parent)
{
if (inst == nullptr)
inst = new skylander_dialog(parent);
return inst;
}
void skylander_dialog::clear_skylander(u8 slot)
{
if (const auto& slot_infos = sky_slots[slot])
{
const auto& [cur_slot, id, var] = slot_infos.value();
g_skyportal.remove_skylander(cur_slot);
sky_slots[slot] = {};
update_edits();
}
}
void skylander_dialog::create_skylander(u8 slot)
{
skylander_creator_dialog create_dlg(this);
if (create_dlg.exec() == Accepted)
{
load_skylander_path(slot, create_dlg.get_file_path());
}
}
void skylander_dialog::load_skylander(u8 slot)
{
const QString file_path = QFileDialog::getOpenFileName(this, tr("Select Skylander File"), last_skylander_path, tr("Skylander (*.sky *.bin *.dmp *.dump);;All Files (*)"));
if (file_path.isEmpty())
{
return;
}
last_skylander_path = QFileInfo(file_path).absolutePath() + "/";
load_skylander_path(slot, file_path);
}
void skylander_dialog::load_skylander_path(u8 slot, const QString& path)
{
fs::file sky_file(path.toStdString(), fs::read + fs::write + fs::lock);
if (!sky_file)
{
QMessageBox::warning(this, tr("Failed to open the skylander file!"), tr("Failed to open the skylander file(%1)!\nFile may already be in use on the portal.").arg(path), QMessageBox::Ok);
return;
}
std::array<u8, 0x40 * 0x10> data;
if (sky_file.read(data.data(), data.size()) != data.size())
{
QMessageBox::warning(this, tr("Failed to read the skylander file!"), tr("Failed to read the skylander file(%1)!\nFile was too small.").arg(path), QMessageBox::Ok);
return;
}
clear_skylander(slot);
u16 sky_id = reinterpret_cast<le_t<u16>&>(data[0x10]);
u16 sky_var = reinterpret_cast<le_t<u16>&>(data[0x1C]);
u8 portal_slot = g_skyportal.load_skylander(data.data(), std::move(sky_file));
sky_slots[slot] = std::tuple(portal_slot, sky_id, sky_var);
update_edits();
}
void skylander_dialog::update_edits()
{
for (auto i = 0; i < UI_SKY_NUM; i++)
{
QString display_string;
if (const auto& sd = sky_slots[i])
{
const auto& [portal_slot, sky_id, sky_var] = sd.value();
const auto found_sky = list_skylanders.find(std::make_pair(sky_id, sky_var));
if (found_sky != list_skylanders.cend())
{
display_string = QString::fromStdString(found_sky->second);
}
else
{
display_string = QString(tr("Unknown (Id:%1 Var:%2)")).arg(sky_id).arg(sky_var);
}
}
else
{
display_string = tr("None");
}
edit_skylanders[i]->setText(display_string);
}
}
| 31,358
|
C++
|
.cpp
| 779
| 36.150193
| 197
| 0.621945
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
5,101
|
camera_settings_dialog.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/camera_settings_dialog.cpp
|
#include "stdafx.h"
#include "camera_settings_dialog.h"
#include "ui_camera_settings_dialog.h"
#include "Emu/Io/camera_config.h"
#include <QCameraDevice>
#include <QMediaDevices>
#include <QMessageBox>
#include <QPushButton>
#if QT_CONFIG(permissions)
#include <QPermissions>
#endif
LOG_CHANNEL(camera_log, "Camera");
template <>
void fmt_class_string<QVideoFrameFormat::PixelFormat>::format(std::string& out, u64 arg)
{
format_enum(out, arg, [](QVideoFrameFormat::PixelFormat value)
{
switch (value)
{
case QVideoFrameFormat::Format_ARGB8888: return "ARGB8888";
case QVideoFrameFormat::Format_ARGB8888_Premultiplied: return "ARGB8888_Premultiplied";
case QVideoFrameFormat::Format_XRGB8888: return "XRGB8888";
case QVideoFrameFormat::Format_BGRA8888: return "BGRA8888";
case QVideoFrameFormat::Format_BGRA8888_Premultiplied: return "BGRA8888_Premultiplied";
case QVideoFrameFormat::Format_BGRX8888: return "BGRX8888";
case QVideoFrameFormat::Format_ABGR8888: return "ABGR8888";
case QVideoFrameFormat::Format_XBGR8888: return "XBGR8888";
case QVideoFrameFormat::Format_RGBA8888: return "RGBA8888";
case QVideoFrameFormat::Format_RGBX8888: return "RGBX8888";
case QVideoFrameFormat::Format_AYUV: return "AYUV";
case QVideoFrameFormat::Format_AYUV_Premultiplied: return "AYUV_Premultiplied";
case QVideoFrameFormat::Format_YUV420P: return "YUV420P";
case QVideoFrameFormat::Format_YUV422P: return "YUV422P";
case QVideoFrameFormat::Format_YV12: return "YV12";
case QVideoFrameFormat::Format_UYVY: return "UYVY";
case QVideoFrameFormat::Format_YUYV: return "YUYV";
case QVideoFrameFormat::Format_NV12: return "NV12";
case QVideoFrameFormat::Format_NV21: return "NV21";
case QVideoFrameFormat::Format_IMC1: return "IMC1";
case QVideoFrameFormat::Format_IMC2: return "IMC2";
case QVideoFrameFormat::Format_IMC3: return "IMC3";
case QVideoFrameFormat::Format_IMC4: return "IMC4";
case QVideoFrameFormat::Format_Y8: return "Y8";
case QVideoFrameFormat::Format_Y16: return "Y16";
case QVideoFrameFormat::Format_P010: return "P010";
case QVideoFrameFormat::Format_P016: return "P016";
case QVideoFrameFormat::Format_SamplerExternalOES: return "SamplerExternalOES";
case QVideoFrameFormat::Format_Jpeg: return "Jpeg";
case QVideoFrameFormat::Format_SamplerRect: return "SamplerRect";
default: return unknown;
}
});
}
Q_DECLARE_METATYPE(QCameraDevice);
camera_settings_dialog::camera_settings_dialog(QWidget* parent)
: QDialog(parent)
, ui(new Ui::camera_settings_dialog)
{
ui->setupUi(this);
load_config();
for (const QCameraDevice& camera_info : QMediaDevices::videoInputs())
{
if (camera_info.isNull()) continue;
ui->combo_camera->addItem(camera_info.description(), QVariant::fromValue(camera_info));
camera_log.notice("Found camera: '%s'", camera_info.description());
}
connect(ui->combo_camera, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &camera_settings_dialog::handle_camera_change);
connect(ui->combo_settings, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &camera_settings_dialog::handle_settings_change);
connect(ui->buttonBox, &QDialogButtonBox::clicked, [this](QAbstractButton* button)
{
if (button == ui->buttonBox->button(QDialogButtonBox::Save))
{
save_config();
accept();
}
else if (button == ui->buttonBox->button(QDialogButtonBox::Apply))
{
save_config();
}
});
if (ui->combo_camera->count() == 0)
{
ui->combo_camera->setEnabled(false);
ui->combo_settings->setEnabled(false);
ui->buttonBox->button(QDialogButtonBox::Save)->setEnabled(false);
ui->buttonBox->button(QDialogButtonBox::Apply)->setEnabled(false);
}
else
{
// TODO: show camera ID somewhere
ui->combo_camera->setCurrentIndex(0);
}
}
camera_settings_dialog::~camera_settings_dialog()
{
}
void camera_settings_dialog::handle_camera_change(int index)
{
if (index < 0 || !ui->combo_camera->itemData(index).canConvert<QCameraDevice>())
{
ui->combo_settings->clear();
return;
}
const QCameraDevice camera_info = ui->combo_camera->itemData(index).value<QCameraDevice>();
if (camera_info.isNull())
{
ui->combo_settings->clear();
return;
}
m_camera.reset(new QCamera(camera_info));
m_media_capture_session.reset(new QMediaCaptureSession(nullptr));
m_media_capture_session->setCamera(m_camera.get());
m_media_capture_session->setVideoSink(ui->videoWidget->videoSink());
if (!m_camera->isAvailable())
{
ui->combo_settings->clear();
QMessageBox::warning(this, tr("Camera not available"), tr("The selected camera is not available.\nIt might be blocked by another application."));
return;
}
ui->combo_settings->blockSignals(true);
ui->combo_settings->clear();
QList<QCameraFormat> settings = camera_info.videoFormats();
std::sort(settings.begin(), settings.end(), [](const QCameraFormat& l, const QCameraFormat& r) -> bool
{
if (l.resolution().width() > r.resolution().width()) return true;
if (l.resolution().width() < r.resolution().width()) return false;
if (l.resolution().height() > r.resolution().height()) return true;
if (l.resolution().height() < r.resolution().height()) return false;
if (l.minFrameRate() > r.minFrameRate()) return true;
if (l.minFrameRate() < r.minFrameRate()) return false;
if (l.maxFrameRate() > r.maxFrameRate()) return true;
if (l.maxFrameRate() < r.maxFrameRate()) return false;
if (l.pixelFormat() > r.pixelFormat()) return true;
if (l.pixelFormat() < r.pixelFormat()) return false;
return false;
});
for (const QCameraFormat& setting : settings)
{
if (setting.isNull()) continue;
const QString description = tr("%0x%1, %2-%3 FPS, Format=%4")
.arg(setting.resolution().width())
.arg(setting.resolution().height())
.arg(setting.minFrameRate())
.arg(setting.maxFrameRate())
.arg(QString::fromStdString(fmt::format("%s", setting.pixelFormat())));
ui->combo_settings->addItem(description, QVariant::fromValue(setting));
}
ui->combo_settings->blockSignals(false);
if (ui->combo_settings->count() == 0)
{
ui->combo_settings->setEnabled(false);
}
else
{
// Load selected settings from config file
int index = 0;
bool success = false;
const std::string key = camera_info.id().toStdString();
cfg_camera::camera_setting cfg_setting = g_cfg_camera.get_camera_setting(key, success);
if (success)
{
camera_log.notice("Found config entry for camera \"%s\"", key);
// Select matching drowdown entry
const double epsilon = 0.001;
for (int i = 0; i < ui->combo_settings->count(); i++)
{
const QCameraFormat tmp = ui->combo_settings->itemData(i).value<QCameraFormat>();
if (tmp.resolution().width() == cfg_setting.width &&
tmp.resolution().height() == cfg_setting.height &&
tmp.minFrameRate() >= (cfg_setting.min_fps - epsilon) &&
tmp.minFrameRate() <= (cfg_setting.min_fps + epsilon) &&
tmp.maxFrameRate() >= (cfg_setting.max_fps - epsilon) &&
tmp.maxFrameRate() <= (cfg_setting.max_fps + epsilon) &&
tmp.pixelFormat() == static_cast<QVideoFrameFormat::PixelFormat>(cfg_setting.format))
{
index = i;
break;
}
}
}
ui->combo_settings->setCurrentIndex(std::max<int>(0, index));
ui->combo_settings->setEnabled(true);
// Update config to match user interface outcome
const QCameraFormat setting = ui->combo_settings->currentData().value<QCameraFormat>();
cfg_setting.width = setting.resolution().width();
cfg_setting.height = setting.resolution().height();
cfg_setting.min_fps = setting.minFrameRate();
cfg_setting.max_fps = setting.maxFrameRate();
cfg_setting.format = static_cast<int>(setting.pixelFormat());
g_cfg_camera.set_camera_setting(key, cfg_setting);
}
}
void camera_settings_dialog::handle_settings_change(int index)
{
if (!m_camera)
{
return;
}
if (!m_camera->isAvailable())
{
QMessageBox::warning(this, tr("Camera not available"), tr("The selected camera is not available.\nIt might be blocked by another application."));
return;
}
#if QT_CONFIG(permissions)
const QCameraPermission permission;
switch (qApp->checkPermission(permission))
{
case Qt::PermissionStatus::Undetermined:
camera_log.notice("Requesting camera permission");
qApp->requestPermission(permission, this, [this, index]()
{
handle_settings_change(index);
});
return;
case Qt::PermissionStatus::Denied:
camera_log.error("RPCS3 has no permissions to access cameras on this device.");
QMessageBox::warning(this, tr("Camera permissions denied!"), tr("RPCS3 has no permissions to access cameras on this device."));
return;
case Qt::PermissionStatus::Granted:
camera_log.notice("Camera permission granted");
break;
}
#endif
if (index >= 0 && ui->combo_settings->itemData(index).canConvert<QCameraFormat>() && ui->combo_camera->currentData().canConvert<QCameraDevice>())
{
const QCameraFormat setting = ui->combo_settings->itemData(index).value<QCameraFormat>();
if (!setting.isNull())
{
m_camera->setCameraFormat(setting);
}
cfg_camera::camera_setting cfg_setting;
cfg_setting.width = setting.resolution().width();
cfg_setting.height = setting.resolution().height();
cfg_setting.min_fps = setting.minFrameRate();
cfg_setting.max_fps = setting.maxFrameRate();
cfg_setting.format = static_cast<int>(setting.pixelFormat());
g_cfg_camera.set_camera_setting(ui->combo_camera->currentData().value<QCameraDevice>().id().toStdString(), cfg_setting);
}
m_camera->start();
}
void camera_settings_dialog::load_config()
{
if (!g_cfg_camera.load())
{
camera_log.notice("Could not load camera config. Using defaults.");
}
}
void camera_settings_dialog::save_config()
{
g_cfg_camera.save();
}
| 9,689
|
C++
|
.cpp
| 251
| 35.856574
| 147
| 0.735751
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,102
|
game_list_grid.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/game_list_grid.cpp
|
#include "stdafx.h"
#include "game_list_grid.h"
#include "game_list_grid_item.h"
#include "movie_item.h"
#include "gui_settings.h"
#include "qt_utils.h"
#include "Utilities/File.h"
#include <QApplication>
#include <QStringBuilder>
game_list_grid::game_list_grid()
: flow_widget(nullptr), game_list_base()
{
setObjectName("game_list_grid");
setContextMenuPolicy(Qt::CustomContextMenu);
m_icon_ready_callback = [this](const game_info& game)
{
Q_EMIT IconReady(game);
};
connect(this, &game_list_grid::IconReady, this, [this](const game_info& game)
{
if (!game || !game->item) return;
game->item->call_icon_func();
}, Qt::QueuedConnection); // The default 'AutoConnection' doesn't seem to work in this specific case...
connect(this, &flow_widget::ItemSelectionChanged, this, [this](int index)
{
if (game_list_grid_item* item = static_cast<game_list_grid_item*>(::at32(items(), index)))
{
Q_EMIT ItemSelectionChanged(item->game());
}
});
}
void game_list_grid::clear_list()
{
clear();
}
void game_list_grid::populate(
const std::vector<game_info>& game_data,
const std::map<QString, QString>& notes_map,
const std::map<QString, QString>& title_map,
const std::string& selected_item_id,
bool play_hover_movies)
{
clear_list();
const QString game_icon_path = play_hover_movies ? QString::fromStdString(fs::get_config_dir() + "/Icons/game_icons/") : "";
game_list_grid_item* selected_item = nullptr;
blockSignals(true);
const auto get_title = [&title_map](const QString& serial, const std::string& name) -> QString
{
if (const auto it = title_map.find(serial); it != title_map.cend())
{
return it->second.simplified();
}
return QString::fromStdString(name).simplified();
};
for (const auto& game : game_data)
{
const QString serial = QString::fromStdString(game->info.serial);
const QString title = get_title(serial, game->info.name);
game_list_grid_item* item = new game_list_grid_item(this, game, title);
item->installEventFilter(this);
item->setFocusPolicy(Qt::StrongFocus);
game->item = item;
if (const auto it = notes_map.find(serial); it != notes_map.cend() && !it->second.isEmpty())
{
item->setToolTip(tr("%0 [%1]\n\nNotes:\n%2").arg(title).arg(serial).arg(it->second));
}
else
{
item->setToolTip(tr("%0 [%1]").arg(title).arg(serial));
}
item->set_icon_func([this, item, game](const QVideoFrame& frame)
{
if (!item || !game)
{
return;
}
if (const QPixmap pixmap = item->get_movie_image(frame); item->get_active() && !pixmap.isNull())
{
item->set_icon(gui::utils::get_centered_pixmap(pixmap, m_icon_size, 0, 0, 1.0, Qt::FastTransformation));
}
else
{
std::lock_guard lock(item->pixmap_mutex);
item->set_icon(game->pxmap);
if (!game->has_hover_gif && !game->has_hover_pam)
{
game->pxmap = {};
}
item->stop_movie();
}
});
if (play_hover_movies && game->has_hover_gif)
{
item->set_movie_path(game_icon_path % serial % "/hover.gif");
}
else if (play_hover_movies && game->has_hover_pam)
{
item->set_movie_path(QString::fromStdString(game->info.movie_path));
}
if (selected_item_id == game->info.path + game->info.icon_path)
{
selected_item = item;
}
add_widget(item);
}
blockSignals(false);
// Update layout before setting focus on the selected item
show();
QApplication::processEvents();
select_item(selected_item);
}
void game_list_grid::repaint_icons(std::vector<game_info>& game_data, const QColor& icon_color, const QSize& icon_size, qreal device_pixel_ratio)
{
m_icon_size = icon_size;
m_icon_color = icon_color;
QPixmap placeholder(icon_size * device_pixel_ratio);
placeholder.setDevicePixelRatio(device_pixel_ratio);
placeholder.fill(Qt::transparent);
const bool show_title = m_icon_size.width() > (gui::gl_icon_size_medium.width() + gui::gl_icon_size_small.width()) / 2;
for (game_info& game : game_data)
{
if (game_list_grid_item* item = static_cast<game_list_grid_item*>(game->item))
{
if (item->icon_loading())
{
// We already have an icon. Simply set the icon size to let the label scale itself in a quick and dirty fashion.
item->set_icon_size(m_icon_size);
}
else
{
// We don't have an icon. Set a placeholder to initialize the layout.
game->pxmap = placeholder;
item->call_icon_func();
}
item->set_icon_load_func([this, game, device_pixel_ratio, cancel = item->icon_loading_aborted()](int)
{
IconLoadFunction(game, device_pixel_ratio, cancel);
});
item->adjust_size();
item->show_title(show_title);
item->got_visible = false;
}
}
}
void game_list_grid::FocusAndSelectFirstEntryIfNoneIs()
{
if (!items().empty())
{
items().front()->setFocus();
}
}
bool game_list_grid::eventFilter(QObject* watched, QEvent* event)
{
if (!event)
{
return false;
}
if (event->type() == QEvent::MouseButtonDblClick && static_cast<QMouseEvent*>(event)->button() == Qt::LeftButton)
{
if (game_list_grid_item* item = static_cast<game_list_grid_item*>(watched))
{
Q_EMIT ItemDoubleClicked(item->game());
return true;
}
}
return false;
}
void game_list_grid::keyPressEvent(QKeyEvent* event)
{
if (!event)
{
return;
}
const auto modifiers = event->modifiers();
if (modifiers == Qt::ControlModifier && event->key() == Qt::Key_F && !event->isAutoRepeat())
{
Q_EMIT FocusToSearchBar();
return;
}
flow_widget::keyPressEvent(event);
}
| 5,458
|
C++
|
.cpp
| 181
| 27.254144
| 145
| 0.687357
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,103
|
config_adapter.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/config_adapter.cpp
|
#include "config_adapter.h"
#include "Emu/system_config.h"
LOG_CHANNEL(cfg_log, "CFG");
// Helper methods to interact with YAML and the config settings.
namespace cfg_adapter
{
static cfg::_base& get_cfg(cfg::_base& root, const std::string& name)
{
if (root.get_type() == cfg::type::node)
{
for (const auto& node : static_cast<cfg::node&>(root).get_nodes())
{
if (node->get_name() == name)
{
return *node;
}
}
}
fmt::throw_exception("Node not found: %s", name);
}
static cfg::_base& get_cfg(cfg::_base& root, const cfg_location::const_iterator begin, const cfg_location::const_iterator end)
{
return begin == end ? root : get_cfg(get_cfg(root, *begin), begin + 1, end);
}
YAML::Node get_node(const YAML::Node& node, const cfg_location::const_iterator begin, const cfg_location::const_iterator end)
{
if (begin == end)
{
return node;
}
if (!node || !node.IsMap())
{
cfg_log.fatal("Node error. A cfg_location does not match its cfg::node (location: %s)", get_yaml_node_location(node));
return YAML::Node();
}
return get_node(node[*begin], begin + 1, end); // TODO
}
YAML::Node get_node(const YAML::Node& node, const cfg_location& location)
{
return get_node(node, location.cbegin(), location.cend());
}
std::vector<std::string> get_options(const cfg_location& location)
{
return cfg_adapter::get_cfg(g_cfg, location.cbegin(), location.cend()).to_list();
}
static bool get_is_dynamic(const cfg_location& location)
{
return cfg_adapter::get_cfg(g_cfg, location.cbegin(), location.cend()).get_is_dynamic();
}
bool get_is_dynamic(emu_settings_type type)
{
return get_is_dynamic(::at32(settings_location, type));
}
std::string get_setting_name(emu_settings_type type)
{
const cfg_location& loc = ::at32(settings_location, type);
return ::at32(loc, loc.size() - 1);
}
}
| 1,869
|
C++
|
.cpp
| 59
| 28.864407
| 127
| 0.681313
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,104
|
game_list_grid_item.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/game_list_grid_item.cpp
|
#include "game_list_grid_item.h"
#include <QVBoxLayout>
#include <QStyle>
game_list_grid_item::game_list_grid_item(QWidget* parent, game_info game, const QString& title)
: flow_widget_item(parent), movie_item_base(), m_game(std::move(game))
{
setObjectName("game_list_grid_item");
setAttribute(Qt::WA_Hover); // We need to enable the hover attribute to ensure that hover events are handled.
cb_on_first_visibility = [this]()
{
if (!icon_loading())
{
call_icon_load_func(0);
}
};
m_icon_label = new QLabel(this);
m_icon_label->setObjectName("game_list_grid_item_icon_label");
m_icon_label->setAttribute(Qt::WA_TranslucentBackground);
m_icon_label->setScaledContents(true);
m_title_label = new QLabel(title, this);
m_title_label->setObjectName("game_list_grid_item_title_label");
m_title_label->setAlignment(Qt::AlignVCenter | Qt::AlignHCenter);
m_title_label->setWordWrap(true);
m_title_label->setVisible(false);
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(m_icon_label, 1);
layout->addWidget(m_title_label, 0);
setLayout(layout);
}
void game_list_grid_item::set_icon_size(const QSize& size)
{
m_icon_size = size;
}
void game_list_grid_item::set_icon(const QPixmap& pixmap)
{
m_icon_size = pixmap.size() / devicePixelRatioF();
m_icon_label->setPixmap(pixmap);
}
void game_list_grid_item::adjust_size()
{
m_icon_label->setMinimumSize(m_icon_size);
m_icon_label->setMaximumSize(m_icon_size);
m_title_label->setMaximumWidth(m_icon_size.width());
}
void game_list_grid_item::show_title(bool visible)
{
if (m_title_label)
{
m_title_label->setVisible(visible);
}
}
void game_list_grid_item::polish_style()
{
flow_widget_item::polish_style();
m_title_label->style()->unpolish(m_title_label);
m_title_label->style()->polish(m_title_label);
}
bool game_list_grid_item::event(QEvent* event)
{
switch (event->type())
{
case QEvent::HoverEnter:
set_active(true);
break;
case QEvent::HoverLeave:
set_active(false);
break;
default:
break;
}
return flow_widget_item::event(event);
}
| 2,060
|
C++
|
.cpp
| 72
| 26.583333
| 110
| 0.736949
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,105
|
config_checker.cpp
|
RPCS3_rpcs3/rpcs3/rpcs3qt/config_checker.cpp
|
#include "stdafx.h"
#include "config_checker.h"
#include "Emu/system_config.h"
#include <QDialog>
#include <QDialogButtonBox>
#include <QMessageBox>
#include <QTextEdit>
#include <QVBoxLayout>
#include <QLabel>
LOG_CHANNEL(gui_log, "GUI");
config_checker::config_checker(QWidget* parent, const QString& content, bool is_log) : QDialog(parent)
{
setObjectName("config_checker");
setAttribute(Qt::WA_DeleteOnClose);
QVBoxLayout* layout = new QVBoxLayout();
QLabel* label = new QLabel(this);
layout->addWidget(label);
QString result;
if (check_config(content, result, is_log))
{
setWindowTitle(tr("Interesting!"));
if (result.isEmpty())
{
label->setText(tr("Found config.\nIt seems to match the default config."));
}
else
{
label->setText(tr("Found config.\nSome settings seem to deviate from the default config:"));
QTextEdit* text_box = new QTextEdit();
text_box->setReadOnly(true);
text_box->setHtml(result);
layout->addWidget(text_box);
resize(400, 600);
}
}
else
{
setWindowTitle(tr("Ooops!"));
label->setText(result);
}
QDialogButtonBox* box = new QDialogButtonBox(QDialogButtonBox::Close);
connect(box, &QDialogButtonBox::rejected, this, &QDialog::reject);
layout->addWidget(box);
setLayout(layout);
}
bool config_checker::check_config(QString content, QString& result, bool is_log)
{
cfg_root config{};
if (is_log)
{
const QString start_token = "SYS: Used configuration:\n";
const QString end_token = "\n·";
qsizetype start = content.indexOf(start_token);
qsizetype end = -1;
if (start >= 0)
{
start += start_token.size();
end = content.indexOf(end_token, start);
}
if (end < 0)
{
result = tr("Cannot find any config!");
return false;
}
content = content.mid(start, end - start);
}
if (!config.from_string(content.toStdString()))
{
gui_log.error("log_viewer: Failed to parse config:\n%s", content);
result = tr("Cannot find any config!");
return false;
}
std::function<void(const cfg::_base*, std::string&, int)> print_diff_recursive;
print_diff_recursive = [&print_diff_recursive](const cfg::_base* base, std::string& diff, int indentation) -> void
{
if (!base)
{
return;
}
const auto indent = [](std::string& str, int indentation)
{
for (int i = 0; i < indentation * 2; i++)
{
str += " ";
}
};
switch (base->get_type())
{
case cfg::type::node:
{
if (const auto& node = static_cast<const cfg::node*>(base))
{
std::string diff_tmp;
for (const auto& n : node->get_nodes())
{
print_diff_recursive(n, diff_tmp, indentation + 1);
}
if (!diff_tmp.empty())
{
indent(diff, indentation);
if (!base->get_name().empty())
{
fmt::append(diff, "<b>%s:</b><br>", base->get_name());
}
fmt::append(diff, "%s", diff_tmp);
}
}
break;
}
case cfg::type::_bool:
case cfg::type::_enum:
case cfg::type::_int:
case cfg::type::uint:
case cfg::type::string:
{
const std::string val = base->to_string();
const std::string def = base->def_to_string();
if (val != def)
{
indent(diff, indentation);
if (def.empty())
{
fmt::append(diff, "%s: <span style=\"color:red;\">%s</span><br>", base->get_name(), val);
}
else
{
fmt::append(diff, "%s: <span style=\"color:red;\">%s</span> <span style=\"color:gray;\">default:</span> <span style=\"color:green;\">%s</span><br>", base->get_name(), val, def);
}
}
break;
}
case cfg::type::set:
{
if (const auto& node = static_cast<const cfg::set_entry*>(base))
{
const std::vector<std::string> set_entries = node->to_list();
if (!set_entries.empty())
{
indent(diff, indentation);
fmt::append(diff, "<b>%s:</b><br>", base->get_name());
for (const std::string& entry : set_entries)
{
indent(diff, indentation + 1);
fmt::append(diff, "- <span style=\"color:red;\">%s</span><br>", entry);
}
}
}
break;
}
case cfg::type::log:
{
if (const auto& node = static_cast<const cfg::log_entry*>(base))
{
const auto& log_entries = node->get_map();
if (!log_entries.empty())
{
indent(diff, indentation);
fmt::append(diff, "<b>%s:</b><br>", base->get_name());
for (const auto& entry : log_entries)
{
indent(diff, indentation + 1);
fmt::append(diff, "<span style=\"color:red;\">%s: %s</span><br>", entry.first, entry.second);
}
}
}
break;
}
case cfg::type::map:
case cfg::type::device:
{
// Ignored
break;
}
}
};
std::string diff;
print_diff_recursive(&config, diff, 0);
result = QString::fromStdString(diff);
return true;
}
| 4,708
|
C++
|
.cpp
| 180
| 22.461111
| 182
| 0.631591
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.