Skip to content

Commit 89e2783

Browse files
committed
add current
1 parent 126e0fe commit 89e2783

File tree

10 files changed

+229
-61
lines changed

10 files changed

+229
-61
lines changed

src-tauri/src/analyzer.rs

+32-11
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,36 @@
1-
use std::path::{Path, PathBuf};
1+
use crate::commands::{ProgressCallback, ProgressUpdate};
2+
use crate::serializer::Dataset;
23
use anyhow::anyhow;
4+
use std::path::{Path, PathBuf};
35
use tokio::fs::remove_file;
46
use tokio::process::Command;
5-
use crate::serializer::Dataset;
67

7-
8-
pub async fn analyze_all(deps_dir: &Path, data_dir: &Path, datasets: &Vec<Dataset>) -> anyhow::Result<Vec<(PathBuf, u64)>> {
8+
pub async fn analyze_all(
9+
deps_dir: &Path,
10+
data_dir: &Path,
11+
datasets: &Vec<Dataset>,
12+
progress_callback: &ProgressCallback,
13+
) -> anyhow::Result<Vec<(PathBuf, u64)>> {
914
let mut results = vec![];
1015

1116
for dataset in datasets {
1217
let result = analyze(deps_dir, data_dir, dataset).await?;
1318
results.push(result);
19+
progress_callback(ProgressUpdate::Increment { iterations: 1 });
1420
}
1521

1622
Ok(results)
1723
}
1824

19-
async fn analyze(deps_dir: &Path, data_dir: &Path, dataset: &Dataset) -> anyhow::Result<(PathBuf, u64)> {
25+
async fn analyze(
26+
deps_dir: &Path,
27+
data_dir: &Path,
28+
dataset: &Dataset,
29+
) -> anyhow::Result<(PathBuf, u64)> {
2030
let mut command = Command::new(deps_dir.join("SRM_Rate.exe")); // TODO: figure out lifetimes here
2131

22-
command.arg(dataset.heavy_water.to_str().unwrap())
32+
command
33+
.arg(dataset.heavy_water.to_str().unwrap())
2334
.arg(dataset.spreadsheet.to_str().unwrap());
2435

2536
let input_file_name = dataset.spreadsheet.file_stem().unwrap().to_str().unwrap();
@@ -29,12 +40,22 @@ async fn analyze(deps_dir: &Path, data_dir: &Path, dataset: &Dataset) -> anyhow:
2940
.await
3041
.map_err(|err| anyhow!(format!("Command couldn't run: {err}")))?;
3142

32-
remove_file(&dataset.heavy_water).await.map_err(|err| anyhow!(format!("Couldn't delete heavy water file: {err}")))?;
33-
remove_file(&dataset.spreadsheet).await.map_err(|err| anyhow!(format!("Couldn't delete spreadsheet file: {err}")))?;
43+
remove_file(&dataset.heavy_water)
44+
.await
45+
.map_err(|err| anyhow!(format!("Couldn't delete heavy water file: {err}")))?;
46+
remove_file(&dataset.spreadsheet)
47+
.await
48+
.map_err(|err| anyhow!(format!("Couldn't delete spreadsheet file: {err}")))?;
3449

3550
if output.status.success() {
36-
Ok((data_dir.join(format!("{input_file_name}.RateConst.csv")), dataset.samples_removed))
51+
Ok((
52+
data_dir.join(format!("{input_file_name}.RateConst.csv")),
53+
dataset.samples_removed,
54+
))
3755
} else {
38-
Err(anyhow!(format!("The command didn't complete successfully: {}", String::from_utf8_lossy(&output.stdout))))
56+
Err(anyhow!(format!(
57+
"The command didn't complete successfully: {}",
58+
String::from_utf8_lossy(&output.stderr)
59+
)))
3960
}
40-
}
61+
}

src-tauri/src/commands.rs

+73-34
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use std::path::Path;
33
use futures::future::join_all;
44
use reqwest::Client;
55
use tauri::api::dialog::blocking::FileDialogBuilder;
6+
use tauri::Manager;
67
use tokio::fs;
78
use tokio::fs::create_dir;
89
use crate::aggregator::aggregate;
@@ -14,35 +15,35 @@ use crate::processor::process_file;
1415
use crate::serializer::{serialize, serialize_calculations};
1516
use tokio::task::{JoinHandle, JoinSet};
1617

18+
pub enum ProgressUpdate {
19+
Set {
20+
iterations: usize,
21+
total_iterations: Option<usize>,
22+
},
23+
Increment {
24+
iterations: usize,
25+
},
26+
}
1727

18-
#[tauri::command]
19-
pub async fn install_dependencies(app_handle: tauri::AppHandle) -> Result<(), String> {
20-
let dependencies_dir = app_handle
21-
.path_resolver()
22-
.app_local_data_dir()
23-
.unwrap()
24-
.join("dependencies");
25-
26-
if fs::try_exists(&dependencies_dir).await.unwrap() == true {
27-
fs::remove_dir_all(&dependencies_dir)
28-
.await
29-
.map_err(|err| format!("Failed to remove existing dependencies: {err}"))?;
30-
}
28+
pub type ProgressCallback = Box<dyn Fn(ProgressUpdate) + Send + Sync>;
3129

32-
let client = Client::new();
33-
let response = client
34-
.get("https://github.com/rgsadygov/SRM_executables/archive/refs/heads/main.zip")
35-
.send()
36-
.await
37-
.map_err(|err| format!("Failed to download dependencies: {err}"))?
38-
.bytes()
39-
.await
40-
.unwrap();
30+
#[derive(Clone, serde::Serialize)]
31+
struct ProgressSetPayload {
32+
uuid: String,
33+
iterations: usize,
34+
total_iterations: Option<usize>,
35+
}
4136

42-
zip_extract::extract(Cursor::new(response), &dependencies_dir, true)
43-
.map_err(|err| format!("Failed to extract dependencies: {err}"))?;
37+
#[derive(Clone, serde::Serialize)]
38+
struct ProgressIncrementPayload {
39+
uuid: String,
40+
iterations: usize,
41+
}
4442

45-
Ok(())
43+
#[derive(Clone, serde::Serialize)]
44+
struct ErrorPayload {
45+
uuid: String,
46+
message: String,
4647
}
4748

4849
#[tauri::command]
@@ -54,7 +55,8 @@ pub async fn process_data(
5455
input_files: Vec<InputFile>,
5556
) -> Result<(), String> {
5657
// TODO: https://tauri.app/v1/guides/features/events/
57-
dbg!("is this running?");
58+
dbg!("Run");
59+
dbg!(&input_files);
5860

5961
let deps_path = match engine_type {
6062
EngineType::Single =>
@@ -64,26 +66,63 @@ pub async fn process_data(
6466
.resolve_resource("assets").unwrap().join("multi-timepoint-engine"),
6567
};
6668

69+
let window = app.get_window("main").unwrap();
6770
let mut tasks: Vec<JoinHandle<anyhow::Result<()>>> = vec![];
68-
dbg!("wtf");
69-
7071

7172
for input_file in input_files {
73+
dbg!("hellno");
7274
let deps_path = deps_path.clone();
75+
let window = window.clone();
76+
let input_uuid = input_file.uuid.clone();
7377

7478
let task = tokio::spawn(async move {
75-
process_file(
79+
let window2 = window.clone();
80+
let progress_callback: ProgressCallback = Box::new(move |update| {
81+
match update {
82+
ProgressUpdate::Set { iterations, total_iterations } => {
83+
let payload = ProgressSetPayload {
84+
uuid: input_uuid.clone(),
85+
iterations,
86+
total_iterations,
87+
};
88+
89+
window2.emit("progress-set", payload).unwrap();
90+
}
91+
ProgressUpdate::Increment { iterations } => {
92+
let payload = ProgressIncrementPayload {
93+
uuid: input_uuid.clone(),
94+
iterations,
95+
};
96+
97+
window2.emit("progress-update", payload).unwrap();
98+
}
99+
}
100+
});
101+
102+
let input_uuid = input_file.uuid.clone();
103+
104+
match process_file(
76105
&deps_path,
77106
should_remove_na_calculations,
78107
tolerance_multiplier,
79108
input_file,
80-
).await?;
81-
82-
dbg!("hello?");
83-
84-
Ok(())
109+
progress_callback,
110+
).await {
111+
Ok(()) => Ok(()),
112+
Err(err) => {
113+
dbg!(&err);
114+
let payload = ErrorPayload {
115+
uuid: input_uuid,
116+
message: err.to_string(),
117+
};
118+
window.emit("process-error", payload).unwrap();
119+
Err(err)
120+
}
121+
}
85122
});
86123

124+
dbg!("hello yes");
125+
87126
tasks.push(task);
88127
}
89128

src-tauri/src/main.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ mod lib;
1313
#[tokio::main]
1414
async fn main() {
1515
tauri::Builder::default()
16-
.invoke_handler(tauri::generate_handler![commands::install_dependencies, commands::process_data])
16+
.invoke_handler(tauri::generate_handler![commands::process_data])
1717
.run(tauri::generate_context!())
1818
.expect("error while running tauri application");
1919
}

src-tauri/src/processor.rs

+19-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use anyhow::anyhow;
33
use tokio::fs::create_dir;
44
use crate::aggregator::aggregate;
55
use crate::analyzer::analyze_all;
6+
use crate::commands::{ProgressCallback, ProgressUpdate};
67
use crate::grouper::{group_by_na_columns, group_by_peptides};
78
use crate::parser::{InputFile, parse};
89
use crate::serializer::{serialize, serialize_calculations};
@@ -12,7 +13,14 @@ pub async fn process_file(
1213
should_remove_na_calculations: bool,
1314
tolerance_multiplier: f64,
1415
input_file_path: InputFile,
16+
progress_callback: ProgressCallback,
1517
) -> anyhow::Result<()> {
18+
dbg!("Run 2");
19+
progress_callback(ProgressUpdate::Set {
20+
iterations: 0,
21+
total_iterations: Some(100),
22+
});
23+
1624
let temp_dir = tempfile::tempdir().map_err(|e| anyhow!(e.to_string()))?;
1725
let data_dir = temp_dir.path().join("data");
1826

@@ -28,6 +36,10 @@ pub async fn process_file(
2836
) = parse(input_file_path).await?;
2937

3038
let groups = group_by_na_columns(group_by_peptides(tolerance_multiplier, peptides));
39+
progress_callback(ProgressUpdate::Set {
40+
iterations: 0,
41+
total_iterations: Some(groups.len() * 2 + groups.len() / 10),
42+
});
3143

3244
let datasets = serialize(
3345
should_remove_na_calculations,
@@ -36,9 +48,10 @@ pub async fn process_file(
3648
mice,
3749
labels,
3850
groups,
51+
&progress_callback,
3952
).await.unwrap();
4053

41-
let calculations = analyze_all(&deps_dir, &data_dir, &datasets).await?;
54+
let calculations = analyze_all(&deps_dir, &data_dir, &datasets, &progress_callback).await?;
4255
let calculations = aggregate(&calculations).await.map_err(|e| anyhow!(e.to_string()))?;
4356

4457
let input_file_name = input_file_path
@@ -51,6 +64,11 @@ pub async fn process_file(
5164

5265
serialize_calculations(&file_path, &calculations)?;
5366

67+
progress_callback(ProgressUpdate::Set {
68+
iterations: 100,
69+
total_iterations: Some(100),
70+
});
71+
5472
temp_dir.close().map_err(|e| anyhow!(e.to_string()))?;
5573

5674
Ok(())

src-tauri/src/serializer.rs

+6-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use csv::Writer;
55
use tokio::fs::File;
66
use tokio::io::AsyncWriteExt;
77
use crate::aggregator::Calculation;
8-
8+
use crate::commands::{ProgressCallback, ProgressUpdate};
99
use crate::grouper::NAGroup;
1010
use crate::parser::{Day, Label, Mouse, Peptide};
1111

@@ -24,6 +24,7 @@ pub async fn serialize(
2424
mice: Vec<Mouse>,
2525
labels: Vec<Label>,
2626
groups: Vec<NAGroup>,
27+
progress_callback: &ProgressCallback,
2728
) -> anyhow::Result<Vec<Dataset>> {
2829
let mut datasets = vec![];
2930

@@ -55,6 +56,10 @@ pub async fn serialize(
5556
heavy_water,
5657
samples_removed: columns_removed,
5758
});
59+
60+
progress_callback(ProgressUpdate::Increment {
61+
iterations: 1,
62+
});
5863
}
5964

6065
Ok(datasets)

src/lib/components/interfaces/dashboard/InputData.svelte

+12-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<script lang="ts">
2-
import { DocumentChartBar, Icon, XMark } from 'svelte-hero-icons'
2+
import { DocumentChartBar, ExclamationCircle, Icon, XMark } from 'svelte-hero-icons'
33
import type { InputFile } from '$lib/types/form'
44
import { createEventDispatcher } from 'svelte'
55
@@ -12,8 +12,17 @@
1212
</script>
1313

1414
<div class="flex items-center flex-nowrap pl-5 py-3 pr-4 w-full bg-muted first:rounded-t-md last:rounded-b-md">
15-
<Icon src={DocumentChartBar} solid class="w-6 h-6 mr-2" />
16-
<span class="truncate">{inputFile.path.name}</span>
15+
{#if inputFile.errors}
16+
<Icon src={ExclamationCircle} solid class="w-6 h-6 mr-2 text-destructive" />
17+
{:else}
18+
<Icon src={DocumentChartBar} solid class="w-6 h-6 mr-2" />
19+
{/if}
20+
<div>
21+
<p class="truncate">{inputFile.path.name}</p>
22+
{#if inputFile.errors}
23+
<p class="truncate text-xs text-muted-foreground">{inputFile.errors}</p>
24+
{/if}
25+
</div>
1726
<div class="grow"></div>
1827
<button on:click={() => dispatch('delete')} class="h-full p-1 rounded-md hover:bg-card">
1928
<Icon src={XMark} class="w-5 h-5" />

0 commit comments

Comments
 (0)