1
0
mirror of https://github.com/4yn/slidershim.git synced 2024-11-24 05:50:12 +01:00

fix warnings

This commit is contained in:
4yn 2022-02-05 11:44:42 +08:00
parent 263d21c0a6
commit bfb7f7dc95
13 changed files with 70 additions and 60 deletions

View File

@ -7,3 +7,9 @@
- ouptut websocket - ouptut websocket
- led websocket - led websocket
- comments - comments
```
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
$env:RUST_BACKTRACE = "1";
yarn tauri dev
```

View File

@ -13,7 +13,8 @@ use env_logger;
use log::info; use log::info;
use tauri::{ use tauri::{
AppHandle, CustomMenuItem, Event, Manager, Runtime, SystemTray, SystemTrayEvent, SystemTrayMenu, async_runtime::Handle as AsyncHandle, AppHandle, CustomMenuItem, Event, Manager, Runtime,
SystemTray, SystemTrayEvent, SystemTrayMenu,
}; };
fn show_window<R: Runtime>(handle: &AppHandle<R>) { fn show_window<R: Runtime>(handle: &AppHandle<R>) {
@ -29,6 +30,7 @@ fn quit_app() {
} }
fn main() { fn main() {
// Setup logger
env_logger::Builder::new() env_logger::Builder::new()
.filter_level(log::LevelFilter::Debug) .filter_level(log::LevelFilter::Debug)
.init(); .init();
@ -39,13 +41,14 @@ fn main() {
let config_handle = config.lock().unwrap(); let config_handle = config.lock().unwrap();
let config_handle_ref = config_handle.as_ref().unwrap(); let config_handle_ref = config_handle.as_ref().unwrap();
config_handle_ref.save(); config_handle_ref.save();
let mut manager_handle = manager.lock().unwrap(); // let mut manager_handle = manager.lock().unwrap();
manager_handle.take(); // manager_handle.take();
manager_handle.replace(slider_io::Manager::new(config_handle_ref.clone())); // manager_handle.replace(slider_io::Manager::new(config_handle_ref.clone()));
} }
tauri::Builder::default() tauri::Builder::default()
.system_tray( .system_tray(
// System tray content
SystemTray::new().with_menu( SystemTray::new().with_menu(
SystemTrayMenu::new() SystemTrayMenu::new()
.add_item(CustomMenuItem::new("slidershim".to_string(), "slidershim").disabled()) .add_item(CustomMenuItem::new("slidershim".to_string(), "slidershim").disabled())
@ -54,6 +57,7 @@ fn main() {
), ),
) )
.on_system_tray_event(|app_handle, event| match event { .on_system_tray_event(|app_handle, event| match event {
// System tray events
SystemTrayEvent::LeftClick { SystemTrayEvent::LeftClick {
position: _, position: _,
size: _, size: _,
@ -75,9 +79,26 @@ fn main() {
_ => {} _ => {}
}) })
.setup(move |app| { .setup(move |app| {
// Before app starts
// Hide event
let app_handle = app.handle();
app.listen_global("hide", move |_| {
hide_window(&app_handle);
});
// Quit event
app.listen_global("quit", |_| {
quit_app();
});
// UI ready event
let app_handle = app.handle(); let app_handle = app.handle();
let config_clone = Arc::clone(&config); let config_clone = Arc::clone(&config);
app.listen_global("heartbeat", move |_| { app.listen_global("heartbeat", move |_| {
let handle = AsyncHandle::try_current();
println!("handle, {:?}", handle);
let config_handle = config_clone.lock().unwrap(); let config_handle = config_clone.lock().unwrap();
info!("Heartbeat received"); info!("Heartbeat received");
app_handle app_handle
@ -88,6 +109,7 @@ fn main() {
.unwrap(); .unwrap();
}); });
// Config set event
let config_clone = Arc::clone(&config); let config_clone = Arc::clone(&config);
let manager_clone = Arc::clone(&manager); let manager_clone = Arc::clone(&manager);
app.listen_global("setConfig", move |event| { app.listen_global("setConfig", move |event| {
@ -105,20 +127,12 @@ fn main() {
} }
}); });
let app_handle = app.handle();
app.listen_global("hide", move |_| {
hide_window(&app_handle);
});
app.listen_global("quit", |_| {
quit_app();
});
Ok(()) Ok(())
}) })
.build(tauri::generate_context!()) .build(tauri::generate_context!())
.expect("error while running tauri application") .expect("error while running tauri application")
.run(|app_handle, event| match event { .run(|app_handle, event| match event {
// After app starts
Event::CloseRequested { label, api, .. } if label.as_str() == "main" => { Event::CloseRequested { label, api, .. } if label.as_str() == "main" => {
api.prevent_close(); api.prevent_close();
hide_window(app_handle); hide_window(app_handle);

View File

@ -10,10 +10,10 @@ use hyper::{
use log::{error, info}; use log::{error, info};
use path_clean::PathClean; use path_clean::PathClean;
use std::{convert::Infallible, future::Future, net::SocketAddr, path::PathBuf}; use std::{convert::Infallible, future::Future, net::SocketAddr, path::PathBuf};
use tokio::{fs::File, select}; use tokio::fs::File;
use tokio_tungstenite::WebSocketStream; use tokio_tungstenite::WebSocketStream;
use tokio_util::codec::{BytesCodec, FramedRead}; use tokio_util::codec::{BytesCodec, FramedRead};
use tungstenite::{handshake, Error, Message}; use tungstenite::{handshake, Message};
use crate::slider_io::{controller_state::FullState, worker::AsyncJob}; use crate::slider_io::{controller_state::FullState, worker::AsyncJob};
@ -58,7 +58,10 @@ async fn handle_brokenithm(ws_stream: WebSocketStream<Upgraded>, state: FullStat
let head = chars.next().unwrap(); let head = chars.next().unwrap();
match head { match head {
'a' => { 'a' => {
ws_write.send(Message::Text("alive".to_string())).await; ws_write
.send(Message::Text("alive".to_string()))
.await
.unwrap();
} }
'b' => { 'b' => {
let flat_state: Vec<bool> = chars let flat_state: Vec<bool> = chars
@ -155,10 +158,13 @@ async fn handle_request(
let method = request.method(); let method = request.method();
let path = request.uri().path(); let path = request.uri().path();
if method != Method::GET { if method != Method::GET {
error!("Server unknown method {} {}", method, path); error!(
"Server unknown method {} -> {} {}",
remote_addr, method, path
);
return error_response().await; return error_response().await;
} }
info!("Server {} {}", method, path); info!("Server {} -> {} {}", remote_addr, method, path);
match ( match (
request.uri().path(), request.uri().path(),

View File

@ -1,9 +1,7 @@
use std::{convert::TryFrom, fs, path::PathBuf};
use log::info;
use directories::ProjectDirs; use directories::ProjectDirs;
use log::info;
use serde_json::Value; use serde_json::Value;
use std::{convert::TryFrom, fs, path::PathBuf};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum DeviceMode { pub enum DeviceMode {
@ -158,7 +156,7 @@ impl Config {
fn get_saved_path() -> Option<Box<PathBuf>> { fn get_saved_path() -> Option<Box<PathBuf>> {
let project_dir = ProjectDirs::from("me", "imp.ress", "slidershim").unwrap(); let project_dir = ProjectDirs::from("me", "imp.ress", "slidershim").unwrap();
let config_dir = project_dir.config_dir(); let config_dir = project_dir.config_dir();
fs::create_dir_all(config_dir); fs::create_dir_all(config_dir).unwrap();
let config_path = config_dir.join("config.json"); let config_path = config_dir.join("config.json");
@ -171,7 +169,7 @@ impl Config {
return None; return None;
} }
info!("Config file found at {:?}", config_path); info!("Config file found at {:?}", config_path);
let mut saved_data = fs::read_to_string(config_path.as_path()).ok()?; let saved_data = fs::read_to_string(config_path.as_path()).ok()?;
return Self::from_str(saved_data.as_str()); return Self::from_str(saved_data.as_str());
} }

View File

@ -79,8 +79,8 @@ impl FullState {
impl Clone for FullState { impl Clone for FullState {
fn clone(&self) -> Self { fn clone(&self) -> Self {
Self { Self {
controller_state: Arc::clone(&self.controller_state), controller_state: self.clone_controller(),
led_state: Arc::clone(&self.led_state), led_state: self.clone_led(),
} }
} }
} }

View File

@ -1,14 +1,11 @@
use log::{error, info};
use rusb::{self, DeviceHandle, GlobalContext};
use std::{ use std::{
error::Error, error::Error,
ops::{Deref, DerefMut}, ops::{Deref, DerefMut},
thread,
time::Duration, time::Duration,
}; };
use log::{error, info};
use rusb::{self, DeviceHandle, GlobalContext};
use crate::slider_io::{ use crate::slider_io::{
config::DeviceMode, config::DeviceMode,
controller_state::{ControllerState, FullState, LedState}, controller_state::{ControllerState, FullState, LedState},
@ -215,12 +212,12 @@ const TIMEOUT: Duration = Duration::from_millis(20);
impl ThreadJob for HidDeviceJob { impl ThreadJob for HidDeviceJob {
fn setup(&mut self) -> bool { fn setup(&mut self) -> bool {
match self.setup_impl() { match self.setup_impl() {
Ok(r) => { Ok(_) => {
info!("Device OK"); info!("Device OK");
true true
} }
Err(e) => { Err(e) => {
error!("Device setup failed, exiting thread early"); error!("Device setup failed: {}", e);
false false
} }
} }

View File

@ -1,5 +1,3 @@
use std::sync::{Arc, Mutex};
use vigem_client::{Client, TargetId, XButtons, XGamepad, Xbox360Wired}; use vigem_client::{Client, TargetId, XButtons, XGamepad, Xbox360Wired};
use crate::slider_io::{output::OutputHandler, voltex::VoltexState}; use crate::slider_io::{output::OutputHandler, voltex::VoltexState};

View File

@ -1,5 +1,4 @@
use std::mem; use std::mem;
use winapi::{ use winapi::{
ctypes::c_int, ctypes::c_int,
um::winuser::{SendInput, INPUT, INPUT_KEYBOARD, KEYBDINPUT, KEYEVENTF_KEYUP}, um::winuser::{SendInput, INPUT, INPUT_KEYBOARD, KEYBDINPUT, KEYEVENTF_KEYUP},
@ -64,8 +63,7 @@ const VOLTEX_KB_MAP: [usize; 41] = [
pub struct KeyboardOutput { pub struct KeyboardOutput {
ground_to_idx: [usize; 41], ground_to_idx: [usize; 41],
idx_to_keycode: [u16; 41], idx_to_keycode: [u16; 41],
keycode_to_idx: [usize; 256], // keycode_to_idx: [usize; 256],
next_keys: [bool; 41], next_keys: [bool; 41],
last_keys: [bool; 41], last_keys: [bool; 41],
@ -114,7 +112,7 @@ impl KeyboardOutput {
Self { Self {
ground_to_idx, ground_to_idx,
idx_to_keycode, idx_to_keycode,
keycode_to_idx, // keycode_to_idx,
next_keys: [false; 41], next_keys: [false; 41],
last_keys: [false; 41], last_keys: [false; 41],
kb_buf, kb_buf,
@ -131,20 +129,20 @@ impl KeyboardOutput {
.zip(self.last_keys.iter_mut()) .zip(self.last_keys.iter_mut())
.enumerate() .enumerate()
{ {
let wVk = self.idx_to_keycode[i]; let keycode = self.idx_to_keycode[i];
if wVk == 0 { if keycode == 0 {
continue; continue;
} }
match (*n, *l) { match (*n, *l) {
(false, true) => { (false, true) => {
let inner: &mut KEYBDINPUT = unsafe { self.kb_buf[self.n_kb_buf as usize].u.ki_mut() }; let inner: &mut KEYBDINPUT = unsafe { self.kb_buf[self.n_kb_buf as usize].u.ki_mut() };
inner.wVk = self.idx_to_keycode[i]; inner.wVk = keycode;
inner.dwFlags = 0; inner.dwFlags = 0;
self.n_kb_buf += 1; self.n_kb_buf += 1;
} }
(true, false) => { (true, false) => {
let inner: &mut KEYBDINPUT = unsafe { self.kb_buf[self.n_kb_buf as usize].u.ki_mut() }; let inner: &mut KEYBDINPUT = unsafe { self.kb_buf[self.n_kb_buf as usize].u.ki_mut() };
inner.wVk = self.idx_to_keycode[i]; inner.wVk = keycode;
inner.dwFlags = KEYEVENTF_KEYUP; inner.dwFlags = KEYEVENTF_KEYUP;
self.n_kb_buf += 1; self.n_kb_buf += 1;
} }

View File

@ -1,14 +1,12 @@
use log::{error, info};
use palette::{FromColor, Hsv, Srgb};
use serialport::{ClearBuffer, SerialPort};
use std::{ use std::{
ops::DerefMut, ops::DerefMut,
thread, thread,
time::{Duration, Instant}, time::{Duration, Instant},
}; };
use log::{error, info};
use palette::{FromColor, Hsv, Srgb};
use serialport::{ClearBuffer, SerialPort, StopBits};
use crate::slider_io::{ use crate::slider_io::{
config::{LedMode, ReactiveLayout}, config::{LedMode, ReactiveLayout},
controller_state::{FullState, LedState}, controller_state::{FullState, LedState},
@ -165,7 +163,7 @@ impl ThreadJob for LedJob {
Some(s) Some(s)
} }
Err(e) => { Err(e) => {
error!("Serial port could not open, exiting thread early"); error!("Serial port could not open: {}", e);
None None
} }
}; };
@ -205,7 +203,7 @@ impl ThreadJob for LedJob {
} }
if serial_data_avail > 0 { if serial_data_avail > 0 {
serial_port.clear(ClearBuffer::All); serial_port.clear(ClearBuffer::All).unwrap();
} }
} }
} }

View File

@ -10,6 +10,7 @@ use crate::slider_io::{
worker::{AsyncWorker, ThreadWorker}, worker::{AsyncWorker, ThreadWorker},
}; };
#[allow(dead_code)]
pub struct Manager { pub struct Manager {
state: FullState, state: FullState,
config: Config, config: Config,

View File

@ -8,7 +8,7 @@ use crate::slider_io::{
worker::ThreadJob, worker::ThreadJob,
}; };
pub trait OutputHandler: Send + Drop { pub trait OutputHandler: Send {
fn tick(&mut self, flat_controller_state: &Vec<bool>); fn tick(&mut self, flat_controller_state: &Vec<bool>);
fn reset(&mut self); fn reset(&mut self);
} }

View File

@ -5,6 +5,7 @@ pub struct Buffer {
pub len: usize, pub len: usize,
} }
#[allow(dead_code)]
impl Buffer { impl Buffer {
pub fn new() -> Self { pub fn new() -> Self {
Buffer { Buffer {

View File

@ -2,7 +2,6 @@ use async_trait::async_trait;
use log::info; use log::info;
use std::{ use std::{
future::Future, future::Future,
pin::Pin,
sync::{ sync::{
atomic::{AtomicBool, Ordering}, atomic::{AtomicBool, Ordering},
Arc, Arc,
@ -10,11 +9,7 @@ use std::{
thread, thread,
}; };
use tokio::{ use tokio::{runtime::Runtime, sync::oneshot, task};
runtime::Runtime,
sync::oneshot::{self, Receiver},
task,
};
pub trait ThreadJob: Send { pub trait ThreadJob: Send {
fn setup(&mut self) -> bool; fn setup(&mut self) -> bool;
@ -95,7 +90,7 @@ impl AsyncWorker {
let task = runtime.spawn(async move { let task = runtime.spawn(async move {
job job
.run(async move { .run(async move {
recv_stop.await; recv_stop.await.unwrap();
}) })
.await; .await;
}); });
@ -121,8 +116,6 @@ impl Drop for AsyncWorker {
// }); // });
} }
let name = self.name;
if self.task.is_some() { if self.task.is_some() {
// let task = self.task.take().unwrap(); // let task = self.task.take().unwrap();
// self.runtime.block_on(async move { // self.runtime.block_on(async move {