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}
29
30#[derive(Clone, Debug, PartialEq, Eq)]
35pub enum BarcodeImage {
36 Linear { modules: Vec<bool>, text: String },
39 Matrix { width: usize, modules: Vec<bool> },
41}
42
43#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
47pub enum ErrorCorrection {
48 Low,
50 #[default]
52 Medium,
53 Quartile,
55 High,
57}
58
59impl crate::prop::PropEnum for ErrorCorrection {
60 const NAMES: &'static [&'static str] = &["low", "medium", "quartile", "high"];
61
62 fn from_index(index: usize) -> Option<Self> {
63 [ErrorCorrection::Low, ErrorCorrection::Medium, ErrorCorrection::Quartile, ErrorCorrection::High].get(index).copied()
64 }
65
66 fn index(self) -> usize {
67 self as usize
68 }
69}
70
71#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
73pub struct BarcodeOptions {
74 pub error_correction: ErrorCorrection,
76}
77
78pub trait BarcodeProvider {
80 fn formats(&self) -> Vec<&'static str>;
82 fn encode(&self, format: &str, data: &str, options: &BarcodeOptions) -> Result<BarcodeImage, String>;
85}
86
87#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
92pub enum ColumnKind {
93 #[default]
94 Text,
95 Integer,
96 Number,
98 Date,
99 DateTime,
100 Bool,
101}
102
103#[derive(Clone, Debug, PartialEq)]
105pub enum CellValue {
106 Empty,
107 Text(String),
108 Number(f64),
109 Bool(bool),
110 Date(i32, u32, u32),
112 DateTime(i32, u32, u32, u32, u32, u32),
114}
115
116#[derive(Clone, Debug, Default, PartialEq)]
118pub struct ExportColumn {
119 pub title: String,
120 pub kind: ColumnKind,
121 pub format: String,
122}
123
124#[derive(Clone, Debug, Default, PartialEq)]
126pub struct ExportTable {
127 pub name: String,
128 pub columns: Vec<ExportColumn>,
129 pub rows: Vec<Vec<CellValue>>,
130}
131
132pub trait ExportProvider {
134 fn extension(&self) -> &'static str;
136 fn mime(&self) -> &'static str;
138 fn write(&self, tables: &[ExportTable]) -> Result<Vec<u8>, String>;
140}
141
142pub trait PdfProvider {
151 fn begin(&self, width: f32, height: f32) -> Result<Box<dyn PdfDocument>, String>;
153
154 fn write(&self, pages: &PageSet) -> Result<Vec<u8>, String> {
156 let mut doc = self.begin(pages.width, pages.height)?;
157 for page in &pages.pages {
158 doc.add_page(page)?;
159 }
160 doc.finish()
161 }
162}
163
164pub trait PdfDocument {
166 fn add_page(&mut self, page: &Page) -> Result<(), String>;
167 fn finish(self: Box<Self>) -> Result<Vec<u8>, String>;
169}
170
171pub trait MapTileProvider {
176 fn tile_url(&self, z: u32, x: u32, y: u32) -> String;
178 fn attribution(&self) -> String;
180}
181
182#[derive(Clone, Debug, PartialEq, Eq)]
187pub struct TileServer {
188 pub url: String,
189 pub attribution: String,
190}
191
192impl Default for TileServer {
193 fn default() -> Self {
194 Self { url: "https://tile.openstreetmap.org/{z}/{x}/{y}.png".into(), attribution: "© OpenStreetMap".into() }
195 }
196}
197
198impl TileServer {
199 pub fn expand(template: &str, z: u32, x: u32, y: u32) -> String {
201 let shard = ["a", "b", "c"][((x + y) % 3) as usize];
202 template.replace("{z}", &z.to_string()).replace("{x}", &x.to_string()).replace("{y}", &y.to_string()).replace("{s}", shard)
203 }
204}
205
206impl MapTileProvider for TileServer {
207 fn tile_url(&self, z: u32, x: u32, y: u32) -> String {
208 Self::expand(&self.url, z, x, y)
209 }
210
211 fn attribution(&self) -> String {
212 self.attribution.clone()
213 }
214}
215
216impl Ui {
219 pub fn provided(&self, id: ComponentId) -> Option<Provided<'_>> {
221 self.component(id)?.provided()
222 }
223}
224
225#[derive(Clone, Debug, Default, PartialEq)]
231pub struct MediaTags {
232 pub title: String,
233 pub artist: String,
234 pub album: String,
235 pub track: u32,
237 pub year: u32,
239 pub duration: f64,
241 pub cover: Option<Vec<u8>>,
243}
244
245#[derive(Clone, Debug)]
247pub enum MediaInput {
248 Path(String),
249 Bytes(Vec<u8>, String),
250}
251
252pub type TagReader = std::sync::Arc<dyn Fn(&MediaInput) -> Result<MediaTags, String> + Send + Sync>;
254
255pub trait MediaTagsProvider {
257 fn tag_reader(&self) -> TagReader;
258}
259
260#[derive(Clone, Debug, PartialEq)]
266pub struct HttpRequest {
267 pub method: String,
269 pub url: String,
270 pub headers: Vec<(String, String)>,
271 pub body: Vec<u8>,
272 pub timeout_ms: u32,
274 pub max_response_bytes: u64,
276 pub max_redirects: u32,
278 pub allow_http: bool,
281}
282
283pub const HTTP_MAX_RESPONSE: u64 = 16 * 1024 * 1024;
285
286impl Default for HttpRequest {
287 fn default() -> Self {
288 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 }
289 }
290}
291
292impl HttpRequest {
293 pub fn new(method: &str, url: impl Into<String>) -> Self {
295 Self { method: method.trim().to_ascii_uppercase(), url: url.into(), ..Default::default() }
296 }
297
298 pub fn get(url: impl Into<String>) -> Self {
299 Self::new("GET", url)
300 }
301
302 pub fn post(url: impl Into<String>) -> Self {
303 Self::new("POST", url)
304 }
305
306 pub fn put(url: impl Into<String>) -> Self {
307 Self::new("PUT", url)
308 }
309
310 pub fn patch(url: impl Into<String>) -> Self {
311 Self::new("PATCH", url)
312 }
313
314 pub fn delete(url: impl Into<String>) -> Self {
315 Self::new("DELETE", url)
316 }
317
318 pub fn header(mut self, name: &str, value: impl Into<String>) -> Self {
320 self.set_header(name, value);
321 self
322 }
323
324 pub fn set_header(&mut self, name: &str, value: impl Into<String>) {
326 self.headers.retain(|(k, _)| !k.eq_ignore_ascii_case(name));
327 self.headers.push((name.to_string(), value.into()));
328 }
329
330 pub fn header_value(&self, name: &str) -> Option<&str> {
332 self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
333 }
334
335 pub fn bearer(self, token: &str) -> Self {
337 self.header("Authorization", format!("Bearer {token}"))
338 }
339
340 pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
341 self.body = body.into();
342 self
343 }
344
345 pub fn json_text(self, json: impl Into<String>) -> Self {
347 self.header("Content-Type", "application/json").body(json.into().into_bytes())
348 }
349
350 pub fn timeout_ms(mut self, ms: u32) -> Self {
351 self.timeout_ms = ms;
352 self
353 }
354
355 pub fn max_response_bytes(mut self, bytes: u64) -> Self {
356 self.max_response_bytes = bytes;
357 self
358 }
359
360 pub fn max_redirects(mut self, n: u32) -> Self {
361 self.max_redirects = n;
362 self
363 }
364
365 pub fn allow_http(mut self, allow: bool) -> Self {
366 self.allow_http = allow;
367 self
368 }
369
370 pub fn response_limit(&self) -> u64 {
372 if self.max_response_bytes == 0 { HTTP_MAX_RESPONSE } else { self.max_response_bytes }
373 }
374
375 pub fn check_url(&self, url: &str) -> Result<(), String> {
378 check_scheme(url, "https", "http", self.allow_http)
379 }
380}
381
382pub fn check_scheme(url: &str, secure: &str, insecure: &str, allow_insecure: bool) -> Result<(), String> {
385 let lower = url.trim().to_ascii_lowercase();
386 let (scheme, rest) = lower.split_once("://").ok_or_else(|| format!("endereço sem esquema: '{url}'"))?;
387 if scheme == secure {
388 return Ok(());
389 }
390 if scheme != insecure {
391 return Err(format!("esquema não aceito: '{scheme}' (use {secure}://)"));
392 }
393 if allow_insecure || is_loopback_host(url_host(rest)) {
394 return Ok(());
395 }
396 Err(format!("{insecure}:// sem TLS só para este computador; use {secure}:// (ou ligue o allow_http/allow_insecure do componente)"))
397}
398
399pub fn url_host(rest: &str) -> &str {
401 let rest = rest.split_once("://").map_or(rest, |(_, r)| r);
402 let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
403 let host = authority.rsplit('@').next().unwrap_or_default();
404 if let Some(v6) = host.strip_prefix('[') {
405 return v6.split(']').next().unwrap_or_default();
406 }
407 host.split(':').next().unwrap_or_default()
408}
409
410fn is_loopback_host(host: &str) -> bool {
411 matches!(host, "localhost" | "::1") || host.starts_with("127.")
412}
413
414#[derive(Clone, Debug, Default, PartialEq)]
417pub struct HttpResponse {
418 pub status: u16,
419 pub headers: Vec<(String, String)>,
420 pub body: Vec<u8>,
421 pub url: String,
422}
423
424impl HttpResponse {
425 pub fn ok(&self) -> bool {
427 (200..300).contains(&self.status)
428 }
429
430 pub fn header(&self, name: &str) -> Option<&str> {
432 self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
433 }
434
435 pub fn text(&self) -> String {
437 String::from_utf8_lossy(&self.body).into_owned()
438 }
439}
440
441pub type HttpDone = Box<dyn FnOnce(Result<HttpResponse, String>) + Send>;
443
444pub trait HttpProvider {
447 fn send(&self, request: HttpRequest, done: HttpDone);
449}
450
451#[derive(Clone, Debug, PartialEq)]
453pub struct WebSocketRequest {
454 pub url: String,
455 pub protocols: Vec<String>,
457 pub headers: Vec<(String, String)>,
459 pub connect_timeout_ms: u32,
461 pub max_message_bytes: u64,
463 pub allow_insecure: bool,
465}
466
467impl Default for WebSocketRequest {
468 fn default() -> Self {
469 Self { url: String::new(), protocols: Vec::new(), headers: Vec::new(), connect_timeout_ms: 10_000, max_message_bytes: HTTP_MAX_RESPONSE, allow_insecure: false }
470 }
471}
472
473impl WebSocketRequest {
474 pub fn check_url(&self) -> Result<(), String> {
475 check_scheme(&self.url, "wss", "ws", self.allow_insecure)
476 }
477
478 pub fn message_limit(&self) -> u64 {
480 if self.max_message_bytes == 0 { HTTP_MAX_RESPONSE } else { self.max_message_bytes }
481 }
482}
483
484#[derive(Clone, Debug, PartialEq)]
486pub enum WebSocketEvent {
487 Open { protocol: String },
489 Text(String),
490 Binary(Vec<u8>),
491 Error(String),
493 Closed { code: u16, reason: String },
496}
497
498pub type WebSocketEvents = Box<dyn FnMut(WebSocketEvent) + Send>;
500
501pub trait WebSocketConnection {
503 fn send_text(&mut self, text: &str) -> Result<(), String>;
504 fn send_binary(&mut self, data: &[u8]) -> Result<(), String>;
505 fn close(&mut self, code: u16, reason: &str);
507}
508
509pub trait WebSocketProvider {
512 fn connect(&self, request: WebSocketRequest, events: WebSocketEvents) -> Box<dyn WebSocketConnection>;
514}