Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 43 additions & 27 deletions core/socket_lib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,13 +118,9 @@ pub enum Message {
pub struct CursorSocket {
#[cfg(unix)]
stream: UnixStream,
#[cfg(unix)]
_listener: Option<UnixListener>,

#[cfg(windows)]
stream: TcpStream,
#[cfg(windows)]
_listener: Option<TcpListener>,
}

impl CursorSocket {
Expand All @@ -133,10 +129,7 @@ impl CursorSocket {
{
let stream = UnixStream::connect(socket_path)?;
stream.set_read_timeout(None)?;
Ok(Self {
stream,
_listener: None,
})
Ok(Self { stream })
}

#[cfg(windows)]
Expand All @@ -145,10 +138,7 @@ impl CursorSocket {
let addr = format!("127.0.0.1:{port}");
let stream = TcpStream::connect(addr)?;
stream.set_read_timeout(None)?;
Ok(Self {
stream,
_listener: None,
})
Ok(Self { stream })
}
}

Expand All @@ -161,14 +151,28 @@ impl CursorSocket {
}

let listener = UnixListener::bind(socket_path)?;
log::info!("Wait for client");
let (stream, _) = listener.accept()?;
listener.set_nonblocking(true)?;
let mut stream = None;
for i in 0..10 {
log::info!("Waiting for client {i}/10");
match listener.accept() {
Ok((s, _)) => {
stream = Some(s);
break;
}
Err(_) => {
std::thread::sleep(std::time::Duration::from_secs(1));
}
}
}
let stream = stream.ok_or_else(|| {
std::io::Error::other("Client did not connect after multiple attempts")
})?;
stream.set_nonblocking(false)?;
log::info!("Client connected");
stream.set_read_timeout(None)?;

Ok(Self {
stream,
_listener: Some(listener),
})
Ok(Self { stream })
}

#[cfg(windows)]
Expand Down Expand Up @@ -207,13 +211,28 @@ impl CursorSocket {
fs::write(socket_path, port.to_string())?;

log::info!("Listening on port {port}, waiting for client");
let (stream, _) = listener.accept()?;
listener.set_nonblocking(true)?;
let mut stream = None;
for i in 0..10 {
log::info!("Waiting for client {i}/10");
match listener.accept() {
Ok((s, _)) => {
stream = Some(s);
break;
}
Err(_) => {
std::thread::sleep(std::time::Duration::from_secs(1));
}
}
}
let stream = stream.ok_or_else(|| {
std::io::Error::other("Client did not connect after multiple attempts")
})?;
stream.set_nonblocking(false)?;
log::info!("Client connected");
stream.set_read_timeout(None)?;

Ok(Self {
stream,
_listener: Some(listener),
})
Ok(Self { stream })
}
}

Expand Down Expand Up @@ -267,10 +286,7 @@ impl CursorSocket {

pub fn duplicate(&self) -> Result<Self, std::io::Error> {
let new_stream = self.stream.try_clone()?;
Ok(Self {
stream: new_stream,
_listener: None,
})
Ok(Self { stream: new_stream })
}
}

Expand Down
6 changes: 1 addition & 5 deletions core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -918,13 +918,9 @@ impl RenderEventLoop {
Self { event_loop }
}

pub fn run(self, input: RenderLoopRunArgs) -> Result<(), RenderLoopError> {
pub fn run(self, input: RenderLoopRunArgs, socket_path: String) -> Result<(), RenderLoopError> {
log::info!("Starting RenderEventLoop with input: {input}");

let temp_dir = std::env::temp_dir();
let socket_name = std::env::var("CORE_SOCKET_NAME").unwrap_or("core-socket".to_string());
let socket_path = format!("{}/{socket_name}", temp_dir.display());

log::info!("Creating socket at path: {socket_path}");
let mut socket = CursorSocket::new_create(&socket_path).map_err(|e| {
log::error!("Error creating socket: {e:?}");
Expand Down
14 changes: 13 additions & 1 deletion core/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ struct Args {
/// Sentry DSN
#[arg(short, long)]
sentry_dsn: Option<String>,

/// Socket name
#[arg(long)]
socket_path: Option<String>,
}

fn main() -> Result<(), impl std::error::Error> {
Expand Down Expand Up @@ -43,8 +47,16 @@ fn main() -> Result<(), impl std::error::Error> {
}
};

let socket_path = match args.socket_path {
Some(path) => path,
None => std::env::temp_dir()
.join("core-socket")
.to_string_lossy()
.to_string(),
};

let input_args = RenderLoopRunArgs { textures_path };

let render_event_loop = RenderEventLoop::new();
render_event_loop.run(input_args)
render_event_loop.run(input_args, socket_path)
}
1 change: 0 additions & 1 deletion tauri/Taskfile.yml
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ tasks:
env:
HOPP_SUFFIX: "_repl"
VITE_PORT: 1421
CORE_SOCKET_NAME: "core-socket-replica"
cmds:
- |
# Create repl hopp_core binary
Expand Down
34 changes: 25 additions & 9 deletions tauri/src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ pub mod permissions;
pub mod sounds;

use log::LevelFilter;
use rand::{distributions::Alphanumeric, Rng};
use sounds::SoundEntry;
use std::env;
use std::path::{Path, PathBuf};
Expand Down Expand Up @@ -139,6 +140,7 @@ async fn show_stdout(mut receiver: Receiver<CommandEvent>, app_handle: AppHandle
fn start_sidecar(
app: &tauri::AppHandle,
textures_path: &Path,
socket_path: &str,
) -> (Receiver<CommandEvent>, CommandChild) {
log::info!("start_sidecar: Creating core process texture_path: {textures_path:?}");

Expand All @@ -155,7 +157,12 @@ fn start_sidecar(
}
}

let mut args = vec!["--textures-path", textures_path.to_str().unwrap()];
let mut args = vec![
"--socket-path",
socket_path,
"--textures-path",
textures_path.to_str().unwrap(),
];

let sentry_dsn = get_sentry_dsn();
if !cfg!(debug_assertions) {
Expand All @@ -173,15 +180,11 @@ fn start_sidecar(
}

/// Creates a socket connection to communicate with the core process.
fn create_core_process_socket() -> Result<CursorSocket, CoreProcessCreationError> {
fn create_core_process_socket(socket_path: &str) -> Result<CursorSocket, CoreProcessCreationError> {
let max_tries = 10;
let mut tries = 0;
loop {
let temp_dir = std::env::temp_dir();

let socket_name = std::env::var("CORE_SOCKET_NAME").unwrap_or("core-socket".to_string());
let socket_path = format!("{}/{socket_name}", temp_dir.display());
match CursorSocket::new(&socket_path) {
match CursorSocket::new(socket_path) {
Ok(socket) => return Ok(socket),
Err(_) => {
log::debug!(
Expand Down Expand Up @@ -209,6 +212,7 @@ async fn send_ping(mut socket: CursorSocket) {
let res = socket.send_message(Message::Ping);
if let Err(e) = res {
log::error!("Failed to send ping: {e:?}");
sentry_utils::upload_logs_event("Failed to send ping".to_string());
break;
}
std::thread::sleep(std::time::Duration::from_secs(
Expand Down Expand Up @@ -242,9 +246,13 @@ pub fn create_core_process(
}
log::info!("create_core_process: resources_dir: {resources_dir:?}");

let (rx, core_process) = start_sidecar(app, &resources_dir);
let tmp_dir = std::env::temp_dir();
let socket_name = format!("core-socket-{}", create_random_suffix());
let socket_path = format!("{}/{socket_name}", tmp_dir.display());

let (rx, core_process) = start_sidecar(app, &resources_dir, &socket_path);
tauri::async_runtime::spawn(show_stdout(rx, app.clone()));
let socket = create_core_process_socket()?;
let socket = create_core_process_socket(&socket_path)?;
let socket_clone = socket.duplicate().unwrap();
tauri::async_runtime::spawn(send_ping(socket_clone));
Ok((
Expand Down Expand Up @@ -529,3 +537,11 @@ pub fn set_window_corner_radius(window: &tauri::WebviewWindow, radius: f64) {
})
.unwrap();
}

fn create_random_suffix() -> String {
rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(10)
.map(char::from)
.collect()
}
9 changes: 8 additions & 1 deletion tauri/src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,11 @@ fn main() {
},
));
}
let log_file_name = if cfg!(debug_assertions) {
Some("debug".to_string())
} else {
None
};
let app = app
.plugin(tauri_plugin_autostart::init(
MacosLauncher::LaunchAgent,
Expand All @@ -628,7 +633,9 @@ fn main() {
.plugin(
tauri_plugin_log::Builder::default()
.targets([
Target::new(TargetKind::LogDir { file_name: None }),
Target::new(TargetKind::LogDir {
file_name: log_file_name,
}),
Target::new(TargetKind::Stdout),
Target::new(TargetKind::Webview),
])
Expand Down
Loading