async fn check_server_connection(client: &Client, url: &str) -> Result<(), Box> {
let response = client.get(url).send().await?;
if response.status().is_success() {
Ok(())
} else {
Err("Failed to connect to the server".into())
}
}
#[tauri::command]
pub async fn start_downloads(app_handle: AppHandle) -> Result<(), String> {
let exe_dir = get_exe_dir();
let patch_file_path = exe_dir.join("patch.json");
let download_dir = exe_dir.join("patchs");
code
if !download_dir.exists() {
tokio_fs::create_dir_all(&download_dir).await.map_err(|e| e.to_string())?;
}
let patches = read_patch_file(&patch_file_path).await.map_err(|e| e.to_string())?;
let client = Client::new();
let total_files = patches.len();
app_handle.emit("download_message", DownloadMessage {
message: "Conectando ao servidor...".to_string(),
}).map_err(|e| e.to_string())?;
let server_url = "https://hil-speed.hetzner.com/";
if let Err(err) = check_server_connection(&client, server_url).await {
app_handle.emit("download_message", DownloadMessage {
message: format!("Erro ao conectar ao servidor: {}", err),
}).map_err(|e| e.to_string())?;
return Err(format!("Erro ao conectar ao servidor: {}", err));
}
app_handle.emit("download_message", DownloadMessage {
message: "Conexão estabelecida com sucesso. Iniciando download...".to_string(),
}).map_err(|e| e.to_string())?;
// Executando downloads sequencialmente
for (current_file, entry) in patches.into_iter().enumerate() {
let current_file = current_file + 1;
if let Err(err) = download_file(&app_handle, &client, entry, &download_dir, current_file, total_files).await {
eprintln!("Erro ao baixar arquivo: {}", err);
app_handle.emit("download_message", DownloadMessage {
message: format!("Erro ao baixar arquivo: {}", err),
}).map_err(|e| e.to_string())?;
}
}
Ok(())
}
As mensagens dentro do while some estão gerando lag gráficos, como posso mostrar mensagens em tempo real e evitar o uso de lag gráficos ?
You're experiencing graphical lag because you're emitting events to the frontend on every chunk of data received during the download process. If the chunks are small and numerous, this results in a flood of events sent to the frontend, overwhelming it and causing the UI to lag.
To fix this issue, you need to limit the rate at which you emit events to the frontend. Instead of emitting an event on every chunk, you can emit events at regular intervals (e.g., every 500 milliseconds). This way, you reduce the number of events sent to the frontend, preventing it from lagging, while still providing real-time updates.
Here's how you can modify your download_file function to emit events at regular intervals:
rust
use std::time::{Duration, Instant};
async fn download_file(
app_handle: &AppHandle,
client: &Client,
entry: PatchEntry,
download_dir: &Path,
current_file: usize,
total_files: usize,
) -> Result<(), Box<dyn std::error::Error>> {
let url = format!("https://hil-speed.hetzner.com/{}", entry.file_name);
let file_path = download_dir.join(&entry.file_name);
let mut response = client.get(&url).send().await?;
let total_bytes = response.content_length().unwrap_or(0);
let mut file = tokio_fs::OpenOptions::new()
.write(true)
.create(true)
.open(file_path)
.await?;
let mut downloaded_bytes = 0;
let start_time = Instant::now();
// Variables to control the emission rate
let mut last_emit_time = Instant::now();
let emit_interval = Duration::from_millis(500); // Change this value as needed
app_handle.emit("download_message", DownloadMessage { message: "Baixando".to_string() })?;
while let Some(chunk) = response.chunk().await? {
file.write_all(&chunk).await?;
downloaded_bytes += chunk.len() as u64;
let now = Instant::now();
// Only emit updates if the specified interval has passed
if now.duration_since(last_emit_time) >= emit_interval {
let elapsed_time = now.duration_since(start_time).as_secs_f64();
let speed = if elapsed_time > 0.0 {
downloaded_bytes as f64 / elapsed_time
} else {
0.0
};
app_handle.emit("download_info", DownloadInfo {
current_file,
total_files,
file_name: entry.file_name.clone(),
downloaded_bytes,
total_bytes,
})?;
app_handle.emit("download_speed", speed)?;
// Update the last emit time
last_emit_time = now;
}
}
// Emit final update after download completes
let final_elapsed_time = Instant::now().duration_since(start_time).as_secs_f64();
let final_speed = if final_elapsed_time > 0.0 {
downloaded_bytes as f64 / final_elapsed_time
} else {
0.0
};
app_handle.emit("download_info", DownloadInfo {
current_file,
total_files,
file_name: entry.file_name.clone(),
downloaded_bytes,
total_bytes,
})?;
app_handle.emit("download_speed", final_speed)?;
app_handle.emit("download_message", DownloadMessage { message: "Download concluído".to_string() })?;
Ok(())
}
Explanation:
Introducing a Timer:
We use last_emit_time to keep track of the last time an event was emitted.
emit_interval defines how often we emit events (every 500 milliseconds in this example).
Emitting Events at Intervals:
Inside the loop, we check if the time since last_emit_time is greater than or equal to emit_interval.
If it is, we emit the download_info and download_speed events and update last_emit_time.
Final Update After Download Completes:
After the loop finishes, we emit a final update to ensure the frontend has the latest information.
Benefits:
Reduced Event Flooding:
By controlling the emission rate, we prevent the frontend from being overwhelmed by too many events.
Smooth UI Updates:
The frontend receives updates at a steady rate, improving user experience without lag.
Adjusting the Emit Interval:
You can adjust the emit_interval value based on your needs.
A smaller interval (e.g., 200 milliseconds) provides more frequent updates but may risk reintroducing lag if too low.
A larger interval (e.g., 1000 milliseconds) reduces the number of updates but might make the progress bar feel less responsive.
Handling Large Files and Chunk Sizes:
If you're dealing with very large files or very small chunks, you might need to adjust the interval or implement additional logic to emit updates when a certain amount of data has been downloaded.
Optimizing Frontend Handling:
Debouncing in Frontend:
Alternatively, you could implement debouncing or throttling on the frontend side to handle rapid events more gracefully.
Efficient Rendering:
Ensure that your frontend efficiently updates UI elements and avoids heavy computations or re-renders on each update.
Example of Emitting After a Certain Amount of Data:
If you prefer to emit events after a certain amount of data is downloaded (e.g., every 1 MB), you can modify the code as follows:
rust
let mut last_emitted_bytes = 0;
let emit_threshold = 1_000_000; // 1 MB in bytes
while let Some(chunk) = response.chunk().await? {
file.write_all(&chunk).await?;
downloaded_bytes += chunk.len() as u64;
if downloaded_bytes - last_emitted_bytes >= emit_threshold {
let elapsed_time = Instant::now().duration_since(start_time).as_secs_f64();
let speed = if elapsed_time > 0.0 {
downloaded_bytes as f64 / elapsed_time
} else {
0.0
};
app_handle.emit("download_info", DownloadInfo {
current_file,
total_files,
file_name: entry.file_name.clone(),
downloaded_bytes,
total_bytes,
})?;
app_handle.emit("download_speed", speed)?;
last_emitted_bytes = downloaded_bytes;
}
}
Conclusion:
By limiting the frequency of events emitted to the frontend, you can provide real-time progress updates without causing graphical lag. Adjust the emission strategy based on your application's requirements to achieve the best balance between responsiveness and performance.