cargo clippy

This commit is contained in:
Aleksander 2026-03-31 22:15:14 +02:00
parent 5420efa4d3
commit f44c4b78bc
55 changed files with 239 additions and 322 deletions

View File

@ -223,13 +223,12 @@ impl WayVRClient {
); );
} }
if let PacketServer::WvrStateChanged(_) = &packet { if let PacketServer::WvrStateChanged(_) = &packet
if let Some(on_signal) = &mut client.on_signal { && let Some(on_signal) = &mut client.on_signal
if (*on_signal)(&packet) { && (*on_signal)(&packet)
// Signal consumed {
return Ok(()); // Signal consumed
} return Ok(());
}
} }
// queue packet to read if it contains a serial response // queue packet to read if it contains a serial response
@ -415,7 +414,10 @@ impl WayVRClient {
Ok(()) Ok(())
} }
pub async fn fn_wlx_switch_set(client: WayVRClientMutex, set: Option<usize>) -> anyhow::Result<()> { pub async fn fn_wlx_switch_set(
client: WayVRClientMutex,
set: Option<usize>,
) -> anyhow::Result<()> {
send_only!(client, &PacketClient::WlxSwitchSet(set)); send_only!(client, &PacketClient::WlxSwitchSet(set));
Ok(()) Ok(())
} }

View File

@ -48,6 +48,7 @@ macro_rules! gen_id {
//ThingVec //ThingVec
#[allow(dead_code)] #[allow(dead_code)]
impl $container_name { impl $container_name {
#[allow(clippy::new_without_default)]
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
vec: Vec::new(), vec: Vec::new(),

View File

@ -208,8 +208,6 @@ pub struct InteractionState {
pub grabbed: Option<GrabData>, pub grabbed: Option<GrabData>,
pub clicked_id: Option<OverlayID>, pub clicked_id: Option<OverlayID>,
pub hovered_id: Option<OverlayID>, pub hovered_id: Option<OverlayID>,
pub next_push: Instant,
pub haptics: Option<f32>,
pub should_block_input: bool, pub should_block_input: bool,
pub should_block_poses: bool, pub should_block_poses: bool,
} }
@ -221,8 +219,6 @@ impl Default for InteractionState {
grabbed: None, grabbed: None,
clicked_id: None, clicked_id: None,
hovered_id: None, hovered_id: None,
next_push: Instant::now(),
haptics: None,
should_block_input: false, should_block_input: false,
should_block_poses: false, should_block_poses: false,
} }
@ -292,7 +288,6 @@ pub struct PointerHit {
pub mode: PointerMode, pub mode: PointerMode,
pub primary: bool, pub primary: bool,
pub uv: Vec2, pub uv: Vec2,
pub dist: f32,
} }
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
@ -699,7 +694,6 @@ where
mode, mode,
primary: false, primary: false,
uv, uv,
dist: hit.dist,
}; };
let result = overlay.config.backend.on_hover(app, &pointer_hit); let result = overlay.config.backend.on_hover(app, &pointer_hit);

View File

@ -28,7 +28,9 @@ pub enum BackendError {
#[error("OpenXR Error: {0:?}")] #[error("OpenXR Error: {0:?}")]
OpenXrError(#[from] ::openxr::sys::Result), OpenXrError(#[from] ::openxr::sys::Result),
#[error("Shutdown")] #[error("Shutdown")]
#[allow(dead_code)]
Shutdown, Shutdown,
#[allow(dead_code)]
#[error("Restart")] #[error("Restart")]
Restart, Restart,
#[error("Fatal: {0:?}")] #[error("Fatal: {0:?}")]

View File

@ -162,7 +162,7 @@ impl OpenVrInputSource {
// global input from overlays is enabled in SteamVR developer settings // global input from overlays is enabled in SteamVR developer settings
// (taken from https://github.com/ValveSoftware/openvr/issues/1236) // (taken from https://github.com/ValveSoftware/openvr/issues/1236)
nPriority: if should_block_input_left { nPriority: if should_block_input_left {
0x01000000 0x0100_0000
} else { } else {
0x0 0x0
}, },
@ -174,7 +174,7 @@ impl OpenVrInputSource {
ulSecondaryActionSet: 0, ulSecondaryActionSet: 0,
unPadding: 0, unPadding: 0,
nPriority: if should_block_input_right { nPriority: if should_block_input_right {
0x01000000 0x0100_0000
} else { } else {
0x0 0x0
}, },

View File

@ -176,7 +176,7 @@ impl PlayspaceMover {
} }
} }
for (_, pointer) in app.input_state.pointers.iter().enumerate() { for pointer in &app.input_state.pointers {
if pointer.now.space_reset && !pointer.before.space_reset { if pointer.now.space_reset && !pointer.before.space_reset {
self.reset_offset(chaperone_mgr, &app.input_state); self.reset_offset(chaperone_mgr, &app.input_state);
log::info!("Space reset"); log::info!("Space reset");

View File

@ -5,10 +5,10 @@ use xr::OverlaySessionCreateFlagsEXTX;
macro_rules! next_chain_insert { macro_rules! next_chain_insert {
($layer:expr, $payload:expr) => {{ ($layer:expr, $payload:expr) => {{
let payload_ptr = $payload.as_mut() as *mut _ as *mut xr::sys::BaseInStructure; let payload_ptr = std::ptr::from_mut($payload.as_mut()).cast::<xr::sys::BaseInStructure>();
let new_elem = payload_ptr.as_mut().unwrap(); let new_elem = payload_ptr.as_mut().unwrap();
let mut raw = $layer.into_raw(); let mut raw = $layer.into_raw();
new_elem.next = raw.next as _; new_elem.next = raw.next.cast();
raw.next = payload_ptr as *const _; raw.next = payload_ptr as *const _;
raw raw
}}; }};
@ -70,7 +70,7 @@ pub(super) fn init_xr() -> Result<(xr::Instance, xr::SystemId), anyhow::Error> {
log::warn!("Missing XR_KHR_composition_layer_color_scale_bias extension."); log::warn!("Missing XR_KHR_composition_layer_color_scale_bias extension.");
} }
let xr_mndx_system_buttons = "XR_MNDX_system_buttons".as_bytes().to_vec(); let xr_mndx_system_buttons = b"XR_MNDX_system_buttons".to_vec();
if available_extensions.other.contains(&xr_mndx_system_buttons) { if available_extensions.other.contains(&xr_mndx_system_buttons) {
enabled_extensions.other.push(xr_mndx_system_buttons); enabled_extensions.other.push(xr_mndx_system_buttons);
} }

View File

@ -719,7 +719,7 @@ fn suggest_bindings(instance: &xr::Instance, hands: &[&OpenXrHandSource; 3]) {
log::debug!( log::debug!(
"Bindings for {} bound successfully.", "Bindings for {} bound successfully.",
&profile.profile[22..] &profile.profile[22..]
) );
} }
} }
} }

View File

@ -370,7 +370,7 @@ pub fn openxr_run(show_by_default: bool, headless: bool) -> Result<(), BackendEr
{ {
log::trace!("{}: hidden, skip render", o.config.name); log::trace!("{}: hidden, skip render", o.config.name);
continue; continue;
}; }
if !o.data.init { if !o.data.init {
log::trace!("{}: init", o.config.name); log::trace!("{}: init", o.config.name);

View File

@ -98,7 +98,7 @@ impl Skybox {
sky: None, sky: None,
grid: None, grid: None,
grid_pose: translation_rotation_to_posef(Vec3A::ZERO, Quat::from_rotation_x(PI * -0.5)), grid_pose: translation_rotation_to_posef(Vec3A::ZERO, Quat::from_rotation_x(PI * -0.5)),
grid_color_scale_bias_khr: grid_color_scale_bias_khr, grid_color_scale_bias_khr,
}) })
} }

View File

@ -49,6 +49,7 @@ pub enum InputTask {
} }
#[cfg(feature = "openvr")] #[cfg(feature = "openvr")]
#[allow(dead_code)]
pub enum OpenVrTask { pub enum OpenVrTask {
ColorGain(ColorChannel, f32), ColorGain(ColorChannel, f32),
} }
@ -66,6 +67,7 @@ pub enum PlayspaceTask {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
#[allow(clippy::enum_variant_names)] #[allow(clippy::enum_variant_names)]
#[allow(dead_code)]
pub enum ModifyPanelCommand { pub enum ModifyPanelCommand {
SetText(String), SetText(String),
SetColor(String), SetColor(String),
@ -110,6 +112,7 @@ pub enum OverlayTask {
Drop(OverlaySelector), Drop(OverlaySelector),
} }
#[allow(dead_code)]
pub enum TaskType { pub enum TaskType {
Input(InputTask), Input(InputTask),
Overlay(OverlayTask), Overlay(OverlayTask),

View File

@ -22,7 +22,7 @@ use smithay::wayland::selection::{
wlr_data_control as selection_wlr, wlr_data_control as selection_wlr,
}; };
use smithay::wayland::shell::kde::decoration::{KdeDecorationHandler, KdeDecorationState}; use smithay::wayland::shell::kde::decoration::{KdeDecorationHandler, KdeDecorationState};
use smithay::wayland::shell::xdg::decoration::{XdgDecorationHandler, XdgDecorationState}; use smithay::wayland::shell::xdg::decoration::XdgDecorationHandler;
use smithay::wayland::shm::{ShmHandler, ShmState, with_buffer_contents}; use smithay::wayland::shm::{ShmHandler, ShmState, with_buffer_contents};
use smithay::wayland::single_pixel_buffer::get_single_pixel_buffer; use smithay::wayland::single_pixel_buffer::get_single_pixel_buffer;
use smithay::{ use smithay::{
@ -69,7 +69,6 @@ pub struct Application {
pub primary_selection_state: PrimarySelectionState, pub primary_selection_state: PrimarySelectionState,
pub ext_data_control_state: selection_ext::DataControlState, pub ext_data_control_state: selection_ext::DataControlState,
pub wlr_data_control_state: selection_wlr::DataControlState, pub wlr_data_control_state: selection_wlr::DataControlState,
pub xdg_decoration_state: XdgDecorationState,
pub kde_decoration_state: KdeDecorationState, pub kde_decoration_state: KdeDecorationState,
pub wayvr_tasks: SyncEventQueue<WayVRTask>, pub wayvr_tasks: SyncEventQueue<WayVRTask>,
pub redraw_requests: HashSet<wayland_server::backend::ObjectId>, pub redraw_requests: HashSet<wayland_server::backend::ObjectId>,
@ -78,10 +77,6 @@ pub struct Application {
} }
impl Application { impl Application {
pub fn check_redraw(&mut self, surface: &WlSurface) -> bool {
self.redraw_requests.remove(&surface.id())
}
pub fn cleanup(&mut self) { pub fn cleanup(&mut self) {
self.image_importer.cleanup(); self.image_importer.cleanup();
} }

View File

@ -65,6 +65,7 @@ macro_rules! gen_id {
}) })
} }
#[allow(dead_code)]
pub fn iter_mut( pub fn iter_mut(
&mut self, &mut self,
) -> impl Iterator<Item = ($handle_name, &mut $instance_name)> { ) -> impl Iterator<Item = ($handle_name, &mut $instance_name)> {

View File

@ -28,10 +28,7 @@ use smithay::{
}, },
shell::{ shell::{
kde::decoration::KdeDecorationState, kde::decoration::KdeDecorationState,
xdg::{ xdg::{SurfaceCachedState, ToplevelSurface, XdgShellState, XdgToplevelSurfaceData},
SurfaceCachedState, ToplevelSurface, XdgShellState, XdgToplevelSurfaceData,
decoration::XdgDecorationState,
},
}, },
shm::ShmState, shm::ShmState,
}, },
@ -43,7 +40,6 @@ use std::{
sync::Arc, sync::Arc,
time::{Duration, Instant}, time::{Duration, Instant},
}; };
use time::get_millis;
use vulkano::image::view::ImageView; use vulkano::image::view::ImageView;
use wayvr_ipc::{packet_client::PositionMode, packet_server}; use wayvr_ipc::{packet_client::PositionMode, packet_server};
use wgui::gfx::WGfx; use wgui::gfx::WGfx;
@ -68,8 +64,6 @@ use crate::{
windowing::{OverlayID, OverlaySelector}, windowing::{OverlayID, OverlaySelector},
}; };
const STR_INVALID_HANDLE_DISP: &str = "Invalid display handle";
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct WaylandEnv { pub struct WaylandEnv {
pub display_num: u32, pub display_num: u32,
@ -90,6 +84,7 @@ pub struct ProcessWayVREnv {
#[derive(Clone)] #[derive(Clone)]
pub struct ExternalProcessRequest { pub struct ExternalProcessRequest {
#[allow(dead_code)]
pub env: ProcessWayVREnv, pub env: ProcessWayVREnv,
pub client: wayland_server::Client, pub client: wayland_server::Client,
pub pid: u32, pub pid: u32,
@ -105,23 +100,7 @@ pub enum WayVRTask {
CloseWindowRequest(window::WindowHandle), CloseWindowRequest(window::WindowHandle),
} }
pub enum BlitMethod {
Dmabuf,
Software,
}
impl BlitMethod {
pub fn from_string(str: &str) -> Option<Self> {
match str {
"dmabuf" => Some(Self::Dmabuf),
"software" => Some(Self::Software),
_ => None,
}
}
}
pub struct WvrServerState { pub struct WvrServerState {
time_start: u64,
pub manager: client::WayVRCompositor, pub manager: client::WayVRCompositor,
pub wm: window::WindowManager, pub wm: window::WindowManager,
pub processes: process::ProcessVec, pub processes: process::ProcessVec,
@ -153,6 +132,9 @@ impl WvrServerState {
gfx_extras: &WGfxExtras, gfx_extras: &WGfxExtras,
signals: SyncEventQueue<WayVRSignal>, signals: SyncEventQueue<WayVRSignal>,
) -> anyhow::Result<Self> { ) -> anyhow::Result<Self> {
const fn filter_allow_any(_: &wayland_server::Client) -> bool {
true
}
log::info!("Initializing WayVR server"); log::info!("Initializing WayVR server");
let display: wayland_server::Display<Application> = wayland_server::Display::new()?; let display: wayland_server::Display<Application> = wayland_server::Display::new()?;
let dh = display.handle(); let dh = display.handle();
@ -164,9 +146,6 @@ impl WvrServerState {
let primary_selection_state = PrimarySelectionState::new::<Application>(&dh); let primary_selection_state = PrimarySelectionState::new::<Application>(&dh);
let mut seat = seat_state.new_wl_seat(&dh, "wayvr"); let mut seat = seat_state.new_wl_seat(&dh, "wayvr");
fn filter_allow_any(_: &wayland_server::Client) -> bool {
true
}
let ext_data_control_state = selection_ext::DataControlState::new::<Application, _>( let ext_data_control_state = selection_ext::DataControlState::new::<Application, _>(
&dh, &dh,
Some(&primary_selection_state), Some(&primary_selection_state),
@ -178,7 +157,6 @@ impl WvrServerState {
filter_allow_any, filter_allow_any,
); );
let xdg_decoration_state = XdgDecorationState::new::<Application>(&dh);
let kde_decoration_state = let kde_decoration_state =
KdeDecorationState::new::<Application>(&dh, kde_decoration::Mode::Server); KdeDecorationState::new::<Application>(&dh, kde_decoration::Mode::Server);
@ -255,7 +233,6 @@ impl WvrServerState {
primary_selection_state, primary_selection_state,
wlr_data_control_state, wlr_data_control_state,
ext_data_control_state, ext_data_control_state,
xdg_decoration_state,
kde_decoration_state, kde_decoration_state,
wayvr_tasks: tasks.clone(), wayvr_tasks: tasks.clone(),
redraw_requests: HashSet::new(), redraw_requests: HashSet::new(),
@ -263,10 +240,7 @@ impl WvrServerState {
popup_manager: PopupManager::default(), popup_manager: PopupManager::default(),
}; };
let time_start = get_millis();
Ok(Self { Ok(Self {
time_start,
manager: client::WayVRCompositor::new(state, display, seat_keyboard, seat_pointer)?, manager: client::WayVRCompositor::new(state, display, seat_keyboard, seat_pointer)?,
processes: ProcessVec::new(), processes: ProcessVec::new(),
wm: window::WindowManager::new(), wm: window::WindowManager::new(),
@ -341,8 +315,8 @@ impl WvrServerState {
let (min_size, max_size) = with_states(toplevel.wl_surface(), |state| { let (min_size, max_size) = with_states(toplevel.wl_surface(), |state| {
let mut guard = state.cached_state.get::<SurfaceCachedState>(); let mut guard = state.cached_state.get::<SurfaceCachedState>();
let mut min_size = guard.current().min_size; let (mut min_size, mut max_size) =
let mut max_size = guard.current().max_size; { (guard.current().min_size, guard.current().max_size) };
if min_size.is_empty() { if min_size.is_empty() {
min_size = Size::new(1, 1); min_size = Size::new(1, 1);
@ -365,7 +339,7 @@ impl WvrServerState {
size.clamp(min_size, max_size), size.clamp(min_size, max_size),
p.pos_mode, p.pos_mode,
Some(p.app_name.clone()), Some(p.app_name.clone()),
p.icon.as_ref().cloned(), p.icon.clone(),
p.exec_path.ends_with("cage"), p.exec_path.ends_with("cage"),
) )
} }
@ -396,14 +370,13 @@ impl WvrServerState {
let mut needs_title = true; let mut needs_title = true;
let (xdg_title, app_id): (Option<String>, Option<String>) = let (xdg_title, app_id): (Option<String>, Option<String>) =
with_states(toplevel.wl_surface(), |states| { with_states(toplevel.wl_surface(), |states| {
states states.data_map.get::<XdgToplevelSurfaceData>().map_or(
.data_map (None, None),
.get::<XdgToplevelSurfaceData>() |t| {
.map(|t| {
let t = t.lock().unwrap(); let t = t.lock().unwrap();
(t.title.clone(), t.app_id.clone()) (t.title.clone(), t.app_id.clone())
}) },
.unwrap_or((None, None)) )
}); });
if let Some(xdg_title) = xdg_title { if let Some(xdg_title) = xdg_title {
needs_title = false; needs_title = false;
@ -429,7 +402,7 @@ impl WvrServerState {
// Fall back to identicon // Fall back to identicon
let icon = match icon { let icon = match icon {
Some(icon) => icon, Some(icon) => icon,
None => DesktopFinder::create_icon(&*title)?.into(), None => DesktopFinder::create_icon(&title)?.into(),
}; };
app.tasks.enqueue(TaskType::Overlay(OverlayTask::Create( app.tasks.enqueue(TaskType::Overlay(OverlayTask::Create(
@ -573,7 +546,7 @@ impl WvrServerState {
continue; continue;
} }
if let Some(oid) = self.window_to_overlay.get(&hnd).cloned() { if let Some(oid) = self.window_to_overlay.get(&hnd).copied() {
tasks.enqueue(TaskType::Overlay(OverlayTask::Drop(OverlaySelector::Id( tasks.enqueue(TaskType::Overlay(OverlayTask::Drop(OverlaySelector::Id(
oid, oid,
)))); ))));
@ -591,7 +564,7 @@ impl WvrServerState {
} }
pub fn get_overlay_id(&self, window: window::WindowHandle) -> Option<OverlayID> { pub fn get_overlay_id(&self, window: window::WindowHandle) -> Option<OverlayID> {
self.window_to_overlay.get(&window).cloned() self.window_to_overlay.get(&window).copied()
} }
pub fn send_mouse_move(&mut self, handle: window::WindowHandle, x: u32, y: u32) { pub fn send_mouse_move(&mut self, handle: window::WindowHandle, x: u32, y: u32) {
@ -653,32 +626,12 @@ impl WvrServerState {
self.cur_modifiers = modifiers; self.cur_modifiers = modifiers;
} }
// Check if process with given arguments already exists
pub fn process_query(
&self,
exec_path: &str,
args: &[&str],
_env: &[(&str, &str)],
) -> Option<process::ProcessHandle> {
for (idx, cell) in self.processes.vec.iter().enumerate() {
if let Some(cell) = &cell
&& let process::Process::Managed(process) = &cell.obj
{
if process.exec_path != exec_path || process.args != args {
continue;
}
return Some(process::ProcessVec::get_handle(cell, idx));
}
}
None
}
pub fn add_external_process(&mut self, pid: u32) -> process::ProcessHandle { pub fn add_external_process(&mut self, pid: u32) -> process::ProcessHandle {
self.processes self.processes
.add(process::Process::External(process::ExternalProcess { pid })) .add(process::Process::External(process::ExternalProcess { pid }))
} }
#[allow(clippy::too_many_arguments)]
pub fn spawn_process( pub fn spawn_process(
&mut self, &mut self,
app_name: &str, app_name: &str,
@ -756,16 +709,12 @@ fn generate_auth_key() -> String {
uuid.to_string() uuid.to_string()
} }
pub struct SpawnProcessResult {
pub auth_key: String,
pub child: std::process::Child,
}
struct SurfaceBufWithImageContainer { struct SurfaceBufWithImageContainer {
inner: RefCell<SurfaceBufWithImage>, inner: RefCell<SurfaceBufWithImage>,
} }
#[derive(Clone)] #[derive(Clone)]
#[allow(dead_code)]
pub struct SurfaceBufWithImage { pub struct SurfaceBufWithImage {
pub image: Arc<ImageView>, pub image: Arc<ImageView>,
pub transform: Transform, pub transform: Transform,

View File

@ -27,6 +27,7 @@ pub struct ExternalProcess {
} }
#[derive(Debug)] #[derive(Debug)]
#[allow(clippy::large_enum_variant)]
pub enum Process { pub enum Process {
Managed(WayVRProcess), // Process spawned by WayVR Managed(WayVRProcess), // Process spawned by WayVR
External(ExternalProcess), // External process not directly controlled by us External(ExternalProcess), // External process not directly controlled by us
@ -58,11 +59,12 @@ impl Process {
} }
} }
#[allow(dead_code)]
pub fn get_name(&self) -> String { pub fn get_name(&self) -> String {
match self { match self {
Self::Managed(p) => p Self::Managed(p) => p
.get_name() .get_name()
.or_else(|| p.exec_path.split('/').last().map(String::from)) .or_else(|| p.exec_path.split('/').next_back().map(String::from))
.unwrap_or_else(|| String::from("unknown")), .unwrap_or_else(|| String::from("unknown")),
Self::External(p) => p.get_name().unwrap_or_else(|| String::from("unknown")), Self::External(p) => p.get_name().unwrap_or_else(|| String::from("unknown")),
} }

View File

@ -22,9 +22,6 @@ const FILES: [&str; 1] = ["keyboard.yaml"];
#[repr(usize)] #[repr(usize)]
pub enum ConfigType { pub enum ConfigType {
Keyboard, Keyboard,
Watch,
Settings,
Anchor,
} }
pub fn load_known_yaml<T>(config_type: ConfigType) -> T pub fn load_known_yaml<T>(config_type: ConfigType) -> T

View File

@ -352,16 +352,12 @@ pub fn export_dmabuf_image(
Ok(ExportedDmabufImage { Ok(ExportedDmabufImage {
view: ImageView::new_default(image)?, view: ImageView::new_default(image)?,
fd, fd,
modifier: DrmModifier::from(modifier), modifier,
offset: layout.offset as _, offset: layout.offset as _,
stride: layout.row_pitch as _, stride: layout.row_pitch as _,
}) })
} }
fn align_to(value: u64, alignment: u64) -> u64 {
((value + alignment - 1) / alignment) * alignment
}
pub(super) fn get_drm_formats(device: Arc<Device>) -> Vec<DrmFormat> { pub(super) fn get_drm_formats(device: Arc<Device>) -> Vec<DrmFormat> {
let possible_formats = [ let possible_formats = [
DrmFourcc::Abgr8888, DrmFourcc::Abgr8888,

View File

@ -28,24 +28,20 @@ use {ash::vk, std::os::raw::c_void};
use vulkano::{ use vulkano::{
self, VulkanObject, self, VulkanObject,
buffer::{Buffer, BufferContents, IndexBuffer, Subbuffer}, buffer::{Buffer, BufferContents, Subbuffer},
device::{ device::{
DeviceCreateInfo, DeviceExtensions, DeviceFeatures, Queue, QueueCreateInfo, QueueFlags, DeviceCreateInfo, DeviceExtensions, DeviceFeatures, Queue, QueueCreateInfo, QueueFlags,
physical::{PhysicalDevice, PhysicalDeviceType}, physical::{PhysicalDevice, PhysicalDeviceType},
}, },
format::Format, format::Format,
instance::{Instance, InstanceCreateInfo, InstanceExtensions}, instance::{Instance, InstanceCreateInfo, InstanceExtensions},
pipeline::graphics::{ pipeline::graphics::vertex_input::Vertex,
color_blend::{AttachmentBlend, BlendFactor, BlendOp},
vertex_input::Vertex,
},
shader::ShaderModule, shader::ShaderModule,
}; };
use dmabuf::get_drm_formats; use dmabuf::get_drm_formats;
pub type Vert2Buf = Subbuffer<[Vert2Uv]>; pub type Vert2Buf = Subbuffer<[Vert2Uv]>;
pub type IndexBuf = IndexBuffer;
#[repr(C)] #[repr(C)]
#[derive(BufferContents, Vertex, Copy, Clone, Debug)] #[derive(BufferContents, Vertex, Copy, Clone, Debug)]
@ -56,17 +52,6 @@ pub struct Vert2Uv {
pub in_uv: [f32; 2], pub in_uv: [f32; 2],
} }
pub const INDICES: [u16; 6] = [2, 1, 0, 1, 2, 3];
pub const BLEND_ALPHA: AttachmentBlend = AttachmentBlend {
src_color_blend_factor: BlendFactor::SrcAlpha,
dst_color_blend_factor: BlendFactor::OneMinusSrcAlpha,
color_blend_op: BlendOp::Add,
src_alpha_blend_factor: BlendFactor::One,
dst_alpha_blend_factor: BlendFactor::One,
alpha_blend_op: BlendOp::Max,
};
pub struct WGfxExtras { pub struct WGfxExtras {
pub shaders: HashMap<&'static str, Arc<ShaderModule>>, pub shaders: HashMap<&'static str, Arc<ShaderModule>>,
pub drm_formats: Arc<[DrmFormat]>, pub drm_formats: Arc<[DrmFormat]>,
@ -711,6 +696,7 @@ impl GpuFutures {
pub trait ExtentExt { pub trait ExtentExt {
fn extent_f32(&self) -> [f32; 2]; fn extent_f32(&self) -> [f32; 2];
#[allow(dead_code)]
fn extent_vec2(&self) -> Vec2; fn extent_vec2(&self) -> Vec2;
fn extent_u32arr(&self) -> [u32; 2]; fn extent_u32arr(&self) -> [u32; 2];
} }

View File

@ -186,7 +186,6 @@ fn short_duration(btn: &ComponentButton, app: &AppState) -> bool {
btn.get_time_since_last_pressed().as_secs_f32() < app.session.config.long_press_duration btn.get_time_since_last_pressed().as_secs_f32() < app.session.config.long_press_duration
} }
#[allow(clippy::too_many_lines)]
pub(super) fn setup_custom_button<S: 'static>( pub(super) fn setup_custom_button<S: 'static>(
layout: &mut Layout, layout: &mut Layout,
parser_state: &ParserState, parser_state: &ParserState,
@ -222,7 +221,8 @@ pub(super) fn setup_custom_button<S: 'static>(
// pass attribs with key `_context_{name}` to the context_menu template // pass attribs with key `_context_{name}` to the context_menu template
let mut template_params = HashMap::new(); let mut template_params = HashMap::new();
for AttribPair { attrib, value } in &attribs.pairs { for AttribPair { attrib, value } in &attribs.pairs {
const PREFIX: &'static str = "_context_"; const PREFIX: &str = "_context_";
#[allow(clippy::manual_strip)]
if attrib.starts_with(PREFIX) { if attrib.starts_with(PREFIX) {
template_params.insert(attrib[PREFIX.len()..].into(), value.clone()); template_params.insert(attrib[PREFIX.len()..].into(), value.clone());
} }
@ -348,10 +348,10 @@ pub(super) fn setup_custom_button<S: 'static>(
} }
"::OverlayReset" => { "::OverlayReset" => {
let arg: Arc<str> = args.collect::<Vec<_>>().join(" ").into(); let arg: Arc<str> = args.collect::<Vec<_>>().join(" ").into();
if arg.len() < 1 { if arg.is_empty() {
log_cmd_missing_arg(parser_state, TAG, name, command); log_cmd_missing_arg(parser_state, TAG, name, command);
return; return;
}; }
Box::new(move |_common, data, app, _| { Box::new(move |_common, data, app, _| {
if !test_button(data) || !test_duration(&button, app) { if !test_button(data) || !test_duration(&button, app) {
@ -367,10 +367,10 @@ pub(super) fn setup_custom_button<S: 'static>(
} }
"::OverlayToggle" => { "::OverlayToggle" => {
let arg: Arc<str> = args.collect::<Vec<_>>().join(" ").into(); let arg: Arc<str> = args.collect::<Vec<_>>().join(" ").into();
if arg.len() < 1 { if arg.is_empty() {
log_cmd_missing_arg(parser_state, TAG, name, command); log_cmd_missing_arg(parser_state, TAG, name, command);
return; return;
}; }
Box::new(move |_common, data, app, _| { Box::new(move |_common, data, app, _| {
if !test_button(data) || !test_duration(&button, app) { if !test_button(data) || !test_duration(&button, app) {
@ -387,10 +387,10 @@ pub(super) fn setup_custom_button<S: 'static>(
} }
"::OverlayDrop" => { "::OverlayDrop" => {
let arg: Arc<str> = args.collect::<Vec<_>>().join(" ").into(); let arg: Arc<str> = args.collect::<Vec<_>>().join(" ").into();
if arg.len() < 1 { if arg.is_empty() {
log_cmd_missing_arg(parser_state, TAG, name, command); log_cmd_missing_arg(parser_state, TAG, name, command);
return; return;
}; }
Box::new(move |_common, data, app, _| { Box::new(move |_common, data, app, _| {
if !test_button(data) || !test_duration(&button, app) { if !test_button(data) || !test_duration(&button, app) {
@ -422,10 +422,10 @@ pub(super) fn setup_custom_button<S: 'static>(
}), }),
"::CustomOverlayReload" => { "::CustomOverlayReload" => {
let arg: Arc<str> = args.collect::<Vec<_>>().join(" ").into(); let arg: Arc<str> = args.collect::<Vec<_>>().join(" ").into();
if arg.len() < 1 { if arg.is_empty() {
log_cmd_missing_arg(parser_state, TAG, name, command); log_cmd_missing_arg(parser_state, TAG, name, command);
return; return;
}; }
Box::new(move |_common, data, app, _| { Box::new(move |_common, data, app, _| {
if !test_button(data) || !test_duration(&button, app) { if !test_button(data) || !test_duration(&button, app) {
@ -460,10 +460,10 @@ pub(super) fn setup_custom_button<S: 'static>(
} }
"::WvrOverlayCloseWindow" => { "::WvrOverlayCloseWindow" => {
let arg: Arc<str> = args.collect::<Vec<_>>().join(" ").into(); let arg: Arc<str> = args.collect::<Vec<_>>().join(" ").into();
if arg.len() < 1 { if arg.is_empty() {
log_cmd_missing_arg(parser_state, TAG, name, command); log_cmd_missing_arg(parser_state, TAG, name, command);
return; return;
}; }
Box::new(move |_common, data, app, _| { Box::new(move |_common, data, app, _| {
if !test_button(data) || !test_duration(&button, app) { if !test_button(data) || !test_duration(&button, app) {
return Ok(EventResult::Pass); return Ok(EventResult::Pass);
@ -486,10 +486,10 @@ pub(super) fn setup_custom_button<S: 'static>(
} }
"::WvrOverlayKillProcess" | "::WvrOverlayTermProcess" => { "::WvrOverlayKillProcess" | "::WvrOverlayTermProcess" => {
let arg: Arc<str> = args.collect::<Vec<_>>().join(" ").into(); let arg: Arc<str> = args.collect::<Vec<_>>().join(" ").into();
if arg.len() < 1 { if arg.is_empty() {
log_cmd_missing_arg(parser_state, TAG, name, command); log_cmd_missing_arg(parser_state, TAG, name, command);
return; return;
}; }
let signal = if command == "::WvrOverlayKillProcess" { let signal = if command == "::WvrOverlayKillProcess" {
KillSignal::Kill KillSignal::Kill
@ -685,7 +685,6 @@ pub(super) fn setup_custom_button<S: 'static>(
button: button.clone(), button: button.clone(),
exec: args.fold(String::new(), |c, n| c + " " + n), exec: args.fold(String::new(), |c, n| c + " " + n),
mut_state: RefCell::new(ShellButtonMutableState::default()), mut_state: RefCell::new(ShellButtonMutableState::default()),
carry_over: RefCell::new(None),
}); });
layout.add_event_listener::<AppState, S>( layout.add_event_listener::<AppState, S>(
@ -725,7 +724,6 @@ pub(super) fn setup_custom_button<S: 'static>(
if let Ok(osc_arg) = parse_osc_value(arg).inspect_err(|e| { if let Ok(osc_arg) = parse_osc_value(arg).inspect_err(|e| {
let msg = format!("Could not parse OSC value \"{arg}\": {e:?}"); let msg = format!("Could not parse OSC value \"{arg}\": {e:?}");
log_cmd_invalid_arg(parser_state, TAG, name, command, &msg); log_cmd_invalid_arg(parser_state, TAG, name, command, &msg);
return;
}) { }) {
osc_args.push(osc_arg); osc_args.push(osc_arg);
} }
@ -776,10 +774,10 @@ struct ShellButtonMutableState {
} }
struct ShellButtonState { struct ShellButtonState {
#[allow(dead_code)] // preserve lifetime of this button component
button: Rc<ComponentButton>, button: Rc<ComponentButton>,
exec: String, exec: String,
mut_state: RefCell<ShellButtonMutableState>, mut_state: RefCell<ShellButtonMutableState>,
carry_over: RefCell<Option<String>>,
} }
fn shell_on_action(state: &ShellButtonState) -> anyhow::Result<()> { fn shell_on_action(state: &ShellButtonState) -> anyhow::Result<()> {

View File

@ -16,6 +16,7 @@ use crate::{
pub struct DeviceList; pub struct DeviceList;
impl DeviceList { impl DeviceList {
#[allow(clippy::unused_self)]
pub fn on_notify( pub fn on_notify(
&mut self, &mut self,
app: &AppState, app: &AppState,
@ -25,6 +26,7 @@ impl DeviceList {
doc_params: &ParseDocumentParams, doc_params: &ParseDocumentParams,
) -> anyhow::Result<bool> { ) -> anyhow::Result<bool> {
let mut elements_changed = false; let mut elements_changed = false;
#[allow(clippy::single_match)]
match event_data { match event_data {
OverlayEventData::DevicesChanged => { OverlayEventData::DevicesChanged => {
let devices_root = parser_state let devices_root = parser_state
@ -48,7 +50,7 @@ impl DeviceList {
params.insert("idx".into(), i.to_string().into()); params.insert("idx".into(), i.to_string().into());
parser_state.instantiate_template( parser_state.instantiate_template(
&doc_params, doc_params,
template, template,
layout, layout,
devices_root, devices_root,

View File

@ -261,7 +261,7 @@ fn timer_on_tick(
data: &mut event::CallbackData, data: &mut event::CallbackData,
) { ) {
let duration = Local::now() let duration = Local::now()
.signed_duration_since(&state.start) .signed_duration_since(state.start)
.num_seconds(); .num_seconds();
let time = &state let time = &state
@ -271,7 +271,7 @@ fn timer_on_tick(
.replace("%h", &format!("{:02}", ((duration / 60) / 60))); .replace("%h", &format!("{:02}", ((duration / 60) / 60)));
let label = data.obj.get_as_mut::<WidgetLabel>().unwrap(); let label = data.obj.get_as_mut::<WidgetLabel>().unwrap();
label.set_text(common, Translation::from_raw_text(&time)); label.set_text(common, Translation::from_raw_text(time));
} }
fn ipd_on_tick( fn ipd_on_tick(

View File

@ -11,7 +11,6 @@ use wgui::{
button::ComponentButton, checkbox::ComponentCheckbox, radio_group::ComponentRadioGroup, button::ComponentButton, checkbox::ComponentCheckbox, radio_group::ComponentRadioGroup,
slider::ComponentSlider, slider::ComponentSlider,
}, },
drawing,
event::{ event::{
CallbackDataCommon, Event as WguiEvent, EventAlterables, EventCallback, EventListenerID, CallbackDataCommon, Event as WguiEvent, EventAlterables, EventCallback, EventListenerID,
EventListenerKind, InternalStateChangeEvent, MouseButtonEvent, MouseButtonIndex, EventListenerKind, InternalStateChangeEvent, MouseButtonEvent, MouseButtonIndex,
@ -55,8 +54,6 @@ pub mod set_list;
const DEFAULT_MAX_SIZE: f32 = 2048.0; const DEFAULT_MAX_SIZE: f32 = 2048.0;
const COLOR_ERR: drawing::Color = drawing::Color::new(1., 0., 1., 1.);
pub type OnNotifyFunc<S> = pub type OnNotifyFunc<S> =
Box<dyn Fn(&mut GuiPanel<S>, &mut AppState, OverlayEventData) -> anyhow::Result<()>>; Box<dyn Fn(&mut GuiPanel<S>, &mut AppState, OverlayEventData) -> anyhow::Result<()>>;
@ -449,7 +446,7 @@ impl<S: 'static> OverlayBackend for GuiPanel<S> {
self.interaction_transform self.interaction_transform
} }
fn get_attrib(&self, attrib: BackendAttrib) -> Option<BackendAttribValue> { fn get_attrib(&self, attrib: BackendAttrib) -> Option<BackendAttribValue> {
self.extra_attribs.get(&attrib).cloned() self.extra_attribs.get(attrib).cloned()
} }
fn set_attrib(&mut self, _app: &mut AppState, _value: BackendAttribValue) -> bool { fn set_attrib(&mut self, _app: &mut AppState, _value: BackendAttribValue) -> bool {
false false
@ -459,22 +456,22 @@ impl<S: 'static> OverlayBackend for GuiPanel<S> {
fn log_missing_attrib(parser_state: &ParserState, tag_name: &str, attrib: &str) { fn log_missing_attrib(parser_state: &ParserState, tag_name: &str, attrib: &str) {
log::warn!( log::warn!(
"{:?}: <{tag_name}> is missing \"{attrib}\"", "{:?}: <{tag_name}> is missing \"{attrib}\"",
parser_state.path.get_path_buf() parser_state.path.get_path_buf().display()
) );
} }
fn log_invalid_attrib(parser_state: &ParserState, tag_name: &str, attrib: &str, value: &str) { fn log_invalid_attrib(parser_state: &ParserState, tag_name: &str, attrib: &str, value: &str) {
log::warn!( log::warn!(
"{:?}: <{tag_name}> value for \"{attrib}\" is invalid: {value}", "{:?}: <{tag_name}> value for \"{attrib}\" is invalid: {value}",
parser_state.path.get_path_buf() parser_state.path.get_path_buf().display()
) );
} }
fn log_cmd_missing_arg(parser_state: &ParserState, tag_name: &str, attrib: &str, command: &str) { fn log_cmd_missing_arg(parser_state: &ParserState, tag_name: &str, attrib: &str, command: &str) {
log::warn!( log::warn!(
"{:?}: <{tag_name}> \"{attrib}\": \"{command}\" has missing arguments", "{:?}: <{tag_name}> \"{attrib}\": \"{command}\" has missing arguments",
parser_state.path.get_path_buf() parser_state.path.get_path_buf().display()
) );
} }
fn log_cmd_invalid_arg( fn log_cmd_invalid_arg(
@ -486,8 +483,8 @@ fn log_cmd_invalid_arg(
) { ) {
log::warn!( log::warn!(
"{:?}: <{tag_name}> \"{attrib}\": \"{command}\" has invalid argument: {arg}", "{:?}: <{tag_name}> \"{attrib}\": \"{command}\" has invalid argument: {arg}",
parser_state.path.get_path_buf() parser_state.path.get_path_buf().display()
) );
} }
pub fn apply_custom_command<T>( pub fn apply_custom_command<T>(
@ -600,7 +597,7 @@ pub fn apply_custom_command<T>(
.parser_state .parser_state
.fetch_component_as::<ComponentRadioGroup>(element) .fetch_component_as::<ComponentRadioGroup>(element)
{ {
radio.set_value(&mut com, &value_str)?; radio.set_value(&mut com, value_str)?;
} }
} }
ModifyPanelCommand::GetValue => todo!(), ModifyPanelCommand::GetValue => todo!(),

View File

@ -99,7 +99,7 @@ impl OverlayList {
if meta.visible { if meta.visible {
let mut com = CallbackDataCommon { let mut com = CallbackDataCommon {
alterables: alterables, alterables,
state: &layout.state, state: &layout.state,
}; };
overlay_button.set_sticky_state(&mut com, true); overlay_button.set_sticky_state(&mut com, true);
@ -116,18 +116,13 @@ impl OverlayList {
params.insert("idx".into(), i.to_string().into()); params.insert("idx".into(), i.to_string().into());
params.insert("name".into(), meta.name.as_ref().into()); params.insert("name".into(), meta.name.as_ref().into());
parser_state.instantiate_template( parser_state
&doc_params, .instantiate_template(doc_params, template, layout, root, params)?;
template,
layout,
root,
params,
)?;
let overlay_button = parser_state let overlay_button = parser_state
.fetch_component_as::<ComponentButton>(&format!("overlay_{i}"))?; .fetch_component_as::<ComponentButton>(&format!("overlay_{i}"))?;
if meta.visible { if meta.visible {
let mut com = CallbackDataCommon { let mut com = CallbackDataCommon {
alterables: alterables, alterables,
state: &layout.state, state: &layout.state,
}; };
overlay_button.set_sticky_state(&mut com, true); overlay_button.set_sticky_state(&mut com, true);
@ -138,7 +133,7 @@ impl OverlayList {
} }
OverlayEventData::VisibleOverlaysChanged(overlays) => { OverlayEventData::VisibleOverlaysChanged(overlays) => {
let mut com = CallbackDataCommon { let mut com = CallbackDataCommon {
alterables: alterables, alterables,
state: &layout.state, state: &layout.state,
}; };
let mut overlay_buttons = self.overlay_buttons.clone(); let mut overlay_buttons = self.overlay_buttons.clone();

View File

@ -18,10 +18,6 @@ pub struct SetList {
} }
impl SetList { impl SetList {
pub fn num_sets(&self) -> usize {
self.set_buttons.len()
}
pub fn on_notify( pub fn on_notify(
&mut self, &mut self,
layout: &mut Layout, layout: &mut Layout,
@ -34,7 +30,7 @@ impl SetList {
match event_data { match event_data {
OverlayEventData::ActiveSetChanged(current_set) => { OverlayEventData::ActiveSetChanged(current_set) => {
let mut com = CallbackDataCommon { let mut com = CallbackDataCommon {
alterables: alterables, alterables,
state: &layout.state, state: &layout.state,
}; };
if let Some(old_set) = self.current_set.take() if let Some(old_set) = self.current_set.take()
@ -64,7 +60,7 @@ impl SetList {
parser_state.fetch_component_as::<ComponentButton>(&format!("set_{i}"))?; parser_state.fetch_component_as::<ComponentButton>(&format!("set_{i}"))?;
if self.current_set == Some(i) { if self.current_set == Some(i) {
let mut com = CallbackDataCommon { let mut com = CallbackDataCommon {
alterables: alterables, alterables,
state: &layout.state, state: &layout.state,
}; };
set_button.set_sticky_state(&mut com, true); set_button.set_sticky_state(&mut com, true);

View File

@ -9,7 +9,7 @@ use crate::{
}, },
ipc::signal::WayVRSignal, ipc::signal::WayVRSignal,
state::AppState, state::AppState,
windowing::{OverlaySelector, manager::OverlayWindowManager}, windowing::manager::OverlayWindowManager,
}; };
fn process_tick_tasks( fn process_tick_tasks(
@ -54,12 +54,6 @@ where
app.tasks app.tasks
.enqueue(TaskType::Overlay(OverlayTask::SwitchSet(set))); .enqueue(TaskType::Overlay(OverlayTask::SwitchSet(set)));
} }
WayVRSignal::DropOverlay(overlay_id) => {
app.tasks
.enqueue(TaskType::Overlay(OverlayTask::Drop(OverlaySelector::Id(
overlay_id,
))));
}
WayVRSignal::CustomTask(custom_task) => { WayVRSignal::CustomTask(custom_task) => {
app.tasks app.tasks
.enqueue(TaskType::Overlay(OverlayTask::ModifyPanel(custom_task))); .enqueue(TaskType::Overlay(OverlayTask::ModifyPanel(custom_task)));

View File

@ -15,6 +15,7 @@ use wayvr_ipc::{
packet_server::{self, PacketServer, WlxInputStatePointer}, packet_server::{self, PacketServer, WlxInputStatePointer},
}; };
#[allow(dead_code)] // not used for now, wayvr accepts any client
pub struct AuthInfo { pub struct AuthInfo {
pub client_name: String, pub client_name: String,
pub protocol_version: u32, // client protocol version pub protocol_version: u32, // client protocol version
@ -75,6 +76,7 @@ fn read_payload(conn: &mut local_socket::Stream, size: u32) -> Option<Payload> {
pub struct TickParams<'a> { pub struct TickParams<'a> {
pub wvr_server: &'a mut WvrServerState, pub wvr_server: &'a mut WvrServerState,
#[allow(dead_code)]
pub tasks: &'a mut Vec<wayvr::TickTask>, pub tasks: &'a mut Vec<wayvr::TickTask>,
pub signals: &'a SyncEventQueue<WayVRSignal>, pub signals: &'a SyncEventQueue<WayVRSignal>,
pub input_state: &'a InputState, pub input_state: &'a InputState,

View File

@ -2,7 +2,6 @@
pub enum WayVRSignal { pub enum WayVRSignal {
BroadcastStateChanged(wayvr_ipc::packet_server::WvrStateChanged), BroadcastStateChanged(wayvr_ipc::packet_server::WvrStateChanged),
DeviceHaptics(usize, crate::backend::input::Haptics), DeviceHaptics(usize, crate::backend::input::Haptics),
DropOverlay(crate::windowing::OverlayID),
SwitchSet(Option<usize>), SwitchSet(Option<usize>),
ShowHide, ShowHide,
CustomTask(crate::backend::task::ModifyPanelTask), CustomTask(crate::backend::task::ModifyPanelTask),

View File

@ -1,21 +1,22 @@
#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)] #![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]
#![allow( #![allow(
dead_code,
clippy::suboptimal_flops,
clippy::default_trait_access,
clippy::cast_precision_loss,
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
clippy::cast_possible_wrap,
clippy::cast_lossless,
clippy::match_wildcard_for_single_variants,
clippy::doc_markdown,
clippy::struct_excessive_bools,
clippy::needless_pass_by_value,
clippy::needless_pass_by_ref_mut,
clippy::multiple_crate_versions,
clippy::cargo_common_metadata, clippy::cargo_common_metadata,
clippy::option_if_let_else clippy::cast_lossless,
clippy::cast_possible_truncation,
clippy::cast_possible_wrap,
clippy::cast_precision_loss,
clippy::cast_sign_loss,
clippy::default_trait_access,
clippy::doc_markdown,
clippy::match_wildcard_for_single_variants,
clippy::multiple_crate_versions,
clippy::needless_pass_by_ref_mut,
clippy::needless_pass_by_value,
clippy::option_if_let_else,
clippy::struct_excessive_bools,
clippy::suboptimal_flops,
clippy::too_many_lines,
clippy::use_self
)] )]
mod app_misc; mod app_misc;
mod backend; mod backend;
@ -132,7 +133,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
Some(XrBackend::OpenXR) => args.push("--openxr"), Some(XrBackend::OpenXR) => args.push("--openxr"),
Some(XrBackend::OpenVR) => args.push("--openvr"), Some(XrBackend::OpenVR) => args.push("--openvr"),
_ => {} _ => {}
}; }
let _ = Command::new(exe).args(args).spawn(); let _ = Command::new(exe).args(args).spawn();
} }

View File

@ -33,7 +33,7 @@ pub fn create_custom(app: &mut AppState, name: Arc<str>) -> Option<OverlayWindow
.ok()?; .ok()?;
if let Some(icon) = panel.parser_state.data.var_map.get("_panel_icon") { if let Some(icon) = panel.parser_state.data.var_map.get("_panel_icon") {
let icon = expand_env_vars(&icon); let icon = expand_env_vars(icon);
panel panel
.extra_attribs .extra_attribs
.insert(BackendAttrib::Icon, BackendAttribValue::Icon(icon.into())); .insert(BackendAttrib::Icon, BackendAttribValue::Icon(icon.into()));

View File

@ -304,7 +304,7 @@ pub fn create_dash_frontend(app: &mut AppState) -> anyhow::Result<OverlayWindowC
pub struct DashInterfaceLive {} pub struct DashInterfaceLive {}
impl DashInterfaceLive { impl DashInterfaceLive {
pub fn new() -> Self { pub const fn new() -> Self {
Self {} Self {}
} }
} }
@ -411,9 +411,10 @@ impl DashInterface<AppState> for DashInterfaceLive {
app.tasks app.tasks
.enqueue(TaskType::Overlay(OverlayTask::ToggleOverlay( .enqueue(TaskType::Overlay(OverlayTask::ToggleOverlay(
OverlaySelector::Id(oid), OverlaySelector::Id(oid),
match visible { if visible {
true => ToggleMode::EnsureOn, ToggleMode::EnsureOn
false => ToggleMode::EnsureOff, } else {
ToggleMode::EnsureOff
}, },
))); )));
Ok(()) Ok(())
@ -499,7 +500,7 @@ impl DashInterface<AppState> for DashInterfaceLive {
#[cfg(feature = "openxr")] #[cfg(feature = "openxr")]
fn monado_client_focus(&mut self, app: &mut AppState, name: &str) -> anyhow::Result<()> { fn monado_client_focus(&mut self, app: &mut AppState, name: &str) -> anyhow::Result<()> {
let Some(monado) = &mut app.monado else { let Some(monado) = &mut app.monado else {
return Ok(()); // no monado avoilable return Ok(()); // no monado available
}; };
monado_client_focus(monado, name) monado_client_focus(monado, name)

View File

@ -65,6 +65,7 @@ type EditModeWrapPanel = GuiPanel<EditModeState>;
#[derive(Default)] #[derive(Default)]
pub struct EditWrapperManager { pub struct EditWrapperManager {
#[allow(dead_code)]
edit_mode: bool, edit_mode: bool,
panel_pool: Vec<EditModeWrapPanel>, panel_pool: Vec<EditModeWrapPanel>,
} }
@ -371,9 +372,9 @@ fn make_edit_panel(app: &mut AppState) -> anyhow::Result<EditModeWrapPanel> {
let sel = OverlaySelector::Id(*state.id.borrow()); let sel = OverlaySelector::Id(*state.id.borrow());
app.tasks.enqueue(TaskType::Overlay(OverlayTask::Modify( app.tasks.enqueue(TaskType::Overlay(OverlayTask::Modify(
sel, sel,
Box::new(move |_app, owc| { Box::new(move |app, owc| {
let attrib = BackendAttribValue::StereoFullFrame(full_frame); let attrib = BackendAttribValue::StereoFullFrame(full_frame);
owc.backend.set_attrib(_app, attrib); owc.backend.set_attrib(app, attrib);
}), }),
))); )));
Ok(EventResult::Consumed) Ok(EventResult::Consumed)
@ -534,7 +535,7 @@ fn reset_panel(
panel.state.stereo.reset(&mut common, &stereo); panel.state.stereo.reset(&mut common, &stereo);
// Set the checkbox label based on stereo mode // Set the checkbox label based on stereo mode
let translation = get_stereo_full_frame_translation(&stereo); let translation = get_stereo_full_frame_translation(stereo);
let c = panel let c = panel
.parser_state .parser_state
.fetch_component_as::<ComponentCheckbox>("stereo_full_frame_box")?; .fetch_component_as::<ComponentCheckbox>("stereo_full_frame_box")?;
@ -636,23 +637,23 @@ const fn cb_assign_block_input(
} }
fn cb_assign_stereo_full_frame( fn cb_assign_stereo_full_frame(
_app: &mut AppState, app: &mut AppState,
owc: &mut OverlayWindowConfig, owc: &mut OverlayWindowConfig,
full_frame: bool, full_frame: bool,
) { ) {
owc.dirty = true; owc.dirty = true;
let attrib = BackendAttribValue::StereoFullFrame(full_frame); let attrib = BackendAttribValue::StereoFullFrame(full_frame);
owc.backend.set_attrib(_app, attrib); owc.backend.set_attrib(app, attrib);
} }
fn cb_assign_stereo_adjust_mouse( fn cb_assign_stereo_adjust_mouse(
_app: &mut AppState, app: &mut AppState,
owc: &mut OverlayWindowConfig, owc: &mut OverlayWindowConfig,
adjust_mouse: bool, adjust_mouse: bool,
) { ) {
owc.dirty = true; owc.dirty = true;
let attrib = BackendAttribValue::StereoAdjustMouse(adjust_mouse); let attrib = BackendAttribValue::StereoAdjustMouse(adjust_mouse);
owc.backend.set_attrib(_app, attrib); owc.backend.set_attrib(app, attrib);
} }
fn set_up_slider( fn set_up_slider(

View File

@ -14,7 +14,6 @@ pub trait SpriteTabKey {
} }
struct SpriteTabButtonState<S> { struct SpriteTabButtonState<S> {
name: &'static str,
sprite: CustomGlyphData, sprite: CustomGlyphData,
component: Rc<ComponentButton>, component: Rc<ComponentButton>,
state: S, state: S,
@ -69,7 +68,6 @@ where
buttons.insert( buttons.insert(
*name, *name,
Rc::new(SpriteTabButtonState { Rc::new(SpriteTabButtonState {
name,
sprite, sprite,
component, component,
state, state,

View File

@ -22,7 +22,7 @@ pub fn new_stereo_tab_handler(
Box::new(move |common, state| { Box::new(move |common, state| {
let stereo = *state; let stereo = *state;
let translation = get_stereo_full_frame_translation(&stereo); let translation = get_stereo_full_frame_translation(stereo);
checkbox.set_text(common, Translation::from_translation_key(translation)); checkbox.set_text(common, Translation::from_translation_key(translation));
Box::new(move |app, owc| { Box::new(move |app, owc| {
@ -59,7 +59,7 @@ impl SpriteTabKey for StereoMode {
} }
} }
pub fn get_stereo_full_frame_translation(stereo: &StereoMode) -> &'static str { pub const fn get_stereo_full_frame_translation(stereo: StereoMode) -> &'static str {
match stereo { match stereo {
StereoMode::LeftRight | StereoMode::RightLeft => "EDIT_MODE.STEREO_3D_MODE.FULL_FRAME_SBS", StereoMode::LeftRight | StereoMode::RightLeft => "EDIT_MODE.STEREO_3D_MODE.FULL_FRAME_SBS",
StereoMode::TopBottom => "EDIT_MODE.STEREO_3D_MODE.FULL_FRAME_TAB", StereoMode::TopBottom => "EDIT_MODE.STEREO_3D_MODE.FULL_FRAME_TAB",

View File

@ -119,7 +119,7 @@ pub fn create_keyboard(app: &mut AppState, wayland: bool) -> anyhow::Result<Over
}) })
} }
fn alt_modifier_to_key(m: AltModifier) -> KeyModifier { const fn alt_modifier_to_key(m: AltModifier) -> KeyModifier {
match m { match m {
AltModifier::Shift => SHIFT, AltModifier::Shift => SHIFT,
AltModifier::Ctrl => CTRL, AltModifier::Ctrl => CTRL,

View File

@ -25,8 +25,6 @@ use wlx_common::{
use super::capture::{ScreenPipeline, WlxCaptureIn, WlxCaptureOut, receive_callback}; use super::capture::{ScreenPipeline, WlxCaptureIn, WlxCaptureOut, receive_callback};
const CURSOR_SIZE: f32 = 16. / 1440.;
static START: LazyLock<Instant> = LazyLock::new(Instant::now); static START: LazyLock<Instant> = LazyLock::new(Instant::now);
static NEXT_MOVE: AtomicU64 = AtomicU64::new(0); static NEXT_MOVE: AtomicU64 = AtomicU64::new(0);
@ -404,7 +402,7 @@ impl OverlayBackend for ScreenBackend {
} }
} }
fn mouse_transform_to_transform(mouse_transform: MouseTransform) -> Transform { const fn mouse_transform_to_transform(mouse_transform: MouseTransform) -> Transform {
match mouse_transform { match mouse_transform {
MouseTransform::Default => Transform::Undefined, MouseTransform::Default => Transform::Undefined,
MouseTransform::Normal => Transform::Normal, MouseTransform::Normal => Transform::Normal,

View File

@ -20,8 +20,6 @@ use crate::{
windowing::{OverlaySelector, Z_ORDER_TOAST, window::OverlayWindowConfig}, windowing::{OverlaySelector, Z_ORDER_TOAST, window::OverlayWindowConfig},
}; };
const FONT_SIZE: isize = 16;
const PADDING: (f32, f32) = (25., 7.);
const PIXELS_TO_METERS: f32 = 1. / 2000.; const PIXELS_TO_METERS: f32 = 1. / 2000.;
static TOAST_NAME: LazyLock<Arc<str>> = LazyLock::new(|| "toast".into()); static TOAST_NAME: LazyLock<Arc<str>> = LazyLock::new(|| "toast".into());
@ -210,6 +208,9 @@ fn new_toast(toast: Toast, app: &mut AppState) -> Option<OverlayWindowConfig> {
}) })
} }
// FIXME: Will these functions be used in the future? Can they be removed?
#[allow(dead_code)]
fn msg_err(app: &mut AppState, message: &str) { fn msg_err(app: &mut AppState, message: &str) {
Toast::new(ToastTopic::Error, "TOAST.ERROR".into(), message.into()) Toast::new(ToastTopic::Error, "TOAST.ERROR".into(), message.into())
.with_timeout(3.) .with_timeout(3.)
@ -218,6 +219,7 @@ fn msg_err(app: &mut AppState, message: &str) {
// Display the same error in the terminal and as a toast in VR. // Display the same error in the terminal and as a toast in VR.
// Formatted as "Failed to XYZ: Object is not defined" // Formatted as "Failed to XYZ: Object is not defined"
#[allow(dead_code)]
pub fn error_toast<ErrorType>(app: &mut AppState, title: &str, err: ErrorType) pub fn error_toast<ErrorType>(app: &mut AppState, title: &str, err: ErrorType)
where where
ErrorType: std::fmt::Display + std::fmt::Debug, ErrorType: std::fmt::Display + std::fmt::Debug,
@ -228,6 +230,7 @@ where
msg_err(app, &format!("{title}: {err}")); msg_err(app, &format!("{title}: {err}"));
} }
#[allow(dead_code)]
pub fn error_toast_str(app: &mut AppState, message: &str) { pub fn error_toast_str(app: &mut AppState, message: &str) {
log::error!("{message}"); log::error!("{message}");
msg_err(app, message); msg_err(app, message);

View File

@ -1,11 +1,10 @@
use std::{rc::Rc, time::Duration}; use std::time::Duration;
use glam::{Affine3A, Quat, Vec3, vec3}; use glam::{Affine3A, Quat, Vec3, vec3};
use wgui::{ use wgui::{
assets::AssetPath, assets::AssetPath,
components::button::ComponentButton, components::button::ComponentButton,
event::{CallbackDataCommon, EventAlterables, StyleSetRequest}, event::{CallbackDataCommon, EventAlterables, StyleSetRequest},
layout::WidgetID,
parser::{Fetchable, ParseDocumentParams}, parser::{Fetchable, ParseDocumentParams},
taffy, taffy,
}; };
@ -27,23 +26,12 @@ use crate::{
}; };
pub const WATCH_NAME: &str = "watch"; pub const WATCH_NAME: &str = "watch";
const MAX_TOOLBOX_BUTTONS: usize = 16;
const MAX_DEVICES: usize = 12;
pub const WATCH_POS: Vec3 = vec3(-0.03, -0.01, 0.125); pub const WATCH_POS: Vec3 = vec3(-0.03, -0.01, 0.125);
pub const WATCH_ROT: Quat = Quat::from_xyzw(-0.707_106_6, 0.000_796_361_8, 0.707_106_6, 0.0); pub const WATCH_ROT: Quat = Quat::from_xyzw(-0.707_106_6, 0.000_796_361_8, 0.707_106_6, 0.0);
struct OverlayButton {
button: Rc<ComponentButton>,
label: WidgetID,
sprite: WidgetID,
condensed: bool,
}
#[derive(Default)] #[derive(Default)]
struct WatchState { struct WatchState {
edit_mode_widgets: Vec<(WidgetID, bool)>,
edit_add_widget: WidgetID,
device_list: DeviceList, device_list: DeviceList,
overlay_list: OverlayList, overlay_list: OverlayList,
set_list: SetList, set_list: SetList,

View File

@ -545,7 +545,7 @@ impl OverlayBackend for WvrWindowBackend {
return; return;
}; };
let mut hit2 = hit.clone(); let mut hit2 = *hit;
hit2.uv.y *= meta.extent[1] as f32 / (meta.extent[1] - self.inner_extent[1]) as f32; hit2.uv.y *= meta.extent[1] as f32 / (meta.extent[1] - self.inner_extent[1]) as f32;
self.panel_hovered = true; self.panel_hovered = true;
return self.panel.on_pointer(app, &hit2, pressed); return self.panel.on_pointer(app, &hit2, pressed);

View File

@ -231,5 +231,6 @@ impl AppSession {
pub struct ScreenMeta { pub struct ScreenMeta {
pub name: Arc<str>, pub name: Arc<str>,
#[allow(dead_code)]
pub native_handle: u32, pub native_handle: u32,
} }

View File

@ -1,4 +1,7 @@
// This code was autogenerated with `dbus-codegen-rust -g -m None -d org.fcitx.Fcitx5 -p /controller`, see https://github.com/diwic/dbus-rs #![allow(dead_code)]
#![allow(clippy::all)]
#![allow(clippy::pedantic)]
// This code below was autogenerated with `dbus-codegen-rust -g -m None -d org.fcitx.Fcitx5 -p /controller`, see https://github.com/diwic/dbus-rs
use dbus; use dbus;
#[allow(unused_imports)] #[allow(unused_imports)]
use dbus::arg; use dbus::arg;

View File

@ -1,4 +1,7 @@
// This code was autogenerated with `dbus-codegen-rust -g -m None -d org.freedesktop.Notifications -p /org/freedesktop/Notifications`, see https://github.com/diwic/dbus-rs #![allow(dead_code)]
#![allow(clippy::all)]
#![allow(clippy::pedantic)]
// This code below was autogenerated with `dbus-codegen-rust -g -m None -d org.freedesktop.Notifications -p /org/freedesktop/Notifications`, see https://github.com/diwic/dbus-rs
use dbus; use dbus;
#[allow(unused_imports)] #[allow(unused_imports)]
use dbus::arg; use dbus::arg;

View File

@ -27,6 +27,7 @@ use crate::{
pub struct FrameMeta { pub struct FrameMeta {
pub extent: [u32; 2], pub extent: [u32; 2],
pub transform: Affine3A, pub transform: Affine3A,
#[allow(dead_code)]
pub format: Format, pub format: Format,
pub clear: WGfxClearMode, pub clear: WGfxClearMode,
pub stereo: StereoMode, pub stereo: StereoMode,
@ -72,10 +73,6 @@ impl RenderResources {
self.cmd_bufs.first_mut().unwrap() // first must always be populated self.cmd_bufs.first_mut().unwrap() // first must always be populated
} }
pub fn is_stereo(&self) -> bool {
self.cmd_bufs.len() > 1
}
pub fn end(self) -> anyhow::Result<SmallVec<[RenderResult; 2]>> { pub fn end(self) -> anyhow::Result<SmallVec<[RenderResult; 2]>> {
let mut ret_val = SmallVec::new_const(); let mut ret_val = SmallVec::new_const();

View File

@ -195,7 +195,7 @@ where
ToggleMode::EnsureOn if o.config.is_active() => return Ok(()), ToggleMode::EnsureOn if o.config.is_active() => return Ok(()),
ToggleMode::EnsureOff if !o.config.is_active() => return Ok(()), ToggleMode::EnsureOff if !o.config.is_active() => return Ok(()),
_ => {} _ => {}
}; }
let parent_set = if o.config.global { let parent_set = if o.config.global {
&mut self.global_set &mut self.global_set
@ -515,7 +515,7 @@ impl<T> OverlayWindowManager<T> {
} }
// global overlays // global overlays
for (name, ows) in app.session.config.global_set.clone().into_iter() { for (name, ows) in app.session.config.global_set.clone() {
let mut ows = ows.clone(); let mut ows = ows.clone();
// fix angle_fade missing on watch if loading older state // fix angle_fade missing on watch if loading older state
@ -523,7 +523,7 @@ impl<T> OverlayWindowManager<T> {
ows.angle_fade = true; ows.angle_fade = true;
} }
if let Some(oid) = self.lookup(&*name) if let Some(oid) = self.lookup(&name)
&& let Some(o) = self.mut_by_id(oid) && let Some(o) = self.mut_by_id(oid)
{ {
o.config.global = true; o.config.global = true;
@ -685,6 +685,7 @@ impl<T> OverlayWindowManager<T> {
self.overlays.iter() self.overlays.iter()
} }
#[allow(dead_code)]
pub fn iter_mut(&mut self) -> impl Iterator<Item = (OverlayID, &'_ mut OverlayWindowData<T>)> { pub fn iter_mut(&mut self) -> impl Iterator<Item = (OverlayID, &'_ mut OverlayWindowData<T>)> {
self.overlays.iter_mut() self.overlays.iter_mut()
} }
@ -851,6 +852,7 @@ impl<T> OverlayWindowManager<T> {
.inspect_err(|e| log::error!("VisibleOverlaysChanged: {e:?}")); .inspect_err(|e| log::error!("VisibleOverlaysChanged: {e:?}"));
} }
#[allow(clippy::unnecessary_wraps)]
fn overlays_changed(&mut self, app: &mut AppState) -> anyhow::Result<()> { fn overlays_changed(&mut self, app: &mut AppState) -> anyhow::Result<()> {
let mut meta = Vec::with_capacity(self.overlays.len()); let mut meta = Vec::with_capacity(self.overlays.len());
for (id, data) in &self.overlays { for (id, data) in &self.overlays {
@ -886,6 +888,7 @@ impl<T> OverlayWindowManager<T> {
Ok(()) Ok(())
} }
#[allow(clippy::unnecessary_wraps)]
fn visible_overlays_changed(&mut self, app: &mut AppState) -> anyhow::Result<()> { fn visible_overlays_changed(&mut self, app: &mut AppState) -> anyhow::Result<()> {
let mut vis = Vec::with_capacity(self.overlays.len()); let mut vis = Vec::with_capacity(self.overlays.len());
@ -923,6 +926,7 @@ impl<T> OverlayWindowManager<T> {
} }
} }
#[allow(clippy::unnecessary_wraps)]
pub fn devices_changed(&mut self, app: &mut AppState) -> anyhow::Result<()> { pub fn devices_changed(&mut self, app: &mut AppState) -> anyhow::Result<()> {
if let Some(watch) = self.mut_by_id(self.watch_id) { if let Some(watch) = self.mut_by_id(self.watch_id) {
let _ = watch let _ = watch

View File

@ -102,6 +102,7 @@ pub async fn wvr_process_terminate(
) )
} }
#[allow(clippy::too_many_arguments)]
pub async fn wvr_process_launch( pub async fn wvr_process_launch(
state: &mut WayVRClientState, state: &mut WayVRClientState,
exec: String, exec: String,

View File

@ -163,7 +163,7 @@ async fn run_once(state: &mut WayVRClientState, args: Args) -> anyhow::Result<()
} => { } => {
wlx_device_haptics(state, device, intensity, duration, frequency).await; wlx_device_haptics(state, device, intensity, duration, frequency).await;
} }
Subcommands::ShowHide {} => { Subcommands::ShowHide => {
wlx_show_hide(state).await; wlx_show_hide(state).await;
} }
Subcommands::PanelModify { Subcommands::PanelModify {
@ -192,7 +192,7 @@ async fn run_once(state: &mut WayVRClientState, args: Args) -> anyhow::Result<()
wlx_panel_modify(state, overlay, element, command).await; wlx_panel_modify(state, overlay, element, command).await;
} }
Subcommands::SwitchSet { set_or_0: set } => { Subcommands::SwitchSet { set_or_0: set } => {
let set = if set <= 0 { None } else { Some((set - 1) as _) }; let set = if set == 0 { None } else { Some((set - 1) as _) };
wlx_switch_set(state, set).await; wlx_switch_set(state, set).await;
} }
} }
@ -301,6 +301,7 @@ enum PosModeEnum {
} }
#[derive(clap::Parser, Debug)] #[derive(clap::Parser, Debug)]
#[allow(clippy::enum_variant_names)]
enum SubcommandPanelModify { enum SubcommandPanelModify {
/// Set the text of a <label> or <Button> /// Set the text of a <label> or <Button>
SetText { SetText {

View File

@ -227,6 +227,7 @@ impl ComponentButton {
} }
} }
#[allow(clippy::too_many_arguments)]
fn anim_hover( fn anim_hover(
common: &mut CallbackDataCommon, common: &mut CallbackDataCommon,
rect: &mut WidgetRectangle, rect: &mut WidgetRectangle,

View File

@ -180,7 +180,7 @@ impl Color {
} }
#[must_use] #[must_use]
pub fn as_arr(&self) -> [f32; 4] { pub const fn as_arr(&self) -> [f32; 4] {
[self.r, self.b, self.g, self.a] [self.r, self.b, self.g, self.a]
} }
} }
@ -306,7 +306,7 @@ impl PushScissorStackResult {
} }
} }
/// Returns Some() if scissor has been pushed. /// Returns `Some()` if scissor has been pushed.
pub fn push_scissor_stack( pub fn push_scissor_stack(
transform_stack: &mut TransformStack, transform_stack: &mut TransformStack,
scissor_stack: &mut ScissorStack, scissor_stack: &mut ScissorStack,

View File

@ -31,6 +31,7 @@ impl<V> WGfxPass<V>
where where
V: BufferContents + Vertex, V: BufferContents + Vertex,
{ {
#[allow(clippy::too_many_arguments)]
pub(super) fn new( pub(super) fn new(
pipeline: &Arc<WGfxPipeline<V>>, pipeline: &Arc<WGfxPipeline<V>>,
dimensions: [f32; 2], dimensions: [f32; 2],

View File

@ -263,6 +263,7 @@ where
) )
} }
#[allow(clippy::too_many_arguments)]
pub fn create_pass( pub fn create_pass(
self: &Arc<Self>, self: &Arc<Self>,
dimensions: [f32; 2], dimensions: [f32; 2],

View File

@ -1,9 +1,13 @@
use std::fmt::Debug; use std::fmt::Debug;
pub trait LogErr { pub trait LogErr {
#[must_use]
fn log_err(self, additional: &str) -> Self; fn log_err(self, additional: &str) -> Self;
#[must_use]
fn log_err_with<D: Debug>(self, additional: &D) -> Self; fn log_err_with<D: Debug>(self, additional: &D) -> Self;
#[must_use]
fn log_warn(self, additional: &str) -> Self; fn log_warn(self, additional: &str) -> Self;
#[must_use]
fn log_warn_with<D: Debug>(self, additional: &D) -> Self; fn log_warn_with<D: Debug>(self, additional: &D) -> Self;
} }

View File

@ -123,29 +123,26 @@ impl ImageRenderer {
} }
fn upload_image( fn upload_image(
gfx: Arc<WGfx>, gfx: &Arc<WGfx>,
res: [u32; 2], res: [u32; 2],
img: &ImageVertexWithContent, img: &ImageVertexWithContent,
) -> anyhow::Result<Option<Arc<ImageView>>> { ) -> anyhow::Result<Option<Arc<ImageView>>> {
let raster = match RasterizedCustomGlyph::try_from(&RasterizeCustomGlyphRequest { let Some(raster) = RasterizedCustomGlyph::try_from(&RasterizeCustomGlyphRequest {
data: img.content.clone(), data: img.content.clone(),
width: res[0] as _, width: res[0] as _,
height: res[1] as _, height: res[1] as _,
x_bin: SubpixelBin::Zero, x_bin: SubpixelBin::Zero,
y_bin: SubpixelBin::Zero, y_bin: SubpixelBin::Zero,
scale: 1.0, // unused scale: 1.0, // unused
}) { }) else {
Some(x) => x, log::error!("Unable to rasterize custom image");
None => { return Ok(None);
log::error!("Unable to rasterize custom image");
return Ok(None);
}
}; };
let mut cmd_buf = gfx.create_xfer_command_buffer(CommandBufferUsage::OneTimeSubmit)?; let mut cmd_buf = gfx.create_xfer_command_buffer(CommandBufferUsage::OneTimeSubmit)?;
let image = cmd_buf.upload_image( let image = cmd_buf.upload_image(
raster.width as _, raster.width.into(),
raster.height as _, raster.height.into(),
Format::R8G8B8A8_UNORM, Format::R8G8B8A8_UNORM,
&raster.data, &raster.data,
)?; )?;
@ -166,59 +163,56 @@ impl ImageRenderer {
let res = viewport.resolution(); let res = viewport.resolution();
self.model_buffer.upload(gfx)?; self.model_buffer.upload(gfx)?;
for img in self.image_verts.iter() { for img in &self.image_verts {
let pass = match self.cached_passes.get_mut(&img.content_key) { let pass = if let Some(x) = self.cached_passes.get_mut(&img.content_key) {
Some(x) => { if x.content_id != img.content.id || x.res != res {
if x.content_id != img.content.id || x.res != res { // image changed
// image changed let Some(image_view) = Self::upload_image(&self.pipeline.gfx, res, img)? else {
let Some(image_view) = Self::upload_image(self.pipeline.gfx.clone(), res, img)? else {
continue;
};
x.inner
.update_sampler(2, image_view, self.pipeline.gfx.texture_filter)?;
}
x
}
None => {
let vert_buffer = self.pipeline.gfx.empty_buffer(
BufferUsage::VERTEX_BUFFER | BufferUsage::TRANSFER_DST,
(std::mem::size_of::<ImageVertex>()) as _,
)?;
let Some(image_view) = Self::upload_image(self.pipeline.gfx.clone(), res, img)? else {
continue; continue;
}; };
let set0 = viewport.get_image_descriptor(&self.pipeline); x.inner
let set1 = self.model_buffer.get_image_descriptor(&self.pipeline); .update_sampler(2, image_view, self.pipeline.gfx.texture_filter)?;
let set2 = self
.pipeline
.inner
.uniform_sampler(2, image_view, self.pipeline.gfx.texture_filter)?;
let pass = self.pipeline.inner.create_pass(
[res[0] as _, res[1] as _],
[0.0, 0.0],
vert_buffer.clone(),
0..4,
0..1,
vec![set0, set1, set2],
vk_scissor,
)?;
self.cached_passes.insert(
img.content_key,
CachedPass {
content_id: img.content.id,
vert_buffer,
inner: pass,
res,
},
);
self.cached_passes.get_mut(&img.content_key).unwrap()
} }
x
} else {
let vert_buffer = self.pipeline.gfx.empty_buffer(
BufferUsage::VERTEX_BUFFER | BufferUsage::TRANSFER_DST,
(std::mem::size_of::<ImageVertex>()) as _,
)?;
let Some(image_view) = Self::upload_image(&self.pipeline.gfx, res, img)? else {
continue;
};
let set0 = viewport.get_image_descriptor(&self.pipeline);
let set1 = self.model_buffer.get_image_descriptor(&self.pipeline);
let set2 = self
.pipeline
.inner
.uniform_sampler(2, image_view, self.pipeline.gfx.texture_filter)?;
let pass = self.pipeline.inner.create_pass(
[res[0] as _, res[1] as _],
[0.0, 0.0],
vert_buffer.clone(),
0..4,
0..1,
vec![set0, set1, set2],
vk_scissor,
)?;
self.cached_passes.insert(
img.content_key,
CachedPass {
content_id: img.content.id,
vert_buffer,
inner: pass,
res,
},
);
self.cached_passes.get_mut(&img.content_key).unwrap()
}; };
pass.vert_buffer.write()?[0..1].clone_from_slice(&[img.vert]); pass.vert_buffer.write()?[0..1].clone_from_slice(&[img.vert]);

View File

@ -2,6 +2,7 @@ use std::{
collections::HashMap, collections::HashMap,
f32, f32,
hash::{DefaultHasher, Hasher}, hash::{DefaultHasher, Hasher},
path::Path,
sync::{ sync::{
Arc, Weak, Arc, Weak,
atomic::{AtomicUsize, Ordering}, atomic::{AtomicUsize, Ordering},
@ -54,7 +55,7 @@ impl CustomGlyphCache {
self self
.inner .inner
.get(&hashed_asset) .get(&hashed_asset)
.and_then(|a| a.upgrade()) .and_then(CustomGlyphDataWeak::upgrade)
.inspect(|_| log::debug!("Glyph cache hit on: '{path}'")) .inspect(|_| log::debug!("Glyph cache hit on: '{path}'"))
.ok_or(hashed_asset) .ok_or(hashed_asset)
} }
@ -100,11 +101,10 @@ struct CustomGlyphDataWeak {
impl CustomGlyphDataWeak { impl CustomGlyphDataWeak {
fn upgrade(&self) -> Option<CustomGlyphData> { fn upgrade(&self) -> Option<CustomGlyphData> {
if let Some(content) = self.content.upgrade() { self
Some(CustomGlyphData { id: self.id, content }) .content
} else { .upgrade()
None .map(|content| CustomGlyphData { id: self.id, content })
}
} }
} }
@ -142,11 +142,15 @@ impl CustomGlyphData {
} }
} }
pub fn from_assets(globals: &WguiGlobals, path: AssetPath) -> anyhow::Result<Self> { pub fn from_assets(globals: &WguiGlobals, asset_path: AssetPath) -> anyhow::Result<Self> {
let path_str = path.get_str(); let path_str = asset_path.get_str();
let data = globals.get_asset(path)?; let data = globals.get_asset(asset_path)?;
let path = Path::new(path_str);
let is_svg = path
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("svg") || ext.eq_ignore_ascii_case("svgz"));
if path_str.ends_with(".svg") || path_str.ends_with(".svgz") { if is_svg {
Self::from_bytes_svg(globals, path_str, &data) Self::from_bytes_svg(globals, path_str, &data)
} else { } else {
Self::from_bytes_raster(globals, path_str, &data) Self::from_bytes_raster(globals, path_str, &data)
@ -156,7 +160,7 @@ impl CustomGlyphData {
pub fn from_bytes_raster(globals: &WguiGlobals, path: &str, data: &[u8]) -> anyhow::Result<Self> { pub fn from_bytes_raster(globals: &WguiGlobals, path: &str, data: &[u8]) -> anyhow::Result<Self> {
let globals_borrow = &mut globals.get(); let globals_borrow = &mut globals.get();
match globals_borrow.custom_glyph_cache.get(path, data) { match globals_borrow.custom_glyph_cache.get(path, data) {
Ok(data) => return Ok(data), Ok(data) => Ok(data),
Err(hashed_asset) => { Err(hashed_asset) => {
let data = Self::new(CustomGlyphContent::from_bin_raster(data)?); let data = Self::new(CustomGlyphContent::from_bin_raster(data)?);
globals_borrow.custom_glyph_cache.insert(hashed_asset, &data); globals_borrow.custom_glyph_cache.insert(hashed_asset, &data);
@ -168,7 +172,7 @@ impl CustomGlyphData {
pub fn from_bytes_svg(globals: &WguiGlobals, path: &str, data: &[u8]) -> anyhow::Result<Self> { pub fn from_bytes_svg(globals: &WguiGlobals, path: &str, data: &[u8]) -> anyhow::Result<Self> {
let globals_borrow = &mut globals.get(); let globals_borrow = &mut globals.get();
match globals_borrow.custom_glyph_cache.get(path, data) { match globals_borrow.custom_glyph_cache.get(path, data) {
Ok(data) => return Ok(data), Ok(data) => Ok(data),
Err(hashed_asset) => { Err(hashed_asset) => {
let data = Self::new(CustomGlyphContent::from_bin_svg(data)?); let data = Self::new(CustomGlyphContent::from_bin_svg(data)?);
log::trace!("Caching {path} with content_id {}", data.id); log::trace!("Caching {path} with content_id {}", data.id);

View File

@ -58,7 +58,7 @@ impl SamplePlayer {
Err(_) => assets.load_from_path(path)?.into(), Err(_) => assets.load_from_path(path)?.into(),
}; };
self.register_sample(sample_name, AudioSample::from_mp3(&*sound_bytes)?)?; self.register_sample(sample_name, AudioSample::from_mp3(&sound_bytes)?)?;
Ok(()) Ok(())
}; };
@ -146,7 +146,7 @@ impl AudioSample {
} }
pub fn try_bytes_from_config(path: &str) -> anyhow::Result<Rc<[u8]>> { pub fn try_bytes_from_config(path: &str) -> anyhow::Result<Rc<[u8]>> {
let real_path = crate::config_io::get_config_root().join(&*path); let real_path = crate::config_io::get_config_root().join(path);
let mut file = std::fs::File::open(&real_path) let mut file = std::fs::File::open(&real_path)
.inspect_err(|e| log::debug!("Could not open file '{}': {e:?}", real_path.display()))?; .inspect_err(|e| log::debug!("Could not open file '{}': {e:?}", real_path.display()))?;

View File

@ -66,6 +66,7 @@ pub struct DesktopFinder {
} }
impl DesktopFinder { impl DesktopFinder {
#[allow(clippy::new_without_default)]
pub fn new() -> Self { pub fn new() -> Self {
let xdg = xdg::BaseDirectories::new(); let xdg = xdg::BaseDirectories::new();

View File

@ -42,8 +42,8 @@ impl BackendAttribValue {
pub fn is_default(&self) -> bool { pub fn is_default(&self) -> bool {
match self { match self {
Self::Stereo(val) => *val == StereoMode::default(), Self::Stereo(val) => *val == StereoMode::default(),
Self::StereoFullFrame(val) => *val == false, Self::StereoFullFrame(val) => !*val,
Self::StereoAdjustMouse(val) => *val == false, Self::StereoAdjustMouse(val) => !*val,
Self::MouseTransform(val) => *val == MouseTransform::default(), Self::MouseTransform(val) => *val == MouseTransform::default(),
Self::Icon(_) => false, Self::Icon(_) => false,
} }