Merge branch 'sync' into sneed

This commit is contained in:
Vindicus999
2026-07-25 22:36:30 -04:00
25 changed files with 829 additions and 620 deletions
+2
View File
@@ -32,8 +32,10 @@ jobs:
- name: Run ruff lint check - name: Run ruff lint check
uses: astral-sh/ruff-action@v3 uses: astral-sh/ruff-action@v3
with: with:
version: "0.16.0"
args: "check" args: "check"
- name: Run ruff format check - name: Run ruff format check
uses: astral-sh/ruff-action@v3 uses: astral-sh/ruff-action@v3
with: with:
version: "0.16.0"
args: "format --check" args: "format --check"
+1 -1
View File
@@ -96,7 +96,7 @@ tasks.register("generatePngs", GeneratePngsTask) {
android { android {
namespace = "org.meumeu.wivrn" namespace = "org.meumeu.wivrn"
ndkVersion = "28.2.13676358" ndkVersion = "29.0.14206865"
lint { lint {
disable += "ExpiredTargetSdkVersion" disable += "ExpiredTargetSdkVersion"
+27 -7
View File
@@ -829,9 +829,6 @@ void application::initialize_vulkan()
} }
#endif #endif
} }
std::ranges::sort(extensions);
for (const auto & [extension_name, spec_version]: extensions)
spdlog::info(" {} (version {})", extension_name, spec_version);
vk_device_extensions.push_back(VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME); vk_device_extensions.push_back(VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME);
vk_device_extensions.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME); vk_device_extensions.push_back(VK_KHR_SAMPLER_YCBCR_CONVERSION_EXTENSION_NAME);
@@ -853,6 +850,19 @@ void application::initialize_vulkan()
instance_extensions.push_back(VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME); instance_extensions.push_back(VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME);
#endif #endif
std::ranges::sort(extensions);
for (const auto & [extension_name, spec_version]: extensions)
{
if (runtime_hmd_traits.blacklisted_extensions.contains(extension_name))
{
spdlog::info(" {} (version {}) (blacklisted)", extension_name, spec_version);
if (std::ranges::find(instance_extensions, extension_name) != instance_extensions.end())
throw std::runtime_error("Required Vulkan instance extension is blacklisted");
}
else
spdlog::info(" {} (version {})", extension_name, spec_version);
}
vk::ApplicationInfo application_info{ vk::ApplicationInfo application_info{
.pApplicationName = app_info.name.c_str(), .pApplicationName = app_info.name.c_str(),
.applicationVersion = (uint32_t)app_info.version, .applicationVersion = (uint32_t)app_info.version,
@@ -912,9 +922,19 @@ void application::initialize_vulkan()
spdlog::info("Available Vulkan device extensions:"); spdlog::info("Available Vulkan device extensions:");
for (const auto & [extension_name, spec_version]: extensions) for (const auto & [extension_name, spec_version]: extensions)
{ {
spdlog::info(" {} (version {})", extension_name, spec_version); if (runtime_hmd_traits.blacklisted_extensions.contains(extension_name))
if (auto it = optional_device_extensions.find(extension_name); it != optional_device_extensions.end()) {
vk_device_extensions.push_back(it->data()); spdlog::info(" {} (version {}) (blacklisted)", extension_name, spec_version);
if (std::ranges::find(vk_device_extensions, extension_name) != instance_extensions.end())
throw std::runtime_error("Required Vulkan device extension is blacklisted");
}
else
{
spdlog::info(" {} (version {})", extension_name, spec_version);
if (auto it = optional_device_extensions.find(extension_name); it != optional_device_extensions.end())
vk_device_extensions.push_back(it->data());
}
} }
spdlog::info("Initializing Vulkan with device {}", physical_device_properties.deviceName.data()); spdlog::info("Initializing Vulkan with device {}", physical_device_properties.deviceName.data());
@@ -1312,7 +1332,7 @@ void application::initialize()
auto it = std::find_if(opt_extensions.begin(), auto it = std::find_if(opt_extensions.begin(),
opt_extensions.end(), opt_extensions.end(),
[&ext](const char * i) { return strcmp(i, ext.extensionName) == 0; }); [&ext](const char * i) { return strcmp(i, ext.extensionName) == 0; });
if (it != opt_extensions.end()) if (it != opt_extensions.end() and not runtime_hmd_traits.blacklisted_extensions.contains(ext.extensionName))
xr_extensions.push_back(*it); xr_extensions.push_back(*it);
} }
+2 -6
View File
@@ -80,11 +80,7 @@ int32_t wivrn::android::audio::speaker_data_cb(AAudioStream * stream, void * use
{ {
// Buffer underrun: add 5ms buffer // Buffer underrun: add 5ms buffer
size_t target_buffer_size = frame_size * AAudioStream_getSampleRate(stream) * 0.005; size_t target_buffer_size = frame_size * AAudioStream_getSampleRate(stream) * 0.005;
#if __cpp_lib_shared_ptr_arrays >= 201707L
self->speaker_tmp.data.c = std::make_shared<uint8_t[]>(target_buffer_size, 0); self->speaker_tmp.data.c = std::make_shared<uint8_t[]>(target_buffer_size, 0);
#else
self->speaker_tmp.data.c.reset(new uint8_t[target_buffer_size]());
#endif
self->speaker_tmp.payload = std::span(self->speaker_tmp.data.c.get(), target_buffer_size); self->speaker_tmp.payload = std::span(self->speaker_tmp.data.c.get(), target_buffer_size);
self->buffer_size_bytes += target_buffer_size; self->buffer_size_bytes += target_buffer_size;
spdlog::debug("Audio sync: underrun, add {} bytes buffer", spdlog::debug("Audio sync: underrun, add {} bytes buffer",
@@ -159,9 +155,9 @@ void wivrn::android::audio::build_microphone(AAudioStreamBuilder * builder, int3
AAudioStreamBuilder_setSharingMode(builder, AAUDIO_SHARING_MODE_EXCLUSIVE); AAudioStreamBuilder_setSharingMode(builder, AAUDIO_SHARING_MODE_EXCLUSIVE);
AAudioStreamBuilder_setFormat(builder, AAUDIO_FORMAT_PCM_I16); AAudioStreamBuilder_setFormat(builder, AAUDIO_FORMAT_PCM_I16);
if (application::get_config().mic_unprocessed_audio) if (application::get_config().mic_unprocessed_audio)
{
AAudioStreamBuilder_setInputPreset(builder, AAUDIO_INPUT_PRESET_UNPROCESSED); AAudioStreamBuilder_setInputPreset(builder, AAUDIO_INPUT_PRESET_UNPROCESSED);
} else
AAudioStreamBuilder_setInputPreset(builder, AAUDIO_INPUT_PRESET_VOICE_COMMUNICATION);
AAudioStreamBuilder_setDataCallback(builder, &microphone_data_cb, this); AAudioStreamBuilder_setDataCallback(builder, &microphone_data_cb, this);
AAudioStreamBuilder_setErrorCallback(builder, &microphone_error_cb, this); AAudioStreamBuilder_setErrorCallback(builder, &microphone_error_cb, this);
+137 -71
View File
@@ -19,8 +19,11 @@
#include "hmd_traits.h" #include "hmd_traits.h"
#include "utils/overloaded.h"
#include "utils/strings.h"
#include "xr/to_string.h" #include "xr/to_string.h"
#include <boost/pfr.hpp>
#include <cassert> #include <cassert>
#include <cctype> #include <cctype>
#include <cstdlib> #include <cstdlib>
@@ -30,6 +33,8 @@
#include <limits> #include <limits>
#include <optional> #include <optional>
#include <string> #include <string>
#include <type_traits>
#include <unordered_map>
#include <spdlog/spdlog.h> #include <spdlog/spdlog.h>
@@ -54,7 +59,11 @@ static std::optional<std::string> get_property(const char * property)
} }
#endif #endif
static std::optional<std::string> env_string(std::string_view name) template <typename T>
std::optional<T> env(std::string_view name);
template <>
std::optional<std::string> env(std::string_view name)
{ {
#ifdef __ANDROID__ #ifdef __ANDROID__
auto android_sysprop_name = std::format("debug.wivrn.{}", name); auto android_sysprop_name = std::format("debug.wivrn.{}", name);
@@ -71,9 +80,10 @@ static std::optional<std::string> env_string(std::string_view name)
#endif #endif
} }
static std::optional<uint32_t> env_u32(std::string_view name) template <>
std::optional<uint32_t> env(std::string_view name)
{ {
const auto value = env_string(name); const auto value = env<std::string>(name);
if (not value) if (not value)
return std::nullopt; return std::nullopt;
try try
@@ -90,9 +100,10 @@ static std::optional<uint32_t> env_u32(std::string_view name)
} }
} }
static std::optional<bool> env_bool(std::string_view name) template <>
std::optional<bool> env(std::string_view name)
{ {
const auto value = env_string(name); const auto value = env<std::string>(name);
if (not value) if (not value)
return std::nullopt; return std::nullopt;
if (strcmp(value->c_str(), "1") == 0 || strcasecmp(value->c_str(), "true") == 0 || strcasecmp(value->c_str(), "yes") == 0 || strcasecmp(value->c_str(), "on") == 0) if (strcmp(value->c_str(), "1") == 0 || strcasecmp(value->c_str(), "true") == 0 || strcasecmp(value->c_str(), "yes") == 0 || strcasecmp(value->c_str(), "on") == 0)
@@ -102,7 +113,32 @@ static std::optional<bool> env_bool(std::string_view name)
return std::nullopt; return std::nullopt;
} }
hmd_traits::hmd_traits() = default; template <>
std::optional<std::unordered_map<std::string, std::string>> env(std::string_view name)
{
const auto values = env<std::string>(name);
if (not values)
return std::nullopt;
std::unordered_map<std::string, std::string> map;
for (auto value: utils::split(*values, ","))
{
if (auto pos = value.find('='); pos != std::string::npos)
map.insert(std::make_pair(value.substr(0, pos), value.substr(pos + 1)));
}
return map;
}
template <>
std::optional<std::unordered_set<std::string>> env(std::string_view name)
{
const auto values = env<std::string>(name);
if (not values)
return std::nullopt;
return std::unordered_set<std::string>{std::from_range, utils::split(*values, ",")};
}
void hmd_traits::init() void hmd_traits::init()
{ {
@@ -203,8 +239,32 @@ void hmd_traits::init()
{ {
// Accepts OpenXR 1.1 but doesn't actually implement it // Accepts OpenXR 1.1 but doesn't actually implement it
max_openxr_api_version = XR_API_VERSION_1_0; max_openxr_api_version = XR_API_VERSION_1_0;
// Doesn't handle additive blend, so needs specific ray model // Doesn't handle additive blend, so needs specific ray model
controller_ray_model = "assets://ray-htc.glb"; // Fixed in XR elite firmware version 2.0
bool need_htc_ray = true;
const auto version = get_property("ro.product.version");
if (version)
{
auto digits = utils::split(*version, ".");
if (not digits.empty())
{
try
{
auto major = std::stoi(digits[0]);
if (major >= 2 and model == "VIVE XR Series")
need_htc_ray = false;
}
catch (...)
{}
}
}
if (need_htc_ray)
override_shader = {
{"ray.frag", "ray_htc.frag"},
{"ray_skinned.vert", "ray_skinned_htc.vert"},
{"ray.vert", "ray_htc.vert"},
};
controller_profile = "htc-vive-focus-3"; controller_profile = "htc-vive-focus-3";
@@ -231,69 +291,75 @@ void hmd_traits::init()
#endif #endif
spdlog::info("HMD traits initialized"); spdlog::info("HMD traits initialized");
auto log_string = [](std::string_view name, std::string & field) {
if (auto val = env_string(name))
{
spdlog::info("\t{} override: {} -> {}", name, field, *val);
field = *val;
}
else
{
spdlog::info("\t{}: {}", name, field);
}
};
auto log_u32 = [](std::string_view name, uint32_t & field) {
if (auto val = env_u32(name))
{
spdlog::info("\t{} override: {} -> {}", name, field, *val);
field = *val;
}
else
{
spdlog::info("\t{}: {}", name, field);
}
};
auto log_bool = [](std::string_view name, bool & field) {
if (auto val = env_bool(name))
{
spdlog::info("\t{} override: {} -> {}", name, field, *val);
field = *val;
}
else
{
spdlog::info("\t{}: {}", name, field);
}
};
log_string("controller_profile", controller_profile); boost::pfr::for_each_field_with_name(
log_string("controller_ray_model", controller_ray_model); *this,
if (auto val = env_string("max_openxr_api_version")) utils::overloaded{
{ [](std::string_view name, auto & field) {
XrVersion v; if (auto val = env<std::remove_cvref_t<decltype(field)>>(name))
if (val == "1.1") {
v = XR_API_VERSION_1_1; spdlog::info("\t{} override: {} -> {}", name, field, *val);
else if (val == "1.0") field = *val;
v = XR_API_VERSION_1_0; }
else else
{ {
spdlog::warn("XrVersion {} not recognized", *val); spdlog::info("\t{}: {}", name, field);
v = max_openxr_api_version; }
} },
spdlog::info("\t{} override: {} -> {}", "max_openxr_api_version", xr::to_string(max_openxr_api_version), xr::to_string(v)); [](std::string_view name, XrVersion & field) {
max_openxr_api_version = v; if (auto val = env<std::string>(name))
} {
else XrVersion v;
{ if (val == "1.1")
spdlog::info("\t{}: {}", "max_openxr_api_version", xr::to_string(max_openxr_api_version)); v = XR_API_VERSION_1_1;
} else if (val == "1.0")
log_u32("panel_width_override", panel_width_override); v = XR_API_VERSION_1_0;
log_bool("needs_srgb_conversion", needs_srgb_conversion); else
log_bool("view_locate", view_locate); {
log_bool("vk_debug_ext_allowed", vk_debug_ext_allowed); spdlog::warn("XrVersion {} not recognized", *val);
log_bool("bind_simple_controller", bind_simple_controller); v = field;
log_bool("hand_interaction_grip_surface", hand_interaction_grip_surface); }
log_bool("pico_face_tracker", pico_face_tracker); spdlog::info("\t{} override: {} -> {}", name, xr::to_string(field), xr::to_string(v));
log_bool("discard_frame", discard_frame); field = v;
}
else
{
spdlog::info("\t{}: {}", name, xr::to_string(field));
}
},
[](std::string_view name, std::unordered_map<std::string, std::string> & field) {
if (auto val = env<std::unordered_map<std::string, std::string>>(name))
{
for (const auto & [original, overridden]: *val)
field.insert_or_assign(original, overridden);
}
std::erase_if(field, [](const std::pair<std::string, std::string> & kv) { return kv.second == ""; });
for (const auto & [original, overridden]: field)
{
spdlog::info("\t{}: {} -> {}", name, original, overridden);
}
},
[](std::string_view name, std::unordered_set<std::string> & field) {
if (auto val = env<std::unordered_set<std::string>>(name))
{
for (const auto & i: *val)
{
if (i.starts_with("-"))
field.erase(i.substr(1));
else
field.insert(i);
}
}
for (const auto & i: field)
{
spdlog::info("\t{}: {}", name, i);
}
},
[](std::string_view, hmd_permissions) {},
});
} }
static XrViewConfigurationView scale_view(XrViewConfigurationView view, uint32_t width) static XrViewConfigurationView scale_view(XrViewConfigurationView view, uint32_t width)
@@ -488,11 +554,11 @@ std::pair<glm::vec3, glm::quat> hmd_traits::controller_offset(xr::spaces space)
{ {
case xr::spaces::grip_left: case xr::spaces::grip_left:
case xr::spaces::grip_right: case xr::spaces::grip_right:
return {{0, 0, -0.03}, glm::angleAxis(glm::radians(-35.f), glm::vec3{1, 0, 0})}; return {{0, 0, 0}, {1, 0, 0, 0}};
case xr::spaces::aim_left: case xr::spaces::aim_left:
case xr::spaces::aim_right: case xr::spaces::aim_right:
return {{0, 0, 0}, {1, 0, 0, 0}}; return {{0, -0.045, 0.035}, {1, 0, 0, 0}};
default: default:
break; break;
+3 -3
View File
@@ -25,6 +25,7 @@
#include <glm/gtc/quaternion.hpp> #include <glm/gtc/quaternion.hpp>
#include <magic_enum_containers.hpp> #include <magic_enum_containers.hpp>
#include <string> #include <string>
#include <unordered_set>
#include <utility> #include <utility>
#include <openxr/openxr.h> #include <openxr/openxr.h>
@@ -54,14 +55,13 @@ public:
bool hand_interaction_grip_surface = true; bool hand_interaction_grip_surface = true;
bool pico_face_tracker = false; bool pico_face_tracker = false;
bool discard_frame = true; // can do xrBeginFrame twice to discard the first one bool discard_frame = true; // can do xrBeginFrame twice to discard the first one
std::unordered_map<std::string, std::string> override_shader;
std::unordered_set<std::string> blacklisted_extensions;
#ifndef NDEBUG #ifndef NDEBUG
private:
bool initialized_ = false; bool initialized_ = false;
#endif #endif
public: public:
hmd_traits();
void init(); void init();
const char * permission_name(feature f) const const char * permission_name(feature f) const
+7
View File
@@ -19,6 +19,7 @@
#include "scene_loader.h" #include "scene_loader.h"
#include "gpu_buffer.h" #include "gpu_buffer.h"
#include "hmd_traits.h"
#include "image_loader.h" #include "image_loader.h"
#include "render/scene_components.h" #include "render/scene_components.h"
#include "render/vertex_layout.h" #include "render/vertex_layout.h"
@@ -835,6 +836,9 @@ public:
if (auto it = extras.find({fastgltf::Category::Materials, material_id, "fragment_shader"}); it != extras.end()) if (auto it = extras.find({fastgltf::Category::Materials, material_id, "fragment_shader"}); it != extras.end())
material.fragment_shader = it->second; material.fragment_shader = it->second;
if (auto it = application::get_hmd_traits().override_shader.find(material.fragment_shader); it != application::get_hmd_traits().override_shader.end())
material.fragment_shader = it->second;
renderer::material::gpu_data & material_data = material.staging; renderer::material::gpu_data & material_data = material.staging;
material_data.base_color_factor = convert(gltf_material.pbrData.baseColorFactor); material_data.base_color_factor = convert(gltf_material.pbrData.baseColorFactor);
@@ -917,6 +921,9 @@ public:
else else
primitive_ref.vertex_shader = "lit_skinned.vert"; primitive_ref.vertex_shader = "lit_skinned.vert";
if (auto it = application::get_hmd_traits().override_shader.find(primitive_ref.vertex_shader); it != application::get_hmd_traits().override_shader.end())
primitive_ref.vertex_shader = it->second;
// For attributes types, see https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes-overview (§ 3.7.2.1) // For attributes types, see https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#meshes-overview (§ 3.7.2.1)
auto shader = shader_loader{device}(primitive_ref.vertex_shader); auto shader = shader_loader{device}(primitive_ref.vertex_shader);
for (const auto & input: shader->inputs) for (const auto & input: shader->inputs)
+3 -1
View File
@@ -133,7 +133,9 @@ void main()
discard; discard;
} }
out_color = vec4(mesh.emissive_factor * texture(emissive_texture, texcoord).rgb, 0); // https://registry.khronos.org/OpenXR/specs/1.1/html/xrspec.html#fundamentals-colors
// alpha can't be 0 or it will zero RGB values too
out_color = vec4(mesh.emissive_factor * texture(emissive_texture, texcoord).rgb, 1.0 / 255.0);
#endif // HTC_WORKAROUND #endif // HTC_WORKAROUND
} }
+4 -1
View File
@@ -199,7 +199,10 @@ xr::instance::instance(std::string_view application_name, std::vector<const char
std::ranges::sort(all_extensions, [](const char * a, const char * b) { return strcmp(a, b) < 0; }, &XrExtensionProperties::extensionName); std::ranges::sort(all_extensions, [](const char * a, const char * b) { return strcmp(a, b) < 0; }, &XrExtensionProperties::extensionName);
for (XrExtensionProperties & i: all_extensions) for (XrExtensionProperties & i: all_extensions)
{ {
spdlog::info(" {} (version {})", i.extensionName, i.extensionVersion); if (application::get_hmd_traits().blacklisted_extensions.contains(i.extensionName))
spdlog::info(" {} (version {}) (blacklisted)", i.extensionName, i.extensionVersion);
else
spdlog::info(" {} (version {})", i.extensionName, i.extensionVersion);
#ifndef NDEBUG #ifndef NDEBUG
if (!strcmp(i.extensionName, "XR_EXT_debug_utils")) if (!strcmp(i.extensionName, "XR_EXT_debug_utils"))
{ {
+9 -15
View File
@@ -255,14 +255,12 @@ std::pair<wivrn::deserialization_packet, sockaddr_in6> wivrn::UDP::receive_from_
sockaddr_in6 addr; sockaddr_in6 addr;
socklen_t addrlen = sizeof(addr); socklen_t addrlen = sizeof(addr);
size_t size = recvfrom(fd, nullptr, 0, MSG_PEEK | MSG_TRUNC, (sockaddr *)&addr, &addrlen); ssize_t peeked = recvfrom(fd, nullptr, 0, MSG_PEEK | MSG_TRUNC, (sockaddr *)&addr, &addrlen);
if (peeked < 0)
throw std::system_error{errno, std::generic_category()};
#if defined(__cpp_lib_smart_ptr_for_overwrite) && __cpp_lib_smart_ptr_for_overwrite >= 202002L auto buffer = std::make_shared_for_overwrite<uint8_t[]>(peeked);
auto buffer = std::make_shared_for_overwrite<uint8_t[]>(size); ssize_t received = recvfrom(fd, buffer.get(), peeked, 0, (sockaddr *)&addr, &addrlen);
#else
std::shared_ptr<uint8_t[]> buffer(new uint8_t[size]);
#endif
ssize_t received = recvfrom(fd, buffer.get(), size, 0, (sockaddr *)&addr, &addrlen);
if (received < 0) if (received < 0)
throw std::system_error{errno, std::generic_category()}; throw std::system_error{errno, std::generic_category()};
@@ -310,11 +308,7 @@ wivrn::deserialization_packet wivrn::UDP::receive_raw()
static const size_t num_messages = 20; static const size_t num_messages = 20;
if ((not buffer) or buffer.use_count() > 1) if ((not buffer) or buffer.use_count() > 1)
{ {
#if defined(__cpp_lib_smart_ptr_for_overwrite) && __cpp_lib_smart_ptr_for_overwrite >= 202002L
buffer = std::make_shared_for_overwrite<uint8_t[]>(message_size * num_messages); buffer = std::make_shared_for_overwrite<uint8_t[]>(message_size * num_messages);
#else
buffer.reset(new uint8_t[message_size * num_messages]);
#endif
} }
std::array<iovec, num_messages> iovecs; std::array<iovec, num_messages> iovecs;
std::array<mmsghdr, num_messages> mmsgs; std::array<mmsghdr, num_messages> mmsgs;
@@ -462,6 +456,8 @@ size_t wivrn::UDP::send_many_raw(std::span<serialization_packet> packets)
wivrn::deserialization_packet wivrn::TCP::receive_raw() wivrn::deserialization_packet wivrn::TCP::receive_raw()
{ {
static constexpr size_t max_payload = 16 * 1024 * 1024;
ssize_t expected_size; ssize_t expected_size;
if (data.size_bytes() < sizeof(uint32_t)) if (data.size_bytes() < sizeof(uint32_t))
@@ -471,6 +467,8 @@ wivrn::deserialization_packet wivrn::TCP::receive_raw()
else else
{ {
uint32_t payload_size = *reinterpret_cast<uint32_t *>(data.data()); uint32_t payload_size = *reinterpret_cast<uint32_t *>(data.data());
if (payload_size > max_payload)
throw std::runtime_error("Invalid packet: size " + std::to_string(payload_size));
expected_size = payload_size + sizeof(uint32_t) - data.size_bytes(); expected_size = payload_size + sizeof(uint32_t) - data.size_bytes();
} }
@@ -479,11 +477,7 @@ wivrn::deserialization_packet wivrn::TCP::receive_raw()
size_t new_size = std::max<size_t>(data.size_bytes() + expected_size, size_t new_size = std::max<size_t>(data.size_bytes() + expected_size,
4096); 4096);
auto old = std::move(buffer); auto old = std::move(buffer);
#if defined(__cpp_lib_smart_ptr_for_overwrite) && __cpp_lib_smart_ptr_for_overwrite >= 202002L
buffer = std::make_shared_for_overwrite<uint8_t[]>(new_size); buffer = std::make_shared_for_overwrite<uint8_t[]>(new_size);
#else
buffer.reset(new uint8_t[new_size]);
#endif
memcpy(buffer.get(), data.data(), data.size_bytes()); memcpy(buffer.get(), data.data(), data.size_bytes());
data = std::span(buffer.get(), data.size()); data = std::span(buffer.get(), data.size());
capacity_left = new_size - data.size_bytes(); capacity_left = new_size - data.size_bytes();
+121 -102
View File
@@ -2,7 +2,7 @@ msgid ""
msgstr "" msgstr ""
"Project-Id-Version: WiVRn 0.16\n" "Project-Id-Version: WiVRn 0.16\n"
"Report-Msgid-Bugs-To: \n" "Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-07-09 12:31+0900\n" "POT-Creation-Date: 2026-07-14 20:45+0900\n"
"PO-Revision-Date: 2024-06-20 10:33+0900\n" "PO-Revision-Date: 2024-06-20 10:33+0900\n"
"Last-Translator: Mitsuami Megane <hello@mitsua.me>\n" "Last-Translator: Mitsuami Megane <hello@mitsua.me>\n"
"Language: Japanese\n" "Language: Japanese\n"
@@ -36,22 +36,22 @@ msgstr "パソコンでVRアプリを起動するか、ここからアプリを
msgid "Start an application on {} or select one to start streaming." msgid "Start an application on {} or select one to start streaming."
msgstr "{}でVRアプリを起動するか、ここからアプリを選択しましょう。" msgstr "{}でVRアプリを起動するか、ここからアプリを選択しましょう。"
#: client/scenes/gui_common.cpp:39 client/scenes/gui_common.cpp:65 #: client/scenes/gui_common.cpp:42 client/scenes/gui_common.cpp:68
msgctxt "automatic refresh rate" msgctxt "automatic refresh rate"
msgid "Automatic" msgid "Automatic"
msgstr "自動" msgstr "自動"
#: client/scenes/gui_common.cpp:43 #: client/scenes/gui_common.cpp:46
#, c++-format #, c++-format
msgctxt "refresh rate selection, with reprojection" msgctxt "refresh rate selection, with reprojection"
msgid "{} ({} with space warp)" msgid "{} ({} with space warp)"
msgstr "{} ({}、スペースワープ有効)" msgstr "{} ({}、スペースワープ有効)"
#: client/scenes/gui_common.cpp:61 #: client/scenes/gui_common.cpp:64
msgid "Refresh rate" msgid "Refresh rate"
msgstr "リフレッシュレート" msgstr "リフレッシュレート"
#: client/scenes/gui_common.cpp:75 #: client/scenes/gui_common.cpp:78
msgid "" msgid ""
"Select refresh rate based on measured application performance.\n" "Select refresh rate based on measured application performance.\n"
"May cause flicker when a change happens." "May cause flicker when a change happens."
@@ -59,34 +59,78 @@ msgstr ""
"アプリケーションのパフォーマンスを基づいて自動的に設定します。\n" "アプリケーションのパフォーマンスを基づいて自動的に設定します。\n"
"変更時にチラツキが発生する可能性があります。" "変更時にチラツキが発生する可能性があります。"
#: client/scenes/gui_common.cpp:103 #: client/scenes/gui_common.cpp:106
msgid "Minimum refresh rate" msgid "Minimum refresh rate"
msgstr "最低リフレッシュレート" msgstr "最低リフレッシュレート"
#: client/scenes/gui_common.cpp:126 #: client/scenes/gui_common.cpp:133
msgctxt "virtual body tracker selection"
msgid "Chest"
msgstr "胸"
#: client/scenes/gui_common.cpp:134
msgctxt "virtual body tracker selection"
msgid "Left elbow"
msgstr "左肘"
#: client/scenes/gui_common.cpp:135
msgctxt "virtual body tracker selection"
msgid "Right elbow"
msgstr "右肘"
#: client/scenes/gui_common.cpp:136
msgctxt "virtual body tracker selection"
msgid "Hip"
msgstr "腰"
#: client/scenes/gui_common.cpp:137
msgctxt "virtual body tracker selection"
msgid "Left knee"
msgstr "左膝"
#: client/scenes/gui_common.cpp:138
msgctxt "virtual body tracker selection"
msgid "Right knee"
msgstr "右膝"
#: client/scenes/gui_common.cpp:139
msgctxt "virtual body tracker selection"
msgid "Left foot"
msgstr "左足"
#: client/scenes/gui_common.cpp:140
msgctxt "virtual body tracker selection"
msgid "Right foot"
msgstr "右足"
#: client/scenes/gui_common.cpp:146
msgid "Virtual body trackers"
msgstr "推定ボディトラッカー"
#: client/scenes/gui_common.cpp:208
msgctxt "openxr_post_processing" msgctxt "openxr_post_processing"
msgid "Normal" msgid "Normal"
msgstr "ノーマル" msgstr "ノーマル"
#: client/scenes/gui_common.cpp:129 #: client/scenes/gui_common.cpp:211
msgctxt "openxr_post_processing" msgctxt "openxr_post_processing"
msgid "Quality" msgid "Quality"
msgstr "クオリティ" msgstr "クオリティ"
#: client/scenes/gui_common.cpp:131 #: client/scenes/gui_common.cpp:213
msgctxt "openxr_post_processing" msgctxt "openxr_post_processing"
msgid "Disabled" msgid "Disabled"
msgstr "無効" msgstr "無効"
#: client/scenes/gui_common.cpp:143 #: client/scenes/gui_common.cpp:225
msgid "OpenXR post-processing" msgid "OpenXR post-processing"
msgstr "OpenXRポストエフェクト" msgstr "OpenXRポストエフェクト"
#: client/scenes/gui_common.cpp:148 #: client/scenes/gui_common.cpp:230
msgid "Supersampling" msgid "Supersampling"
msgstr "スーパーサンプリング" msgstr "スーパーサンプリング"
#: client/scenes/gui_common.cpp:169 #: client/scenes/gui_common.cpp:251
msgid "" msgid ""
"Reduce flicker for high contrast edges.\n" "Reduce flicker for high contrast edges.\n"
"Useful when the input resolution is high compared to the headset display" "Useful when the input resolution is high compared to the headset display"
@@ -94,11 +138,11 @@ msgstr ""
"コントラストが高い部分のギザギザを低減する。\n" "コントラストが高い部分のギザギザを低減する。\n"
"ストリームの解像度は、HMDの解像度より高い場合は有用です。" "ストリームの解像度は、HMDの解像度より高い場合は有用です。"
#: client/scenes/gui_common.cpp:174 #: client/scenes/gui_common.cpp:256
msgid "Sharpening" msgid "Sharpening"
msgstr "シャープ" msgstr "シャープ"
#: client/scenes/gui_common.cpp:195 #: client/scenes/gui_common.cpp:277
msgid "" msgid ""
"Improve clarity of high contrast edges and counteract blur.\n" "Improve clarity of high contrast edges and counteract blur.\n"
"Useful when the input resolution is low compared to the headset display" "Useful when the input resolution is low compared to the headset display"
@@ -138,14 +182,14 @@ msgid "Default environment"
msgstr "デフォルトのホーム環境" msgstr "デフォルトのホーム環境"
#: client/scenes/lobby_gui.cpp:100 client/scenes/lobby_gui.cpp:240 #: client/scenes/lobby_gui.cpp:100 client/scenes/lobby_gui.cpp:240
#: client/scenes/stream_gui.cpp:933 #: client/scenes/stream_gui.cpp:944
msgid "Disconnect" msgid "Disconnect"
msgstr "切断する" msgstr "切断する"
#: client/scenes/lobby_gui.cpp:120 client/scenes/lobby_gui.cpp:250 #: client/scenes/lobby_gui.cpp:120 client/scenes/lobby_gui.cpp:250
#: client/scenes/lobby_gui_customize.cpp:752 #: client/scenes/lobby_gui_customize.cpp:752
#: client/scenes/lobby_gui_customize.cpp:843 #: client/scenes/lobby_gui_customize.cpp:843
#: client/scenes/lobby_gui_customize.cpp:899 client/scenes/stream_gui.cpp:929 #: client/scenes/lobby_gui_customize.cpp:899 client/scenes/stream_gui.cpp:940
msgid "Close" msgid "Close"
msgstr "閉じる" msgstr "閉じる"
@@ -192,7 +236,7 @@ msgid "TCP only"
msgstr "TCPのみを使用" msgstr "TCPのみを使用"
#: client/scenes/lobby_gui.cpp:337 client/scenes/lobby_gui_customize.cpp:654 #: client/scenes/lobby_gui.cpp:337 client/scenes/lobby_gui_customize.cpp:654
#: client/scenes/stream_gui.cpp:884 #: client/scenes/stream_gui.cpp:895
msgid "Cancel" msgid "Cancel"
msgstr "キャンセル" msgstr "キャンセル"
@@ -366,7 +410,8 @@ msgid ""
"it through OpenXR." "it through OpenXR."
msgstr "" msgstr ""
"HMDに接続された入力デバイスをPC上で仮想デバイスとして再現します。\n" "HMDに接続された入力デバイスをPC上で仮想デバイスとして再現します。\n"
"サーバー側で入力デバイスの転送を許可してください(Flatpak版サーバーでは利用不可)。\n" "サーバー側で入力デバイスの転送を許可してください(Flatpak版サーバーでは利用不"
"可)。\n"
"OpenXR対応アプリなら、仮想デバイスなしでゲームコントローラーが使用可能です。" "OpenXR対応アプリなら、仮想デバイスなしでゲームコントローラーが使用可能です。"
#: client/scenes/lobby_gui.cpp:795 #: client/scenes/lobby_gui.cpp:795
@@ -418,37 +463,11 @@ msgstr ""
"そうでなければ、トラッキングデータはHMDとコントローラーの情報から推測されるこ" "そうでなければ、トラッキングデータはHMDとコントローラーの情報から推測されるこ"
"とになる。" "とになる。"
#: client/scenes/lobby_gui.cpp:873 #: client/scenes/lobby_gui.cpp:881
msgid "Enable lower body tracking"
msgstr "下半身トラッキングを有効する"
#: client/scenes/lobby_gui.cpp:879
msgid ""
"Estimate lower body joint positions using Generative Legs\n"
"Requires 'Hand and body tracking' to be enabled in the Quest movement "
"tracking settings"
msgstr ""
"下半身に計算された疑似トラッキングを使用する。\n"
"Quest設定・動きのトラッキング・ジェスチャーコントロールとボディトラッキングを"
"有効する必要がある。"
#: client/scenes/lobby_gui.cpp:882
msgid "Enable hip tracking"
msgstr "腰のトラッキングを有効する"
#: client/scenes/lobby_gui.cpp:888
msgid ""
"Only takes affect with lower body tracking enabled\n"
"May be desired when using another source of hip tracking"
msgstr ""
"下半身トラッキングが有効な場合に使用可能。\n"
"腰トラッカーを持ってる方は無効にしましょう。"
#: client/scenes/lobby_gui.cpp:897
msgid "Enable in-stream window" msgid "Enable in-stream window"
msgstr "ストリーミング中の設定パネル" msgstr "ストリーミング中の設定パネル"
#: client/scenes/lobby_gui.cpp:900 #: client/scenes/lobby_gui.cpp:884
msgid "" msgid ""
"Enables the configuration window to be shown while the game is streaming.\n" "Enables the configuration window to be shown while the game is streaming.\n"
"If enabled, the window is activated by pressing both thumbsticks." "If enabled, the window is activated by pressing both thumbsticks."
@@ -456,137 +475,137 @@ msgstr ""
"ストリーミング中にも設定パネルを表示できるようにします。\n" "ストリーミング中にも設定パネルを表示できるようにします。\n"
"両方のサムスティックを同時に押して切り替えることができます。" "両方のサムスティックを同時に押して切り替えることができます。"
#: client/scenes/lobby_gui.cpp:904 #: client/scenes/lobby_gui.cpp:888
msgid "Extended configuration values" msgid "Extended configuration values"
msgstr "設定に対する制限の緩和" msgstr "設定に対する制限の緩和"
#: client/scenes/lobby_gui.cpp:907 #: client/scenes/lobby_gui.cpp:891
msgid "Allows unsafe configuration values, use at your own risk." msgid "Allows unsafe configuration values, use at your own risk."
msgstr "不安定な状態が発生しないよう、十分にご注意ください。" msgstr "不安定な状態が発生しないよう、十分にご注意ください。"
#: client/scenes/lobby_gui.cpp:1095 client/scenes/lobby_gui.cpp:1103 #: client/scenes/lobby_gui.cpp:1079 client/scenes/lobby_gui.cpp:1087
#: client/scenes/stream_gui.cpp:175 client/scenes/stream_gui.cpp:373 #: client/scenes/stream_gui.cpp:175 client/scenes/stream_gui.cpp:373
msgid "CPU time" msgid "CPU time"
msgstr "CPU使用時間" msgstr "CPU使用時間"
#: client/scenes/lobby_gui.cpp:1099 #: client/scenes/lobby_gui.cpp:1083
msgid "CPU time [ms]" msgid "CPU time [ms]"
msgstr "CPU使用時間、ミリ秒" msgstr "CPU使用時間、ミリ秒"
#: client/scenes/lobby_gui.cpp:1109 client/scenes/lobby_gui.cpp:1117 #: client/scenes/lobby_gui.cpp:1093 client/scenes/lobby_gui.cpp:1101
#: client/scenes/stream_gui.cpp:177 client/scenes/stream_gui.cpp:374 #: client/scenes/stream_gui.cpp:177 client/scenes/stream_gui.cpp:374
msgid "GPU time" msgid "GPU time"
msgstr "GPU使用時間" msgstr "GPU使用時間"
#: client/scenes/lobby_gui.cpp:1113 #: client/scenes/lobby_gui.cpp:1097
msgid "GPU time [ms]" msgid "GPU time [ms]"
msgstr "GPU使用時間、ミリ秒" msgstr "GPU使用時間、ミリ秒"
#: client/scenes/lobby_gui.cpp:1177 #: client/scenes/lobby_gui.cpp:1161
msgid "Enable the microphone?" msgid "Enable the microphone?"
msgstr "マイクを有効にしますか?" msgstr "マイクを有効にしますか?"
#: client/scenes/lobby_gui.cpp:1182 #: client/scenes/lobby_gui.cpp:1166
msgid "Enable eye tracking?" msgid "Enable eye tracking?"
msgstr "アイトラッキングを有効にしますか?" msgstr "アイトラッキングを有効にしますか?"
#: client/scenes/lobby_gui.cpp:1187 #: client/scenes/lobby_gui.cpp:1171
msgid "Enable face tracking?" msgid "Enable face tracking?"
msgstr "フェースラッキングを有効にしますか?" msgstr "フェースラッキングを有効にしますか?"
#: client/scenes/lobby_gui.cpp:1192 #: client/scenes/lobby_gui.cpp:1176
msgid "Enable body tracking?" msgid "Enable body tracking?"
msgstr "ボディトラッキングを有効にしますか?" msgstr "ボディトラッキングを有効にしますか?"
#: client/scenes/lobby_gui.cpp:1200 #: client/scenes/lobby_gui.cpp:1184
msgid "Welcome to WiVRn" msgid "Welcome to WiVRn"
msgstr "WiVRnへようこそ!" msgstr "WiVRnへようこそ!"
#: client/scenes/lobby_gui.cpp:1228 #: client/scenes/lobby_gui.cpp:1212
msgid "Yes" msgid "Yes"
msgstr "はい" msgstr "はい"
#: client/scenes/lobby_gui.cpp:1235 #: client/scenes/lobby_gui.cpp:1219
msgid "No" msgid "No"
msgstr "いいえ" msgstr "いいえ"
#: client/scenes/lobby_gui.cpp:1254 client/scenes/lobby_gui.cpp:1900 #: client/scenes/lobby_gui.cpp:1238 client/scenes/lobby_gui.cpp:1884
msgid "Licenses" msgid "Licenses"
msgstr "ライセンス" msgstr "ライセンス"
#: client/scenes/lobby_gui.cpp:1530 #: client/scenes/lobby_gui.cpp:1514
msgid "Microphone is enabled" msgid "Microphone is enabled"
msgstr "マイクは有効です" msgstr "マイクは有効です"
#: client/scenes/lobby_gui.cpp:1531 #: client/scenes/lobby_gui.cpp:1515
msgid "Microphone is disabled" msgid "Microphone is disabled"
msgstr "マイクは無効です" msgstr "マイクは無効です"
#: client/scenes/lobby_gui.cpp:1540 #: client/scenes/lobby_gui.cpp:1524
msgid "Hand tracking is enabled" msgid "Hand tracking is enabled"
msgstr "ハンドトラッキングは有効です" msgstr "ハンドトラッキングは有効です"
#: client/scenes/lobby_gui.cpp:1541 #: client/scenes/lobby_gui.cpp:1525
msgid "Hand tracking is disabled" msgid "Hand tracking is disabled"
msgstr "ハンドラッキングは無効です" msgstr "ハンドラッキングは無効です"
#: client/scenes/lobby_gui.cpp:1550 #: client/scenes/lobby_gui.cpp:1534
msgid "Eye tracking is enabled" msgid "Eye tracking is enabled"
msgstr "アイトラッキングは有効です" msgstr "アイトラッキングは有効です"
#: client/scenes/lobby_gui.cpp:1551 #: client/scenes/lobby_gui.cpp:1535
msgid "Eye tracking is disabled" msgid "Eye tracking is disabled"
msgstr "アイトラッキングは無効です" msgstr "アイトラッキングは無効です"
#: client/scenes/lobby_gui.cpp:1561 #: client/scenes/lobby_gui.cpp:1545
msgid "Face tracking is enabled" msgid "Face tracking is enabled"
msgstr "フェーストラッキングは有効です" msgstr "フェーストラッキングは有効です"
#: client/scenes/lobby_gui.cpp:1562 #: client/scenes/lobby_gui.cpp:1546
msgid "Face tracking is disabled" msgid "Face tracking is disabled"
msgstr "フェーストラッキングは無効です" msgstr "フェーストラッキングは無効です"
#: client/scenes/lobby_gui.cpp:1576 #: client/scenes/lobby_gui.cpp:1560
msgid "Body tracking is enabled" msgid "Body tracking is enabled"
msgstr "ボディトラッキングは有効です" msgstr "ボディトラッキングは有効です"
#: client/scenes/lobby_gui.cpp:1577 #: client/scenes/lobby_gui.cpp:1561
msgid "Body tracking is disabled" msgid "Body tracking is disabled"
msgstr "ボディトラッキングは無効です" msgstr "ボディトラッキングは無効です"
#: client/scenes/lobby_gui.cpp:1593 #: client/scenes/lobby_gui.cpp:1577
msgid "Add server" msgid "Add server"
msgstr "サーバーを追加する" msgstr "サーバーを追加する"
#: client/scenes/lobby_gui.cpp:1879 #: client/scenes/lobby_gui.cpp:1863
msgid "Server list" msgid "Server list"
msgstr "サーバー" msgstr "サーバー"
#: client/scenes/lobby_gui.cpp:1882 client/scenes/stream_gui.cpp:914 #: client/scenes/lobby_gui.cpp:1866 client/scenes/stream_gui.cpp:925
msgid "Settings" msgid "Settings"
msgstr "設定" msgstr "設定"
#: client/scenes/lobby_gui.cpp:1885 #: client/scenes/lobby_gui.cpp:1869
msgid "Post-processing" msgid "Post-processing"
msgstr "ポストエフェクト" msgstr "ポストエフェクト"
#: client/scenes/lobby_gui.cpp:1888 #: client/scenes/lobby_gui.cpp:1872
msgid "Customize" msgid "Customize"
msgstr "カスタマイズ" msgstr "カスタマイズ"
#: client/scenes/lobby_gui.cpp:1892 #: client/scenes/lobby_gui.cpp:1876
msgid "Debug" msgid "Debug"
msgstr "デバッグ" msgstr "デバッグ"
#: client/scenes/lobby_gui.cpp:1897 #: client/scenes/lobby_gui.cpp:1881
msgid "About" msgid "About"
msgstr "WiVRnについて" msgstr "WiVRnについて"
#: client/scenes/lobby_gui.cpp:1903 #: client/scenes/lobby_gui.cpp:1887
msgid "Exit" msgid "Exit"
msgstr "完了" msgstr "完了"
#: client/scenes/lobby_gui.cpp:1920 #: client/scenes/lobby_gui.cpp:1904
msgid "" msgid ""
"Press the grip button or put your palm up\n" "Press the grip button or put your palm up\n"
"to move the main window" "to move the main window"
@@ -594,7 +613,7 @@ msgstr ""
"メイン・パネルを動かすには、グリップを握るか、\n" "メイン・パネルを動かすには、グリップを握るか、\n"
"手のひらを上向きにしましょう。" "手のひらを上向きにしましょう。"
#: client/scenes/lobby_gui.cpp:1922 #: client/scenes/lobby_gui.cpp:1906
msgid "Press the grip button to move the main window" msgid "Press the grip button to move the main window"
msgstr "グリップを握ってパネルを動かしましょう。" msgstr "グリップを握ってパネルを動かしましょう。"
@@ -735,7 +754,7 @@ msgstr "「Motion-to-photon」推定遅延 {}ミリ秒"
msgid "Press the grip button to move the window" msgid "Press the grip button to move the window"
msgstr "グリップを握ってパネルを動かしましょう。" msgstr "グリップを握ってパネルを動かしましょう。"
#: client/scenes/stream_gui.cpp:353 client/scenes/stream_gui.cpp:628 #: client/scenes/stream_gui.cpp:353 client/scenes/stream_gui.cpp:635
msgid "Press both thumbsticks to display the WiVRn window" msgid "Press both thumbsticks to display the WiVRn window"
msgstr "両方のサムスティックを同時に押すことで設定表示" msgstr "両方のサムスティックを同時に押すことで設定表示"
@@ -743,90 +762,90 @@ msgstr "両方のサムスティックを同時に押すことで設定表示"
msgid "Motion to photon latency" msgid "Motion to photon latency"
msgstr "「Motion-to-photon」遅延" msgstr "「Motion-to-photon」遅延"
#: client/scenes/stream_gui.cpp:405 #: client/scenes/stream_gui.cpp:406
msgid "Bitrate:" msgid "Bitrate:"
msgstr "ビットレート:" msgstr "ビットレート:"
#: client/scenes/stream_gui.cpp:415 #: client/scenes/stream_gui.cpp:416
msgid "Click to adjust bitrate" msgid "Click to adjust bitrate"
msgstr "クリックしてビットレートを調整" msgstr "クリックしてビットレートを調整"
#: client/scenes/stream_gui.cpp:422 #: client/scenes/stream_gui.cpp:429
msgid "Foveation center override" msgid "Foveation center override"
msgstr "光学中心の調整" msgstr "光学中心の調整"
#: client/scenes/stream_gui.cpp:425 #: client/scenes/stream_gui.cpp:432
msgid "Enable" msgid "Enable"
msgstr "有効" msgstr "有効"
#: client/scenes/stream_gui.cpp:433 client/scenes/stream_gui.cpp:504 #: client/scenes/stream_gui.cpp:440 client/scenes/stream_gui.cpp:511
#, c++-format #, c++-format
msgid "Height {:.1f} deg" msgid "Height {:.1f} deg"
msgstr "仰角 {:.1f}°" msgstr "仰角 {:.1f}°"
#: client/scenes/stream_gui.cpp:434 client/scenes/stream_gui.cpp:505 #: client/scenes/stream_gui.cpp:441 client/scenes/stream_gui.cpp:512
#, c++-format #, c++-format
msgid "Distance {:.2f} m" msgid "Distance {:.2f} m"
msgstr "距離 {:.2f}m" msgstr "距離 {:.2f}m"
#: client/scenes/stream_gui.cpp:435 #: client/scenes/stream_gui.cpp:442
msgid "Default" msgid "Default"
msgstr "デフォルト" msgstr "デフォルト"
#: client/scenes/stream_gui.cpp:446 #: client/scenes/stream_gui.cpp:453
msgid "Change" msgid "Change"
msgstr "編集" msgstr "編集"
#: client/scenes/stream_gui.cpp:478 #: client/scenes/stream_gui.cpp:485
msgid "Use the right thumbstick to adjust the bitrate" msgid "Use the right thumbstick to adjust the bitrate"
msgstr "右スティックでビットレートを調整しましょう" msgstr "右スティックでビットレートを調整しましょう"
#: client/scenes/stream_gui.cpp:479 #: client/scenes/stream_gui.cpp:486
msgid "Press A to go back" msgid "Press A to go back"
msgstr "「A」を押して戻る" msgstr "「A」を押して戻る"
#: client/scenes/stream_gui.cpp:480 #: client/scenes/stream_gui.cpp:487
#, c++-format #, c++-format
msgid "Bitrate: {}Mbit/s" msgid "Bitrate: {}Mbit/s"
msgstr "ビットレート:{}Mbps" msgstr "ビットレート:{}Mbps"
#: client/scenes/stream_gui.cpp:502 #: client/scenes/stream_gui.cpp:509
msgid "Use the thumbsticks to move the foveation center" msgid "Use the thumbsticks to move the foveation center"
msgstr "ジョイスティックを使って中心点を調整しましょう。" msgstr "ジョイスティックを使って中心点を調整しましょう。"
#: client/scenes/stream_gui.cpp:503 #: client/scenes/stream_gui.cpp:510
msgid "Press A to save or B to cancel" msgid "Press A to save or B to cancel"
msgstr "AかBを押してキャンセル。" msgstr "AかBを押してキャンセル。"
#: client/scenes/stream_gui.cpp:561 #: client/scenes/stream_gui.cpp:568
msgid "Running XR applications:" msgid "Running XR applications:"
msgstr "XRアプリの実行" msgstr "XRアプリの実行"
#: client/scenes/stream_gui.cpp:578 #: client/scenes/stream_gui.cpp:585
msgid "Overlays" msgid "Overlays"
msgstr "オーバーレイ" msgstr "オーバーレイ"
#: client/scenes/stream_gui.cpp:617 #: client/scenes/stream_gui.cpp:624
msgid "Request to quit, may be ignored by the application" msgid "Request to quit, may be ignored by the application"
msgstr "終了シグナルを送信する" msgstr "終了シグナルを送信する"
#: client/scenes/stream_gui.cpp:900 #: client/scenes/stream_gui.cpp:911
msgid "Applications" msgid "Applications"
msgstr "アプリ" msgstr "アプリ"
#: client/scenes/stream_gui.cpp:903 #: client/scenes/stream_gui.cpp:914
msgid "Start" msgid "Start"
msgstr "実行する" msgstr "実行する"
#: client/scenes/stream_gui.cpp:917 #: client/scenes/stream_gui.cpp:928
msgid "Stats" msgid "Stats"
msgstr "統計情報" msgstr "統計情報"
#: client/scenes/stream_gui.cpp:923 #: client/scenes/stream_gui.cpp:934
msgid "Statistics overlay" msgid "Statistics overlay"
msgstr "統計オーバーレイ" msgstr "統計オーバーレイ"
#: client/scenes/stream_gui.cpp:926 #: client/scenes/stream_gui.cpp:937
msgid "Compact view" msgid "Compact view"
msgstr "コンパクト・モード" msgstr "コンパクト・モード"
+1 -1
View File
@@ -1,6 +1,6 @@
# Ruff config — https://docs.astral.sh/ruff/ # Ruff config — https://docs.astral.sh/ruff/
# `include` sets which files are linted; widen it to cover more paths. # `include` sets which files are linted; widen it to cover more paths.
include = ["tools/perfetto/**/*.py"] include = ["tools/**/*.py"]
line-length = 100 line-length = 100
target-version = "py310" target-version = "py310"
+4 -12
View File
@@ -82,17 +82,6 @@ struct method_trait<Method, Result (wivrn::compositor::*)(Args...)>
namespace namespace
{ {
os_mutex copy_mutex(std::mutex & m)
{
return {
.mutex = *m.native_handle(),
#ifndef NDEBUG
.initialized = true,
.recursive = false,
#endif
};
}
const comp_swapchain_image & get_layer_image(const comp_layer & layer, uint32_t swapchain_index, uint32_t image_index) const comp_swapchain_image & get_layer_image(const comp_layer & layer, uint32_t swapchain_index, uint32_t image_index)
{ {
return reinterpret_cast<struct comp_swapchain *>(comp_layer_get_swapchain(&layer, swapchain_index))->images[image_index]; return reinterpret_cast<struct comp_swapchain *>(comp_layer_get_swapchain(&layer, swapchain_index))->images[image_index];
@@ -735,8 +724,11 @@ compositor::compositor(wivrn_session & session) :
// vk_init_from_given assumes a graphics queue was provided // vk_init_from_given assumes a graphics queue was provided
c_base->vk.graphics_queue = nullptr; c_base->vk.graphics_queue = nullptr;
// Monado submits to the main queue from IPC client threads under
// main_queue->mutex: our own submissions must take the same lock.
vk::detail::resultCheck(vk::Result(vk_init_mutex(&c_base->vk)), "vk_init_mutex");
if (c_base->vk.main_queue) if (c_base->vk.main_queue)
c_base->vk.main_queue->mutex = copy_mutex(vk.queue.mutex); vk.queue.mutex.share(c_base->vk.main_queue->mutex.mutex);
{ {
comp_vulkan_formats formats{}; comp_vulkan_formats formats{};
+6 -3
View File
@@ -572,9 +572,12 @@ void wivrn::video_encoder_vulkan::init(const vk::VideoCapabilitiesKHR & video_ca
ts_pool = gpu_timestamp_pool(vk, encode_queue.family_index, num_slots, std::format("vulkan encoder {} encode", stream_idx)); ts_pool = gpu_timestamp_pool(vk, encode_queue.family_index, num_slots, std::format("vulkan encoder {} encode", stream_idx));
if (tmp_image) if (tmp_image)
ts_pool_image_copy = gpu_timestamp_pool(vk, encode_queue.family_index, num_slots, std::format("vulkan encoder {} image-copy", stream_idx)); ts_pool_image_copy = gpu_timestamp_pool(vk, encode_queue.family_index, num_slots, std::format("vulkan encoder {} image-copy", stream_idx));
const uint32_t host_copy_family = vk.transfer_queue ? vk.transfer_queue.family_index : encode_queue.family_index; if (slot_data[0].host_buffer)
ts_pool_host_copy = gpu_timestamp_pool(vk, host_copy_family, num_slots, std::format("vulkan encoder {} host-copy", stream_idx)); {
ts_pool_host_copy_overflow = gpu_timestamp_pool(vk, host_copy_family, num_slots, std::format("vulkan encoder {} host-copy-overflow", stream_idx)); const uint32_t host_copy_family = vk.transfer_queue ? vk.transfer_queue.family_index : encode_queue.family_index;
ts_pool_host_copy = gpu_timestamp_pool(vk, host_copy_family, num_slots, std::format("vulkan encoder {} host-copy", stream_idx));
ts_pool_host_copy_overflow = gpu_timestamp_pool(vk, host_copy_family, num_slots, std::format("vulkan encoder {} host-copy-overflow", stream_idx));
}
// command pools // command pools
{ {
+3 -1
View File
@@ -53,6 +53,7 @@ namespace wivrn::trace
namespace namespace
{ {
bool initialized = false; bool initialized = false;
bool enabled = false;
::vk_bundle * calibration = nullptr; ::vk_bundle * calibration = nullptr;
perfetto::Track g_encoder_track(1); perfetto::Track g_encoder_track(1);
@@ -266,6 +267,7 @@ void init()
U_LOG_D("wivrn::trace: WIVRN_TRACING not set, perfetto tracing disabled"); U_LOG_D("wivrn::trace: WIVRN_TRACING not set, perfetto tracing disabled");
return; return;
} }
enabled = true;
const bool use_system = mode == tracing_mode::system or mode == tracing_mode::both; const bool use_system = mode == tracing_mode::system or mode == tracing_mode::both;
const bool use_inprocess = mode == tracing_mode::inprocess or mode == tracing_mode::both; const bool use_inprocess = mode == tracing_mode::inprocess or mode == tracing_mode::both;
@@ -321,7 +323,7 @@ void shutdown()
bool is_enabled() bool is_enabled()
{ {
return initialized; return enabled;
} }
void set_calibration_source(::vk_bundle * monado_vk) void set_calibration_source(::vk_bundle * monado_vk)
+37 -1
View File
@@ -23,6 +23,7 @@
#include <cstdint> #include <cstdint>
#include <inplace_vector.hpp> #include <inplace_vector.hpp>
#include <mutex> #include <mutex>
#include <pthread.h>
#include <type_traits> #include <type_traits>
#include <vector> #include <vector>
#include <vulkan/vulkan_raii.hpp> #include <vulkan/vulkan_raii.hpp>
@@ -62,9 +63,44 @@ uint64_t vk_handle(const T & handle)
struct vk_bundle struct vk_bundle
{ {
// Lockable that can be redirected to a pthread_mutex_t owned by monado,
// so that all VkQueue submitters take the same lock.
class queue_mutex
{
pthread_mutex_t storage = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t * mutex = &storage;
public:
queue_mutex() = default;
queue_mutex(const queue_mutex &) = delete;
queue_mutex & operator=(const queue_mutex &) = delete;
~queue_mutex()
{
pthread_mutex_destroy(&storage);
}
void lock()
{
pthread_mutex_lock(mutex);
}
bool try_lock()
{
return pthread_mutex_trylock(mutex) == 0;
}
void unlock()
{
pthread_mutex_unlock(mutex);
}
// external must be initialized, not currently locked, and
// outlive the last lock()
void share(pthread_mutex_t & external)
{
mutex = &external;
}
};
struct queue_data struct queue_data
{ {
std::mutex mutex; queue_mutex mutex;
vk::raii::Queue queue = nullptr; vk::raii::Queue queue = nullptr;
uint32_t family_index = vk::QueueFamilyIgnored; uint32_t family_index = vk::QueueFamilyIgnored;
operator bool() const operator bool() const
+30 -28
View File
@@ -1,47 +1,49 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import os
import re import re
import subprocess
import sys
from elftools.elf.elffile import ELFFile from elftools.elf.elffile import ELFFile
from elftools.elf.sections import NoteSection from elftools.elf.sections import NoteSection
import os
import sys
import subprocess
def get_lib_list(path): def get_lib_list(path):
def get_build_id(filename): def get_build_id(filename):
with open(filename, 'rb') as f: with open(filename, "rb") as f:
for sect in ELFFile(f).iter_sections(): for sect in ELFFile(f).iter_sections():
if not isinstance(sect, NoteSection): if not isinstance(sect, NoteSection):
continue continue
for note in sect.iter_notes(): for note in sect.iter_notes():
if note['n_type'] in {'NT_GNU_BUILD_ID', 'NT_GNU_GOLD_VERSION'}: if note["n_type"] in {"NT_GNU_BUILD_ID", "NT_GNU_GOLD_VERSION"}:
return note['n_desc'] return note["n_desc"]
return None return None
libs = {} libs = {}
for root, dirs, files in os.walk(path): for root, dirs, files in os.walk(path):
for name in files: for name in files:
if name.endswith('.so'): if name.endswith(".so"):
build_id = get_build_id(os.path.join(root, name)) build_id = get_build_id(os.path.join(root, name))
if build_id: if build_id:
libs[build_id] = os.path.join(root, name) libs[build_id] = os.path.join(root, name)
return libs return libs
libs = get_lib_list('build/intermediates/merged_native_libs') libs = get_lib_list("build/intermediates/merged_native_libs")
r = re.compile("^.*#[0-9]+ pc ([0-9a-f]+) .*BuildId: ([0-9a-f]*).*") r = re.compile("^.*#[0-9]+ pc ([0-9a-f]+) .*BuildId: ([0-9a-f]*).*")
for line in sys.stdin: for line in sys.stdin:
m = r.match(line.rstrip()) m = r.match(line.rstrip())
if m: if m:
address = m[1] address = m[1]
build_id = m[2] build_id = m[2]
if build_id in libs: if build_id in libs:
lib = libs[build_id] lib = libs[build_id]
subprocess.run(['llvm-symbolizer'], input=(lib + ' 0x' + address).encode("utf-8")) subprocess.run(
["llvm-symbolizer"], input=(lib + " 0x" + address).encode("utf-8"), check=False
)
+124 -106
View File
@@ -1,133 +1,151 @@
#!/usr/bin/env python #!/usr/bin/env python
import polib
import argparse import argparse
import os import os
import pathlib import pathlib
import subprocess import subprocess
import tempfile import tempfile
def list_files(base: str, exts: str|list[str]): import polib
if type(exts) == str:
exts = [exts]
for root, dirs, files in os.walk(base):
for f in files:
for ext in exts:
if f.endswith(ext):
yield os.path.join(root, f)
ISSUE_LABEL="localisation"
ISSUE_TITLE="[{lang}] Missing translations" def list_files(base: str, exts: str | list[str]):
if type(exts) == str:
exts = [exts]
for root, dirs, files in os.walk(base):
for f in files:
for ext in exts:
if f.endswith(ext):
yield os.path.join(root, f)
ISSUE_LABEL = "localisation"
ISSUE_TITLE = "[{lang}] Missing translations"
if __name__ == "__main__": if __name__ == "__main__":
root = os.path.dirname(os.path.dirname(__file__)) root = os.path.dirname(os.path.dirname(__file__))
locale_dir = os.path.join(root, "locale") locale_dir = os.path.join(root, "locale")
cwd = os.getcwd() cwd = os.getcwd()
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
prog='check_po.py', prog="check_po.py", description="Check that all strings are translated in a .po file"
description='Check that all strings are translated in a .po file') )
parser.add_argument('lang', type=str, nargs="*") parser.add_argument("lang", type=str, nargs="*")
parser.add_argument('--github-repository') parser.add_argument("--github-repository")
parser.add_argument('--github-token') parser.add_argument("--github-token")
parser.add_argument('--manage-issues', action="store_true") parser.add_argument("--manage-issues", action="store_true")
args = parser.parse_args() args = parser.parse_args()
if len(args.lang) == 0: if len(args.lang) == 0:
for d in sorted(os.listdir(locale_dir)): for d in sorted(os.listdir(locale_dir)):
if os.path.isdir(os.path.join(locale_dir, d)): if os.path.isdir(os.path.join(locale_dir, d)):
args.lang.append(d) args.lang.append(d)
if args.manage_issues: if args.manage_issues:
from github import Auth, Github, GithubException from github import Auth, Github, GithubException
gh = Github(auth=Auth.Token(args.github_token))
repo = gh.get_repo(args.github_repository)
with tempfile.TemporaryDirectory() as tmpdir: gh = Github(auth=Auth.Token(args.github_token))
client_pot = os.path.join(tmpdir, "client.pot") repo = gh.get_repo(args.github_repository)
dashboard_pot = os.path.join(tmpdir, "dashboard.pot")
subprocess.check_call( with tempfile.TemporaryDirectory() as tmpdir:
["xgettext", client_pot = os.path.join(tmpdir, "client.pot")
"--c++", "--from-code=UTF-8", dashboard_pot = os.path.join(tmpdir, "dashboard.pot")
"--keyword=_:1,1t",
"--keyword=_S:1,1t",
"--keyword=_C:1c,2,2t",
"--keyword=_cS:1c,2,2t",
"--keyword=_cF:1c,2,2t",
"--keyword=_F:1,1t",
"--keyword=gettext_noop:1,1t",
"--output", client_pot,
"--package-name=WiVRn",
] + sorted(list_files(os.path.join(root, "client"), ".cpp"))
)
subprocess.check_call( subprocess.check_call(
["xgettext", [
"--c++", "--kde", "--from-code=UTF-8", "xgettext",
"--keyword=i18n:1", "--c++",
"--keyword=i18nc:1c,2", "--from-code=UTF-8",
"--keyword=i18np:1,2", "--keyword=_:1,1t",
"--keyword=i18ncp:1c,2,3", "--keyword=_S:1,1t",
"--output", dashboard_pot, "--keyword=_C:1c,2,2t",
"--package-name=WiVRn-dashboard", "--keyword=_cS:1c,2,2t",
] + sorted(list_files(os.path.join(root, "dashboard"), [".cpp", ".qml"])) "--keyword=_cF:1c,2,2t",
) "--keyword=_F:1,1t",
"--keyword=gettext_noop:1,1t",
"--output",
client_pot,
"--package-name=WiVRn",
]
+ sorted(list_files(os.path.join(root, "client"), ".cpp"))
)
client_ref = polib.pofile(client_pot) subprocess.check_call(
dashboard_ref = polib.pofile(dashboard_pot) [
"xgettext",
"--c++",
"--kde",
"--from-code=UTF-8",
"--keyword=i18n:1",
"--keyword=i18nc:1c,2",
"--keyword=i18np:1,2",
"--keyword=i18ncp:1c,2,3",
"--output",
dashboard_pot,
"--package-name=WiVRn-dashboard",
]
+ sorted(list_files(os.path.join(root, "dashboard"), [".cpp", ".qml"]))
)
for lang in args.lang: client_ref = polib.pofile(client_pot)
lang_issues = dict() dashboard_ref = polib.pofile(dashboard_pot)
for po_ref, po in ((client_ref, os.path.join(locale_dir, lang, "wivrn.po")),
(dashboard_ref, os.path.join(locale_dir, lang, "wivrn-dashboard.po"))):
if not os.path.exists(po):
continue
po_file = polib.pofile(po)
po = os.path.relpath(po, cwd)
entries = [i.msgid for i in po_file.translated_entries()]
missing = 0 for lang in args.lang:
for i in po_ref: lang_issues = {}
if not i.obsolete: for po_ref, po in (
if not i.msgid in entries: (client_ref, os.path.join(locale_dir, lang, "wivrn.po")),
missing = missing + 1 (dashboard_ref, os.path.join(locale_dir, lang, "wivrn-dashboard.po")),
print(f"::notice file={po}::{lang} translation for {repr(i.msgid)} is missing") ):
if not os.path.exists(po):
continue
po_file = polib.pofile(po)
po = os.path.relpath(po, cwd)
entries = [i.msgid for i in po_file.translated_entries()]
if not po in lang_issues: missing = 0
lang_issues[po] = [] for i in po_ref:
lang_issues[po].append(repr(i.msgid)) if not i.obsolete and i.msgid not in entries:
missing = missing + 1
print(f"::notice file={po}::{lang} translation for {i.msgid!r} is missing")
if missing > 0: if po not in lang_issues:
print(f"::warning file={po}::{lang} {missing} translations missing") lang_issues[po] = []
lang_issues[po].append(repr(i.msgid))
if args.manage_issues: if missing > 0:
issues = [i for i in repo.get_issues(state="all", labels = [ISSUE_LABEL]) if i.title == ISSUE_TITLE.format(lang=lang)] print(f"::warning file={po}::{lang} {missing} translations missing")
issue_body = 'The following translations are missing:\n' if args.manage_issues:
for po in lang_issues: issues = [
issue_body += '\n## ' + pathlib.Path(po).name + '\n' i
for msg in lang_issues[po]: for i in repo.get_issues(state="all", labels=[ISSUE_LABEL])
issue_body += '- ' + msg + '\n' if i.title == ISSUE_TITLE.format(lang=lang)
]
if len(lang_issues) > 0: issue_body = "The following translations are missing:\n"
if issues: for po, msgs in lang_issues.items():
for issue in issues: issue_body += "\n## " + pathlib.Path(po).name + "\n"
if issue.state != "open" or issue.body != issue_body: for msg in msgs:
issue.edit(state="open", body=issue_body) issue_body += "- " + msg + "\n"
else:
try: if len(lang_issues) > 0:
repo.create_issue( if issues:
title=ISSUE_TITLE.format(lang=lang), for issue in issues:
body=issue_body, if issue.state != "open" or issue.body != issue_body:
labels=[ISSUE_LABEL] issue.edit(state="open", body=issue_body)
) else:
except GithubException as e: try:
# Ignore error when issues are disabled on repository repo.create_issue(
if e.status != 410: title=ISSUE_TITLE.format(lang=lang),
raise body=issue_body,
else: labels=[ISSUE_LABEL],
for issue in issues: )
issue.edit(state="closed", body="All translations are up to date") except GithubException as e:
# Ignore error when issues are disabled on repository
if e.status != 410:
raise
else:
for issue in issues:
issue.edit(state="closed", body="All translations are up to date")
+10 -9
View File
@@ -1,25 +1,26 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import sys
import os.path import os.path
import sys
print( print(
"""// Generated file, do not edit """// Generated file, do not edit
#include <map> #include <map>
#include <string> #include <string>
#include <vector> #include <vector>
std::map<std::string, std::vector<int>> glyph_set_per_language = {""") std::map<std::string, std::vector<int>> glyph_set_per_language = {"""
)
for po_file in sys.argv[1:]: for po_file in sys.argv[1:]:
lang = os.path.basename(os.path.dirname(po_file)) lang = os.path.basename(os.path.dirname(po_file))
with open(po_file) as f: with open(po_file) as f:
charset = sorted(set(f.read())) charset = sorted(set(f.read()))
# Basic Latin and Latin-1 Supplement are always included # Basic Latin and Latin-1 Supplement are always included
charset = ', '.join([str(ord(c)) for c in charset if ord(c) > 255]) charset = ", ".join([str(ord(c)) for c in charset if ord(c) > 255])
print("\t{{ \"{}\", {{{}}}}},".format(lang, charset)) print(f'\t{{ "{lang}", {{{charset}}}}},')
print("};") print("};")
+206 -186
View File
@@ -1,29 +1,31 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
__license__ = 'MIT' __license__ = "MIT"
import json import argparse
from urllib.parse import urlparse, ParseResult, parse_qs import asyncio
import os
import contextlib import contextlib
import copy import copy
import glob
import subprocess
import argparse
import logging
import hashlib import hashlib
import asyncio import itertools
from typing import Any, Dict, List, NamedTuple, Optional, Tuple, TypedDict import json
import logging
import os
import subprocess
from typing import Any, NamedTuple, TypedDict
from urllib.parse import ParseResult, parse_qs, urlparse
import aiohttp import aiohttp
import toml import toml
CRATES_IO = 'https://static.crates.io/crates' CRATES_IO = "https://static.crates.io/crates"
CARGO_HOME = 'cargo' CARGO_HOME = "cargo"
CARGO_CRATES = f'{CARGO_HOME}/vendor' CARGO_CRATES = f"{CARGO_HOME}/vendor"
VENDORED_SOURCES = 'vendored-sources' VENDORED_SOURCES = "vendored-sources"
GIT_CACHE = 'flatpak-cargo/git' GIT_CACHE = "flatpak-cargo/git"
COMMIT_LEN = 7 COMMIT_LEN = 7
logger = logging.getLogger(__name__)
@contextlib.contextmanager @contextlib.contextmanager
def workdir(path: str): def workdir(path: str):
@@ -36,134 +38,141 @@ def workdir(path: str):
def canonical_url(url: str) -> ParseResult: def canonical_url(url: str) -> ParseResult:
'Converts a string to a Cargo Canonical URL, as per https://github.com/rust-lang/cargo/blob/35c55a93200c84a4de4627f1770f76a8ad268a39/src/cargo/util/canonical_url.rs#L19' "Converts a string to a Cargo Canonical URL, as per https://github.com/rust-lang/cargo/blob/35c55a93200c84a4de4627f1770f76a8ad268a39/src/cargo/util/canonical_url.rs#L19"
# Hrm. The upstream cargo does not replace those URLs, but if we don't then it doesn't work too well :( # Hrm. The upstream cargo does not replace those URLs, but if we don't then it doesn't work too well :(
url = url.replace('git+https://', 'https://') url = url.replace("git+https://", "https://")
u = urlparse(url) u = urlparse(url)
# It seems cargo drops query and fragment # It seems cargo drops query and fragment
u = ParseResult(u.scheme, u.netloc, u.path, '', '', '') u = ParseResult(u.scheme, u.netloc, u.path, "", "", "")
u = u._replace(path = u.path.rstrip('/')) u = u._replace(path=u.path.rstrip("/"))
if u.netloc == 'github.com': if u.netloc == "github.com":
u = u._replace(scheme = 'https') u = u._replace(scheme="https")
u = u._replace(path = u.path.lower()) u = u._replace(path=u.path.lower())
if u.path.endswith('.git'): if u.path.endswith(".git"):
u = u._replace(path = u.path[:-len('.git')]) u = u._replace(path=u.path[: -len(".git")])
return u return u
def get_git_tarball(repo_url: str, commit: str) -> str: def get_git_tarball(repo_url: str, commit: str) -> str:
url = canonical_url(repo_url) url = canonical_url(repo_url)
path = url.path.split('/')[1:] path = url.path.split("/")[1:]
assert len(path) == 2 assert len(path) == 2
owner = path[0] owner = path[0]
if path[1].endswith('.git'): if path[1].endswith(".git"):
repo = path[1].replace('.git', '') repo = path[1].replace(".git", "")
else: else:
repo = path[1] repo = path[1]
if url.hostname == 'github.com': if url.hostname == "github.com":
return f'https://codeload.{url.hostname}/{owner}/{repo}/tar.gz/{commit}' return f"https://codeload.{url.hostname}/{owner}/{repo}/tar.gz/{commit}"
elif url.hostname.split('.')[0] == 'gitlab': # type: ignore elif url.hostname.split(".")[0] == "gitlab": # type: ignore
return f'https://{url.hostname}/{owner}/{repo}/-/archive/{commit}/{repo}-{commit}.tar.gz' return f"https://{url.hostname}/{owner}/{repo}/-/archive/{commit}/{repo}-{commit}.tar.gz"
elif url.hostname == 'bitbucket.org': elif url.hostname == "bitbucket.org":
return f'https://{url.hostname}/{owner}/{repo}/get/{commit}.tar.gz' return f"https://{url.hostname}/{owner}/{repo}/get/{commit}.tar.gz"
else: else:
raise ValueError(f'Don\'t know how to get tarball for {repo_url}') raise ValueError(f"Don't know how to get tarball for {repo_url}")
async def get_remote_sha256(url: str) -> str: async def get_remote_sha256(url: str) -> str:
logging.info(f"started sha256({url})") logger.info(f"started sha256({url})")
sha256 = hashlib.sha256() sha256 = hashlib.sha256()
async with aiohttp.ClientSession(raise_for_status=True) as http_session: async with (
async with http_session.get(url) as response: aiohttp.ClientSession(raise_for_status=True) as http_session,
while True: http_session.get(url) as response,
data = await response.content.read(4096) ):
if not data: while True:
break data = await response.content.read(4096)
sha256.update(data) if not data:
logging.info(f"done sha256({url})") break
sha256.update(data)
logger.info(f"done sha256({url})")
return sha256.hexdigest() return sha256.hexdigest()
_TomlType = Dict[str, Any] _TomlType = dict[str, Any]
def load_toml(tomlfile: str = 'Cargo.lock') -> _TomlType: def load_toml(tomlfile: str = "Cargo.lock") -> _TomlType:
with open(tomlfile, 'r') as f: with open(tomlfile, "r") as f:
toml_data = toml.load(f) toml_data = toml.load(f)
return toml_data return toml_data
def git_repo_name(git_url: str, commit: str) -> str: def git_repo_name(git_url: str, commit: str) -> str:
name = canonical_url(git_url).path.split('/')[-1] name = canonical_url(git_url).path.split("/")[-1]
return f'{name}-{commit[:COMMIT_LEN]}' return f"{name}-{commit[:COMMIT_LEN]}"
def fetch_git_repo(git_url: str, commit: str) -> str: def fetch_git_repo(git_url: str, commit: str) -> str:
repo_dir = git_url.replace('://', '_').replace('/', '_') repo_dir = git_url.replace("://", "_").replace("/", "_")
cache_dir = os.environ.get('XDG_CACHE_HOME', os.path.expanduser('~/.cache')) cache_dir = os.environ.get("XDG_CACHE_HOME", os.path.expanduser("~/.cache"))
clone_dir = os.path.join(cache_dir, 'flatpak-cargo', repo_dir) clone_dir = os.path.join(cache_dir, "flatpak-cargo", repo_dir)
if not os.path.isdir(os.path.join(clone_dir, '.git')): if not os.path.isdir(os.path.join(clone_dir, ".git")):
subprocess.run(['git', 'clone', '--depth=1', git_url, clone_dir], check=True) subprocess.run(["git", "clone", "--depth=1", git_url, clone_dir], check=True)
rev_parse_proc = subprocess.run(['git', 'rev-parse', 'HEAD'], cwd=clone_dir, check=True, rev_parse_proc = subprocess.run(
stdout=subprocess.PIPE) ["git", "rev-parse", "HEAD"], cwd=clone_dir, check=True, stdout=subprocess.PIPE
)
head = rev_parse_proc.stdout.decode().strip() head = rev_parse_proc.stdout.decode().strip()
if head[:COMMIT_LEN] != commit[:COMMIT_LEN]: if head[:COMMIT_LEN] != commit[:COMMIT_LEN]:
subprocess.run(['git', 'fetch', 'origin', commit], cwd=clone_dir, check=True) subprocess.run(["git", "fetch", "origin", commit], cwd=clone_dir, check=True)
subprocess.run(['git', 'checkout', commit], cwd=clone_dir, check=True) subprocess.run(["git", "checkout", commit], cwd=clone_dir, check=True)
# Get the submodules as they might contain dependencies. This is a noop if # Get the submodules as they might contain dependencies. This is a noop if
# there are no submodules in the repository # there are no submodules in the repository
subprocess.run(['git', 'submodule', 'update', '--init', '--recursive'], cwd=clone_dir, check=True) subprocess.run(
["git", "submodule", "update", "--init", "--recursive"], cwd=clone_dir, check=True
)
return clone_dir return clone_dir
def update_workspace_keys(pkg, workspace): def update_workspace_keys(pkg, workspace):
for key, item in pkg.items(): for key, item in pkg.items():
# There cannot be a 'workspace' key if the item is not a dict. # There cannot be a 'workspace' key if the item is not a dict.
if not isinstance(item, dict): if not isinstance(item, dict):
continue; continue
# Recurse for keys under target.cfg(..) # Recurse for keys under target.cfg(..)
if key == 'target': if key == "target":
for target in item.values(): for target in item.values():
update_workspace_keys(target, workspace) update_workspace_keys(target, workspace)
continue; continue
# dev-dependencies and build-dependencies should reference root dependencies table from workspace # dev-dependencies and build-dependencies should reference root dependencies table from workspace
elif key == 'dev-dependencies' or key == 'build-dependencies': elif key == "dev-dependencies" or key == "build-dependencies":
update_workspace_keys(item, workspace.get('dependencies', None)) update_workspace_keys(item, workspace.get("dependencies", None))
continue; continue
if not workspace or not key in workspace: if not workspace or not key in workspace:
continue; continue
workspace_item = workspace[key] workspace_item = workspace[key]
if 'workspace' in item: if "workspace" in item:
if isinstance(workspace_item, dict): if isinstance(workspace_item, dict):
del item['workspace'] del item["workspace"]
for dep_key, workspace_value in workspace_item.items(): for dep_key, workspace_value in workspace_item.items():
# features are additive # features are additive
if dep_key == 'features' and 'features' in item: if dep_key == "features" and "features" in item:
item['features'] += workspace_value item["features"] += workspace_value
else: else:
item[dep_key] = workspace_value item[dep_key] = workspace_value
elif len(item) > 1: elif len(item) > 1:
del item['workspace'] del item["workspace"]
item.update({ 'version': workspace_item }) item.update({"version": workspace_item})
else: else:
pkg[key] = workspace_item pkg[key] = workspace_item
else: else:
update_workspace_keys(item, workspace_item) update_workspace_keys(item, workspace_item)
class _GitPackage(NamedTuple): class _GitPackage(NamedTuple):
path: str path: str
package: _TomlType package: _TomlType
workspace: Optional[_TomlType] workspace: _TomlType | None
@property @property
def normalized(self) -> _TomlType: def normalized(self) -> _TomlType:
@@ -175,27 +184,26 @@ class _GitPackage(NamedTuple):
return package return package
_GitPackagesType = Dict[str, _GitPackage]
_GitPackagesType = dict[str, _GitPackage]
async def get_git_repo_packages(git_url: str, commit: str) -> _GitPackagesType: async def get_git_repo_packages(git_url: str, commit: str) -> _GitPackagesType:
logging.info('Loading packages from %s', git_url) logger.info("Loading packages from %s", git_url)
git_repo_dir = fetch_git_repo(git_url, commit) git_repo_dir = fetch_git_repo(git_url, commit)
packages: _GitPackagesType = {} packages: _GitPackagesType = {}
def get_cargo_toml_packages(root_dir: str, workspace: Optional[_TomlType] = None): def get_cargo_toml_packages(root_dir: str, workspace: _TomlType | None = None):
assert not os.path.isabs(root_dir) and os.path.isdir(root_dir) assert not os.path.isabs(root_dir) and os.path.isdir(root_dir)
with workdir(root_dir): with workdir(root_dir):
if os.path.exists('Cargo.toml'): if os.path.exists("Cargo.toml"):
cargo_toml = load_toml('Cargo.toml') cargo_toml = load_toml("Cargo.toml")
workspace = cargo_toml.get('workspace') or workspace workspace = cargo_toml.get("workspace") or workspace
if 'package' in cargo_toml: if "package" in cargo_toml:
packages[cargo_toml['package']['name']] = _GitPackage( packages[cargo_toml["package"]["name"]] = _GitPackage(
path=os.path.normpath(root_dir), path=os.path.normpath(root_dir), package=cargo_toml, workspace=workspace
package=cargo_toml,
workspace=workspace
) )
for child in os.scandir(root_dir): for child in os.scandir(root_dir):
if child.is_dir(): if child.is_dir():
@@ -203,11 +211,11 @@ async def get_git_repo_packages(git_url: str, commit: str) -> _GitPackagesType:
get_cargo_toml_packages(child.path, workspace) get_cargo_toml_packages(child.path, workspace)
with workdir(git_repo_dir): with workdir(git_repo_dir):
get_cargo_toml_packages('.') get_cargo_toml_packages(".")
assert packages, f"No packages found in {git_repo_dir}" assert packages, f"No packages found in {git_repo_dir}"
logging.debug( logger.debug(
'Packages in %s:\n%s', "Packages in %s:\n%s",
git_url, git_url,
json.dumps( json.dumps(
{k: v.path for k, v in packages.items()}, {k: v.path for k, v in packages.items()},
@@ -217,99 +225,104 @@ async def get_git_repo_packages(git_url: str, commit: str) -> _GitPackagesType:
return packages return packages
_FlatpakSourceType = Dict[str, Any] _FlatpakSourceType = dict[str, Any]
async def get_git_repo_sources( async def get_git_repo_sources(
url: str, url: str,
commit: str, commit: str,
tarball: bool = False, tarball: bool = False,
) -> List[_FlatpakSourceType]: ) -> list[_FlatpakSourceType]:
name = git_repo_name(url, commit) name = git_repo_name(url, commit)
if tarball: if tarball:
tarball_url = get_git_tarball(url, commit) tarball_url = get_git_tarball(url, commit)
git_repo_sources = [{ git_repo_sources = [
'type': 'archive', {
'archive-type': 'tar-gzip', "type": "archive",
'url': tarball_url, "archive-type": "tar-gzip",
'sha256': await get_remote_sha256(tarball_url), "url": tarball_url,
'dest': f'{GIT_CACHE}/{name}', "sha256": await get_remote_sha256(tarball_url),
}] "dest": f"{GIT_CACHE}/{name}",
}
]
else: else:
git_repo_sources = [{ git_repo_sources = [
'type': 'git', {
'url': url, "type": "git",
'commit': commit, "url": url,
'dest': f'{GIT_CACHE}/{name}', "commit": commit,
}] "dest": f"{GIT_CACHE}/{name}",
}
]
return git_repo_sources return git_repo_sources
_GitRepo = TypedDict('_GitRepo', {'lock': asyncio.Lock, 'commits': Dict[str, _GitPackagesType]}) _GitRepo = TypedDict("_GitRepo", {"lock": asyncio.Lock, "commits": dict[str, _GitPackagesType]})
_GitReposType = Dict[str, _GitRepo] _GitReposType = dict[str, _GitRepo]
_VendorEntryType = Dict[str, Dict[str, str]] _VendorEntryType = dict[str, dict[str, str]]
async def get_git_package_sources( async def get_git_package_sources(
package: _TomlType, package: _TomlType,
git_repos: _GitReposType, git_repos: _GitReposType,
) -> Tuple[List[_FlatpakSourceType], _VendorEntryType]: ) -> tuple[list[_FlatpakSourceType], _VendorEntryType]:
name = package['name'] name = package["name"]
source = package['source'] source = package["source"]
commit = urlparse(source).fragment commit = urlparse(source).fragment
assert commit, 'The commit needs to be indicated in the fragement part' assert commit, "The commit needs to be indicated in the fragement part"
canonical = canonical_url(source) canonical = canonical_url(source)
repo_url = canonical.geturl() repo_url = canonical.geturl()
git_repo = git_repos.setdefault(repo_url, { git_repo = git_repos.setdefault(
'commits': {}, repo_url,
'lock': asyncio.Lock(), {
}) "commits": {},
async with git_repo['lock']: "lock": asyncio.Lock(),
if commit not in git_repo['commits']: },
git_repo['commits'][commit] = await get_git_repo_packages(repo_url, commit) )
async with git_repo["lock"]:
if commit not in git_repo["commits"]:
git_repo["commits"][commit] = await get_git_repo_packages(repo_url, commit)
cargo_vendored_entry: _VendorEntryType = { cargo_vendored_entry: _VendorEntryType = {
repo_url: { repo_url: {
'git': repo_url, "git": repo_url,
'replace-with': VENDORED_SOURCES, "replace-with": VENDORED_SOURCES,
} }
} }
rev = parse_qs(urlparse(source).query).get('rev') rev = parse_qs(urlparse(source).query).get("rev")
tag = parse_qs(urlparse(source).query).get('tag') tag = parse_qs(urlparse(source).query).get("tag")
branch = parse_qs(urlparse(source).query).get('branch') branch = parse_qs(urlparse(source).query).get("branch")
if rev: if rev:
assert len(rev) == 1 assert len(rev) == 1
cargo_vendored_entry[repo_url]['rev'] = rev[0] cargo_vendored_entry[repo_url]["rev"] = rev[0]
elif tag: elif tag:
assert len(tag) == 1 assert len(tag) == 1
cargo_vendored_entry[repo_url]['tag'] = tag[0] cargo_vendored_entry[repo_url]["tag"] = tag[0]
elif branch: elif branch:
assert len(branch) == 1 assert len(branch) == 1
cargo_vendored_entry[repo_url]['branch'] = branch[0] cargo_vendored_entry[repo_url]["branch"] = branch[0]
logging.info("Adding package %s from %s", name, repo_url) logger.info("Adding package %s from %s", name, repo_url)
git_pkg = git_repo['commits'][commit][name] git_pkg = git_repo["commits"][commit][name]
pkg_repo_dir = os.path.join(GIT_CACHE, git_repo_name(repo_url, commit), git_pkg.path) pkg_repo_dir = os.path.join(GIT_CACHE, git_repo_name(repo_url, commit), git_pkg.path)
git_sources: List[_FlatpakSourceType] = [ git_sources: list[_FlatpakSourceType] = [
{ {
'type': 'shell', "type": "shell",
'commands': [ "commands": [f'cp -r --reflink=auto "{pkg_repo_dir}" "{CARGO_CRATES}/{name}"'],
f'cp -r --reflink=auto "{pkg_repo_dir}" "{CARGO_CRATES}/{name}"'
],
}, },
{ {
'type': 'inline', "type": "inline",
'contents': toml.dumps(git_pkg.normalized), "contents": toml.dumps(git_pkg.normalized),
'dest': f'{CARGO_CRATES}/{name}', #-{version}', "dest": f"{CARGO_CRATES}/{name}", # -{version}',
'dest-filename': 'Cargo.toml', "dest-filename": "Cargo.toml",
}, },
{ {
'type': 'inline', "type": "inline",
'contents': json.dumps({'package': None, 'files': {}}), "contents": json.dumps({"package": None, "files": {}}),
'dest': f'{CARGO_CRATES}/{name}', #-{version}', "dest": f"{CARGO_CRATES}/{name}", # -{version}',
'dest-filename': '.cargo-checksum.json', "dest-filename": ".cargo-checksum.json",
} },
] ]
return (git_sources, cargo_vendored_entry) return (git_sources, cargo_vendored_entry)
@@ -319,49 +332,49 @@ async def get_package_sources(
package: _TomlType, package: _TomlType,
cargo_lock: _TomlType, cargo_lock: _TomlType,
git_repos: _GitReposType, git_repos: _GitReposType,
) -> Optional[Tuple[List[_FlatpakSourceType], _VendorEntryType]]: ) -> tuple[list[_FlatpakSourceType], _VendorEntryType] | None:
metadata = cargo_lock.get('metadata') metadata = cargo_lock.get("metadata")
name = package['name'] name = package["name"]
version = package['version'] version = package["version"]
if 'source' not in package: if "source" not in package:
logging.debug('%s has no source', name) logger.debug("%s has no source", name)
return None return None
source = package['source'] source = package["source"]
if source.startswith('git+'): if source.startswith("git+"):
return await get_git_package_sources(package, git_repos) return await get_git_package_sources(package, git_repos)
key = f'checksum {name} {version} ({source})' key = f"checksum {name} {version} ({source})"
if metadata is not None and key in metadata: if metadata is not None and key in metadata:
checksum = metadata[key] checksum = metadata[key]
elif 'checksum' in package: elif "checksum" in package:
checksum = package['checksum'] checksum = package["checksum"]
else: else:
logging.warning(f'{name} doesn\'t have checksum') logger.warning(f"{name} doesn't have checksum")
return None return None
crate_sources = [ crate_sources = [
{ {
'type': 'archive', "type": "archive",
'archive-type': 'tar-gzip', "archive-type": "tar-gzip",
'url': f'{CRATES_IO}/{name}/{name}-{version}.crate', "url": f"{CRATES_IO}/{name}/{name}-{version}.crate",
'sha256': checksum, "sha256": checksum,
'dest': f'{CARGO_CRATES}/{name}-{version}', "dest": f"{CARGO_CRATES}/{name}-{version}",
}, },
{ {
'type': 'inline', "type": "inline",
'contents': json.dumps({'package': checksum, 'files': {}}), "contents": json.dumps({"package": checksum, "files": {}}),
'dest': f'{CARGO_CRATES}/{name}-{version}', "dest": f"{CARGO_CRATES}/{name}-{version}",
'dest-filename': '.cargo-checksum.json', "dest-filename": ".cargo-checksum.json",
}, },
] ]
return (crate_sources, {'crates-io': {'replace-with': VENDORED_SOURCES}}) return (crate_sources, {"crates-io": {"replace-with": VENDORED_SOURCES}})
async def generate_sources( async def generate_sources(
cargo_lock: _TomlType, cargo_lock: _TomlType,
git_tarballs: bool = False, git_tarballs: bool = False,
) -> List[_FlatpakSourceType]: ) -> list[_FlatpakSourceType]:
# { # {
# "git-repo-url": { # "git-repo-url": {
# "lock": asyncio.Lock(), # "lock": asyncio.Lock(),
@@ -373,13 +386,13 @@ async def generate_sources(
# } # }
# } # }
git_repos: _GitReposType = {} git_repos: _GitReposType = {}
sources: List[_FlatpakSourceType] = [] sources: list[_FlatpakSourceType] = []
package_sources = [] package_sources = []
cargo_vendored_sources = { cargo_vendored_sources = {
VENDORED_SOURCES: {'directory': f'{CARGO_CRATES}'}, VENDORED_SOURCES: {"directory": f"{CARGO_CRATES}"},
} }
pkg_coros = [get_package_sources(p, cargo_lock, git_repos) for p in cargo_lock['package']] pkg_coros = [get_package_sources(p, cargo_lock, git_repos) for p in cargo_lock["package"]]
for pkg in await asyncio.gather(*pkg_coros): for pkg in await asyncio.gather(*pkg_coros):
if pkg is None: if pkg is None:
continue continue
@@ -388,49 +401,56 @@ async def generate_sources(
package_sources.extend(pkg_sources) package_sources.extend(pkg_sources)
cargo_vendored_sources.update(cargo_vendored_entry) cargo_vendored_sources.update(cargo_vendored_entry)
logging.debug('Adding collected git repos:\n%s', json.dumps(list(git_repos), indent=4)) logger.debug("Adding collected git repos:\n%s", json.dumps(list(git_repos), indent=4))
git_repo_coros = [] git_repo_coros = []
for git_url, git_repo in git_repos.items(): for git_url, git_repo in git_repos.items():
for git_commit in git_repo['commits']: for git_commit in git_repo["commits"]:
git_repo_coros.append(get_git_repo_sources(git_url, git_commit, git_tarballs)) git_repo_coros.append(get_git_repo_sources(git_url, git_commit, git_tarballs))
sources.extend(sum(await asyncio.gather(*git_repo_coros), [])) sources.extend(itertools.chain.from_iterable(await asyncio.gather(*git_repo_coros)))
sources.extend(package_sources) sources.extend(package_sources)
logging.debug('Vendored sources:\n%s', json.dumps(cargo_vendored_sources, indent=4)) logger.debug("Vendored sources:\n%s", json.dumps(cargo_vendored_sources, indent=4))
sources.append({ sources.append(
'type': 'inline', {
'contents': toml.dumps({ "type": "inline",
'source': cargo_vendored_sources, "contents": toml.dumps(
}), {
'dest': CARGO_HOME, "source": cargo_vendored_sources,
'dest-filename': 'config' }
}) ),
"dest": CARGO_HOME,
"dest-filename": "config",
}
)
return sources return sources
def main(): def main():
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument('cargo_lock', help='Path to the Cargo.lock file') parser.add_argument("cargo_lock", help="Path to the Cargo.lock file")
parser.add_argument('-o', '--output', required=False, help='Where to write generated sources') parser.add_argument("-o", "--output", required=False, help="Where to write generated sources")
parser.add_argument('-t', '--git-tarballs', action='store_true', help='Download git repos as tarballs') parser.add_argument(
parser.add_argument('-d', '--debug', action='store_true') "-t", "--git-tarballs", action="store_true", help="Download git repos as tarballs"
)
parser.add_argument("-d", "--debug", action="store_true")
args = parser.parse_args() args = parser.parse_args()
if args.output is not None: if args.output is not None:
outfile = args.output outfile = args.output
else: else:
outfile = 'generated-sources.json' outfile = "generated-sources.json"
if args.debug: if args.debug:
loglevel = logging.DEBUG loglevel = logging.DEBUG
else: else:
loglevel = logging.INFO loglevel = logging.INFO
logging.basicConfig(level=loglevel) logging.basicConfig(level=loglevel)
generated_sources = asyncio.run(generate_sources(load_toml(args.cargo_lock), generated_sources = asyncio.run(
git_tarballs=args.git_tarballs)) generate_sources(load_toml(args.cargo_lock), git_tarballs=args.git_tarballs)
with open(outfile, 'w') as out: )
with open(outfile, "w") as out:
json.dump(generated_sources, out, indent=4, sort_keys=False) json.dump(generated_sources, out, indent=4, sort_keys=False)
if __name__ == '__main__': if __name__ == "__main__":
main() main()
+36 -31
View File
@@ -1,13 +1,13 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import xml.etree.ElementTree as ET
import argparse import argparse
import os
import sys
import typing
import datetime import datetime
import email.utils import email.utils
import os
import subprocess import subprocess
import sys
import typing
import xml.etree.ElementTree as ET
HEADER = """wivrn ({version}-1) {distribution}; urgency=medium HEADER = """wivrn ({version}-1) {distribution}; urgency=medium
@@ -21,17 +21,17 @@ FOOTER = """
""" """
def write_entry( def write_entry(
out: typing.TextIO, out: typing.TextIO,
version: str, version: str,
data: list[str], data: list[str],
author: str, author: str,
distribution: str, distribution: str,
date: datetime.datetime date: datetime.datetime,
) -> None: ) -> None:
out.write(HEADER.format(version=version, distribution=distribution)) out.write(HEADER.format(version=version, distribution=distribution))
for item in data: out.writelines(ITEM.format(text=item) for item in data)
out.write(ITEM.format(text=item))
out.write(FOOTER.format(author=author, date=email.utils.format_datetime(date))) out.write(FOOTER.format(author=author, date=email.utils.format_datetime(date)))
@@ -45,36 +45,41 @@ def main():
args = parser.parse_args() args = parser.parse_args()
if not args.metainfo: if args.metainfo:
args.metainfo = open(os.path.join(os.path.dirname(__file__), "../dashboard/io.github.wivrn.wivrn.metainfo.xml")) tree = ET.parse(args.metainfo)
else:
tree = ET.parse(args.metainfo) default_metainfo = os.path.join(
os.path.dirname(__file__), "../dashboard/io.github.wivrn.wivrn.metainfo.xml"
)
with open(default_metainfo) as metainfo:
tree = ET.parse(metainfo)
if args.nightly: if args.nightly:
version = subprocess.check_output(["git", "describe", "--tags", "--always"]).decode().strip() version = (
if version[0] == 'v': subprocess.check_output(["git", "describe", "--tags", "--always"]).decode().strip()
version = version[1:] # remove the initial "v" )
if version[0] == "v":
version = version[1:] # remove the initial "v"
else: else:
version = '0-' + version version = "0-" + version
write_entry( write_entry(
out=args.out, out=args.out,
version=version, version=version,
data=["Nightly build"], data=["Nightly build"],
author=args.author, author=args.author,
distribution=args.distribution, distribution=args.distribution,
date=datetime.datetime.now() date=datetime.datetime.now().astimezone(),
) )
for release in tree.find("releases").findall("release"): for release in tree.find("releases").findall("release"):
write_entry( write_entry(
out=args.out, out=args.out,
version=release.get("version"), version=release.get("version"),
data=[item.text for item in release.findall("description/ul/li")], data=[item.text for item in release.findall("description/ul/li")],
author=args.author, author=args.author,
distribution=args.distribution, distribution=args.distribution,
date=datetime.datetime.fromisoformat(release.get("date")) date=datetime.datetime.fromisoformat(release.get("date")),
) )
if __name__ == "__main__": if __name__ == "__main__":
+22 -21
View File
@@ -20,9 +20,7 @@ class CMakeFile:
with open(filename) as f: with open(filename) as f:
data = f.read() data = f.read()
for match in re.findall("FetchContent_Declare\\(([^)]*)\\)", data): for match in re.findall("FetchContent_Declare\\(([^)]*)\\)", data):
words = [word for word words = [word for word in match.replace("\n", " ").split(" ") if word]
in match.replace("\n", " ").split(" ")
if word]
self.entries[words[0]] = words[1:] self.entries[words[0]] = words[1:]
def get(self, target: str, key: str) -> str: def get(self, target: str, key: str) -> str:
@@ -36,7 +34,9 @@ if __name__ == "__main__":
parser.add_argument("--git") parser.add_argument("--git")
parser.add_argument("--gitlocal", action="store_true") parser.add_argument("--gitlocal", action="store_true")
parser.add_argument("--dir", action="store_true") parser.add_argument("--dir", action="store_true")
parser.add_argument("--out", help="directory where to write manifest and additional files", default=".") parser.add_argument(
"--out", help="directory where to write manifest and additional files", default="."
)
args = parser.parse_args() args = parser.parse_args()
if not (args.git or args.dir): if not (args.git or args.dir):
@@ -52,34 +52,35 @@ if __name__ == "__main__":
xrizer_repo = "https://github.com/Supreeeme/xrizer" xrizer_repo = "https://github.com/Supreeeme/xrizer"
xrizer_commit = re.findall(f"url: {xrizer_repo}.git[ \n]*commit: ([a-f0-9]*)", template)[0] xrizer_commit = re.findall(f"url: {xrizer_repo}.git[ \n]*commit: ([a-f0-9]*)", template)[0]
lock = urlopen(f"{xrizer_repo}/raw/{xrizer_commit}/Cargo.lock") lock = urlopen(f"{xrizer_repo}/raw/{xrizer_commit}/Cargo.lock")
gen_src = asyncio.run(flatpakcargogenerator.generate_sources( gen_src = asyncio.run(flatpakcargogenerator.generate_sources(toml.loads(lock.read().decode())))
toml.loads(lock.read().decode())))
with open(os.path.join(args.out, "xrizer-gen-src.json"), "w") as f: with open(os.path.join(args.out, "xrizer-gen-src.json"), "w") as f:
json.dump(gen_src, f, indent=4, sort_keys=False) json.dump(gen_src, f, indent=4, sort_keys=False)
with open(os.path.join(root, "monado-rev")) as f:
monado_commit = open(os.path.join(root, "monado-rev")).read() monado_commit = f.read()
boost_url = cmake.get("boost", "URL") boost_url = cmake.get("boost", "URL")
boost_sha256 = cmake.get("boost", "URL_HASH").split("=")[-1] boost_sha256 = cmake.get("boost", "URL_HASH").split("=")[-1]
try: try:
git_tag = subprocess.check_output( git_tag = (
["git", "describe", "--exact-match", "--tags"], subprocess.check_output(
cwd=root, ["git", "describe", "--exact-match", "--tags"], cwd=root, stderr=subprocess.DEVNULL
stderr=subprocess.DEVNULL )
).decode().strip() .decode()
.strip()
)
git_commit = "" git_commit = ""
git_desc = "" git_desc = ""
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
git_tag = "" git_tag = ""
git_commit = subprocess.check_output( git_commit = (
["git", "rev-parse", "HEAD"], subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=root).decode().strip()
cwd=root )
).decode().strip() git_desc = (
git_desc = subprocess.check_output( subprocess.check_output(["git", "describe", "--tags", "--always"], cwd=root)
["git", "describe", "--tags", "--always"], .decode()
cwd=root .strip()
).decode().strip() )
if args.git or args.gitlocal: if args.git or args.gitlocal:
template = template.replace("WIVRN_SRC1", "type: git") template = template.replace("WIVRN_SRC1", "type: git")
View File
+16 -7
View File
@@ -18,6 +18,7 @@ import subprocess
import sys import sys
import tempfile import tempfile
import time import time
import urllib.error
import urllib.request import urllib.request
from datetime import datetime from datetime import datetime
from pathlib import Path from pathlib import Path
@@ -91,7 +92,7 @@ def download_tracebox(url, dest):
else: else:
print(f"\r {downloaded / 1e6:.1f} MB", end="", flush=True) print(f"\r {downloaded / 1e6:.1f} MB", end="", flush=True)
print() print()
except Exception as e: except (OSError, urllib.error.URLError) as e:
Path(dest).unlink(missing_ok=True) Path(dest).unlink(missing_ok=True)
sys.exit(f"wivrn_capture: download failed: {e}") sys.exit(f"wivrn_capture: download failed: {e}")
@@ -106,13 +107,15 @@ def ensure_tracebox(path):
def pgrep(name): def pgrep(name):
"""Return list of matching PIDs (as strings), or [].""" """Return list of matching PIDs (as strings), or []."""
r = subprocess.run(["pgrep", "-x", name], capture_output=True, text=True) r = subprocess.run(["pgrep", "-x", name], capture_output=True, text=True, check=False)
return r.stdout.split() if r.returncode == 0 else [] return r.stdout.split() if r.returncode == 0 else []
def socket_listening(sock_path): def socket_listening(sock_path):
"""Return True if a Unix socket at sock_path is bound and listening.""" """Return True if a Unix socket at sock_path is bound and listening."""
r = subprocess.run(["ss", "-lxH", "src", str(sock_path)], capture_output=True, text=True) r = subprocess.run(
["ss", "-lxH", "src", str(sock_path)], capture_output=True, text=True, check=False
)
return bool(r.stdout.strip()) return bool(r.stdout.strip())
@@ -121,7 +124,11 @@ def wait_for_producer(tracebox, env, timeout_s=20):
deadline = time.time() + timeout_s deadline = time.time() + timeout_s
while time.time() < deadline: while time.time() < deadline:
r = subprocess.run( r = subprocess.run(
[str(tracebox), "perfetto", "--query"], env=env, capture_output=True, text=True [str(tracebox), "perfetto", "--query"],
env=env,
capture_output=True,
text=True,
check=False,
) )
if "track_event" in r.stdout: if "track_event" in r.stdout:
return True return True
@@ -193,7 +200,7 @@ def main():
if args.output: if args.output:
out = Path(args.output) out = Path(args.output)
else: else:
ts = datetime.now().strftime("%Y%m%d-%H%M%S") ts = datetime.now().astimezone().strftime("%Y%m%d-%H%M%S")
out = Path(f"wivrn-{ts}.pftrace") out = Path(f"wivrn-{ts}.pftrace")
if not cfg.is_file(): if not cfg.is_file():
@@ -234,9 +241,11 @@ def main():
def cleanup(): def cleanup():
run_cfg.unlink(missing_ok=True) run_cfg.unlink(missing_ok=True)
if started_probes: if started_probes:
subprocess.run([*sudo, "pkill", "-x", "traced_probes"], capture_output=True) subprocess.run(
[*sudo, "pkill", "-x", "traced_probes"], capture_output=True, check=False
)
if started_traced: if started_traced:
subprocess.run([*sudo, "pkill", "-x", "traced"], capture_output=True) subprocess.run([*sudo, "pkill", "-x", "traced"], capture_output=True, check=False)
producer_sock.unlink(missing_ok=True) producer_sock.unlink(missing_ok=True)
consumer_sock.unlink(missing_ok=True) consumer_sock.unlink(missing_ok=True)
+18 -7
View File
@@ -1,15 +1,17 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import pandas
import csv import csv
import typing import typing
import pandas
class Frame: class Frame:
def __init__(self, num): def __init__(self, num):
self.num = num self.num = num
self.events = dict() self.events = {}
self.streams = dict() self.streams = {}
self.flags = dict() self.flags = {}
self.len = 1 self.len = 1
def set(self, event, timestamp, stream): def set(self, event, timestamp, stream):
@@ -17,7 +19,7 @@ class Frame:
self.events[event] = timestamp self.events[event] = timestamp
else: else:
if stream not in self.streams: if stream not in self.streams:
self.streams[stream] = dict() self.streams[stream] = {}
if event in ("blit", "display"): if event in ("blit", "display"):
if event not in self.streams[stream]: if event not in self.streams[stream]:
self.streams[stream][event] = [timestamp] self.streams[stream][event] = [timestamp]
@@ -31,6 +33,7 @@ class Frame:
def flag(self, stream, flag): def flag(self, stream, flag):
self.flags[stream if stream != 255 else None] = flag self.flags[stream if stream != 255 else None] = flag
def read(file: typing.TextIO) -> pandas.DataFrame: def read(file: typing.TextIO) -> pandas.DataFrame:
timings = csv.reader(file) timings = csv.reader(file)
@@ -38,7 +41,6 @@ def read(file: typing.TextIO) -> pandas.DataFrame:
frames = [] frames = []
streams = 0 streams = 0
for event, frame, timestamp, stream, *extra in timings: for event, frame, timestamp, stream, *extra in timings:
if event == "event": if event == "event":
continue continue
@@ -68,7 +70,16 @@ def read(file: typing.TextIO) -> pandas.DataFrame:
frames[frame].flag(stream, x) frames[frame].flag(stream, x)
common_cols = ["wake_up", "begin", "submit"] common_cols = ["wake_up", "begin", "submit"]
stream_cols = ["encode_begin", "encode_end", "send_begin", "send_end", "receive_begin", "receive_end", "decode_begin", "decode_end"] stream_cols = [
"encode_begin",
"encode_end",
"send_begin",
"send_end",
"receive_begin",
"receive_end",
"decode_begin",
"decode_end",
]
display_cols = ["blit", "display"] display_cols = ["blit", "display"]
columns = ["frame"] + common_cols + stream_cols + display_cols columns = ["frame"] + common_cols + stream_cols + display_cols