Creating a cross-platform desktop application with Rust and Tauri that executes a shell command and streams its output to the frontend involves several steps. Below is a comprehensive guide to building this application, including code snippets for both the Rust backend and the frontend.
Prerequisites
-
Rust installed on your system. If not, install it from here.
-
Node.js and npm installed. Download from here.
-
Tauri CLI installed globally:
cargo install tauri-cli
Step 1: Create a New Tauri Project
We'll start by creating a new Tauri project using the Tauri CLI.
cargo create-tauri-app my_app
Alternatively, you can manually set up a Tauri project. Here's how:
-
Initialize a new frontend project (you can use any frontend framework or plain HTML/JS):
mkdir my_app
cd my_app
npm init -y
-
Install Tauri dependencies:
npm install @tauri-apps/api
-
Initialize Tauri in the project:
npx tauri init
Step 2: Set Up the Frontend
We'll create a simple HTML file with a button to start the command and a textarea to display the output.
File: index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Tauri Command Runner</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
#output {
width: 100%;
height: 400px;
margin-top: 20px;
font-family: monospace;
}
button {
padding: 10px 20px;
font-size: 16px;
}
</style>
<!-- Include Tauri API -->
<script src="https://unpkg.com/@tauri-apps/api@latest/dist/tauri.js"></script>
</head>
<body>
<h1>Tauri Command Runner</h1>
<button id="runBtn">Run Ping Command</button>
<textarea id="output" readonly></textarea>
<script>
const { invoke, listen } = window.__TAURI__.event;
document.getElementById('runBtn').addEventListener('click', () => {
// Clear previous output
document.getElementById('output').value = '';
// Invoke the Rust command
invoke('run_command');
});
// Listen for the 'command-output' event from Rust
listen('command-output', event => {
const outputArea = document.getElementById('output');
outputArea.value += event.payload + '\n';
outputArea.scrollTop = outputArea.scrollHeight;
});
</script>
</body>
</html>
Explanation:
- We include the Tauri API to interact with the backend.
- The button with
id="runBtn" triggers the command execution.
- The
textarea with id="output" displays the command output.
- We use the
invoke function to call the Rust command run_command.
- We set up an event listener for
command-output to receive output lines from the backend.
Step 3: Configure Tauri
Ensure Tauri is configured to serve your index.html file.
File: src-tauri/tauri.conf.json
Make sure the distDir and devPath point to your frontend files:
{
"build": {
"distDir": "../",
"devPath": "../"
},
"tauri": {
// ... other configurations
}
}
Step 4: Implement the Rust Backend
We'll write a Rust command that executes ping 8.8.8.8 and streams its output to the frontend.
File: src-tauri/src/main.rs
#![cfg_attr(
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
)]
use std::{
io::{BufRead, BufReader},
process::{Command, Stdio},
};
use tauri::{Manager, Window};
// Define the command that will be callable from the frontend
#[tauri::command]
fn run_command(window: Window) {
// Spawn a new thread to run the command asynchronously
std::thread::spawn(move || {
// Start the ping command
let mut cmd = if cfg!(target_os = "windows") {
Command::new("ping")
.args(&["8.8.8.8"])
.stdout(Stdio::piped())
.spawn()
.expect("Failed to spawn command")
} else {
Command::new("ping")
.args(&["-c", "5", "8.8.8.8"]) // Adjust arguments for Unix
.stdout(Stdio::piped())
.spawn()
.expect("Failed to spawn command")
};
// If we can get the stdout, read it line by line
if let Some(stdout) = cmd.stdout.take() {
let reader = BufReader::new(stdout);
for line in reader.lines() {
match line {
Ok(line) => {
// Emit the line to the frontend
window
.emit("command-output", line)
.unwrap_or_else(|e| eprintln!("Failed to emit event: {}", e));
}
Err(err) => {
eprintln!("Error reading line: {}", err);
}
}
}
} else {
eprintln!("Failed to capture stdout");
}
// Wait for the command to finish
cmd.wait().expect("Command wasn't running");
});
}
fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![run_command])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
Explanation:
- We define a Tauri command
run_command that can be invoked from the frontend.
- The command runs in a new thread to avoid blocking the main thread.
- We use
Command::new to start the ping command. Note that the arguments differ between Windows and Unix-like systems:
- On Windows,
ping by default sends 4 echo requests.
- On Unix-like systems, we use
-c 5 to send 5 packets.
- We capture the standard output (
stdout) of the command.
- We use a
BufReader to read the output line by line.
- We emit each line to the frontend using
window.emit("command-output", line).
- We handle potential errors gracefully, printing them to
stderr.
Step 5: Run the Application
In the terminal, navigate to your project directory and run:
npm install
Then, start the Tauri application:
npm run tauri dev
Note: If you don't have a package.json with the Tauri scripts, you can run:
npx tauri dev
Step 6: Test the Application
When the application starts:
- Click the "Run Ping Command" button.
- You should see the output of the
ping command appear in the textarea below, updating in real-time.
Cross-Platform Considerations
Ensure that the command arguments are appropriate for the target operating system. The ping command differs between Windows and Unix-like systems. The provided Rust code handles this with a conditional compilation check using cfg!(target_os).
Security Considerations
-
Avoid Shell Injection: Be cautious with commands that incorporate user input. Using unvalidated input in command execution can lead to shell injection vulnerabilities. In this example, we're using a fixed command (ping 8.8.8.8), so it's safe.
-
Permissions: Ensure your application has the necessary permissions to execute system commands.
Additional Enhancements
Custom Commands
You can modify the run_command function to accept parameters from the frontend:
Frontend JavaScript:
invoke('run_command', { command: 'ping', args: ['-c', '5', '8.8.4.4'] });
Rust Backend:
#[tauri::command]
fn run_command(window: Window, command: String, args: Vec<String>) {
// ... Use 'command' and 'args' to run the process
}
Security Note: If you allow custom commands, validate and sanitize the input to prevent security risks.
Stop Command Execution
Implement a way to terminate the running command from the frontend.
Rust Backend Modification:
Maintain a HashMap of running processes and provide a command to kill them.
Conclusion
You've now created a cross-platform desktop application using Rust and Tauri that executes a shell command and streams its output live to the frontend. This setup can be extended to execute other commands or to build more complex applications that interact with system processes.
References