use crate::pages::{Page, PageSet};
use crate::ui::Ui;
use crate::component::ComponentId;
#[derive(Clone, Copy)]
pub enum Provided<'a> {
Barcode(&'a dyn BarcodeProvider),
Export(&'a dyn ExportProvider),
Pdf(&'a dyn PdfProvider),
MapTiles(&'a dyn MapTileProvider),
MediaTags(&'a dyn MediaTagsProvider),
Http(&'a dyn HttpProvider),
WebSocket(&'a dyn WebSocketProvider),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BarcodeImage {
Linear { modules: Vec<bool>, text: String },
Matrix { width: usize, modules: Vec<bool> },
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ErrorCorrection {
Low,
#[default]
Medium,
Quartile,
High,
}
impl crate::prop::PropEnum for ErrorCorrection {
const NAMES: &'static [&'static str] = &["low", "medium", "quartile", "high"];
fn from_index(index: usize) -> Option<Self> {
[ErrorCorrection::Low, ErrorCorrection::Medium, ErrorCorrection::Quartile, ErrorCorrection::High].get(index).copied()
}
fn index(self) -> usize {
self as usize
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct BarcodeOptions {
pub error_correction: ErrorCorrection,
}
pub trait BarcodeProvider {
fn formats(&self) -> Vec<&'static str>;
fn encode(&self, format: &str, data: &str, options: &BarcodeOptions) -> Result<BarcodeImage, String>;
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ColumnKind {
#[default]
Text,
Integer,
Number,
Date,
DateTime,
Bool,
}
#[derive(Clone, Debug, PartialEq)]
pub enum CellValue {
Empty,
Text(String),
Number(f64),
Bool(bool),
Date(i32, u32, u32),
DateTime(i32, u32, u32, u32, u32, u32),
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ExportColumn {
pub title: String,
pub kind: ColumnKind,
pub format: String,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ExportTable {
pub name: String,
pub columns: Vec<ExportColumn>,
pub rows: Vec<Vec<CellValue>>,
}
pub trait ExportProvider {
fn extension(&self) -> &'static str;
fn mime(&self) -> &'static str;
fn write(&self, tables: &[ExportTable]) -> Result<Vec<u8>, String>;
}
pub trait PdfProvider {
fn begin(&self, width: f32, height: f32) -> Result<Box<dyn PdfDocument>, String>;
fn write(&self, pages: &PageSet) -> Result<Vec<u8>, String> {
let mut doc = self.begin(pages.width, pages.height)?;
for page in &pages.pages {
doc.add_page(page)?;
}
doc.finish()
}
}
pub trait PdfDocument {
fn add_page(&mut self, page: &Page) -> Result<(), String>;
fn finish(self: Box<Self>) -> Result<Vec<u8>, String>;
}
pub trait MapTileProvider {
fn tile_url(&self, z: u32, x: u32, y: u32) -> String;
fn attribution(&self) -> String;
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TileServer {
pub url: String,
pub attribution: String,
}
impl Default for TileServer {
fn default() -> Self {
Self { url: "https://tile.openstreetmap.org/{z}/{x}/{y}.png".into(), attribution: "© OpenStreetMap".into() }
}
}
impl TileServer {
pub fn expand(template: &str, z: u32, x: u32, y: u32) -> String {
let shard = ["a", "b", "c"][((x + y) % 3) as usize];
template.replace("{z}", &z.to_string()).replace("{x}", &x.to_string()).replace("{y}", &y.to_string()).replace("{s}", shard)
}
}
impl MapTileProvider for TileServer {
fn tile_url(&self, z: u32, x: u32, y: u32) -> String {
Self::expand(&self.url, z, x, y)
}
fn attribution(&self) -> String {
self.attribution.clone()
}
}
impl Ui {
pub fn provided(&self, id: ComponentId) -> Option<Provided<'_>> {
self.component(id)?.provided()
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct MediaTags {
pub title: String,
pub artist: String,
pub album: String,
pub track: u32,
pub year: u32,
pub duration: f64,
pub cover: Option<Vec<u8>>,
}
#[derive(Clone, Debug)]
pub enum MediaInput {
Path(String),
Bytes(Vec<u8>, String),
}
pub type TagReader = std::sync::Arc<dyn Fn(&MediaInput) -> Result<MediaTags, String> + Send + Sync>;
pub trait MediaTagsProvider {
fn tag_reader(&self) -> TagReader;
}
#[derive(Clone, Debug, PartialEq)]
pub struct HttpRequest {
pub method: String,
pub url: String,
pub headers: Vec<(String, String)>,
pub body: Vec<u8>,
pub timeout_ms: u32,
pub max_response_bytes: u64,
pub max_redirects: u32,
pub allow_http: bool,
}
pub const HTTP_MAX_RESPONSE: u64 = 16 * 1024 * 1024;
impl Default for HttpRequest {
fn default() -> Self {
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 }
}
}
impl HttpRequest {
pub fn new(method: &str, url: impl Into<String>) -> Self {
Self { method: method.trim().to_ascii_uppercase(), url: url.into(), ..Default::default() }
}
pub fn get(url: impl Into<String>) -> Self {
Self::new("GET", url)
}
pub fn post(url: impl Into<String>) -> Self {
Self::new("POST", url)
}
pub fn put(url: impl Into<String>) -> Self {
Self::new("PUT", url)
}
pub fn patch(url: impl Into<String>) -> Self {
Self::new("PATCH", url)
}
pub fn delete(url: impl Into<String>) -> Self {
Self::new("DELETE", url)
}
pub fn header(mut self, name: &str, value: impl Into<String>) -> Self {
self.set_header(name, value);
self
}
pub fn set_header(&mut self, name: &str, value: impl Into<String>) {
self.headers.retain(|(k, _)| !k.eq_ignore_ascii_case(name));
self.headers.push((name.to_string(), value.into()));
}
pub fn header_value(&self, name: &str) -> Option<&str> {
self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
}
pub fn bearer(self, token: &str) -> Self {
self.header("Authorization", format!("Bearer {token}"))
}
pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
self.body = body.into();
self
}
pub fn json_text(self, json: impl Into<String>) -> Self {
self.header("Content-Type", "application/json").body(json.into().into_bytes())
}
pub fn timeout_ms(mut self, ms: u32) -> Self {
self.timeout_ms = ms;
self
}
pub fn max_response_bytes(mut self, bytes: u64) -> Self {
self.max_response_bytes = bytes;
self
}
pub fn max_redirects(mut self, n: u32) -> Self {
self.max_redirects = n;
self
}
pub fn allow_http(mut self, allow: bool) -> Self {
self.allow_http = allow;
self
}
pub fn response_limit(&self) -> u64 {
if self.max_response_bytes == 0 { HTTP_MAX_RESPONSE } else { self.max_response_bytes }
}
pub fn check_url(&self, url: &str) -> Result<(), String> {
check_scheme(url, "https", "http", self.allow_http)
}
}
pub fn check_scheme(url: &str, secure: &str, insecure: &str, allow_insecure: bool) -> Result<(), String> {
let lower = url.trim().to_ascii_lowercase();
let (scheme, rest) = lower.split_once("://").ok_or_else(|| format!("endereço sem esquema: '{url}'"))?;
if scheme == secure {
return Ok(());
}
if scheme != insecure {
return Err(format!("esquema não aceito: '{scheme}' (use {secure}://)"));
}
if allow_insecure || is_loopback_host(url_host(rest)) {
return Ok(());
}
Err(format!("{insecure}:// sem TLS só para este computador; use {secure}:// (ou ligue o allow_http/allow_insecure do componente)"))
}
pub fn url_host(rest: &str) -> &str {
let rest = rest.split_once("://").map_or(rest, |(_, r)| r);
let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
let host = authority.rsplit('@').next().unwrap_or_default();
if let Some(v6) = host.strip_prefix('[') {
return v6.split(']').next().unwrap_or_default();
}
host.split(':').next().unwrap_or_default()
}
fn is_loopback_host(host: &str) -> bool {
matches!(host, "localhost" | "::1") || host.starts_with("127.")
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct HttpResponse {
pub status: u16,
pub headers: Vec<(String, String)>,
pub body: Vec<u8>,
pub url: String,
}
impl HttpResponse {
pub fn ok(&self) -> bool {
(200..300).contains(&self.status)
}
pub fn header(&self, name: &str) -> Option<&str> {
self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
}
pub fn text(&self) -> String {
String::from_utf8_lossy(&self.body).into_owned()
}
}
pub type HttpDone = Box<dyn FnOnce(Result<HttpResponse, String>) + Send>;
pub trait HttpProvider {
fn send(&self, request: HttpRequest, done: HttpDone);
}
#[derive(Clone, Debug, PartialEq)]
pub struct WebSocketRequest {
pub url: String,
pub protocols: Vec<String>,
pub headers: Vec<(String, String)>,
pub connect_timeout_ms: u32,
pub max_message_bytes: u64,
pub allow_insecure: bool,
}
impl Default for WebSocketRequest {
fn default() -> Self {
Self { url: String::new(), protocols: Vec::new(), headers: Vec::new(), connect_timeout_ms: 10_000, max_message_bytes: HTTP_MAX_RESPONSE, allow_insecure: false }
}
}
impl WebSocketRequest {
pub fn check_url(&self) -> Result<(), String> {
check_scheme(&self.url, "wss", "ws", self.allow_insecure)
}
pub fn message_limit(&self) -> u64 {
if self.max_message_bytes == 0 { HTTP_MAX_RESPONSE } else { self.max_message_bytes }
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum WebSocketEvent {
Open { protocol: String },
Text(String),
Binary(Vec<u8>),
Error(String),
Closed { code: u16, reason: String },
}
pub type WebSocketEvents = Box<dyn FnMut(WebSocketEvent) + Send>;
pub trait WebSocketConnection {
fn send_text(&mut self, text: &str) -> Result<(), String>;
fn send_binary(&mut self, data: &[u8]) -> Result<(), String>;
fn close(&mut self, code: u16, reason: &str);
}
pub trait WebSocketProvider {
fn connect(&self, request: WebSocketRequest, events: WebSocketEvents) -> Box<dyn WebSocketConnection>;
}