1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
//! How the list on this computer is grouped.
//!
//! Beside [`crate::store`] because a grouping is stored the same way the list is, under
//! its own key: two files, read back separately, agreeing about what an id means.
use std::collections::BTreeMap;
use crate::named::{self, Line, List, Named};
use crate::workspace::{LocalEntity, Workspace};
/// Where the folders and their membership are kept between sessions.
///
/// ⚠️ Membership is by workspace id, which is the same id the local list is stored
/// under — the two files are read back into one list, so they have to agree about what
/// an id means.
pub(crate) const KEY: &str = "drawbar.folders";
const VERSION: &str = "drawbar folders 1";
/// What a folder line is headed with.
const FOLDER: &str = "f";
/// One folder on this computer.
pub type Folder = Named;
/// How the local list is grouped.
///
/// ⚠️ A folder is a **view of the list**, not a place bytes live: an asset in one is an
/// asset like any other, and nothing here is a directory, an archive or anything the
/// instrument has ever heard of. Membership is kept beside the divider rather than in
/// the workspace for that reason.
#[derive(Default)]
pub struct Folders {
list: List,
/// Which folder an asset is in, by its workspace id. Absent is loose.
///
/// ⚠️ Ordered, because [`Folders::written`] walks it and a store that comes out in a
/// different order every session is a store written every session.
of: BTreeMap<u64, u64>,
}
impl Folders {
pub fn all(&self) -> &[Folder] {
self.list.all()
}
pub(crate) fn name_of(&self, id: u64) -> Option<&str> {
self.list.name_of(id)
}
/// A new folder, under a name nothing else in the list is using, or nothing where
/// the list has no id left ([`List::make`]).
pub(crate) fn make(&mut self) -> Option<u64> {
self.list.make("New folder")
}
pub(crate) fn rename(&mut self, id: u64, name: String) {
self.list.rename(id, name);
}
/// Drop a folder. What was in it goes back to the loose part of the list — a folder
/// holds nothing, so removing one cannot take anything with it.
pub(crate) fn remove(&mut self, id: u64) {
self.list.remove(id);
self.of.retain(|_, held| *held != id);
}
pub(crate) fn file(&mut self, entity: u64, folder: Option<u64>) {
match folder.filter(|id| self.list.holds(*id)) {
Some(id) => self.of.insert(entity, id),
None => self.of.remove(&entity),
};
}
pub(crate) fn forget(&mut self, entity: u64) {
self.of.remove(&entity);
}
/// Drop the memberships of assets the list does not hold.
///
/// The store keeps the folders and the assets in two files that are read back
/// separately, and only the asset file decides what survived — anything too big to
/// keep, or dropped for want of room, leaves its membership behind. Left alone they
/// accumulate for as long as the app is installed.
pub(crate) fn forget_missing(&mut self, workspace: &Workspace) {
self.of.retain(|entity, _| workspace.get(*entity).is_some());
}
/// Which folder an asset is in.
pub fn holding(&self, entity: u64) -> Option<u64> {
self.of.get(&entity).copied()
}
/// What this folder holds, in the order the list holds it.
pub(crate) fn members<'a>(&self, id: u64, workspace: &'a Workspace) -> Vec<&'a LocalEntity> {
workspace
.listed()
.filter(|entity| self.holding(entity.id) == Some(id))
.collect()
}
}
impl Folders {
/// The folders and their membership as one string, for the store.
///
/// `f` lines are the folders and `m` lines are what is in them, so a folder with
/// nothing in it survives a session like any other.
pub(crate) fn written(&self) -> String {
let mut out = named::written(VERSION, FOLDER, &self.list);
for (entity, folder) in &self.of {
out.push_str(&named::member(*entity, *folder));
}
out
}
/// Read back what [`Folders::written`] wrote. Anything unaccounted for is no folders
/// at all — half a grouping is worse than none, because a folder nobody made is one
/// nobody can explain.
pub(crate) fn read(text: &str) -> Folders {
let mut folders = Folders::default();
for line in named::read(text, VERSION, FOLDER) {
match line {
Line::Named { id, name } => folders.list.restore(id, name),
Line::Member { asset, group } => {
folders.of.insert(asset, group);
}
}
}
// A membership naming a folder that is not in the file would be an asset nothing
// shows and nothing can get back.
let Folders { list, of } = &mut folders;
of.retain(|_, folder| list.holds(*folder));
folders
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A new folder is one nothing else is called, so two of them are two rows rather
/// than one row twice.
#[test]
fn a_new_folder_gets_a_name_no_other_folder_is_using() {
let mut folders = Folders::default();
let names: Vec<String> = (0..3)
.map(|_| {
let id = folders.make().unwrap();
folders.name_of(id).expect("it was made").to_string()
})
.collect();
assert_eq!(names, ["New folder", "New folder 2", "New folder 3"]);
// And the ids are as distinct as the names.
let ids: Vec<u64> = folders.all().iter().map(|folder| folder.id).collect();
assert_eq!(ids, vec![1, 2, 3]);
}
/// A folder holds nothing, so losing one loses nothing: what was in it is back in
/// the loose part of the list.
#[test]
fn removing_a_folder_leaves_what_was_in_it_on_this_computer() {
let mut folders = Folders::default();
let (kept, gone) = (folders.make().unwrap(), folders.make().unwrap());
folders.file(7, Some(kept));
folders.file(8, Some(gone));
folders.remove(gone);
assert_eq!(folders.holding(7), Some(kept));
assert_eq!(folders.holding(8), None, "loose, not lost");
// And a folder that never existed is not a place anything can be put.
folders.file(9, Some(gone));
assert_eq!(folders.holding(9), None);
}
/// The grouping comes back as it was left, empty folders included — and a membership
/// naming a folder the file does not hold is dropped rather than hiding an asset in
/// a folder nobody can open.
#[test]
fn the_folders_and_what_is_in_them_survive_a_session() {
let mut folders = Folders::default();
let (sunday, empty) = (folders.make().unwrap(), folders.make().unwrap());
folders.rename(sunday, "Sunday\tmorning".into());
folders.file(7, Some(sunday));
folders.file(8, Some(sunday));
let after = Folders::read(&folders.written());
assert_eq!(after.all().len(), 2, "an empty folder is still a folder");
assert_eq!(after.name_of(sunday), Some("Sunday\tmorning"));
assert_eq!(after.name_of(empty), Some("New folder 2"));
assert_eq!(after.holding(7), Some(sunday));
assert_eq!(after.holding(8), Some(sunday));
// Nothing readable is no folders at all, never half a grouping.
assert!(Folders::read("").all().is_empty());
assert!(Folders::read("drawbar folders 99\nf\t1\tSunday\n")
.all()
.is_empty());
let orphaned = Folders::read(&format!("{VERSION}\nm\t7\t3\n"));
assert_eq!(orphaned.holding(7), None);
}
/// ⚠️ The store is rewritten whenever it differs from what is in it, so a grouping
/// that writes its lines in a different order each time is a write each time.
#[test]
fn one_grouping_is_written_as_the_same_bytes_every_time() {
let mut folders = Folders::default();
let sunday = folders.make().unwrap();
for entity in [91, 7, 40, 2, 68, 13] {
folders.file(entity, Some(sunday));
}
let written = folders.written();
assert_eq!(written, folders.written());
let members: Vec<&str> = written
.lines()
.filter_map(|line| line.strip_prefix("m\t"))
.filter_map(|line| line.split('\t').next())
.collect();
assert_eq!(members, ["2", "7", "13", "40", "68", "91"]);
}
/// A line this build did not write is dropped rather than guessed at, and the rest of
/// the file is still read.
#[test]
fn a_line_that_is_not_a_line_is_dropped_and_the_rest_is_read() {
let read = |lines: &str| Folders::read(&format!("{VERSION}\n{lines}"));
let kept = read("f\tx\tNot a number\nf\t1\tSunday\n");
assert_eq!(kept.all().len(), 1, "an id that is not a number");
assert_eq!(kept.name_of(1), Some("Sunday"));
let short = read("f\t1\tSunday\nm\t7\n");
assert_eq!(short.holding(7), None, "a membership missing its folder");
let wide = read("f\t1\tSunday\nm\t7\t1\textra\n");
assert_eq!(wide.holding(7), None, "a line with a column too many");
let unknown = read("f\t1\tSunday\nx\t7\t1\n");
assert_eq!(unknown.all().len(), 1, "a head this build does not write");
}
/// ⚠️ Two `f` lines claiming one id is a file with two names for one folder, and
/// every membership naming that id means whichever of them is kept. The first is, so
/// the second is refused rather than quietly renaming a folder on the way in.
#[test]
fn a_second_folder_line_for_an_id_already_read_is_refused() {
let folders = Folders::read(&format!("{VERSION}\nf\t1\tSunday\nf\t1\tMonday\nm\t7\t1\n"));
assert_eq!(folders.all().len(), 1);
assert_eq!(folders.name_of(1), Some("Sunday"));
assert_eq!(folders.holding(7), Some(1));
}
/// A name holding a newline would otherwise be two lines, and the second of them a
/// line this build refuses.
#[test]
fn a_folder_named_across_two_lines_comes_back_as_one_name() {
let mut folders = Folders::default();
let id = folders.make().unwrap();
folders.rename(id, "Sunday\nmorning".into());
let after = Folders::read(&folders.written());
assert_eq!(after.name_of(id), Some("Sunday\nmorning"));
assert_eq!(after.all().len(), 1);
}
}