Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: VRServer gracefully shutdown #632

Merged
merged 20 commits into from
Apr 11, 2023
Merged
Show file tree
Hide file tree
Changes from 14 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
47 changes: 39 additions & 8 deletions gui/src-tauri/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
#![cfg_attr(all(not(debug_assertions), windows), windows_subsystem = "windows")]
use std::env;
use std::{env, thread};
use std::ffi::{OsStr, OsString};
use std::io::Write;
#[cfg(windows)]
use std::os::windows::process::CommandExt;
use std::panic;
use std::path::{Path, PathBuf};
use std::process::{Child, Stdio};
use std::time::Duration;

use clap::Parser;
use const_format::concatcp;
use rand::{seq::SliceRandom, thread_rng};
use shadow_rs::shadow;
use tauri::api::process::Command;
use tauri::Manager;
use tauri::api::process::{Command, CommandChild};
use tauri::{RunEvent, Manager};

#[cfg(windows)]
use tauri::WindowEvent;
use tempfile::Builder;
Expand All @@ -31,6 +33,7 @@ static POSSIBLE_TITLES: &[&str] = &[
"never gonna let you down",
"uwu sowwy",
];

shadow!(build);
// Tauri has a way to return the package.json version, but it's not a constant...
const VERSION: &str = if build::TAG.is_empty() {
Expand Down Expand Up @@ -173,6 +176,7 @@ fn main() {
}

// Spawn server process
let mut backend = Option::<CommandChild>::default();
let run_path = get_launch_path(cli);

let stdout_recv = if let Some(p) = run_path {
Expand All @@ -190,18 +194,19 @@ fn main() {
};

log::info!("Using Java binary: {:?}", java_bin);
let (recv, _child) = Command::new(java_bin.to_str().unwrap())
let (recv, child) = Command::new(java_bin.to_str().unwrap())
.current_dir(p)
.args(["-Xmx512M", "-jar", "slimevr.jar", "--no-gui"])
.spawn()
.expect("Unable to start the server jar");
_ = backend.insert(child);
ImUrX marked this conversation as resolved.
Show resolved Hide resolved
Some(recv)
} else {
log::warn!("No server found. We will not start the server.");
None
};

let run_result = tauri::Builder::default()
let build_result = tauri::Builder::default()
.plugin(tauri_plugin_window_state::Builder::default().build())
.setup(|app| {
if let Some(mut recv) = stdout_recv {
Expand Down Expand Up @@ -237,8 +242,23 @@ fn main() {
WindowEvent::Resized(_) => std::thread::sleep(std::time::Duration::from_nanos(1)),
_ => (),
})
.run(tauri::generate_context!());
match run_result {
.build(tauri::generate_context!());
match build_result {
Ok(app) => {
app.run(move |_app_handle, event| match event {
RunEvent::ExitRequested { .. } => {
if let Some(mut child) = backend.take() {
let write_result = child.write(b"exit\n");
match write_result {
Ok(()) => log::info!("send exit to backend"),
Err(_) => log::info!("fail to send exit to backend"),
}
thread::sleep(Duration::from_millis(10000));
marcozzxx810 marked this conversation as resolved.
Show resolved Hide resolved
}
}
_ => {}
});
}
#[cfg(windows)]
// Often triggered when the user doesn't have webview2 installed
Err(tauri::Error::Runtime(tauri_runtime::Error::CreateWebview(error))) => {
Expand All @@ -258,7 +278,18 @@ fn main() {
}
return;
}
_ => run_result.expect("error while running tauri application"),
Err(error) => {
log::error!("Error {}", error);
use tauri::api::dialog::{
blocking::MessageDialogBuilder, MessageDialogButtons, MessageDialogKind,
};

MessageDialogBuilder::new("SlimeVR", "Some unknown Error occurs: ".to_owned()+ &error.to_string())
.buttons(MessageDialogButtons::OkCancel)
.kind(MessageDialogKind::Error)
.show();
return;
}
}
}

Expand Down
2 changes: 2 additions & 0 deletions server/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -168,3 +168,5 @@ configure<com.diffplug.gradle.spotless.SpotlessExtension> {
eclipse().configFile("spotless.xml")
}
}

tasks.getByName("run", JavaExec::class) { standardInput = System.`in` }
27 changes: 27 additions & 0 deletions server/src/main/java/dev/slimevr/CommandServer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package dev.slimevr;

import java.util.Scanner;


public class CommandServer extends Thread {
private VRServer vrServer;

public CommandServer(VRServer vrServer) {
this.vrServer = vrServer;
}

public void run() {
Scanner scan = new Scanner(System.in);
while (true) {
if (scan.hasNext()) {
String command = scan.nextLine();
if (command.equals("exit")) {
this.vrServer.interrupt();
break;
}
}
}
scan.close();
}

}
24 changes: 10 additions & 14 deletions server/src/main/java/dev/slimevr/Main.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ val VERSION =
(GIT_VERSION_TAG.ifEmpty { GIT_COMMIT_HASH }) +
if (GIT_CLEAN) "" else "-dirty"
var vrServer: VRServer? = null
var commandServer: CommandServer? = null

fun main(args: Array<String>) {
System.setProperty("awt.useSystemAAFontSettings", "on")
Expand Down Expand Up @@ -63,6 +64,7 @@ fun main(args: Array<String>) {
"SlimeVR: Java Runtime Mismatch",
JOptionPane.ERROR_MESSAGE
)
LogManager.closeLogger()
return
}
try {
Expand All @@ -84,27 +86,21 @@ fun main(args: Array<String>) {
"SlimeVR: Ports are busy",
JOptionPane.ERROR_MESSAGE
)
LogManager.closeLogger()
return
}
try {
vrServer = VRServer()
vrServer!!.start()
Keybinding(vrServer)
commandServer = CommandServer(vrServer)
commandServer!!.start()
vrServer!!.join()
commandServer!!.join()
exitProcess(0)
LogManager.closeLogger()
} catch (e: Throwable) {
e.printStackTrace()
try {
Thread.sleep(2000L)
} catch (e2: InterruptedException) {
e.printStackTrace()
}
exitProcess(1) // Exit in case error happened on init and window
// not appeared, but some thread
// started
} finally {
try {
Thread.sleep(2000L)
} catch (e: InterruptedException) {
e.printStackTrace()
}
exitProcess(1)
}
}
5 changes: 4 additions & 1 deletion server/src/main/java/dev/slimevr/VRServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,10 @@ public void run() {
// final long time = System.currentTimeMillis() - start;
try {
Thread.sleep(1); // 1000Hz
} catch (InterruptedException ignored) {}
} catch (InterruptedException error) {
LogManager.info("VRServer thread interrupted");
break;
}
}
}

Expand Down
7 changes: 7 additions & 0 deletions server/src/main/java/io/eiren/util/logging/LogManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,13 @@ public static void log(Level level, String message, Throwable t) {
log.log(level, message, t);
}

public static void closeLogger() {
for (Handler handler : global.getHandlers()) {
handler.close();
removeHandler(handler);
}
}

static {
boolean hasConsoleHandler = false;
for (Handler h : global.getHandlers()) {
Expand Down