Compare commits

..

No commits in common. "Dev" and "V0.2.0_Alpha" have entirely different histories.

72 changed files with 3097 additions and 3195 deletions

42
.gitattributes vendored
View file

@ -1,42 +0,0 @@
* 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
# Linux shell files must always be LF
*.sh text eol=lf

View file

@ -1,38 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.

View file

@ -1,20 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

View file

@ -1,91 +0,0 @@
# This starter workflow is for a CMake project running on multiple platforms. There is a different starter workflow if you just want a single platform.
# See: https://github.com/actions/starter-workflows/blob/main/ci/cmake-single-platform.yml
name: CMake on multiple platforms
on:
workflow_dispatch:
push:
branches: [ "Stable", "Dev" ]
pull_request:
branches: [ "Stable", "Dev" ]
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
# Set fail-fast to false to ensure that feedback is delivered for all matrix combinations. Consider changing this to true when your workflow is stable.
fail-fast: false
# Set up a matrix to run the following 3 configurations:
# 1. <Windows, Release, latest MSVC compiler toolchain on the default runner image, default generator>
# 2. <Linux, Release, latest GCC compiler toolchain on the default runner image, default generator>
# 3. <Linux, Release, latest Clang compiler toolchain on the default runner image, default generator>
#
# To add more build types (Release, Debug, RelWithDebInfo, etc.) customize the build_type list.
matrix:
os: [ubuntu-latest, windows-latest] # macos-latest
build_type: [Release]
c_compiler: [gcc, clang, cl]
cpp_compiler: [g++, clang++, cl]
include:
- os: windows-latest
c_compiler: cl
cpp_compiler: cl
- os: ubuntu-latest
c_compiler: gcc
cpp_compiler: g++
- os: ubuntu-latest
c_compiler: clang
cpp_compiler: clang++
#- os: macos-latest
# c_compiler: clang
# cpp_compiler: clang++
exclude:
- os: windows-latest
c_compiler: gcc
- os: windows-latest
c_compiler: clang
- os: ubuntu-latest
c_compiler: cl
- os: ubuntu-latest
cpp_compiler: cl
#- os: macos-latest
# c_compiler: gcc
#- os: macos-latest
# cpp_compiler: g++
#- os: macos-latest
# c_compiler: cl
#- os: macos-latest
# cpp_compiler: cl
steps:
- uses: actions/checkout@v4
with:
submodules: 'recursive'
- name: Set reusable strings
# Turn repeated input strings (such as the build output directory) into step outputs. These step outputs can be used throughout the workflow file.
id: strings
shell: bash
run: |
echo "build-output-dir=${{ github.workspace }}/build" >> "$GITHUB_OUTPUT"
- name: Configure CMake
# Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generator such as make.
# See https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html?highlight=cmake_build_type
run: >
cmake -B ${{ steps.strings.outputs.build-output-dir }}
-DCMAKE_CXX_COMPILER=${{ matrix.cpp_compiler }}
-DCMAKE_C_COMPILER=${{ matrix.c_compiler }}
-DCMAKE_BUILD_TYPE=${{ matrix.build_type }}
-S ${{ github.workspace }}
- name: Build
# Build your program with the given configuration. Note that --config is needed because the default Windows generator is a multi-config generator (Visual Studio generator).
run: cmake --build ${{ steps.strings.outputs.build-output-dir }} --config ${{ matrix.build_type }}
- name: Test
working-directory: ${{ steps.strings.outputs.build-output-dir }}
# Execute tests defined by the CMake configuration. Note that --build-config is needed because the default Windows generator is a multi-config generator (Visual Studio generator).
# See https://cmake.org/cmake/help/latest/manual/ctest.1.html for more detail
run: ctest --build-config ${{ matrix.build_type }}

59
.github/workflows/release.yml vendored Normal file
View file

@ -0,0 +1,59 @@
# .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 }}

51
.github/workflows/rust-build.yml vendored Normal file
View file

@ -0,0 +1,51 @@
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

32
.gitignore vendored
View file

@ -1,29 +1,13 @@
# Setup .gitignore as a whitelist
*
!*/
build/**
# track this file
!.gitignore
!.gitattributes
!.gitmodules
!CMakeLists.txt
!/license
!readme.md
!Images/*
!src/**
!res/HarmonyLinkLogo.ico
!Resources/**
!.github/**
!HarmonyLinkLib/**
!HarmonyLinkTest/**
# Blacklist specific build directories
linuxbuild/
build/
.idea/
winbuild/
!Compile.sh
!Compile.bat
HarmonyLinkLib/.vscode/
!Build.rs
!Cargo.toml
!Cargo.lock
!LICENSE
!README.md

0
.gitmodules vendored
View file

View file

@ -1,85 +0,0 @@
# Copyright (c) 2024 Jordon Brooks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
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()
add_compile_definitions($<$<CONFIG:Debug>:DEBUG_MODE>)
#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 HarmonyLinkTestShared)
# 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 Normal file

File diff suppressed because it is too large Load diff

42
Cargo.toml Normal file
View file

@ -0,0 +1,42 @@
[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

@ -1,68 +0,0 @@
@echo off
setlocal enabledelayedexpansion
REM Clear the screen
cls
REM Define the color codes
set GREEN=
set NC=
REM Prompt the user to choose a compiler
echo %GREEN%Select the compiler to use:%NC%
echo 1^ ) MSBuild (default)
echo 2^ ) MinGW
echo 3^ ) Ninja
set /p choice=Enter the number of your choice:
REM Set the generator and compiler based on the user's choice
if "%choice%"=="2" (
set "GENERATOR=MinGW Makefiles"
set "COMPILER_OPTION=-DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++"
) else if "%choice%"=="3" (
set "GENERATOR=Ninja"
set "COMPILER_OPTION="
) else (
set "GENERATOR=Visual Studio 17 2022"
set "COMPILER_OPTION=-A x64"
set "choice=1"
)
echo Using generator: %GENERATOR%
REM Prompt the user to choose a build type
echo %GREEN%Select the build type:%NC%
echo 1^ ) Release (default)
echo 2^ ) Debug
set /p build_choice=Enter the number of your choice:
REM Set the build type based on the user's choice
if "%build_choice%"=="2" (
set "BUILD_TYPE=Debug"
) else (
set "BUILD_TYPE=Release"
)
echo Build type: %BUILD_TYPE%
REM Create the build directory if it doesn't exist
if not exist "winbuild" (
mkdir winbuild
)
cd winbuild
REM Get the number of processors
for /f "tokens=2 delims==" %%a in ('wmic cpu get NumberOfLogicalProcessors /value') do set "NUM_PROCESSORS=%%a"
REM Run CMake with the selected generator and build type
cmake -G "%GENERATOR%" %COMPILER_OPTION% -DCMAKE_BUILD_TYPE=%BUILD_TYPE% ..
REM Build the project
if "%choice%"=="1" (
cmake --build . --config %BUILD_TYPE% -- /m:%NUM_PROCESSORS%
) else (
cmake --build . --config %BUILD_TYPE% -- -j %NUM_PROCESSORS%
)
cd ..

View file

@ -1,127 +0,0 @@
#!/bin/bash
set -e
clear
# Define color codes
GREEN='\033[0;32m'
NC='\033[0m' # No Color
PURPLE='\033[0;35m'
GRAY='\033[1;30m'
# Ensure dialog is installed
if ! command -v dialog &> /dev/null
then
echo "dialog could not be found. Please install it to use this script."
exit
fi
# Function to check if a compiler is installed
check_compiler() {
if command -v $1 &> /dev/null
then
COMPILER_OPTIONS+=("$2" "$3" "$4")
fi
}
# Array to store the menu options
COMPILER_OPTIONS=()
# Add available compilers to the options array
check_compiler g++ "1" "g++ (default)" "on"
check_compiler clang++ "2" "clang++" "off"
check_compiler clang++-15 "3" "clang++ 15" "off"
check_compiler clang++-16 "4" "clang++ 16" "off"
check_compiler clang++-17 "5" "clang++ 17" "off"
# Debug: print the compiler options
echo "Compiler options: ${COMPILER_OPTIONS[@]}"
# Check if any compilers are available
if [ ${#COMPILER_OPTIONS[@]} -eq 0 ]; then
dialog --msgbox "No compilers found. Please install a compiler to use this script." 10 40
exit
fi
# Prompt the user to choose one or more compilers
compiler_choices=$(dialog --colors --title "\Zb\Z5Select Compiler\Zn" --checklist "\nChoose one or more compilers:" 15 60 ${#COMPILER_OPTIONS[@]} "${COMPILER_OPTIONS[@]}" 3>&1 1>&2 2>&3)
# Process the selected compilers
C_COMPILERS=()
CXX_COMPILERS=()
# Debug: print the compiler choices
echo "Compiler choices: $compiler_choices"
for choice in $compiler_choices; do
case $choice in
1)
C_COMPILERS+=("gcc")
CXX_COMPILERS+=("g++")
;;
2)
C_COMPILERS+=("clang")
CXX_COMPILERS+=("clang++")
;;
3)
C_COMPILERS+=("clang-15")
CXX_COMPILERS+=("clang++-15")
;;
4)
C_COMPILERS+=("clang-16")
CXX_COMPILERS+=("clang++-16")
;;
5)
C_COMPILERS+=("clang-17")
CXX_COMPILERS+=("clang++-17")
;;
esac
done
# Output the chosen compilers
msg="Chosen compilers:\n"
for i in "${!C_COMPILERS[@]}"; do
msg+="C compiler: ${C_COMPILERS[$i]}, C++ compiler: ${CXX_COMPILERS[$i]}\n"
done
dialog --colors --msgbox "\Zb\Z5$msg\Zn" 20 60
# Prompt the user to choose a build type
build_choice=$(dialog --colors --title "\Zb\Z5Select Build Type\Zn" --menu "\nChoose a build type:" 10 40 2 \
1 "Release (default)" \
2 "Debug" 3>&1 1>&2 2>&3)
# Set the build type based on the user's choice
case $build_choice in
2)
BUILD_TYPE=Debug
;;
*)
BUILD_TYPE=Release
;;
esac
# Output the chosen build type
dialog --colors --msgbox "\Zb\Z5Build type:\Zn $BUILD_TYPE" 10 40
clear
# Create the build directory if it doesn't exist
if [ ! -d "linuxbuild" ]; then
mkdir linuxbuild
fi
cd linuxbuild
# Run CMake with the selected compilers and build type
for i in "${!C_COMPILERS[@]}"; do
cmake -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCMAKE_C_COMPILER=${C_COMPILERS[$i]} -DCMAKE_CXX_COMPILER=${CXX_COMPILERS[$i]} ..
# Build the project
cmake --build . --config $BUILD_TYPE -j 15 #--clean-first #--verbose
done
cd ..
# End with a success message
dialog --colors --msgbox "\Zb\Z5Build(s) completed successfully!\Zn" 10 40

View file

@ -1,237 +0,0 @@
# Copyright (c) 2024 Jordon Brooks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
cmake_minimum_required(VERSION 3.10)
project(HarmonyLinkLib VERSION 2.1.2 LANGUAGES CXX)
include(FetchContent)
# Fetch fmt library
FetchContent_Declare(
fmt
GIT_REPOSITORY https://github.com/fmtlib/fmt.git
GIT_TAG 10.2.1 # Specify the desired version of {fmt}
)
FetchContent_MakeAvailable(fmt)
set_target_properties(fmt PROPERTIES FOLDER External)
set_target_properties(fmt PROPERTIES POSITION_INDEPENDENT_CODE TRUE)
# Fetch ghc library
FetchContent_Declare(
ghc_filesystem
GIT_REPOSITORY https://github.com/gulrak/filesystem.git
GIT_TAG v1.5.14 # Specify the desired version of ghc
)
FetchContent_MakeAvailable(ghc_filesystem)
set_target_properties(ghc_filesystem PROPERTIES FOLDER External)
set_target_properties(ghc_filesystem PROPERTIES POSITION_INDEPENDENT_CODE TRUE)
# 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)
# Define metadata variables
set(FILE_DESCRIPTION "Enhances handheld gaming with intelligent hardware recognition, dynamic adaptability, and robust API access for Windows and Linux, including Steam Deck and Wine support.")
set(INTERNAL_NAME "HarmonyLinkLib")
set(ORIGINAL_FILENAME "HarmonyLinkLib.dll")
set(PRODUCT_NAME "HarmonyLinkLib")
set(COMMENTS "")
# Configure version.rc file for shared library
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/Resources/Version.rc.in ${CMAKE_CURRENT_BINARY_DIR}/version.rc @ONLY)
# Explicitly list source files
set(COMMON_SOURCES
"src/Platform/IPlatformUtilities.cpp"
"src/HarmonyLinkLib.cpp"
"src/Version.cpp"
"src/Platform/WineUtilities.cpp"
"src/Utilities.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/Enums/ESteamDeck.h"
"include/FString.h"
"include/HarmonyLinkLib.h"
"include/Version.h"
"src/Platform/IPlatformUtilities.h"
"src/Platform/WineUtilities.h"
"src/Utilities.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)
add_definitions(-DBUILD_WINDOWS)
elseif(UNIX)
if(APPLE)
add_definitions(-DBUILD_MACOS)
else()
add_definitions(-DBUILD_LINUX)
endif()
add_definitions(-DBUILD_UNIX)
endif()
# 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})
list(APPEND SHARED_SOURCES ${CMAKE_CURRENT_BINARY_DIR}/version.rc)
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()
# Detect the compiler name
get_filename_component(COMPILER_NAME ${CMAKE_CXX_COMPILER} NAME)
# Replace forbidden characters in file names (optional, if needed)
string(REPLACE "." "_" COMPILER_NAME ${COMPILER_NAME})
string(REPLACE "/" "_" COMPILER_NAME ${COMPILER_NAME})
string(REPLACE "\\" "_" COMPILER_NAME ${COMPILER_NAME})
# Create the shared library
add_library(HarmonyLinkLibShared SHARED ${LIB_SOURCES} ${SHARED_SOURCES} ${LIB_INCLUDES})
target_include_directories(HarmonyLinkLibShared
PRIVATE
"${PROJECT_SOURCE_DIR}/src"
PUBLIC
"${PROJECT_BINARY_DIR}"
"${PROJECT_SOURCE_DIR}/include"
)
target_compile_definitions(HarmonyLinkLibShared PRIVATE HARMONYLINKLIB_SHARED)
set_target_properties(HarmonyLinkLibShared PROPERTIES OUTPUT_NAME "HarmonyLinkLibShared_${COMPILER_NAME}")
# Create the static library
add_library(HarmonyLinkLibStatic STATIC ${LIB_SOURCES} ${LIB_INCLUDES})
target_include_directories(HarmonyLinkLibStatic
PRIVATE
"${PROJECT_SOURCE_DIR}/src"
PUBLIC
"${PROJECT_BINARY_DIR}"
"${PROJECT_SOURCE_DIR}/include"
)
target_compile_definitions(HarmonyLinkLibStatic PRIVATE HARMONYLINKLIB_STATIC)
set_target_properties(HarmonyLinkLibStatic PROPERTIES OUTPUT_NAME "HarmonyLinkLibStatic_${COMPILER_NAME}")
# Set output directories for all build types
#foreach(TYPE IN ITEMS DEBUG RELEASE)
# string(TOUPPER ${TYPE} TYPE_UPPER)
# set_target_properties(HarmonyLinkLibShared PROPERTIES
# RUNTIME_OUTPUT_DIRECTORY_${TYPE_UPPER} "${CMAKE_BINARY_DIR}/bin/${TYPE}/HarmonyLinkLib"
# LIBRARY_OUTPUT_DIRECTORY_${TYPE_UPPER} "${CMAKE_BINARY_DIR}/lib/${TYPE}/HarmonyLinkLib"
# ARCHIVE_OUTPUT_DIRECTORY_${TYPE_UPPER} "${CMAKE_BINARY_DIR}/archive/${TYPE}/HarmonyLinkLib"
# )
# set_target_properties(HarmonyLinkLibStatic PROPERTIES
# ARCHIVE_OUTPUT_DIRECTORY_${TYPE_UPPER} "${CMAKE_BINARY_DIR}/archive/${TYPE}/HarmonyLinkLibStatic"
# )
#endforeach()
# Link fmt to HarmonyLinkLib
target_link_libraries(HarmonyLinkLibStatic PRIVATE fmt::fmt-header-only)
target_link_libraries(HarmonyLinkLibShared PRIVATE fmt::fmt-header-only)
# Link ghc to HarmonyLinkLib
target_link_libraries(HarmonyLinkLibStatic PRIVATE ghc_filesystem)
target_link_libraries(HarmonyLinkLibShared PRIVATE ghc_filesystem)
# Determine the compiler and set appropriate flags for libc++
if (UNIX AND CMAKE_CXX_COMPILER_ID MATCHES "Clang")
# Use libc++ instead of libstdc++ with Clang
target_compile_options(HarmonyLinkLibStatic PRIVATE -stdlib=libc++)
target_compile_options(HarmonyLinkLibShared PRIVATE -stdlib=libc++)
target_link_options(HarmonyLinkLibStatic PRIVATE -stdlib=libc++)
target_link_options(HarmonyLinkLibShared PRIVATE -stdlib=libc++)
# Link against the libc++ library and the filesystem library
target_link_libraries(HarmonyLinkLibStatic PRIVATE c++ c++abi c++experimental)
target_link_libraries(HarmonyLinkLibShared PRIVATE c++ c++abi c++experimental)
elseif (UNIX AND CMAKE_CXX_COMPILER_ID MATCHES "GNU")
# Use libstdc++ with GCC
target_link_options(HarmonyLinkLibStatic PRIVATE -static-libgcc -static-libstdc++)
target_link_options(HarmonyLinkLibShared PRIVATE -static-libgcc -static-libstdc++)
# Link against the libstdc++ filesystem library if necessary
#target_link_libraries(HarmonyLinkLibStatic PRIVATE stdc++fs)
#target_link_libraries(HarmonyLinkLibShared PRIVATE stdc++fs)
endif()

View file

@ -1,49 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <windows.h>
#include <winver.h>
VS_VERSION_INFO VERSIONINFO
FILEVERSION @PROJECT_VERSION_MAJOR@,@PROJECT_VERSION_MINOR@,@PROJECT_VERSION_PATCH@,0
PRODUCTVERSION @PROJECT_VERSION_MAJOR@,@PROJECT_VERSION_MINOR@,@PROJECT_VERSION_PATCH@,0
FILEFLAGSMASK 0x3fL
FILEFLAGS 0x0L
FILEOS VOS_NT_WINDOWS32
FILETYPE VFT_DLL
FILESUBTYPE 0x0L
{
BLOCK "StringFileInfo"
{
BLOCK "040904b0"
{
VALUE "CompanyName", "N/A"
VALUE "FileDescription", "@FILE_DESCRIPTION@"
VALUE "FileVersion", "@PROJECT_VERSION_MAJOR@.@PROJECT_VERSION_MINOR@.@PROJECT_VERSION_PATCH@.0"
VALUE "InternalName", "@INTERNAL_NAME@"
VALUE "OriginalFilename", "@ORIGINAL_FILENAME@"
VALUE "ProductName", "@PRODUCT_NAME@"
VALUE "ProductVersion", "@PROJECT_VERSION_MAJOR@.@PROJECT_VERSION_MINOR@.@PROJECT_VERSION_PATCH@.0"
VALUE "Comments", "@COMMENTS@"
VALUE "LegalCopyright", "N/A"
VALUE "LegalTrademarks", "N/A"
VALUE "PrivateBuild", "N/A"
VALUE "SpecialBuild", "N/A"
}
}
BLOCK "VarFileInfo"
{
VALUE "Translation", 0x409, 1200
}
}

View file

@ -1,38 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
// Use a preprocessor definition to switch between export and import declarations
#ifdef BUILD_WINDOWS
#ifdef HARMONYLINKLIB_STATIC
#define HARMONYLINKLIB_API
#else
#ifdef HARMONYLINKLIB_SHARED
#define HARMONYLINKLIB_API __declspec(dllexport)
#else
#define HARMONYLINKLIB_API __declspec(dllimport)
#endif
#endif
#else
#ifdef HARMONYLINKLIB_SHARED
#ifdef __clang__
#define HARMONYLINKLIB_API __attribute__((visibility("default")))
#else
#define HARMONYLINKLIB_API
#endif
#else
#define HARMONYLINKLIB_API
#endif
#endif

View file

@ -1,37 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
// Undefine the LINUX macro to avoid conflicts with the enum definition.
#undef LINUX
#include <cstdint>
// Enum class for representing different types of devices
namespace HarmonyLinkLib
{
enum class EDevice : uint8_t
{
UNKNOWN,
DESKTOP,
LAPTOP,
HANDHELD,
STEAM_DECK,
// ROG_ALLY
// AYONEO_SLIDE
// etc...
};
}

View file

@ -1,30 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <cstdint>
// Enum class for representing different operating platforms
namespace HarmonyLinkLib
{
enum class EPlatform : uint8_t
{
UNKNOWN,
WINDOWS,
LINUX,
MAC,
UNIX,
};
}

View file

@ -1,29 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <cstdint>
// Enum class for representing different types of devices
namespace HarmonyLinkLib
{
enum class ESteamDeck : uint8_t
{
NONE, // Device is not a steam deck
UNKNOWN, // Device is a steam deck but model cannot be determined
LCD,
OLED,
};
}

View file

@ -1,177 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#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

@ -1,62 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* 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
{
HARMONYLINKLIB_API bool HL_Init();
HARMONYLINKLIB_API bool get_is_wine();
HARMONYLINKLIB_API bool get_is_linux();
HARMONYLINKLIB_API bool get_is_docked();
HARMONYLINKLIB_API FCPUInfo* get_cpu_info();
HARMONYLINKLIB_API FDevice* get_device_info();
HARMONYLINKLIB_API FOSVerInfo* get_os_version();
HARMONYLINKLIB_API FBattery* get_battery_status();
}

View file

@ -1,27 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#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

@ -1,36 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#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

@ -1,54 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#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

@ -1,32 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <HarmonyLinkStruct.h>
#include "Enums/EDevice.h"
#include "Enums/EPlatform.h"
#include "Enums/ESteamDeck.h"
namespace HarmonyLinkLib
{
// Struct to represent a specific device with both platform and device type
struct FDevice : HarmonyLinkStruct
{
EPlatform platform = EPlatform::UNKNOWN;
EDevice device = EDevice::UNKNOWN;
ESteamDeck steam_deck_model = ESteamDeck::NONE;
};
}

View file

@ -1,64 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#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

@ -1,58 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#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

@ -1,25 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// 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

@ -1,137 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "HarmonyLinkLib.h"
#include <iostream>
#include "Platform/IPlatformUtilities.h"
#include "Version.h"
namespace HarmonyLinkLib
{
std::shared_ptr<IPlatformUtilities> PlatformUtilities = nullptr;
bool HL_Init()
{
std::wcout << "HarmonyLink V" << version::ToString().c_str() << " Copyright (C) 2023 Jordon Brooks\n";
PlatformUtilities = IPlatformUtilities::GetInstance();
return PlatformUtilities != nullptr;
}
bool get_is_wine()
{
if (!PlatformUtilities)
{
std::wcout << "Failed to get platform utilities!\n";
return false;
}
return PlatformUtilities->is_running_under_wine();
}
bool get_is_linux()
{
if (!PlatformUtilities)
{
std::wcout << "Failed to get platform utilities!\n";
return false;
}
return PlatformUtilities->is_linux();
}
bool get_is_docked()
{
if (!PlatformUtilities)
{
std::wcout << "Failed to get platform utilities!\n";
return false;
}
return PlatformUtilities->is_docked();
}
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

@ -1,245 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "IPlatformUtilities.h"
#include <fmt/core.h>
#include <set>
#include <unordered_map>
#include "Utilities.h"
#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
}
bool IPlatformUtilities::is_steam_deck()
{
const std::shared_ptr<FDevice> device = get_device();
return device && device->device == EDevice::STEAM_DECK;
}
bool IPlatformUtilities::is_docked()
{
static constexpr uint8_t CHARGING_SCORE = 3;
static constexpr uint8_t EXTERNAL_MONITOR_SCORE = 4;
static constexpr uint8_t STEAM_DECK_RESOLUTION_SCORE = 3;
static constexpr uint8_t KEYBOARD_DETECTION_SCORE = 1;
static constexpr uint8_t MOUSE_DETECTION_SCORE = 2;
static constexpr uint8_t CONTROLLER_DETECTION_SCORE = 3;
static constexpr uint8_t FINAL_TARGET_DETECTION_SCORE = 9;
const std::shared_ptr<FDevice> device = get_device();
if (!device)
{
std::wcout << "Error: failed to get device.\n";
return false;
}
if (device->device != EDevice::STEAM_DECK)
{
std::wcout << "Error: Dock detection is currently only supported on Steam Decks.\n";
return false;
}
uint8_t score = 0;
Utilities::DebugPrint("Detected: ", false);
if (is_charging())
{
Utilities::DebugPrint("Charging, ", false);
score += CHARGING_SCORE;
}
if (get_is_external_monitor_connected())
{
Utilities::DebugPrint("External monitor, ", false);
score += EXTERNAL_MONITOR_SCORE;
}
if (get_is_steam_deck_native_resolution())
{
Utilities::DebugPrint("Non-native resolution, ", false);
score += STEAM_DECK_RESOLUTION_SCORE;
}
if (get_keyboard_detected())
{
Utilities::DebugPrint("keyboard ", false);
score += KEYBOARD_DETECTION_SCORE;
}
if (get_mouse_detected())
{
Utilities::DebugPrint("mouse, ", false);
score += MOUSE_DETECTION_SCORE;
}
if (get_external_controller_detected())
{
Utilities::DebugPrint("external controller, ", false);
score += CONTROLLER_DETECTION_SCORE;
}
Utilities::DebugPrint(fmt::format("Score: {}/{}", score, FINAL_TARGET_DETECTION_SCORE).c_str());
return score >= FINAL_TARGET_DETECTION_SCORE;
}
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;
}
const ESteamDeck steam_deck_model = detect_steam_deck(new_device);
if (steam_deck_model != ESteamDeck::NONE) {
new_device.device = EDevice::STEAM_DECK;
new_device.steam_deck_model = steam_deck_model;
}
return std::make_shared<FDevice>(new_device);
}
// Helper function to check if the device is a Steam Deck
ESteamDeck IPlatformUtilities::detect_steam_deck(const FDevice& device) {
// Check if the device is already identified as a Steam Deck
if (device.device == EDevice::STEAM_DECK && device.steam_deck_model != ESteamDeck::NONE) {
return device.steam_deck_model;
}
ESteamDeck steam_deck_model = ESteamDeck::NONE;
// Retrieve and process CPU information
const std::shared_ptr<FCPUInfo> cpu_info = get_cpu_info();
if (!cpu_info) {
wprintf(L"CPU information not available.\n");
} else {
// Convert the CPU model name to lower case once
FString cpu_model_lower = FString::to_lower(cpu_info->Model_Name);
// Map of CPU models to their corresponding Steam Deck models
static const std::unordered_map<FString, ESteamDeck> model_map = {
{FString::to_lower("amd custom apu 0405"), ESteamDeck::LCD},
{FString::to_lower("amd custom apu 0932"), ESteamDeck::OLED}
};
auto iterator = model_map.find(cpu_model_lower);
if (iterator != model_map.end()) {
steam_deck_model = iterator->second;
wprintf(L"Steam Deck detected by CPU model name: %hs.\n", cpu_model_lower.c_str());
}
}
// Check for Steam Deck by OS version only if no model has been detected yet
if (steam_deck_model == ESteamDeck::NONE)
{
if (const std::shared_ptr<FOSVerInfo> version = get_os_version())
{
if (version->variant_id == "steamdeck" && version->name == "SteamOS")
{
// Use UNKNOWN if OS matches but CPU model doesn't fit known profiles
steam_deck_model = ESteamDeck::UNKNOWN;
wprintf(L"Steam Deck OS detected but model is unknown.\n");
}
}
else
{
wprintf(L"OS version information not available.\n");
}
}
return steam_deck_model;
}
bool IPlatformUtilities::is_connected_to_ac()
{
const std::shared_ptr<FBattery> battery = get_battery_status();
return battery && battery->is_connected_to_ac;
}
bool IPlatformUtilities::is_charging()
{
const std::shared_ptr<FBattery> battery = get_battery_status();
return battery && battery->has_battery && battery->is_connected_to_ac;
}
}

View file

@ -1,60 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "Enums/ESteamDeck.h"
#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 bool is_steam_deck();
virtual bool is_docked();
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;
virtual bool get_is_external_monitor_connected() = 0;
virtual bool get_keyboard_detected() = 0;
virtual bool get_mouse_detected() = 0;
virtual bool get_external_controller_detected() = 0;
virtual bool get_is_steam_deck_native_resolution() = 0;
//virtual bool get_is_ethernet_connected() = 0;
//virtual bool get_is_external_input_detected() = 0;
ESteamDeck detect_steam_deck(const FDevice& device);
bool is_connected_to_ac();
bool is_charging();
// Add more virtual functions for other OS interactions here
};
}

View file

@ -1,38 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#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

@ -1,37 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#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

@ -1,20 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "MacUtilities.h"
namespace HarmonyLinkLib
{
}

View file

@ -1,25 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "Platform/Unix/UnixUtilities.h"
namespace HarmonyLinkLib
{
class MacUtitities : public UnixUtilities {
public:
// Mac-specific overrides and additional functionality
};
}

View file

@ -1,72 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "UnixUtilities.h"
namespace HarmonyLinkLib
{
bool UnixUtilities::is_running_under_wine()
{
std::wcout << "This feature is not supported on unix systems yet.\n";
return false;
}
std::shared_ptr<FCPUInfo> UnixUtilities::get_cpu_info()
{
std::wcout << "This feature is not supported on unix systems yet.\n";
return nullptr;
}
std::shared_ptr<FBattery> UnixUtilities::get_battery_status()
{
std::wcout << "This feature is not supported on unix systems yet.\n";
return nullptr;
}
std::shared_ptr<FOSVerInfo> UnixUtilities::get_os_version()
{
std::wcout << "This feature is not supported on unix systems yet.\n";
return nullptr;
}
bool UnixUtilities::get_is_external_monitor_connected()
{
std::wcout << "This feature is not supported on unix-based systems yet.\n";
return false;
}
bool UnixUtilities::get_keyboard_detected()
{
std::wcout << "This feature is not supported on unix-based systems yet.\n";
return false;
}
bool UnixUtilities::get_mouse_detected()
{
std::wcout << "This feature is not supported on unix-based systems yet.\n";
return false;
}
bool UnixUtilities::get_external_controller_detected()
{
std::wcout << "This feature is not supported on unix-based systems yet.\n";
return false;
}
bool UnixUtilities::get_is_steam_deck_native_resolution()
{
std::wcout << "This feature is not supported on unix-based systems yet.\n";
return false;
}
}

View file

@ -1,42 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "Platform/IPlatformUtilities.h"
namespace HarmonyLinkLib
{
// This is more of a "catch all" for all unix-based systems
// that don't have their own implementations.
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;
bool get_is_external_monitor_connected() override;
bool get_keyboard_detected() override;
bool get_mouse_detected() override;
bool get_external_controller_detected() override;
bool get_is_steam_deck_native_resolution() override;
// Implementation for other Unix/Linux-specific functions
};
}

View file

@ -1,177 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "WindowsUtilities.h"
#include <sstream>
#include <Windows.h>
#include <XInput.h>
#pragma comment(lib, "XInput.lib")
#include "Platform/WineUtilities.h"
#include <algorithm>
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);
}
bool WindowsUtilities::get_is_external_monitor_connected()
{
// SM_CMONITORS returns the count of all display monitors.
const int monitorCount = GetSystemMetrics(SM_CMONITORS);
// More than one monitor implies an external monitor is connected.
return monitorCount > 1;
}
bool WindowsUtilities::get_keyboard_detected()
{
UINT n_devices;
std::vector<RAWINPUTDEVICELIST> devices;
GetRawInputDeviceList(devices.data(), &n_devices, sizeof(RAWINPUTDEVICELIST));
if (n_devices == 0)
{
return false;
}
return std::any_of(devices.begin(), devices.end(), [](const RAWINPUTDEVICELIST& device)
{
return device.dwType == RIM_TYPEKEYBOARD;
});
}
bool WindowsUtilities::get_mouse_detected()
{
UINT n_devices;
std::vector<RAWINPUTDEVICELIST> devices;
GetRawInputDeviceList(devices.data(), &n_devices, sizeof(RAWINPUTDEVICELIST));
if (n_devices == 0)
{
return false;
}
return std::any_of(devices.begin(), devices.end(), [](const RAWINPUTDEVICELIST& device)
{
return device.dwType == RIM_TYPEMOUSE;
});
}
bool WindowsUtilities::get_external_controller_detected()
{
static_assert(XUSER_MAX_COUNT <= UINT8_MAX, "XUSER_MAX_COUNT exceeds uint8_t size");
uint8_t connectedGamepads = 0;
for (DWORD i = 0; i < XUSER_MAX_COUNT; ++i) {
XINPUT_STATE state;
ZeroMemory(&state, sizeof(XINPUT_STATE));
if (XInputGetState(i, &state) == ERROR_SUCCESS) {
connectedGamepads++;
}
}
return connectedGamepads > 1;
}
bool WindowsUtilities::get_is_steam_deck_native_resolution()
{
DEVMODE devMode;
devMode.dmSize = sizeof(DEVMODE);
// Get the current display settings for the primary monitor
if (EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &devMode)) {
// Check if the resolution is higher than 800p (1280x800)
if (devMode.dmPelsWidth > 1280 || devMode.dmPelsHeight > 800) {
return true;
}
}
return false;
}
}

View file

@ -1,40 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#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;
bool get_is_external_monitor_connected() override;
bool get_keyboard_detected() override;
bool get_mouse_detected() override;
bool get_external_controller_detected() override;
bool get_is_steam_deck_native_resolution() override;
};
}

View file

@ -1,218 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "WineUtilities.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include <unordered_map>
#include <ghc/filesystem.hpp>
#ifdef BUILD_WINDOWS
#include <windows.h>
#endif
namespace fs = ghc::filesystem;
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); fs::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

@ -1,60 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#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

@ -1,53 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "Utilities.h"
#include <iostream>
#include "FString.h"
void HarmonyLinkLib::Utilities::DebugPrint(const FString& String, bool AddNewline)
{
#ifdef DEBUG_MODE
std::wcout << String.c_str();
if (AddNewline)
{
std::wcout << L"\n";
}
#endif
}
void HarmonyLinkLib::Utilities::DebugPrint(const char* String, bool AddNewline)
{
#ifdef DEBUG_MODE
std::wcout << std::wstring(String, String + std::strlen(String));
if (AddNewline) {
std::wcout << L"\n";
}
#endif
}
void HarmonyLinkLib::Utilities::DebugPrint(const wchar_t* String, bool AddNewline)
{
#ifdef DEBUG_MODE
std::wcout << String;
if (AddNewline) {
std::wcout << L"\n";
}
#endif
}

View file

@ -1,30 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include "HarmonyLinkLib.h"
namespace HarmonyLinkLib
{
class FString;
class Utilities
{
public:
static void DebugPrint(const FString& String, bool AddNewline = true);
static void DebugPrint(const char* String, bool AddNewline = true);
static void DebugPrint(const wchar_t* String, bool AddNewline = true);
};
}

View file

@ -1,15 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "Version.h"

View file

@ -1,58 +0,0 @@
# Copyright (c) 2024 Jordon Brooks
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
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 for static library
add_executable(HarmonyLinkTestStatic ${TEST_SOURCES} ${TEST_HEADERS})
target_link_libraries(HarmonyLinkTestStatic PRIVATE HarmonyLinkLibStatic)
target_compile_definitions(HarmonyLinkTestStatic PRIVATE HARMONYLINKLIB_STATIC)
# Add executable for shared library
add_executable(HarmonyLinkTestShared ${TEST_SOURCES} ${TEST_HEADERS})
target_link_libraries(HarmonyLinkTestShared PRIVATE HarmonyLinkLibShared)
target_compile_definitions(HarmonyLinkTestShared PRIVATE HARMONYLINKLIB_SHARED)
# Set output directories for all build types
foreach(TYPE IN ITEMS DEBUG RELEASE)
string(TOUPPER ${TYPE} TYPE_UPPER)
# Static test executable properties
set_target_properties(HarmonyLinkTestStatic PROPERTIES
RUNTIME_OUTPUT_DIRECTORY_${TYPE_UPPER} "${CMAKE_BINARY_DIR}/bin/${TYPE}/HarmonyLinkTestStatic"
LIBRARY_OUTPUT_DIRECTORY_${TYPE_UPPER} "${CMAKE_BINARY_DIR}/lib/${TYPE}/HarmonyLinkTestStatic"
ARCHIVE_OUTPUT_DIRECTORY_${TYPE_UPPER} "${CMAKE_BINARY_DIR}/archive/${TYPE}/HarmonyLinkTestStatic"
)
# Shared test executable properties
set_target_properties(HarmonyLinkTestShared PROPERTIES
RUNTIME_OUTPUT_DIRECTORY_${TYPE_UPPER} "${CMAKE_BINARY_DIR}/bin/${TYPE}/HarmonyLinkTestShared"
LIBRARY_OUTPUT_DIRECTORY_${TYPE_UPPER} "${CMAKE_BINARY_DIR}/lib/${TYPE}/HarmonyLinkTestShared"
ARCHIVE_OUTPUT_DIRECTORY_${TYPE_UPPER} "${CMAKE_BINARY_DIR}/archive/${TYPE}/HarmonyLinkTestShared"
)
endforeach()
# Copy the DLL to the executable directory after building the shared test executable
add_custom_command(TARGET HarmonyLinkTestShared POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
"$<TARGET_FILE:HarmonyLinkLibShared>"
"$<TARGET_FILE_DIR:HarmonyLinkTestShared>")

View file

@ -1,169 +0,0 @@
// Copyright (c) 2024 Jordon Brooks
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#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);
if (!HarmonyLinkLib::HL_Init())
{
std::cout << "Failed to init HarmonyLinkLib\n";
return 1;
}
std::cout << "HarmonyLinkLib successfully initialised!\n";
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();
}
const bool is_docked = HarmonyLinkLib::get_is_docked();
const char* dock_check_string = is_docked ? "is" : "isn't";
wprintf(L"Device %hs docked\n", dock_check_string);
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;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 501 KiB

811
LICENSE
View file

@ -1,201 +1,674 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
1. Definitions.
Preamble
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
The precise terms and conditions for copying, distribution and
modification follow.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
TERMS AND CONDITIONS
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
0. Definitions.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
"This License" refers to version 3 of the GNU General Public License.
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
A "covered work" means either the unmodified Program or a work based
on the Program.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
1. Source Code.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
END OF TERMS AND CONDITIONS
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
APPENDIX: How to apply the Apache License to your work.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
Copyright [yyyy] [name of copyright owner]
The Corresponding Source for a work in source code form is that
same work.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
2. Basic Permissions.
http://www.apache.org/licenses/LICENSE-2.0
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 3 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, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

148
README.md
View file

@ -2,121 +2,109 @@
<img src="Images/HarmonyLinkLogo.png" alt="HarmonyLinkLogo"/>
</p>
Welcome to HarmonyLink 2.0. This iteration represents a leap forward in enhancing the handheld gaming experience, now re-engineered as a C++ dynamic link library (DLL) for seamless integration directly into games.
Welcome to the server-side application for the HarmonyLink project. This innovative software is developed with the Rust programming language and is aimed at enhancing the handheld gaming experience.
## Table of Contents
- [Shaping the Vision, Living the Reality](#shaping-the-vision,-living-the-reality)
- [Key Features](#key-features)
- [HarmonyLink in Action](#harmonylink-in-action)
- [Integration Guide](#integration-guide)
- [For Game Developers](#for-game-developers)
- [Unreal Engine 5 Plugin](#unreal-engine-5-plugin)
- [Building From Source](#building-from-source)
- [Using the Program](#using-the-program)
- [Windows Users](#windows-users)
- [Steam Deck (Linux) Users](#steam-deck-linux-users)
- [How It Works](#how-it-works)
- [Getting Started](https://github.com/Jordonbc/HarmonyLink/wiki/Getting-Started)
- [Getting Started](https://github.com/Jordonbc/HarmonyLinkServer/wiki/Getting-Started)
- [HarmonyLink: View](#harmonylink-view)
- [Showcasing HarmonyLink](#showcasing-harmonylink)
- [Frequently Asked Questions (FAQ)](#frequently-asked-questions-faq)
- [Contributing](#contributing)
- [License](#license)
## Shaping the Vision, Living the Reality
HarmonyLink is on a mission to transform handheld gaming by providing an interactive experience. This server-side application is at the heart of making this vision a reality.
## Key Features
- **Intelligent Hardware Recognition**: HarmonyLink 2.0 can accurately identify specific devices like the Steam Deck without relying on manual environment variables or command line arguments.
- **Robust API**: The API provided by HarmonyLink 2.0 offers developers straightforward and effortless access to detailed system information. Designed with intuitiveness in mind, it allows for rapid integration into projects, minimizing development overhead.
1. **Device Identification**: HarmonyLink equips games with the ability to identify the specific handheld device they are operating on.
2. **Real-Time Metrics**: Games can access real-time data about the handheld device's power usage and docking status through HarmonyLink.
3. **Cross-Platform Compatibility**: HarmonyLink extends its functionality to Windows games running on Proton/Wine.
- **Enhanced Adaptability**: With the ability to dynamically adjust game settings and performance based on detected hardware capabilities and current operating conditions, HarmonyLink 2.0 ensures games are optimized for each specific device.
## Using HarmonyLinkServer
- **Wine Environment Detection**: HarmonyLink 2.0 includes mechanisms to detect when it is running within a Wine environment, enabling it to deliver system information about the underlying Linux system while operating through Wine.
For users who wish to run the precompiled release version of HarmonyLinkServer, please follow the instructions specific to your platform below.
- **Precise Steam Deck Hardware Detection**: Unlike conventional methods that may rely on environment variables, HarmonyLink 2.0 detects the presence of Steam Deck hardware directly, ensuring reliable identification and optimization for this specific device.
### Windows Users
- **Battery and Charging Status Awareness**: The software provides real-time data on battery levels and charging status, allowing games to adapt their behavior based on power availability and to manage resource usage effectively.
1. Navigate to the [latest release](https://github.com/Jordonbc/HarmonyLinkServer/releases/latest) on the project's GitHub page.
2. Download the `.zip` archive for Windows.
3. Extract the contents of the `.zip` archive to a directory of your choice.
4. Open a command prompt in the directory where you extracted the files.
5. Run the HarmonyLinkServer executable by typing `./harmony_link_server.exe`.
- **Cross-Platform Functionality**: HarmonyLink 2.0 is designed to work on Windows (including Wine environments) as well as natively on Linux, offering broad support for a variety of gaming setups.
Please note that you'll need to manually start the program each time you want to use it.
- **Unreal Engine 5 Compatibility**: HarmonyLink 2.0 comes with full support for Unreal Engine 5, making it a versatile tool for developers working with one of the most advanced game engines in the industry.
### Steam Deck (Linux) Users
## HarmonyLink in Action
1. Navigate to the [latest release](https://github.com/Jordonbc/HarmonyLinkServer/releases/latest) on the project's GitHub page.
2. Download the `.zip` archive for Linux.
3. Extract the contents of the `.zip` archive to a directory of your choice.
Experience the capabilities of HarmonyLink: Legacy (June 2023 version) with our demonstration:
#### Running in Desktop Mode
<h3 align="center" style="font-size: 16pt;"> Video below ⬇️</h3>
To use HarmonyLinkServer in Desktop Mode, follow these steps:
<p align="center">
<a href="https://www.youtube.com/watch?v=qU3w_fo4nY4"><img src="https://img.youtube.com/vi/qU3w_fo4nY4/0.jpg" alt="HarmonyLinkExample" height="480"/></a>
</p>
1. Open a terminal in the directory where you extracted the files.
2. Run the HarmonyLinkServer executable by typing `./harmony_link_server`.
<p align="center">
<br><br><br>
<img src="Images/SteamDeckExample.jpg" alt="HarmonyLinkExample" height="480"/>
</p>
Please note that you'll need to keep the terminal window open while using HarmonyLinkServer in desktop mode.
The picture above shows a packaged Win64 (exe) Shipping build of a UE5 project with the HarmonyLink plugin enabled running via Proton. Widgets were added to the viewport to display these values. The values are updated on tick, with no noticable performance loss.
As you can see, Even though it's running on Proton, we can still detect the underlying system specifications.
## Integration Guide
### For Game Developers
Integrate HarmonyLink 2.0 into your game project with ease:
1. Download the latest version of HarmonyLink 2.0 from the [releases page](https://git.bbgames.dev/jordon/HarmonyLink/releases/latest).
2. Add the HarmonyLink DLL to your project according to your development environment's specifications.
3. Utilize the provided API to access device-specific metrics and enhance your game's performance on handheld devices.
Refer to the [integration documentation](https://git.bbgames.dev/jordon/HarmonyLink/wiki) for detailed instructions.
### Unreal Engine 5 Plugin
For developers leveraging Unreal Engine 5.3 or newer*, HarmonyLink 2.0 is readily accessible as a plugin:
1. Clone or download the HarmonyLink UE5 Plugin from the [Unreal Engine Plugin repository](https://git.bbgames.dev/jordon/HarmonyLinkUE).
2. Place the HarmonyLink plugin folder into the `Plugins` directory of your Unreal Engine 5 project.
3. Enable the HarmonyLink plugin from the Edit > Plugins menu within Unreal Engine 5.
4. Access HarmonyLink functionalities via Blueprints or C++ within your project.
For a step-by-step guide, visit the [Unreal Engine 5 Plugin instructions](https://git.bbgames.dev/jordon/HarmonyLinkUE/wiki) on our wiki.
*With potential backward compatibility, not verified.
## Building From Source
If you prefer to build HarmonyLink 2.0 from the source code, follow these steps:
1. Clone the repository using `git clone https://github.com/Jordonbc/HarmonyLink.git`.
2. Navigate into the cloned directory with `cd HarmonyLink`.
3. Ensure CMake is installed and up-to-date on your system.
4. Generate the build configuration with `cmake -S . -B build`.
5. Compile the code by running `cmake --build build --config Release`.
6. The built DLL will be located in the `build/bin/HarmonyLinkLib` directory.
For additional building options and troubleshooting, refer to the [building from source documentation](https://git.bbgames.dev/jordon/HarmonyLink/wiki).
#### Optional: Setting Up as a Service for Gamemode
For a seamless experience in gamemode, you have the option to set up HarmonyLinkServer as a service on your Steam Deck. Please be aware that this setup process will require a moderate level of technical knowledge.
## How It Works
HarmonyLink 2.0 functions without the need for a separate server application. The DLL is integrated directly into the game, providing a conduit between the game and the device hardware for real-time metrics and enhanced performance adaptability.
HarmonyLink operates using a client-server structure. This server-side application runs on the host side (native Linux or Windows), and games access the metrics via an API.
Developers and modders can easily implement GET and POST requests from the API, integrating system metrics into games. These metrics can be used to adapt the game's quality settings, providing a more customized gaming experience.
## HarmonyLink: View
To view the API in action, check out [HarmonyLink: View](https://github.com/Jordonbc/HarmonyLinkView). This sister project provides a comprehensive interface to see what data the API is providing.
## Showcasing HarmonyLink
👇 To help visualize its functionality, we've included a demonstration video that showcases HarmonyLink in action on a Steam Deck in gamemode.
[![HarmonyLink in action](https://img.youtube.com/vi/qU3w_fo4nY4/0.jpg)](https://www.youtube.com/watch?v=qU3w_fo4nY4)
## Contributing Guidelines
Please refer to our [Contributing Guidelines](CONTRIBUTING.md) for detailed information on how to contribute to HarmonyLinkServer. It includes instructions for bug reports, feature requests, and pull requests.
We appreciate your interest in improving HarmonyLinkServer and look forward to your contributions!
## Frequently Asked Questions (FAQ)
- **What new capabilities does HarmonyLink 2.0 bring?**
HarmonyLink 2.0 offers a streamlined, more efficient way for games to interact with handheld hardware, now as a C++ DLL for easy integration without the need for server-side components.
### Q1: What platforms are supported by HarmonyLink?
- **How can developers integrate HarmonyLink 2.0 into their games?**
Developers can include HarmonyLink 2.0 in their projects by adding the DLL and making API calls as needed. Detailed instructions are available on our wiki.
A: HarmonyLink supports both native Linux and Windows platforms, and extends its functionality to Windows games running on Proton/Wine.
- **Does HarmonyLink 2.0 support Proton/Wine?**
Yes, it includes workarounds and functionalities tailored for games running in Proton/Wine environments.
### Q2: How can I get started with HarmonyLink?
- **Does HarmonyLink 2.0 rely `STEAM_DECK=1`?**
A: You can start by cloning the HarmonyLinkServer repository. Detailed instructions are provided on the [Getting Started](https://github.com/Jordonbc/HarmonyLinkServer/wiki/Getting-Started) wiki page.
No, HarmonyLink 2.0 does not rely on the `STEAM_DECK=1` environment variable. Instead, it employs advanced hardware detection techniques to accurately identify the presence of specific devices, such as the Steam Deck. This direct detection method ensures reliable performance optimization tailored to the actual hardware, independent of any user-modified environment settings.
### Q3: Can HarmonyLink be used with games developed in different game engines?
## Contributing
A: Yes, HarmonyLink is designed to be engine-agnostic and can be used with games developed in different engines. For Unreal Engine, there is a specific [Unreal Engine Plugin](https://github.com/Jordonbc/HarmonyLinkUE) available.
Your contributions make HarmonyLink better. Please review our [Contributing Guidelines](CONTRIBUTING.md) for information on submitting pull requests and helping with development.
### Q4: Is HarmonyLink only for game developers, or can players also use it?
A: While game developers will find HarmonyLink particularly useful for optimizing their games for handheld devices, players can also benefit from the enhanced gaming experience that HarmonyLink provides.
### Q5: Does HarmonyLink have any impact on the performance of the games?
A: HarmonyLink is designed to be lightweight and efficient, with minimal impact on game performance. The primary purpose of HarmonyLink is to enhance game performance by allowing games to adapt their settings based on real-time device metrics.
## License
HarmonyLink 2.0 is released under the GNU General Public License v3.0 or later. See the [LICENSE](LICENSE) file for details.
This project is licensed under the GNU General Public License v3.0 or later. Please do not redistribute HarmonyLinkServer. e.g.: Proving an alternative download link or distributing with a game.

View file

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

72
build.rs Normal file
View file

@ -0,0 +1,72 @@
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(())
}

14
src/api/api.rs Normal file
View file

@ -0,0 +1,14 @@
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...
}

99
src/api/endpoints_v1.rs Normal file
View file

@ -0,0 +1,99 @@
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...
}

3
src/api/mod.rs Normal file
View file

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

28
src/api/server.rs Normal file
View file

@ -0,0 +1,28 @@
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)
}

37
src/main.rs Normal file
View file

@ -0,0 +1,37 @@
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;
});
}

2
src/v1/all_info/mod.rs Normal file
View file

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

18
src/v1/all_info/stats.rs Normal file
View file

@ -0,0 +1,18 @@
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

@ -0,0 +1,24 @@
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")
}
}

2
src/v1/battery/mod.rs Normal file
View file

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

38
src/v1/battery/stats.rs Normal file
View file

@ -0,0 +1,38 @@
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)
}

28
src/v1/battery/structs.rs Normal file
View file

@ -0,0 +1,28 @@
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")
}
}

2
src/v1/docking/mod.rs Normal file
View file

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

90
src/v1/docking/stats.rs Normal file
View file

@ -0,0 +1,90 @@
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())
}

39
src/v1/docking/structs.rs Normal file
View file

@ -0,0 +1,39 @@
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")
}
}

4
src/v1/mod.rs Normal file
View file

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

2
src/v1/os/mod.rs Normal file
View file

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

45
src/v1/os/stats.rs Normal file
View file

@ -0,0 +1,45 @@
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)
}

38
src/v1/os/structs.rs Normal file
View file

@ -0,0 +1,38 @@
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")
}
}

41
src/version/info.rs Normal file
View file

@ -0,0 +1,41 @@
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(", ")
}
}

1
src/version/mod.rs Normal file
View file

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