Skip to main content

egui_pop_api/about/
report.rs

1//! Report a problem: the new-issue URL `help.report` opens, prefilled
2//! with what a maintainer asks first (the version info, the platform, the
3//! page shown, the last inspect pick). An idea (`help.suggest`,
4//! [`Report::idea_url`]) carries its title and the page alone.
5//!
6//! The URL follows GitHub's query parameters: `title` and `body`, or,
7//! with an issue form (`template=bug.yml`), one parameter per form field,
8//! named by the field's `id` ([`FIELD_VERSION`], [`FIELD_PLATFORM`],
9//! [`FIELD_PAGE`], [`FIELD_PICK`]). It is kept under [`URL_LIMIT`]
10//! bytes: the pick is trimmed first, then the page, each ending
11//! `(trimmed)`.
12//!
13//! ```
14//! use egui_pop_api::about::report::{Report, URL_LIMIT};
15//!
16//! let report = Report {
17//!     title: "Problem in Files".into(),
18//!     version: "Darkroom 1.2.0\negui-pop 0.3.0\n".into(),
19//!     platform: "linux x86_64".into(),
20//!     page: Some("Files".into()),
21//!     pick: None,
22//! };
23//! let url = report.url("https://github.com/o/r/issues", Some("bug.yml"));
24//! assert!(url.url.starts_with("https://github.com/o/r/issues/new?template=bug.yml&title=Problem%20in%20Files&"));
25//! assert!(url.url.len() <= URL_LIMIT && !url.trimmed);
26//! ```
27
28use serde::Serialize;
29
30/// The longest URL built, in bytes: GitHub answers 414 a little over
31/// 8 KB.
32pub const URL_LIMIT: usize = 8000;
33
34/// The issue form fields the URL fills, by `id` (the repository's form
35/// declares them; `.github/ISSUE_TEMPLATE/bug.yml` in egui-pop's).
36pub const FIELD_VERSION: &str = "version";
37pub const FIELD_PLATFORM: &str = "platform";
38pub const FIELD_PAGE: &str = "page";
39pub const FIELD_PICK: &str = "pick";
40
41/// What ends a trimmed field.
42pub const TRIMMED: &str = "\n(trimmed)";
43
44/// What a report says before the reporter writes a word.
45#[derive(Clone, Debug, Default, PartialEq, Serialize)]
46pub struct Report {
47    pub title: String,
48    /// The version info, without its platform line.
49    pub version: String,
50    /// Where the application runs (`AppInfo::platform`).
51    pub platform: String,
52    /// The page or view shown, when the application can say.
53    pub page: Option<String>,
54    /// The last inspect pick, as its text block.
55    pub pick: Option<String>,
56}
57
58/// A new-issue URL, and whether a field was trimmed to fit.
59#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
60pub struct IssueUrl {
61    pub url: String,
62    pub trimmed: bool,
63}
64
65impl Report {
66    /// The new-issue URL under `issues` (the issue list,
67    /// `https://github.com/owner/repo/issues`; `…/issues/new` is taken as
68    /// is). `form`: the issue form's file name (`bug.yml`), its fields
69    /// then filled one by one; without it, everything goes in the body.
70    pub fn url(&self, issues: &str, form: Option<&str>) -> IssueUrl {
71        let base = issues.trim_end_matches('/');
72        let base = if base.ends_with("/new") {
73            base.to_string()
74        } else {
75            format!("{base}/new")
76        };
77        let build = |page: Option<&str>, pick: Option<&str>| -> String {
78            let mut q: Vec<(&str, String)> = Vec::new();
79            if let Some(f) = form {
80                q.push(("template", f.to_string()));
81            }
82            q.push(("title", self.title.clone()));
83            match form {
84                Some(_) => {
85                    q.push((FIELD_VERSION, self.version.clone()));
86                    q.push((FIELD_PLATFORM, self.platform.clone()));
87                    if let Some(p) = page {
88                        q.push((FIELD_PAGE, p.to_string()));
89                    }
90                    if let Some(p) = pick {
91                        q.push((FIELD_PICK, p.to_string()));
92                    }
93                }
94                None => q.push(("body", self.body(page, pick))),
95            }
96            let query: Vec<String> = q
97                .iter()
98                .map(|(k, v)| format!("{k}={}", encode(v)))
99                .collect();
100            format!("{base}?{}", query.join("&"))
101        };
102        let page = self.page.as_deref();
103        let full = build(page, self.pick.as_deref());
104        if full.len() <= URL_LIMIT {
105            return IssueUrl {
106                url: full,
107                trimmed: false,
108            };
109        }
110        // The pick first, then the page.
111        if let Some(pick) = &self.pick
112            && let Some(url) = fit(pick, |p| build(page, Some(p)))
113        {
114            return IssueUrl { url, trimmed: true };
115        }
116        let url = match page {
117            Some(p) => fit(p, |p| build(Some(p), None)).unwrap_or_else(|| build(None, None)),
118            None => build(None, None),
119        };
120        IssueUrl { url, trimmed: true }
121    }
122
123    /// The new-issue URL of an idea under `issues`: its title and the
124    /// page, in the idea form `form` (`feature.yml`, its page field
125    /// [`FIELD_PAGE`]) or in the body without one. The version info, the
126    /// platform and the pick are left out: an idea is not a bug.
127    pub fn idea_url(&self, issues: &str, form: Option<&str>) -> IssueUrl {
128        let base = issues.trim_end_matches('/');
129        let base = if base.ends_with("/new") {
130            base.to_string()
131        } else {
132            format!("{base}/new")
133        };
134        let build = |page: Option<&str>| -> String {
135            let mut q: Vec<(&str, String)> = Vec::new();
136            if let Some(f) = form {
137                q.push(("template", f.to_string()));
138            }
139            q.push(("title", self.title.clone()));
140            match (form, page) {
141                (Some(_), Some(p)) => q.push((FIELD_PAGE, p.to_string())),
142                (Some(_), None) => {}
143                (None, _) => {
144                    let mut body =
145                        String::from("### The idea\n\n\n\n### How you do it today\n\n\n");
146                    if let Some(p) = page {
147                        body.push_str("\n### Page\n\n");
148                        body.push_str(p);
149                        body.push('\n');
150                    }
151                    q.push(("body", body));
152                }
153            }
154            let query: Vec<String> = q
155                .iter()
156                .map(|(k, v)| format!("{k}={}", encode(v)))
157                .collect();
158            format!("{base}?{}", query.join("&"))
159        };
160        let full = build(self.page.as_deref());
161        if full.len() <= URL_LIMIT {
162            return IssueUrl {
163                url: full,
164                trimmed: false,
165            };
166        }
167        let url = match self.page.as_deref() {
168            Some(p) => fit(p, |p| build(Some(p))).unwrap_or_else(|| build(None)),
169            None => build(None),
170        };
171        IssueUrl { url, trimmed: true }
172    }
173
174    /// The body without an issue form: a section per field, the
175    /// reporter's three first.
176    pub fn body(&self, page: Option<&str>, pick: Option<&str>) -> String {
177        let mut s = String::from(
178            "### What happened\n\n\n\n### What you expected\n\n\n\n### Steps to reproduce\n\n1. \n\n",
179        );
180        s.push_str("### Version info\n\n```text\n");
181        s.push_str(self.version.trim_end());
182        s.push_str("\n```\n\n### Platform\n\n");
183        s.push_str(&self.platform);
184        s.push('\n');
185        if let Some(p) = page {
186            s.push_str("\n### Page\n\n");
187            s.push_str(p);
188            s.push('\n');
189        }
190        if let Some(p) = pick {
191            s.push_str("\n### Inspected element\n\n```text\n");
192            s.push_str(p.trim_end());
193            s.push_str("\n```\n");
194        }
195        s
196    }
197}
198
199/// The longest start of `text`, ended with [`TRIMMED`], whose URL
200/// (`build`) fits; `None` when not even the mark alone fits.
201fn fit(text: &str, build: impl Fn(&str) -> String) -> Option<String> {
202    let cuts: Vec<usize> = text
203        .char_indices()
204        .map(|(i, _)| i)
205        .chain([text.len()])
206        .collect();
207    let at = |n: usize| format!("{}{TRIMMED}", text[..cuts[n]].trim_end());
208    if build(&at(0)).len() > URL_LIMIT {
209        return None;
210    }
211    // The largest number of characters kept that fits.
212    let (mut lo, mut hi) = (0, cuts.len() - 1);
213    while lo < hi {
214        let mid = (lo + hi).div_ceil(2);
215        if build(&at(mid)).len() <= URL_LIMIT {
216            lo = mid;
217        } else {
218            hi = mid - 1;
219        }
220    }
221    Some(build(&at(lo)))
222}
223
224/// Percent-encodes a query value: everything but the unreserved
225/// characters (RFC 3986), as UTF-8 bytes.
226pub fn encode(text: &str) -> String {
227    let mut out = String::with_capacity(text.len());
228    for b in text.bytes() {
229        match b {
230            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
231                out.push(b as char);
232            }
233            _ => out.push_str(&format!("%{b:02X}")),
234        }
235    }
236    out
237}
238
239/// A browser and its operating system, read from a user agent string
240/// (`Firefox 132 on Linux`); the string itself when neither is known.
241pub fn describe_user_agent(ua: &str) -> String {
242    let version = |marker: &str| -> Option<String> {
243        let rest = &ua[ua.find(marker)? + marker.len()..];
244        let v: String = rest
245            .chars()
246            .take_while(|c| c.is_ascii_digit() || *c == '.')
247            .collect();
248        let major = v.split('.').next().unwrap_or("").to_string();
249        (!major.is_empty()).then_some(major)
250    };
251    let named = |name: &str, marker: &str| version(marker).map(|v| format!("{name} {v}"));
252    let browser = named("Edge", "Edg/")
253        .or_else(|| named("Opera", "OPR/"))
254        .or_else(|| named("Samsung Internet", "SamsungBrowser/"))
255        .or_else(|| named("Firefox", "Firefox/"))
256        .or_else(|| named("Firefox", "FxiOS/"))
257        .or_else(|| named("Chrome", "CriOS/"))
258        .or_else(|| named("Chrome", "Chrome/"))
259        .or_else(|| {
260            ua.contains("Safari/")
261                .then(|| named("Safari", "Version/"))
262                .flatten()
263        });
264    let os = if ua.contains("Windows") {
265        Some("Windows")
266    } else if ua.contains("Android") {
267        Some("Android")
268    } else if ua.contains("iPhone") || ua.contains("iPad") {
269        Some("iOS")
270    } else if ua.contains("Mac OS X") || ua.contains("Macintosh") {
271        Some("macOS")
272    } else if ua.contains("CrOS") {
273        Some("ChromeOS")
274    } else if ua.contains("Linux") {
275        Some("Linux")
276    } else {
277        None
278    };
279    match (browser, os) {
280        (Some(b), Some(o)) => format!("{b} on {o}"),
281        (Some(b), None) => b,
282        (None, Some(o)) => format!("an unknown browser on {o}: {ua}"),
283        (None, None) => ua.to_string(),
284    }
285}