1use std::hash::Hash;
9
10use crate::*;
11
12use std::future::{Future, IntoFuture};
17use std::pin::Pin;
18
19use day_spec::present::{ButtonRole, PresentButton, PresentResult, PresentSpec};
20
21type Presenting<T> = Pin<Box<dyn Future<Output = T>>>;
23
24pub struct Alert<T> {
35 title: String,
36 message: Option<String>,
37 sheet: bool,
38 buttons: Vec<(String, ButtonRole, Option<T>)>,
40}
41
42pub fn alert<M>(title: impl IntoText<M>) -> Alert<()> {
43 Alert {
44 title: title.into_text().initial(),
45 message: None,
46 sheet: false,
47 buttons: Vec::new(),
48 }
49}
50
51impl<T> Alert<T> {
52 pub fn new<M>(title: impl IntoText<M>) -> Alert<T> {
53 Alert {
54 title: title.into_text().initial(),
55 message: None,
56 sheet: false,
57 buttons: Vec::new(),
58 }
59 }
60 pub fn message<M>(mut self, m: impl IntoText<M>) -> Self {
61 self.message = Some(m.into_text().initial());
62 self
63 }
64 pub fn sheet(mut self) -> Self {
66 self.sheet = true;
67 self
68 }
69 pub fn button<M>(mut self, label: impl IntoText<M>, value: T) -> Self {
71 self.buttons.push((
72 label.into_text().initial(),
73 ButtonRole::Default,
74 Some(value),
75 ));
76 self
77 }
78 pub fn destructive<M>(mut self, label: impl IntoText<M>, value: T) -> Self {
80 self.buttons.push((
81 label.into_text().initial(),
82 ButtonRole::Destructive,
83 Some(value),
84 ));
85 self
86 }
87 pub fn cancel<M>(mut self, label: impl IntoText<M>) -> Self {
89 self.buttons
90 .push((label.into_text().initial(), ButtonRole::Cancel, None));
91 self
92 }
93
94 pub async fn present(self) -> Option<T> {
96 let spec = PresentSpec::Dialog {
97 title: self.title,
98 message: self.message,
99 buttons: self
100 .buttons
101 .iter()
102 .map(|(label, role, _)| PresentButton {
103 label: label.clone(),
104 role: *role,
105 })
106 .collect(),
107 sheet: self.sheet,
108 };
109 let mut payloads: Vec<Option<T>> = self.buttons.into_iter().map(|(_, _, v)| v).collect();
110 match day_core::present(spec).await {
111 PresentResult::Button(i) => {
112 let i = i as usize;
113 if i < payloads.len() {
114 payloads[i].take()
115 } else {
116 None
117 }
118 }
119 _ => None,
120 }
121 }
122}
123
124impl<T: 'static> IntoFuture for Alert<T> {
125 type Output = Option<T>;
126 type IntoFuture = Presenting<Option<T>>;
127 fn into_future(self) -> Self::IntoFuture {
128 Box::pin(self.present())
129 }
130}
131
132pub struct Confirm {
134 title: String,
135 message: Option<String>,
136 confirm: String,
137 cancel: String,
138 destructive: bool,
139}
140
141pub fn confirm<M>(title: impl IntoText<M>) -> Confirm {
142 Confirm {
143 title: title.into_text().initial(),
144 message: None,
145 confirm: day_localization::t(day_localization::key::day_ok),
148 cancel: day_localization::t(day_localization::key::day_cancel),
149 destructive: false,
150 }
151}
152
153impl Confirm {
154 pub fn message<M>(mut self, m: impl IntoText<M>) -> Self {
155 self.message = Some(m.into_text().initial());
156 self
157 }
158 pub fn confirm_label<M>(mut self, label: impl IntoText<M>) -> Self {
159 self.confirm = label.into_text().initial();
160 self
161 }
162 pub fn cancel_label<M>(mut self, label: impl IntoText<M>) -> Self {
163 self.cancel = label.into_text().initial();
164 self
165 }
166 pub fn destructive(mut self) -> Self {
168 self.destructive = true;
169 self
170 }
171 pub async fn present(self) -> bool {
172 let confirm_role = if self.destructive {
173 ButtonRole::Destructive
174 } else {
175 ButtonRole::Default
176 };
177 let spec = PresentSpec::Dialog {
178 title: self.title,
179 message: self.message,
180 buttons: vec![
181 PresentButton {
182 label: self.cancel,
183 role: ButtonRole::Cancel,
184 },
185 PresentButton {
186 label: self.confirm,
187 role: confirm_role,
188 },
189 ],
190 sheet: false,
191 };
192 matches!(day_core::present(spec).await, PresentResult::Button(1))
194 }
195}
196
197impl IntoFuture for Confirm {
198 type Output = bool;
199 type IntoFuture = Presenting<bool>;
200 fn into_future(self) -> Self::IntoFuture {
201 Box::pin(self.present())
202 }
203}
204
205pub struct Prompt {
207 title: String,
208 message: Option<String>,
209 placeholder: String,
210 initial: String,
211 ok: String,
212 cancel: String,
213}
214
215pub fn prompt<M>(title: impl IntoText<M>) -> Prompt {
216 Prompt {
217 title: title.into_text().initial(),
218 message: None,
219 placeholder: String::new(),
220 initial: String::new(),
221 ok: day_localization::t(day_localization::key::day_ok),
223 cancel: day_localization::t(day_localization::key::day_cancel),
224 }
225}
226
227impl Prompt {
228 pub fn message<M>(mut self, m: impl IntoText<M>) -> Self {
229 self.message = Some(m.into_text().initial());
230 self
231 }
232 pub fn placeholder<M>(mut self, p: impl IntoText<M>) -> Self {
233 self.placeholder = p.into_text().initial();
234 self
235 }
236 pub fn initial<M>(mut self, v: impl IntoText<M>) -> Self {
237 self.initial = v.into_text().initial();
238 self
239 }
240 pub fn ok_label<M>(mut self, label: impl IntoText<M>) -> Self {
241 self.ok = label.into_text().initial();
242 self
243 }
244 pub fn cancel_label<M>(mut self, label: impl IntoText<M>) -> Self {
245 self.cancel = label.into_text().initial();
246 self
247 }
248 pub async fn present(self) -> Option<String> {
249 let spec = PresentSpec::Prompt {
250 title: self.title,
251 message: self.message,
252 placeholder: self.placeholder,
253 initial: self.initial,
254 ok: self.ok,
255 cancel: self.cancel,
256 };
257 match day_core::present(spec).await {
258 PresentResult::Text(t) => Some(t),
259 _ => None,
260 }
261 }
262}
263
264impl IntoFuture for Prompt {
265 type Output = Option<String>;
266 type IntoFuture = Presenting<Option<String>>;
267 fn into_future(self) -> Self::IntoFuture {
268 Box::pin(self.present())
269 }
270}
271
272use day_spec::present::FileFilter;
277
278#[derive(Clone, Debug, PartialEq, Eq, Hash)]
290pub struct FileUrl(String);
291
292impl FileUrl {
293 pub fn new(locator: impl Into<String>) -> Self {
295 FileUrl(locator.into())
296 }
297 pub fn as_str(&self) -> &str {
299 &self.0
300 }
301 pub fn local_path(&self) -> Option<std::path::PathBuf> {
304 if self.0.starts_with("file://") {
305 return day_spec::transfer::file_paths(self.0.as_bytes())?
306 .into_iter()
307 .next();
308 }
309 if self.0.contains("://") {
310 return None;
311 }
312 Some(std::path::PathBuf::from(&self.0))
313 }
314 pub fn bookmark(&self, read_only: bool) -> std::io::Result<Vec<u8>> {
318 crate::file_access::bookmark(self, read_only)
319 }
320 pub fn resolve_bookmark(bytes: &[u8]) -> std::io::Result<crate::FileAccess> {
323 crate::file_access::resolve(bytes)
324 }
325 pub fn file_name(&self) -> Option<String> {
327 let s = self.0.trim_end_matches(['/', '\\']);
328 let tail = s.rsplit(['/', '\\']).next().unwrap_or(s);
329 if tail.is_empty() {
330 None
331 } else {
332 Some(tail.to_string())
333 }
334 }
335 pub fn read(&self) -> std::io::Result<Vec<u8>> {
337 match self.local_path() {
338 Some(p) => fs_read(&p),
339 None => Err(std::io::Error::new(
340 std::io::ErrorKind::Unsupported,
341 "content:// URIs are not directly readable",
342 )),
343 }
344 }
345 pub async fn read_limited(&self, limit: usize) -> std::io::Result<Vec<u8>> {
349 #[cfg(target_arch = "wasm32")]
350 {
351 let bytes = self.read()?;
352 if bytes.len() > limit {
353 return Err(std::io::ErrorKind::InvalidData.into());
354 }
355 Ok(bytes)
356 }
357 #[cfg(not(target_arch = "wasm32"))]
358 {
359 let file = self.clone();
362 match day_core::spawn_blocking(move || file.read_bounded(limit)).await {
363 Ok(result) => result,
364 Err(e) => Err(std::io::Error::other(e)),
365 }
366 }
367 }
368 #[cfg(not(target_arch = "wasm32"))]
369 fn read_bounded(&self, limit: usize) -> std::io::Result<Vec<u8>> {
370 use std::io::Read;
371 let path = self.local_path().ok_or(std::io::ErrorKind::Unsupported)?;
372 #[cfg(any(target_os = "macos", target_os = "ios"))]
373 let _access = crate::file_access::scoped_read(&path)?;
374 let file = std::fs::File::open(path)?;
375 if file.metadata()?.len() > limit as u64 {
376 return Err(std::io::ErrorKind::InvalidData.into());
377 }
378 let mut bytes = Vec::new();
379 file.take((limit as u64).saturating_add(1))
380 .read_to_end(&mut bytes)?;
381 if bytes.len() > limit {
382 return Err(std::io::ErrorKind::InvalidData.into());
383 }
384 Ok(bytes)
385 }
386 pub fn read_to_string(&self) -> std::io::Result<String> {
388 match self.local_path() {
389 Some(p) => fs_read(&p).and_then(|b| {
390 String::from_utf8(b).map_err(|_| std::io::ErrorKind::InvalidData.into())
391 }),
392 None => Err(std::io::Error::new(
393 std::io::ErrorKind::Unsupported,
394 "content:// URIs are not directly readable",
395 )),
396 }
397 }
398}
399
400impl std::fmt::Display for FileUrl {
401 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
402 f.write_str(&self.0)
403 }
404}
405
406fn parse_filter(name: impl Into<String>, extensions: &[&str]) -> FileFilter {
407 FileFilter {
408 name: name.into(),
409 extensions: extensions
410 .iter()
411 .map(|e| e.trim_start_matches('.').to_string())
412 .collect(),
413 }
414}
415
416pub struct OpenFile {
424 title: String,
425 filters: Vec<FileFilter>,
426}
427
428pub fn open_file() -> OpenFile {
430 OpenFile {
431 title: day_localization::t(day_localization::key::day_open),
432 filters: Vec::new(),
433 }
434}
435
436impl OpenFile {
437 pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
439 self.title = t.into_text().initial();
440 self
441 }
442 pub fn filter(mut self, name: impl Into<String>, extensions: &[&str]) -> Self {
444 self.filters.push(parse_filter(name, extensions));
445 self
446 }
447 pub async fn present(self) -> Option<FileUrl> {
448 let spec = PresentSpec::OpenFile {
449 title: self.title,
450 filters: self.filters,
451 multiple: false,
452 };
453 match day_core::present(spec).await {
454 PresentResult::Files(mut v) if !v.is_empty() => Some(FileUrl(v.remove(0))),
455 _ => None,
456 }
457 }
458}
459
460impl IntoFuture for OpenFile {
461 type Output = Option<FileUrl>;
462 type IntoFuture = Presenting<Option<FileUrl>>;
463 fn into_future(self) -> Self::IntoFuture {
464 Box::pin(self.present())
465 }
466}
467
468pub struct OpenFiles {
477 title: String,
478 filters: Vec<FileFilter>,
479}
480
481pub fn open_files() -> OpenFiles {
483 OpenFiles {
484 title: day_localization::t(day_localization::key::day_open),
485 filters: Vec::new(),
486 }
487}
488
489impl OpenFiles {
490 pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
492 self.title = t.into_text().initial();
493 self
494 }
495 pub fn filter(mut self, name: impl Into<String>, extensions: &[&str]) -> Self {
497 self.filters.push(parse_filter(name, extensions));
498 self
499 }
500 pub async fn present(self) -> Vec<FileUrl> {
501 let spec = PresentSpec::OpenFile {
502 title: self.title,
503 filters: self.filters,
504 multiple: true,
505 };
506 match day_core::present(spec).await {
507 PresentResult::Files(v) => v.into_iter().map(FileUrl).collect(),
508 _ => Vec::new(),
509 }
510 }
511}
512
513impl IntoFuture for OpenFiles {
514 type Output = Vec<FileUrl>;
515 type IntoFuture = Presenting<Vec<FileUrl>>;
516 fn into_future(self) -> Self::IntoFuture {
517 Box::pin(self.present())
518 }
519}
520
521pub struct OpenFolder {
532 title: String,
533}
534
535pub fn open_folder() -> OpenFolder {
537 OpenFolder {
538 title: day_localization::t(day_localization::key::day_open_folder),
539 }
540}
541
542impl OpenFolder {
543 pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
545 self.title = t.into_text().initial();
546 self
547 }
548 pub async fn present(self) -> Option<FileUrl> {
549 let spec = PresentSpec::OpenFolder { title: self.title };
550 match day_core::present(spec).await {
551 PresentResult::Files(mut v) if !v.is_empty() => Some(FileUrl(v.remove(0))),
552 _ => None,
553 }
554 }
555}
556
557impl IntoFuture for OpenFolder {
558 type Output = Option<FileUrl>;
559 type IntoFuture = Presenting<Option<FileUrl>>;
560 fn into_future(self) -> Self::IntoFuture {
561 Box::pin(self.present())
562 }
563}
564
565pub struct SaveFile {
575 title: String,
576 suggested_name: String,
577 filters: Vec<FileFilter>,
578 data: Vec<u8>,
579}
580
581pub fn save_file(data: impl Into<Vec<u8>>) -> SaveFile {
583 SaveFile {
584 title: day_localization::t(day_localization::key::day_save),
585 suggested_name: "untitled.txt".to_string(),
586 filters: Vec::new(),
587 data: data.into(),
588 }
589}
590
591impl SaveFile {
592 pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
594 self.title = t.into_text().initial();
595 self
596 }
597 pub fn suggested_name(mut self, name: impl Into<String>) -> Self {
599 self.suggested_name = name.into();
600 self
601 }
602 pub fn filter(mut self, name: impl Into<String>, extensions: &[&str]) -> Self {
604 self.filters.push(parse_filter(name, extensions));
605 self
606 }
607 pub async fn present(self) -> Option<FileUrl> {
608 let mut src = day_core::app_temp_dir();
610 src.push(format!(
611 "day-save-{}-{}",
612 stage_tag(),
613 sanitize_name(&self.suggested_name)
614 ));
615 if !fs_write(&src, &self.data) {
616 return None;
617 }
618 let spec = PresentSpec::SaveFile {
619 title: self.title,
620 suggested_name: self.suggested_name,
621 src_path: src.to_string_lossy().into_owned(),
622 filters: self.filters,
623 };
624 let dest = match day_core::present(spec).await {
625 PresentResult::Files(mut v) if !v.is_empty() => FileUrl(v.remove(0)),
626 _ => {
627 fs_remove(&src);
628 return None;
629 }
630 };
631 if let Some(p) = dest.local_path()
635 && p != src
636 {
637 fs_copy(&src, &p);
638 }
639 fs_remove(&src);
640 Some(dest)
641 }
642}
643
644impl IntoFuture for SaveFile {
645 type Output = Option<FileUrl>;
646 type IntoFuture = Presenting<Option<FileUrl>>;
647 fn into_future(self) -> Self::IntoFuture {
648 Box::pin(self.present())
649 }
650}
651
652#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
656mod files {
657 use std::path::Path;
658 pub(super) fn fs_read(p: &Path) -> std::io::Result<Vec<u8>> {
659 std::fs::read(p)
660 }
661 pub(super) fn fs_write(p: &Path, bytes: &[u8]) -> bool {
662 std::fs::write(p, bytes).is_ok()
663 }
664 pub(super) fn fs_copy(src: &Path, dest: &Path) {
665 let _ = std::fs::copy(src, dest);
666 }
667 pub(super) fn fs_remove(p: &Path) {
668 let _ = std::fs::remove_file(p);
669 }
670 pub(super) fn stage_tag() -> u32 {
671 std::process::id()
672 }
673}
674#[cfg(all(target_family = "wasm", target_os = "unknown"))]
675mod files {
676 use day_spec::present::web_files;
677 use std::path::Path;
678 pub(super) fn fs_read(p: &Path) -> std::io::Result<Vec<u8>> {
679 web_files::read(&p.to_string_lossy())
680 .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "no such web file"))
681 }
682 pub(super) fn fs_write(p: &Path, bytes: &[u8]) -> bool {
683 web_files::write(&p.to_string_lossy(), bytes.to_vec());
684 true
685 }
686 pub(super) fn fs_copy(src: &Path, dest: &Path) {
687 if let Some(b) = web_files::read(&src.to_string_lossy()) {
688 web_files::write(&dest.to_string_lossy(), b);
689 }
690 }
691 pub(super) fn fs_remove(p: &Path) {
692 web_files::remove(&p.to_string_lossy());
693 }
694 pub(super) fn stage_tag() -> u32 {
696 0
697 }
698}
699use files::{fs_copy, fs_read, fs_remove, fs_write, stage_tag};
700
701fn sanitize_name(name: &str) -> String {
703 let s: String = name
704 .chars()
705 .map(|c| {
706 if c.is_alphanumeric() || matches!(c, '.' | '-' | '_') {
707 c
708 } else {
709 '_'
710 }
711 })
712 .collect();
713 if s.is_empty() {
714 "untitled".to_string()
715 } else {
716 s
717 }
718}
719
720#[cfg(all(test, not(target_arch = "wasm32")))]
721mod document_read_tests {
722 use super::*;
723 #[test]
724 fn bounded_read_accepts_exact_limit_rejects_oversize_and_opaque_uris() {
725 let path = std::env::temp_dir().join(format!("day-document-test-{}", std::process::id()));
726 std::fs::write(&path, b"12345").unwrap();
727 let file = FileUrl::new(path.to_str().unwrap());
728 assert_eq!(file.read_bounded(5).unwrap(), b"12345");
729 assert_eq!(
730 file.read_bounded(4).unwrap_err().kind(),
731 std::io::ErrorKind::InvalidData
732 );
733 assert_eq!(
734 FileUrl::new("content://fixture/test")
735 .read_bounded(5)
736 .unwrap_err()
737 .kind(),
738 std::io::ErrorKind::Unsupported
739 );
740 std::fs::remove_file(path).unwrap();
741 }
742}
743
744#[cfg(feature = "conformance")]
745pub(crate) mod conformance {
746 use day_core::conformance::{Case, Drive};
747 use day_reactive::Signal;
748 use day_spec::Cap;
749
750 use crate::*;
751
752 fn asker() -> impl day_core::Piece {
754 let answer = Signal::new(String::from("none"));
755 column((
756 label(move || format!("answer {}", answer.get())).id(day_core::id!(answer)),
757 button("Ask")
758 .action(move || {
759 let set = answer.setter();
760 day_core::task(async move {
761 let yes = confirm("Delete it?").present().await;
762 set.set(if yes { "yes" } else { "no" }.into());
763 });
764 })
765 .id(day_core::id!(ask)),
766 rectangle()
769 .frame(40.0, 40.0)
770 .focusable()
771 .id(day_core::id!(after_dialog)),
772 ))
773 }
774
775 #[day_macros::test(day_core)]
778 fn confirm_native_answer() -> Case {
779 Case::new()
780 .proves_cap(Cap::Dialogs)
781 .proves_duty("present")
782 .proves_duty("dismiss")
783 .requires(Cap::Dialogs)
784 .page(asker)
785 .drive(|d: Drive| async move {
786 d.dialogs_scripted(false).await?;
787 d.tap("ask").await?;
788 d.assert_presented(Some("Delete it?")).await?;
789 d.respond(Some(1)).await?;
790 d.assert_text("answer", "answer yes").await?;
791 d.focus("after_dialog").await?;
794 d.assert_focused("after_dialog", true).await
795 })
796 }
797
798 #[day_macros::test(day_core)]
800 fn confirm_native_dismiss() -> Case {
801 Case::new()
802 .proves_cap(Cap::Dialogs)
803 .requires(Cap::Dialogs)
804 .page(asker)
805 .drive(|d: Drive| async move {
806 d.dialogs_scripted(false).await?;
807 d.tap("ask").await?;
808 d.assert_presented(None).await?;
809 d.respond(None).await?;
810 d.assert_text("answer", "answer no").await?;
811 d.focus("after_dialog").await?;
812 d.assert_focused("after_dialog", true).await
813 })
814 }
815
816 fn prompt_asker() -> impl day_core::Piece {
817 let answer = Signal::new(String::from("pending"));
818 column((
819 label(move || answer.get()).id(day_core::id!(answer)),
820 button("Ask").id(day_core::id!(ask)).action(move || {
821 let set = answer.setter();
822 day_core::task(async move {
823 let value = prompt("Your name")
824 .message("Enter a name")
825 .placeholder("Name")
826 .initial("Ada")
827 .present()
828 .await;
829 set.set(format!("{value:?}"));
830 });
831 }),
832 ))
833 }
834
835 #[day_macros::test(day_core)]
836 fn prompt_native_answer() -> Case {
837 Case::new()
838 .requires(Cap::Dialogs)
839 .proves_cap(Cap::Dialogs)
840 .proves_duty("present")
841 .proves_duty("dismiss")
842 .page(prompt_asker)
843 .drive(|d: Drive| async move {
844 d.dialogs_scripted(false).await?;
845 d.tap("ask").await?;
846 d.assert_presented(Some("Your name")).await?;
847 d.respond_text("Zoë 東京\n\"quoted\"").await?;
848 d.assert_text("answer", "Some(\"Zoë 東京\\n\\\"quoted\\\"\")")
849 .await?;
850 d.tap("ask").await?;
851 d.respond_text("").await?;
852 d.assert_text("answer", "Some(\"\")").await
853 })
854 }
855
856 #[day_macros::test(day_core)]
857 fn prompt_native_dismiss() -> Case {
858 Case::new()
859 .requires(Cap::Dialogs)
860 .proves_cap(Cap::Dialogs)
861 .page(prompt_asker)
862 .drive(|d: Drive| async move {
863 d.dialogs_scripted(false).await?;
864 d.tap("ask").await?;
865 d.assert_presented(Some("Your name")).await?;
866 d.respond(None).await?;
867 d.assert_text("answer", "None").await
868 })
869 }
870
871 #[day_macros::test(day_core)]
872 fn alert_sheet_preserves_button_indices() -> Case {
873 Case::new()
874 .requires(Cap::Dialogs)
875 .proves_cap(Cap::Dialogs)
876 .page(|| {
877 let answer = Signal::new(String::from("pending"));
878 column((
879 label(move || answer.get()).id(day_core::id!(answer)),
880 button("Ask").id(day_core::id!(ask)).action(move || {
881 let set = answer.setter();
882 day_core::task(async move {
883 let value = Alert::new("Choose an action")
884 .sheet()
885 .button("First", 10)
886 .cancel("Cancel")
887 .destructive("Delete", 30)
888 .button("Last", 40)
889 .present()
890 .await;
891 set.set(format!("{value:?}"));
892 });
893 }),
894 ))
895 })
896 .drive(|d: Drive| async move {
897 d.dialogs_scripted(false).await?;
898 d.tap("ask").await?;
899 d.assert_presented(Some("Choose an action")).await?;
900 d.respond(Some(2)).await?;
901 d.assert_text("answer", "Some(30)").await?;
902 d.tap("ask").await?;
903 d.respond(Some(1)).await?;
904 d.assert_text("answer", "None").await
905 })
906 }
907}