1use crate::pages::{Page, PageSet};
15use crate::ui::Ui;
16use crate::component::ComponentId;
17
18#[derive(Clone, Copy)]
20pub enum Provided<'a> {
21 Barcode(&'a dyn BarcodeProvider),
22 Export(&'a dyn ExportProvider),
23 Pdf(&'a dyn PdfProvider),
24 MapTiles(&'a dyn MapTileProvider),
25 MediaTags(&'a dyn MediaTagsProvider),
26 Http(&'a dyn HttpProvider),
27 WebSocket(&'a dyn WebSocketProvider),
28 DocumentConverter(&'a dyn DocumentConverterProvider),
29}
30
31#[derive(Clone, Debug, PartialEq, Eq)]
36pub enum BarcodeImage {
37 Linear { modules: Vec<bool>, text: String },
40 Matrix { width: usize, modules: Vec<bool> },
42}
43
44#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
48pub enum ErrorCorrection {
49 Low,
51 #[default]
53 Medium,
54 Quartile,
56 High,
58}
59
60impl crate::prop::PropEnum for ErrorCorrection {
61 const NAMES: &'static [&'static str] = &["low", "medium", "quartile", "high"];
62
63 fn from_index(index: usize) -> Option<Self> {
64 [ErrorCorrection::Low, ErrorCorrection::Medium, ErrorCorrection::Quartile, ErrorCorrection::High].get(index).copied()
65 }
66
67 fn index(self) -> usize {
68 self as usize
69 }
70}
71
72#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
74pub struct BarcodeOptions {
75 pub error_correction: ErrorCorrection,
77}
78
79pub trait BarcodeProvider {
81 fn formats(&self) -> Vec<&'static str>;
83 fn encode(&self, format: &str, data: &str, options: &BarcodeOptions) -> Result<BarcodeImage, String>;
86}
87
88#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
93pub enum ColumnKind {
94 #[default]
95 Text,
96 Integer,
97 Number,
99 Date,
100 DateTime,
101 Bool,
102}
103
104#[derive(Clone, Debug, PartialEq)]
106pub enum CellValue {
107 Empty,
108 Text(String),
109 Number(f64),
110 Bool(bool),
111 Date(i32, u32, u32),
113 DateTime(i32, u32, u32, u32, u32, u32),
115}
116
117#[derive(Clone, Debug, Default, PartialEq)]
119pub struct ExportColumn {
120 pub title: String,
121 pub kind: ColumnKind,
122 pub format: String,
123}
124
125#[derive(Clone, Debug, Default, PartialEq)]
127pub struct ExportTable {
128 pub name: String,
129 pub columns: Vec<ExportColumn>,
130 pub rows: Vec<Vec<CellValue>>,
131}
132
133pub trait ExportProvider {
135 fn extension(&self) -> &'static str;
137 fn mime(&self) -> &'static str;
139 fn write(&self, tables: &[ExportTable]) -> Result<Vec<u8>, String>;
141}
142
143pub trait PdfProvider {
152 fn begin(&self, width: f32, height: f32) -> Result<Box<dyn PdfDocument>, String>;
154
155 fn write(&self, pages: &PageSet) -> Result<Vec<u8>, String> {
157 let mut doc = self.begin(pages.width, pages.height)?;
158 for page in &pages.pages {
159 doc.add_page(page)?;
160 }
161 doc.finish()
162 }
163}
164
165pub trait PdfDocument {
167 fn add_page(&mut self, page: &Page) -> Result<(), String>;
168 fn finish(self: Box<Self>) -> Result<Vec<u8>, String>;
170}
171
172pub trait MapTileProvider {
177 fn tile_url(&self, z: u32, x: u32, y: u32) -> String;
179 fn attribution(&self) -> String;
181}
182
183#[derive(Clone, Debug, PartialEq, Eq)]
188pub struct TileServer {
189 pub url: String,
190 pub attribution: String,
191}
192
193impl Default for TileServer {
194 fn default() -> Self {
195 Self { url: "https://tile.openstreetmap.org/{z}/{x}/{y}.png".into(), attribution: "© OpenStreetMap".into() }
196 }
197}
198
199impl TileServer {
200 pub fn expand(template: &str, z: u32, x: u32, y: u32) -> String {
202 let shard = ["a", "b", "c"][((x + y) % 3) as usize];
203 template.replace("{z}", &z.to_string()).replace("{x}", &x.to_string()).replace("{y}", &y.to_string()).replace("{s}", shard)
204 }
205}
206
207impl MapTileProvider for TileServer {
208 fn tile_url(&self, z: u32, x: u32, y: u32) -> String {
209 Self::expand(&self.url, z, x, y)
210 }
211
212 fn attribution(&self) -> String {
213 self.attribution.clone()
214 }
215}
216
217impl Ui {
220 pub fn provided(&self, id: ComponentId) -> Option<Provided<'_>> {
222 self.component(id)?.provided()
223 }
224}
225
226#[derive(Clone, Debug, Default, PartialEq)]
232pub struct MediaTags {
233 pub title: String,
234 pub artist: String,
235 pub album: String,
236 pub track: u32,
238 pub year: u32,
240 pub duration: f64,
242 pub cover: Option<Vec<u8>>,
244}
245
246#[derive(Clone, Debug)]
248pub enum MediaInput {
249 Path(String),
250 Bytes(Vec<u8>, String),
251}
252
253pub type TagReader = std::sync::Arc<dyn Fn(&MediaInput) -> Result<MediaTags, String> + Send + Sync>;
255
256pub trait MediaTagsProvider {
258 fn tag_reader(&self) -> TagReader;
259}
260
261#[derive(Clone, Debug, PartialEq)]
267pub struct HttpRequest {
268 pub method: String,
270 pub url: String,
271 pub headers: Vec<(String, String)>,
272 pub body: Vec<u8>,
273 pub timeout_ms: u32,
275 pub max_response_bytes: u64,
277 pub max_redirects: u32,
279 pub allow_http: bool,
282}
283
284pub const HTTP_MAX_RESPONSE: u64 = 16 * 1024 * 1024;
286
287impl Default for HttpRequest {
288 fn default() -> Self {
289 Self { method: "GET".into(), url: String::new(), headers: Vec::new(), body: Vec::new(), timeout_ms: 30_000, max_response_bytes: HTTP_MAX_RESPONSE, max_redirects: 5, allow_http: false }
290 }
291}
292
293impl HttpRequest {
294 pub fn new(method: &str, url: impl Into<String>) -> Self {
296 Self { method: method.trim().to_ascii_uppercase(), url: url.into(), ..Default::default() }
297 }
298
299 pub fn get(url: impl Into<String>) -> Self {
300 Self::new("GET", url)
301 }
302
303 pub fn post(url: impl Into<String>) -> Self {
304 Self::new("POST", url)
305 }
306
307 pub fn put(url: impl Into<String>) -> Self {
308 Self::new("PUT", url)
309 }
310
311 pub fn patch(url: impl Into<String>) -> Self {
312 Self::new("PATCH", url)
313 }
314
315 pub fn delete(url: impl Into<String>) -> Self {
316 Self::new("DELETE", url)
317 }
318
319 pub fn header(mut self, name: &str, value: impl Into<String>) -> Self {
321 self.set_header(name, value);
322 self
323 }
324
325 pub fn set_header(&mut self, name: &str, value: impl Into<String>) {
327 self.headers.retain(|(k, _)| !k.eq_ignore_ascii_case(name));
328 self.headers.push((name.to_string(), value.into()));
329 }
330
331 pub fn header_value(&self, name: &str) -> Option<&str> {
333 self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
334 }
335
336 pub fn bearer(self, token: &str) -> Self {
338 self.header("Authorization", format!("Bearer {token}"))
339 }
340
341 pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
342 self.body = body.into();
343 self
344 }
345
346 pub fn json_text(self, json: impl Into<String>) -> Self {
348 self.header("Content-Type", "application/json").body(json.into().into_bytes())
349 }
350
351 pub fn timeout_ms(mut self, ms: u32) -> Self {
352 self.timeout_ms = ms;
353 self
354 }
355
356 pub fn max_response_bytes(mut self, bytes: u64) -> Self {
357 self.max_response_bytes = bytes;
358 self
359 }
360
361 pub fn max_redirects(mut self, n: u32) -> Self {
362 self.max_redirects = n;
363 self
364 }
365
366 pub fn allow_http(mut self, allow: bool) -> Self {
367 self.allow_http = allow;
368 self
369 }
370
371 pub fn response_limit(&self) -> u64 {
373 if self.max_response_bytes == 0 { HTTP_MAX_RESPONSE } else { self.max_response_bytes }
374 }
375
376 pub fn check_url(&self, url: &str) -> Result<(), String> {
379 check_scheme(url, "https", "http", self.allow_http)
380 }
381}
382
383static SYSTEM_ROOTS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
384
385pub fn set_system_roots(on: bool) {
391 SYSTEM_ROOTS.store(on, std::sync::atomic::Ordering::Relaxed);
392}
393
394pub fn system_roots() -> bool {
396 SYSTEM_ROOTS.load(std::sync::atomic::Ordering::Relaxed)
397}
398
399pub const DEFAULT_USER_AGENT: &str = concat!("aylis/", env!("CARGO_PKG_VERSION"));
401
402static USER_AGENT: std::sync::RwLock<String> = std::sync::RwLock::new(String::new());
403
404pub fn set_http_user_agent(agent: &str) {
409 let clean: String = agent.trim().chars().filter(|c| !c.is_control()).collect();
410 *USER_AGENT.write().unwrap_or_else(std::sync::PoisonError::into_inner) = clean;
411}
412
413pub fn http_user_agent() -> String {
415 let agent = USER_AGENT.read().unwrap_or_else(std::sync::PoisonError::into_inner);
416 if agent.is_empty() { DEFAULT_USER_AGENT.to_string() } else { agent.clone() }
417}
418
419impl Ui {
420 pub fn set_http_user_agent(&mut self, agent: &str) {
423 set_http_user_agent(agent);
424 }
425
426 pub fn http_user_agent(&self) -> String {
428 http_user_agent()
429 }
430}
431
432static APP_VERSION: std::sync::RwLock<String> = std::sync::RwLock::new(String::new());
433
434pub fn set_app_version(version: &str) {
437 *APP_VERSION.write().unwrap_or_else(std::sync::PoisonError::into_inner) = version.trim().to_string();
438}
439
440pub fn app_version() -> String {
442 APP_VERSION.read().unwrap_or_else(std::sync::PoisonError::into_inner).clone()
443}
444
445static APP_USER_MODEL_ID: std::sync::RwLock<String> = std::sync::RwLock::new(String::new());
446
447pub fn set_app_user_model_id(id: &str) {
451 *APP_USER_MODEL_ID.write().unwrap_or_else(std::sync::PoisonError::into_inner) = id.trim().to_string();
452}
453
454pub fn app_user_model_id() -> Option<String> {
456 let id = APP_USER_MODEL_ID.read().unwrap_or_else(std::sync::PoisonError::into_inner);
457 (!id.is_empty()).then(|| id.clone())
458}
459
460pub type PdfConversion = std::sync::Arc<dyn Fn(&[u8], &str) -> Result<Vec<u8>, String> + Send + Sync>;
466
467pub trait DocumentConverterProvider {
470 fn extensions(&self) -> Vec<String>;
472 fn pdf_conversion(&self) -> Option<PdfConversion>;
474}
475
476pub fn check_scheme(url: &str, secure: &str, insecure: &str, allow_insecure: bool) -> Result<(), String> {
479 let lower = url.trim().to_ascii_lowercase();
480 let (scheme, rest) = lower.split_once("://").ok_or_else(|| format!("endereço sem esquema: '{url}'"))?;
481 if scheme == secure {
482 return Ok(());
483 }
484 if scheme != insecure {
485 return Err(format!("esquema não aceito: '{scheme}' (use {secure}://)"));
486 }
487 if allow_insecure || is_loopback_host(url_host(rest)) {
488 return Ok(());
489 }
490 Err(format!("{insecure}:// sem TLS só para este computador; use {secure}:// (ou ligue o allow_http/allow_insecure do componente)"))
491}
492
493pub fn url_host(rest: &str) -> &str {
495 let rest = rest.split_once("://").map_or(rest, |(_, r)| r);
496 let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
497 let host = authority.rsplit('@').next().unwrap_or_default();
498 if let Some(v6) = host.strip_prefix('[') {
499 return v6.split(']').next().unwrap_or_default();
500 }
501 host.split(':').next().unwrap_or_default()
502}
503
504fn is_loopback_host(host: &str) -> bool {
505 matches!(host, "localhost" | "::1") || host.starts_with("127.")
506}
507
508#[derive(Clone, Debug, Default, PartialEq)]
511pub struct HttpResponse {
512 pub status: u16,
513 pub headers: Vec<(String, String)>,
514 pub body: Vec<u8>,
515 pub url: String,
516}
517
518impl HttpResponse {
519 pub fn ok(&self) -> bool {
521 (200..300).contains(&self.status)
522 }
523
524 pub fn header(&self, name: &str) -> Option<&str> {
526 self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
527 }
528
529 pub fn text(&self) -> String {
531 String::from_utf8_lossy(&self.body).into_owned()
532 }
533}
534
535pub type HttpDone = Box<dyn FnOnce(Result<HttpResponse, String>) + Send>;
537
538pub trait HttpProvider {
541 fn send(&self, request: HttpRequest, done: HttpDone);
543}
544
545#[derive(Clone, Debug, PartialEq)]
547pub struct WebSocketRequest {
548 pub url: String,
549 pub protocols: Vec<String>,
551 pub headers: Vec<(String, String)>,
553 pub connect_timeout_ms: u32,
555 pub max_message_bytes: u64,
557 pub allow_insecure: bool,
559}
560
561impl Default for WebSocketRequest {
562 fn default() -> Self {
563 Self { url: String::new(), protocols: Vec::new(), headers: Vec::new(), connect_timeout_ms: 10_000, max_message_bytes: HTTP_MAX_RESPONSE, allow_insecure: false }
564 }
565}
566
567impl WebSocketRequest {
568 pub fn check_url(&self) -> Result<(), String> {
569 check_scheme(&self.url, "wss", "ws", self.allow_insecure)
570 }
571
572 pub fn message_limit(&self) -> u64 {
574 if self.max_message_bytes == 0 { HTTP_MAX_RESPONSE } else { self.max_message_bytes }
575 }
576}
577
578#[derive(Clone, Debug, PartialEq)]
580pub enum WebSocketEvent {
581 Open { protocol: String },
583 Text(String),
584 Binary(Vec<u8>),
585 Error(String),
587 Closed { code: u16, reason: String },
590}
591
592pub type WebSocketEvents = Box<dyn FnMut(WebSocketEvent) + Send>;
594
595pub trait WebSocketConnection {
597 fn send_text(&mut self, text: &str) -> Result<(), String>;
598 fn send_binary(&mut self, data: &[u8]) -> Result<(), String>;
599 fn close(&mut self, code: u16, reason: &str);
601}
602
603pub trait WebSocketProvider {
606 fn connect(&self, request: WebSocketRequest, events: WebSocketEvents) -> Box<dyn WebSocketConnection>;
608}