forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

files.rs189 lines, 7.8 KiBHistoryRawDownload
1//! Paths in and out: the pickers, the URIs, the names.
2
3use crate::*;
4
5/// How a finished export announces itself. Written by `poll_export` and read
6/// by the notice bar, which is what makes that one line clickable.
7pub(crate) const EXPORT_DONE: &str = "Export done → ";
8
9/// The path as a URI the bus will take: percent-encoded, because an export
10/// lands wherever its source lives and those directories have spaces in them.
11/// Bytes, not chars -- a path is not required to be UTF-8.
12pub(crate) fn file_uri(path: &std::path::Path) -> String {
13 use std::os::unix::ffi::OsStrExt;
14 let mut uri = String::from("file://");
15 for &b in path.as_os_str().as_bytes() {
16 match b {
17 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => {
18 uri.push(b as char)
19 }
20 _ => uri.push_str(&format!("%{b:02X}")),
21 }
22 }
23 uri
24}
25
26/// Shows a file in the desktop's file manager, selected: the freedesktop
27/// interface every major one answers, asked for over the session bus. With no
28/// file manager on the bus the folder itself is the next best thing, and with
29/// neither there is nothing to say -- the notice the click retired was the
30/// answer, and a machine without a desktop opener is not one a second notice
31/// would help. Blocks on two child processes, so it is never called on the UI
32/// thread.
33pub(crate) fn show_in_file_manager(path: &std::path::Path) {
34 // The URI must be absolute; an export path is only as absolute as the
35 // source it was built from.
36 let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
37 let shown = std::process::Command::new("busctl")
38 .args([
39 "--user",
40 "call",
41 "org.freedesktop.FileManager1",
42 "/org/freedesktop/FileManager1",
43 "org.freedesktop.FileManager1",
44 "ShowItems",
45 "ass",
46 "1",
47 &file_uri(&path),
48 "",
49 ])
50 .status()
51 .is_ok_and(|s| s.success());
52 if shown {
53 return;
54 }
55 if let Some(dir) = path.parent() {
56 let _ = std::process::Command::new("xdg-open").arg(dir).status();
57 }
58}
59
60/// Runs the first chooser that is installed. `Some(None)` is a cancelled
61/// dialog; `None` is a machine with no chooser at all, and what still works
62/// without one differs per dialog, so the caller words that refusal.
63///
64/// The desktop's own choosers, asked for by name because gpui 0.2 has no file
65/// dialog of its own and none of these is worth a dependency.
66pub(crate) fn run_picker(pickers: [(&str, Vec<String>); 2]) -> Option<Option<PathBuf>> {
67 for (bin, args) in pickers {
68 // Not installed: try the next one. Anything else (a cancel, a refusal)
69 // is that chooser's answer and is taken as final.
70 let Ok(out) = std::process::Command::new(bin).args(args).output() else {
71 continue;
72 };
73 // A chooser that could not open at all (no display to draw on, a broken toolkit) says
74 // so on stderr and is not a cancel: the next one is tried, and with none left the
75 // caller says no dialog could open.
76 let cancelled = out.status.code() == Some(1) && out.stderr.iter().all(u8::is_ascii_whitespace);
77 if !out.status.success() && !cancelled {
78 continue;
79 }
80 let path = String::from_utf8_lossy(&out.stdout).trim().to_string();
81 return Some((!path.is_empty()).then(|| PathBuf::from(path)));
82 }
83 None
84}
85
86/// `title` is what the dialog calls itself: two buttons open this same chooser
87/// for two different questions -- a file to import, a file to take subtitles out
88/// of -- and a dialog titled "import" over the second one is the wrong question
89/// answered. No extension filter on either: what can be read is the engine's
90/// answer (`PlaybackSession::parse_subtitles` takes a container as readily as a
91/// `.srt`), and a list of suffixes written here would hide a file edith would
92/// have taken.
93pub(crate) fn pick_file(title: &str) -> Result<Option<PathBuf>, &'static str> {
94 run_picker([
95 (
96 "zenity",
97 vec!["--file-selection".into(), format!("--title={title}")],
98 ),
99 ("kdialog", vec!["--getopenfilename".into()]),
100 ])
101 .ok_or(NO_DIALOG)
102}
103
104/// What is said when no file dialog could open (none installed, or none that can draw here). The callers
105/// that can take a typed path open the path sheet instead of saying this.
106pub(crate) const NO_DIALOG: &str = "No file chooser opened here.";
107
108/// A folder chooser, opened on `start`. `Err` is a machine with no chooser at all.
109pub(crate) fn pick_folder(title: &str, start: &std::path::Path) -> Result<Option<PathBuf>, &'static str> {
110 // A trailing slash makes the dialog open inside the folder, not on it.
111 let start = format!("{}/", start.to_string_lossy().trim_end_matches('/'));
112 run_picker([
113 (
114 "zenity",
115 vec!["--file-selection".into(), "--directory".into(), format!("--title={title}"), format!("--filename={start}")],
116 ),
117 ("kdialog", vec!["--getexistingdirectory".into(), start]),
118 ])
119 .ok_or("No folder dialog could open here. Type the path instead.")
120}
121
122/// The save-side dialog, opened on where the export would land anyway: with no
123/// chooser installed that default is still what gets written, so this refusal
124/// costs the export nothing and says so.
125pub(crate) fn pick_save(default: &std::path::Path) -> Result<Option<PathBuf>, &'static str> {
126 let default = default.to_string_lossy().into_owned();
127 run_picker([
128 (
129 "zenity",
130 vec![
131 "--file-selection".into(),
132 // No `--confirm-overwrite`: zenity 4.2 lists it as deprecated
133 // and does the confirming itself.
134 "--save".into(),
135 "--title=edith — export to".into(),
136 format!("--filename={default}"),
137 ],
138 ),
139 ("kdialog", vec!["--getsavefilename".into(), default]),
140 ])
141 .ok_or("No file chooser: exporting beside the source")
142}
143
144/// Where a save goes when the timeline did not come from a project file: the
145/// media path with `.edith` for an extension, beside it like an export. A
146/// project loaded from disk keeps its own path instead, so saving it twice
147/// writes the same file.
148pub(crate) fn project_path(source: impl Into<PathBuf>) -> PathBuf {
149 let mut path = source.into();
150 path.set_extension("edith");
151 path
152}
153
154/// Whether a dropped or named path is a project rather than media. Exactly the
155/// lowercase extension `save_project` writes -- anything else goes to the
156/// demuxer, which is the one that can say what it really is.
157pub(crate) fn is_project(path: &std::path::Path) -> bool {
158 path.extension().is_some_and(|e| e == "edith")
159}
160
161/// A path's name without its extension, for every surface that shows what a
162/// file *is* rather than what it is stored as (cleanse round 2: the bench's
163/// name plates and the ledger's project identity). One place, so the two can
164/// never come to disagree about the same file's name.
165pub(crate) fn stem(path: &std::path::Path) -> String {
166 if let Some(title) = engine::generate::title(path) {
167 return title.into();
168 }
169 if let Some(title) = engine::generate::tone_title(path) {
170 return title;
171 }
172 path.file_stem()
173 .map_or_else(|| file_name(path), |n| n.to_string_lossy().into())
174}
175
176/// The tail of a path, for showing. A path that is all root has none, and reads
177/// as itself.
178pub(crate) fn file_name(path: &std::path::Path) -> String {
179 if let Some(title) = engine::generate::title(path) {
180 return title.into();
181 }
182 if let Some(title) = engine::generate::tone_title(path) {
183 return title;
184 }
185 path.file_name().map_or_else(
186 || path.display().to_string(),
187 |n| n.to_string_lossy().into(),
188 )
189}