8447
Co
conveyor / files
conveyor / templates / library / widgets / editor.rs
24.4 KB
1//! A floating code editor: the project's files as a tree on the left, the picked file on the 2//! right, with line numbers and the caret's line lit; long lines wrap. Text edits in place (Ctrl+S anywhere in the card, or Save, writes it), and Commit 3//! commits the picked changed files with a message. Code is coloured by its language in the 4//! picked scheme (Molokai, Nord, Jellybeans or Kanagawa); PNG, JPEG and SVG show as images, and 5//! Preview toggles a Markdown file between its source and the rendered page. 6//! The project is the one whose desktop this card is on. Opened from a ticket in review (keyed 7//! `branch-<id>`), it browses that ticket's branch instead, read-only, its changed files lit. 8use super::{api::*, look, branch::Snapshot, canvas, code_lang, code_theme, git_commit::{self, Commit}, ui}; 9use rune::{Align, Color, El, Image, ImageCache, Key, KeyEvent, Keybind, Live, ScrollPos, ScrollSpec, Side, Span, SurfaceFit, TextEdit, TextStyle, Tx, col, el, row, text, text_input}; 10use rune_kit::syntax::Syntax; 11use std::{collections::{BTreeSet, HashMap}, path::{Path, PathBuf}, rc::Rc}; 12 13pub const WIDGET: Widget = Widget { title: "Editor", size: (860.0, 540.0), new: |cx| Box::new(Editor::load(cx)) }; 14 15/// Files past this (images aside) show a note instead of their contents. 16const MAX_BYTES: u64 = 2 << 20; 17 18enum Content { 19 None, 20 /// In `Editor::text`. 21 Text, 22 /// Decoding, then decoded. 23 Loading(Image), 24 Image(Image), 25 Note(String), 26} 27 28pub struct Editor { 29 /// The project's folder, and its listings: (name, is_dir), refreshed every 2 s. 30 root: PathBuf, 31 listings: HashMap<PathBuf, Vec<(String, bool)>>, 32 listed_at: f64, 33 expanded: BTreeSet<PathBuf>, 34 file: Option<PathBuf>, 35 content: Content, 36 /// The open text, what's on disk, and what the draft file last got. 37 text: TextEdit, 38 saved: String, 39 drafted: String, 40 images: Rc<ImageCache>, 41 dir: PathBuf, 42 /// The colour scheme dropdown shows. 43 menu: bool, 44 /// The code view's scroll (offset y, viewport height), the offset the caret last followed, 45 /// and the caret a scroll last put down with the column it keeps. 46 scroll: Live<[f32; 2]>, 47 scrolled: f32, 48 goal: Option<(usize, usize)>, 49 /// The width the code wraps at, from its last layout (0 until then: no wrapping). 50 width: f32, 51 /// Why the last save failed, until a save works or another file opens. 52 error: Option<String>, 53 /// The ticket branch this card browses instead of the project's folder, read-only, and the 54 /// selection that typing there goes back to. 55 branch: Option<Snapshot>, 56 held: (usize, usize), 57 /// The Commit dropdown's message, picked files and git runs. 58 commit: Commit, 59 /// Markdown files show rendered instead of their source; kept as the "preview" file. 60 preview: bool, 61} 62 63impl Editor { 64 /// "state": the open file on the first line, then one expanded folder per line. "draft": unsaved text. 65 fn load(cx: &Cx) -> Self { 66 let state = std::fs::read_to_string(cx.dir.join("state")).unwrap_or_default(); 67 let mut lines = state.lines().map(PathBuf::from); 68 let file = lines.next().filter(|p| !p.as_os_str().is_empty()); 69 let branch = cx.id.rsplit('.').next().and_then(|k| k.strip_prefix("branch-")?.parse().ok()) 70 .map(|id| Snapshot::new(super::root::project_of(cx.id), id)); 71 let mut e = Editor { root: branch.as_ref().map_or_else(|| project_dir(cx), |b| b.tree.clone()), listings: HashMap::new(), listed_at: 0.0, expanded: lines.collect(), 72 file: None, content: Content::None, text: TextEdit::new(""), saved: String::new(), drafted: String::new(), images: cx.images(), dir: cx.dir.clone(), menu: false, 73 scroll: Live::new([0.0; 2]), scrolled: 0.0, goal: None, width: 0.0, error: None, branch, held: (0, 0), commit: Commit::load(&cx.dir), 74 preview: cx.dir.join("preview").exists() }; 75 let draft = std::fs::read_to_string(e.dir.join("draft")); 76 if let Some(f) = file { e.open(f) } 77 if let (Content::Text, Ok(draft)) = (&e.content, draft) { e.text.text = draft } 78 e 79 } 80 81 fn save_state(&self) { 82 let open = self.file.as_ref().map(|f| f.display().to_string()).unwrap_or_default(); 83 let lines: String = self.expanded.iter().map(|d| format!("{}\n", d.display())).collect(); 84 let _ = std::fs::write(self.dir.join("state"), format!("{open}\n{lines}")); 85 } 86 87 fn open(&mut self, path: PathBuf) { 88 let _ = std::fs::remove_file(self.dir.join("draft")); 89 let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("").to_lowercase(); 90 let size = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0); 91 let image = matches!(ext.as_str(), "png" | "jpg" | "jpeg" | "svg" | "svgz"); 92 self.content = match if size > MAX_BYTES && !image { Ok(vec![]) } else { std::fs::read(&path) } { 93 Err(e) => Content::Note(format!("Can't read it: {e}")), 94 Ok(_) if size > MAX_BYTES && !image => Content::Note(format!("Too large to open here ({})", kb(size))), 95 Ok(b) if image => Content::Loading(self.images.load(b)), 96 Ok(b) => match String::from_utf8(b) { 97 Ok(s) if !s.contains('\0') => { (self.text, self.drafted, self.saved) = (TextEdit::new(s.clone()), s.clone(), s); Content::Text } 98 _ => Content::Note(format!("Binary file ({})", kb(size))), 99 }, 100 }; 101 (self.text.anchor, self.text.focus, self.error) = (0, 0, None); 102 self.file = Some(path); 103 self.save_state(); 104 } 105 106 fn save(&mut self) { 107 let (Some(f), Content::Text, None) = (&self.file, &self.content, &self.branch) else { return }; 108 match std::fs::write(f, &self.text.text) { 109 Ok(()) => { (self.saved, self.error) = (self.text.text.clone(), None); let _ = std::fs::remove_file(self.dir.join("draft")); } 110 Err(e) => self.error = Some(format!("Can't save: {e}")), 111 } 112 } 113 114 fn toggle(&mut self, dir: PathBuf) { 115 if !self.expanded.remove(&dir) { self.listings.insert(dir.clone(), list(&dir)); self.expanded.insert(dir); } 116 self.save_state(); 117 } 118 119 /// A scroll that leaves the caret behind takes it along: to the first line still showing when 120 /// scrolling down, the last when scrolling up, at the column it had. 121 fn follow(&mut self, mono: TextStyle) { 122 let line = mono.line_px(); 123 let [off, height] = self.scroll.get(); 124 let down = off > self.scrolled; 125 if off == self.scrolled { return } 126 self.scrolled = off; 127 let e = &mut self.text; 128 let starts: Vec<usize> = std::iter::once(0).chain(e.text.match_indices('\n').map(|(i, _)| i + 1)).collect(); 129 let at = starts.partition_point(|&s| s <= e.focus) - 1; 130 let tops = tops(&e.text, mono, self.width); 131 let (first, last) = (((off - 8.0) / line).ceil().max(0.0) as usize, ((off + height - 8.0) / line).floor() as usize); 132 let first = tops.partition_point(|&r| r < first).min(starts.len() - 1); 133 let last = tops.partition_point(|&r| r < last).saturating_sub(1).max(first).min(starts.len() - 1); 134 let to = if down && at < first { first.min(last) } else if !down && at > last { last } else { return }; 135 let column = match self.goal { Some((f, c)) if f == e.focus => c, _ => e.text[starts[at]..e.focus].chars().count() }; 136 let end = starts.get(to + 1).map_or(e.text.len(), |&s| s - 1); 137 let focus = e.text[starts[to]..end].char_indices().nth(column).map_or(end, |(i, _)| starts[to] + i); 138 if e.anchor == e.focus { e.anchor = focus } 139 e.focus = focus; 140 self.goal = Some((focus, column)); 141 } 142 143 fn toggle_preview(&mut self) { 144 self.preview = !self.preview; 145 let f = self.dir.join("preview"); 146 let _ = if self.preview { std::fs::write(f, "") } else { std::fs::remove_file(f) }; 147 } 148 149 /// The open file is Markdown text, and it shows rendered. 150 fn previewing(&self) -> bool { 151 self.preview && matches!(self.content, Content::Text) && self.file.as_deref().is_some_and(is_markdown) 152 } 153 154 fn modified(&self) -> bool { 155 matches!(self.content, Content::Text) && self.text.text != self.saved 156 } 157} 158 159impl View for Editor { 160 fn update(&mut self, cx: &Cx) { 161 // A decoded image shows at once: the no-op act asks for a render. 162 if let Content::Loading(i) = &self.content && i.is_ready() { self.content = Content::Image(i.clone()); cx.act(|_| {}) } 163 // A branch's new tip: its files replace the old ones, the open one included. 164 if self.branch.as_mut().is_some_and(|b| b.poll(cx.now, &project_dir(cx))) { 165 self.listed_at = 0.0; 166 if let Some(f) = self.file.clone() { self.open(f) } 167 } 168 let root = self.branch.as_ref().map_or_else(|| project_dir(cx), |b| b.tree.clone()); 169 if root != self.root || cx.now - self.listed_at > 2.0 { (self.root, self.listed_at) = (root, cx.now); self.listings.clear(); } 170 for d in std::iter::once(&self.root).chain(self.expanded.iter().filter(|d| d.starts_with(&self.root))) { 171 if !self.listings.contains_key(d) { self.listings.insert(d.clone(), list(d)); } 172 } 173 // A branch is read-only: typing is undone before it shows, while the caret and selection move freely. 174 if self.branch.is_some() { 175 if self.text.text != self.saved { self.text.text = self.saved.clone(); (self.text.anchor, self.text.focus) = self.held } 176 self.held = (self.text.anchor, self.text.focus); 177 } 178 // Unsaved typing goes to "draft" so a restart keeps it. 179 if matches!(self.content, Content::Text) && self.text.text != self.drafted { 180 self.drafted = self.text.text.clone(); 181 let draft = self.dir.join("draft"); 182 let _ = if self.text.text == self.saved { std::fs::remove_file(draft) } else { std::fs::write(draft, &self.text.text) }; 183 } 184 self.commit.update(cx, &self.root); 185 } 186 187 fn view(&self, cx: &Cx) -> El { 188 let t = look::of(cx); 189 let mut tree = col().w_full(); 190 if self.listings.contains_key(&self.root) { tree = self.tree(cx, tree, &self.root, 0) } 191 else if let Some(b) = self.branch.as_ref().filter(|b| !b.ready()) { 192 tree = tree.child(text(b.error().unwrap_or(format!("Getting branch t-{}…", b.ticket))).font(t.label).color(t.text_secondary).wrap()) 193 } else { tree = tree.child(text(format!("No folder at {}", self.root.display())).font(t.label).color(t.text_secondary).wrap()) } 194 let id = cx.id.to_owned(); 195 // Focusable with a key handler, so Ctrl+S saves from the tree and header as well as the code. 196 col().w_full().h_full().gap(8.0).focusable(true) 197 .on_key(move |h: &mut HostState, k: &KeyEvent, tx: &mut Tx| save_key().matches_tx(k, tx) && get::<Editor>(h, &id).map(|e| e.save()).is_some()) 198 .child(self.header(cx)) 199 .child(el().w_full().h(1.0).fill(t.separator)) 200 .child(row().w_full().grow(1.0).min_h(0.0).gap(8.0) 201 .child(col().key("tree").w_frac(0.25).min_w(120.0).h_full().min_h(0.0).scroll(ScrollSpec { stick_bottom: false }).child(tree)) 202 .child(el().w(1.0).h_full().fill(t.separator)) 203 .child(col().key("content").grow(1.0).min_w(0.0).h_full().min_h(0.0).child(self.content(cx)))) 204 // Last, so it draws over the code. 205 .child(if self.menu { scheme_menu(cx) } else { el() }) 206 .child(git_commit::menu(&t, cx, &self.commit, |e: &mut Editor| &mut e.commit, 207 on(cx.id, |e: &mut Editor, _| { e.save(); e.commit.run(&e.root) }))) 208 } 209} 210 211impl Editor { 212 /// The project, the open file's path under it with a dot while modified, why a save failed, 213 /// a Save button (Saved, greyed, while the file matches the disk), Commit, and ×. 214 fn header(&self, cx: &Cx) -> El { 215 let t = look::of(cx); 216 let project = cx.data.projects.iter().find(|p| Path::new(&p.path) == self.root).map_or("Editor", |p| p.slug.as_str()); 217 let path = self.file.as_ref().map(|f| rel(&self.root, f)).unwrap_or_default(); 218 // The card is focusable, so it takes the press: the header moves the card itself. 219 let mut h = row().key("header").w_full().center_y().gap(8.0).on_drag(canvas::mover(cx)); 220 h = match &self.branch { 221 Some(b) => h.child(text(super::root::project_of(cx.id)).font(t.title).color(t.text)) 222 .child(row().key("branch").px(8.0).py(2.0).radius(8.0).fill(t.press).help("A read-only copy of the ticket's branch; changed files are lit") 223 .child(text(format!("t-{}", b.ticket)).font(t.label).color(t.accent))), 224 None => h.child(text(project).font(t.title).color(t.text)), 225 }; 226 h = h.child(text(path).font(t.label).color(t.text_secondary).truncate().min_w(0.0).shrink()); 227 if self.modified() { h = h.child(text("●").font(t.label).color(t.warn)); } 228 h = h.child(el().grow(1.0)); 229 let error = self.error.clone().or_else(|| self.branch.as_ref().filter(|b| b.ready()).and_then(|b| b.error())); 230 if let Some(e) = &error { h = h.child(text(e.as_str()).key("save-error").font(t.label).color(t.danger).truncate().min_w(0.0).shrink()); } 231 if matches!(self.content, Content::Text) && !self.previewing() { 232 let before = self.text.text.get(..self.text.focus).unwrap_or(""); 233 let col_n = before.len() - before.rfind('\n').map_or(0, |i| i + 1) + 1; 234 h = h.child(text(format!("Ln {}, Col {col_n}", before.matches('\n').count() + 1)).font(t.label).color(t.text_secondary)); 235 } 236 if let Content::Image(i) = &self.content && let Some([w, ht]) = i.size() { 237 h = h.child(text(format!("{w}×{ht}")).font(t.label).color(t.text_secondary)); 238 } 239 if matches!(self.content, Content::Text) && self.file.as_deref().is_some_and(is_markdown) { 240 h = h.child(ui::button(&t, "md-preview", if self.preview { "Source" } else { "Preview" }, true, on(cx.id, |e: &mut Editor, _| e.toggle_preview())) 241 .help(if self.preview { "Show the Markdown source" } else { "Show the rendered Markdown" })); 242 } 243 let commit = git_commit::button(&t, cx, &self.commit, &self.root, on(cx.id, |e: &mut Editor, _| { e.save(); e.commit.toggle_open() })); 244 if self.branch.is_some() { 245 if let Content::Text = self.content { h = h.child(text("Read-only").font(t.label).color(t.text_secondary)).child(scheme_button(cx, self.menu)) } 246 } else if let Content::Text = self.content { 247 let label = if self.modified() { "Save" } else { "Saved" }; 248 h = h.child(ui::primary(&t, "save", label, self.modified(), on(cx.id, |e: &mut Editor, _| e.save())).help(format!("Save ({})", save_key().label()))) 249 .child(commit).child(scheme_button(cx, self.menu)); 250 } else { h = h.child(commit) } 251 h.child(canvas::maximize(cx)).child(canvas::close(cx, "Close editor")) 252 } 253 254 /// `dir`'s entries at `depth`, folders first, with expanded folders' entries under them. 255 fn tree(&self, cx: &Cx, mut tree: El, dir: &Path, depth: usize) -> El { 256 let t = look::of(cx); 257 for (name, is_dir) in self.listings.get(dir).into_iter().flatten() { 258 let path = dir.join(name); 259 let open = *is_dir && self.expanded.contains(&path); 260 let picked = self.file.as_ref() == Some(&path); 261 let changed = self.branch.as_ref().is_some_and(|b| b.changed(&path)); 262 let glyph = if !is_dir { " " } else if open { "▾" } else { "▸" }; 263 let p = path.clone(); 264 tree = tree.child(row().key(format!("node-{}", rel(&self.root, &path).replace('/', "|"))).w_full().min_h(24.0) 265 .pl(6.0 + depth as f32 * 14.0).pr(6.0).gap(6.0).center_y().radius(5.0).role("button").label(name.as_str()) 266 .fill(if picked { t.press } else { t.card }).hover(t.hover) 267 .on_press_tx(on(cx.id, move |e: &mut Editor, _| if p.is_dir() { e.toggle(p.clone()) } else { e.open(p.clone()) })) 268 .child(text(glyph).font(t.label).color(t.text_secondary).w(10.0)) 269 .child(text(name.as_str()).font(t.label).color(if changed { t.accent } else if picked || *is_dir { t.text } else { t.text_secondary }).truncate())); 270 if open { tree = self.tree(cx, tree, &path, depth + 1) } 271 } 272 tree 273 } 274 275 fn content(&self, cx: &Cx) -> El { 276 let t = look::of(cx); 277 let note = |s: &str| col().w_full().h_full().center().child(text(s).font(t.body).color(t.text_secondary)); 278 match &self.content { 279 Content::None => note("Pick a file on the left"), 280 Content::Note(s) => note(s), 281 Content::Loading(_) => note("Loading…"), 282 Content::Image(i) => match (i.size(), i.error()) { 283 (_, Some(e)) => note(&format!("Can't show this image: {e}")), 284 (None, _) => note("Can't show this image"), 285 (Some([w, h]), _) => col().w_full().h_full().center().child(el().key("image").w_full().h_full() 286 .max_w(w as f32).max_h(h as f32).pixels_fit(i.pixels(), SurfaceFit::Fit)), 287 }, 288 Content::Text if self.previewing() => col().key("markdown").w_full().h_full().min_h(0.0).scroll(ScrollSpec { stick_bottom: false }) 289 .child(col().w_full().padding(12.0).child(ui::markdown(&t, &self.text.text, t.body, t.text))), 290 Content::Text => { 291 let scheme = code_theme::of(cx); 292 let lang = self.file.as_deref().map(code_lang::of).unwrap_or_default(); 293 let spans = scheme.syntax().spans(&code_lang::highlight(&lang, &self.text.text), 0); 294 // Each number sits on its line's first row, with a blank gutter row per wrapped row under it. 295 let (line, mono) = (t.mono.line_px(), t.mono); 296 let tops = tops(&self.text.text, mono, self.width); 297 let caret = self.text.text.get(..self.text.focus).unwrap_or("").matches('\n').count(); 298 let digits = (tops.len() - 1).to_string().len(); 299 let numbers: String = tops.windows(2).enumerate().map(|(i, r)| format!("{:>digits$}{}", i + 1, "\n".repeat(r[1] - r[0]))).collect(); 300 let at = tops[caret] + caret * digits; 301 let (id, scroll) = (cx.id.to_owned(), self.scroll.clone()); 302 let wid = id.clone(); 303 col().key("code").w_full().h_full().min_h(0.0).radius(6.0).fill(scheme.bg()).scroll(ScrollSpec { stick_bottom: false }) 304 .on_scroll_offset(move |at: ScrollPos| { scroll.set([at.offset[1], at.viewport[1]]); }) 305 // Laid out again on every frame of a scroll, which is when the caret follows. 306 .child(row().w_full().py(8.0).on_layout(move |h: &mut HostState, _| if let Some(e) = get::<Editor>(h, &id) { e.follow(mono) }) 307 .child(text(numbers.trim_end_matches('\n')).key("gutter").font(t.mono).color(scheme.syntax().color(Syntax::Comment)) 308 .spans(vec![Span { color: Some(scheme.fg()), ..Span::new(at, at + digits) }]) 309 .fill(scheme.bg()).pl(8.0).pr(12.0)) 310 .child(el().key("caret-line").pin(Some(0.0), Some(8.0 + tops[caret] as f32 * line), Some(0.0), None) 311 .h((tops[caret + 1] - tops[caret]) as f32 * line).fill(Color::WHITE.alpha(0.06))) 312 .child(text_input(&self.text, t.mono).wrap_anywhere().grow(1.0).min_w(0.0).pr(8.0).color(scheme.fg()).caret(t.accent, t.accent.alpha(0.3)).spans(spans) 313 .on_layout(move |h: &mut HostState, r: [f32; 4]| if let Some(e) = get::<Editor>(h, &wid) && e.width != r[2] - 8.0 { e.width = r[2] - 8.0 }) 314 .on_edit(edit(cx.id, |e: &mut Editor| &mut e.text)) 315 .on_submit(on(cx.id, |e: &mut Editor, _| newline(&mut e.text))) 316 .on_input_key(keys(cx.id)))) 317 } 318 } 319 } 320} 321 322/// The colour scheme button: the picked scheme with its keyword colour, opening `scheme_menu`. 323fn scheme_button(cx: &Cx, open: bool) -> El { 324 let (t, picked) = (look::of(cx), code_theme::of(cx)); 325 let b = row().key(ui::anchor(cx, "code-theme")).min_h(24.0).px(8.0).gap(6.0).center().radius(6.0).role("button").label("Colour scheme") 326 .hover(t.press).on_press_tx(on(cx.id, |e: &mut Editor, _| e.menu = !e.menu)) 327 .child(swatch(picked)).child(text(picked.name).font(t.label).color(t.text_secondary)) 328 .child(text(if open { "▴" } else { "▾" }).font(t.label).color(t.text_secondary)); 329 el().key("code-theme").child(if open { b.fill(t.press) } else { b }) 330} 331 332/// Every scheme under the button, a check on the picked one; a pick or a click outside closes it. 333fn scheme_menu(cx: &Cx) -> El { 334 let (t, picked, id) = (look::of(cx), code_theme::of(cx), cx.id.to_owned()); 335 let close = |h: &mut HostState, id: &str| if let Some(e) = get::<Editor>(h, id) { e.menu = false }; 336 let mut list = ui::popover(&t, col().key("code-themes").w(160.0).padding(4.0).gap(2.0)) 337 .anchored_fit(ui::anchor(cx, "code-theme"), Side::Bottom, Align::End, 4.0) 338 .modal(true, { let id = id.clone(); move |h: &mut HostState| close(h, &id) }); 339 for s in &code_theme::ALL { 340 let (name, id) = (s.name, id.clone()); 341 list = list.child(row().key(format!("scheme-{name}")).w_full().min_h(28.0).px(8.0).gap(8.0).center_y().radius(5.0) 342 .role("button").label(name).hover(t.hover) 343 .on_press_tx(move |h: &mut HostState, _: &mut Tx| { share(h, "code_theme", name); close(h, &id) }) 344 .child(swatch(s)).child(text(name).font(t.label).color(t.text).grow(1.0)) 345 .child(text(if s.name == picked.name { "✓" } else { "" }).font(t.label).color(t.accent))); 346 } 347 list 348} 349 350fn swatch(s: &code_theme::Scheme) -> El { 351 el().w(10.0).h(10.0).radius(5.0).fill(s.syntax().color(Syntax::Keyword)) 352} 353 354/// The shortcut that saves: Ctrl+S (⌘S on macOS). 355fn save_key() -> Keybind { Keybind::new("mod+s") } 356 357/// In the code: Ctrl+S saves; Tab indents four spaces. 358fn keys(id: &str) -> impl Fn(&mut HostState, &KeyEvent, &mut Tx) -> bool + 'static { 359 let id = id.to_owned(); 360 move |h: &mut HostState, k: &KeyEvent, tx: &mut Tx| { 361 let Some(e) = get::<Editor>(h, &id) else { return false }; 362 if save_key().matches_tx(k, tx) { e.save(); return true } 363 if k.key == Key::Tab && !k.mods.shift { e.text.insert(" "); return true } 364 false 365 } 366} 367 368/// The row each line of `text` starts on when wrapped at `width` in `mono`, and the row count last. 369/// A line short enough for the width at the font's advance is one row without shaping it. 370fn tops(text: &str, mono: TextStyle, width: f32) -> Vec<usize> { 371 let (advance, line) = (rune::text::advance("M", mono), mono.line_px()); 372 let opts = rune::text::RichLayoutOptions::new().wrap_anywhere(); 373 let rows = |l: &str| if width <= 0.0 || (!l.contains('\t') && l.chars().count() as f32 * advance <= width) { 1 } 374 else { ((rune::text::measure_with(l, &[], mono, Some(width), opts).1 / line).round() as usize).max(1) }; 375 std::iter::once(0).chain(text.split('\n').scan(0, |at, l| { *at += rows(l); Some(*at) })).collect() 376} 377 378/// Return: a line break that keeps the current line's indent. 379fn newline(edit: &mut TextEdit) { 380 let before = edit.text.get(..edit.focus.min(edit.anchor)).unwrap_or(""); 381 let line = &before[before.rfind('\n').map_or(0, |i| i + 1)..]; 382 let indent: String = line.chars().take_while(|c| *c == ' ' || *c == '\t').collect(); 383 edit.insert(&format!("\n{indent}")); 384} 385 386/// The folder of the project whose desktop holds this card: `root.canvas-<slug>.<key>`, or the widgets project on `root.canvas`. 387fn project_dir(cx: &Cx) -> PathBuf { 388 let slug = super::root::project_of(cx.id); 389 cx.data.projects.iter().find(|p| p.slug == slug).map(|p| PathBuf::from(&p.path)).unwrap_or_default() 390} 391 392/// A folder's entries, folders first then files, by name; `.git` left out. 393fn list(dir: &Path) -> Vec<(String, bool)> { 394 let mut v: Vec<(String, bool)> = std::fs::read_dir(dir).into_iter().flatten().flatten() 395 .map(|e| (e.file_name().to_string_lossy().into_owned(), e.path().is_dir())) 396 .filter(|(n, _)| n != ".git").collect(); 397 v.sort_by_key(|(n, d)| (!d, n.to_lowercase())); 398 v 399} 400 401fn is_markdown(p: &Path) -> bool { 402 p.extension().and_then(|e| e.to_str()).is_some_and(|e| matches!(e.to_lowercase().as_str(), "md" | "markdown")) 403} 404 405fn rel(root: &Path, p: &Path) -> String { 406 p.strip_prefix(root).unwrap_or(p).display().to_string() 407} 408 409fn kb(n: u64) -> String { 410 if n < 1 << 20 { format!("{:.1} KB", n as f64 / 1024.0) } else { format!("{:.1} MB", n as f64 / 1048576.0) } 411}