1use std::ffi::CString;
16use std::fs::{File, OpenOptions};
17use std::io::Write as _;
18use std::os::fd::{AsRawFd as _, FromRawFd as _, OwnedFd};
19use std::os::unix::ffi::OsStrExt as _;
20use std::os::unix::fs::OpenOptionsExt as _;
21use std::os::unix::net::{UnixListener, UnixStream};
22use std::path::{Component, Path, PathBuf};
23use std::sync::atomic::{AtomicU64, Ordering};
24use std::sync::{Arc, Mutex};
25
26use crate::portal::FileFilter;
27use crate::shell::{
28 Filter, FrameReader, HandedDocument, Handshake, MAX_FRAME_BYTES, PROTOCOL, PickMode, Reply,
29 Request, send_frame,
30};
31const MAX_NAME: usize = 255;
33
34pub const CANNOT_HAND: &str = "Files can't be handed to this app on this computer.";
37pub const DOES_NOT_FIT: &str =
38 "The file chooser's answer doesn't fit what the app asked for. Try again.";
39const GONE: &str = "That file is no longer available to the app. Choose it again.";
40pub const NOT_CHOSEN: &str = "This app can only open files you chose for it.";
41pub const NOTHING_OPENS: &str = "Nothing on this computer opens this file.";
42const BAD_LINK: &str = "That link isn't a web address or anything else that can be opened.";
43const DID_NOT_OPEN: &str = "It didn't open. Try again.";
44pub const NO_APP_CHOOSER: &str = "This computer can't ask you to choose an app yet.";
45const NO_IDENTITY_CHOOSER: &str = "This computer can't ask you to choose an identity yet.";
46const NOT_ASKED: &str = "The file chooser couldn't be shown. Try again.";
47
48#[derive(Clone)]
50pub struct Serving {
51 pub person: Option<Arc<dyn Person>>,
53 pub grants: Arc<dyn Grants>,
55 pub opens: Arc<dyn Opens>,
57}
58
59#[derive(Debug, Clone)]
61pub struct Caller {
62 pub app: String,
63 pub workspace: String,
64}
65
66#[derive(Debug, Clone, PartialEq, Eq)]
69#[allow(
70 clippy::struct_excessive_bools,
71 reason = "each flag is one of the chooser's independent options"
72)]
73pub struct Question {
74 pub title: String,
75 pub save: bool,
76 pub directory: bool,
77 pub writable_directory: bool,
78 pub multiple: bool,
79 pub accept_label: Option<String>,
80 pub current_name: Option<String>,
81 pub filters: Vec<FileFilter>,
82}
83
84impl Question {
85 #[must_use]
87 pub const fn choice(&self) -> Choice {
88 if self.save {
89 Choice::Save
90 } else if self.directory {
91 Choice::Folder {
92 write: self.writable_directory,
93 }
94 } else {
95 Choice::Read
96 }
97 }
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum Choice {
104 Read,
105 Folder { write: bool },
106 Save,
107}
108
109impl Choice {
110 #[must_use]
112 pub const fn writes(self) -> bool {
113 matches!(self, Self::Save | Self::Folder { write: true })
114 }
115}
116
117#[derive(Debug, Clone)]
119pub struct Granted {
120 pub reference: PathBuf,
122 pub name: String,
124 pub host: PathBuf,
126 pub choice: Choice,
128 pub save_sibling: Option<std::ffi::OsString>,
130}
131
132pub trait Grants: Send + Sync {
135 fn grant(&self, caller: &Caller, chosen: &Path, choice: Choice) -> Result<Granted, String>;
140
141 fn document(&self, caller: &Caller, reference: &Path) -> Option<Granted>;
143}
144
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub enum Asked {
148 Cancelled,
149 Failed,
150}
151
152pub trait Person: Send + Sync {
154 fn choose(
161 &self,
162 caller: &Caller,
163 handle: String,
164 question: &Question,
165 ) -> Result<Vec<PathBuf>, Asked>;
166}
167
168pub trait Opens: Send + Sync {
170 fn open(&self, workspace: &str, uri: &str) -> Result<Option<()>, String>;
175}
176
177pub fn serve_connection(serving: Arc<Serving>, stream: UnixStream) {
181 let Ok(writer) = stream.try_clone() else {
182 return;
183 };
184 let mut reader = FrameReader::new(stream);
185 let Some(handshake) = read_handshake(&mut reader) else {
186 tracing::warn!("a chooser connection named no app: it is closed");
187 return;
188 };
189 let connection = Arc::new(Connection {
190 serving,
191 number: CONNECTIONS.fetch_add(1, Ordering::Relaxed),
192 app: handshake.app_id,
193 workspace: handshake.workspace_id,
194 writer: Mutex::new(writer),
195 });
196 loop {
197 let frame = match reader.line() {
198 Ok(Some(frame)) => frame,
199 Ok(None) => break,
200 Err(error) => {
201 tracing::warn!(app = %connection.app, %error, "a chooser request is unreadable");
202 break;
203 }
204 };
205 let request = match serde_json::from_slice::<Request>(frame.trim_ascii_end()) {
206 Ok(request) => request,
207 Err(error) => {
208 tracing::warn!(app = %connection.app, %error, "a chooser request does not decode");
209 break;
210 }
211 };
212 match request {
213 Request::Reopen {
214 id,
215 reference,
216 write,
217 } => {
218 let (reply, fds) = connection.reopen(id, &reference, write);
219 connection.say_with(&reply, &fds);
220 }
221 Request::Saved { id, reference } => connection.say(&connection.saved(id, &reference)),
222 Request::ChooseApp { id, .. } => connection.say(&Reply::Failed {
223 id,
224 reason: NO_APP_CHOOSER.to_owned(),
225 }),
226 Request::AwaitIdentity { id } | Request::ChooseIdentity { id } => {
227 connection.say(&Reply::Failed {
228 id,
229 reason: NO_IDENTITY_CHOOSER.to_owned(),
230 });
231 }
232 request @ Request::Pick { .. } => {
233 Connection::ask_person(&connection, request);
234 }
235 waits => {
236 let asking = Arc::clone(&connection);
237 if let Err(error) = std::thread::Builder::new()
238 .name("tilo-chooser-ask".into())
239 .spawn(move || {
240 let reply = asking.answer(waits);
241 asking.say(&reply);
242 })
243 {
244 tracing::warn!(%error, "a chooser request could not be answered");
245 }
246 }
247 }
248 }
249}
250
251pub fn serve_listener(listener: &UnixListener, serving: &Arc<Serving>) {
253 for stream in listener.incoming() {
254 match stream {
255 Ok(stream) => {
256 let serving = Arc::clone(serving);
257 if let Err(error) = std::thread::Builder::new()
258 .name("tilo-chooser-app".into())
259 .spawn(move || serve_connection(serving, stream))
260 {
261 tracing::warn!(%error, "a chooser connection could not be served");
262 }
263 }
264 Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
265 Err(error) => {
266 tracing::warn!(%error, "the chooser service's accept failed");
267 std::thread::sleep(std::time::Duration::from_millis(100));
268 }
269 }
270 }
271}
272
273pub fn pair(serving: Serving, app: &str, workspace: &str) -> std::io::Result<UnixStream> {
280 let (app_end, runtime_end) = UnixStream::pair()?;
281 let handshake = Handshake {
282 protocol: PROTOCOL,
283 app_id: app.to_owned(),
284 workspace_id: workspace.to_owned(),
285 };
286 let mut frame = serde_json::to_vec(&handshake).map_err(std::io::Error::other)?;
287 frame.push(b'\n');
288 let mut writer = app_end.try_clone()?;
289 writer.write_all(&frame)?;
290 writer.flush()?;
291 let serving = Arc::new(serving);
292 std::thread::Builder::new()
293 .name("tilo-chooser".into())
294 .spawn(move || serve_connection(serving, runtime_end))?;
295 Ok(app_end)
296}
297
298static CONNECTIONS: AtomicU64 = AtomicU64::new(0);
299
300struct Connection {
302 serving: Arc<Serving>,
303 number: u64,
305 app: String,
306 workspace: String,
307 writer: Mutex<UnixStream>,
308}
309
310fn pick_question(request: Request) -> Option<(u64, Question)> {
312 match request {
313 Request::Pick {
314 id,
315 mode,
316 multiple,
317 title,
318 accept_label,
319 suggested_name,
320 filters,
321 } => Some((
322 id,
323 Question {
324 title,
325 save: mode == PickMode::Save,
326 directory: matches!(mode, PickMode::Directory | PickMode::WritableDirectory),
327 writable_directory: mode == PickMode::WritableDirectory,
328 multiple,
329 accept_label: Some(accept_label).filter(|label| !label.is_empty()),
330 current_name: suggested_name.filter(|name| !name.is_empty()),
331 filters: filters.iter().map(filter_of).collect(),
332 },
333 )),
334 _ => None,
335 }
336}
337
338fn filter_of(filter: &Filter) -> FileFilter {
339 let mut made = FileFilter::new(&filter.name);
340 for glob in &filter.globs {
341 made = made.glob(glob);
342 }
343 for mimetype in &filter.mimetypes {
344 made = made.mimetype(mimetype);
345 }
346 made
347}
348
349fn read_handshake(reader: &mut FrameReader) -> Option<Handshake> {
351 let frame = reader.line().ok()??;
352 let handshake: Handshake = serde_json::from_slice(frame.trim_ascii_end()).ok()?;
353 let named = |name: &str| !name.is_empty() && name.len() <= MAX_NAME;
354 (handshake.protocol == PROTOCOL && named(&handshake.app_id) && named(&handshake.workspace_id))
355 .then_some(handshake)
356}
357
358impl Connection {
359 fn say(&self, reply: &Reply) {
362 self.say_with(reply, &[]);
363 }
364
365 fn say_with(&self, reply: &Reply, fds: &[crate::shell::Descriptor]) {
366 let Ok(mut frame) = serde_json::to_vec(reply) else {
367 return;
368 };
369 if frame.len() >= MAX_FRAME_BYTES {
370 tracing::warn!(app = %self.app, "a chooser reply is larger than the wire allows");
371 return;
372 }
373 frame.push(b'\n');
374 let writer = self
375 .writer
376 .lock()
377 .unwrap_or_else(std::sync::PoisonError::into_inner);
378 if let Err(error) = send_frame(&writer, &frame, fds) {
379 tracing::debug!(%error, app = %self.app, "an app closed its end of the chooser");
380 }
381 }
382
383 fn caller(&self) -> Caller {
385 Caller {
386 app: self.app.clone(),
387 workspace: self.workspace.clone(),
388 }
389 }
390
391 fn ask_person(connection: &Arc<Self>, request: Request) {
395 let Some((id, question)) = pick_question(request) else {
396 return;
397 };
398 let Some(person) = connection.serving.person.clone() else {
399 return connection.say(&Reply::Nobody { id });
400 };
401 let caller = Caller {
402 app: connection.app.clone(),
403 workspace: connection.workspace.clone(),
404 };
405 let handle = format!("chooser:{}:{id}", connection.number);
406 let asking = Arc::clone(connection);
407 let chosen = person.choose(&caller, handle, &question);
408 let reply = match chosen {
409 Ok(paths) => {
410 let (reply, fds) = asking.hand(id, &paths, question.choice());
411 asking.say_with(&reply, &fds);
412 return;
413 }
414 Err(Asked::Cancelled) => Reply::Cancelled { id },
415 Err(Asked::Failed) => failed(id, NOT_ASKED),
416 };
417 asking.say(&reply);
418 }
419
420 fn answer(&self, request: Request) -> Reply {
422 match request {
423 Request::Open { id, path } => match self.opened_path(&path) {
424 Ok(host) => match file_uri(&host) {
425 Some(uri) => match self.open(&uri) {
426 Ok(true) => Reply::Opened { id },
427 Ok(false) => failed(id, NOTHING_OPENS),
428 Err(reason) => failed(id, reason),
429 },
430 None => failed(id, NOT_CHOSEN),
431 },
432 Err(reason) => failed(id, reason),
433 },
434 Request::OpenUri { id, uri } => self.open_uri(id, &uri),
435 Request::Pick { id, .. }
436 | Request::Reopen { id, .. }
437 | Request::Saved { id, .. }
438 | Request::ChooseApp { id, .. }
439 | Request::AwaitIdentity { id }
440 | Request::ChooseIdentity { id }
441 | Request::PickContents { id, .. }
442 | Request::ReadContents { id, .. }
443 | Request::ReleaseContents { id, .. } => failed(id, DOES_NOT_FIT),
444 }
445 }
446
447 fn hand(
450 &self,
451 id: u64,
452 paths: &[PathBuf],
453 choice: Choice,
454 ) -> (Reply, Vec<crate::shell::Descriptor>) {
455 let caller = self.caller();
456 let mut documents = Vec::with_capacity(paths.len());
457 let mut fds = Vec::with_capacity(paths.len());
458 for path in paths {
459 let granted = match self.serving.grants.grant(&caller, path, choice) {
460 Ok(granted) => granted,
461 Err(reason) => {
462 tracing::debug!(%reason, path = %path.display(), "a chosen item is not kept for the app");
463 return (failed(id, &reason), Vec::new());
464 }
465 };
466 match open_document(&granted, choice) {
467 Ok(fd) => {
468 documents.push(HandedDocument {
469 reference: granted.reference,
470 name: granted.name,
471 });
472 fds.push(crate::shell::Descriptor::from(fd));
473 }
474 Err(error) => {
475 tracing::debug!(%error, "a chosen item cannot be opened for the app");
476 return (failed(id, DOES_NOT_FIT), Vec::new());
477 }
478 }
479 }
480 if documents.is_empty() {
481 return (failed(id, DOES_NOT_FIT), Vec::new());
482 }
483 (Reply::Handed { id, documents }, fds)
484 }
485
486 fn reopen(
489 &self,
490 id: u64,
491 reference: &Path,
492 write: bool,
493 ) -> (Reply, Vec<crate::shell::Descriptor>) {
494 let opened = (|| {
495 let caller = self.caller();
496 let granted = self
497 .serving
498 .grants
499 .document(&caller, reference)
500 .ok_or(NOT_CHOSEN)?;
501 let within = reference
502 .strip_prefix(&granted.reference)
503 .map_err(|_| NOT_CHOSEN)?;
504 let relative = plain_relative(within).ok_or(NOT_CHOSEN)?;
505 let file = if relative.as_os_str().is_empty() {
506 let choice = if write { granted.choice } else { Choice::Read };
507 File::from(open_document(&granted, choice).map_err(|_| NOT_CHOSEN)?)
508 } else {
509 if !matches!(granted.choice, Choice::Folder { .. }) {
510 return Err(NOT_CHOSEN);
511 }
512 if write && !granted.choice.writes() {
513 return Err(NOT_CHOSEN);
514 }
515 open_beneath(&granted.host, &relative, write)?
516 };
517 let name = relative.file_name().map_or_else(
518 || granted.name.clone(),
519 |name| name.to_string_lossy().into_owned(),
520 );
521 Ok((
522 OwnedFd::from(file),
523 HandedDocument {
524 reference: reference.to_path_buf(),
525 name,
526 },
527 ))
528 })();
529 match opened {
530 Ok((fd, document)) => (
531 Reply::Handed {
532 id,
533 documents: vec![document],
534 },
535 vec![crate::shell::Descriptor::from(fd)],
536 ),
537 Err(reason) => (failed(id, reason), Vec::new()),
538 }
539 }
540
541 fn saved(&self, id: u64, reference: &Path) -> Reply {
543 let renamed = (|| {
544 let caller = self.caller();
545 let granted = self
546 .serving
547 .grants
548 .document(&caller, reference)
549 .ok_or(NOT_CHOSEN)?;
550 if granted.choice != Choice::Save || granted.reference != reference {
551 return Err(NOT_CHOSEN);
552 }
553 let beside = granted.save_sibling.ok_or(NOT_CHOSEN)?;
554 std::fs::rename(granted.host.with_file_name(beside), &granted.host).map_err(|_| GONE)
555 })();
556 match renamed {
557 Ok(()) => Reply::Saved { id },
558 Err(reason) => failed(id, reason),
559 }
560 }
561
562 fn opened_path(&self, path: &Path) -> Result<PathBuf, &'static str> {
564 let granted = self
565 .serving
566 .grants
567 .document(&self.caller(), path)
568 .ok_or(NOT_CHOSEN)?;
569 let within = path
570 .strip_prefix(&granted.reference)
571 .map_err(|_| NOT_CHOSEN)?;
572 if within.as_os_str().is_empty() {
573 return Ok(granted.host);
574 }
575 plain_relative(within).ok_or(NOT_CHOSEN)?;
576 if matches!(granted.choice, Choice::Folder { .. }) {
578 Ok(granted.host.join(within))
579 } else {
580 Err(NOT_CHOSEN)
581 }
582 }
583
584 fn open_uri(&self, id: u64, uri: &str) -> Reply {
587 let Ok(parsed) = url::Url::parse(uri) else {
588 return failed(id, BAD_LINK);
589 };
590 if parsed.scheme() == "file" {
591 let Ok(path) = parsed.to_file_path() else {
592 return failed(id, BAD_LINK);
593 };
594 let host = match self.opened_path(&path) {
595 Ok(host) => host,
596 Err(reason) => return failed(id, reason),
597 };
598 let Some(uri) = file_uri(&host) else {
599 return failed(id, NOT_CHOSEN);
600 };
601 return match self.open(&uri) {
602 Ok(true) => Reply::Opened { id },
603 Ok(false) => failed(id, NOTHING_OPENS),
604 Err(reason) => failed(id, reason),
605 };
606 }
607 match self.open(uri) {
608 Ok(true) => Reply::Opened { id },
609 Ok(false) => Reply::Unclaimed { id },
610 Err(reason) => failed(id, reason),
611 }
612 }
613
614 fn open(&self, uri: &str) -> Result<bool, &'static str> {
616 match self.serving.opens.open(&self.workspace, uri) {
617 Ok(opened) => Ok(opened.is_some()),
618 Err(error) => {
619 tracing::warn!(app = %self.app, %error, "what an app asked to open did not open");
620 Err(DID_NOT_OPEN)
621 }
622 }
623 }
624}
625
626fn open_document(granted: &Granted, choice: Choice) -> Result<OwnedFd, std::io::Error> {
629 let file = match choice {
630 Choice::Read => crate::portal::open_regular_file(&granted.host)?,
631 Choice::Folder { .. } => crate::portal::open_directory_handle(&granted.host)?,
632 Choice::Save => open_for_save(granted)?,
633 };
634 Ok(OwnedFd::from(file))
635}
636
637fn open_for_save(granted: &Granted) -> std::io::Result<File> {
638 let beside = granted.save_sibling.clone().ok_or_else(|| {
639 std::io::Error::new(
640 std::io::ErrorKind::InvalidInput,
641 "a save writes beside a file",
642 )
643 })?;
644 OpenOptions::new()
645 .write(true)
646 .create(true)
647 .truncate(true)
648 .mode(0o644)
649 .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
650 .open(granted.host.with_file_name(beside))
651}
652
653fn plain_relative(relative: &Path) -> Option<PathBuf> {
656 let mut plain = PathBuf::new();
657 for component in relative.components() {
658 match component {
659 Component::Normal(name) => plain.push(name),
660 _ => return None,
661 }
662 }
663 Some(plain)
664}
665
666fn open_beneath(root: &Path, relative: &Path, write: bool) -> Result<File, &'static str> {
669 let directory = crate::portal::open_directory_handle(root).map_err(|_| NOT_CHOSEN)?;
670 let mut current = OwnedFd::from(directory);
671 let parts: Vec<&std::ffi::OsStr> = relative.iter().collect();
672 let count = parts.len();
673 for (at, part) in parts.into_iter().enumerate() {
674 let last = at.saturating_add(1) == count;
675 let flags = if last && write {
676 libc::O_WRONLY | libc::O_CREAT | libc::O_TRUNC | libc::O_NOFOLLOW | libc::O_CLOEXEC
677 } else if last {
678 libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_CLOEXEC
679 } else {
680 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC
681 };
682 let name = CString::new(part.as_bytes()).map_err(|_| NOT_CHOSEN)?;
683 let fd = unsafe { libc::openat(current.as_raw_fd(), name.as_ptr(), flags, 0o644) };
685 if fd < 0 {
686 return Err(NOT_CHOSEN);
687 }
688 current = unsafe { OwnedFd::from_raw_fd(fd) };
690 }
691 let file = File::from(current);
692 if write && !file.metadata().map_err(|_| NOT_CHOSEN)?.is_file() {
693 return Err(NOT_CHOSEN);
694 }
695 Ok(file)
696}
697
698fn file_uri(path: &Path) -> Option<String> {
700 url::Url::from_file_path(path).ok().map(String::from)
701}
702
703fn failed(id: u64, reason: &str) -> Reply {
704 Reply::Failed {
705 id,
706 reason: reason.to_owned(),
707 }
708}
709
710#[cfg(all(test, unix))]
711mod tests {
712 use std::collections::HashMap;
713 use std::io::Read as _;
714 use std::path::{Path, PathBuf};
715 use std::sync::Arc;
716
717 use super::*;
718 use crate::portal::{OpenFileOutcome, PickRequest, SaveOutcome};
719
720 struct Chosen(PathBuf);
722
723 impl Person for Chosen {
724 fn choose(
725 &self,
726 _caller: &Caller,
727 _handle: String,
728 _question: &Question,
729 ) -> Result<Vec<PathBuf>, Asked> {
730 Ok(vec![self.0.clone()])
731 }
732 }
733
734 #[derive(Default)]
736 struct Kept(Mutex<HashMap<PathBuf, Granted>>);
737
738 impl Grants for Kept {
739 fn grant(
740 &self,
741 _caller: &Caller,
742 chosen: &Path,
743 choice: Choice,
744 ) -> Result<Granted, String> {
745 let name = chosen
746 .file_name()
747 .map(|name| name.to_string_lossy().into_owned())
748 .ok_or_else(|| "the choice names no file".to_owned())?;
749 let reference = Path::new("/run/tilo/chosen/records")
750 .join("test")
751 .join(&name);
752 let save_sibling = (choice == Choice::Save).then(|| {
753 let mut sibling = std::ffi::OsString::from(".");
754 sibling.push(&name);
755 sibling.push(".tilo-save");
756 sibling
757 });
758 let granted = Granted {
759 reference: reference.clone(),
760 name,
761 host: chosen.to_path_buf(),
762 choice,
763 save_sibling,
764 };
765 self.0
766 .lock()
767 .unwrap_or_else(std::sync::PoisonError::into_inner)
768 .insert(reference, granted.clone());
769 Ok(granted)
770 }
771
772 fn document(&self, _caller: &Caller, reference: &Path) -> Option<Granted> {
773 let kept = self
774 .0
775 .lock()
776 .unwrap_or_else(std::sync::PoisonError::into_inner);
777 kept.iter()
778 .find(|(given, _)| reference.starts_with(given))
779 .map(|(_, granted)| granted.clone())
780 }
781 }
782
783 struct NoOpen;
784
785 impl Opens for NoOpen {
786 fn open(&self, _workspace: &str, _uri: &str) -> Result<Option<()>, String> {
787 Ok(None)
788 }
789 }
790
791 #[test]
792 fn a_choice_hands_its_descriptor_and_a_reference_it_alone_reopens() {
793 let directory = tempfile::tempdir().unwrap();
794 let chosen = directory.path().join("plan.txt");
795 std::fs::write(&chosen, "Spring planting").unwrap();
796 let serving = Serving {
797 person: Some(Arc::new(Chosen(chosen))),
798 grants: Arc::new(Kept::default()),
799 opens: Arc::new(NoOpen),
800 };
801 let stream = pair(
802 serving,
803 "so.tilo.notes",
804 "5ba25f73-87c5-447f-a5a6-880dc4249a81",
805 )
806 .unwrap();
807 let picker = crate::shell::picker(stream, crate::unavailable_picker()).unwrap();
808
809 let opened = picker
812 .open_handle(PickRequest::open("Import a plan", "Import"))
813 .recv_timeout(tilo_test_env::hang_bound())
814 .unwrap();
815 let OpenFileOutcome::Opened(opened) = opened else {
816 panic!("the chosen file was not handed over");
817 };
818 assert_eq!(opened.display_name(), "plan.txt");
819 let reference = opened
820 .reference()
821 .expect("a reference names it")
822 .to_path_buf();
823 let mut file = opened.into_file();
824 let mut contents = String::new();
825 file.read_to_string(&mut contents).unwrap();
826 assert_eq!(contents, "Spring planting");
827
828 let reopened = picker
830 .reopen(&reference, false)
831 .recv_timeout(tilo_test_env::hang_bound())
832 .unwrap();
833 let OpenFileOutcome::Opened(reopened) = reopened else {
834 panic!("a reference the app was given reopens");
835 };
836 let mut file = reopened.into_file();
837 let mut contents = String::new();
838 file.read_to_string(&mut contents).unwrap();
839 assert_eq!(contents, "Spring planting");
840
841 for never in [
843 PathBuf::from("/etc/passwd"),
844 directory.path().join("never.txt"),
845 ] {
846 let refused = picker
847 .reopen(&never, false)
848 .recv_timeout(tilo_test_env::hang_bound())
849 .unwrap();
850 assert!(
851 matches!(refused, OpenFileOutcome::Failed(_)),
852 "{} must not be reachable through the chooser",
853 never.display()
854 );
855 }
856 }
857
858 #[test]
859 fn a_save_writes_beside_the_file_and_commits_over_it() {
860 let directory = tempfile::tempdir().unwrap();
861 let destination = directory.path().join("report.txt");
862 let serving = Serving {
863 person: Some(Arc::new(Chosen(destination.clone()))),
864 grants: Arc::new(Kept::default()),
865 opens: Arc::new(NoOpen),
866 };
867 let stream = pair(
868 serving,
869 "so.tilo.notes",
870 "5ba25f73-87c5-447f-a5a6-880dc4249a81",
871 )
872 .unwrap();
873 let picker = crate::shell::picker(stream, crate::unavailable_picker()).unwrap();
874
875 let saving = picker.save_contents(
876 PickRequest::save("Save the report", "Save", "report.txt"),
877 b"the report".to_vec(),
878 );
879 let outcome = saving.recv_timeout(tilo_test_env::hang_bound()).unwrap();
880 assert_eq!(outcome, SaveOutcome::Saved, "the chooser commits the save");
881 assert_eq!(std::fs::read(&destination).unwrap(), b"the report");
882
883 let mut left: Vec<_> = std::fs::read_dir(directory.path())
884 .unwrap()
885 .map(|entry| entry.unwrap().file_name())
886 .collect();
887 left.sort();
888 assert_eq!(
889 left,
890 ["report.txt"],
891 "the bytes are written beside the file and the file is the only thing left"
892 );
893 }
894}