fix windows build continued

This commit is contained in:
vcoppe committed 2026-11-01 16:52:36 +01:00
1 parent 17b5c1d567
commit 77c542d9aa
11 files changed
+957 -907

No files matched your search

+6 -9
View File
@@ -3,20 +3,20 @@
mod bytes;
mod commands;
mod state;
mod store;
mod workspace;
pub mod state;
pub mod store;
pub mod workspace;
use commands::*;
use tauri::{Emitter, Manager};
/// The engine of the app: each file has its own history, so that undoing only concerns the
/// selected files, and opening or closing a file is not something to undo.
pub(crate) type Engine = gpx_engine::Engine<gpx_engine::PerFileHistory>;
pub type Engine = gpx_engine::Engine<gpx_engine::PerFileHistory>;
/// The GPX files among what the system gave to the app (the arguments of the command line, when a
/// file is opened with it).
fn gpx_paths(arguments: impl IntoIterator<Item = String>) -> Vec<std::path::PathBuf> {
pub fn gpx_paths(arguments: impl IntoIterator<Item = String>) -> Vec<std::path::PathBuf> {
arguments
.into_iter()
.map(std::path::PathBuf::from)
@@ -108,7 +108,7 @@ fn menu<R: tauri::Runtime>(app: &tauri::AppHandle<R>) -> tauri::Result<tauri::me
}
/// Gives the builder the commands that reach the engine (which it has to be given as `AppState`).
fn register_commands<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri::Builder<R> {
pub fn register_commands<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri::Builder<R> {
builder.invoke_handler(tauri::generate_handler![
// selection
selection::select,
@@ -234,6 +234,3 @@ fn register_commands<R: tauri::Runtime>(builder: tauri::Builder<R>) -> tauri::Bu
system::reveal_path,
])
}
#[cfg(test)]
mod tests;
-7
View File
@@ -280,13 +280,6 @@ impl AppState {
})
}
/// An engine that keeps its data in a directory of its own, and has nobody to tell.
#[cfg(test)]
pub fn temporary() -> Self {
let directory = std::env::temp_dir().join(format!("gpx-studio-{}", uuid::Uuid::new_v4()));
Self::open(directory, Arc::new(|_, _| {})).expect("the storage can be opened")
}
/// Opens files that the system gave to the app, see `Core::open_external`.
pub fn open_external(&self, paths: Vec<PathBuf>) {
self.core(move |core| core.open_external(&paths));
-66
View File
@@ -217,69 +217,3 @@ impl Storage for FileStorage {
Ok(())
}
}
#[cfg(test)]
mod tests {
use crate::Engine;
use gpx_engine::{Action, Command, Load, LoadFiles, Persister};
use super::*;
fn directory() -> PathBuf {
std::env::temp_dir().join(format!("gpx-studio-store-{}", Uuid::new_v4()))
}
fn engine_with_a_file() -> Engine {
let mut engine = Engine::default();
let data = std::fs::read("../gpx-rs/data/simple.gpx").unwrap();
engine
.execute(Action::Edit(Command::LoadFiles(LoadFiles {
files: vec![Load {
data: &data,
name: "simple",
}],
})))
.unwrap();
engine
}
#[test]
fn keeps_the_files_and_the_settings_between_sessions() {
let root = directory();
let engine = engine_with_a_file();
let order = engine.order().to_vec();
let storage = FileStorage::open(&root).unwrap();
pollster::block_on(Persister::default().save(&storage, engine.snapshot())).unwrap();
pollster::block_on(storage.put_setting("units", "\"metric\"")).unwrap();
// another session
let storage = FileStorage::open(&root).unwrap();
let restored = pollster::block_on(Persister::default().restore(&storage)).unwrap();
let mut other = Engine::default();
other.restore(restored);
assert_eq!(other.order(), order);
assert_eq!(
other.file_statistics(&order[0]).unwrap().total_distance,
engine.file_statistics(&order[0]).unwrap().total_distance
);
assert_eq!(storage.settings()["units"], "\"metric\"");
fs::remove_dir_all(root).unwrap();
}
#[test]
fn refuses_a_commit_that_is_not_based_on_the_head() {
let root = directory();
let storage = FileStorage::open(&root).unwrap();
let batch = Batch {
order: Some(vec![]),
..Default::default()
};
assert_eq!(pollster::block_on(storage.commit(&batch)), Ok(Revision(1)));
assert_eq!(
pollster::block_on(storage.commit(&batch)),
Err(CommitError::Stale { head: Revision(1) })
);
fs::remove_dir_all(root).unwrap();
}
}
-787
View File
@@ -1,787 +0,0 @@
//! The commands, called the way the frontend calls them (through the IPC of Tauri), on the sample
//! files of the engine.
use serde_json::{Value, json};
use tauri::test::{INVOKE_KEY, get_ipc_response, mock_builder, mock_context, noop_assets};
use tauri::webview::InvokeRequest;
use tauri::{WebviewWindow, ipc::CallbackFn, ipc::InvokeBody, ipc::InvokeResponseBody};
struct App(WebviewWindow<tauri::test::MockRuntime>);
impl App {
fn new() -> Self {
let app =
crate::register_commands(mock_builder().manage(crate::state::AppState::temporary()))
.build(mock_context(noop_assets()))
.unwrap();
let window = tauri::WebviewWindowBuilder::new(&app, "main", Default::default())
.build()
.unwrap();
// the app has to outlive its window
std::mem::forget(app);
Self(window)
}
fn request(
&self,
cmd: &str,
body: InvokeBody,
headers: tauri::http::HeaderMap,
) -> InvokeResponseBody {
get_ipc_response(
&self.0,
InvokeRequest {
cmd: cmd.into(),
callback: CallbackFn(0),
error: CallbackFn(1),
url: "tauri://localhost".parse().unwrap(),
body,
headers,
invoke_key: INVOKE_KEY.to_string(),
},
)
.unwrap_or_else(|error| panic!("{cmd} failed: {error}"))
}
fn call(&self, cmd: &str, args: Value) -> Value {
match self.request(cmd, InvokeBody::Json(args), Default::default()) {
InvokeResponseBody::Json(json) => serde_json::from_str(&json).unwrap(),
InvokeResponseBody::Raw(_) => panic!("{cmd} returned bytes"),
}
}
/// The error of a command that fails.
fn error(&self, cmd: &str, args: Value) -> Value {
let request = InvokeRequest {
cmd: cmd.into(),
callback: CallbackFn(0),
error: CallbackFn(1),
url: "tauri://localhost".parse().unwrap(),
body: InvokeBody::Json(args),
headers: Default::default(),
invoke_key: INVOKE_KEY.to_string(),
};
get_ipc_response(&self.0, request).expect_err(&format!("{cmd} did not fail"))
}
fn bytes(&self, cmd: &str, args: Value) -> Vec<u8> {
match self.request(cmd, InvokeBody::Json(args), Default::default()) {
InvokeResponseBody::Raw(bytes) => bytes,
InvokeResponseBody::Json(_) => panic!("{cmd} returned JSON"),
}
}
fn load(&self, names: &[&str]) -> Value {
let mut data = vec![];
let mut lengths = vec![];
for name in names {
let file = std::fs::read(format!("../gpx-rs/data/{name}.gpx")).unwrap();
lengths.push(file.len());
data.extend(file);
}
let header = |value: Value| value.to_string().replace('"', "%22").parse().unwrap();
let mut headers = tauri::http::HeaderMap::new();
headers.insert("lengths", header(json!(lengths)));
headers.insert("names", header(json!(names)));
match self.request("load_files", InvokeBody::Raw(data), headers) {
InvokeResponseBody::Json(json) => serde_json::from_str(&json).unwrap(),
InvokeResponseBody::Raw(_) => panic!("load_files returned bytes"),
}
}
}
fn f64s(bytes: &[u8]) -> Vec<f64> {
bytes
.as_chunks::<8>()
.0
.iter()
.map(|chunk| f64::from_le_bytes(*chunk))
.collect()
}
#[test]
fn loads_files_and_describes_them() {
let app = App::new();
let outcome = app.load(&["simple", "with_tracks"]);
assert_eq!(outcome["changed"], true);
assert_eq!(outcome["added"].as_array().unwrap().len(), 2);
assert!(outcome.get("error").is_none());
let order = app.call("file_order", json!({}));
let first = order[0].as_str().unwrap();
assert_eq!(
app.call("selection", json!({})),
json!({ "type": "file", "fileIds": [first] })
);
let structure = app.call("file_structure", json!({ "fileId": first }));
assert_eq!(structure["name"], "simple");
let segment = &structure["tracks"][0]["segments"][0];
let length = segment["length"].as_f64().unwrap() as usize;
assert!(length > 0);
// coordinates are little-endian doubles, lng and lat for each trackpoint
let coordinates =
f64s(&app.bytes("segment_coordinates", json!({ "segmentId": segment["id"] })));
assert_eq!(coordinates.len(), 2 * length);
let statistics = app.call("file_statistics", json!({ "fileId": first }));
assert!(statistics["totalDistance"].as_f64().unwrap() > 0.0);
assert!(
statistics["bounds"]["west"].as_f64().unwrap()
<= statistics["bounds"]["east"].as_f64().unwrap()
);
assert_eq!(
app.call(
"file_structure",
json!({ "fileId": "00000000-0000-0000-0000-000000000000" })
),
Value::Null
);
}
#[test]
fn reads_the_statistics_of_the_selection() {
let app = App::new();
app.load(&["simple"]);
let distance = f64s(&app.bytes("total_distance", json!({})));
assert!(distance.len() > 1);
assert_eq!(f64s(&app.bytes("lng", json!({}))).len(), distance.len());
assert!(
app.call("selection_statistics", json!({}))["totalDistance"]
.as_f64()
.unwrap()
> 0.0
);
// optional arrays start with a byte telling whether they are there
let hr = app.bytes("hr", json!({}));
assert_eq!(hr[0], 0);
// the slope segments are intervals of trackpoints
let starts = app.bytes("slope_segment_starts", json!({}));
let slopes = f64s(&app.bytes("slope_segment_slopes", json!({})));
assert_eq!(starts.len() / 4, slopes.len());
assert!(!slopes.is_empty() && slopes.len() < distance.len());
let point = app.call("selection_point", json!({ "index": 1 }));
assert!(point["slopeSegmentDistance"].is_number());
assert!(point.get("time").is_none());
assert_eq!(
app.call("selection_point", json!({ "index": distance.len() })),
Value::Null
);
assert!(
app.call("slice_statistics", json!({ "start": 1, "end": 3 }))["totalDistance"].is_number()
);
assert_eq!(
app.call("slice_statistics", json!({ "start": 0, "end": 100000 })),
Value::Null
);
app.load(&["with_hr"]);
app.call("select_all", json!({}));
let hr = app.bytes("hr", json!({}));
assert_eq!(hr[0], 1);
assert_eq!((hr.len() - 1) % 8, 0);
}
#[test]
fn edits_undoes_and_selects() {
let app = App::new();
let outcome = app.call(
"new_file",
json!({ "name": "route", "lng": 4.4, "lat": 50.8 }),
);
assert_eq!(outcome["changed"], true);
// each file has its own history, which starts when it appears
assert_eq!(app.call("can_undo", json!({})), false);
let id = app.call("file_order", json!({}))[0].clone();
let outcome = app.call("metadata", json!({ "name": "renamed", "desc": "" }));
assert_eq!(outcome["modified"], json!([id]));
assert_eq!(
app.call("file_structure", json!({ "fileId": id }))["name"],
"renamed"
);
let outcome = app.call("select", json!({ "fileIds": [], "mode": "replace" }));
assert_eq!(outcome["selectionChanged"], true);
assert_eq!(app.call("selection", json!({})), json!({ "type": "empty" }));
app.call("select", json!({ "fileIds": [id], "mode": "toggle" }));
assert_eq!(app.call("can_undo", json!({})), true);
app.call("undo", json!({}));
assert_eq!(
app.call("file_structure", json!({ "fileId": id }))["name"],
"route"
);
assert_eq!(app.call("can_redo", json!({})), true);
// creating the file is not something to undo
assert_eq!(app.call("can_undo", json!({})), false);
let outcome = app.call("undo", json!({}));
assert_eq!(outcome["changed"], false);
assert_eq!(app.call("file_order", json!({})), json!([id]));
// what cannot be done says why
let outcome = app.call("reverse", json!({}));
assert_eq!(outcome["changed"], false);
assert!(outcome["error"].is_string());
}
#[test]
fn moves_and_clipboard() {
let app = App::new();
app.load(&["simple", "with_tracks"]);
let ids = app.call("file_order", json!({}));
app.call("select", json!({ "fileIds": [ids[0]], "mode": "replace" }));
app.call("copy", json!({}));
assert_eq!(
app.call("clipboard", json!({})),
json!({ "type": "files", "ids": [ids[0]], "cut": false })
);
let outcome = app.call(
"move_elements",
json!({
"what": { "type": "file", "fileIds": [ids[0]] },
"to": { "type": "files", "index": 9007199254740991u64 },
}),
);
assert_eq!(outcome["orderChanged"], true);
assert_eq!(app.call("file_order", json!({})), json!([ids[1], ids[0]]));
}
#[test]
fn waypoints_exports_and_routing_revisions() {
let app = App::new();
app.call("new_file", json!({ "name": "file" }));
let outcome = app.call(
"new_waypoint",
json!({ "lng": 4.4, "lat": 50.8, "ele": 100, "name": "summit", "desc": "", "icon": "Summit", "link": "https://example.com" }),
);
assert_eq!(outcome["changed"], true);
let file = app.call("file_order", json!({}))[0].clone();
let waypoint =
app.call("file_structure", json!({ "fileId": file }))["waypoints"][0]["id"].clone();
let details = app.call(
"waypoint",
json!({ "fileId": file, "waypointId": waypoint }),
);
assert_eq!(details["name"], "summit");
assert_eq!(details["sym"], "Summit");
assert_eq!(details["links"][0]["href"], "https://example.com");
let exported = app.bytes(
"export_file",
json!({ "fileId": file, "time": true, "hr": true, "cad": true, "atemp": true, "power": true, "osm": true }),
);
assert_eq!(exported[0], 1);
assert!(
String::from_utf8(exported[1..].to_vec())
.unwrap()
.contains("<wpt")
);
assert_eq!(app.call("exportable_data", json!({ "fileIds": [file] })), 0);
let stale = app.call(
"route",
json!({
"revision": 12345, "start": 0, "end": 0,
"lng": [4.4], "lat": [50.8], "ele": [0],
"attributes": { "surface": { "starts": [0], "values": [0], "names": [] } },
"anchors": [],
}),
);
assert_eq!(stale["changed"], false);
assert!(stale["error"].as_str().unwrap().contains("routing buffers"));
}
#[test]
fn keeps_settings_for_the_session() {
let app = App::new();
app.call(
"set_setting",
json!({ "key": "units", "value": "\"metric\"" }),
);
assert_eq!(
app.call("open_storage", json!({}))["settings"]["units"],
"\"metric\""
);
app.call("delete_setting", json!({ "key": "units" }));
assert_eq!(app.call("open_storage", json!({}))["settings"], json!({}));
}
#[test]
fn the_files_are_still_there_in_the_next_session() {
use crate::state::AppState;
use gpx_engine::api;
let directory =
std::env::temp_dir().join(format!("gpx-studio-session-{}", uuid::Uuid::new_v4()));
let data = std::fs::read("../gpx-rs/data/simple.gpx").unwrap();
let first = AppState::open(&directory, std::sync::Arc::new(|_, _| {})).unwrap();
let lengths = [data.len()];
let names = ["simple".to_string()];
first.run(move |e| api::load_files(e, &data, &lengths, &names));
let order = first.read(api::file_order);
let second = AppState::open(&directory, std::sync::Arc::new(|_, _| {})).unwrap();
assert_eq!(second.read(api::file_order), order);
let outcome = second.read(api::Outcome::everything);
assert_eq!(
serde_json::to_value(&outcome).unwrap()["added"],
serde_json::json!(order)
);
std::fs::remove_dir_all(directory).unwrap();
}
#[test]
fn only_gpx_files_that_exist_are_taken_from_what_the_system_gives() {
let directory = std::env::temp_dir().join(format!("gpx-studio-args-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&directory).unwrap();
let track = directory.join("track.GPX");
std::fs::copy("../gpx-rs/data/simple.gpx", &track).unwrap();
let text = directory.join("notes.txt");
std::fs::write(&text, "x").unwrap();
let arguments = [
"--flag".to_string(),
track.to_string_lossy().into_owned(),
text.to_string_lossy().into_owned(),
directory.join("missing.gpx").to_string_lossy().into_owned(),
];
assert_eq!(crate::gpx_paths(arguments), [track]);
std::fs::remove_dir_all(directory).unwrap();
}
#[test]
fn a_file_opened_with_the_app_is_opened_selected_and_announced() {
use crate::state::AppState;
use gpx_engine::api;
use std::sync::{Arc, Mutex};
let directory = std::env::temp_dir().join(format!("gpx-studio-open-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&directory).unwrap();
let track = directory.join("track.gpx");
std::fs::copy("../gpx-rs/data/simple.gpx", &track).unwrap();
let events = Arc::new(Mutex::new(vec![]));
let sink = events.clone();
let state = AppState::open(
directory.join("store"),
Arc::new(move |name, payload| sink.lock().unwrap().push((name.to_string(), payload))),
)
.unwrap();
state.open_external(vec![track.clone()]);
// opening it again is a selection, not another file
state.open_external(vec![track]);
assert_eq!(state.read(api::file_order).len(), 1);
assert!(matches!(
state.read(api::selection),
api::Selection::File { .. }
));
let events = events.lock().unwrap();
let opened: Vec<_> = events
.iter()
.filter(|(name, _)| name == "files-opened")
.collect();
assert_eq!(opened.len(), 2);
assert_eq!(opened[0].1["added"].as_array().unwrap().len(), 1);
assert!(opened[1].1["added"].as_array().unwrap().is_empty());
assert!(events.iter().any(|(name, _)| name == "workspace-changed"));
std::fs::remove_dir_all(directory).unwrap();
}
#[test]
fn files_are_opened_closed_and_made_in_a_folder() {
let app = App::new();
let folder = std::env::temp_dir().join(format!("gpx-tests-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&folder).unwrap();
let path = folder.join("track.gpx");
std::fs::copy("../gpx-rs/data/simple.gpx", &path).unwrap();
// opened from the disk, clean
let outcome = app.call("open_paths", json!({ "paths": [path] }));
assert_eq!(outcome["added"].as_array().unwrap().len(), 1);
let id = outcome["added"][0].as_str().unwrap().to_string();
let state = app.call("workspace_state", json!({}));
assert_eq!(state["files"][&id]["dirty"], false);
assert!(state["files"][&id]["path"].is_string());
// a new file made in a folder is written there at once, so that the tree shows it
let created = app.call(
"new_file",
json!({ "name": "route", "lng": 4.4, "lat": 50.8, "folder": folder }),
);
let new_id = created["added"][0].as_str().unwrap().to_string();
let state = app.call("workspace_state", json!({}));
assert_eq!(state["files"][&new_id]["dirty"], false);
assert!(state["files"][&new_id]["path"].is_string());
assert!(folder.join("route.gpx").exists());
// the tree needs an open folder
assert_eq!(app.call("list_folder", json!({})), json!([]));
// closing: what is saved goes, what has edits stays unless it is discarded
app.call("select", json!({ "fileIds": [new_id], "mode": "replace" }));
app.call("style", json!({ "color": "#ff0000" }));
app.call("close_files", json!({ "fileIds": [id, new_id] }));
assert_eq!(app.call("file_order", json!({})), json!([new_id]));
app.call(
"close_files",
json!({ "fileIds": [new_id], "unsaved": "discard" }),
);
assert_eq!(app.call("file_order", json!({})), json!([]));
std::fs::remove_dir_all(folder).unwrap();
}
/// A file that is open from outside of any folder follows the disk too.
#[test]
fn a_file_outside_the_open_folder_is_read_again_when_the_disk_changes() {
use std::sync::mpsc;
use std::time::Duration;
let (events, received) = mpsc::channel();
let directory = std::env::temp_dir().join(format!("gpx-store-{}", uuid::Uuid::new_v4()));
let state = crate::state::AppState::open(
directory.clone(),
std::sync::Arc::new(move |name, _| {
let _ = events.send(name.to_string());
}),
)
.unwrap();
let folder = std::env::temp_dir().join(format!("gpx-tests-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&folder).unwrap();
let path = folder.join("track.gpx");
std::fs::copy("../gpx-rs/data/simple.gpx", &path).unwrap();
let opened = path.clone();
let id = state.core(move |core| {
let outcome = core.workspace.open_files(&mut core.engine, &[opened], true);
core.keep_workspace();
outcome.added()[0].clone()
});
let id = uuid::Uuid::parse_str(&id).unwrap();
// the name comes from the path, which does not change: the content does
let signature = |state: &crate::state::AppState| {
state.core(move |core| crate::workspace::signature(&core.engine, id))
};
let before = signature(&state);
std::fs::copy("../gpx-rs/data/with_time.gpx", &path).unwrap();
// the debounced watcher tells the frontend that the engine changed
let mut changed = false;
while let Ok(event) = received.recv_timeout(Duration::from_secs(10)) {
if event == "engine-changed" {
changed = true;
break;
}
}
assert!(changed, "the file was not read again");
assert_ne!(signature(&state), before);
std::fs::remove_dir_all(folder).unwrap();
std::fs::remove_dir_all(directory).unwrap();
}
#[test]
fn files_made_from_a_file_of_the_open_folder_are_written_next_to_it_at_once() {
let state = crate::state::AppState::temporary();
let folder = std::env::temp_dir().join(format!("gpx-tests-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(folder.join("sub")).unwrap();
std::fs::copy("../gpx-rs/data/simple.gpx", folder.join("sub/track.gpx")).unwrap();
let sub = folder.join("sub");
let (copied, new_file) = state.core(move |core| {
core.workspace.open_folder(&mut core.engine, &folder, false);
let opened = core
.workspace
.open_files(&mut core.engine, &[sub.join("track.gpx")], true);
core.keep_workspace();
assert_eq!(opened.added().len(), 1);
let copy = core.creating(None, false, gpx_engine::api::duplicate);
let fresh = core.creating(None, true, |e| {
gpx_engine::api::new_file(e, "fresh", None, None, None, false)
});
// a copy of the file goes next to it, a new file with nothing selected in the selection
// of the file that was just made
(copy, fresh)
});
let sub = std::env::temp_dir();
let _ = sub;
assert_eq!(copied.added().len(), 1);
assert_eq!(new_file.added().len(), 1);
let status = state.core(|core| core.workspace_state());
assert!(status.files.values().all(|file| !file.dirty));
let paths: Vec<String> = status
.files
.values()
.map(|file| file.path.clone().unwrap())
.collect();
// the copy is in the subfolder, named after its name (the one in the file, not of the file)
assert!(
paths.iter().any(|path| path.ends_with("sub/simple.gpx")),
"{paths:?}"
);
// the new file went where the selected file is
assert!(
paths.iter().any(|path| path.ends_with("sub/fresh.gpx")),
"{paths:?}"
);
}
#[test]
fn the_parts_of_a_split_are_numbered_from_one() {
let state = crate::state::AppState::temporary();
let folder = std::env::temp_dir().join(format!("gpx-tests-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&folder).unwrap();
std::fs::copy("../gpx-rs/data/simple.gpx", folder.join("track.gpx")).unwrap();
let root = folder.clone();
let outcome = state.core(move |core| {
core.workspace.open_folder(&mut core.engine, &root, false);
core.workspace
.open_files(&mut core.engine, &[root.join("track.gpx")], true);
core.keep_workspace();
let revision = core.engine.routing().revision;
core.creating(None, false, |e| {
gpx_engine::api::split(e, revision, 2, gpx_engine::SplitType::Files)
})
});
assert_eq!(outcome.added().len(), 2, "{:?}", outcome.added());
let mut names: Vec<String> = std::fs::read_dir(&folder)
.unwrap()
.flatten()
.map(|entry| entry.file_name().to_string_lossy().into_owned())
.collect();
names.sort();
// the file stays, its two parts are numbered from 1, under their name (the one in the file)
assert_eq!(names, ["simple (1).gpx", "simple (2).gpx", "track.gpx"]);
std::fs::remove_dir_all(folder).unwrap();
}
#[test]
fn files_can_be_reordered() {
let app = App::new();
let mut ids = vec![];
for name in ["a", "b", "c"] {
let outcome = app.call("new_file", json!({ "name": name }));
ids.push(outcome["added"][0].as_str().unwrap().to_string());
}
assert_eq!(app.call("file_order", json!({})), json!(ids));
let outcome = app.call("reorder", json!({ "fileIds": [ids[2]], "index": 0 }));
assert_eq!(outcome["changed"], true);
assert_eq!(outcome["orderChanged"], true);
assert_eq!(
app.call("file_order", json!({})),
json!([ids[2], ids[0], ids[1]])
);
}
/// A folder of its own, with GPX files whose name inside is not the name of the file.
fn folder_with(files: &[&str]) -> std::path::PathBuf {
let folder = std::env::temp_dir().join(format!("gpx-names-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&folder).unwrap();
for name in files {
std::fs::write(
folder.join(format!("{name}.gpx")),
r#"<?xml version="1.0"?><gpx version="1.1" creator="test"><metadata><name>Inside</name></metadata><trk><trkseg><trkpt lat="50.0" lon="4.0"></trkpt><trkpt lat="50.1" lon="4.1"></trkpt></trkseg></trk></gpx>"#,
)
.unwrap();
}
folder
}
fn name_of(app: &App, id: &str) -> String {
app.call("file_structure", json!({ "fileId": id }))["name"]
.as_str()
.unwrap()
.to_string()
}
/// The name of the file on the disk of an open file, without its extension.
fn file_stem_of(app: &App, id: &str) -> String {
let path = app.call("workspace_state", json!({}))["files"][id]["path"].clone();
std::path::Path::new(path.as_str().unwrap())
.file_stem()
.unwrap()
.to_string_lossy()
.into_owned()
}
#[test]
fn a_file_keeps_its_name_and_its_file_is_renamed_apart() {
let app = App::new();
let folder = folder_with(&["outside", "taken"]);
let outcome = app.call(
"open_paths",
json!({ "paths": [folder.join("outside.gpx")] }),
);
let id = outcome["added"][0].as_str().unwrap().to_string();
let dirty = |app: &App| app.call("workspace_state", json!({}))["files"][&id]["dirty"].clone();
let inside = |name: &str| std::fs::read_to_string(folder.join(format!("{name}.gpx"))).unwrap();
// the name in the file is its name, not the one of the file
assert_eq!(name_of(&app, &id), "Inside");
assert_eq!(file_stem_of(&app, &id), "outside");
assert_eq!(dirty(&app), false);
// renaming it is an edit of the file only, which is undone
app.call("select", json!({ "fileIds": [id], "mode": "replace" }));
let outcome = app.call("metadata", json!({ "name": "renamed", "desc": "" }));
assert!(outcome.get("error").is_none());
assert_eq!(name_of(&app, &id), "renamed");
assert_eq!(file_stem_of(&app, &id), "outside");
assert_eq!(dirty(&app), true);
app.call("undo", json!({}));
assert_eq!(name_of(&app, &id), "Inside");
assert_eq!(dirty(&app), false);
// the file on the disk is renamed apart: not an edit, the file is as saved as it was
let renamed = app.call("rename_file", json!({ "fileId": id, "name": "moved" }));
assert_eq!(renamed, true);
assert!(folder.join("moved.gpx").exists() && !folder.join("outside.gpx").exists());
assert_eq!(file_stem_of(&app, &id), "moved");
assert_eq!(name_of(&app, &id), "Inside");
assert_eq!(dirty(&app), false);
assert_eq!(app.call("can_undo", json!({})), false);
// saving writes to the new place, under the name of the file
app.call("metadata", json!({ "name": "saved", "desc": "" }));
app.call("save_files", json!({ "fileIds": [id] }));
assert!(inside("moved").contains("<name>saved</name>"));
assert_eq!(name_of(&app, &id), "saved");
// the name of another file is not taken
let error = app.error("rename_file", json!({ "fileId": id, "name": "taken" }));
assert_eq!(error, crate::workspace::NAME_TAKEN);
assert!(folder.join("moved.gpx").exists());
// a name is one that a file can have
app.call("rename_file", json!({ "fileId": id, "name": "a/b" }));
assert!(folder.join("a_b.gpx").exists());
// only the case changes: the same file
app.call("rename_file", json!({ "fileId": id, "name": "A_B" }));
let names: Vec<String> = std::fs::read_dir(&folder)
.unwrap()
.map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
.collect();
assert!(names.contains(&"A_B.gpx".to_string()));
assert_eq!(names.len(), 2);
assert_eq!(name_of(&app, &id), "saved");
std::fs::remove_dir_all(folder).unwrap();
}
#[test]
fn a_new_file_written_under_another_name_keeps_its_own() {
let app = App::new();
let folder = folder_with(&["route"]);
// a new file made in the folder is written there at once: route.gpx is taken
let created = app.call(
"new_file",
json!({ "name": "route", "lng": 4.4, "lat": 50.8, "folder": folder }),
);
let id = created["added"][0].as_str().unwrap().to_string();
assert!(folder.join("route (2).gpx").exists());
// the file keeps its name, whatever the name of the file it was written to
assert_eq!(name_of(&app, &id), "route");
assert_eq!(
app.call("workspace_state", json!({}))["files"][&id]["dirty"],
false
);
// which is not an edit to undo
app.call("select", json!({ "fileIds": [id], "mode": "replace" }));
assert_eq!(app.call("can_undo", json!({})), false);
std::fs::remove_dir_all(folder).unwrap();
}
#[test]
fn a_file_open_as_a_preview_is_replaced_until_it_is_kept_or_edited() {
let app = App::new();
let folder = folder_with(&["a", "b", "c", "d"]);
let path = |name: &str| folder.join(format!("{name}.gpx"));
let open = |name: &str, preview: bool| {
app.call(
"open_paths",
json!({ "paths": [path(name)], "preview": preview }),
)
};
let state = |app: &App| app.call("workspace_state", json!({}))["files"].clone();
let names = |app: &App| -> Vec<String> {
let order = app.call("file_order", json!({}));
order
.as_array()
.unwrap()
.iter()
.map(|id| file_stem_of(app, id.as_str().unwrap()))
.collect()
};
let a = open("a", true)["added"][0].as_str().unwrap().to_string();
assert_eq!(state(&app)[&a]["preview"], true);
// the next preview replaces it
let b = open("b", true)["added"][0].as_str().unwrap().to_string();
assert_eq!(names(&app), ["b"]);
assert_eq!(state(&app)[&b]["preview"], true);
// opened for good (a double click), it stays when another one is previewed
open("b", false);
assert_eq!(state(&app)[&b]["preview"], false);
let c = open("c", true)["added"][0].as_str().unwrap().to_string();
assert_eq!(names(&app), ["b", "c"]);
// something done to the preview keeps it too
app.call("style", json!({ "color": "#ff0000" }));
assert_eq!(state(&app)[&c]["preview"], false);
open("d", true);
assert_eq!(names(&app), ["b", "c", "d"]);
// several files at once are open for good
app.call(
"open_paths",
json!({ "paths": [path("a"), path("d")], "preview": true }),
);
assert_eq!(names(&app), ["b", "c", "d", "a"]);
let files = state(&app);
assert!(
files
.as_object()
.unwrap()
.values()
.all(|file| file["preview"] == false)
);
std::fs::remove_dir_all(folder).unwrap();
}
#[test]
fn the_preview_goes_when_something_else_is_selected_unless_it_was_kept() {
let app = App::new();
let folder = folder_with(&["a", "b", "c"]);
let open = |name: &str, preview: bool| {
app.call(
"open_paths",
json!({ "paths": [folder.join(format!("{name}.gpx"))], "preview": preview }),
)["added"][0]
.as_str()
.map(str::to_string)
};
let order = |app: &App| app.call("file_order", json!({})).as_array().unwrap().len();
let a = open("a", false).unwrap();
// looked at, then something else is selected: it goes
let b = open("b", true).unwrap();
assert_eq!(order(&app), 2);
app.call("select", json!({ "fileIds": [a], "mode": "replace" }));
assert_eq!(order(&app), 1);
// nothing selected: it stays
open("b", true);
app.call("select", json!({ "fileIds": [], "mode": "replace" }));
assert_eq!(order(&app), 2);
// kept (hidden, its menu opened...): it stays when something else is selected
let c = open("c", true).unwrap();
assert_eq!(order(&app), 2, "c replaces b");
app.call("keep_files", json!({ "fileIds": [c] }));
assert_eq!(
app.call("workspace_state", json!({}))["files"][&c]["preview"],
false
);
app.call("select", json!({ "fileIds": [a], "mode": "replace" }));
assert_eq!(order(&app), 2);
let _ = b;
std::fs::remove_dir_all(folder).unwrap();
}
+2 -812
View File
@@ -148,7 +148,7 @@ pub struct Entry {
pub is_dir: bool,
}
fn is_gpx(path: &Path) -> bool {
pub fn is_gpx(path: &Path) -> bool {
path.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| extension.eq_ignore_ascii_case("gpx"))
@@ -156,7 +156,7 @@ fn is_gpx(path: &Path) -> bool {
/// Compares names the way people read them: the numbers in them by their value ("track 2" before
/// "track 10"), the rest regardless of case.
fn natural_cmp(a: &str, b: &str) -> Ordering {
pub fn natural_cmp(a: &str, b: &str) -> Ordering {
let (mut a, mut b) = (a.chars().peekable(), b.chars().peekable());
loop {
let order = match (a.peek().copied(), b.peek().copied()) {
@@ -1040,813 +1040,3 @@ impl Workspace {
})
}
}
#[cfg(test)]
mod tests {
use gpx_engine::SelectMode;
use super::*;
fn gpx(name: &str) -> String {
format!(
r#"<?xml version="1.0"?><gpx version="1.1" creator="test" xmlns="http://www.topografix.com/GPX/1/1"><metadata><name>{name}</name></metadata><trk><name>{name}</name><trkseg><trkpt lat="50.0" lon="4.0"><ele>10</ele></trkpt><trkpt lat="50.1" lon="4.1"><ele>20</ele></trkpt></trkseg></trk></gpx>"#
)
}
/// The GPX files of a folder and of the folders in it.
pub(super) fn gpx_files(folder: &Path) -> Vec<PathBuf> {
let mut found = vec![];
for entry in fs::read_dir(folder).unwrap().flatten() {
let path = entry.path();
if path.is_dir() {
found.extend(gpx_files(&path));
} else if is_gpx(&path) {
found.push(path);
}
}
found.sort();
found
}
struct Fixture {
folder: PathBuf,
engine: Engine,
workspace: Workspace,
}
impl Fixture {
fn new() -> Self {
let folder =
canonical(&std::env::temp_dir()).join(format!("gpx-ws-{}", Uuid::new_v4()));
fs::create_dir_all(&folder).unwrap();
Self {
folder,
engine: Engine::default(),
workspace: Workspace::default(),
}
}
fn write(&self, name: &str, title: &str) -> PathBuf {
let path = self.folder.join(name);
fs::write(&path, gpx(title)).unwrap();
path
}
/// Opens the folder, and all the files that are in it.
fn open_folder(&mut self) {
let folder = self.folder.clone();
self.workspace.open_folder(&mut self.engine, &folder, false);
let files = gpx_files(&folder);
self.workspace.open_files(&mut self.engine, &files, false);
}
fn reconcile(&mut self, changed: Option<&[PathBuf]>) -> Option<api::Outcome> {
self.workspace.reconcile(&mut self.engine, changed)
}
fn save(&mut self, ids: &[Uuid]) {
self.workspace
.save(&mut self.engine, ids, &BTreeMap::new(), None)
.unwrap();
}
fn ids(&self) -> Vec<Uuid> {
self.engine.order().iter().map(|id| id.0).collect()
}
fn id_named(&self, name: &str) -> Uuid {
self.ids()
.into_iter()
.find(|id| self.name(*id) == name)
.unwrap()
}
fn name(&self, id: Uuid) -> String {
self.engine
.file_structure(&FileId(id))
.unwrap()
.name
.clone()
}
/// What the file holds: the name of its track (its own name is the one of the file).
fn content(&self, id: Uuid) -> String {
self.engine.file_structure(&FileId(id)).unwrap().tracks[0]
.info
.name
.clone()
.unwrap_or_default()
}
fn rename(&mut self, id: Uuid, name: &str) {
api::select(&mut self.engine, &[id], SelectMode::Replace);
assert!(!api::metadata(&mut self.engine, name, "").has_error());
}
fn status(&self, id: Uuid) -> FileStatus {
self.workspace
.state(&self.engine)
.files
.remove(&id.to_string())
.unwrap()
}
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.folder);
}
}
#[test]
fn an_opened_file_is_clean_until_it_is_edited_and_clean_again_once_saved() {
let mut fx = Fixture::new();
let path = fx.write("a.gpx", "a");
fx.workspace
.open_files(&mut fx.engine, std::slice::from_ref(&path), true);
let id = fx.ids()[0];
assert!(!fx.workspace.is_dirty(&fx.engine, id));
assert_eq!(fx.status(id).path.as_deref(), path.to_str());
fx.rename(id, "renamed");
assert!(fx.workspace.is_dirty(&fx.engine, id));
// nothing is written before it is saved
assert!(fs::read_to_string(&path).unwrap().contains(">a<"));
fx.save(&[id]);
assert!(!fx.workspace.is_dirty(&fx.engine, id));
assert!(fs::read_to_string(&path).unwrap().contains(">renamed<"));
// going back before the save is an edit again
api::select(&mut fx.engine, &[id], SelectMode::Replace);
api::undo(&mut fx.engine);
assert!(fx.workspace.is_dirty(&fx.engine, id));
api::redo(&mut fx.engine);
assert!(!fx.workspace.is_dirty(&fx.engine, id));
}
#[test]
fn a_file_that_is_not_on_the_disk_is_unsaved_until_it_is_given_a_place() {
let mut fx = Fixture::new();
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
let id = fx.ids()[0];
assert!(fx.workspace.is_dirty(&fx.engine, id));
assert_eq!(
fx.workspace.unlinked(&fx.engine, &[id]),
[(id, "fresh".to_string())]
);
// nowhere to put it without being told
fx.save(&[id]);
assert!(fx.workspace.is_dirty(&fx.engine, id));
let path = fx.folder.join("fresh.gpx");
let paths = BTreeMap::from([(id, path.clone())]);
fx.workspace
.save(&mut fx.engine, &[id], &paths, None)
.unwrap();
assert!(path.exists());
assert!(!fx.workspace.is_dirty(&fx.engine, id));
assert!(fx.workspace.unlinked(&fx.engine, &[id]).is_empty());
}
#[test]
fn several_files_without_a_place_go_in_a_folder_with_names_that_are_free() {
let mut fx = Fixture::new();
fx.write("fresh.gpx", "already there");
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
api::new_file(&mut fx.engine, "a/b: c", None, None, None, false);
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
let ids = fx.ids();
let folder = fx.folder.clone();
fx.workspace
.save(&mut fx.engine, &ids, &BTreeMap::new(), Some(&folder))
.unwrap();
for name in ["fresh (2).gpx", "fresh (3).gpx", "a_b_ c.gpx"] {
assert!(fx.folder.join(name).exists(), "{name}");
}
assert!(ids.iter().all(|id| !fx.workspace.is_dirty(&fx.engine, *id)));
}
#[test]
fn what_this_app_writes_is_not_a_change_of_the_disk() {
let mut fx = Fixture::new();
let path = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
api::select(&mut fx.engine, &[id], SelectMode::Replace);
assert!(!api::style(&mut fx.engine, Some("#ff0000"), None, None).has_error());
fx.save(&[id]);
assert!(fx.reconcile(Some(&[path])).is_none());
assert!(!fx.status(id).replaced && !fx.status(id).dirty);
}
#[test]
fn the_folders_of_the_files_outside_the_open_folder_are_watched_too() {
let mut fx = Fixture::new();
let inside = fx.write("in.gpx", "in");
let elsewhere = canonical(&std::env::temp_dir()).join(format!("gpx-ws-{}", Uuid::new_v4()));
fs::create_dir_all(&elsewhere).unwrap();
let (one, two) = (elsewhere.join("one.gpx"), elsewhere.join("two.gpx"));
fs::write(&one, gpx("one")).unwrap();
fs::write(&two, gpx("two")).unwrap();
let folder = fx.folder.clone();
// no folder: only the folder of the files
fx.workspace.open_files(&mut fx.engine, &[one, two], false);
assert_eq!(fx.workspace.watched(), [(elsewhere.clone(), false)]);
// the open folder as a whole, and the file in it needs nothing more
fx.workspace.open_folder(&mut fx.engine, &folder, false);
fx.workspace.open_files(&mut fx.engine, &[inside], false);
assert_eq!(
fx.workspace.watched(),
[(folder, true), (elsewhere.clone(), false)]
);
// closing the files stops it
let ids = fx.ids();
fx.workspace.close_files(&mut fx.engine, &ids, true);
assert_eq!(fx.workspace.watched(), [(fx.folder.clone(), true)]);
fs::remove_dir_all(elsewhere).unwrap();
}
#[test]
fn opening_a_folder_does_not_open_its_files() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
let folder = fx.folder.clone();
let outcome = fx.workspace.open_folder(&mut fx.engine, &folder, false);
assert!(!outcome.changed);
assert!(fx.ids().is_empty());
assert_eq!(fx.workspace.folder.as_deref(), Some(folder.as_path()));
}
#[test]
fn folders_are_made_renamed_and_moved_and_the_open_files_follow() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
let root = fx.folder.clone();
let path_of = |fx: &Fixture| PathBuf::from(fx.status(id).path.unwrap());
let first = fx.workspace.create_folder(&root, "New folder").unwrap();
let second = fx.workspace.create_folder(&root, "New folder").unwrap();
assert_eq!(first, root.join("New folder"));
assert_eq!(second, root.join("New folder 2"));
fx.workspace.move_paths(&[a], &first).unwrap();
assert_eq!(path_of(&fx), first.join("a.gpx"));
assert!(first.join("a.gpx").exists() && !fx.status(id).dirty);
let trips = fx.workspace.rename_path(&first, "Trips").unwrap();
assert_eq!(path_of(&fx), root.join("Trips/a.gpx"));
// a folder does not go into itself, nor onto something else
assert!(
fx.workspace
.move_paths(std::slice::from_ref(&trips), &trips)
.is_err()
);
assert_eq!(
fx.workspace.rename_path(&trips, "New folder 2"),
Err(NAME_TAKEN.to_owned())
);
fx.workspace.move_paths(&[trips], &second).unwrap();
assert_eq!(path_of(&fx), second.join("Trips/a.gpx"));
// a file keeps its extension
let closed = fx.write("c.gpx", "c");
assert_eq!(
fx.workspace.rename_path(&closed, "d").unwrap(),
root.join("d.gpx")
);
// the open folder and what is not in it are left alone
assert!(fx.workspace.rename_path(&root, "x").is_err());
let elsewhere = canonical(&std::env::temp_dir());
assert!(fx.workspace.rename_path(&elsewhere, "x").is_err());
assert!(fx.workspace.create_folder(&elsewhere, "x").is_err());
}
#[test]
fn deleted_files_are_closed_unless_they_have_edits() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
let b = fx.write("b.gpx", "b");
fx.open_folder();
let (id_a, id_b) = (fx.id_named("a"), fx.id_named("b"));
api::select(&mut fx.engine, &[id_b], SelectMode::Replace);
assert!(!api::style(&mut fx.engine, Some("#ff0000"), None, None).has_error());
let outcome = fx
.workspace
.delete_paths(&mut fx.engine, &[a.clone(), b.clone()], |paths| {
paths.iter().for_each(|path| fs::remove_file(path).unwrap());
Ok(())
})
.unwrap();
assert!(outcome.changed);
assert_eq!(fx.ids(), [id_b]);
assert!(!fx.ids().contains(&id_a));
let status = fx.status(id_b);
assert!(status.dirty && status.missing);
assert!(!a.exists() && !b.exists());
}
#[test]
fn the_tree_of_the_folder_shows_folders_first_and_only_gpx_files() {
let mut fx = Fixture::new();
fx.write("b.gpx", "b");
fx.write("A.GPX", "a");
fx.write("b 10.gpx", "b 10");
fx.write("b 2.gpx", "b 2");
fx.write("notes.txt", "not a track");
fx.write(".hidden.gpx", "hidden");
fs::create_dir(fx.folder.join("zoo")).unwrap();
fs::create_dir(fx.folder.join("Alps")).unwrap();
fs::create_dir(fx.folder.join(".git")).unwrap();
fx.write("zoo/c.gpx", "c");
let folder = fx.folder.clone();
fx.workspace.open_folder(&mut fx.engine, &folder, false);
let names = |entries: Vec<Entry>| -> Vec<(String, bool)> {
entries.into_iter().map(|e| (e.name, e.is_dir)).collect()
};
assert_eq!(
names(fx.workspace.list_folder(&folder).unwrap()),
[
("Alps".to_string(), true),
("zoo".to_string(), true),
("A.GPX".to_string(), false),
("b.gpx".to_string(), false),
("b 2.gpx".to_string(), false),
("b 10.gpx".to_string(), false),
]
);
assert_eq!(
names(fx.workspace.list_folder(&folder.join("zoo")).unwrap()),
[("c.gpx".to_string(), false)]
);
// only what is in the open folder can be listed
let elsewhere = canonical(&std::env::temp_dir());
assert!(fx.workspace.list_folder(&elsewhere).is_err());
}
#[test]
fn names_are_sorted_by_the_numbers_they_hold() {
let mut names = vec![
"track 10",
"track 2",
"Track 1",
"track",
"track 02b",
"track 2a",
"b",
"A",
];
names.sort_by(|a, b| natural_cmp(a, b).then_with(|| a.cmp(b)));
assert_eq!(
names,
[
"A",
"b",
"track",
"Track 1",
"track 2",
"track 2a",
"track 02b",
"track 10",
]
);
}
#[test]
fn a_file_without_edits_is_read_again_when_the_disk_changes() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.write("a.gpx", "theirs");
let outcome = fx.reconcile(Some(std::slice::from_ref(&a))).unwrap();
assert!(outcome.changed);
// the same file, now the one on the disk
assert_eq!(fx.ids(), [id]);
assert_eq!(fx.content(id), "theirs");
let status = fx.status(id);
assert!(!status.dirty && !status.replaced);
// looking again changes nothing
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_none());
}
#[test]
fn a_file_with_edits_is_flagged_when_the_disk_changes_and_not_read_again() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.rename(id, "mine");
fx.write("a.gpx", "theirs");
let outcome = fx.reconcile(Some(std::slice::from_ref(&a))).unwrap();
assert!(!outcome.changed);
assert_eq!(fx.name(id), "mine");
let status = fx.status(id);
assert!(status.dirty && status.replaced && !status.missing);
// looking again changes nothing
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_none());
// the disk goes back to what was read: only the edits are left
fx.write("a.gpx", "a");
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_some());
let status = fx.status(id);
assert!(status.dirty && !status.replaced);
}
#[test]
fn the_user_can_take_the_disk_instead_of_the_edits() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.rename(id, "mine");
fx.write("a.gpx", "theirs");
fx.reconcile(None);
assert!(fx.status(id).replaced);
fx.workspace.reload(&mut fx.engine, &[id]).unwrap();
assert_eq!(fx.content(id), "theirs");
let status = fx.status(id);
assert!(!status.dirty && !status.replaced);
// and it is one undo step
api::select(&mut fx.engine, &[id], SelectMode::Replace);
api::undo(&mut fx.engine);
assert_eq!(fx.content(id), "mine");
}
#[test]
fn saving_overwrites_what_replaced_the_file() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.rename(id, "mine");
fx.write("a.gpx", "theirs");
fx.reconcile(None);
assert!(fx.status(id).replaced);
fx.save(&[id]);
assert!(fs::read_to_string(a).unwrap().contains(">mine<"));
assert!(!fx.status(id).replaced && !fx.status(id).dirty);
}
#[test]
fn a_file_that_is_gone_from_the_disk_stays_open_and_dirty_until_it_is_saved_again() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fs::remove_file(&a).unwrap();
assert!(fx.reconcile(Some(std::slice::from_ref(&a))).is_some());
assert_eq!(fx.ids(), [id]);
let status = fx.status(id);
assert!(status.dirty && status.missing && status.path.is_some());
// saving puts it back
fx.save(&[id]);
assert!(a.exists());
let status = fx.status(id);
assert!(!status.dirty && !status.missing);
}
#[test]
fn a_file_that_comes_back_different_is_read_again() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fs::remove_file(&a).unwrap();
fx.reconcile(None);
assert!(fx.status(id).missing);
fx.write("a.gpx", "back");
fx.reconcile(None);
assert_eq!(fx.content(id), "back");
let status = fx.status(id);
assert!(!status.dirty && !status.missing);
}
#[test]
fn what_changed_while_the_app_was_closed_is_found_when_it_starts() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.write("a.gpx", "changed");
assert!(fx.reconcile(None).is_some());
assert_eq!(fx.content(id), "changed");
fs::remove_file(a).unwrap();
assert!(fx.reconcile(None).is_some());
assert!(fx.status(id).missing);
}
#[test]
fn new_files_made_from_a_file_of_the_folder_are_saved_next_to_it() {
let mut fx = Fixture::new();
fs::create_dir(fx.folder.join("sub")).unwrap();
fx.write("sub/b.gpx", "b");
fx.write("a.gpx", "a");
fx.open_folder();
let b = fx.id_named("b");
let sub = fx.folder.join("sub");
assert_eq!(fx.workspace.source_dir(&[b]), Some(canonical(&sub)));
let before = fx.ids();
api::select(&mut fx.engine, &[b], SelectMode::Replace);
let outcome = api::duplicate(&mut fx.engine);
let copy = fx
.ids()
.into_iter()
.find(|id| !before.contains(id))
.unwrap();
fx.workspace.inherit(outcome.added(), &canonical(&sub));
assert_eq!(fx.status(copy).folder.as_deref(), canonical(&sub).to_str());
assert!(fx.status(copy).path.is_none() && fx.status(copy).dirty);
// nobody needs to be asked where it goes
assert!(fx.workspace.unlinked(&fx.engine, &[copy]).is_empty());
fx.save(&[copy]);
assert!(sub.join("b (2).gpx").exists());
let status = fx.status(copy);
assert!(!status.dirty && status.folder.is_none());
assert_eq!(
status.path.as_deref(),
canonical(&sub.join("b (2).gpx")).to_str()
);
// the copy of the copy is next to it as well
assert_eq!(fx.workspace.source_dir(&[copy]), Some(canonical(&sub)));
}
#[test]
fn a_file_outside_the_open_folder_hands_nothing_down() {
let mut fx = Fixture::new();
let elsewhere = canonical(&std::env::temp_dir()).join(format!("gpx-ws-{}", Uuid::new_v4()));
fs::create_dir_all(&elsewhere).unwrap();
let outside = elsewhere.join("o.gpx");
fs::write(&outside, gpx("o")).unwrap();
let folder = fx.folder.clone();
fx.workspace.open_folder(&mut fx.engine, &folder, false);
fx.workspace
.open_files(&mut fx.engine, std::slice::from_ref(&outside), true);
let id = fx.ids()[0];
assert_eq!(fx.workspace.source_dir(&[id]), None);
// a new file with no source is not linked to a folder by `source_dir`: the caller falls back
fs::remove_dir_all(elsewhere).unwrap();
}
#[test]
fn closing_files_asks_what_to_do_with_the_unsaved_ones() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.write("b.gpx", "b");
fx.open_folder();
let (a, b) = (fx.id_named("a"), fx.id_named("b"));
fx.rename(a, "edited");
assert_eq!(fx.workspace.unsaved(&fx.engine, &[a, b]), [a]);
// without a choice what has edits stays
let outcome = fx.workspace.close_files(&mut fx.engine, &[a, b], false);
assert!(outcome.changed);
assert_eq!(fx.ids(), [a]);
// saved first
fx.save(&[a]);
fx.workspace.close_files(&mut fx.engine, &[a], false);
assert!(fx.ids().is_empty());
assert!(
fs::read_to_string(fx.folder.join("a.gpx"))
.unwrap()
.contains("edited")
);
assert!(fx.workspace.links.is_empty());
}
#[test]
fn closing_files_can_discard_their_edits() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
let a = fx.ids()[0];
fx.rename(a, "edited");
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
let fresh = fx.id_named("fresh");
fx.workspace.close_files(&mut fx.engine, &[a, fresh], true);
assert!(fx.ids().is_empty());
assert!(
fs::read_to_string(fx.folder.join("a.gpx"))
.unwrap()
.contains(">a<")
);
}
#[test]
fn closing_the_folder_closes_every_file() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
api::new_file(&mut fx.engine, "fresh", None, None, None, false);
assert_eq!(fx.ids().len(), 2);
// the new file has nowhere to go: it has to be discarded
let outcome = fx.workspace.close_folder(&mut fx.engine, false);
assert!(outcome.changed);
assert_eq!(fx.ids().len(), 1);
assert!(fx.workspace.folder.is_none());
let outcome = fx.workspace.close_folder(&mut fx.engine, true);
assert!(outcome.changed);
assert!(fx.ids().is_empty());
}
#[test]
fn opening_another_folder_closes_the_first_with_all_its_files() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
let a = fx.ids()[0];
fx.rename(a, "edited");
let other = canonical(&std::env::temp_dir()).join(format!("gpx-ws-{}", Uuid::new_v4()));
fs::create_dir_all(&other).unwrap();
// the edits stay, nothing is lost without a choice
fx.workspace.open_folder(&mut fx.engine, &other, false);
assert_eq!(fx.ids(), [a]);
assert_eq!(fx.workspace.folder.as_deref(), Some(other.as_path()));
let first = fx.folder.clone();
fx.workspace.open_folder(&mut fx.engine, &first, true);
assert!(fx.ids().is_empty());
assert!(
fs::read_to_string(fx.folder.join("a.gpx"))
.unwrap()
.contains(">a<")
);
fs::remove_dir_all(other).unwrap();
}
#[test]
fn opening_the_same_folder_again_changes_nothing() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
let folder = fx.folder.clone();
let outcome = fx.workspace.open_folder(&mut fx.engine, &folder, true);
assert!(!outcome.changed);
assert_eq!(fx.ids().len(), 1);
}
#[test]
fn a_failed_save_stops_at_the_file_and_leaves_it_dirty() {
let mut fx = Fixture::new();
fx.write("a.gpx", "a");
fx.open_folder();
let id = fx.ids()[0];
fx.rename(id, "edited");
// the place of the file is taken by a folder
fs::remove_file(fx.folder.join("a.gpx")).unwrap();
fs::create_dir(fx.folder.join("a.gpx")).unwrap();
let result = fx
.workspace
.save(&mut fx.engine, &[id], &BTreeMap::new(), None);
assert!(result.is_err());
assert!(fx.workspace.is_dirty(&fx.engine, id));
}
#[test]
fn saving_as_gives_the_file_another_place() {
let mut fx = Fixture::new();
let a = fx.write("a.gpx", "a");
fx.write("b.gpx", "b");
fx.open_folder();
let id = fx.id_named("a");
let other = fx.id_named("b");
fx.rename(id, "edited");
let target = fx.folder.join("copy.gpx");
fx.workspace.save_as(&mut fx.engine, id, &target).unwrap();
assert!(fs::read_to_string(&target).unwrap().contains("edited"));
assert!(fs::read_to_string(a).unwrap().contains(">a<"));
let status = fx.status(id);
assert!(!status.dirty);
assert_eq!(status.path.as_deref(), canonical(&target).to_str());
// the place of another open file is not available
let taken = fx.folder.join("b.gpx");
assert!(fx.workspace.save_as(&mut fx.engine, id, &taken).is_err());
assert!(!fx.workspace.is_dirty(&fx.engine, other));
}
}
#[cfg(test)]
mod restart_tests {
use gpx_engine::Persister;
use super::*;
use crate::store::FileStorage;
/// What the app does when it starts again: the engine and the links are read from what was
/// kept.
fn restart(engine: &Engine, workspace: &Workspace, root: &Path) -> (Engine, Workspace) {
let storage = FileStorage::open(root).unwrap();
pollster::block_on(Persister::default().save(&storage, engine.snapshot())).unwrap();
let mut restarted = Engine::default();
let restored = pollster::block_on(Persister::default().restore(&storage)).unwrap();
restarted.restore(restored);
let links = serde_json::to_string(workspace).unwrap();
(restarted, serde_json::from_str(&links).unwrap())
}
fn setup() -> (PathBuf, Engine, Workspace, Vec<Uuid>) {
let root = std::env::temp_dir().join(format!("gpx-restart-{}", Uuid::new_v4()));
let folder = root.join("tracks");
fs::create_dir_all(&folder).unwrap();
for name in ["with_tracks", "with_time", "with_waypoint"] {
let _ = fs::copy(
format!("../gpx-rs/data/{name}.gpx"),
folder.join(format!("{name}.gpx")),
);
}
let mut engine = Engine::default();
let mut workspace = Workspace::default();
workspace.open_folder(&mut engine, &folder, false);
workspace.open_files(&mut engine, &tests::gpx_files(&folder), false);
let ids = engine.order().iter().map(|id| id.0).collect();
(root, engine, workspace, ids)
}
#[test]
fn files_that_were_not_edited_are_not_unsaved_after_a_restart() {
let (root, engine, workspace, ids) = setup();
assert!(ids.len() >= 2);
let (restarted, mut workspace) = restart(&engine, &workspace, &root.join("store"));
// the files are the same, but the engine knows their contents by new identities
assert!(ids.iter().any(|id| workspace.is_dirty(&restarted, *id)));
workspace.verify(&restarted);
assert!(ids.iter().all(|id| !workspace.is_dirty(&restarted, *id)));
fs::remove_dir_all(root).unwrap();
}
#[test]
fn files_that_were_edited_are_still_unsaved_after_a_restart() {
let (root, mut engine, workspace, ids) = setup();
api::select(&mut engine, &[ids[0]], gpx_engine::SelectMode::Replace);
api::metadata(&mut engine, "edited", "");
assert!(workspace.is_dirty(&engine, ids[0]));
let (restarted, mut workspace) = restart(&engine, &workspace, &root.join("store"));
workspace.verify(&restarted);
assert!(workspace.is_dirty(&restarted, ids[0]));
assert!(
ids[1..]
.iter()
.all(|id| !workspace.is_dirty(&restarted, *id))
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn links_made_before_the_content_was_kept_are_checked_against_the_disk() {
let (root, mut engine, mut workspace, ids) = setup();
api::select(&mut engine, &[ids[0]], gpx_engine::SelectMode::Replace);
api::metadata(&mut engine, "edited", "");
for link in workspace.links.values_mut() {
link.export_hash = 0;
}
let (restarted, mut workspace) = restart(&engine, &workspace, &root.join("store"));
workspace.verify(&restarted);
assert!(workspace.is_dirty(&restarted, ids[0]));
assert!(
ids[1..]
.iter()
.all(|id| !workspace.is_dirty(&restarted, *id))
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn the_folders_of_new_files_and_the_old_flag_name_survive_a_restart() {
let (root, engine, mut workspace, ids) = setup();
let folder = workspace.folder.clone().unwrap();
let fresh = Uuid::new_v4();
workspace.inherit(&[fresh.to_string()], &folder);
workspace.links.get_mut(&ids[0]).unwrap().replaced = true;
let json = serde_json::to_string(&workspace).unwrap();
// links written by the previous version had `conflict`, which is the same thing
let json = json.replace("\"replaced\"", "\"conflict\"");
assert!(json.contains("\"conflict\":true"));
let read: Workspace = serde_json::from_str(&json).unwrap();
assert!(read.links[&ids[0]].replaced);
assert_eq!(read.dirs.get(&fresh), Some(&folder));
let _ = engine;
fs::remove_dir_all(root).unwrap();
}
}