Good stuff

This commit is contained in:
Luke Street
2026-09-10 01:11:06 -06:00
parent b84f8f56de
commit a7171c1956
64 changed files with 2626 additions and 1271 deletions
+9 -1
View File
@@ -223,6 +223,14 @@ if (DUSK_HAS_FUNCHOOK)
endif ()
FetchContent_MakeAvailable(${_fetch_content_deps})
if (DUSK_HAS_FUNCHOOK AND APPLE)
target_sources(funchook-static PRIVATE src/dusk/mods/loader/code_patch_macos.cpp)
target_include_directories(funchook-static PRIVATE src/dusk/mods/loader)
set_source_files_properties(src/dusk/mods/loader/code_patch_macos.cpp
TARGET_DIRECTORY funchook-static PROPERTIES
COMPILE_OPTIONS "-O2;-fno-sanitize=all;-fno-stack-protector")
endif ()
# Use signed char on ARM to match the original game (and x86)
string(TOLOWER "${CMAKE_SYSTEM_PROCESSOR}" _arch)
if(_arch MATCHES "^(arm|aarch64)" AND CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "GNU")
@@ -249,7 +257,7 @@ find_package(Threads REQUIRED)
set(GAME_COMPILE_DEFS DUSK_BUILDING_GAME=1)
set(GAME_LIBS aurora::core aurora::gx aurora::gd aurora::si aurora::vi aurora::pad aurora::mtx aurora::os aurora::dvd aurora::thp
aurora::card borealis::http borealis::cli borealis::crash borealis::data borealis::disc borealis::discord borealis::file_select borealis::io borealis::log borealis::net borealis::presentation borealis::sentry borealis::update borealis::ws freeverb cxxopts::cxxopts absl::flat_hash_map nlohmann_json::nlohmann_json TracyClient fmt::fmt
Threads::Threads zstd::libzstd dusklight_game_headers picosha2)
Threads::Threads zstd::libzstd dusklight_game_headers picosha2 PNG::PNG)
if (DUSK_HAS_FUNCHOOK)
list(APPEND GAME_LIBS funchook-static)
endif ()
+49 -53
View File
@@ -2,59 +2,55 @@ file(READ "${SOURCE_DIR}/cmake/capstone.cmake.in" _content)
# Insert PATCH_COMMAND before CONFIGURE_COMMAND in the ExternalProject_Add.
# Bracket args prevent cmake from substituting ${...} while writing this file.
string(REPLACE
" CONFIGURE_COMMAND \"\""
[=[ PATCH_COMMAND "${CMAKE_COMMAND}" -DDIR=${CMAKE_CURRENT_BINARY_DIR}/capstone-src -P "${CAPSTONE_FIX_SCRIPT}"
if (NOT _content MATCHES "CAPSTONE_FIX_SCRIPT")
string(REPLACE
" CONFIGURE_COMMAND \"\""
[=[ PATCH_COMMAND "${CMAKE_COMMAND}" -DDIR=${CMAKE_CURRENT_BINARY_DIR}/capstone-src -P "${CAPSTONE_FIX_SCRIPT}"
CONFIGURE_COMMAND ""]=]
_content "${_content}")
file(WRITE "${SOURCE_DIR}/cmake/capstone.cmake.in" "${_content}")
file(READ "${SOURCE_DIR}/src/funchook_unix.c" _unix_content)
# macOS rejects the POSIX mprotect RWX/RW transition for executable image pages on arm64.
# Use Mach VM_PROT_COPY for the short patch window, then restore RX permissions.
if (NOT _unix_content MATCHES "VM_PROT_READ \\| VM_PROT_WRITE \\| VM_PROT_COPY")
string(REPLACE
[=[ rv = mprotect(mstate->addr, mstate->size, prot);]=]
[=[#ifdef __APPLE__
kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)mstate->addr,
(vm_size_t)mstate->size, FALSE,
VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY);
if (kr == KERN_SUCCESS) {
funchook_log(funchook, " unprotect memory %p (size=%"PRIuPTR", prot=read,write,copy) <- %p (size=%"PRIuPTR")\n",
mstate->addr, mstate->size, start, len);
return 0;
}
funchook_set_error_message(funchook, "Failed to unprotect memory %p (size=%"PRIuPTR", prot=read,write,copy) <- %p (size=%"PRIuPTR", error=%s)",
mstate->addr, mstate->size, start, len,
mach_error_string(kr));
return FUNCHOOK_ERROR_MEMORY_FUNCTION;
#endif
rv = mprotect(mstate->addr, mstate->size, prot);]=]
_unix_content "${_unix_content}")
string(REPLACE
[=[ char errbuf[128];
int rv = mprotect(mstate->addr, mstate->size, PROT_READ | PROT_EXEC);]=]
[=[ char errbuf[128];
#ifdef __APPLE__
kern_return_t kr = vm_protect(mach_task_self(), (vm_address_t)mstate->addr,
(vm_size_t)mstate->size, FALSE,
VM_PROT_READ | VM_PROT_EXECUTE);
if (kr == KERN_SUCCESS) {
funchook_log(funchook, " protect memory %p (size=%"PRIuPTR", prot=read,exec)\n",
mstate->addr, mstate->size);
return 0;
}
funchook_set_error_message(funchook, "Failed to protect memory %p (size=%"PRIuPTR", prot=read,exec, error=%s)",
mstate->addr, mstate->size,
mach_error_string(kr));
return FUNCHOOK_ERROR_MEMORY_FUNCTION;
#endif
int rv = mprotect(mstate->addr, mstate->size, PROT_READ | PROT_EXEC);]=]
_unix_content "${_unix_content}")
_content "${_content}")
file(WRITE "${SOURCE_DIR}/cmake/capstone.cmake.in" "${_content}")
endif ()
file(WRITE "${SOURCE_DIR}/src/funchook_unix.c" "${_unix_content}")
file(READ "${SOURCE_DIR}/src/funchook.c" _content)
if (NOT _content MATCHES "commit_code_patch")
string(REPLACE "#include \"funchook_internal.h\""
"#include \"funchook_internal.h\"\n#ifdef __APPLE__\n#include \"code_patch_macos.hpp\"\n#endif"
_content "${_content}")
foreach(_operation install uninstall)
if (_operation STREQUAL "install")
set(_expected old_code)
set(_replacement new_code)
else ()
set(_expected new_code)
set(_replacement old_code)
endif ()
set(_original " mem_state_t mstate;
int rv = funchook_unprotect_begin(funchook, &mstate, entry->target_func, JUMP32_BYTE_SIZE);
if (rv != 0) {
return rv;
}
memcpy(entry->target_func, entry->${_replacement}, JUMP32_BYTE_SIZE);
rv = funchook_unprotect_end(funchook, &mstate);
if (rv != 0) {
return rv;
}
flush_instruction_cache(entry->target_func, JUMP32_BYTE_SIZE);")
string(FIND "${_content}" "${_original}" _position)
if (_position EQUAL -1)
message(FATAL_ERROR "Funchook ${_operation} patch site changed")
endif ()
string(REPLACE "${_original}" "#ifdef __APPLE__
int rv = commit_code_patch(entry->target_func, entry->${_expected},
entry->${_replacement}, JUMP32_BYTE_SIZE);
if (rv != 0) {
funchook_set_error_message(funchook, \"Code patch commit failed (Mach error %d)\", rv);
return FUNCHOOK_ERROR_MEMORY_FUNCTION;
}
#else
${_original}
#endif" _content "${_content}")
endforeach ()
file(WRITE "${SOURCE_DIR}/src/funchook.c" "${_content}")
endif ()
+12
View File
@@ -1484,6 +1484,12 @@ set(DUSK_FILES
src/dusk/mods/loader/depgraph.hpp
src/dusk/mods/loader/loader.cpp
src/dusk/mods/loader/loader.hpp
src/dusk/mods/loader/manifest.cpp
src/dusk/mods/loader/manifest.hpp
src/dusk/mods/loader/natives.cpp
src/dusk/mods/loader/natives.hpp
src/dusk/mods/loader/packages.cpp
src/dusk/mods/loader/packages.hpp
src/dusk/mods/loader/native_module.cpp
src/dusk/mods/loader/native_module.hpp
src/dusk/mods/loader/prepatch.cpp
@@ -1601,6 +1607,12 @@ set(DUSK_FILES
src/dusk/ui/nav_types.hpp
src/dusk/ui/nav_group.cpp
src/dusk/ui/nav_group.hpp
src/dusk/ui/context_menu.cpp
src/dusk/ui/context_menu.hpp
src/dusk/ui/icon_button.cpp
src/dusk/ui/icon_button.hpp
src/dusk/ui/tooltip.cpp
src/dusk/ui/tooltip.hpp
src/dusk/ui/number_button.cpp
src/dusk/ui/number_button.hpp
src/dusk/ui/overlay.cpp
+36 -33
View File
@@ -118,10 +118,9 @@ catalog-card-art {
position: relative;
flex: 0 0 118dp;
min-height: 118dp;
background-color: rgba(var(--color-border-rgb), 12%);
}
catalog-card-art-shadow {
catalog-card-art-image {
display: block;
position: absolute;
top: 0;
@@ -129,7 +128,7 @@ catalog-card-art-shadow {
bottom: 0;
left: 0;
pointer-events: none;
decorator: linear-gradient(180deg, rgba(var(--color-surface-rgb), 0%) 45%, rgba(var(--color-surface-rgb), 85%));
mask-image: linear-gradient(180deg, #fff 45%, transparent);
}
catalog-card-body {
@@ -182,7 +181,6 @@ catalog-card-body > small {
height: 56dp;
border-radius: var(--radius-panel);
overflow: hidden;
background-color: rgba(var(--color-border-rgb), 18%);
box-shadow: rgba(var(--color-black-rgb), 60%) 0 6dp 16dp;
}
@@ -235,8 +233,10 @@ catalog-card-body > footer {
catalog-card-body > footer stat {
display: flex;
flex: 0 0 auto;
align-items: center;
gap: 3dp;
white-space: nowrap;
}
catalog-card-body > footer icon {
@@ -329,10 +329,9 @@ catalog-detail-hero {
flex: 0 0 220dp;
min-height: 220dp;
padding: 18dp var(--space-xl) 20dp var(--space-xl);
background-color: rgba(var(--color-control-rgb), 75%);
}
catalog-detail-hero-shadow {
catalog-detail-hero-image {
display: block;
position: absolute;
top: 0;
@@ -340,7 +339,7 @@ catalog-detail-hero-shadow {
bottom: 0;
left: 0;
pointer-events: none;
decorator: linear-gradient(180deg, rgba(var(--color-surface-rgb), 25%) 40%, rgba(var(--color-surface-rgb), 92%));
mask-image: linear-gradient(180deg, #fff 40%, transparent);
}
catalog-detail-actions {
@@ -403,10 +402,11 @@ catalog-source-actions button {
}
.catalog-install-action.idle {
--button-background: rgba(var(--color-interactive-rgb), 40%);
--button-background-hover: rgba(var(--color-interactive-rgb), 55%);
--button-background-selected: rgba(var(--color-interactive-rgb), 55%);
--button-background-active: rgba(var(--color-interactive-rgb), 55%);
--button-background: rgba(var(--color-interactive-rgb), 18%);
--button-background-hover: rgba(var(--color-interactive-rgb), 42%);
--button-background-selected: rgba(var(--color-interactive-rgb), 42%);
--button-background-active: rgba(var(--color-interactive-rgb), 65%);
box-shadow: rgba(var(--color-accent-rgb), 65%) 0 0 0 1dp;
}
.catalog-install-action.paused {
@@ -467,10 +467,6 @@ catalog-source-actions button {
box-shadow: rgba(var(--color-success-rgb), 50%) 0 0 0 2dp;
}
.catalog-install-action.installed:disabled {
opacity: 1;
}
.catalog-install-action.installing progress fill {
background-color: rgba(var(--color-info-rgb), 80%);
}
@@ -513,7 +509,6 @@ catalog-detail-identity mod-icon {
height: 70dp;
border-radius: var(--radius-panel);
overflow: hidden;
background-color: rgba(var(--color-border-rgb), 25%);
box-shadow: rgba(var(--color-black-rgb), 65%) 0 8dp 20dp;
}
@@ -561,11 +556,7 @@ catalog-detail-stats {
flex-flow: row;
align-items: center;
gap: 28dp;
padding: 13dp 28dp;
border-top-width: 1dp;
border-top-color: rgba(var(--color-border-rgb), 30%);
border-bottom-width: 1dp;
border-bottom-color: rgba(var(--color-border-rgb), 30%);
margin: 0 var(--space-xl);
font-size: var(--font-size-2xs);
color: rgba(var(--color-text-rgb), 58%);
}
@@ -582,11 +573,6 @@ catalog-detail-stats icon {
line-height: 1;
}
catalog-detail-stats > stat > b {
color: var(--color-text);
font-weight: bold;
}
catalog-detail-body {
display: flex;
flex-flow: row;
@@ -705,6 +691,8 @@ catalog-gallery {
}
.catalog-screenshot {
position: relative;
overflow: hidden;
flex: 1 1 0;
height: 100%;
min-width: 0;
@@ -718,6 +706,25 @@ catalog-gallery {
flex: 2 1 0;
}
catalog-screenshot-image,
catalog-screenshot-more {
display: block;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
pointer-events: none;
}
catalog-screenshot-more {
display: flex;
align-items: center;
justify-content: center;
background-color: rgba(var(--color-black-rgb), 60%);
color: var(--color-white);
}
catalog-dependencies {
display: flex;
flex-flow: column;
@@ -759,13 +766,14 @@ catalog-detail-body dl {
display: flex;
flex-flow: row wrap;
margin: 0;
font-size: var(--font-size-2xs);
font-size: var(--font-size-sm);
}
catalog-detail-body dt {
flex: 0 0 42%;
padding: 5dp 0;
opacity: 0.5;
font-weight: bold;
opacity: 0.8;
}
catalog-detail-body dd {
@@ -775,11 +783,6 @@ catalog-detail-body dd {
text-align: right;
}
catalog-source-actions {
display: flex;
flex-flow: column;
}
window.screenshot-viewer > content {
flex-flow: column;
padding: 18dp;
+20 -3
View File
@@ -199,6 +199,22 @@ mod-header.has-banner {
margin: -24dp -24dp 0dp -24dp;
}
mod-header-image {
display: block;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
pointer-events: none;
mask-image: linear-gradient(180deg, #fff 40%, transparent);
filter: grayscale(0);
}
mod-header.inactive mod-header-image {
filter: grayscale(1);
}
mod-actions {
position: absolute;
top: 24dp;
@@ -209,9 +225,10 @@ mod-actions {
}
mod-actions button {
font-size: var(--font-size-md);
padding: 6dp 14dp;
background-color: rgba(var(--color-surface-rgb), 80%);
--button-background: rgba(var(--color-surface-rgb), 80%);
--button-background-hover: rgba(var(--color-control-rgb), 90%);
--button-background-selected: rgba(var(--color-control-rgb), 90%);
--button-background-active: rgba(var(--color-surface-rgb), 90%);
box-shadow: rgba(var(--color-border-rgb), 60%) 0 0 0 1dp;
}
+62
View File
@@ -186,3 +186,65 @@ color-value:hover,
color-value:focus-visible {
color: var(--color-accent);
}
popover.context-menu {
min-width: 200dp;
max-width: 90%;
max-height: 90%;
overflow-y: auto;
padding: 6dp;
gap: 2dp;
transform-origin: left top;
}
.context-menu button {
display: flex;
align-items: center;
gap: 10dp;
padding: 8dp 12dp;
flex: 0 0 auto;
white-space: nowrap;
--button-background: transparent;
background-color: var(--button-background);
box-shadow: none;
transition: background-color 0.1s linear-in-out;
}
.context-menu button:not(:disabled):hover,
.context-menu button:not(:disabled):focus-visible {
background-color: var(--button-background-hover);
box-shadow: none;
}
.context-menu button:not(:disabled):active {
background-color: var(--button-background-active);
}
.context-menu button:disabled {
background-color: transparent;
box-shadow: none;
opacity: 0.4;
cursor: unavailable;
}
.context-menu button.destructive {
color: var(--color-error);
}
.context-menu icon {
display: block;
flex: 0 0 1em;
width: 1em;
height: 1em;
font-family: var(--font-family-icons);
font-weight: normal;
line-height: 1;
}
menu-separator {
display: block;
flex: 0 0 1dp;
height: 1dp;
margin: 4dp 6dp;
background-color: var(--color-border);
}
+1 -1
View File
@@ -57,7 +57,7 @@ window > close {
position: fixed;
top: 8dp;
right: 8dp;
z-index: 1;
z-index: 2;
width: 48dp;
height: 48dp;
font-family: var(--font-family-icons);
+39
View File
@@ -940,3 +940,42 @@ modal-actions.vertical button.modal-btn {
width: 100%;
}
}
button.icon-button {
display: flex;
align-items: center;
justify-content: center;
width: 44dp;
height: 44dp;
padding: var(--space-sm);
box-sizing: border-box;
flex-shrink: 0;
font-size: var(--font-size-5xl);
}
button.icon-button icon {
display: block;
flex-shrink: 0;
line-height: 1;
pointer-events: none;
}
ui-tooltip {
display: none;
position: absolute;
z-index: 1000;
max-width: 240dp;
padding: 6dp 10dp;
border: 1dp var(--color-border);
border-radius: var(--radius-panel);
background-color: rgba(var(--color-surface-rgb), 96%);
color: var(--color-text);
font-size: var(--font-size-md);
word-break: break-word;
pointer-events: none;
focus: none;
}
ui-tooltip.visible {
display: block;
}
+2
View File
@@ -42,6 +42,8 @@ extern "C" {
#define MOD_ABI_VERSION 1u
#define MOD_ERROR_MESSAGE_SIZE 512u
#define DUSKLIGHT_SERVICE_ID_PREFIX "dev.twilitrealm.dusklight."
typedef struct ModContext ModContext;
typedef enum ModResult {
+1 -1
View File
@@ -3,7 +3,7 @@
#include <mods/api.h>
#include <mods/svc/config.h>
#define ACTOR_SERVICE_ID "dev.twilitrealm.dusklight.actor"
#define ACTOR_SERVICE_ID DUSKLIGHT_SERVICE_ID_PREFIX "actor"
#define ACTOR_SERVICE_MAJOR 1u
#define ACTOR_SERVICE_MINOR 0u
+1 -1
View File
@@ -6,7 +6,7 @@
#include <mods/service.hpp>
#endif
#define CAMERA_SERVICE_ID "dev.twilitrealm.dusklight.camera"
#define CAMERA_SERVICE_ID DUSKLIGHT_SERVICE_ID_PREFIX "camera"
#define CAMERA_SERVICE_MAJOR 1u
#define CAMERA_SERVICE_MINOR 1u
+1 -1
View File
@@ -6,7 +6,7 @@
#include <mods/service.hpp>
#endif
#define CONFIG_SERVICE_ID "dev.twilitrealm.dusklight.config"
#define CONFIG_SERVICE_ID DUSKLIGHT_SERVICE_ID_PREFIX "config"
#define CONFIG_SERVICE_MAJOR 1u
#define CONFIG_SERVICE_MINOR 0u
+1 -1
View File
@@ -6,7 +6,7 @@
#include <mods/service.hpp>
#endif
#define FILE_SERVICE_ID "dev.twilitrealm.dusklight.file"
#define FILE_SERVICE_ID DUSKLIGHT_SERVICE_ID_PREFIX "file"
#define FILE_SERVICE_MAJOR 1u
#define FILE_SERVICE_MINOR 0u
+1 -1
View File
@@ -6,7 +6,7 @@
#include <mods/service.hpp>
#endif
#define FLOW_SERVICE_ID "dev.twilitrealm.dusklight.flow"
#define FLOW_SERVICE_ID DUSKLIGHT_SERVICE_ID_PREFIX "flow"
#define FLOW_SERVICE_MAJOR 1u
#define FLOW_SERVICE_MINOR 0u
+1 -1
View File
@@ -15,7 +15,7 @@
* ordinary version check then fails mods built against the old epoch with a clear message instead
* of letting them corrupt memory.
*/
#define GAME_SERVICE_ID "dev.twilitrealm.dusklight.game"
#define GAME_SERVICE_ID DUSKLIGHT_SERVICE_ID_PREFIX "game"
#define GAME_SERVICE_MAJOR 2u
#define GAME_SERVICE_MINOR 0u
+1 -1
View File
@@ -3,7 +3,7 @@
#include <mods/api.h>
#include <mods/svc/config.h>
#define GAME_MODE_SERVICE_ID "dev.twilitrealm.dusklight.gamemode"
#define GAME_MODE_SERVICE_ID DUSKLIGHT_SERVICE_ID_PREFIX "gamemode"
#define GAME_MODE_SERVICE_MAJOR 1u
#define GAME_MODE_SERVICE_MINOR 0u
+1 -1
View File
@@ -31,7 +31,7 @@
* should be released in mod_shutdown. The device outlives all mods.
*/
#define GFX_SERVICE_ID "dev.twilitrealm.dusklight.gfx"
#define GFX_SERVICE_ID DUSKLIGHT_SERVICE_ID_PREFIX "gfx"
#define GFX_SERVICE_MAJOR 1u
#define GFX_SERVICE_MINOR 2u
+1 -1
View File
@@ -20,7 +20,7 @@
* (file-local statics included).
*/
#define HOOK_SERVICE_ID "dev.twilitrealm.dusklight.hook"
#define HOOK_SERVICE_ID DUSKLIGHT_SERVICE_ID_PREFIX "hook"
#define HOOK_SERVICE_MAJOR 1u
#define HOOK_SERVICE_MINOR 1u
+1 -1
View File
@@ -11,7 +11,7 @@
* Always available; every other service can be reached from it.
*/
#define HOST_SERVICE_ID "dev.twilitrealm.dusklight.host"
#define HOST_SERVICE_ID DUSKLIGHT_SERVICE_ID_PREFIX "host"
#define HOST_SERVICE_MAJOR 2u
#define HOST_SERVICE_MINOR 2u
+1 -1
View File
@@ -6,7 +6,7 @@
#include <mods/service.hpp>
#endif
#define HTTP_SERVICE_ID "dev.twilitrealm.dusklight.http"
#define HTTP_SERVICE_ID DUSKLIGHT_SERVICE_ID_PREFIX "http"
#define HTTP_SERVICE_MAJOR 1u
#define HTTP_SERVICE_MINOR 0u
+1 -1
View File
@@ -6,7 +6,7 @@
#include <mods/service.hpp>
#endif
#define ITEM_SERVICE_ID "dev.twilitrealm.dusklight.item"
#define ITEM_SERVICE_ID DUSKLIGHT_SERVICE_ID_PREFIX "item"
#define ITEM_SERVICE_MAJOR 2u
#define ITEM_SERVICE_MINOR 3u
+1 -1
View File
@@ -11,7 +11,7 @@
* (prefixed with its ID).
*/
#define LOG_SERVICE_ID "dev.twilitrealm.dusklight.log"
#define LOG_SERVICE_ID DUSKLIGHT_SERVICE_ID_PREFIX "log"
#define LOG_SERVICE_MAJOR 1u
#define LOG_SERVICE_MINOR 0u
+1 -1
View File
@@ -6,7 +6,7 @@
#include <mods/service.hpp>
#endif
#define MESSAGE_SERVICE_ID "dev.twilitrealm.dusklight.message"
#define MESSAGE_SERVICE_ID DUSKLIGHT_SERVICE_ID_PREFIX "message"
#define MESSAGE_SERVICE_MAJOR 1u
#define MESSAGE_SERVICE_MINOR 1u
+1 -1
View File
@@ -6,7 +6,7 @@
#include <mods/service.hpp>
#endif
#define NET_SERVICE_ID "dev.twilitrealm.dusklight.net"
#define NET_SERVICE_ID DUSKLIGHT_SERVICE_ID_PREFIX "net"
#define NET_SERVICE_MAJOR 1u
#define NET_SERVICE_MINOR 0u
+1 -1
View File
@@ -6,7 +6,7 @@
#include <mods/service.hpp>
#endif
#define OVERLAY_SERVICE_ID "dev.twilitrealm.dusklight.overlay"
#define OVERLAY_SERVICE_ID DUSKLIGHT_SERVICE_ID_PREFIX "overlay"
#define OVERLAY_SERVICE_MAJOR 1u
#define OVERLAY_SERVICE_MINOR 0u
+1 -1
View File
@@ -12,7 +12,7 @@
* for temporary storage.
*/
#define RESOURCE_SERVICE_ID "dev.twilitrealm.dusklight.resource"
#define RESOURCE_SERVICE_ID DUSKLIGHT_SERVICE_ID_PREFIX "resource"
#define RESOURCE_SERVICE_MAJOR 1u
#define RESOURCE_SERVICE_MINOR 0u
+1 -1
View File
@@ -6,7 +6,7 @@
#include <mods/service.hpp>
#endif
#define SAVE_SERVICE_ID "dev.twilitrealm.dusklight.save"
#define SAVE_SERVICE_ID DUSKLIGHT_SERVICE_ID_PREFIX "save"
#define SAVE_SERVICE_MAJOR 1u
#define SAVE_SERVICE_MINOR 0u
+1 -1
View File
@@ -6,7 +6,7 @@
#include <mods/service.hpp>
#endif
#define STAGE_SERVICE_ID "dev.twilitrealm.dusklight.stage"
#define STAGE_SERVICE_ID DUSKLIGHT_SERVICE_ID_PREFIX "stage"
#define STAGE_SERVICE_MAJOR 1u
#define STAGE_SERVICE_MINOR 0u
+1 -1
View File
@@ -6,7 +6,7 @@
#include <mods/service.hpp>
#endif
#define TEXTURE_SERVICE_ID "dev.twilitrealm.dusklight.texture"
#define TEXTURE_SERVICE_ID DUSKLIGHT_SERVICE_ID_PREFIX "texture"
#define TEXTURE_SERVICE_MAJOR 1u
#define TEXTURE_SERVICE_MINOR 0u
+1 -1
View File
@@ -8,7 +8,7 @@
#include <mods/service.hpp>
#endif
#define UI_SERVICE_ID "dev.twilitrealm.dusklight.ui"
#define UI_SERVICE_ID DUSKLIGHT_SERVICE_ID_PREFIX "ui"
#define UI_SERVICE_MAJOR 2u
#define UI_SERVICE_MINOR 2u
+1 -1
View File
@@ -7,7 +7,7 @@
#include <mods/service.hpp>
#endif
#define WEBSOCKET_SERVICE_ID "dev.twilitrealm.dusklight.websocket"
#define WEBSOCKET_SERVICE_ID DUSKLIGHT_SERVICE_ID_PREFIX "websocket"
#define WEBSOCKET_SERVICE_MAJOR 1u
#define WEBSOCKET_SERVICE_MINOR 0u
+1 -1
View File
@@ -8,7 +8,7 @@
#include <limits.h>
#define WINDOW_SERVICE_ID "dev.twilitrealm.dusklight.window"
#define WINDOW_SERVICE_ID DUSKLIGHT_SERVICE_ID_PREFIX "window"
#define WINDOW_SERVICE_MAJOR 1u
#define WINDOW_SERVICE_MINOR 0u
+1 -1
View File
@@ -13,9 +13,9 @@ namespace dusk::archive {
enum class PackageFormat {
Unknown,
Mod,
// Save,
};
/** File-backed ZIP reader shared by Dusklight package formats. */
class ZipArchive {
public:
explicit ZipArchive(const std::filesystem::path& path);
+12 -4
View File
@@ -208,8 +208,11 @@ struct LoadedMod {
std::string dataDirUtf8;
uint32_t searchDirIndex = 0;
// Native lib is dlopen'd in place and stays resident for the session. Reload is unsupported.
bool fromDirectory = false;
// Native lib is dlopen'd in place.
bool nativeInPlace = false;
bool hasUserPackage = false;
bool hasBundledCopy = false;
FileIdentity fileIdentity;
std::unique_ptr<ConfigVar<bool>> cvarIsEnabled;
@@ -259,6 +262,8 @@ struct LoadedMod {
[[nodiscard]] bool activation_failed() const { return loadFailed || (is_enabled() && !active); }
};
struct PackageCandidate;
class ModLoader {
public:
static ModLoader& instance();
@@ -279,6 +284,7 @@ public:
[[nodiscard]] std::filesystem::path user_mods_dir() const;
[[nodiscard]] bool can_uninstall(const LoadedMod& mod) const;
[[nodiscard]] bool can_update(const LoadedMod& mod) const;
[[nodiscard]] LoadedMod* find_mod(std::string_view id);
[[nodiscard]] const LoadedMod* find_mod(std::string_view id) const;
[[nodiscard]] uint64_t generation() const noexcept { return m_generation; }
@@ -359,14 +365,17 @@ private:
void apply_pending_requests();
[[nodiscard]] OperationResult install_staged(const std::filesystem::path& path);
[[nodiscard]] OperationResult load_runtime_mod(const std::filesystem::path& path);
[[nodiscard]] OperationResult reload_runtime_mod(LoadedMod& mod);
[[nodiscard]] OperationResult reload_runtime_mod(
LoadedMod& mod, const PackageCandidate* replacement = nullptr);
[[nodiscard]] OperationResult uninstall_runtime_mod(LoadedMod& mod);
[[nodiscard]] OperationResult runtime_result(LoadedMod& mod);
void forget_mod(LoadedMod& mod);
void flush_toasts();
void on_enabled_changed(LoadedMod& mod);
// Deactivates `target` (if needed) and its transitive dependents, optionally re-reads the
// bundle from disk, then reactivates whatever the current cvar/provider state allows.
void apply_lifecycle_change(LoadedMod& target, bool reload);
void apply_lifecycle_change(
LoadedMod& target, bool reload, const PackageCandidate* replacement = nullptr);
// `target` plus transitive active/suspended dependents, in m_mods (init) order.
std::vector<LoadedMod*> collect_lifecycle_set(LoadedMod& target) const;
void resume_lifecycle_set(const std::vector<LoadedMod*>& mods);
@@ -374,7 +383,6 @@ private:
bool ensure_native_loaded(LoadedMod& mod);
};
// Reads and validates mod.json without loading native code or changing loader state.
bool inspect_mod_bundle(const std::filesystem::path& path, ModMetadata& metadata,
std::string& error, bool* hasNative = nullptr) noexcept;
+223
View File
@@ -0,0 +1,223 @@
#include "code_patch_macos.hpp"
#include <libkern/OSCacheControl.h>
#include <mach/mach.h>
#include <mach/mach_vm.h>
#include <pthread.h>
#include <stdint.h>
#include <unistd.h>
#define PATCH_CODE \
__attribute__((section("__TEXT,__code_patch,regular,pure_instructions"), noinline))
extern const char kPatchBegin[] asm("section$start$__TEXT$__code_patch");
extern const char kPatchEnd[] asm("section$end$__TEXT$__code_patch");
namespace {
constexpr unsigned kMaxThreads = 1024;
constexpr unsigned kMaxAttempts = 16;
constexpr size_t kMaxPatchSize = 16;
pthread_mutex_t sPatchMutex = PTHREAD_MUTEX_INITIALIZER;
struct ThreadList {
thread_act_array_t threads = nullptr;
mach_msg_type_number_t count = 0;
};
PATCH_CODE void release_threads(ThreadList& list) {
for (unsigned i = 0; i < list.count; ++i) {
mach_port_deallocate(mach_task_self(), list.threads[i]);
}
if (list.threads != nullptr) {
vm_deallocate(mach_task_self(), reinterpret_cast<vm_address_t>(list.threads),
list.count * sizeof(thread_t));
}
}
PATCH_CODE kern_return_t read_pc(thread_t thread, uintptr_t& pc) {
#if defined(__aarch64__)
arm_thread_state64_t state{};
mach_msg_type_number_t count = ARM_THREAD_STATE64_COUNT;
const auto result = thread_get_state(
thread, ARM_THREAD_STATE64, reinterpret_cast<thread_state_t>(&state), &count);
pc = arm_thread_state64_get_pc(state);
#elif defined(__x86_64__)
x86_thread_state64_t state{};
mach_msg_type_number_t count = x86_THREAD_STATE64_COUNT;
const auto result = thread_get_state(
thread, x86_THREAD_STATE64, reinterpret_cast<thread_state_t>(&state), &count);
pc = state.__rip;
#else
#error Unsupported macOS architecture
#endif
return result;
}
PATCH_CODE __attribute__((aligned(16384))) kern_return_t commit_patch(uintptr_t target,
const unsigned char* expected, const unsigned char* replacement, size_t size, uintptr_t page,
size_t pageSize, thread_t currentThread) {
ThreadList initial;
auto result = task_threads(mach_task_self(), &initial.threads, &initial.count);
if (result != KERN_SUCCESS) {
return result;
}
thread_t suspended[kMaxThreads];
unsigned suspendedCount = 0;
if (initial.count > kMaxThreads) {
release_threads(initial);
return KERN_RESOURCE_SHORTAGE;
}
for (unsigned i = 0; i < initial.count; ++i) {
const auto thread = initial.threads[i];
if (thread == currentThread) {
continue;
}
result = thread_suspend(thread);
if (result != KERN_SUCCESS) {
break;
}
suspended[suspendedCount++] = thread;
uintptr_t pc = 0;
result = read_pc(thread, pc);
if (result != KERN_SUCCESS) {
break;
}
if (pc >= target && pc < target + size) {
result = KERN_ABORTED;
break;
}
}
if (result == KERN_SUCCESS) {
ThreadList current;
result = task_threads(mach_task_self(), &current.threads, &current.count);
if (result == KERN_SUCCESS) {
for (unsigned i = 0; i < current.count; ++i) {
bool known = false;
for (unsigned j = 0; j < initial.count; ++j) {
known |= current.threads[i] == initial.threads[j];
}
if (!known) {
result = KERN_ABORTED;
break;
}
}
}
release_threads(current);
}
if (result == KERN_SUCCESS) {
const auto* bytes = reinterpret_cast<const volatile unsigned char*>(target);
for (size_t i = 0; i < size; ++i) {
if (bytes[i] != expected[i]) {
result = KERN_INVALID_VALUE;
break;
}
}
}
if (result == KERN_SUCCESS) {
result = mach_vm_protect(
mach_task_self(), page, pageSize, false, VM_PROT_READ | VM_PROT_WRITE | VM_PROT_COPY);
if (result == KERN_SUCCESS) {
auto* bytes = reinterpret_cast<volatile unsigned char*>(target);
for (size_t i = 0; i < size; ++i) {
bytes[i] = replacement[i];
}
sys_icache_invalidate(reinterpret_cast<void*>(target), size);
result = mach_vm_protect(
mach_task_self(), page, pageSize, false, VM_PROT_READ | VM_PROT_EXECUTE);
if (result != KERN_SUCCESS) {
for (size_t i = 0; i < size; ++i) {
bytes[i] = expected[i];
}
sys_icache_invalidate(reinterpret_cast<void*>(target), size);
if (mach_vm_protect(mach_task_self(), page, pageSize, false,
VM_PROT_READ | VM_PROT_EXECUTE) != KERN_SUCCESS)
{
__builtin_trap(); // Can't resume into non-executable code
}
}
}
}
for (unsigned i = 0; i < suspendedCount; ++i) {
if (thread_resume(suspended[i]) != KERN_SUCCESS) {
__builtin_trap();
}
}
release_threads(initial);
return result;
}
} // namespace
extern "C" int commit_code_patch(
void* targetPointer, const void* expected, const void* replacement, size_t size) {
if (targetPointer == nullptr || expected == nullptr || replacement == nullptr || size == 0 ||
size > kMaxPatchSize)
{
return KERN_INVALID_ARGUMENT;
}
const auto target = reinterpret_cast<uintptr_t>(targetPointer);
const size_t pageSize = vm_page_size;
if (target > UINTPTR_MAX - size - pageSize) {
return KERN_INVALID_ADDRESS;
}
const auto page = target & ~(pageSize - 1);
const size_t length = ((target + size + pageSize - 1) & ~(pageSize - 1)) - page;
if (page < reinterpret_cast<uintptr_t>(kPatchEnd) &&
page + length > reinterpret_cast<uintptr_t>(kPatchBegin))
{
return KERN_PROTECTION_FAILURE;
}
unsigned char oldCode[kMaxPatchSize];
unsigned char newCode[kMaxPatchSize];
for (size_t i = 0; i < size; ++i) {
oldCode[i] = static_cast<const unsigned char*>(expected)[i];
newCode[i] = static_cast<const unsigned char*>(replacement)[i];
}
pthread_mutex_lock(&sPatchMutex);
mach_vm_address_t region = page;
mach_vm_size_t regionSize = 0;
vm_region_basic_info_data_64_t info{};
mach_msg_type_number_t count = VM_REGION_BASIC_INFO_COUNT_64;
mach_port_t object = MACH_PORT_NULL;
auto result = mach_vm_region(mach_task_self(), &region, &regionSize, VM_REGION_BASIC_INFO_64,
reinterpret_cast<vm_region_info_t>(&info), &count, &object);
if (object != MACH_PORT_NULL) {
mach_port_deallocate(mach_task_self(), object);
}
if (result == KERN_SUCCESS && (region > page || regionSize < page + length - region ||
info.protection != (VM_PROT_READ | VM_PROT_EXECUTE)))
{
result = KERN_PROTECTION_FAILURE;
}
if (result == KERN_SUCCESS) {
const auto currentThread = mach_thread_self();
uintptr_t pc = 0;
read_pc(currentThread, pc);
thread_suspend(MACH_PORT_NULL);
thread_resume(MACH_PORT_NULL);
vm_deallocate(mach_task_self(), 0, 0);
mach_port_deallocate(mach_task_self(), MACH_PORT_NULL);
sys_icache_invalidate(targetPointer, size);
result = mach_vm_protect(mach_task_self(), page, length, false, info.protection);
if (result == KERN_SUCCESS) {
for (unsigned attempt = 0; attempt < kMaxAttempts; ++attempt) {
result = commit_patch(target, oldCode, newCode, size, page, length, currentThread);
if (result != KERN_ABORTED || attempt + 1 == kMaxAttempts) {
break;
}
usleep(1000);
}
}
mach_port_deallocate(mach_task_self(), currentThread);
}
pthread_mutex_unlock(&sPatchMutex);
return result;
}
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
int commit_code_patch(void* target, const void* expected, const void* replacement, size_t size);
#ifdef __cplusplus
}
#endif
File diff suppressed because it is too large Load Diff
+203
View File
@@ -0,0 +1,203 @@
#include "manifest.hpp"
#include "loader.hpp"
#include "natives.hpp"
#include "packages.hpp"
#include "dusk/mods/log_buffer.hpp"
#include <borealis/io.hpp>
#include <fmt/format.h>
#include <nlohmann/json.hpp>
#include <algorithm>
#include <charconv>
#include <stdexcept>
#include <utility>
using namespace std::string_literals;
namespace fs = std::filesystem;
namespace dusk::mods {
namespace {
class InvalidModDataException : public std::runtime_error {
public:
explicit InvalidModDataException(const std::string& msg) : runtime_error(msg) {}
explicit InvalidModDataException(const char* msg) : runtime_error(msg) {}
};
void validate_mod_id(std::string_view const str) {
if (str.empty()) {
throw InvalidModDataException("Missing ID value in mod metadata");
}
bool lastWasPeriod = false;
for (auto const chr : str) {
if (chr == '.') {
if (lastWasPeriod) {
throw InvalidModDataException("Cannot have two consecutive periods in mod ID");
}
lastWasPeriod = true;
continue;
}
lastWasPeriod = false;
if (chr == '_')
continue;
if (chr >= '0' && chr <= '9')
continue;
if (chr >= 'a' && chr <= 'z')
continue;
if (chr >= 'A' && chr <= 'Z')
continue;
throw InvalidModDataException(
fmt::format("Invalid character '{}' in mod ID. Valid characters are period, "
"underscore, and alphanumerics.",
chr));
}
}
bool bundle_has_file(ModBundle& bundle, const std::string& path) {
try {
bundle.getFileSize(path);
return true;
} catch (const std::runtime_error&) {
return false;
}
}
std::string resolve_image_path(ModBundle& bundle, const std::string& modId, std::string_view key,
const std::string& manifestPath, const std::string& defaultPath) {
if (!manifestPath.empty()) {
if (!is_safe_resource_path(manifestPath)) {
log::write(
modId, LOG_LEVEL_WARN, "invalid {} path '{}' in mod.json", key, manifestPath);
} else if (!bundle_has_file(bundle, manifestPath)) {
log::write(
modId, LOG_LEVEL_WARN, "{} path '{}' not found in bundle", key, manifestPath);
} else {
return manifestPath;
}
}
if (bundle_has_file(bundle, defaultPath)) {
return defaultPath;
}
return {};
}
uint16_t parse_runtime_version_component(std::string_view text, std::string_view fieldName) {
uint32_t value = 0;
const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), value);
if (text.empty() || error != std::errc{} || end != text.data() + text.size() ||
value > UINT16_MAX)
{
throw InvalidModDataException(fmt::format("Invalid {} in runtime version pin", fieldName));
}
return static_cast<uint16_t>(value);
}
std::optional<DelegatedModRuntime> parse_runtime(const nlohmann::json& manifest) {
const auto field = manifest.find("runtime");
if (field == manifest.end()) {
return std::nullopt;
}
if (!field->is_string()) {
throw InvalidModDataException("runtime must be a string");
}
const std::string pin = field->get<std::string>();
const auto at = pin.rfind('@');
if (at == std::string::npos || at == 0 || at + 1 == pin.size() || pin.find('@') != at ||
at >= MOD_META_SERVICE_ID_SIZE)
{
throw InvalidModDataException(
"runtime must be a service id followed by @major or @major.minor");
}
const std::string_view version{pin.data() + at + 1, pin.size() - at - 1};
const auto dot = version.find('.');
if (dot != std::string_view::npos && version.find('.', dot + 1) != std::string_view::npos) {
throw InvalidModDataException("runtime version pin has too many components");
}
DelegatedModRuntime result;
result.id = pin.substr(0, at);
result.major = parse_runtime_version_component(
dot == std::string_view::npos ? version : version.substr(0, dot), "major version");
if (dot != std::string_view::npos) {
result.minMinor = parse_runtime_version_component(version.substr(dot + 1), "minor version");
}
return result;
}
} // namespace
LoadedManifest load_manifest(const std::filesystem::path& modPath, ModBundle& bundle) {
const auto metaJson = bundle.readFile("mod.json");
auto j = nlohmann::json::parse(metaJson);
std::string metaId = j.value("id", "");
std::string metaName = j.value("name", "");
std::string metaVersion = j.value("version", "");
std::string metaAuthor = j.value("author", "");
std::string metaDescription = j.value("description", "");
std::string metaIcon = j.value("icon", "");
std::string metaBanner = j.value("banner", "");
validate_mod_id(metaId);
if (metaName.empty()) {
metaName = borealis::io::fs_path_to_string(modPath.stem());
}
if (metaVersion.empty()) {
metaVersion = "?"s;
}
if (metaAuthor.empty()) {
metaAuthor = "unknown"s;
}
std::string iconPath = resolve_image_path(bundle, metaId, "icon", metaIcon, "res/icon.png"s);
std::string bannerPath =
resolve_image_path(bundle, metaId, "banner", metaBanner, "res/banner.png"s);
return LoadedManifest{
.metadata =
{
std::move(metaId),
std::move(metaName),
std::move(metaVersion),
std::move(metaAuthor),
std::move(metaDescription),
std::move(iconPath),
std::move(bannerPath),
},
.runtime = parse_runtime(j),
};
}
bool inspect_mod_bundle(
const fs::path& path, ModMetadata& metadata, std::string& error, bool* hasNative) noexcept {
try {
auto bundle = load_bundle(path, false);
metadata = load_manifest(path, *bundle).metadata;
if (hasNative != nullptr) {
*hasNative = std::ranges::any_of(bundle->getFileNames(),
[](const auto& name) { return has_native_library_extension(name); });
}
error.clear();
return true;
} catch (const std::exception& exception) {
error = exception.what();
} catch (...) {
error = "Unknown bundle validation error";
}
return false;
}
} // namespace dusk::mods
+14
View File
@@ -0,0 +1,14 @@
#pragma once
#include "dusk/mod_loader.hpp"
namespace dusk::mods {
struct LoadedManifest {
ModMetadata metadata;
std::optional<DelegatedModRuntime> runtime;
};
LoadedManifest load_manifest(const std::filesystem::path& modPath, ModBundle& bundle);
} // namespace dusk::mods
+620
View File
@@ -0,0 +1,620 @@
#include "natives.hpp"
#include "loader.hpp"
#include "native_module.hpp"
#include "dusk/data.hpp"
#include "dusk/mods/log_buffer.hpp"
#include "dusk/mods/svc/registry.hpp"
#include <borealis/io.hpp>
#include <fmt/format.h>
#include <algorithm>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <string>
#include <utility>
#include <variant>
using namespace std::string_view_literals;
namespace fs = std::filesystem;
#if defined(_WIN32)
#if defined(_M_ARM64)
static constexpr std::string_view k_nativePlatform = "windows-arm64"sv;
#elif defined(_M_X64)
static constexpr std::string_view k_nativePlatform = "windows-amd64"sv;
#elif defined(_M_IX86)
static constexpr std::string_view k_nativePlatform = "windows-x86"sv;
#else
static constexpr std::string_view k_nativePlatform = ""sv;
#endif
static constexpr std::string_view k_nativeLibName = "mod.dll"sv;
#elif defined(__ANDROID__)
#if defined(__aarch64__)
static constexpr std::string_view k_nativePlatform = "android-aarch64"sv;
#elif defined(__x86_64__)
static constexpr std::string_view k_nativePlatform = "android-x86_64"sv;
#else
static constexpr std::string_view k_nativePlatform = ""sv;
#endif
static constexpr std::string_view k_nativeLibName = "mod.so"sv;
#elif defined(__APPLE__)
#include <TargetConditionals.h>
#if TARGET_OS_IOS
static constexpr std::string_view k_nativePlatform = "ios-arm64"sv;
#elif TARGET_OS_TV
static constexpr std::string_view k_nativePlatform = "tvos-arm64"sv;
#elif defined(__aarch64__)
static constexpr std::string_view k_nativePlatform = "macos-arm64"sv;
#elif defined(__x86_64__)
static constexpr std::string_view k_nativePlatform = "macos-x86_64"sv;
#else
static constexpr std::string_view k_nativePlatform = ""sv;
#endif
static constexpr std::string_view k_nativeLibName = "mod.so"sv;
#elif defined(__linux__)
#if defined(__aarch64__)
static constexpr std::string_view k_nativePlatform = "linux-aarch64"sv;
#elif defined(__x86_64__)
static constexpr std::string_view k_nativePlatform = "linux-x86_64"sv;
#elif defined(__i386__)
static constexpr std::string_view k_nativePlatform = "linux-x86"sv;
#else
static constexpr std::string_view k_nativePlatform = ""sv;
#endif
static constexpr std::string_view k_nativeLibName = "mod.so"sv;
#else
static constexpr std::string_view k_nativePlatform = ""sv;
static constexpr std::string_view k_nativeLibName = ""sv;
#endif
namespace dusk::mods {
bool has_native_library_extension(std::string_view name) {
const auto endsWith = [name](std::string_view extension) {
if (name.size() < extension.size()) {
return false;
}
const auto suffix = name.substr(name.size() - extension.size());
return std::ranges::equal(suffix, extension, [](char lhs, char rhs) {
const auto lower = [](char value) {
return value >= 'A' && value <= 'Z' ? static_cast<char>(value + ('a' - 'A')) :
value;
};
return lower(lhs) == lower(rhs);
});
};
return endsWith(".dll"sv) || endsWith(".so"sv) || endsWith(".dylib"sv);
}
namespace {
constexpr std::string_view k_nativeLibDir = "lib/"sv;
class DirectoryRollback {
public:
~DirectoryRollback() {
if (!mPath.empty()) {
std::error_code ec;
fs::remove_all(mPath, ec);
}
}
void set_path(fs::path path) { mPath = std::move(path); }
void release() { mPath.clear(); }
private:
fs::path mPath;
};
struct NativeRuntimeLocation {
std::string entry;
std::vector<std::string> runtimeEntries;
bool anyLibs = false;
};
struct NativeLocateFailure {
NativeModStatus status;
std::string logMessage;
};
using NativeLocateResult = std::variant<NativeRuntimeLocation, NativeLocateFailure>;
NativeLocateResult locate_native_runtime(ModBundle& bundle) {
NativeRuntimeLocation result;
const std::string platformPrefix = fmt::format("{}{}/", k_nativeLibDir, k_nativePlatform);
const std::string nativeEntry = platformPrefix + std::string{k_nativeLibName};
for (const auto& name : bundle.getFileNames()) {
if (name.find('/') == std::string::npos && has_native_library_extension(name)) {
return NativeLocateFailure{
NativeModStatus::InvalidBundle,
fmt::format(
"native library '{}' found at the root (natives go in /lib/{{platform}})",
name),
};
}
if (!name.starts_with(k_nativeLibDir)) {
continue;
}
const std::string_view libPath{
name.data() + k_nativeLibDir.size(), name.size() - k_nativeLibDir.size()};
const auto platformEnd = libPath.find('/');
if (platformEnd != std::string_view::npos) {
const auto entryName = libPath.substr(platformEnd + 1);
if (entryName.find('/') == std::string_view::npos &&
(entryName == "mod.dll"sv || entryName == "mod.so"sv))
{
result.anyLibs = true;
}
}
if (!k_nativePlatform.empty() && name.starts_with(platformPrefix)) {
const std::string_view relativeName{
name.data() + platformPrefix.size(), name.size() - platformPrefix.size()};
if (!is_safe_resource_path(relativeName)) {
continue;
}
result.runtimeEntries.push_back(name);
}
if (name == nativeEntry) {
result.entry = name;
}
}
std::ranges::sort(result.runtimeEntries);
result.runtimeEntries.erase(
std::unique(result.runtimeEntries.begin(), result.runtimeEntries.end()),
result.runtimeEntries.end());
return result;
}
// True if the first `capacity` bytes of `str` contain a NUL.
bool terminated_within(const char* str, size_t capacity) {
return std::memchr(str, '\0', capacity) != nullptr;
}
bool parse_meta(NativeMod& native, LoadedMod& mod) {
const ModMeta* meta = native.meta;
if (meta->struct_size < sizeof(ModMeta)) {
log::write(mod.metadata.id, LOG_LEVEL_ERROR, "mod_meta descriptor has invalid size {}",
meta->struct_size);
mod.nativeStatus = NativeModStatus::InvalidMetadata;
return false;
}
const auto* cursor = static_cast<const uint8_t*>(meta->records_begin);
const auto* end = static_cast<const uint8_t*>(meta->records_end);
if (cursor == nullptr || end == nullptr || cursor > end ||
(reinterpret_cast<uintptr_t>(cursor) & 7) != 0)
{
log::write(mod.metadata.id, LOG_LEVEL_ERROR, "mod_meta section bounds are invalid");
mod.nativeStatus = NativeModStatus::InvalidMetadata;
return false;
}
ModMetaParsed parsed;
size_t headerCount = 0;
const auto invalid = [&](std::string_view why) {
log::write(mod.metadata.id, LOG_LEVEL_ERROR, "invalid metadata record at offset {}: {}",
cursor - static_cast<const uint8_t*>(meta->records_begin), why);
mod.nativeStatus = NativeModStatus::InvalidMetadata;
return false;
};
while (cursor < end) {
if (end - cursor < 8) {
return invalid("trailing bytes");
}
uint64_t first = 0;
std::memcpy(&first, cursor, sizeof(first));
if (first == 0) { // linker padding / bounds sentinel
cursor += 8;
continue;
}
const auto* rec = reinterpret_cast<const ModMetaRecord*>(cursor);
const size_t size = rec->size;
if (size < 8 || size % 8 != 0 || size > static_cast<size_t>(end - cursor)) {
return invalid("bad record size");
}
switch (rec->kind) {
case MOD_META_PAD:
break;
case MOD_META_HEADER: {
if (size < sizeof(ModMetaHeader)) {
return invalid("truncated header record");
}
const auto* header = reinterpret_cast<const ModMetaHeader*>(rec);
++headerCount;
parsed.abiVersion = header->abi_version;
break;
}
case MOD_META_IMPORT: {
if (size < sizeof(ModMetaImport)) {
return invalid("truncated import record");
}
auto* record = reinterpret_cast<ModMetaImport*>(const_cast<uint8_t*>(cursor));
if (!terminated_within(record->service_id.chars, sizeof(record->service_id.chars))) {
return invalid("unterminated import service id");
}
parsed.imports.push_back(record);
break;
}
case MOD_META_EXPORT: {
if (size < sizeof(ModMetaExport)) {
return invalid("truncated export record");
}
auto* record = reinterpret_cast<ModMetaExport*>(const_cast<uint8_t*>(cursor));
if (!terminated_within(record->service_id.chars, sizeof(record->service_id.chars))) {
return invalid("unterminated export service id");
}
parsed.exports.push_back(record);
break;
}
case MOD_META_HOOK_FN: {
if (size < sizeof(ModMetaHookFn)) {
return invalid("truncated hook record");
}
parsed.hookFns.push_back(
reinterpret_cast<ModMetaHookFn*>(const_cast<uint8_t*>(cursor)));
break;
}
case MOD_META_HOOK_MEM: {
if (size <= sizeof(ModMetaHookMem)) {
return invalid("truncated hook record");
}
auto* record = reinterpret_cast<ModMetaHookMem*>(const_cast<uint8_t*>(cursor));
const char* strings = reinterpret_cast<const char*>(cursor) + sizeof(ModMetaHookMem);
const size_t capacity = size - sizeof(ModMetaHookMem);
if (!terminated_within(strings, capacity)) {
return invalid("unterminated hook vtable symbol");
}
const size_t vtableLen = std::char_traits<char>::length(strings);
if (!terminated_within(strings + vtableLen + 1, capacity - vtableLen - 1)) {
return invalid("unterminated hook display name");
}
parsed.hookMems.push_back(record);
break;
}
case MOD_META_HOOK_MEM_EXT: {
if (size <= sizeof(ModMetaHookMemExt)) {
return invalid("truncated extended hook record");
}
auto* record = reinterpret_cast<ModMetaHookMemExt*>(const_cast<uint8_t*>(cursor));
if (record->pmf_size <= MOD_META_HOOK_MEM_CAPACITY ||
record->pmf_size > MOD_META_HOOK_MEM_EXT_CAPACITY || record->materialize == nullptr)
{
return invalid("bad extended hook member-pointer size");
}
const char* strings = reinterpret_cast<const char*>(cursor) + sizeof(ModMetaHookMemExt);
const size_t capacity = size - sizeof(ModMetaHookMemExt);
if (!terminated_within(strings, capacity)) {
return invalid("unterminated extended hook vtable symbol");
}
const size_t vtableLen = std::char_traits<char>::length(strings);
if (!terminated_within(strings + vtableLen + 1, capacity - vtableLen - 1)) {
return invalid("unterminated extended hook display name");
}
parsed.hookMemExts.push_back(record);
break;
}
case MOD_META_HOOK_NAME: {
if (size <= sizeof(ModMetaHookName)) {
return invalid("truncated hook record");
}
auto* record = reinterpret_cast<ModMetaHookName*>(const_cast<uint8_t*>(cursor));
const char* name = reinterpret_cast<const char*>(cursor) + sizeof(ModMetaHookName);
if (!terminated_within(name, size - sizeof(ModMetaHookName))) {
return invalid("unterminated hook symbol name");
}
parsed.hookNames.push_back(record);
break;
}
default:
// Additive record kinds may appear within a format version; skip them.
log::write(mod.metadata.id, LOG_LEVEL_DEBUG, "skipping unknown metadata record kind {}",
rec->kind);
break;
}
cursor += size;
}
if (headerCount != 1) {
log::write(mod.metadata.id, LOG_LEVEL_ERROR, "expected 1 metadata header record, found {}",
headerCount);
mod.nativeStatus = NativeModStatus::InvalidMetadata;
return false;
}
if (parsed.abiVersion != MOD_ABI_VERSION) {
log::write(mod.metadata.id, LOG_LEVEL_ERROR, "expects ABI v{} but engine is v{}, skipping",
parsed.abiVersion, MOD_ABI_VERSION);
mod.nativeStatus = NativeModStatus::ApiVersionMismatch;
return false;
}
native.parsed = std::move(parsed);
return true;
}
std::string native_status_message(const NativeModStatus status) {
switch (status) {
case NativeModStatus::BuildDisabled:
return "Code mods are disabled on this Dusklight build";
case NativeModStatus::ModMissingPlatform:
return fmt::format("Mod not supported on this platform ({})", k_nativePlatform);
case NativeModStatus::ApiVersionMismatch:
// TODO: differentiate whether mod or Dusklight is out of date
return "Mod ABI version mismatch";
case NativeModStatus::MissingExport:
return "Missing required mod API exports";
case NativeModStatus::InvalidMetadata:
return "Invalid mod metadata records";
case NativeModStatus::InvalidBundle:
return "Invalid mod bundle layout (old mod?)";
case NativeModStatus::Unknown:
return "Unknown mod load failure";
case NativeModStatus::None:
case NativeModStatus::Loaded:
break;
}
return "native mod failed to load";
}
} // namespace
fs::path ModLoader::external_native_lib_path(const LoadedMod& mod) const {
if (k_nativeLibName.empty()) {
return {};
}
const auto& libDir = m_searchDirs[mod.searchDirIndex].nativeLibDir;
if (libDir.empty()) {
return {};
}
const auto filename = fmt::format("{}{}", mod.metadata.id,
borealis::io::fs_path_to_string(fs::path{k_nativeLibName}.extension()));
fs::path path = libDir / fs::path{filename};
std::error_code ec;
if (!fs::is_regular_file(path, ec)) {
return {};
}
return path;
}
void ModLoader::load_native(
LoadedMod& mod, const std::string& dllEntry, const std::vector<std::string>& runtimeEntries) {
if (!EnableCodeMods) {
log::write(mod.metadata.id, LOG_LEVEL_ERROR, "Code mods are not available in this build");
mod.nativeStatus = NativeModStatus::BuildDisabled;
return;
}
const fs::path cacheDir = m_cacheDir / mod.metadata.id;
const fs::path scratchDir = cacheDir / "data";
std::error_code ec;
fs::create_directories(scratchDir, ec);
if (ec) {
log::write(mod.metadata.id, LOG_LEVEL_ERROR, "failed to create mod directory {}: {}",
data::abbreviated_path_string(scratchDir), ec.message());
return;
}
mod.dir = fs::absolute(scratchDir);
mod.dirUtf8 = borealis::io::fs_path_to_string(mod.dir);
fs::path libPath;
fs::path runtimeDir;
DirectoryRollback runtimeDirRollback;
if (mod.nativeInPlace) {
if (!dllEntry.empty()) {
libPath = mod.modPath / dllEntry;
} else if (auto external = external_native_lib_path(mod); !external.empty()) {
libPath = std::move(external);
} else {
log::write(mod.metadata.id, LOG_LEVEL_ERROR,
"no native library named {} found; skipping", k_nativeLibName);
mod.nativeStatus = NativeModStatus::ModMissingPlatform;
return;
}
runtimeDir = libPath.parent_path();
} else {
if (dllEntry.empty()) {
log::write(mod.metadata.id, LOG_LEVEL_ERROR,
"no native library named {} found; skipping", k_nativeLibName);
mod.nativeStatus = NativeModStatus::ModMissingPlatform;
return;
}
// Every generation gets a new directory. The main module and all of its runtime
// libraries therefore have fresh paths and can coexist with a previous generation
// that is still unwinding after a reload.
runtimeDir = cacheDir / fmt::format("g{}", ++mod.cacheGeneration);
runtimeDirRollback.set_path(runtimeDir);
fs::create_directories(runtimeDir, ec);
if (ec) {
log::write(mod.metadata.id, LOG_LEVEL_ERROR,
"failed to create native runtime directory {}: {}",
data::abbreviated_path_string(runtimeDir), ec.message());
return;
}
const std::string platformPrefix = fmt::format("{}{}/", k_nativeLibDir, k_nativePlatform);
for (const auto& entry : runtimeEntries) {
if (!entry.starts_with(platformPrefix)) {
continue;
}
const std::string_view relativeName{
entry.data() + platformPrefix.size(), entry.size() - platformPrefix.size()};
if (!is_safe_resource_path(relativeName)) {
log::write(mod.metadata.id, LOG_LEVEL_ERROR,
"unsafe native runtime path '{}'; skipping", entry);
return;
}
const fs::path outputPath = runtimeDir / fs::path{relativeName};
fs::create_directories(outputPath.parent_path(), ec);
if (ec) {
log::write(mod.metadata.id, LOG_LEVEL_ERROR,
"failed to create directory for {}: {}", entry, ec.message());
return;
}
std::vector<u8> data;
try {
data = mod.bundle->readFile(entry);
} catch (const std::exception& e) {
log::write(
mod.metadata.id, LOG_LEVEL_ERROR, "failed to extract {}: {}", entry, e.what());
return;
}
std::ofstream out(outputPath, std::ios::binary | std::ios::out);
if (!out) {
log::write(mod.metadata.id, LOG_LEVEL_ERROR, "failed to write {}", entry);
return;
}
out.write(reinterpret_cast<const char*>(data.data()),
static_cast<std::streamsize>(data.size()));
if (!out) {
log::write(mod.metadata.id, LOG_LEVEL_ERROR, "failed to write {}", entry);
return;
}
}
libPath = runtimeDir / fs::path{dllEntry}.filename();
}
auto nativeMod = std::make_unique<NativeMod>();
try {
nativeMod->handle = std::make_unique<loader::NativeModule>(libPath);
} catch (const std::runtime_error& e) {
log::write(mod.metadata.id, LOG_LEVEL_ERROR, "failed to open {}: {}",
data::abbreviated_path_string(libPath), e.what());
return;
}
nativeMod->meta = nativeMod->handle->LookupSymbol<const ModMeta*>("mod_meta");
nativeMod->contextSymbol = nativeMod->handle->LookupSymbol<ModContext**>("mod_ctx");
nativeMod->fn_initialize = nativeMod->handle->LookupSymbol<ModInitializeFn>("mod_initialize");
nativeMod->fn_update = nativeMod->handle->LookupSymbol<ModUpdateFn>("mod_update");
nativeMod->fn_shutdown = nativeMod->handle->LookupSymbol<ModShutdownFn>("mod_shutdown");
if (!nativeMod->meta || !nativeMod->contextSymbol || !nativeMod->fn_initialize ||
!nativeMod->fn_update || !nativeMod->fn_shutdown)
{
log::write(mod.metadata.id, LOG_LEVEL_ERROR,
"{} missing required mod API exports; skipping",
data::abbreviated_path_string(libPath));
mod.nativeStatus = NativeModStatus::MissingExport;
return;
}
if (!parse_meta(*nativeMod, mod)) {
return;
}
if (nativeMod->contextSymbol == nullptr) {
log::write(mod.metadata.id, LOG_LEVEL_ERROR, "missing required mod_ctx export");
mod.nativeStatus = NativeModStatus::MissingExport;
return;
}
*nativeMod->contextSymbol = mod.context.get();
mod.nativePath = fs::absolute(libPath);
mod.nativeDir = fs::absolute(runtimeDir);
mod.nativeDirUtf8 = borealis::io::fs_path_to_string(mod.nativeDir);
mod.native = std::move(nativeMod);
mod.nativeStatus = NativeModStatus::Loaded;
runtimeDirRollback.release();
}
bool ModLoader::load_native_if_present(LoadedMod& mod) {
const auto result = locate_native_runtime(*mod.bundle);
if (const auto* failure = std::get_if<NativeLocateFailure>(&result)) {
mod.nativeStatus = failure->status;
log::write(mod.metadata.id, LOG_LEVEL_ERROR, "{}", failure->logMessage);
fail_mod(mod, MOD_ERROR, native_status_message(failure->status));
return false;
}
const auto& native = std::get<NativeRuntimeLocation>(result);
if (mod.runtime.has_value() &&
(native.anyLibs || (mod.nativeInPlace && !external_native_lib_path(mod).empty())))
{
mod.nativeStatus = NativeModStatus::InvalidBundle;
fail_mod(mod, MOD_CONFLICT, "A mod cannot declare both runtime and native code");
return false;
}
if (!native.anyLibs && !(mod.nativeInPlace && !external_native_lib_path(mod).empty())) {
mod.nativeStatus = NativeModStatus::None;
return true;
}
mod.nativeStatus = NativeModStatus::Unknown;
load_native(mod, native.entry, native.runtimeEntries);
if (mod.nativeStatus != NativeModStatus::Loaded) {
fail_mod(mod, MOD_ERROR, native_status_message(mod.nativeStatus));
return false;
}
return true;
}
void ModLoader::unload_native(LoadedMod& mod) {
if (!mod.native) {
return;
}
// Deferred dlclose: this mod's code may still be on the stack below the current tick
m_retiredNatives.push_back(
{std::move(mod.native), mod.nativeInPlace ? fs::path{} : std::move(mod.nativeDir)});
mod.nativePath.clear();
mod.nativeDir.clear();
mod.nativeDirUtf8.clear();
}
void ModLoader::drain_retired_natives() {
for (auto& retired : m_retiredNatives) {
retired.native.reset();
if (!retired.directory.empty()) {
std::error_code ec;
fs::remove_all(retired.directory, ec);
}
}
m_retiredNatives.clear();
}
bool ModLoader::ensure_native_loaded(LoadedMod& mod) {
if (mod.native || mod.nativeStatus == NativeModStatus::None) {
return true;
}
return load_native_if_present(mod);
}
ModManifestInfo build_manifest_info(const ModMetaParsed& parsed) {
ModManifestInfo info;
info.imports.reserve(parsed.imports.size());
for (const auto* record : parsed.imports) {
if (!svc::valid_service_id(record->service_id.chars)) {
continue;
}
info.imports.push_back({
.id = record->service_id.chars,
.major = record->major_version,
.minMinor = record->min_minor_version,
.required = (record->rec.flags & SERVICE_IMPORT_OPTIONAL) == 0,
});
}
info.exports.reserve(parsed.exports.size());
for (const auto* record : parsed.exports) {
if (!svc::valid_service_id(record->service_id.chars)) {
continue;
}
info.exports.push_back({
.id = record->service_id.chars,
.major = record->major_version,
});
}
return info;
}
} // namespace dusk::mods
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include <string_view>
namespace dusk::mods {
struct ModManifestInfo;
struct ModMetaParsed;
bool has_native_library_extension(std::string_view name);
ModManifestInfo build_manifest_info(const ModMetaParsed& parsed);
} // namespace dusk::mods
+201
View File
@@ -0,0 +1,201 @@
#include "packages.hpp"
#include "loader.hpp"
#include "manifest.hpp"
#include "dusk/data.hpp"
#include <borealis/io.hpp>
#include <borealis/log.hpp>
#include <borealis/update.hpp>
#include <fmt/format.h>
#include <algorithm>
#include <utility>
#include <vector>
namespace fs = std::filesystem;
namespace dusk::mods {
namespace {
constexpr borealis::Log Log{"dusk::mods::loader"};
} // namespace
std::unique_ptr<ModBundle> load_bundle(const fs::path& modPath, bool fromDir) {
if (fromDir) {
return std::make_unique<ModBundleDisk>(modPath);
} else {
return std::make_unique<ModBundleZip>(modPath);
}
}
int compare_package_versions(std::string_view lhs, std::string_view rhs) {
const auto left = borealis::update::parse_version(lhs);
const auto right = borealis::update::parse_version(rhs);
if (left && right) {
return borealis::update::compare_version(*left, *right);
}
return static_cast<int>(left.has_value()) - static_cast<int>(right.has_value());
}
std::vector<PackageCandidate> scan_packages(std::span<const ModSearchDir> searchDirs) {
std::vector<PackageCandidate> packages;
for (size_t dirIndex = 0; dirIndex < searchDirs.size(); ++dirIndex) {
const auto& searchDir = searchDirs[dirIndex];
std::error_code error;
bool alreadyScanned = false;
for (size_t earlier = 0; earlier < dirIndex && !alreadyScanned; ++earlier) {
alreadyScanned = fs::equivalent(searchDirs[earlier].path, searchDir.path, error);
}
if (alreadyScanned || !fs::is_directory(searchDir.path)) {
continue;
}
std::vector<fs::directory_entry> entries;
for (const auto& entry : fs::directory_iterator{searchDir.path}) {
if ((entry.is_directory() && fs::exists(entry.path() / "mod.json")) ||
(entry.is_regular_file() && entry.path().extension() == ".dusk"))
{
entries.push_back(entry);
}
}
std::ranges::sort(entries, {}, &fs::directory_entry::path);
for (const auto& entry : entries) {
try {
const bool fromDirectory = entry.is_directory();
auto bundle = load_bundle(entry.path(), fromDirectory);
packages.push_back({
.path = fs::absolute(entry.path()),
.metadata = load_manifest(entry.path(), *bundle).metadata,
.searchDirIndex = static_cast<uint32_t>(dirIndex),
.fromDirectory = fromDirectory,
.symlink = entry.is_symlink(),
});
} catch (const std::exception& exception) {
Log.error("bad mod package {}: {}",
data::abbreviated_path_string(entry.path()), exception.what());
}
}
}
return packages;
}
const PackageCandidate* select_package(std::span<const PackageCandidate> packages,
std::string_view modId) {
const PackageCandidate* selected = nullptr;
for (const auto& package : packages) {
if (package.metadata.id != modId) {
continue;
}
const int order = selected ?
compare_package_versions(package.metadata.version, selected->metadata.version) : 1;
if (order > 0 || (order == 0 &&
(package.searchDirIndex < selected->searchDirIndex ||
(package.searchDirIndex == selected->searchDirIndex && package.path < selected->path))))
{
selected = &package;
}
}
return selected;
}
void record_package_sources(LoadedMod& mod, std::span<const PackageCandidate> packages) {
mod.hasUserPackage = false;
mod.hasBundledCopy = false;
for (const auto& package : packages) {
if (package.metadata.id != mod.metadata.id) {
continue;
}
if (package.searchDirIndex != 0) {
mod.hasBundledCopy = true;
} else if (!package.fromDirectory && !package.symlink) {
mod.hasUserPackage = true;
}
}
}
PackageInstallResult install_package(const fs::path& path, const fs::path& destination,
std::string_view modId) {
const auto userDir = destination.parent_path();
std::error_code error;
std::string validationError;
const auto destinationStatus = fs::symlink_status(destination, error);
if (error == std::errc::no_such_file_or_directory) {
error.clear();
}
if (error) {
return {.replaced = false,
.error = fmt::format("Could not inspect the destination: {}", error.message())};
}
if (fs::exists(destinationStatus)) {
ModMetadata existingMetadata;
if (!fs::is_regular_file(destinationStatus) ||
!inspect_mod_bundle(destination, existingMetadata, validationError) ||
existingMetadata.id != modId)
{
return {
.replaced = false,
.error = "The destination filename is already used by another package",
};
}
}
std::vector<fs::path> duplicates;
for (fs::directory_iterator entry{userDir, error}, end; !error && entry != end;
entry.increment(error))
{
const auto& candidate = entry->path();
if (candidate.extension() != ".dusk") {
continue;
}
const bool regularFile = entry->is_regular_file(error);
if (error) {
break;
}
if (!regularFile) {
continue;
}
ModMetadata candidateMetadata;
if (inspect_mod_bundle(candidate, candidateMetadata, validationError) &&
candidateMetadata.id == modId)
{
duplicates.push_back(candidate);
}
}
if (error) {
return {.replaced = false,
.error = fmt::format("Could not scan the mods directory: {}", error.message())};
}
std::string replaceError;
if (!borealis::io::atomic_replace(path, destination, replaceError)) {
return {
.replaced = false,
.error = std::move(replaceError),
};
}
std::string cleanupError;
for (const auto& duplicate : duplicates) {
// Replacing a file on a case-insensitive filesystem can preserve its old spelling.
const bool destinationAlias =
fs::equivalent(duplicate, destination, error) && !fs::is_symlink(duplicate, error);
error.clear();
if (destinationAlias) {
if (duplicate.filename() == destination.filename()) {
continue;
}
fs::rename(duplicate, destination, error);
} else {
fs::remove(duplicate, error);
}
if (error) {
cleanupError = fmt::format("Installed, but could not consolidate '{}': {}",
data::abbreviated_path_string(duplicate), error.message());
Log.warn("{}", cleanupError);
}
}
return {.replaced = true, .error = std::move(cleanupError)};
}
} // namespace dusk::mods
+38
View File
@@ -0,0 +1,38 @@
#pragma once
#include "dusk/mod_loader.hpp"
#include <filesystem>
#include <memory>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace dusk::mods {
struct PackageCandidate {
std::filesystem::path path;
ModMetadata metadata;
uint32_t searchDirIndex = 0;
bool fromDirectory = false;
bool symlink = false;
};
std::vector<PackageCandidate> scan_packages(std::span<const ModSearchDir> searchDirs);
int compare_package_versions(std::string_view lhs, std::string_view rhs);
const PackageCandidate* select_package(
std::span<const PackageCandidate> packages, std::string_view modId);
void record_package_sources(LoadedMod& mod, std::span<const PackageCandidate> packages);
std::unique_ptr<ModBundle> load_bundle(const std::filesystem::path& modPath, bool fromDir);
struct PackageInstallResult {
bool replaced = false;
std::string error;
};
PackageInstallResult install_package(const std::filesystem::path& path,
const std::filesystem::path& destination, std::string_view modId);
} // namespace dusk::mods
+23 -9
View File
@@ -297,27 +297,32 @@ bool install_backend(
#endif
}
void deactivate_backend(void* target, InstalledBackend& backend) {
bool deactivate_backend(void* target, InstalledBackend& backend) {
#if DUSK_HAS_PREPATCH
if (backend.kind == BackendKind::Prepatch) {
prepatch::publish(backend.prepatchSite, nullptr);
backend = {};
return;
return true;
}
#endif
#if DUSK_HAS_FUNCHOOK
if (backend.kind == BackendKind::Funchook) {
const int uninst = funchook_uninstall(backend.handle, 0);
if (uninst != 0) {
DuskLog.warn("HookSystem: funchook uninstall for {:p} failed: {}", target,
funchook_error_message(backend.handle));
return false;
}
const int destr = funchook_destroy(backend.handle);
if (uninst != 0 || destr != 0) {
DuskLog.warn("HookSystem: funchook uninstall/destroy for {:p} returned {}/{}", target,
uninst, destr);
if (destr != 0) {
DuskLog.warn("HookSystem: funchook destroy for {:p} returned {}", target, destr);
}
}
#else
(void)target;
#endif
backend = {};
return true;
}
bool handoff_backend(
@@ -352,8 +357,8 @@ bool handoff_hook(void* target, InstalledHook& entry) {
#else
constexpr bool prepatched = false;
#endif
if (!prepatched) {
deactivate_backend(target, entry.backend);
if (!prepatched && !deactivate_backend(target, entry.backend)) {
DuskLog.fatal("HookSystem: cannot hand off a hook that remains installed at {:p}", target);
}
entry.active = nullptr;
@@ -535,13 +540,20 @@ ModResult hook_uninstall(ModContext* context, void* fnAddr, void** originalFnSlo
return MOD_INVALID_ARGUMENT;
}
const bool removedActive = entry.activeStore == originalFnSlot;
#if DUSK_HAS_FUNCHOOK
if (removedActive && entry.backend.kind == BackendKind::Funchook &&
!deactivate_backend(fnAddr, entry.backend)) {
return MOD_ERROR;
}
#endif
if (const auto registryIt = s_registry.find(key);
registryIt != s_registry.end() && erase_callbacks(registryIt->second, context))
{
s_registry.erase(registryIt);
}
const bool removedActive = entry.activeStore == originalFnSlot;
entry.candidates.erase(candidateIt);
*originalFnSlot = nullptr;
if (!removedActive) {
@@ -897,7 +909,9 @@ void hook_remove_mod(LoadedMod& mod) {
auto* target = reinterpret_cast<void*>(it->first);
if (entry.candidates.empty()) {
deactivate_backend(target, entry.backend);
if (!deactivate_backend(target, entry.backend)) {
DuskLog.fatal("HookSystem: cannot detach a mod with a live hook at {:p}", target);
}
it = s_installed.erase(it);
continue;
}
+41 -5
View File
@@ -3,19 +3,22 @@
#include "dusk/app_info.hpp"
#include "dusk/logging.h"
#include "dusk/mods/loader/loader.hpp"
#include "dusk/mods/log_buffer.hpp"
#include <fmt/format.h>
#include <algorithm>
#include <optional>
#include <ranges>
#include <string_view>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace dusk::mods::svc {
namespace {
std::unordered_map<std::string, ServiceRecord> s_services;
std::unordered_set<std::string> s_unavailableServices;
std::vector<const ServiceModule*> s_modules;
std::string service_key(std::string_view id, const uint16_t majorVersion) {
@@ -48,6 +51,7 @@ bool validate_service_header(const ServiceHeader* header, const char* serviceId,
void clear_services() {
s_services.clear();
s_unavailableServices.clear();
s_modules.clear();
}
@@ -137,8 +141,38 @@ const ServiceRecord* find_service_record(const char* serviceId, const uint16_t m
return it != s_services.end() ? &it->second : nullptr;
}
std::string describe_missing_service(const char* serviceId, const uint16_t majorVersion,
const uint16_t minMinorVersion) {
const char* message = "Mod requires a service that is unavailable";
if (std::string_view{serviceId}.starts_with(DUSKLIGHT_SERVICE_ID_PREFIX) &&
!s_unavailableServices.contains(service_key(serviceId, majorVersion)))
{
if (const auto* record = find_service_record(serviceId, majorVersion)) {
if (record->provider == nullptr && record->service != nullptr &&
record->minorVersion < minMinorVersion)
{
message = "Mod requires a newer Dusklight version";
}
} else {
std::optional<uint16_t> highestMajor;
for (const auto& [key, record] : s_services) {
if (record.provider == nullptr && record.service != nullptr && record.id == serviceId) {
highestMajor = std::max(highestMajor.value_or(0), record.majorVersion);
}
}
if (highestMajor) {
message = majorVersion > *highestMajor ?
"Mod requires a newer Dusklight version" :
"Mod must be updated for the current Dusklight version";
}
}
}
return fmt::format("{} (missing: {})", message, serviceId);
}
ModResult register_module(const ServiceModule& module) {
if (module.available != nullptr && !module.available()) {
s_unavailableServices.insert(service_key(module.id, module.majorVersion));
return MOD_UNAVAILABLE;
}
const auto result = register_service(
@@ -146,6 +180,7 @@ ModResult register_module(const ServiceModule& module) {
if (result != MOD_OK) {
return result;
}
s_unavailableServices.erase(service_key(module.id, module.majorVersion));
s_modules.push_back(&module);
if (module.initialize != nullptr) {
module.initialize();
@@ -271,6 +306,9 @@ bool ModLoader::register_static_service_exports(LoadedMod& mod) {
std::string ModLoader::describe_missing_import(
const char* serviceId, const uint16_t majorVersion, const uint16_t minMinorVersion) const {
if (std::string_view{serviceId}.starts_with(DUSKLIGHT_SERVICE_ID_PREFIX)) {
return svc::describe_missing_service(serviceId, majorVersion, minMinorVersion);
}
if (const auto* record = svc::find_service_record(serviceId, majorVersion)) {
if (record->service == nullptr) {
return fmt::format("Required service {}@{} was never published by provider '{}'",
@@ -297,7 +335,7 @@ std::string ModLoader::describe_missing_import(
}
}
return fmt::format("Required service unavailable: {}@{}", serviceId, majorVersion);
return svc::describe_missing_service(serviceId, majorVersion, minMinorVersion);
}
bool ModLoader::resolve_service_imports(LoadedMod& mod) {
@@ -321,9 +359,7 @@ bool ModLoader::resolve_service_imports(LoadedMod& mod) {
continue;
}
mod.active = false;
mod.suspendedByProvider = true;
log::write(mod.metadata.id, LOG_LEVEL_INFO, "suspended: {}",
fail_mod(mod, MOD_UNAVAILABLE,
describe_missing_import(serviceImport->service_id.chars,
serviceImport->major_version, serviceImport->min_minor_version));
return false;
+2
View File
@@ -58,6 +58,8 @@ const ServiceRecord* find_service(
const char* serviceId, uint16_t majorVersion, uint16_t minMinorVersion);
// Unlike find_service, also returns deferred records that have not been published yet.
const ServiceRecord* find_service_record(const char* serviceId, uint16_t majorVersion);
std::string describe_missing_service(const char* serviceId, uint16_t majorVersion,
uint16_t minMinorVersion);
ModResult register_module(const ServiceModule& module);
void modules_mod_deactivating(LoadedMod& mod);
+76
View File
@@ -0,0 +1,76 @@
#include "context_menu.hpp"
#include "button.hpp"
#include "icon_button.hpp"
namespace dusk::ui {
ContextMenu::Binding::Binding(Document& owner, Rml::Element* root, Rml::String selector,
std::function<std::vector<Item>(Rml::Element*)> items)
: mMouseDown{root, Rml::EventId::Mousedown,
[this, &owner, root, selector = std::move(selector), items = std::move(items)](
Rml::Event& event) {
if (event.GetParameter<int>("button", -1) != 1 || !owner.active()) {
return;
}
auto* target = event.GetTargetElement()->Closest(selector);
if (target == nullptr || !root->Contains(target)) {
return;
}
auto menuItems = items(target);
if (menuItems.empty()) {
return;
}
dismiss();
auto menu = std::make_unique<ContextMenu>(target, std::move(menuItems),
Rml::Vector2f{
event.GetParameter<float>("mouse_x", 0),
event.GetParameter<float>("mouse_y", 0),
});
mMenu = menu.get();
mMenu->on_close([this] { mMenu = nullptr; });
push_document(std::move(menu));
event.StopPropagation();
}} {}
ContextMenu::Binding::~Binding() {
dismiss();
}
void ContextMenu::Binding::dismiss() {
if (mMenu != nullptr) {
mMenu->on_close(nullptr);
mMenu->dismiss();
mMenu = nullptr;
}
}
ContextMenu::ContextMenu(
Rml::Element* anchor, std::vector<Item> items, std::optional<Rml::Vector2f> position)
: Popover{anchor, Side::Below, "context-menu"},
mNavigation{body(), {.horizontalBoundary = NavGroup::Boundary::Stop,
.verticalBoundary = NavGroup::Boundary::Stop}} {
if (position) {
set_position(*position);
}
for (auto& item : items) {
if (item.separatorBefore && body()->GetNumChildren() != 0) {
append(body(), "menu-separator");
}
auto& button = mNavigation.add_item<Button>(Rml::String{});
append_text(append(button.root(), "icon"), material_icon(item.icon));
append_text_element(button.root(), "span", item.text);
button.root()->SetClass("destructive", item.destructive);
button.set_disabled(!item.enabled || !item.onPressed);
button.on_pressed([this, callback = std::move(item.onPressed)] {
dismiss();
callback();
});
}
}
bool ContextMenu::focus() {
return mNavigation.focus() || Popover::focus();
}
} // namespace dusk::ui
+41
View File
@@ -0,0 +1,41 @@
#pragma once
#include "nav_group.hpp"
#include "popover.hpp"
namespace dusk::ui {
class ContextMenu : public Popover {
public:
struct Item {
Rml::String text;
Rml::String icon;
std::function<void()> onPressed;
bool enabled = true;
bool destructive = false;
bool separatorBefore = false;
};
class Binding {
public:
Binding(Document& owner, Rml::Element* root, Rml::String selector,
std::function<std::vector<Item>(Rml::Element*)> items);
~Binding();
void dismiss();
private:
ContextMenu* mMenu = nullptr;
ScopedEventListener mMouseDown;
};
ContextMenu(Rml::Element* anchor, std::vector<Item> items,
std::optional<Rml::Vector2f> position = std::nullopt);
bool focus() override;
private:
NavGroup mNavigation;
};
} // namespace dusk::ui
+11 -3
View File
@@ -1,12 +1,14 @@
#include "drop_install_modal.hpp"
#include "dusk/mods/loader/loader.hpp"
#include "dusk/mods/loader/packages.hpp"
#include "dusk/mods/queue.hpp"
#include "format.hpp"
#include "package_row.hpp"
#include "queue_window.hpp"
#include <borealis/io.hpp>
#include <borealis/update.hpp>
#include <fmt/format.h>
#include <algorithm>
@@ -25,6 +27,8 @@ std::vector<DropPackage> prepare_packages(std::vector<DropPackage> packages) {
package.status = package.error;
} else if (std::ranges::find(batchIds, package.metadata.id) != batchIds.end()) {
package.status = "Duplicate package in this drop";
} else if (!borealis::update::parse_version(package.metadata.version)) {
package.status = "Invalid package version";
} else if (package.hasNative && !mods::EnableCodeMods) {
package.status = "Native mods cannot be installed on this platform";
} else if (const auto queued = mods::queue::find_by_mod_id(package.metadata.id);
@@ -34,9 +38,13 @@ std::vector<DropPackage> prepare_packages(std::vector<DropPackage> packages) {
} else if (const auto* installed =
mods::ModLoader::instance().find_mod(package.metadata.id))
{
if (!mods::ModLoader::instance().can_uninstall(*installed)) {
package.status = "Bundled mods cannot be updated in-game";
} else if (installed->metadata.version == package.metadata.version) {
if (!mods::ModLoader::instance().can_update(*installed)) {
package.status = "A development directory cannot be replaced";
} else if (mods::compare_package_versions(
package.metadata.version, installed->metadata.version) < 0) {
package.status = "A newer version is already installed";
} else if (mods::compare_package_versions(
package.metadata.version, installed->metadata.version) == 0) {
package.status = fmt::format("Reinstall {}", package.metadata.version);
package.valid = true;
} else {
+70
View File
@@ -0,0 +1,70 @@
#include "icon_button.hpp"
#include <utility>
namespace dusk::ui {
const char* material_icon(std::string_view name) {
static constexpr std::pair<std::string_view, const char*> icons[] = {
{"play_arrow", "\uE037"},
{"pause", "\uE034"},
{"stop", "\uE047"},
{"replay", "\uE042"},
{"skip_next", "\uE044"},
{"skip_previous", "\uE045"},
{"note_add", "\uE89C"},
{"create_new_folder", "\uE2CC"},
{"delete", "\uE872"},
{"add", "\uE145"},
{"remove", "\uE15B"},
{"close", "\uE5CD"},
{"check", "\uE5CA"},
{"refresh", "\uE5D5"},
{"file_download", "\uE2C4"},
{"download", "\uF090"},
{"schedule", "\uE8B5"},
{"warning", "\uE002"},
{"check_circle", "\uE86C"},
{"favorite", "\uE87D"},
{"arrow_back", "\uE5C4"},
{"open_in_new", "\uE89E"},
{"settings", "\uE8B8"},
{"folder_open", "\uE2C8"},
{"history", "\uE889"},
{"queue_music", "\uE03D"},
{"volume_up", "\uE050"},
{"volume_off", "\uE04F"},
{"shuffle", "\uE043"},
{"repeat", "\uE040"},
{"search", "\uE8B6"},
{"info", "\uE88E"},
{"description", "\uE873"},
{"notes", "\uE26C"},
{"resume", "\uF7D0"},
};
for (const auto& [key, glyph] : icons) {
if (name == key) {
return glyph;
}
}
return "";
}
IconButton::IconButton(Rml::Element* parent, Props props)
: ControlledButton{parent, ControlledButton::Props{.text = "",
.isSelected = std::move(props.isSelected),
.isDisabled = std::move(props.isDisabled)}},
mTooltip{mRoot, props.label} {
mRoot->SetClass("icon-button", true);
mRoot->SetAttribute("aria-label", props.label);
auto* icon = append(mRoot, "icon");
icon->SetAttribute("aria-hidden", "true");
append_text(icon, material_icon(props.icon));
}
void IconButton::update() {
ControlledButton::update();
mTooltip.update();
}
} // namespace dusk::ui
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include "button.hpp"
#include "tooltip.hpp"
#include <string_view>
namespace dusk::ui {
const char* material_icon(std::string_view name);
class IconButton : public ControlledButton {
public:
struct Props {
Rml::String icon;
Rml::String label;
std::function<bool()> isSelected;
std::function<bool()> isDisabled;
};
IconButton(Rml::Element* parent, Props props);
void update() override;
private:
Tooltip mTooltip;
};
} // namespace dusk::ui
+115 -100
View File
@@ -3,10 +3,13 @@
#include "bool_button.hpp"
#include "button.hpp"
#include "dusk/mod_loader.hpp"
#include "dusk/mods/loader/packages.hpp"
#include "dusk/mods/queue.hpp"
#include "dusk/mods/svc/registry.hpp"
#include "fmt/format.h"
#include "format.hpp"
#include "icon_button.hpp"
#include "mods_window.hpp"
#include "nav_group.hpp"
#include "package_row.hpp"
#include "queue_window.hpp"
@@ -125,9 +128,9 @@ void open_web_url(const std::string& url) {
}
}
void set_icon_button_content(Button& button, const Rml::String& glyph, const Rml::String& label) {
void set_icon_button_content(Button& button, std::string_view icon, const Rml::String& label) {
clear_children(button.root());
append_text(append(button.root(), "icon"), glyph);
append_text(append(button.root(), "icon"), material_icon(icon));
append_text_element(button.root(), "span", label);
}
@@ -136,14 +139,13 @@ void append_status(Rml::Element* parent, const Rml::String& title, const Rml::St
append_text_element(parent, "p", message);
}
void append_stat(Rml::Element* parent, const Rml::String& glyph, const Rml::String& value,
void append_stat(Rml::Element* parent, std::string_view icon, const Rml::String& value,
const Rml::String& suffix) {
auto* stat = append(parent, "stat");
if (!glyph.empty()) {
append_text(append(stat, "icon"), glyph);
if (!icon.empty()) {
append_text(append(stat, "icon"), material_icon(icon));
}
append_text_element(stat, "b", value);
append_text(stat, suffix);
append_text_element(stat, "span", value + suffix);
}
void append_detail_field(Rml::Element* list, const Rml::String& label, const Rml::String& value) {
@@ -163,7 +165,7 @@ public:
const auto installedLabel = isInstalled ? "Installed" : format_bytes(mod.packageSize);
auto* art = append(mRoot, "catalog-card-art");
append(art, "catalog-card-art-shadow");
auto* artImage = append(art, "catalog-card-art-image");
auto* icon = append(art, "mod-icon");
auto* iconImage = append(icon, "mod-icon-image");
@@ -176,11 +178,11 @@ public:
append_text_element(body, "p", snippet(mod.summary, 126));
auto* meta = append(body, "footer");
auto* downloads = append(meta, "stat");
append_text(append(downloads, "icon"), "\uF090");
append_text(downloads, format_count(mod.downloads));
append_text(append(downloads, "icon"), material_icon("download"));
append_text_element(downloads, "span", format_count(mod.downloads));
auto* endorsements = append(meta, "stat");
append_text(append(endorsements, "icon"), "\uE87D");
append_text(endorsements, format_count(mod.endorsements));
append_text(append(endorsements, "icon"), material_icon("favorite"));
append_text_element(endorsements, "span", format_count(mod.endorsements));
auto* size = append_text_element(meta, "small", installedLabel);
size->SetClass("size", true);
if (isInstalled) {
@@ -188,9 +190,9 @@ public:
}
if (mod.banner) {
set_image(art, *mod.banner, 640);
set_image(artImage, *mod.banner, 640);
} else if (mod.icon) {
set_image(art, *mod.icon, 256);
set_image(artImage, *mod.icon, 256);
}
if (mod.icon) {
set_image(iconImage, *mod.icon, 128);
@@ -235,7 +237,7 @@ private:
});
auto& back = actions.add_item<Button>("Back");
back.root()->SetClass("catalog-icon-action", true);
set_icon_button_content(back, "\uE5C4", "Back");
set_icon_button_content(back, "arrow_back", "Back");
back.on_pressed([this] { pop(); });
auto& previous = actions.add_item<ControlledButton>(ControlledButton::Props{
.text = "Previous",
@@ -402,15 +404,18 @@ public:
if (mActivationOperation != nullptr && !activationPending) {
mActivationOperation.reset();
}
std::string glyph = "\uE2C4";
std::string_view icon = "file_download";
std::string label;
std::string caption = format_bytes(package_size());
std::string state = "idle";
float progress = 0.0f;
bool disabled = false;
mAction = Action::Install;
if (queued && queued->state != mods::queue::State::Canceled) {
using enum mods::queue::State;
mAction = Action::OpenQueue;
mQueueId = queued->id;
state = queue_state_class(queued->state);
progress = queued->total == 0 ? 0.0f :
std::clamp(static_cast<float>(queued->completed) /
@@ -418,7 +423,7 @@ public:
0.0f, 1.0f);
switch (queued->state) {
case Queued:
glyph = "\uE8B5";
icon = "schedule";
label = "Queued";
if (const auto ahead = mods::queue::active_items_ahead(mRequest.id); ahead != 0) {
caption = fmt::format("{} ahead · opens the queue", ahead);
@@ -432,22 +437,22 @@ public:
caption = "Tap to open the queue";
break;
case Paused:
glyph = "\uE037";
icon = "play_arrow";
label = "Resume";
caption = fmt::format("{} kept on disk", format_bytes(queued->completed));
break;
case Retrying:
glyph = "\uE002";
icon = "warning";
label = fmt::format("Retrying in {}s", queued->retrySeconds);
caption = "Network error · keeps retrying itself";
break;
case Verifying:
glyph = "\uE8B5";
icon = "schedule";
label = "Verifying…";
caption = "Checking package integrity";
break;
case Handoff:
glyph = "\uE8B5";
icon = "schedule";
label = "Installing…";
caption = "Applying package";
progress = 1.0f;
@@ -457,7 +462,7 @@ public:
case InstallFailed:
break;
case Failed:
glyph = "\uE5D5";
icon = "refresh";
label = queued->local ? "Retry package" : "Retry download";
caption = queued->message.empty() ? "Package preparation failed" : queued->message;
progress = 1.0f;
@@ -468,42 +473,50 @@ public:
}
if (label.empty()) {
const bool current = local != nullptr && local->metadata.version == mRequest.version;
mAction = Action::Install;
const int versionOrder = local != nullptr ?
mods::compare_package_versions(mRequest.version, local->metadata.version) : 1;
const bool current = local != nullptr && versionOrder == 0;
const bool updateable =
local != nullptr && !current && mods::ModLoader::instance().can_uninstall(*local);
local != nullptr && versionOrder > 0 &&
mods::ModLoader::instance().can_update(*local);
if (activationPending) {
glyph = "\uE8B5";
icon = "schedule";
label = "Activating…";
caption = "Retrying mod activation";
state = "installing";
progress = 1.0f;
disabled = true;
} else if (current && local->activation_failed()) {
glyph = "\uE5D5";
mAction = Action::RetryActivation;
icon = "refresh";
label = "Retry activation";
caption = activation_failure(*local);
state = "failed";
progress = 1.0f;
} else if (current || (local != nullptr && !updateable)) {
glyph = "\uE86C";
mAction = Action::OpenManager;
icon = "check_circle";
label = "Installed";
caption = fmt::format("Installed · {} · {}", format_bytes(package_size()),
local != nullptr && local->active ? "enabled" : "disabled");
state = "installed";
progress = 1.0f;
disabled = true;
} else {
label = updateable ? "Update" : "Install";
}
}
if (disabled) {
mAction = Action::None;
}
if (mLabel != label || mGlyph != glyph) {
if (mLabel != label || mIcon != icon) {
ui::clear_children(mRoot);
append_text(append(mRoot, "icon"), glyph);
append_text(append(mRoot, "icon"), material_icon(icon));
append_text_element(mRoot, "span", label);
mProgress = append(mRoot, "progress");
mLabel = std::move(label);
mGlyph = std::move(glyph);
mIcon = icon;
}
set_text_content(mCaption, caption);
for (const auto* candidate : {"idle", "queued", "downloading", "paused", "retrying",
@@ -522,6 +535,8 @@ public:
}
private:
enum class Action { Install, OpenQueue, RetryActivation, OpenManager, None };
std::optional<mods::queue::Item> matching_queue_item() const {
auto item = mods::queue::find_by_mod_id(mRequest.id);
if (!item || item->version != mRequest.version ||
@@ -533,17 +548,23 @@ private:
}
void press() {
auto queued = matching_queue_item();
const auto* local = mods::ModLoader::instance().find_mod(mRequest.id);
if (queued && queued->state != mods::queue::State::Canceled) {
mWindow.show_downloads(queued->id);
update();
switch (mAction) {
case Action::OpenQueue:
mWindow.show_downloads(mQueueId);
return;
}
if (local != nullptr && local->metadata.version == mRequest.version &&
local->activation_failed())
{
case Action::RetryActivation:
mActivationOperation = mods::ModLoader::instance().request_reactivate(mRequest.id);
return;
case Action::OpenManager:
pop_to_or_push<ModsWindow>([id = mRequest.id](ModsWindow& window) {
window.select_mod(id);
});
return;
case Action::None:
return;
case Action::Install:
break;
}
if (!mods::queue::enqueue(mRequest)) {
push_toast({
@@ -560,7 +581,9 @@ private:
Rml::Element* mCaption = nullptr;
Rml::Element* mProgress = nullptr;
std::string mLabel;
std::string mGlyph;
std::string mIcon;
std::string mQueueId;
Action mAction = Action::None;
mods::ModOperationHandle mActivationOperation;
uint64_t package_size() const { return std::get<mods::queue::Url>(mRequest.source).size; }
@@ -574,12 +597,12 @@ DetailContent::DetailContent(
.verticalBoundary = Boundary::Stop,
}} {
auto* hero = append(mRoot, "catalog-detail-hero");
auto* heroImage = append(hero, "catalog-detail-hero-image");
if (detail.mod.banner) {
set_image(hero, *detail.mod.banner, 1280);
set_image(heroImage, *detail.mod.banner, 1280);
} else if (detail.mod.icon) {
set_image(hero, *detail.mod.icon, 512);
set_image(heroImage, *detail.mod.icon, 512);
}
append(hero, "catalog-detail-hero-shadow");
auto* actionsRoot = append(hero, "catalog-detail-actions");
auto& actions =
@@ -590,11 +613,11 @@ DetailContent::DetailContent(
});
auto& back = actions.add_item<Button>("Back");
back.root()->SetClass("catalog-icon-action", true);
set_icon_button_content(back, "\ue5c4", "Back");
set_icon_button_content(back, "arrow_back", "Back");
back.on_pressed([&window] { window.pop(); });
auto& open = actions.add_item<Button>("Open in browser");
open.root()->SetClass("catalog-icon-action", true);
set_icon_button_content(open, "\ue89e", "Open in browser");
set_icon_button_content(open, "open_in_new", "Open in browser");
open.on_pressed([url = detail.siteUrl] { open_web_url(url); });
auto* identity = append(hero, "catalog-detail-identity");
@@ -624,9 +647,8 @@ DetailContent::DetailContent(
installControl.add_item<CatalogInstallButton>(window, detail);
auto* stats = append(mRoot, "catalog-detail-stats");
append_stat(stats, "\uF090", format_count(detail.mod.downloads), " downloads");
append_stat(stats, "\uE87D", format_count(detail.mod.endorsements), " endorsements");
append_stat(stats, "", format_bytes(detail.mod.packageSize), " package");
append_stat(stats, "download", format_count(detail.mod.downloads), " downloads");
append_stat(stats, "favorite", format_count(detail.mod.endorsements), " endorsements");
auto* body = append(mRoot, "catalog-detail-body");
auto* main = append(body, "main");
@@ -658,49 +680,56 @@ DetailContent::DetailContent(
auto& screenshot = gallery.add_item<Button>(Button::Props{});
screenshot.root()->SetClass("catalog-screenshot", true);
screenshot.root()->SetClass("primary", index == 0);
set_image(screenshot.root(), detail.screenshots[index].image, index == 0 ? 1280 : 640);
auto* image = append(screenshot.root(), "catalog-screenshot-image");
set_image(image, detail.screenshots[index].image, index == 0 ? 1280 : 640);
if (index == 2 && detail.screenshots.size() > shown) {
screenshot.set_text(fmt::format("+{}", detail.screenshots.size() - shown));
auto* more = append(screenshot.root(), "catalog-screenshot-more");
append_text_element(more, "span", fmt::format("+{}", detail.screenshots.size() - shown));
}
screenshot.on_pressed([&window, index] { window.show_screenshot(index); });
}
}
auto* dependencies = append(main, "section");
dependencies->SetClass("catalog-scroll-anchor", true);
add_existing_item<ScrollAnchor>(dependencies);
append_text(append(dependencies, "h2"), "Dependencies");
auto* dependencyList = append(dependencies, "catalog-dependencies");
size_t requiredDusklight = 0;
bool dusklightSatisfied = true;
for (const auto& import : detail.serviceImports) {
if (import.optional) {
continue;
if (std::ranges::any_of(detail.serviceImports, [](const auto& import) { return !import.optional; })) {
auto* dependencies = append(main, "section");
dependencies->SetClass("catalog-scroll-anchor", true);
add_existing_item<ScrollAnchor>(dependencies);
append_text(append(dependencies, "h2"), "Dependencies");
auto* dependencyList = append(dependencies, "catalog-dependencies");
size_t requiredDusklight = 0;
std::vector<std::string> dusklightProblems;
for (const auto& import : detail.serviceImports) {
if (import.optional) {
continue;
}
const bool available =
mods::svc::find_service(import.id.c_str(), import.major, import.minMinor) != nullptr;
if (import.id.starts_with(DUSKLIGHT_SERVICE_ID_PREFIX)) {
++requiredDusklight;
if (!available) {
dusklightProblems.push_back(mods::svc::describe_missing_service(
import.id.c_str(), import.major, import.minMinor));
}
continue;
}
auto* row = append(dependencyList, "catalog-dependency");
append_text_element(row, "catalog-dependency-name", import.id);
append_text_element(row, "catalog-dependency-status",
fmt::format("v{}.{}+ · {}", import.major, import.minMinor,
available ? "Available" : "Not available"));
row->SetClass("missing", !available);
}
const bool available =
mods::svc::find_service(import.id.c_str(), import.major, import.minMinor) != nullptr;
if (import.id.starts_with("dev.twilitrealm.dusklight.")) {
++requiredDusklight;
dusklightSatisfied = dusklightSatisfied && available;
continue;
if (requiredDusklight != 0) {
auto* row = append(dependencyList, "catalog-dependency");
append_text_element(row, "catalog-dependency-name", "Dusklight services");
append_text_element(row, "catalog-dependency-status",
dusklightProblems.empty() ? fmt::format("{} required · Available", requiredDusklight) :
fmt::format("{} required", requiredDusklight));
for (const auto& problem : dusklightProblems) {
append_text_element(row, "catalog-dependency-status", problem);
}
row->SetClass("missing", !dusklightProblems.empty());
}
auto* row = append(dependencyList, "catalog-dependency");
append_text_element(row, "catalog-dependency-name", import.id);
append_text_element(row, "catalog-dependency-status",
fmt::format("v{}.{}+ · {}", import.major, import.minMinor,
available ? "Available" : "Not available"));
row->SetClass("missing", !available);
}
if (requiredDusklight != 0) {
auto* row = append(dependencyList, "catalog-dependency");
append_text_element(row, "catalog-dependency-name", "Dusklight services");
append_text_element(row, "catalog-dependency-status",
fmt::format("{} required · {}", requiredDusklight,
dusklightSatisfied ? "Available" : "Update required"));
row->SetClass("missing", !dusklightSatisfied);
}
if (requiredDusklight == 0 && dependencyList->GetNumChildren() == 0) {
append_text(dependencyList, "No required dependencies.");
}
auto* changelog = append(main, "section");
@@ -718,27 +747,13 @@ DetailContent::DetailContent(
add_list_markers(changelogFragment);
}
append_text_element(sidebar, "h3", "Details");
auto* detailList = append(sidebar, "dl");
append_detail_field(detailList, "Version", detail.mod.version);
append_detail_field(detailList, "Updated", display_date(detail.mod.updatedAt));
append_detail_field(detailList, "Published", display_date(detail.mod.publishedAt));
append_detail_field(detailList, "Last updated", display_date(detail.mod.updatedAt));
append_detail_field(
detailList, "Category", detail.mod.category ? detail.mod.category->name : "Uncategorized");
append_detail_field(detailList, "License", detail.license.value_or("Not specified"));
append_detail_field(
detailList, "Mod ABI", detail.modAbi ? fmt::format("{}", *detail.modAbi) : "Assets only");
if (detail.sourceUrl && detail.sourceUrl->starts_with("https://")) {
auto* sourceActions = append(sidebar, "catalog-source-actions");
auto& sourceGroup =
add_existing_item<NavGroup>(sourceActions, Props{
.layout = Layout::Vertical,
.horizontalBoundary = Boundary::Bubble,
.verticalBoundary = Boundary::Bubble,
});
sourceGroup.add_item<Button>("View source").on_pressed([url = *detail.sourceUrl] {
open_web_url(url);
});
if (detail.license && !detail.license->empty()) {
append_detail_field(detailList, "License", *detail.license);
}
}
+22 -5
View File
@@ -15,6 +15,7 @@ std::string mod_image_source(const mods::LoadedMod& mod, std::string_view bundle
#ifdef AURORA_ENABLE_RMLUI
#include <RmlUi/Core.h>
#include <aurora/rmlui.hpp>
#include <borealis/log.hpp>
@@ -33,14 +34,15 @@ namespace dusk::ui {
namespace {
constexpr borealis::Log Log{"dusk::ui::modTexture"};
constexpr std::string_view kScheme = "mod";
constexpr std::string_view kSourcePrefix = "mod://";
constexpr size_t kMaxCachedImages = 64;
constexpr size_t kMaxCachedImageBytes = 64 * 1024 * 1024;
constexpr size_t kMaxImageFileSize = 16 * 1024 * 1024;
std::unordered_map<std::string, DecodedImage>& image_cache() {
static auto* cache = new std::unordered_map<std::string, DecodedImage>();
return *cache;
static std::unordered_map<std::string, DecodedImage> cache;
return cache;
}
std::string_view strip_query(std::string_view path) noexcept {
@@ -104,8 +106,20 @@ std::optional<aurora::rmlui::RuntimeTexture> mod_texture_provider(std::string_vi
if (!image) {
return std::nullopt;
}
if (cache.size() >= kMaxCachedImages) {
cache.erase(cache.begin());
if (image->pixels.size() > kMaxCachedImageBytes) {
return std::nullopt;
}
size_t cachedBytes = 0;
for (const auto& [source, cached] : cache) {
cachedBytes += cached.pixels.size();
}
while (cache.size() >= kMaxCachedImages ||
cachedBytes > kMaxCachedImageBytes - image->pixels.size())
{
const auto victim = cache.begin();
cachedBytes -= victim->second.pixels.size();
Rml::ReleaseTexture(victim->first);
cache.erase(victim);
}
it = cache.emplace(key, std::move(*image)).first;
}
@@ -129,6 +143,9 @@ void register_mod_texture_provider() noexcept {
void unregister_mod_texture_provider() noexcept {
aurora::rmlui::unregister_texture_provider(kScheme);
for (const auto& [source, image] : image_cache()) {
Rml::ReleaseTexture(source);
}
image_cache().clear();
}
+208 -49
View File
@@ -1,6 +1,7 @@
#include "mods_window.hpp"
#include "format.hpp"
#include "icon_button.hpp"
#include "logs_window.hpp"
#include "mod_browser.hpp"
#include "mod_texture_provider.hpp"
@@ -11,6 +12,7 @@
#include <borealis/http.hpp>
#include "dusk/data.hpp"
#include "dusk/mod_loader.hpp"
#include "dusk/mods/queue.hpp"
#include "dusk/mods/svc/net.hpp"
@@ -25,6 +27,7 @@
#include <cstddef>
#include <memory>
#include <optional>
#include <ranges>
#include <string>
#include <string_view>
@@ -58,10 +61,54 @@ bool mod_uses_network(const mods::LoadedMod& mod) {
});
}
enum class ModAction {
Retry,
Reload,
Enable,
Disable,
Logs,
OpenFolder,
Uninstall,
};
struct ModActionInfo {
ModAction action;
const char* text;
const char* icon;
};
std::vector<ModActionInfo> available_mod_actions(const mods::LoadedMod& mod) {
std::vector<ModActionInfo> actions;
if (mod.activation_failed()) {
actions.push_back({ModAction::Retry, "Retry", "replay"});
actions.push_back({ModAction::Disable, "Disable", "pause"});
} else if (mod.is_enabled()) {
if (!mod.nativeInPlace) {
actions.push_back({ModAction::Reload, "Reload", "refresh"});
}
actions.push_back({ModAction::Disable, "Disable", "pause"});
} else {
actions.push_back({ModAction::Enable, "Enable", "play_arrow"});
}
actions.push_back({ModAction::Logs, "Logs", "notes"});
if (data::manager().capabilities().canOpenFolder) {
actions.push_back({ModAction::OpenFolder, "Open folder", "folder_open"});
}
if (mods::ModLoader::instance().can_uninstall(mod)) {
actions.push_back({
ModAction::Uninstall,
mod.hasBundledCopy ? "Remove update" : "Uninstall",
"delete",
});
}
return actions;
}
class ModListEntry : public FluentComponent<ModListEntry> {
public:
ModListEntry(Rml::Element* parent, const mods::LoadedMod& mod)
: FluentComponent{append(parent, "mod-entry")} {
mRoot->SetAttribute("mod-id", mod.metadata.id);
auto* icon = append(mRoot, "mod-icon");
if (!mod.metadata.iconPath.empty()) {
auto* image = append(icon, "img");
@@ -171,42 +218,23 @@ private:
class ModDetailHeader : public FluentComponent<ModDetailHeader> {
public:
ModDetailHeader(Rml::Element* parent, const mods::LoadedMod& mod,
std::function<void()> onShowLogs, std::function<void()> onUninstall)
ModDetailHeader(
Rml::Element* parent, const mods::LoadedMod& mod, std::vector<ContextMenu::Item> items)
: FluentComponent{append(parent, "mod-header")} {
mRoot->SetAttribute("mod-id", mod.metadata.id);
const bool hasBanner = !mod.metadata.bannerPath.empty();
mRoot->SetClass(hasBanner ? "has-banner" : "no-banner", true);
mRoot->SetClass("inactive", !mod.active);
if (hasBanner) {
mRoot->SetProperty("decorator", fmt::format(R"(image("{}" cover center center))",
auto* image = append(mRoot, "mod-header-image");
image->SetProperty("decorator", fmt::format(R"(image("{}" cover center center))",
mod_image_source(mod, mod.metadata.bannerPath)));
}
auto* actions = append(mRoot, "mod-actions");
const std::string modId = mod.metadata.id;
if (mod.activation_failed()) {
make_button(actions, "Retry").on_pressed([modId] {
mods::ModLoader::instance().request_reactivate(modId);
});
make_button(actions, "Disable").on_pressed([modId] {
mods::ModLoader::instance().request_disable(modId);
});
} else if (mod.is_enabled()) {
if (!mod.nativeInPlace) {
make_button(actions, "Reload").on_pressed([modId] {
mods::ModLoader::instance().request_reload(modId);
});
}
make_button(actions, "Disable").on_pressed([modId] {
mods::ModLoader::instance().request_disable(modId);
});
} else {
make_button(actions, "Enable").on_pressed([modId] {
mods::ModLoader::instance().request_enable(modId);
});
}
make_button(actions, "Logs").on_pressed(std::move(onShowLogs));
if (mods::ModLoader::instance().can_uninstall(mod)) {
make_button(actions, "Uninstall").on_pressed(std::move(onUninstall));
for (auto& item : items) {
auto& button = make_button(actions, item);
button.on_pressed(std::move(item.onPressed));
}
listen(Rml::EventId::Keydown, [this](Rml::Event& event) {
@@ -242,8 +270,9 @@ public:
}
private:
Button& make_button(Rml::Element* parent, Rml::String text) {
auto button = std::make_unique<Button>(parent, std::move(text));
Button& make_button(Rml::Element* parent, const ContextMenu::Item& item) {
auto button = std::make_unique<IconButton>(
parent, IconButton::Props{.icon = item.icon, .label = item.text});
Button& ref = *button;
mChildren.emplace_back(std::move(button));
mButtons.push_back(&ref);
@@ -255,7 +284,14 @@ private:
} // namespace
ModsWindow::ModsWindow() : Window{Props{.tabBar = false, .styleSheets = {"res/rml/mods.rcss"}}} {
ModsWindow::ModsWindow()
: Window{Props{.tabBar = false, .styleSheets = {"res/rml/mods.rcss"}}},
mContextMenu{*this, mRoot, "mod-entry, mod-header", [this](Rml::Element* target) {
const auto id = target->GetAttribute<Rml::String>("mod-id", "");
auto* mod = mods::ModLoader::instance().find_mod(id);
return mod != nullptr ? mod_actions(*mod, true) :
std::vector<ContextMenu::Item>{};
}} {
mRoot->SetClass("mods", true);
refresh_snapshot();
@@ -264,6 +300,104 @@ ModsWindow::ModsWindow() : Window{Props{.tabBar = false, .styleSheets = {"res/rm
set_content([this](Rml::Element* content) { build_content(content); });
}
void ModsWindow::hide(bool close) {
mContextMenu.dismiss();
Window::hide(close);
}
bool ModsWindow::select_mod(std::string_view id) {
if (mods::ModLoader::instance().find_mod(id) == nullptr) {
return false;
}
mContextMenu.dismiss();
mSelectedModId = id;
mSelectedMod = nullptr;
mBrowserSelected = false;
mFocusSelectedMod = true;
refresh_snapshot();
mQueueItemCount = mods::queue::item_count();
rebuild_content();
return true;
}
bool ModsWindow::focus() {
if (mFocusSelectedMod) {
mDocument->UpdateDocument();
for (size_t i = 0; i < mEntryMods.size(); ++i) {
if (mEntryMods[i]->metadata.id == mSelectedModId && mEntries[i]->focus()) {
mEntries[i]->set_selected(true);
mFocusSelectedMod = false;
return true;
}
}
}
return Window::focus();
}
std::vector<ContextMenu::Item> ModsWindow::mod_actions(
const mods::LoadedMod& mod, bool contextMenu) {
std::vector<ContextMenu::Item> items;
for (const auto& info : available_mod_actions(mod)) {
if (!contextMenu && info.action == ModAction::OpenFolder) {
continue;
}
items.push_back({
.text = info.text,
.icon = info.icon,
.onPressed =
[this, id = mod.metadata.id, action = info.action] {
auto& loader = mods::ModLoader::instance();
auto* current = loader.find_mod(id);
if (current == nullptr) {
return;
}
const auto actions = available_mod_actions(*current);
if (std::ranges::none_of(
actions, [action](const auto& info) { return info.action == action; }))
{
return;
}
switch (action) {
case ModAction::Retry:
loader.request_reactivate(id);
break;
case ModAction::Reload:
loader.request_reload(id);
break;
case ModAction::Enable:
loader.request_enable(id);
break;
case ModAction::Disable:
loader.request_disable(id);
break;
case ModAction::Logs:
push(std::make_unique<LogsWindow>(id));
break;
case ModAction::Uninstall:
confirm_uninstall(*current);
break;
case ModAction::OpenFolder: {
const auto folder = current->fromDirectory ? current->modPath :
current->modPath.parent_path();
if (!data::manager().open_folder(folder)) {
push(std::make_unique<Modal>(Modal::Props{
.title = "Could not open folder",
.bodyText =
"The mod folder could not be opened in the file browser.",
.actions = {{"OK", [](Modal& modal) { modal.pop(); }, {}}},
}));
}
break;
}
}
},
.destructive = info.action == ModAction::Uninstall,
.separatorBefore = info.action == ModAction::Uninstall,
});
}
return items;
}
void ModsWindow::build_content(Rml::Element* content) {
mEntries.clear();
mEntryMods.clear();
@@ -346,27 +480,25 @@ void ModsWindow::build_content(Rml::Element* content) {
void ModsWindow::build_detail(Pane& pane, mods::LoadedMod& mod) {
pane.root()->SetAttribute("mod-id", mod.metadata.id);
pane.add_child<ModDetailHeader>(
mod, [this, id = mod.metadata.id] { push(std::make_unique<LogsWindow>(id)); },
[this, tracked = &mod] { confirm_uninstall(*tracked); });
pane.add_child<ModDetailHeader>(mod, mod_actions(mod, false));
auto* title = append(pane.root(), "mod-title");
append_text(title, fmt::format("{} ", mod.metadata.name));
append_text(append(title, "small"), fmt::format("v{}", mod.metadata.version));
if (mod.loadFailed || mod.suspendedByProvider) {
const auto status = mod_status(mod);
append_text(title, "\u00a0");
auto* badge = append(title, "status-badge");
badge->SetClass(status.badgeClass, true);
append_text(badge, status.text);
}
if (mod_uses_network(mod)) {
append_text(title, "\u00a0");
auto* badge = append(title, "status-badge");
badge->SetClass("network", true);
append_text(badge, "Network");
}
append_text(append(pane.root(), "mod-author"), fmt::format("by {}", mod.metadata.author));
auto* author = append(pane.root(), "mod-author");
append_text(author, fmt::format("by {}\u00a0·\u00a0", mod.metadata.author));
const auto status = mod_status(mod);
auto* badge = append(author, "status-badge");
if (status.badgeClass[0] != '\0') {
badge->SetClass(status.badgeClass, true);
}
append_text(badge, status.text);
if (mod.loadFailed && !mod.failureReason.empty()) {
auto* row = append(pane.root(), "mod-info-row");
@@ -409,7 +541,11 @@ void ModsWindow::build_detail(Pane& pane, mods::LoadedMod& mod) {
}
void ModsWindow::confirm_uninstall(const mods::LoadedMod& mod) {
std::string body = "The mod package will be removed. Settings and saved data are kept.";
const std::string action = mod.hasBundledCopy ? "Remove update" : "Uninstall";
std::string body = mod.hasBundledCopy ?
"Installed mod will be reverted back to the bundled version. Settings "
"and saved data are kept." :
"Installed mod will be removed. Settings and saved data are kept.";
std::vector<std::string_view> dependents;
for (const auto& edge : mod.dependents) {
if (!edge.required || edge.mod == nullptr) {
@@ -418,17 +554,17 @@ void ModsWindow::confirm_uninstall(const mods::LoadedMod& mod) {
dependents.push_back(edge.mod->metadata.name);
}
if (!dependents.empty()) {
body = fmt::format(
"{} Required dependents will be suspended: {}.", body, fmt::join(dependents, ", "));
body = fmt::format("{} Required dependents: {}.", body, fmt::join(dependents, ", "));
}
push(std::make_unique<Modal>(Modal::Props{
.title = fmt::format("Uninstall {}?", mod.metadata.name),
.title = mod.hasBundledCopy ? fmt::format("Revert {}?", mod.metadata.name) :
fmt::format("Uninstall {}?", mod.metadata.name),
.bodyText = std::move(body),
.actions =
{
ModalAction{"Cancel", [](Modal& modal) { modal.pop(); }, {}},
ModalAction{"Uninstall",
ModalAction{action,
[id = mod.metadata.id](Modal& modal) {
mods::ModLoader::instance().request_uninstall(id);
modal.pop();
@@ -494,6 +630,14 @@ void ModsWindow::update() {
dirty = true;
}
if (dirty) {
mContextMenu.dismiss();
const auto previousModId = mSelectedModId;
std::optional<Rml::Property> previousBannerFilter;
if (auto* image = mContentRoot->QuerySelector("mod-header-image")) {
previousBannerFilter = *image->GetProperty(Rml::PropertyId::Filter);
}
auto* list = mContentRoot->QuerySelector("pane.mod-list");
const float listScrollTop = list != nullptr ? list->GetScrollTop() : 0.0f;
auto* focused = mDocument != nullptr ? mDocument->GetFocusLeafNode() : nullptr;
bool hadContentFocus = false;
for (auto* node = focused; node != nullptr; node = node->GetParentNode()) {
@@ -503,18 +647,33 @@ void ModsWindow::update() {
}
}
rebuild_content();
mDocument->UpdateDocument();
if (hadContentFocus) {
if (mBrowserSelected && mBrowserEntry != nullptr) {
mBrowserEntry->focus();
mBrowserEntry->root()->Focus(true);
} else {
for (size_t i = 0; i < mEntryMods.size(); ++i) {
if (mEntryMods[i] == mSelectedMod) {
mEntries[i]->focus();
mEntries[i]->root()->Focus(true);
break;
}
}
}
}
if (previousBannerFilter && previousModId == mSelectedModId) {
mDocument->UpdateDocument();
if (auto* image = mContentRoot->QuerySelector("mod-header-image")) {
const auto target = *image->GetProperty(Rml::PropertyId::Filter);
if (*previousBannerFilter != target) {
image->SetProperty(Rml::PropertyId::Filter, *previousBannerFilter);
image->Animate(Rml::PropertyId::Filter, target, 0.2f,
Rml::Tween{Rml::Tween::Cubic, Rml::Tween::InOut}, 1, false);
}
}
}
if (auto* refreshedList = mContentRoot->QuerySelector("pane.mod-list")) {
refreshedList->SetScrollTop(listScrollTop);
}
}
if (mSelectedMod != nullptr && mSelectedMod->active) {
+8
View File
@@ -1,9 +1,11 @@
#pragma once
#include "window.hpp"
#include "context_menu.hpp"
#include <cstddef>
#include <string>
#include <string_view>
#include <vector>
#include "dusk/mod_loader.hpp"
@@ -15,7 +17,10 @@ class Pane;
class ModsWindow : public Window {
public:
ModsWindow();
void hide(bool close) override;
void update() override;
bool focus() override;
bool select_mod(std::string_view id);
private:
struct ModSnapshot {
@@ -30,6 +35,7 @@ private:
void build_content(Rml::Element* content);
void build_detail(Pane& pane, mods::LoadedMod& mod);
void confirm_uninstall(const mods::LoadedMod& mod);
std::vector<ContextMenu::Item> mod_actions(const mods::LoadedMod& mod, bool contextMenu);
void refresh_snapshot();
void mark_current_entry();
@@ -42,6 +48,8 @@ private:
uint64_t mLoaderGeneration = 0;
size_t mQueueItemCount = 0;
bool mBrowserSelected = false;
bool mFocusSelectedMod = false;
ContextMenu::Binding mContextMenu;
};
} // namespace dusk::ui
+7 -1
View File
@@ -23,7 +23,7 @@ constexpr float kViewportMarginDp = 8.0f;
} // namespace
Popover::Popover(Rml::Element* anchor, Side side, const Rml::String& windowClass)
: Document{kDocumentSource}, mAnchor{anchor}, mSide{side},
: Document{kDocumentSource}, mAnchor{anchor->GetObserverPtr()}, mSide{side},
mBody{mDocument->GetElementById("popover")} {
if (!windowClass.empty()) {
mBody->SetClass(windowClass, true);
@@ -108,6 +108,9 @@ bool Popover::handle_nav_command(Rml::Event&, NavCommand cmd) {
}
void Popover::reposition() {
if (!mAnchor) {
return;
}
auto* context = mDocument->GetContext();
const auto dimensions = Rml::Vector2f{context->GetDimensions()};
const float dpRatio = context->GetDensityIndependentPixelRatio();
@@ -135,6 +138,9 @@ void Popover::reposition() {
break;
}
if (mPosition) {
pos = *mPosition;
}
pos.x = std::clamp(pos.x, margin, std::max(margin, dimensions.x - size.x - margin));
pos.y = std::clamp(pos.y, margin, std::max(margin, dimensions.y - size.y - margin));
mBody->SetProperty(Rml::PropertyId::Left, Rml::Property{pos.x, Rml::Unit::PX});
+6 -1
View File
@@ -2,6 +2,8 @@
#include "document.hpp"
#include <optional>
namespace dusk::ui {
class Popover : public Document {
@@ -24,6 +26,8 @@ public:
Rml::Element* body() const { return mBody; }
void set_position(Rml::Vector2f position) { mPosition = position; }
void dismiss();
void on_close(std::function<void()> callback) { mOnClose = std::move(callback); }
void on_focus(std::function<bool()> callback) { mOnFocus = std::move(callback); }
@@ -35,7 +39,8 @@ private:
void reposition();
void notify_close(bool restoreFocus);
Rml::Element* mAnchor = nullptr;
Rml::ObserverPtr<Rml::Element> mAnchor;
std::optional<Rml::Vector2f> mPosition;
Side mSide;
Rml::Element* mBody = nullptr;
std::function<void()> mOnClose;
+51 -13
View File
@@ -45,6 +45,8 @@ constexpr borealis::Log Log{"dusk::ui"};
constexpr std::string_view kScheme = "https";
constexpr std::string_view kAllowedPrefix = "https://staging.twilitrealm.workers.dev/images/v1/";
constexpr size_t kMaxCachedImages = 64;
constexpr size_t kMaxCachedImageBytes = 64 * 1024 * 1024;
constexpr size_t kMaxPendingRequests = 4;
constexpr size_t kMaxImageFileSize = 16 * 1024 * 1024;
// RmlUi caches the first texture dimensions in image decorators, so the async
// placeholder must preserve the final image's aspect ratio.
@@ -126,19 +128,29 @@ RemoteSource parse_remote_source(std::string_view source) noexcept {
return result;
}
bool make_cache_room() {
bool make_cache_room(size_t incomingBytes = 0, bool addingEntry = true) {
auto& cache = image_cache();
if (cache.size() < kMaxCachedImages) {
return true;
size_t cachedBytes = 0;
for (const auto& [source, entry] : cache) {
cachedBytes += entry.image.pixels.size();
}
const auto victim = std::ranges::min_element(cache, {}, [](const auto& pair) {
return pair.second.state == State::Pending ? std::numeric_limits<uint64_t>::max() :
pair.second.lastUsed;
});
if (victim == cache.end() || victim->second.state == State::Pending) {
if (incomingBytes > kMaxCachedImageBytes) {
return false;
}
cache.erase(victim);
while (cachedBytes > kMaxCachedImageBytes - incomingBytes ||
(addingEntry && cache.size() >= kMaxCachedImages))
{
const auto victim = std::ranges::min_element(cache, {}, [](const auto& pair) {
return pair.second.state == State::Pending ? std::numeric_limits<uint64_t>::max() :
pair.second.lastUsed;
});
if (victim == cache.end() || victim->second.state == State::Pending) {
return false;
}
cachedBytes -= victim->second.image.pixels.size();
Rml::ReleaseTexture(victim->first);
cache.erase(victim);
}
return true;
}
@@ -193,10 +205,6 @@ std::optional<aurora::rmlui::RuntimeTexture> remote_texture_provider(std::string
})
.first;
}
if (iter->second.state == State::Unrequested) {
iter->second.request = start_request(std::string{parsed.requestUrl});
iter->second.state = State::Pending;
}
iter->second.lastUsed = ++use_counter();
if (iter->second.state != State::Ready) {
return transparent_texture(iter->second);
@@ -229,6 +237,11 @@ void finish_request(const std::string& source, Entry& entry, borealis::http::Res
entry.state = State::Failed;
return;
}
if (!make_cache_room(image->pixels.size(), false)) {
entry.state = State::Failed;
Log.warn("Image '{}' exceeds the decoded image cache budget", source);
return;
}
entry.image = std::move(*image);
entry.state = State::Ready;
@@ -244,6 +257,10 @@ void register_remote_texture_provider() noexcept {
void unregister_remote_texture_provider() noexcept {
aurora::rmlui::unregister_texture_provider(kScheme);
for (auto& [source, entry] : image_cache()) {
entry.request.cancel();
Rml::ReleaseTexture(source);
}
image_cache().clear();
use_counter() = 0;
}
@@ -266,6 +283,27 @@ void update_remote_texture_provider() noexcept {
}
entry.request = {};
}
size_t pending = std::ranges::count_if(
image_cache(), [](const auto& pair) { return pair.second.state == State::Pending; });
for (auto& [source, entry] : image_cache()) {
if (pending >= kMaxPendingRequests) {
break;
}
if (entry.state == State::Unrequested) {
try {
entry.request = start_request(std::string{parse_remote_source(source).requestUrl});
entry.state = State::Pending;
++pending;
} catch (const std::exception& exception) {
entry.state = State::Failed;
Log.warn("Failed to request image '{}': {}", source, exception.what());
} catch (...) {
entry.state = State::Failed;
Log.warn("Failed to request image '{}'", source);
}
}
}
}
} // namespace dusk::ui
+26 -45
View File
@@ -1,11 +1,10 @@
#include "runtime_image.hpp"
#include <SDL3/SDL_iostream.h>
#include <SDL3/SDL_surface.h>
#include <borealis/log.hpp>
#include <png.h>
#include <cstddef>
#include <cstring>
#include <memory>
namespace dusk::ui {
namespace {
@@ -16,55 +15,37 @@ constexpr uint32_t kMaxImageDimension = 4096;
} // namespace
std::optional<DecodedImage> decode_png(std::span<const uint8_t> data, std::string_view source) {
SDL_IOStream* stream = SDL_IOFromConstMem(data.data(), data.size());
if (stream == nullptr) {
Log.warn("Failed to open image stream for '{}': {}", source, SDL_GetError());
png_image png{};
png.version = PNG_IMAGE_VERSION;
const std::unique_ptr<png_image, decltype(&png_image_free)> cleanup{&png, png_image_free};
if (!png_image_begin_read_from_memory(&png, data.data(), data.size())) {
Log.warn("Failed to read image header '{}': {}", source, png.message);
return std::nullopt;
}
if (png.width == 0 || png.height == 0 || png.width > kMaxImageDimension ||
png.height > kMaxImageDimension)
{
Log.warn("Image '{}' has unsupported dimensions {}x{}", source, png.width, png.height);
return std::nullopt;
}
SDL_Surface* loadedSurface = SDL_LoadPNG_IO(stream, true);
if (loadedSurface == nullptr) {
Log.warn("Failed to decode image '{}': {}", source, SDL_GetError());
return std::nullopt;
}
SDL_Surface* rgbaSurface = SDL_ConvertSurface(loadedSurface, SDL_PIXELFORMAT_RGBA32);
SDL_DestroySurface(loadedSurface);
if (rgbaSurface == nullptr) {
Log.warn("Failed to convert image '{}': {}", source, SDL_GetError());
return std::nullopt;
}
const auto width = static_cast<uint32_t>(rgbaSurface->w);
const auto height = static_cast<uint32_t>(rgbaSurface->h);
if (width == 0 || height == 0 || width > kMaxImageDimension || height > kMaxImageDimension) {
Log.warn("Image '{}' has unsupported dimensions {}x{}", source, width, height);
SDL_DestroySurface(rgbaSurface);
return std::nullopt;
}
const size_t rowSize = static_cast<size_t>(width) * 4;
png.format = PNG_FORMAT_RGBA;
DecodedImage image{
.pixels = std::vector<uint8_t>(rowSize * height),
.width = width,
.height = height,
.width = png.width,
.height = png.height,
};
for (uint32_t row = 0; row < height; ++row) {
const auto* src = static_cast<const uint8_t*>(rgbaSurface->pixels) +
static_cast<size_t>(row) * static_cast<size_t>(rgbaSurface->pitch);
auto* dst = image.pixels.data() + static_cast<size_t>(row) * rowSize;
std::memcpy(dst, src, rowSize);
for (size_t col = 0; col < rowSize; col += 4) {
const uint8_t alpha = dst[col + 3];
for (size_t channel = 0; channel < 3; ++channel) {
dst[col + channel] =
static_cast<uint8_t>((static_cast<uint32_t>(dst[col + channel]) * alpha) / 255);
}
image.pixels.resize(PNG_IMAGE_SIZE(png));
if (!png_image_finish_read(&png, nullptr, image.pixels.data(), 0, nullptr)) {
Log.warn("Failed to decode image '{}': {}", source, png.message);
return std::nullopt;
}
for (size_t offset = 0; offset < image.pixels.size(); offset += 4) {
const uint8_t alpha = image.pixels[offset + 3];
for (size_t channel = 0; channel < 3; ++channel) {
image.pixels[offset + channel] = static_cast<uint8_t>(
(static_cast<uint32_t>(image.pixels[offset + channel]) * alpha) / 255);
}
}
SDL_DestroySurface(rgbaSurface);
return image;
}
+61
View File
@@ -0,0 +1,61 @@
#include "tooltip.hpp"
#include "ui.hpp"
#include <algorithm>
namespace dusk::ui {
Tooltip::Tooltip(Rml::Element* anchor, const Rml::String& label)
: mAnchor{anchor}, mRoot{append(anchor->GetOwnerDocument(), "ui-tooltip")},
mFollowsFocus{anchor->GetContext()->GetHoverElement() == nullptr},
mMouseMove{anchor->GetContext()->GetRootElement(), Rml::EventId::Mousemove,
[this](Rml::Event&) { mFollowsFocus = false; }, true},
mMouseDown{anchor->GetContext()->GetRootElement(), Rml::EventId::Mousedown,
[this](Rml::Event&) { mFollowsFocus = false; }, true},
mKeyDown{anchor->GetContext()->GetRootElement(), Rml::EventId::Keydown,
[this](Rml::Event& event) {
if (map_nav_event(event) != NavCommand::None) {
mFollowsFocus = true;
}
},
true} {
// Attach outside the pane so scrolling and overflow cannot clip the label.
append_text(mRoot, label);
}
Tooltip::~Tooltip() {
mRoot->GetParentNode()->RemoveChild(mRoot);
}
void Tooltip::update() {
auto* context = mAnchor->GetContext();
const bool active = mFollowsFocus ? mAnchor->Contains(context->GetFocusElement()) :
mAnchor->IsPseudoClassSet("hover");
const bool visible =
!mAnchor->IsPseudoClassSet("disabled") && mAnchor->IsVisible(true) && active;
const bool opening = visible && !mRoot->IsClassSet("visible");
mRoot->SetClass("visible", visible);
if (!visible) {
return;
}
if (opening) {
mRoot->GetOwnerDocument()->UpdateDocument();
}
const float margin = 8.0f * context->GetDensityIndependentPixelRatio();
const auto dimensions = Rml::Vector2f{context->GetDimensions()};
const auto anchor = mAnchor->GetAbsoluteOffset(Rml::BoxArea::Border);
const auto anchorSize = mAnchor->GetBox().GetSize(Rml::BoxArea::Border);
const auto size = mRoot->GetBox().GetSize(Rml::BoxArea::Border);
float x = anchor.x + (anchorSize.x - size.x) * 0.5f;
float y = anchor.y + anchorSize.y + margin;
if (y + size.y > dimensions.y - margin) {
y = anchor.y - size.y - margin;
}
x = std::clamp(x, margin, std::max(margin, dimensions.x - size.x - margin));
y = std::clamp(y, margin, std::max(margin, dimensions.y - size.y - margin));
mRoot->SetProperty(Rml::PropertyId::Left, Rml::Property{x, Rml::Unit::PX});
mRoot->SetProperty(Rml::PropertyId::Top, Rml::Property{y, Rml::Unit::PX});
}
} // namespace dusk::ui
+26
View File
@@ -0,0 +1,26 @@
#pragma once
#include "event.hpp"
namespace dusk::ui {
class Tooltip {
public:
Tooltip(Rml::Element* anchor, const Rml::String& label);
~Tooltip();
Tooltip(const Tooltip&) = delete;
Tooltip& operator=(const Tooltip&) = delete;
void update();
private:
Rml::Element* mAnchor;
Rml::Element* mRoot;
bool mFollowsFocus;
ScopedEventListener mMouseMove;
ScopedEventListener mMouseDown;
ScopedEventListener mKeyDown;
};
} // namespace dusk::ui
+44
View File
@@ -325,6 +325,50 @@ Document& push_document(std::unique_ptr<Document> doc, bool show, bool passive)
return ret;
}
Document& detail::pop_to_or_push_document(bool (*matches)(Document&),
const std::function<std::unique_ptr<Document>()>& create,
const std::function<void(Document&)>& configure) {
Document* destination = nullptr;
size_t destinationIndex = 0;
for (size_t i = sDocumentStack.size(); i > 0; --i) {
auto& document = *sDocumentStack[i - 1];
if (!document.closed() && !document.pending_close() && matches(document)) {
destination = &document;
destinationIndex = i - 1;
break;
}
}
if (destination != nullptr) {
std::vector<Document*> closing;
for (size_t i = sDocumentStack.size(); i > destinationIndex + 1; --i) {
closing.push_back(sDocumentStack[i - 1].get());
}
for (auto* document : closing) {
if (!document->closed() && !document->pending_close()) {
if (document->visible()) {
document->hide(true);
} else {
document->force_hide(true);
}
}
}
configure(*destination);
} else {
auto document = create();
configure(*document);
if (auto* current = top_document()) {
current->cover();
}
destination = &push_document(std::move(document), false);
}
destination->show();
destination->focus();
input::sync_input_block();
return *destination;
}
void bring_document_to_front(Document& doc) noexcept {
const auto it = std::ranges::find_if(
sDocumentStack, [&doc](const auto& entry) { return entry.get() == &doc; });
+21
View File
@@ -4,9 +4,11 @@
#include <SDL3/SDL_events.h>
#include <filesystem>
#include <functional>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include "nav_types.hpp"
@@ -88,6 +90,25 @@ void update() noexcept;
Document& push_document(
std::unique_ptr<Document> doc, bool show = true, bool passive = false) noexcept;
namespace detail {
Document& pop_to_or_push_document(bool (*matches)(Document&),
const std::function<std::unique_ptr<Document>()>& create,
const std::function<void(Document&)>& configure);
}
template <typename T, typename Configure, typename... Args>
T& pop_to_or_push(Configure&& configure, Args&&... args) {
return static_cast<T&>(detail::pop_to_or_push_document(
[](Document& document) { return dynamic_cast<T*>(&document) != nullptr; },
[&]() -> std::unique_ptr<Document> {
return std::make_unique<T>(std::forward<Args>(args)...);
},
[&](Document& document) {
std::invoke(std::forward<Configure>(configure), static_cast<T&>(document));
}));
}
void bring_document_to_front(Document& doc) noexcept;
bool register_scoped_styles(DocumentScope scope, std::string id, const std::string& rcss) noexcept;
void unregister_scoped_styles(DocumentScope scope, std::string_view id) noexcept;