1mod emit;
4mod parse;
5
6pub mod render_value;
7
8use proc_macro2::TokenStream;
9use quote::{ToTokens, quote};
10use std::collections::BTreeMap;
11use syn::{FnArg, Ident, Item, ItemFn, Pat, Result, Stmt};
12
13#[derive(Clone, Copy, Eq, PartialEq)]
15pub enum Platform {
16 LiveActivity,
18 Glance,
20 WidgetKit,
22 Ongoing,
24}
25impl Platform {
26 fn is_apple(self) -> bool {
27 matches!(self, Self::LiveActivity | Self::WidgetKit)
28 }
29}
30pub struct Widget {
32 platform: Platform,
33 name: Ident,
34 argument: Ident,
35 fields: BTreeMap<String, Field>,
36 sections: BTreeMap<String, Node>,
37}
38#[derive(Clone, Copy, PartialEq, Eq)]
39enum Field {
40 Text,
41 Number,
42}
43enum Part {
44 Literal(String),
45 Field(String),
46 Percent(String),
47}
48enum Node {
49 Text(Vec<Part>),
50 Icon(String),
51 Progress(String),
52 Stack {
53 horizontal: bool,
54 gap: u32,
55 children: Vec<Node>,
56 },
57}
58
59impl Widget {
60 pub fn parse(platform: Platform, f: &ItemFn) -> Result<Self> {
62 let arg = match f.sig.inputs.first() {
63 Some(FnArg::Typed(a)) if f.sig.inputs.len() == 1 => match &*a.pat {
64 Pat::Ident(p) if p.by_ref.is_none() && p.subpat.is_none() => p.ident.clone(),
65 _ => return Err(syn::Error::new_spanned(a, "use a named state argument")),
66 },
67 _ => {
68 return Err(syn::Error::new_spanned(
69 &f.sig,
70 "a widget takes one state model",
71 ));
72 }
73 };
74 if f.sig.asyncness.is_some()
75 || f.sig.unsafety.is_some()
76 || !f.sig.generics.params.is_empty()
77 {
78 return Err(syn::Error::new_spanned(
79 &f.sig,
80 "widgets must be safe, synchronous, concrete functions",
81 ));
82 }
83 let m = match f.block.stmts.as_slice() {
84 [Stmt::Expr(syn::Expr::Macro(m), _)] => &m.mac,
85 [Stmt::Macro(m)] => &m.mac,
86 _ => {
87 return Err(syn::Error::new_spanned(
88 &f.block,
89 "expected one static live_activity! or ui! expression",
90 ));
91 }
92 };
93 let mut widget = Self {
94 platform,
95 name: f.sig.ident.clone(),
96 argument: arg,
97 fields: BTreeMap::new(),
98 sections: BTreeMap::new(),
99 };
100 widget.parse_sections(m)?;
101 Ok(widget)
102 }
103 pub fn rust_function(&self, mut f: ItemFn) -> TokenStream {
105 let var = &self.argument;
106 let fields = self.fields.iter().map(|(name, kind)| {
107 let ident = Ident::new(name, self.argument.span());
108 let value = match kind {
109 Field::Text => quote! { ::core::convert::AsRef::<str>::as_ref(&#var.#ident) },
110 Field::Number => quote! { ::core::convert::Into::<f64>::into(#var.#ident) },
111 };
112 quote! { (#name, ::serge::__private::WidgetValue::from(#value)) }
113 });
114 let name = self.name.to_string();
115 f.block = syn::parse_quote!({
116 let _ = &#var;
117 ::serge::PlatformWidget::from_fields(#name, [#(#fields),*])
118 });
119 f.into_token_stream()
120 }
121 pub fn name(&self) -> String {
123 self.name.to_string()
124 }
125 pub fn platform(&self) -> Platform {
127 self.platform
128 }
129 pub fn source(&self, android_package: &str) -> Result<String> {
131 emit::source(self, android_package)
132 }
133 pub fn android_resources(&self, android_package: &str) -> Result<Vec<(String, String)>> {
135 emit::resources(self, android_package)
136 }
137}
138
139pub fn discover(source: &str) -> Result<Vec<Widget>> {
142 fn items(list: Vec<Item>, out: &mut Vec<Widget>) -> Result<()> {
143 for item in list {
144 match item {
145 Item::Fn(f) => {
146 for attr in &f.attrs {
147 let segments: Vec<_> = attr
148 .path()
149 .segments
150 .iter()
151 .map(|s| s.ident.to_string())
152 .collect();
153 let platform = match segments.as_slice() {
154 [.., a, b] if a == "ios" && b == "live_activity" => {
155 Platform::LiveActivity
156 }
157 [.., a, b] if a == "ios" && b == "widget" => Platform::WidgetKit,
158 [.., a, b] if a == "android" && b == "widget" => Platform::Glance,
159 [.., a, b] if a == "android" && b == "ongoing_notification" => {
160 Platform::Ongoing
161 }
162 _ => continue,
163 };
164 out.push(Widget::parse(platform, &f)?);
165 }
166 }
167 Item::Mod(m) => {
168 if let Some((_, list)) = m.content {
169 items(list, out)?;
170 }
171 }
172 _ => {}
173 }
174 }
175 Ok(())
176 }
177 let mut widgets = Vec::new();
178 items(syn::parse_file(source)?.items, &mut widgets)?;
179 Ok(widgets)
180}