Cotton code
50 lines · 2.5 KB · RustRaw
//! How Comms shows a file a message or a mail carries, inside the app (owner, 24 Nov 2026: "a document in a chat//! cannot be opened and read"): a tap opens Comms' own viewer, in every kind of chat and on a mail's attachment, and//! never depends on another app being on the phone.//!//! RULE: a PDF is drawn page by page; words (plain text, CSV, Markdown, JSON, a log, source code, a subtitle file)//! are drawn as words; a picture is drawn as a picture. Anything else (a Word or Excel file, a ZIP) is named in the//! viewer with one line saying Comms cannot show it, and Open in another app. The file's own type decides, and when//! a sender gave none useful (`application/octet-stream`), its name's ending does.use serde::{Deserialize, Serialize};/// What the viewer draws.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "lowercase")]pub enum View {    Pdf,    Text,    Picture,    /// Not drawn here: its name, the line, and Open in another app.    Other,}/// The most of a words file the viewer draws (bytes); longer, it draws this much and says the rest is in the file.pub const TEXT_MOST: u64 = 2 * 1024 * 1024;/// How the viewer shows a file of `mime` named `name`.pub fn view_of(mime: Option<&str>, name: Option<&str>) -> View {    let mime = mime.and_then(|m| m.split(';').next()).map(|m| m.trim().to_ascii_lowercase()).unwrap_or_default();    let by_mime = match mime.as_str() {        "application/pdf" | "application/x-pdf" => Some(View::Pdf),        "image/jpeg" | "image/png" | "image/webp" | "image/gif" | "image/heic" | "image/heif" | "image/bmp" => Some(View::Picture),        "application/json" | "application/xml" | "application/x-subrip" | "application/x-sh" | "application/javascript" | "application/x-yaml" | "application/yaml" => Some(View::Text),        m if m.starts_with("text/") => Some(View::Text),        _ => None,    };    if let Some(view) = by_mime {        return view;    }    let ending = name.and_then(|n| n.rsplit_once('.')).map(|(_, e)| e.trim().to_ascii_lowercase()).unwrap_or_default();    match ending.as_str() {        "pdf" => View::Pdf,        "jpg" | "jpeg" | "png" | "webp" | "gif" | "heic" | "heif" | "bmp" => View::Picture,        "txt" | "text" | "csv" | "tsv" | "md" | "markdown" | "json" | "xml" | "log" | "srt" | "vtt" | "yaml" | "yml" | "ini" | "conf" | "rs" | "kt" | "swift" | "py" | "js" | "ts" | "sh" | "html" | "htm" | "css" | "sql" | "ics" | "vcf" => View::Text,        _ => View::Other,    }}#[cfg(test)]#[path = "viewer_tests.rs"]mod tests;