Revamp: Transition HarmonyLink to C++ with DLL support

This transformative commit marks the evolution of HarmonyLink from a Rust-based server-side application to a C++ implemented, C-compatible dynamic link library (DLL). We've restructured the codebase to streamline integration into games, eliminating the need for a server setup by end-users.

Key Changes:
- Introduced .gitattributes and .gitmodules to manage new dependencies and collaborations.
- Replaced the GitHub workflow files with CMake configurations to support the new C++ build system.
- Introduced a comprehensive set of header and implementation files defining the core functionality, platform-specific utilities, and cross-platform compatibility layers.
- Removed all Rust-specific files (Cargo.toml, Cargo.lock, etc.) and references to ensure a clean transition to the C++ environment.
- Implemented new testing mechanisms within HarmonyLinkTest to ensure robustness and reliability of the DLL.
- Excised previous server-side components and models to focus on the DLL's direct integration into consumer applications.

This update is a direct response to community feedback, showcasing our commitment to adaptability and innovation. HarmonyLink 2.0 is now more accessible, efficient, and tailored for diverse gaming environments, providing developers with an unparalleled level of hardware-software harmony.

Please refer to the updated README for more details on the new structure and how to integrate HarmonyLink 2.0 into your projects.
This commit is contained in:
Jordon Brooks 2024-01-07 20:29:47 +00:00
parent d13fc728df
commit 6bf68eb298
No known key found for this signature in database
GPG key ID: 83964894E5D98D57
60 changed files with 1629 additions and 2389 deletions

39
.gitattributes vendored Normal file
View file

@ -0,0 +1,39 @@
* text=auto
# Sources
*.c text diff=cpp
*.cc text diff=cpp
*.cxx text diff=cpp
*.cpp text diff=cpp
*.cpi text diff=cpp
*.c++ text diff=cpp
*.hpp text diff=cpp
*.h text diff=cpp
*.h++ text diff=cpp
*.hh text diff=cpp
# Compiled Object files
*.slo binary
*.lo binary
*.o binary
*.obj binary
# Precompiled Headers
*.gch binary
*.pch binary
# Compiled Dynamic libraries
*.so binary
*.dylib binary
*.dll binary
# Compiled Static libraries
*.lai binary
*.la binary
*.a binary
*.lib binary
# Executables
*.exe binary
*.out binary
*.app binary

View file

@ -1,59 +0,0 @@
# .github/workflows/release.yml
on:
push:
tags:
- 'release*'
jobs:
release:
name: release ${{ matrix.target }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
include:
- target: x86_64-pc-windows-gnu
archive: zip
- target: x86_64-unknown-linux-musl
archive: tar.gz
steps:
- uses: actions/checkout@master
with:
ssh-key: "${{secrets.RELEASE_KEY}}"
- uses: Swatinem/rust-cache@v2
with:
# The prefix cache key, this can be changed to start a new cache manually.
# default: "v0-rust"
prefix-key: ""
# A cache key that is used instead of the automatic `job`-based key,
# and is stable over multiple jobs.
# default: empty
shared-key: ""
# An additional cache key that is added alongside the automatic `job`-based
# cache key and can be used to further differentiate jobs.
# default: empty
key: ""
# A whitespace separated list of env-var *prefixes* who's value contributes
# to the environment cache key.
# The env-vars are matched by *prefix*, so the default `RUST` var will
# match all of `RUSTC`, `RUSTUP_*`, `RUSTFLAGS`, `RUSTDOC_*`, etc.
# default: "CARGO CC CFLAGS CXX CMAKE RUST"
env-vars: ""
# The cargo workspaces and target directory configuration.
# These entries are separated by newlines and have the form
# `$workspace -> $target`. The `$target` part is treated as a directory
# relative to the `$workspace` and defaults to "target" if not explicitly given.
# default: ". -> target"
workspaces: ". -> target"
- name: Compile and release
uses: rust-build/rust-build.action@v1.4.3
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
RUSTTARGET: ${{ matrix.target }}
ARCHIVE_TYPES: ${{ matrix.archive }}

View file

@ -1,51 +0,0 @@
name: Rust
on:
push:
branches: [ "stable" ]
pull_request:
branches: [ "stable" ]
env:
CARGO_TERM_COLOR: always
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: Swatinem/rust-cache@v2
with:
# The prefix cache key, this can be changed to start a new cache manually.
# default: "v0-rust"
prefix-key: ""
# A cache key that is used instead of the automatic `job`-based key,
# and is stable over multiple jobs.
# default: empty
shared-key: ""
# An additional cache key that is added alongside the automatic `job`-based
# cache key and can be used to further differentiate jobs.
# default: empty
key: ""
# A whitespace separated list of env-var *prefixes* who's value contributes
# to the environment cache key.
# The env-vars are matched by *prefix*, so the default `RUST` var will
# match all of `RUSTC`, `RUSTUP_*`, `RUSTFLAGS`, `RUSTDOC_*`, etc.
# default: "CARGO CC CFLAGS CXX CMAKE RUST"
env-vars: ""
# The cargo workspaces and target directory configuration.
# These entries are separated by newlines and have the form
# `$workspace -> $target`. The `$target` part is treated as a directory
# relative to the `$workspace` and defaults to "target" if not explicitly given.
# default: ". -> target"
workspaces: ". -> target"
- name: Build
run: cargo build --verbose
- name: Run tests
run: cargo test --verbose

24
.gitignore vendored
View file

@ -1,14 +1,18 @@
# Setup .gitignore as a whitelist
* *
!*/ !*/
build/**
# track this file
!.gitignore !.gitignore
!src/** !.gitattributes
!res/HarmonyLinkLogo.ico !.gitmodules
!Resources/**
!Images/** !CMakeLists.txt
!.github/** !license
!Build.rs !readme.md
!Cargo.toml
!Cargo.lock !HarmonyLinkLib/**
!LICENSE !HarmonyLinkTest/**
!README.md !tests/**

0
.gitmodules vendored Normal file
View file

70
CMakeLists.txt Normal file
View file

@ -0,0 +1,70 @@
cmake_minimum_required(VERSION 3.10)
project(HarmonyLinkProject)
# Check the build type and display a message accordingly
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
message(STATUS "Building for Debug")
elseif(CMAKE_BUILD_TYPE STREQUAL "Release")
message(STATUS "Building for Release")
elseif(CMAKE_BUILD_TYPE STREQUAL "MinSizeRel")
message(STATUS "Building for MinSizeRel")
elseif(CMAKE_BUILD_TYPE STREQUAL "RelWithDebInfo")
message(STATUS "Building for RelWithDebInfo")
else()
message(STATUS "Building with unspecified build type")
endif()
#set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
# Platform-specific definitions
if(WIN32)
add_definitions(-DBUILD_WINDOWS)
elseif(UNIX)
if(APPLE)
add_definitions(-DBUILD_MACOS)
else()
add_definitions(-DBUILD_LINUX)
endif()
add_definitions(-DBUILD_UNIX)
endif()
# Set global output directories for all build types
foreach(TYPE IN ITEMS DEBUG RELEASE)
string(TOUPPER ${TYPE} TYPE_UPPER)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_${TYPE_UPPER} "${CMAKE_BINARY_DIR}/bin/${TYPE}")
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_${TYPE_UPPER} "${CMAKE_BINARY_DIR}/lib/${TYPE}")
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_${TYPE_UPPER} "${CMAKE_BINARY_DIR}/archive/${TYPE}")
endforeach()
# Add the library and executable directories
add_subdirectory(HarmonyLinkLib)
add_subdirectory(HarmonyLinkTest)
# Add Google Test as a subdirectory
#add_subdirectory(ThirdParty/googletest)
# Enable testing
#enable_testing()
# Include Google Test's include directory
#include_directories(ThirdParty/googletest/googletest/include)
# Define your test executable
#file(GLOB_RECURSE TEST_SOURCES "tests/*.cpp")
#add_executable(Testing ${TEST_SOURCES})
# Set HarmonyLinkTest as the default startup project
set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT HarmonyLinkTest)
# Link Google Test and HarmonyLink library to the test executable
#target_link_libraries(Testing gtest gtest_main gmock HarmonyLinkLib)
#add_custom_command(TARGET Testing POST_BUILD
# COMMAND ${CMAKE_COMMAND} -E copy_if_different
# "$<TARGET_FILE:HarmonyLinkLib>"
# "$<TARGET_FILE_DIR:Testing>")
# Discover tests
#include(GoogleTest)
#gtest_discover_tests(Testing)

1589
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,42 +0,0 @@
[package]
name = "harmony_link_server"
version = "0.2.0"
edition = "2021"
authors = ["Jordon jordon@jordongamedev.co.uk"]
homepage = "https://jordongamedev.co.uk"
repository = "https://github.com/Jordonbc/HarmonyLinkServer"
license = "GPL-3.0-or-later"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[profile.release]
panic = "abort" # Strip expensive panic clean-up logic
codegen-units = 1 # Compile crates one after another so the compiler can optimize better
lto = true # Enables link to optimizations
opt-level = "z" # Optimize for binary size
strip = true # Remove debug symbols
[package.metadata.winres]
LegalCopyright = "Copyright © 2023 Jordon Brooks"
ProductName = "HarmonyLink: Server"
FileDescription = "Optimized games for your handheld!"
[[bin]]
name = "harmony_link_server"
path = "src/main.rs"
[build-dependencies]
vergen = { version = "8.2.1", features = ["build", "cargo", "git", "gitcl", "rustc", "si"] }
winres = "0.1.12"
[dependencies]
actix-web = "4.3.1"
env_logger = "0.10.0"
log = "0.4.18"
serde = {version = "1.0.163", features = ["derive"]}
serde_json = "1.0.96"
sysinfo = "0.29.0"
os_info = "3.0"
battery = "0.7.8"
lazy_static = "1.4.0"
rusb = "0.9.2"

View file

@ -0,0 +1,129 @@
cmake_minimum_required(VERSION 3.10)
project(HarmonyLinkLib VERSION 2.0.0)
# Find the current Git branch and the last commit timestamp
find_package(Git QUIET)
if(GIT_FOUND)
execute_process(
COMMAND ${GIT_EXECUTABLE} rev-parse --abbrev-ref HEAD
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE GIT_BRANCH_NAME
OUTPUT_STRIP_TRAILING_WHITESPACE
)
execute_process(
COMMAND ${GIT_EXECUTABLE} log -1 --format=%ct
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE GIT_COMMIT_TIMESTAMP
OUTPUT_STRIP_TRAILING_WHITESPACE
)
else()
set(GIT_BRANCH_NAME "Unknown")
set(GIT_COMMIT_TIMESTAMP "Unknown")
endif()
configure_file(include/Version.h.in Version.generated.h)
# Specify the C++ standard
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED True)
# Explicitly list source files
set(COMMON_SOURCES
"src/Platform/IPlatformUtilities.cpp"
"src/HarmonyLinkLib.cpp"
"src/Version.cpp"
"src/dllmain.cpp"
"src/Platform/WineUtilities.cpp"
)
# Explicitly list include files
set(COMMON_INCLUDES
"include/Core.h"
"include/Structs/FBattery.h"
"include/Structs/FOSVerInfo.h"
"include/Structs/FDevice.h"
"include/Structs/FCPUInfo.h"
"include/Enums/EDevice.h"
"include/Enums/EPlatform.h"
"include/FString.h"
"include/HarmonyLinkLib.h"
"include/Version.h"
"src/Platform/IPlatformUtilities.h"
"src/Platform/WineUtilities.h"
)
set(WINDOWS_SOURCES
"src/Platform/Windows/WindowsUtilities.cpp"
)
set(WINDOWS_INCLUDES
"src/Platform/Windows/WindowsUtilities.h"
)
set(LINUX_SOURCES
"src/Platform/Unix/Linux/LinuxUtilities.cpp"
"src/Platform/Unix/UnixUtilities.cpp"
)
set(LINUX_INCLUDES
"src/Platform/Unix/Linux/LinuxUtilities.h"
"src/Platform/Unix/UnixUtilities.h"
)
set(MAC_SOURCES
"src/Platform/Unix/Mac/MacUtilities.cpp"
"src/Platform/Unix/UnixUtilities.cpp"
)
set(MAC_INCLUDES
"src/Platform/Unix/Mac/MacUtilities.h"
"src/Platform/Unix/UnixUtilities.h"
)
# Platform-specific definitions
if(WIN32)
message(STATUS "Compiling for Windows...")
list(APPEND LIB_SOURCES ${COMMON_SOURCES} ${WINDOWS_SOURCES})
list(APPEND LIB_INCLUDES ${COMMON_INCLUDES} ${WINDOWS_INCLUDES})
elseif(UNIX)
message(STATUS "Compiling for Unix-based systems...")
if(APPLE)
message(STATUS "Compiling for Mac...")
list(APPEND LIB_SOURCES ${COMMON_SOURCES} ${MAC_SOURCES})
list(APPEND LIB_INCLUDES ${COMMON_INCLUDES} ${MAC_INCLUDES})
else()
message(STATUS "Compiling for Linux...")
list(APPEND LIB_SOURCES ${COMMON_SOURCES} ${LINUX_SOURCES})
list(APPEND LIB_INCLUDES ${COMMON_INCLUDES} ${LINUX_INCLUDES})
endif()
endif()
# Add library
add_library(HarmonyLinkLib SHARED ${LIB_SOURCES} ${LIB_INCLUDES})
target_include_directories(HarmonyLinkLib
PRIVATE
"${PROJECT_SOURCE_DIR}/src"
PUBLIC
"${PROJECT_BINARY_DIR}"
"${PROJECT_SOURCE_DIR}/include"
)
target_compile_definitions(HarmonyLinkLib PRIVATE HARMONYLINKLIB_EXPORTS)
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
target_compile_definitions(HarmonyLinkLib PRIVATE "DEBUG_MODE")
endif()
# Set output directories for all build types
foreach(TYPE IN ITEMS DEBUG RELEASE)
string(TOUPPER ${TYPE} TYPE_UPPER)
set_target_properties(${PROJECT_NAME} PROPERTIES
RUNTIME_OUTPUT_DIRECTORY_${TYPE_UPPER} "${CMAKE_BINARY_DIR}/bin/${TYPE}/${PROJECT_NAME}"
LIBRARY_OUTPUT_DIRECTORY_${TYPE_UPPER} "${CMAKE_BINARY_DIR}/lib/${TYPE}/${PROJECT_NAME}"
ARCHIVE_OUTPUT_DIRECTORY_${TYPE_UPPER} "${CMAKE_BINARY_DIR}/archive/${TYPE}/${PROJECT_NAME}"
)
endforeach()

View file

@ -0,0 +1,14 @@
// Copyright (C) 2023 Jordon Brooks
#pragma once
// Use a preprocessor definition to switch between export and import declarations
#ifdef _WIN32
#ifdef HARMONYLINKLIB_EXPORTS
#define HARMONYLINKLIB_API __declspec(dllexport)
#else
#define HARMONYLINKLIB_API __declspec(dllimport)
#endif
#else
#define HARMONYLINKLIB_API
#endif

View file

@ -0,0 +1,19 @@
#pragma once
#include <cstdint>
// Enum class for representing different types of devices
namespace HarmonyLinkLib
{
enum class EDevice : uint8_t
{
DESKTOP,
LAPTOP,
HANDHELD,
STEAM_DECK,
// ROG_ALLY
// AYONEO_SLIDE
// etc...
};
}

View file

@ -0,0 +1,15 @@
#pragma once
#include <cstdint>
// Enum class for representing different operating platforms
namespace HarmonyLinkLib
{
enum class EPlatform : uint8_t
{
WINDOWS,
LINUX,
MAC,
UNIX,
};
}

View file

@ -0,0 +1,165 @@
// Copyright (C) 2024 Jordon Brooks
#pragma once
#include <memory>
#include <cstring>
#include <string>
#include "Core.h" // Replace with actual API export macro
/**
* @file FString.h
* @brief FString Class - Custom String Management for DLL Export
*
* The FString class is a custom string management class designed to safely encapsulate
* string handling and memory management, especially for use in DLLs (Dynamic Link Libraries).
* It resolves the common issue of exporting classes containing standard library types,
* such as std::string, across DLL boundaries, which can lead to compiler warnings or errors.
*
* Features:
* - Implements basic string operations such as construction, destruction, copy, and move semantics.
* - Utilizes smart pointers (std::unique_ptr) for automatic memory management, reducing the risk of memory leaks.
* - Provides a simple interface for interacting with character strings, similar to std::string.
* - Includes both deep copy semantics for safety and move semantics for performance in object transfers.
*
* Usage:
* FString can be used as a safer alternative to std::string for classes that are exported from a DLL.
* It handles memory allocation/deallocation automatically and provides a basic set of string operations.
*
* Example:
* FString myString("Hello, world!");
* std::cout << myString.c_str() << std::endl; // Output: Hello, world!
*
* Note:
* - The class is currently designed with basic functionality. Additional features such as
* string concatenation, substring, and comparison operations can be added as needed.
* - Ensure that the HarmonyLinkLibApi.h (or equivalent) file correctly defines the export macro
* for DLL usage.
*
*/
namespace HarmonyLinkLib
{
class HARMONYLINKLIB_API FString {
public:
FString() : data_(new char[1]) {
data_[0] = '\0';
}
FString(const char* str) {
const size_t len = strlen(str);
data_ = new char[len + 1];
memcpy(data_, str, len + 1);
}
// Copy constructor
FString(const FString& other) {
const size_t len = strlen(other.data_);
data_ = new char[len + 1];
memcpy(data_, other.data_, len + 1);
}
~FString() {
delete[] data_;
}
// Copy assignment operator
FString& operator=(const FString& other) {
if (this != &other) {
delete[] data_;
const size_t len = strlen(other.data_);
data_ = new char[len + 1];
memcpy(data_, other.data_, len + 1);
}
return *this;
}
// Concatenation operator for FString objects
FString operator+(const FString& other) const {
size_t thisLen = strlen(this->data_);
size_t otherLen = strlen(other.data_);
char* concatenated = new char[thisLen + otherLen + 1];
memcpy(concatenated, this->data_, thisLen);
memcpy(concatenated + thisLen, other.data_, otherLen + 1);
FString result(concatenated);
delete[] concatenated;
return result;
}
// Concatenation operator for const char*
FString operator+(const char* other) const {
return *this + FString(other);
}
// Friend function to allow concatenation with const char* on the left-hand side
friend FString operator+(const char* lhs, const FString& rhs) {
return FString(lhs) + rhs;
}
// Move constructor
FString(FString&& other) noexcept : data_(other.data_) {
other.data_ = nullptr;
}
FString(const std::string& str) {
const size_t len = str.length();
data_ = new char[len + 1];
memcpy(data_, str.c_str(), len + 1);
}
// Move assignment operator
FString& operator=(FString&& other) noexcept {
if (this != &other) {
delete[] data_;
data_ = other.data_;
other.data_ = nullptr;
}
return *this;
}
bool operator==(const FString& other) const {
return strcmp(data_, other.data_) == 0;
}
// Method to get a lowercase version of the string
static FString to_lower(FString& from)
{
for (size_t i = 0; i < strlen(from.data_); ++i) {
from.data_[i] = static_cast<char>(std::tolower(static_cast<unsigned char>(from.data_[i])));
}
return from;
}
// Overloaded static method to handle const char*
static FString to_lower(const char* from) {
FString temp_string(from); // Create an FString from const char*
return to_lower(temp_string); // Reuse the existing to_lower method
}
const char* c_str() const {
return data_;
}
private:
char* data_ = nullptr;
};
}
namespace std {
template<>
struct hash<HarmonyLinkLib::FString> {
size_t operator()(const HarmonyLinkLib::FString& s) const {
size_t hashValue = 5381; // Starting value recommended by the djb2 algorithm
const char* str = s.c_str();
for (size_t i = 0; str[i] != '\0'; ++i) {
hashValue = ((hashValue << 5) + hashValue) + static_cast<unsigned char>(str[i]);
// Equivalent to hashValue * 33 + str[i]
}
return hashValue;
}
};
}

View file

@ -0,0 +1,44 @@
// Copyright (C) 2023 Jordon Brooks
/**
* IMPORTANT REMINDER:
* Do NOT use standard output functions like std::cout and printf anywhere in this codebase.
*
* Reason:
* Unreal Engine 5's packaging tool encounters issues with these functions, leading to
* packaging failures. The engine sets stdout to UTF-8, which can cause conflicts with
* these standard functions, resulting in a "SECURE CRT: Invalid parameter detected" error
* during packaging.
*
* This issue once required an extensive debugging effort that lasted over 8 hours.
* To prevent similar issues in the future and ensure smooth packaging, always use
* wide-character versions of these functions, such as wprintf and std::wcout, when working
* within the DLL. These functions are compatible with the UTF-8 setting in Unreal Engine 5.
*
*/
#pragma once
#include "Core.h"
#include "Structs/FBattery.h"
#include "Structs/FCPUInfo.h"
#include "Structs/FDevice.h"
#include "Structs/FOSVerInfo.h"
class IPlatformUtilities;
namespace HarmonyLinkLib
{
extern "C" HARMONYLINKLIB_API bool get_is_wine();
extern "C" HARMONYLINKLIB_API FCPUInfo* get_cpu_info();
extern "C" HARMONYLINKLIB_API FDevice* get_device_info();
extern "C" HARMONYLINKLIB_API FOSVerInfo* get_os_version();
extern "C" HARMONYLINKLIB_API FBattery* get_battery_status();
}

View file

@ -0,0 +1,13 @@
#pragma once
struct HarmonyLinkStruct
{
// Virtual destructor is important for proper cleanup of derived types
virtual ~HarmonyLinkStruct() = default;
// Method to deallocate the object
void free() const
{
delete this;
}
};

View file

@ -0,0 +1,22 @@
#pragma once
#include <cstdint>
#include <iostream>
#include "HarmonyLinkStruct.h"
namespace HarmonyLinkLib
{
struct FBattery : HarmonyLinkStruct
{
bool has_battery;
bool is_connected_to_ac;
uint8_t battery_percent;
void to_string() const {
std::wcout << "Battery present: " << (has_battery ? "'Yes'" : "'No'") << '\n';
std::wcout << "Connected to AC: " << (is_connected_to_ac ? "'Yes'" : "'No'") << '\n';
std::wcout << "Battery percent: '" << static_cast<int>(battery_percent) << "%'" << '\n';
}
};
}

View file

@ -0,0 +1,40 @@
#pragma once
#include <cstdint>
#include <unordered_set>
#include "FString.h"
#include "HarmonyLinkStruct.h"
namespace HarmonyLinkLib
{
struct FCPUInfo : HarmonyLinkStruct
{
FString VendorID;
FString Model_Name;
uint32_t Physical_Cores = 0;
uint32_t Logical_Cores = 0;
std::unordered_set<FString> Flags;
void print() const
{
wprintf(L"VendorID: '%hs'\n", VendorID.c_str());
wprintf(L"Model_Name: '%hs'\n", Model_Name.c_str());
wprintf(L"Physical_Cores: '%d'\n", Physical_Cores);
wprintf(L"Logical_Cores: '%d'\n", Logical_Cores);
// Initialize a string to hold all flags
std::string allFlags;
for (const auto& flag : Flags) {
allFlags += std::string(flag.c_str()) + " "; // Append each flag followed by a space
}
// Remove the trailing space
if (!allFlags.empty()) {
allFlags.pop_back();
}
wprintf(L"Flags: '%hs'\n", allFlags.c_str());
}
};
}

View file

@ -0,0 +1,16 @@
#pragma once
#include <HarmonyLinkStruct.h>
#include "Enums/EDevice.h"
#include "Enums/EPlatform.h"
namespace HarmonyLinkLib
{
// Struct to represent a specific device with both platform and device type
struct FDevice : HarmonyLinkStruct
{
EPlatform platform;
EDevice device;
};
}

View file

@ -0,0 +1,50 @@
#pragma once
#include "FString.h"
#include "HarmonyLinkStruct.h"
namespace HarmonyLinkLib
{
struct FOSVerInfo : HarmonyLinkStruct {
// 'name' represents the operating system's name, e.g., "Ubuntu" in Linux or "Windows" in Windows systems.
FString name;
// 'version' is a numerical representation of the OS version. In Linux, it might be the kernel version,
// whereas in Windows, it could be the major version number like 10 for Windows 10.
uint32_t version = 0;
// 'id' is a unique identifier for the OS. In Linux, it might be a lower-case string like "ubuntu".
// In Windows, this could map to the edition ID, such as "Professional".
FString id;
// 'version_id' is a string representing the specific version of the OS.
// For example, "20.04" in Ubuntu or "1909" in Windows 10.
FString version_id;
// 'version_codename' is a codename for the OS version, if available.
// This is common in Linux distributions (e.g., "focal" for Ubuntu 20.04) but not typically used in Windows.
FString version_codename;
// 'pretty_name' is a more readable version of the name, potentially including the version and codename.
// For example, "Ubuntu 20.04 LTS (Focal Fossa)" or "Windows 10 Pro".
FString pretty_name;
// 'variant_id' is an identifier for the specific variant of the OS, if available.
// For example, in Linux distributions, this might be "desktop" for the desktop edition,
// "server" for the server edition, or "core" for a minimal installation. It helps distinguish
// between different flavors or editions of the same version.
// On the Steam Deck, this is set to "steamdeck".
FString variant_id;
void print() const
{
wprintf(L"Name: '%hs'\n", name.c_str());
wprintf(L"Version: '%d'\n", version);
wprintf(L"ID: '%hs'\n", id.c_str());
wprintf(L"Version ID: '%hs'\n", version_id.c_str());
wprintf(L"Version Codename: '%hs'\n", version_codename.c_str());
wprintf(L"Pretty Name: '%hs'\n", pretty_name.c_str());
wprintf(L"Variant ID: '%hs'\n", variant_id.c_str());
}
};
}

View file

@ -0,0 +1,45 @@
// Copyright (C) 2024 Jordon Brooks
#pragma once
#include "Core.h"
#include <Version.generated.h>
#include "FString.h"
namespace HarmonyLinkLib
{
class HARMONYLINKLIB_API version
{
public:
version() = default;
static FString ToString()
{
return HARMONYLINK_VERSION;
}
static FString get_build_timestamp()
{
return {__TIMESTAMP__};
}
static FString get_git_branch()
{
return {GIT_BRANCH_NAME};
}
static FString get_git_commit_timestamp()
{
return {GIT_COMMIT_TIMESTAMP};
}
static bool is_debug()
{
#ifdef DEBUG_MODE
return true;
#else
return false;
#endif
}
};
}

View file

@ -0,0 +1,11 @@
// Version.h.in
#pragma once
#define HARMONYLINK_VERSION_MAJOR @HarmonyLinkLib_VERSION_MAJOR@
#define HARMONYLINK_VERSION_MINOR @HarmonyLinkLib_VERSION_MINOR@
#define HARMONYLINK_VERSION_PATCH @HarmonyLinkLib_VERSION_PATCH@
#define HARMONYLINK_VERSION_TWEAK @HarmonyLinkLib_VERSION_TWEAK@
#define HARMONYLINK_VERSION "@HarmonyLinkLib_VERSION@"
#define GIT_BRANCH_NAME "@GIT_BRANCH_NAME@"
#define GIT_COMMIT_TIMESTAMP "@GIT_COMMIT_TIMESTAMP@"

View file

@ -0,0 +1,94 @@
#include "HarmonyLinkLib.h"
#include <iostream>
#include "Platform/IPlatformUtilities.h"
namespace HarmonyLinkLib
{
std::shared_ptr<IPlatformUtilities> PlatformUtilities = IPlatformUtilities::GetInstance();
bool get_is_wine()
{
if (!PlatformUtilities)
{
std::wcout << "Failed to get platform utilities!\n";
return false;
}
return PlatformUtilities->is_running_under_wine();
}
FCPUInfo* get_cpu_info()
{
if (!PlatformUtilities)
{
std::wcout << "Failed to get platform utilities!\n";
return nullptr;
}
const std::shared_ptr<FCPUInfo> cpu_info = PlatformUtilities->get_cpu_info();
if (!cpu_info)
{
return nullptr;
}
FCPUInfo* new_cpu_info = new FCPUInfo(*cpu_info);
return new_cpu_info;
}
FDevice* get_device_info()
{
if (!PlatformUtilities)
{
std::wcout << "Failed to get platform utilities!\n";
return nullptr;
}
const std::shared_ptr<FDevice> device = PlatformUtilities->get_device();
if (!device)
{
return nullptr;
}
FDevice* new_device = new FDevice(*device);
return new_device;
}
FOSVerInfo* get_os_version()
{
if (!PlatformUtilities)
{
std::wcout << "Failed to get platform utilities!\n";
return nullptr;
}
const std::shared_ptr<FOSVerInfo> os_version_info = PlatformUtilities->get_os_version();
if (!os_version_info)
{
return nullptr;
}
FOSVerInfo* new_os_info = new FOSVerInfo(*os_version_info);
return new_os_info;
}
FBattery* get_battery_status()
{
if (!PlatformUtilities)
{
std::wcout << "Failed to get platform utilities!\n";
return nullptr;
}
const std::shared_ptr<FBattery> new_battery = PlatformUtilities->get_battery_status();
if (!new_battery)
{
return nullptr;
}
FBattery* battery = new FBattery(*new_battery);
return battery;
}
}

View file

@ -0,0 +1,122 @@
#include "IPlatformUtilities.h"
#include <set>
#include "WineUtilities.h"
#if BUILD_WINDOWS
#include "Windows/WindowsUtilities.h"
#elif BUILD_LINUX
#include "Unix/Linux/LinuxUtilities.h"
#elif BUILD_MAC
#include "Unix/Mac/MacUtilities.h"
#elif BUILD_UNIX
#include "Unix/Mac/MacUtilities.h"
#endif
namespace HarmonyLinkLib
{
static std::shared_ptr<IPlatformUtilities> INSTANCE = nullptr;
std::shared_ptr<IPlatformUtilities>& IPlatformUtilities::GetInstance()
{
if (!INSTANCE)
{
#if BUILD_WINDOWS
INSTANCE = std::make_shared<WindowsUtilities>();
#elif BUILD_LINUX
INSTANCE = std::make_shared<LinuxUtilities>();
#elif BUILD_MAC
INSTANCE = std::make_shared<MacUtilities>();
#elif BUILD_UNIX
INSTANCE = std::make_shared<UnixUtilities>();
// ... other platform checks
#else
std::wcout << "Platform is not supported.\n"
#endif
}
return INSTANCE;
}
bool IPlatformUtilities::is_running_under_wine()
{
return WineUtilities::is_wine_present();
}
bool IPlatformUtilities::is_linux()
{
#ifdef BUILD_LINUX
return true;
#else
return is_running_under_wine();
#endif
}
std::shared_ptr<FDevice> IPlatformUtilities::get_device()
{
FDevice new_device;
if (is_linux())
{
new_device.platform = EPlatform::LINUX;
}
else
{
new_device.platform = EPlatform::WINDOWS;
}
const std::shared_ptr<FBattery> battery_status = get_battery_status();
if (battery_status && !battery_status->has_battery)
{
new_device.device = EDevice::DESKTOP;
}
else
{
new_device.device = EDevice::LAPTOP;
}
if (is_steam_deck(new_device)) {
new_device.device = EDevice::STEAM_DECK;
}
return std::make_shared<FDevice>(new_device);
}
// Helper function to check if the device is a Steam Deck
bool IPlatformUtilities::is_steam_deck(const FDevice& device) {
// Check if the device is already identified as a Steam Deck
if (device.device == EDevice::STEAM_DECK) {
return true;
}
// Check for Steam Deck by OS version
if (const std::shared_ptr<FOSVerInfo> version = get_os_version()) {
if (version->variant_id == "steamdeck" && version->name == "SteamOS") {
return true;
}
} else {
wprintf(L"OS version information not available.\n");
}
// Set of known Steam Deck CPU model names
const std::set<std::string> steam_deck_models = {"amd custom apu 0405" /*, other models... */};
// Check for Steam Deck by CPU model name
if (const std::shared_ptr<FCPUInfo> cpu_info = get_cpu_info()) {
const FString cpu_model_lower = FString::to_lower(cpu_info->Model_Name);
for (const auto& model : steam_deck_models) {
if (cpu_model_lower == model) {
wprintf(L"Steam Deck detected by CPU model name.\n");
return true;
}
}
} else {
wprintf(L"CPU information not available.\n");
}
wprintf(L"Device is not a Steam Deck.\n");
return false;
}
}

View file

@ -0,0 +1,34 @@
#pragma once
#include "Structs/FBattery.h"
#include "Structs/FCPUInfo.h"
#include "Structs/FDevice.h"
#include "Structs/FOSVerInfo.h"
namespace HarmonyLinkLib
{
class IPlatformUtilities {
public:
static std::shared_ptr<IPlatformUtilities>& GetInstance();
IPlatformUtilities() = default;
IPlatformUtilities(const IPlatformUtilities& other) = default;
IPlatformUtilities(IPlatformUtilities&& other) = default;
IPlatformUtilities& operator=(const IPlatformUtilities& other) = default;
IPlatformUtilities& operator=(IPlatformUtilities&& other) = default;
virtual ~IPlatformUtilities() = default;
// General OS-level functions
virtual bool is_running_under_wine();
virtual bool is_linux();
virtual std::shared_ptr<FDevice> get_device();
virtual std::shared_ptr<FCPUInfo> get_cpu_info() = 0;
virtual std::shared_ptr<FBattery> get_battery_status() = 0;
virtual std::shared_ptr<FOSVerInfo> get_os_version() = 0;
bool is_steam_deck(const FDevice& device);
// Add more virtual functions for other OS interactions here
};
}

View file

@ -0,0 +1,24 @@
#include "LinuxUtilities.h"
#include <fstream>
#include <string>
#include "Platform/WineUtilities.h"
namespace HarmonyLinkLib
{
std::shared_ptr<FBattery> LinuxUtilities::get_battery_status()
{
return WineUtilities::get_battery_status();
}
std::shared_ptr<FOSVerInfo> LinuxUtilities::get_os_version()
{
return WineUtilities::get_linux_info();
}
std::shared_ptr<FCPUInfo> LinuxUtilities::get_cpu_info()
{
return WineUtilities::get_cpu_info();
}
}

View file

@ -0,0 +1,23 @@
#pragma once
#include "Structs/FOSVerInfo.h"
#include "Platform/Unix/UnixUtilities.h"
namespace HarmonyLinkLib
{
class LinuxUtilities : public UnixUtilities {
public:
// Implementation for other Linux-specific functions
std::shared_ptr<FBattery> get_battery_status() override;
std::shared_ptr<FOSVerInfo> get_os_version() override;
std::shared_ptr<FCPUInfo> get_cpu_info() override;
bool is_linux() override
{
return true;
}
};
}

View file

@ -0,0 +1,6 @@
#include "MacUtilities.h"
namespace HarmonyLinkLib
{
}

View file

@ -0,0 +1,11 @@
#pragma once
#include "Platform/Unix/UnixUtilities.h"
namespace HarmonyLinkLib
{
class MacUtitities : public UnixUtilities {
public:
// Mac-specific overrides and additional functionality
};
}

View file

@ -0,0 +1,24 @@
#include "UnixUtilities.h"
namespace HarmonyLinkLib
{
bool UnixUtilities::is_running_under_wine()
{
return false;
}
std::shared_ptr<FCPUInfo> UnixUtilities::get_cpu_info()
{
return nullptr;
}
std::shared_ptr<FBattery> UnixUtilities::get_battery_status()
{
return nullptr;
}
std::shared_ptr<FOSVerInfo> UnixUtilities::get_os_version()
{
return nullptr;
}
}

View file

@ -0,0 +1,16 @@
#pragma once
#include "Platform/IPlatformUtilities.h"
namespace HarmonyLinkLib
{
class UnixUtilities : public IPlatformUtilities {
public:
bool is_running_under_wine() override;
std::shared_ptr<FCPUInfo> get_cpu_info() override;
std::shared_ptr<FBattery> get_battery_status() override;
std::shared_ptr<FOSVerInfo> get_os_version() override;
// Implementation for other Unix/Linux-specific functions
};
}

View file

@ -0,0 +1,81 @@
#include "WindowsUtilities.h"
#include <sstream>
#include <Windows.h>
#include "Platform/WineUtilities.h"
namespace HarmonyLinkLib
{
std::shared_ptr<FBattery> WindowsUtilities::get_battery_status()
{
if (is_linux())
{
return WineUtilities::get_battery_status();
}
FBattery result;
SYSTEM_POWER_STATUS status;
if (GetSystemPowerStatus(&status)) {
result.has_battery = status.BatteryFlag != 128; // 128 indicates no battery
result.is_connected_to_ac = status.ACLineStatus == 1;
result.battery_percent = result.has_battery ? status.BatteryLifePercent : 0;
} else {
std::wcout << "Failed to get power statistics.\n";
}
return std::make_shared<FBattery>(result);
}
std::shared_ptr<FCPUInfo> WindowsUtilities::get_cpu_info()
{
if (is_linux())
{
return WineUtilities::get_cpu_info();
}
return {};
}
std::shared_ptr<FOSVerInfo> WindowsUtilities::get_os_version()
{
if (is_linux())
{
return WineUtilities::get_linux_info();
}
OSVERSIONINFOEX os_version_info;
ZeroMemory(&os_version_info, sizeof(OSVERSIONINFOEX));
os_version_info.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
if (!GetVersionEx(reinterpret_cast<OSVERSIONINFO*>(&os_version_info))) {
// Handle error if needed
return nullptr;
}
FOSVerInfo os_version;
HKEY h_key;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"), 0, KEY_READ, &h_key) == ERROR_SUCCESS)
{
DWORD dw_size;
DWORD dw_type;
char sz_product_name[256];
dw_size = sizeof(sz_product_name);
if (RegQueryValueEx(h_key, TEXT("ProductName"), nullptr, &dw_type, reinterpret_cast<LPBYTE>(sz_product_name), &dw_size) == ERROR_SUCCESS)
{
os_version.pretty_name = sz_product_name;
}
RegCloseKey(h_key);
}
std::stringstream version;
version << os_version_info.dwMajorVersion << "." << os_version_info.dwMinorVersion;
os_version.version_id = version.str();
os_version.name = "Windows";
os_version.version = os_version_info.dwBuildNumber; // Build number as the version
return std::make_shared<FOSVerInfo>(os_version);
}
}

View file

@ -0,0 +1,16 @@
#pragma once
#include "Platform/IPlatformUtilities.h"
namespace HarmonyLinkLib
{
class WindowsUtilities : public IPlatformUtilities
{
public:
std::shared_ptr<FBattery> get_battery_status() override;
std::shared_ptr<FCPUInfo> get_cpu_info() override;
std::shared_ptr<FOSVerInfo> get_os_version() override;
};
}

View file

@ -0,0 +1,202 @@
#include "WineUtilities.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include <unordered_map>
#include <filesystem>
#ifdef BUILD_WINDOWS
#include <windows.h>
#endif
namespace HarmonyLinkLib
{
bool force_detect_wine = false;
std::shared_ptr<HarmonyLinkLib::FBattery> HarmonyLinkLib::WineUtilities::get_battery_status()
{
std::string append;
if (is_wine_present())
{
append = "Z:";
}
FBattery result = {};
for (int i = 0; i <= 9; ++i) {
if (std::string bat_path = append + "/sys/class/power_supply/BAT" + std::to_string(i); std::filesystem::exists(bat_path)) {
result.has_battery = true;
std::ifstream status_file(bat_path + "/status");
std::string status;
if (status_file.is_open() && std::getline(status_file, status)) {
if (status == "Charging" || status == "AC") {
result.is_connected_to_ac = true;
}
}
std::ifstream capacity_file(bat_path + "/capacity");
if (capacity_file.is_open() && std::getline(capacity_file, status)) {
result.battery_percent = static_cast<uint8_t>(std::stoi(status));
break; // assuming you only need data from the first battery found
}
}
}
return std::make_shared<FBattery>(result);
}
std::shared_ptr<FCPUInfo> WineUtilities::get_cpu_info()
{
std::wcout << "Getting cpu info\n";
std::string append;
if (is_wine_present())
{
append = "Z:";
}
FCPUInfo cpu_info;
std::ifstream file(append + "/proc/cpuinfo");
std::unordered_map<HarmonyLinkLib::FString, HarmonyLinkLib::FString> hashmap;
if (file) {
std::string line;
while (std::getline(file, line)) {
std::istringstream line_stream(line);
std::string key, value;
if (std::getline(line_stream, key, ':')) {
key.erase(key.find_last_not_of(" \t") + 1); // Trim trailing whitespace from key
if (std::getline(line_stream, value)) {
value.erase(0, value.find_first_not_of(" \t")); // Trim leading whitespace from value
// Aggregate flags
if (key == "flags") {
std::istringstream flag_stream(value);
std::string flag;
while (flag_stream >> flag) {
flag.erase(flag.find_last_not_of(" \t") + 1); // Trim trailing whitespace from flag
cpu_info.Flags.insert(HarmonyLinkLib::FString(flag));
//printf("Flag detected: %s\n", flag.c_str());
}
} else {
hashmap[key] = value;
}
}
}
}
file.close();
}
// Now you can access the values using the keys:
cpu_info.VendorID = hashmap["vendor_id"];
cpu_info.Model_Name = hashmap["model name"];
try {
cpu_info.Physical_Cores = std::stoi(hashmap["cpu cores"].c_str());
} catch (const std::invalid_argument& ia) {
std::wcerr << "Invalid argument: " << ia.what() << '\n';
} catch (const std::out_of_range& oor) {
std::wcerr << "Out of Range error: " << oor.what() << '\n';
}
cpu_info.Logical_Cores = (cpu_info.Flags.find("ht") != cpu_info.Flags.end()) ? cpu_info.Physical_Cores * 2 : cpu_info.Physical_Cores;
return std::make_shared<FCPUInfo>(cpu_info);
}
std::shared_ptr<FOSVerInfo> WineUtilities::get_linux_info()
{
std::string append;
if (is_wine_present())
{
append = "Z:";
}
FOSVerInfo os_info;
std::ifstream file(append + "/etc/os-release");
std::unordered_map<HarmonyLinkLib::FString, HarmonyLinkLib::FString> hashmap;
if (file) {
std::string line;
while (std::getline(file, line)) {
std::istringstream lineStream(line);
std::string key, value;
if (std::getline(lineStream, key, '=')) {
if (std::getline(lineStream, value)) {
// Remove leading and trailing whitespace
size_t firstNonSpace = value.find_first_not_of(" \t");
size_t lastNonSpace = value.find_last_not_of(" \t");
if (firstNonSpace != std::string::npos && lastNonSpace != std::string::npos) {
value = value.substr(firstNonSpace, lastNonSpace - firstNonSpace + 1);
} else {
value.clear(); // If value is all whitespace, make it empty
}
// Check for double quotes and remove them
if (!value.empty() && value.front() == '"' && value.back() == '"') {
value = value.substr(1, value.length() - 2);
}
hashmap[key] = value;
}
}
}
file.close();
}
// Now you can access the values using the keys:
os_info.name = hashmap["NAME"];
os_info.id = hashmap["ID"];
os_info.version_id = hashmap["VERSION_ID"];
os_info.version_codename = hashmap["VERSION_CODENAME"];
os_info.pretty_name = hashmap["PRETTY_NAME"];
try {
os_info.version = std::stoi(hashmap["VERSION"].c_str());
} catch (const std::invalid_argument& ia) {
std::cerr << "Invalid argument: " << ia.what() << '\n';
// Handle the error, perhaps by setting a default value or leaving the field unchanged
} catch (const std::out_of_range& oor) {
std::cerr << "Out of Range error: " << oor.what() << '\n';
// Handle the error, perhaps by setting a default value or leaving the field unchanged
}
return std::make_shared<FOSVerInfo>(os_info);
}
bool WineUtilities::is_wine_present()
{
static bool isWineCached = false; // Static variable to store the cached result
static bool isWine = false; // Static variable to indicate if the caching has been done
if (!isWineCached)
{
// Only detect wine if force_detect_wine is true or if we haven't cached the result yet
#ifdef BUILD_WINDOWS
std::wcout << "Detecting wine...\n";
bool HasFound = GetProcAddress(GetModuleHandle("ntdll.dll"), "wine_get_version") != nullptr;
if (!HasFound)
HasFound = GetProcAddress(GetModuleHandle("ntdll.dll"), "proton_get_version") != nullptr;
wprintf(L"wine %s found\n", HasFound ? L"has been" : L"not");
isWine = HasFound; // Cache the result
#else
isWine = false; // In non-Windows builds, always set isWine to false
#endif
isWineCached = true; // Indicate that the result is now cached
}
return isWine; // Return the cached result
}
bool WineUtilities::force_detect_wine_presence()
{
force_detect_wine = true;
return is_wine_present();
}
}

View file

@ -0,0 +1,46 @@
#pragma once
#include "Structs/FBattery.h"
#include "Structs/FCPUInfo.h"
#include "Structs/FOSVerInfo.h"
namespace HarmonyLinkLib
{
class WineUtilities
{
public:
static std::shared_ptr<FBattery> get_battery_status();
static std::shared_ptr<FCPUInfo> get_cpu_info();
/**
* @brief Retrieves Linux OS version information from a specified file.
*
* This function parses a file (typically a Linux OS release file) at the given location
* to extract operating system version information. It reads key-value pairs from the file,
* processes them to handle whitespace and quotes, and then stores them in an FOSVerInfo
* structure. If the file location is invalid or the file cannot be opened, it returns an
* empty FOSVerInfo structure. Errors during parsing, such as invalid format or out of range
* values, are handled with exception catching. In Windows builds where Wine is detected,
* this function can use the file location 'Z:/etc/os-release' to retrieve the underlying
* Linux system information.
*
* @param file_location The location of the file containing OS version information.
* @return A shared pointer to a structure containing the parsed OS version information.
*/
static std::shared_ptr<FOSVerInfo> get_linux_info();
/**
* @brief Detects the presence of Wine or Proton in Windows builds.
*
* This function assesses if the application is running under Wine or Proton by
* querying specific functions in the 'ntdll.dll' module. It is only active in
* Windows builds, returning false for non-Windows builds.
*
* @return bool True if Wine or Proton is detected, false otherwise.
*/
static bool is_wine_present();
static bool force_detect_wine_presence();
};
}

View file

@ -0,0 +1 @@
#include "Version.h"

View file

@ -0,0 +1,49 @@
// Copyright (C) 2024 Jordon Brooks
#include <iostream>
#include "Version.h"
namespace HarmonyLinkLib
{
void HarmonyLinkInit()
{
std::wcout << "HarmonyLink V" << version::ToString().c_str() << " Copyright (C) 2023 Jordon Brooks\n";
}
}
#if BUILD_WINDOWS
#include <windows.h>
// Standard DLL entry point
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {
switch (fdwReason) {
case DLL_PROCESS_ATTACH:
// Code to run when the DLL is loaded
HarmonyLinkLib::HarmonyLinkInit();
break;
case DLL_THREAD_ATTACH:
// Code to run when a thread is created during the DLL's lifetime
case DLL_THREAD_DETACH:
// Code to run when a thread ends normally.
case DLL_PROCESS_DETACH:
// Code to run when the DLL is unloaded
default:
break;
}
return TRUE; // Successful DLL_PROCESS_ATTACH.
}
#endif
#if BUILD_UNIX
__attribute__((constructor))
static void onLibraryLoad() {
// Code to run when the library is loaded
HarmonyLinkLib::HarmonyLinkInit();
}
__attribute__((destructor))
static void onLibraryUnload() {
// Code to run when the library is unloaded
}
#endif

View file

@ -0,0 +1,31 @@
cmake_minimum_required(VERSION 3.10)
project(HarmonyLinkTest)
# Specify the C++ standard
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED True)
# Automatically add all .cpp and .h/.hpp files in the src directory
file(GLOB_RECURSE TEST_SOURCES "src/*.cpp")
file(GLOB_RECURSE TEST_HEADERS "src/*.h" "src/*.hpp")
# Add executable
add_executable(HarmonyLinkTest ${TEST_SOURCES} ${TEST_HEADERS})
# Link the HarmonyLinkLib with HarmonyLinkTest
target_link_libraries(HarmonyLinkTest PRIVATE HarmonyLinkLib)
# Set output directories for all build types
foreach(TYPE IN ITEMS DEBUG RELEASE)
string(TOUPPER ${TYPE} TYPE_UPPER)
set_target_properties(${PROJECT_NAME} PROPERTIES
RUNTIME_OUTPUT_DIRECTORY_${TYPE_UPPER} "${CMAKE_BINARY_DIR}/bin/${TYPE}/${PROJECT_NAME}"
LIBRARY_OUTPUT_DIRECTORY_${TYPE_UPPER} "${CMAKE_BINARY_DIR}/bin/${TYPE}/${PROJECT_NAME}"
ARCHIVE_OUTPUT_DIRECTORY_${TYPE_UPPER} "${CMAKE_BINARY_DIR}/bin/${TYPE}/${PROJECT_NAME}"
)
endforeach()
add_custom_command(TARGET HarmonyLinkTest POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
"$<TARGET_FILE:HarmonyLinkLib>"
"$<TARGET_FILE_DIR:HarmonyLinkTest>")

View file

@ -0,0 +1,143 @@
// Copyright (C) 2023 Jordon Brooks
#include <iostream>
#include <chrono>
#include <thread>
#include <atomic>
#include "HarmonyLinkLib.h"
// Include necessary headers for platform-specific functionality
#ifdef BUILD_WINDOWS
#include <conio.h> // For _kbhit() and _getch()
#include <windows.h> // For system("cls")
#else
#include <unistd.h> // For read()
#include <termios.h> // For termios
#include <stdio.h> // For getchar()
#include <fcntl.h> // For F_GETFL, F_SETFL and O_NONBLOCK
#endif
std::atomic<bool> quitFlag(false);
// Function to clear the screen cross-platform
void clearScreen() {
#ifdef _WIN32
system("cls");
#else
std::cout << "\x1B[2J\x1B[H";
#endif
}
// Function to check if 'q' or 'Q' is pressed in Windows
void checkForQuit() {
while (!quitFlag) {
#ifdef BUILD_WINDOWS
if (_kbhit()) {
const char c = static_cast<char>(_getch());
if (c == 'q' || c == 'Q') {
quitFlag = true;
break;
}
}
#else
struct termios oldt, newt;
int ch;
int oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
if (ch != EOF) {
ungetc(ch, stdin);
if (ch == 'q' || ch == 'Q') {
quitFlag = true;
break;
}
}
#endif
// Checks for input every roughly 60 frames
std::this_thread::sleep_for(std::chrono::milliseconds(16));
}
}
int main()
{
std::cout << "Hello, World!" << '\n';
std::thread inputThread(checkForQuit);
const bool isWine = HarmonyLinkLib::get_is_wine();
const char* test = isWine ? "is" : "isn't";
const HarmonyLinkLib::FOSVerInfo* os_info = HarmonyLinkLib::get_os_version();
const HarmonyLinkLib::FDevice* device_info = HarmonyLinkLib::get_device_info();
const HarmonyLinkLib::FCPUInfo* cpu_info = HarmonyLinkLib::get_cpu_info();
// This loop is to test how stable & expensive these functions are
while (!quitFlag)
{
// Clear the screen
clearScreen();
std::wcout << "This program " << test << " running under wine.\n";
if (cpu_info)
{
cpu_info->print();
}
if (os_info)
{
os_info->print();
}
if (device_info)
{
wprintf(L"Is SteamDeck: %s\n", device_info->device == HarmonyLinkLib::EDevice::STEAM_DECK ? L"true" : L"false");
}
// we can't do this before the loop because we need updated values
if (const HarmonyLinkLib::FBattery* battery = HarmonyLinkLib::get_battery_status())
{
battery->to_string();
battery->free();
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
if (inputThread.joinable())
{
inputThread.join();
}
if (os_info)
{
os_info->free();
}
if (device_info)
{
device_info->free();
}
if (cpu_info)
{
cpu_info->free();
}
return 0;
}

View file

@ -1,11 +0,0 @@
[
{
"brand": "JSAUX",
"model": "HB0603",
"usb_ids": [
[ 4826, 21521 ],
[ 4826, 1041 ],
[ 4826, 33139 ]
]
}
]

View file

@ -1,72 +0,0 @@
use std::env;
use std::error::Error;
use std::fs;
use std::path::Path;
use vergen::EmitBuilder;
fn copy_resources() -> Result<(), Box<dyn Error>> {
// The directory of the Cargo manifest of the package that is currently being built.
let manifest_dir = env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is not defined");
// The directory where the final binaries will be placed.
let profile = env::var("PROFILE")?;
let out_dir = Path::new(&manifest_dir).join("target").join(profile).join("Resources");
if !out_dir.exists() {
fs::create_dir(&out_dir)?;
}
// The Resources directory.
let resources_dir = Path::new(&manifest_dir).join("Resources");
// Ensure the Resources directory exists.
if !resources_dir.exists() {
panic!("Resources directory does not exist");
}
// Iterate over each entry in the Resources directory.
for entry in fs::read_dir(resources_dir)? {
let entry = entry?;
let path = entry.path();
if path.is_file() {
// The destination path is the output directory plus the file name.
let dest_path = out_dir.join(path.file_name().expect("file has no name"));
// Copy the file.
fs::copy(&path, &dest_path)?;
}
}
Ok(())
}
#[cfg(windows)]
fn windows_resource() -> Result<(), Box<dyn Error>> {
let mut res = winres::WindowsResource::new();
res.set_icon("res/HarmonyLinkLogo.ico");
res.compile()?;
Ok(())
}
#[cfg(unix)]
fn windows_resource() -> Result<(), Box<dyn Error>> {
Ok(())
}
fn main() -> Result<(), Box<dyn Error>> {
// Emit the instructions
EmitBuilder::builder()
.all_build()
.all_cargo()
.all_git()
.all_rustc()
.all_sysinfo()
.emit()?;
// Copy the Resources folder
copy_resources()?;
windows_resource()?;
Ok(())
}

View file

@ -1,14 +0,0 @@
use actix_web::{HttpResponse, get, web};
use crate::version::info::Version;
#[get("/supported_versions")]
pub async fn versions() -> HttpResponse {
let version = Version::get();
HttpResponse::Ok().json(&version.supported_api_versions)
}
pub fn configure(cfg: &mut web::ServiceConfig) {
cfg.service(versions);
// Register other version 1 handlers here...
}

View file

@ -1,99 +0,0 @@
use actix_web::web;
use actix_web::{HttpResponse, get};
use crate::v1::{docking, os, all_info, battery};
use crate::version;
#[get("/are_you_there")]
pub async fn heartbeat() -> HttpResponse {
HttpResponse::Ok().body("yes")
}
#[get("/all_info")]
pub async fn get_all_info() -> HttpResponse {
match all_info::stats::get_all_info() {
Ok(info) => {
#[cfg(debug_assertions)]
{
println!("Successfully got all info: {}", &info.clone().to_string());
}
HttpResponse::Ok().json(&info)
},
Err(err) => {
eprintln!("Failed to get all info: {}", err);
HttpResponse::InternalServerError().body(format!("Failed to get device info: {}", err))
}
}
}
#[get("/dock_info")]
pub async fn get_dock_info() -> HttpResponse {
match docking::stats::get_dock() {
Ok(info) => {
#[cfg(debug_assertions)]
{
println!("Successfully got dock info: {}", &info.clone().to_string());
}
HttpResponse::Ok().json(&info)
},
Err(err) => {
eprintln!("Failed to get dock info: {}", err);
HttpResponse::InternalServerError().body(format!("Failed to get dock info: {}", err))
}
}
}
#[get("/os_info")]
pub async fn get_os_info() -> HttpResponse {
match os::stats::get_os() {
Ok(info) => {
#[cfg(debug_assertions)]
{
println!("Successfully got os info: {}", &info.clone().to_string());
}
HttpResponse::Ok().json(&info)
},
Err(err) => {
eprintln!("Failed to get os info: {}", err);
HttpResponse::InternalServerError().body(format!("Failed to get OS info: {}", err))
}
}
}
#[get("/battery_info")]
pub async fn get_battery_info() -> HttpResponse {
match battery::stats::get_battery_info() {
Ok(info) => {
#[cfg(debug_assertions)]
{
println!("Successfully got battery info: {}", &info.clone().to_string());
}
HttpResponse::Ok().json(&info)
},
Err(err) => {
eprintln!("Failed to get battery info: {}", err);
HttpResponse::InternalServerError().body(format!("Failed to get battery info: {}", err))
}
}
}
#[get("/version_info")]
pub async fn get_version_info() -> HttpResponse {
#[cfg(debug_assertions)]
{
println!("Successfully got version info: {}", version::info::Version::get().to_string());
}
HttpResponse::Ok().json(&version::info::Version::get())
}
pub fn configure(cfg: &mut web::ServiceConfig) {
cfg.service(heartbeat);
cfg.service(get_all_info);
cfg.service(get_dock_info);
cfg.service(get_os_info);
cfg.service(get_battery_info);
cfg.service(get_version_info);
// Register other version 1 handlers here...
}

View file

@ -1,3 +0,0 @@
pub mod server;
mod endpoints_v1;
mod api;

View file

@ -1,28 +0,0 @@
use actix_web::{HttpServer, web};
use crate::api::endpoints_v1;
use crate::api::api;
#[allow(dead_code)]
pub async fn stop_actix_web(server: actix_web::dev::Server) -> std::io::Result<()> {
println!("Stopping server.");
server.handle().stop(true).await;
Ok(())
}
pub fn start_actix_web(port: u16) -> std::io::Result<actix_web::dev::Server> {
println!("Starting webserver on 127.0.0.1:{}", port);
let server = HttpServer::new(move || {
let logger = actix_web::middleware::Logger::default();
actix_web::App::new()
.wrap(logger)
.service(web::scope("/api").configure(api::configure))
.service(web::scope("/v1").configure(endpoints_v1::configure))
})
.bind(("127.0.0.1", port))?
.run();
Ok(server)
}

View file

@ -1,37 +0,0 @@
mod v1;
mod version;
use version::info::Version;
mod api;
static PORT: u16 = 9000;
static USE_FALLBACK_DOCK_DETECTION: bool = false;
fn main() {
//#[cfg(debug_assertions)]
{
let version_info = Version::get();
println!("Version: {}", version_info.version);
println!("Build Timestamp: {}", version_info.build_timestamp);
println!("Git Branch: {}", version_info.git_branch);
println!("Git Describe: {}", version_info.git_describe);
println!("Git Commit Timestamp: {}", version_info.git_commit_timestamp);
println!("Debug Build: {}", version_info.debug);
println!("API versions: {}", version_info.supported_api_versions_to_string());
println!("\n\n");
}
println!("HarmonyLink ©️ Jordon Brooks 2023");
let sys = actix_web::rt::System::new();
sys.block_on(async {
let result = api::server::start_actix_web(PORT).expect("err");
let _ = result.await;
});
}

View file

@ -1,2 +0,0 @@
pub mod stats;
pub mod structs;

View file

@ -1,18 +0,0 @@
use crate::v1::docking;
use crate::v1::battery;
use crate::v1::os;
use crate::version;
use super::structs::Allinfo;
/* This will query all the modules and return all the combined data */
pub fn get_all_info() -> Result<Allinfo, Box<dyn std::error::Error>> {
let mut all_info = Allinfo::new();
all_info.dock = docking::stats::get_dock_info()?;
all_info.battery = battery::stats::get_battery_info()?;
all_info.os = os::stats::get_os()?;
all_info.version = version::info::Version::get();
Ok(all_info)
}

View file

@ -1,24 +0,0 @@
use serde::{Deserialize, Serialize};
use crate::{v1::{os, battery, docking::{self, structs::DockInfo}}, version};
#[derive(Deserialize, Serialize, Clone)]
pub struct Allinfo {
pub os: os::structs::OSInfo,
pub battery: battery::structs::BatteryInfo,
pub dock: docking::structs::DockInfo,
pub version: version::info::Version
}
impl Allinfo {
pub fn new() -> Allinfo {
Allinfo { os: os::structs::OSInfo::new(),
battery: battery::structs::BatteryInfo::new(),
dock: DockInfo::new(),
version: version::info::Version::get()
}
}
pub fn to_string(self) -> String {
serde_json::to_string(&self).expect("Failed to parse into string")
}
}

View file

@ -1,2 +0,0 @@
pub mod stats;
pub mod structs;

View file

@ -1,38 +0,0 @@
use crate::v1::battery::structs::ChargingStatus;
use super::structs::BatteryInfo;
pub fn get_battery_info() -> Result<BatteryInfo, Box<dyn std::error::Error>> {
let mut battery_info = BatteryInfo { has_battery: false, battery_percent: 0, charging_status: ChargingStatus::UNKNOWN };
let manager = battery::Manager::new().unwrap();
battery_info.has_battery = manager.batteries().unwrap().count() > 0;
if !battery_info.has_battery {
return Ok(battery_info);
}
for (idx, battery) in manager.batteries()?.enumerate() {
let battery = battery?;
let state = battery.state();
let energy = battery.energy();
let full_energy = battery.energy_full();
let state_of_charge = (energy / full_energy).get::<battery::units::ratio::percent>();
println!("Battery #{}:", idx);
println!("Charging status: {:?}", state);
println!("Charge level: {:.2}%", state_of_charge);
battery_info.battery_percent = state_of_charge.round() as i8;
battery_info.charging_status = match state {
battery::State::Charging => ChargingStatus::Charging,
battery::State::Discharging => ChargingStatus::Battery,
battery::State::Empty => ChargingStatus::Battery,
battery::State::Full => ChargingStatus::Battery,
_ => ChargingStatus::UNKNOWN,
}
}
Ok(battery_info)
}

View file

@ -1,28 +0,0 @@
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize, PartialEq, Clone)]
pub enum ChargingStatus {
Charging,
Battery,
UNKNOWN,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct BatteryInfo {
pub has_battery: bool,
pub battery_percent: i8,
pub charging_status: ChargingStatus,
}
impl BatteryInfo {
pub fn new() -> BatteryInfo {
BatteryInfo {
has_battery: false,
battery_percent: 0,
charging_status: ChargingStatus::UNKNOWN
}
}
pub fn to_string(self) -> String {
serde_json::to_string(&self).expect("Failed to parse into string")
}
}

View file

@ -1,2 +0,0 @@
pub mod stats;
pub mod structs;

View file

@ -1,90 +0,0 @@
use std::{io::BufReader, fs::File};
#[allow(unused_imports)]
use std::collections::HashSet;
use crate::{v1::{battery::{stats::get_battery_info, structs::ChargingStatus}}, USE_FALLBACK_DOCK_DETECTION};
use super::structs::{Dock, DockInfo};
/* This will get the current dock info. */
pub fn get_dock_info() -> Result<DockInfo, Box<dyn std::error::Error>> {
let mut dock = DockInfo::new();
dock.dock_info = get_dock()?;
dock.is_docked = dock.dock_info.brand == String::new() && dock.dock_info.model == String::new();
/*
This code will manually detect a dock if it wasn't automatically picked up by get_dock().
The code currently doesnt work. To manually detect a dock we will detect the presence of
a battery, charging of the handheld, and eventually when I find a cross-platform create,
it will also detect the presence of an external monitor (will most likely only work on a
Steam Deck for now)
*/
if USE_FALLBACK_DOCK_DETECTION {
if !dock.is_docked {
dock.fallback_detection = true;
let battery_info = get_battery_info()?;
if battery_info.has_battery && battery_info.charging_status == ChargingStatus::Charging {
}
}
}
Ok(dock)
}
/* Reads the dock_models.json file and returns a vector of structs with the data */
#[allow(dead_code)]
pub fn read_dock_models_from_file() -> Result<Vec<Dock>, Box<dyn std::error::Error>> {
let file = File::open("Resources/dock_models.json")?;
let reader = BufReader::new(file);
let dock_models: Vec<Dock> = serde_json::from_reader(reader)?;
Ok(dock_models)
}
#[cfg(target_os = "linux")]
/* This will detect the dock model and brand. */
pub fn get_dock() -> Result<Dock, Box<dyn std::error::Error>> {
let devices = rusb::devices()?;
let dock_models = read_dock_models_from_file()?;
for dock_model in dock_models {
let mut found_components = HashSet::new();
for device in devices.iter() {
let device_desc = device.device_descriptor()?;
let device_id = (device_desc.vendor_id(), device_desc.product_id());
// Check if the device is one of the components of the dock.
if dock_model.usb_ids.contains(&[device_desc.vendor_id(), device_desc.product_id()]) {
found_components.insert(device_id);
println!("(get_dock) Detected: {}", serde_json::to_string_pretty(&device_id)?);
}
}
if found_components.len() == dock_model.usb_ids.len() {
println!("(get_dock) All components detected for {}", serde_json::to_string_pretty(&dock_model)?);
return Ok(Dock {
model: dock_model.model.clone(),
brand: dock_model.brand.clone(),
usb_ids: dock_model.usb_ids.clone()
});
}
}
Ok(Dock::new())
}
#[cfg(target_os = "macos")]
/* This will detect the dock model and brand. */
pub fn get_dock() -> Result<Dock, Box<dyn std::error::Error>> {
Ok(Dock::new())
//Err(Box::new(std::io::Error::new(std::io::ErrorKind::Other, "Incorrect OS")))
}
/* This will detect the dock model and brand. */
#[cfg(target_os = "windows")]
pub fn get_dock() -> Result<Dock, Box<dyn std::error::Error>> {
Ok(Dock::new())
}

View file

@ -1,39 +0,0 @@
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize, Clone)]
pub struct Dock {
pub brand: String, // ex: JSAUX
pub model: String, // ex: HB0603
pub usb_ids: Vec<[u16; 2]>,
}
impl Dock {
pub fn new() -> Dock {
Dock { brand: String::new(),
model: String::new(),
usb_ids: vec![],
}
}
pub fn to_string(self) -> String {
serde_json::to_string(&self).expect("Failed to parse into string")
}
}
#[derive(Deserialize, Serialize, Clone)]
pub struct DockInfo {
pub dock_info: Dock,
pub is_docked: bool,
pub fallback_detection: bool,
}
impl DockInfo {
pub fn new() -> DockInfo {
DockInfo { dock_info: Dock::new(),
is_docked: false,
fallback_detection: false
}
}
pub fn to_string(self) -> String {
serde_json::to_string(&self).expect("Failed to parse into string")
}
}

View file

@ -1,4 +0,0 @@
pub mod battery;
pub mod docking;
pub mod os;
pub mod all_info;

View file

@ -1,2 +0,0 @@
pub mod stats;
pub mod structs;

View file

@ -1,45 +0,0 @@
use super::structs::{OSInfo, Platform, Architecture};
pub fn get_platform() -> Platform {
if cfg!(target_os = "windows") {
Platform::WINDOWS
} else if cfg!(target_os = "macos") {
Platform::MAC
} else if cfg!(target_os = "linux") {
Platform::LINUX
} else {
Platform::UNKNOWN
}
}
pub fn get_os() -> Result<OSInfo, Box<dyn std::error::Error>> {
let mut temp = OSInfo::new();
let info = os_info::get();
temp.platform = get_platform();
temp.name = match info.codename() {
Some(s) => s.to_string(),
_ => String::new(),
};
temp.version = info.version().to_string();
if temp.name == String::new() {
temp.name = match info.edition() {
Some(s) => s.to_string(),
_ => String::new(),
};
}
temp.bits = match info.bitness()
{
os_info::Bitness::X32 => Architecture::X86,
os_info::Bitness::X64 => Architecture::X86_64,
_ => Architecture::UNKNOWN,
};
Ok(temp)
}

View file

@ -1,38 +0,0 @@
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize, PartialEq, Clone)]
pub enum Platform {
WINDOWS = 0,
LINUX = 1,
MAC = 2,
UNKNOWN = 255
}
#[derive(Deserialize, Serialize, Clone)]
pub enum Architecture {
X86 = 0,
X86_64 = 1,
UNKNOWN = 255,
}
#[derive(Deserialize, Serialize, Clone)]
pub struct OSInfo {
pub platform: Platform, // Windows, Mac, Linux
pub name: String, // "Windows 11 2306", "Ubuntu 22.04 LTS"
pub version: String, // 2306, 22.04
pub bits: Architecture // 32, 64
}
impl OSInfo {
pub fn new() -> OSInfo {
OSInfo {
platform: Platform::UNKNOWN,
name: String::new(),
version: String::new(),
bits: Architecture::UNKNOWN
}
}
pub fn to_string(self) -> String {
serde_json::to_string(&self).expect("Failed to parse into string")
}
}

View file

@ -1,41 +0,0 @@
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize, Clone)]
pub struct Version {
pub build_timestamp: String,
pub git_branch: String,
pub git_describe: String,
pub git_commit_timestamp: String,
pub debug: bool,
pub version: String,
pub version_major: i32,
pub version_minor: i32,
pub version_patch: i32,
pub version_pre: String,
pub supported_api_versions: Vec<String>
}
impl Version {
pub fn get() -> Version {
Version {
build_timestamp: env!("VERGEN_BUILD_TIMESTAMP").to_string(),
git_branch: env!("VERGEN_GIT_BRANCH").to_string(),
git_describe: env!("VERGEN_GIT_DESCRIBE").to_string(),
git_commit_timestamp: env!("VERGEN_GIT_COMMIT_TIMESTAMP").to_string(),
debug: env!("VERGEN_CARGO_DEBUG").parse().unwrap(),
version: env!("CARGO_PKG_VERSION").to_string(),
version_major: env!("CARGO_PKG_VERSION_MAJOR").parse().unwrap(),
version_minor: env!("CARGO_PKG_VERSION_MINOR").parse().unwrap(),
version_patch: env!("CARGO_PKG_VERSION_PATCH").parse().unwrap(),
version_pre: "Alpha".to_string(),
supported_api_versions: vec!["v1".to_string()]
}
}
pub fn to_string(self) -> String {
serde_json::to_string(&self).expect("Failed to parse into string")
}
pub fn supported_api_versions_to_string(self) -> String {
self.supported_api_versions.join(", ")
}
}

View file

@ -1 +0,0 @@
pub mod info;