preperation for usage of grid_to_absolute_position

This commit is contained in:
2025-12-16 15:08:59 +08:00
parent df934afefa
commit c3268cf298
12 changed files with 162 additions and 97 deletions

View File

@@ -3,9 +3,44 @@ use ts_rs::TS;
use crate::remotes::{friends::FriendshipResponseDto, user::UserProfile}; use crate::remotes::{friends::FriendshipResponseDto, user::UserProfile};
#[derive(Serialize, Deserialize, Clone, Debug, TS)]
#[ts(export)]
pub struct DisplayData {
pub screen_width: i32,
pub screen_height: i32,
pub monitor_scale_factor: f64,
}
impl Default for DisplayData {
fn default() -> Self {
Self {
screen_width: 0,
screen_height: 0,
monitor_scale_factor: 1.0,
}
}
}
#[derive(Serialize, Deserialize, Clone, Debug, TS)]
#[ts(export)]
pub struct SceneData {
pub display: DisplayData,
pub grid_size: i32,
}
impl Default for SceneData {
fn default() -> Self {
Self {
display: DisplayData::default(),
grid_size: 600,
}
}
}
#[derive(Default, Serialize, Deserialize, Clone, Debug, TS)] #[derive(Default, Serialize, Deserialize, Clone, Debug, TS)]
#[ts(export)] #[ts(export)]
pub struct AppData { pub struct AppData {
pub user: Option<UserProfile>, pub user: Option<UserProfile>,
pub friends: Option<Vec<FriendshipResponseDto>>, pub friends: Option<Vec<FriendshipResponseDto>>,
pub scene: SceneData,
} }

View File

@@ -5,10 +5,10 @@ use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use tauri::Emitter; use tauri::Emitter;
use tracing::{error, info, warn}; use tracing::{error, info};
use ts_rs::TS; use ts_rs::TS;
use crate::get_app_handle; use crate::{get_app_handle, lock_r, state::FDOLL};
#[derive(Clone, Serialize, TS)] #[derive(Clone, Serialize, TS)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
@@ -28,18 +28,32 @@ pub struct CursorPositions {
static CURSOR_TRACKER: OnceCell<()> = OnceCell::new(); static CURSOR_TRACKER: OnceCell<()> = OnceCell::new();
fn map_to_grid( /// Convert absolute screen coordinates to grid coordinates
pos: &CursorPosition, pub fn absolute_position_to_grid(pos: &CursorPosition) -> CursorPosition {
grid_size: i32, let guard = lock_r!(FDOLL);
screen_w: i32, let grid_size = guard.app_data.scene.grid_size;
screen_h: i32, let screen_w = guard.app_data.scene.display.screen_width;
) -> CursorPosition { let screen_h = guard.app_data.scene.display.screen_height;
CursorPosition { CursorPosition {
x: pos.x * grid_size / screen_w, x: pos.x * grid_size / screen_w,
y: pos.y * grid_size / screen_h, y: pos.y * grid_size / screen_h,
} }
} }
/// Convert grid coordinates to absolute screen coordinates
pub fn grid_to_absolute_position(grid: &CursorPosition) -> CursorPosition {
let guard = lock_r!(FDOLL);
let grid_size = guard.app_data.scene.grid_size;
let screen_w = guard.app_data.scene.display.screen_width;
let screen_h = guard.app_data.scene.display.screen_height;
CursorPosition {
x: (grid.x * screen_w + grid_size / 2) / grid_size,
y: (grid.y * screen_h + grid_size / 2) / grid_size,
}
}
/// Initialize cursor tracking - can be called multiple times safely from any window /// Initialize cursor tracking - can be called multiple times safely from any window
/// Only the first call will actually start tracking, subsequent calls are no-ops /// Only the first call will actually start tracking, subsequent calls are no-ops
#[tauri::command] #[tauri::command]
@@ -64,55 +78,6 @@ async fn init_cursor_tracking() -> Result<(), String> {
info!("Initializing cursor tracking..."); info!("Initializing cursor tracking...");
let app_handle = get_app_handle(); let app_handle = get_app_handle();
// Get primary monitor with retries
let primary_monitor = {
let mut retry_count = 0;
let max_retries = 3;
loop {
match app_handle.primary_monitor() {
Ok(Some(monitor)) => {
info!("Primary monitor acquired");
break monitor;
}
Ok(None) => {
retry_count += 1;
if retry_count >= max_retries {
return Err(format!(
"No primary monitor found after {} retries",
max_retries
));
}
warn!(
"Primary monitor not available, retrying... ({}/{})",
retry_count, max_retries
);
tokio::time::sleep(Duration::from_millis(100)).await;
}
Err(e) => {
retry_count += 1;
if retry_count >= max_retries {
return Err(format!("Failed to get primary monitor: {}", e));
}
warn!(
"Error getting primary monitor, retrying... ({}/{}): {}",
retry_count, max_retries, e
);
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
}
};
let monitor_dimensions = primary_monitor.size();
let monitor_scale_factor = primary_monitor.scale_factor();
let logical_monitor_dimensions: tauri::LogicalSize<i32> =
monitor_dimensions.to_logical(monitor_scale_factor);
info!(
"Monitor dimensions: {}x{}",
logical_monitor_dimensions.width, logical_monitor_dimensions.height
);
// Try to initialize the device event handler // Try to initialize the device event handler
let device_state = DeviceEventsHandler::new(Duration::from_millis(500)) let device_state = DeviceEventsHandler::new(Duration::from_millis(500))
.ok_or("Failed to create device event handler (already running?)")?; .ok_or("Failed to create device event handler (already running?)")?;
@@ -124,17 +89,26 @@ async fn init_cursor_tracking() -> Result<(), String> {
let send_count_clone = Arc::clone(&send_count); let send_count_clone = Arc::clone(&send_count);
let app_handle_clone = app_handle.clone(); let app_handle_clone = app_handle.clone();
#[cfg(target_os = "windows")]
{
// Get scale factor from global state
let scale_factor = {
let guard = lock_r!(FDOLL);
guard.app_data.scene.display.monitor_scale_factor
};
}
let _guard = device_state.on_mouse_move(move |position: &(i32, i32)| { let _guard = device_state.on_mouse_move(move |position: &(i32, i32)| {
// `device_query` crate appears to behave // `device_query` crate appears to behave
// differently on Windows vs other paltforms. // differently on Windows vs other platforms.
// //
// It doesn't take into account the monitor scale // It doesn't take into account the monitor scale
// factor on Windows, so we handle it manually. // factor on Windows, so we handle it manually.
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
let raw = CursorPosition { let raw = CursorPosition {
x: (position.0 as f64 / monitor_scale_factor) as i32, x: (position.0 as f64 / scale_factor) as i32,
y: (position.1 as f64 / monitor_scale_factor) as i32, y: (position.1 as f64 / scale_factor) as i32,
}; };
#[cfg(not(target_os = "windows"))] #[cfg(not(target_os = "windows"))]
@@ -143,12 +117,7 @@ async fn init_cursor_tracking() -> Result<(), String> {
y: position.1, y: position.1,
}; };
let mapped = map_to_grid( let mapped = absolute_position_to_grid(&raw);
&raw,
600,
logical_monitor_dimensions.width,
logical_monitor_dimensions.height,
);
let positions = CursorPositions { let positions = CursorPositions {
raw, raw,
mapped: mapped.clone(), mapped: mapped.clone(),
@@ -166,7 +135,7 @@ async fn init_cursor_tracking() -> Result<(), String> {
let count = send_count_clone.fetch_add(1, Ordering::Relaxed) + 1; let count = send_count_clone.fetch_add(1, Ordering::Relaxed) + 1;
if count % 100 == 0 { if count % 100 == 0 {
info!("Broadcast {} cursor position updates to all windows. Latest: raw({}, {}), mapped({}, {})", info!("Broadcast {} cursor position updates to all windows. Latest: raw({}, {}), mapped({}, {})",
count, positions.raw.x, positions.raw.y, positions.mapped.x, positions.mapped.y); count, positions.raw.x, positions.raw.y, positions.mapped.x, positions.mapped.y);
} }
} }
Err(e) => { Err(e) => {

View File

@@ -83,6 +83,70 @@ pub fn init_fdoll_state() {
let has_auth = guard.auth_pass.is_some(); let has_auth = guard.auth_pass.is_some();
// Initialize screen dimensions
let app_handle = get_app_handle();
// Get primary monitor with retries
// Note: This duplicates logic from init_cursor_tracking, but we need it here for global state
let primary_monitor = {
let mut retry_count = 0;
let max_retries = 3;
loop {
match app_handle.primary_monitor() {
Ok(Some(monitor)) => {
info!("Primary monitor acquired for state initialization");
break Some(monitor);
}
Ok(None) => {
retry_count += 1;
if retry_count >= max_retries {
warn!("No primary monitor found after {} retries during state init", max_retries);
break None;
}
warn!(
"Primary monitor not available during state init, retrying... ({}/{})",
retry_count, max_retries
);
std::thread::sleep(std::time::Duration::from_millis(100));
}
Err(e) => {
retry_count += 1;
if retry_count >= max_retries {
warn!("Failed to get primary monitor during state init: {}", e);
break None;
}
warn!(
"Error getting primary monitor during state init, retrying... ({}/{}): {}",
retry_count, max_retries, e
);
std::thread::sleep(std::time::Duration::from_millis(100));
}
}
}
};
if let Some(monitor) = primary_monitor {
let monitor_dimensions = monitor.size();
let monitor_scale_factor = monitor.scale_factor();
let logical_monitor_dimensions: tauri::LogicalSize<i32> =
monitor_dimensions.to_logical(monitor_scale_factor);
guard.app_data.scene.display.screen_width = logical_monitor_dimensions.width;
guard.app_data.scene.display.screen_height = logical_monitor_dimensions.height;
guard.app_data.scene.display.monitor_scale_factor = monitor_scale_factor;
guard.app_data.scene.grid_size = 600; // Hardcoded grid size
info!(
"Initialized global AppData with screen dimensions: {}x{}, scale: {}, grid: {}",
logical_monitor_dimensions.width,
logical_monitor_dimensions.height,
monitor_scale_factor,
guard.app_data.scene.grid_size
);
} else {
warn!("Could not initialize screen dimensions in global state - no monitor found");
}
drop(guard); drop(guard);
if has_auth { if has_auth {

View File

@@ -1,8 +1,6 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { UserProfile } from "./UserProfile.js"; import type { FriendshipResponseDto } from "./FriendshipResponseDto";
import type { FriendshipResponseDto } from "./FriendshipResponseDto.js"; import type { SceneData } from "./SceneData";
import type { UserProfile } from "./UserProfile";
export type AppData = { export type AppData = { user: UserProfile | null, friends: Array<FriendshipResponseDto> | null, scene: SceneData, };
user: UserProfile | null;
friends: Array<FriendshipResponseDto> | null;
};

View File

@@ -0,0 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type DisplayData = { screen_width: number, screen_height: number, monitor_scale_factor: number, };

View File

@@ -1,10 +1,4 @@
import type { UserBasicDto } from "./UserBasicDto.js"; // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { UserBasicDto } from "./UserBasicDto";
export type FriendRequestResponseDto = { export type FriendRequestResponseDto = { id: string, sender: UserBasicDto, receiver: UserBasicDto, status: string, createdAt: string, updatedAt: string, };
id: string;
sender: UserBasicDto;
receiver: UserBasicDto;
status: string;
createdAt: string;
updatedAt: string;
};

View File

@@ -1,7 +1,4 @@
import type { UserBasicDto } from "./UserBasicDto.js"; // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { UserBasicDto } from "./UserBasicDto";
export type FriendshipResponseDto = { export type FriendshipResponseDto = { id: string, friend: UserBasicDto, createdAt: string, };
id: string;
friend: UserBasicDto;
createdAt: string;
};

View File

@@ -0,0 +1,4 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { DisplayData } from "./DisplayData";
export type SceneData = { display: DisplayData, grid_size: number, };

View File

@@ -1,3 +1,3 @@
export type SendFriendRequestDto = { // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
receiverId: string;
}; export type SendFriendRequestDto = { receiverId: string, };

View File

@@ -0,0 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type UpdateUserDto = Record<string, never>;

View File

@@ -1,5 +1,3 @@
export type UserBasicDto = { // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
id: string;
name: string; export type UserBasicDto = { id: string, name: string, username: string | null, };
username: string | null;
};

View File

@@ -1,3 +1,3 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type UserProfile = { id: string, name: string, email: string, username: string, createdAt: string, lastLoginAt: string, }; export type UserProfile = { id: string, keycloakSub: string, name: string, email: string, username: string | null, roles: Array<string>, createdAt: string, updatedAt: string, lastLoginAt: string | null, };