1use crate::error::CodegenError;
6use crate::naming::{
7 escape_kotlin_string, kotlin_ident, sanitize_block_comment, to_camel_case, to_snake_case,
8};
9use crate::schema::export::{ExportComposeOutput, GeneratedFile};
10use crate::schema::hybrid::{HybridEventSpec, HybridFileSpec, HybridType, HybridViewSpec};
11use crate::targets::export_common::{
12 android_package_kotlin, event_handler_name, event_stem_pascal, event_wire_aliases,
13 validate_export_view,
14};
15use crate::writer::CodeWriter;
16
17use super::kotlin_bin_codec::{
18 emit_kotlin_bin_read_value, emit_kotlin_bin_write_value, emit_kotlin_enum, emit_kotlin_struct,
19 kotlin_default_expr, kotlin_type, kotlin_zero_default, view_uses_dynamic_value,
20};
21
22pub fn generate_export_compose(
24 file: &HybridFileSpec,
25 view: &HybridViewSpec,
26) -> Result<ExportComposeOutput, CodegenError> {
27 validate_export_view(file, view)?;
28 let content = emit_compose_kotlin(file, view);
29
30 Ok(ExportComposeOutput {
31 view_name: view.name.clone(),
32 compose_kt: GeneratedFile {
33 relative_path: format!("{}Composable.generated.kt", view.name),
34 content,
35 },
36 })
37}
38
39fn emit_compose_kotlin(file: &HybridFileSpec, view: &HybridViewSpec) -> String {
40 let name = &view.name;
41 let snake = to_snake_case(name);
42 let pkg = android_package_kotlin(file);
43 let (enums, structs) = view.referenced_types(file);
44 let has_props = !view.props.is_empty();
45 let has_events = !view.events.is_empty();
46 let has_event_payloads = view.events.iter().any(|e| !e.params.is_empty());
47 let has_structs = !structs.is_empty();
48 let has_dynamic = view_uses_dynamic_value(file, view);
49 let needs_bin_reader = has_event_payloads || has_structs;
50 let needs_bin_writer = has_props || has_structs || !view.methods.is_empty();
51
52 let mut out = CodeWriter::with_capacity(4096);
53 writeln!(
54 out,
55 "// @generated by nativeview-codegen (`export_compose`) — DO NOT EDIT."
56 );
57 writeln!(
58 out,
59 "// Binary typed Jetpack Compose @Composable wrapping `io.github.nativeview.compose.NvSurface` over Runtime ABI v6."
60 );
61 writeln!(out);
62 writeln!(out, "package {pkg}");
63 writeln!(out);
64 writeln!(out, "import androidx.compose.runtime.Composable");
65 if has_event_payloads || has_structs {
66 writeln!(out, "import androidx.compose.runtime.Immutable");
67 }
68 if has_props {
69 writeln!(out, "import androidx.compose.runtime.LaunchedEffect");
70 }
71 writeln!(out, "import androidx.compose.runtime.remember");
72 writeln!(out, "import androidx.compose.ui.Modifier");
73 writeln!(out, "import androidx.compose.ui.platform.LocalContext");
74 if has_events {
75 writeln!(out, "import io.github.nativeview.compose.NvEmittedEvent");
76 }
77 writeln!(out, "import io.github.nativeview.compose.NvHostBridge");
78 writeln!(out, "import io.github.nativeview.compose.NvRuntimeHost");
79 writeln!(out, "import io.github.nativeview.compose.NvSource");
80 writeln!(out, "import io.github.nativeview.compose.NvSurface");
81 writeln!(out, "import io.github.nativeview.compose.NvSurfaceController");
82 writeln!(out, "import io.github.nativeview.compose.rememberNvSurfaceController");
83 if needs_bin_reader {
84 writeln!(out, "import io.github.nativeview.host.BinReader");
85 writeln!(out, "import io.github.nativeview.host.BinTag");
86 }
87 if needs_bin_writer {
88 writeln!(out, "import io.github.nativeview.host.BinWriter");
89 }
90 if has_dynamic {
91 writeln!(out, "import io.github.nativeview.host.HybridRuntime");
92 }
93 writeln!(out, "import io.github.nativeview.host.SurfaceMeasure");
94 writeln!(out, "import io.github.nativeview.host.generated.NvRuntimeAbi");
95 writeln!(out, "import java.util.concurrent.Executor");
96 writeln!(out);
97
98 for e in &enums {
99 emit_kotlin_enum(&mut out, e);
100 }
101 for s in &structs {
102 emit_kotlin_struct(&mut out, file, s, true);
103 }
104 for ev in &view.events {
105 emit_kotlin_event_data_class(&mut out, file, name, ev);
106 }
107 if has_props {
108 emit_kotlin_direct_props_writer(&mut out, view);
109 }
110 emit_kotlin_controller(&mut out, view, &snake);
111 emit_kotlin_composable(&mut out, view);
112
113 out.into_string()
114}
115
116fn emit_kotlin_controller(out: &mut CodeWriter, view: &HybridViewSpec, snake: &str) {
117 let name = &view.name;
118 writeln!(
119 out,
120 "/** Imperative binary command controller for `{}` backed by `NvSurfaceController`. */",
121 sanitize_block_comment(name)
122 );
123 writeln!(
124 out,
125 "class {name}Controller(val inner: NvSurfaceController) {{"
126 );
127 writeln!(out, " fun measureSurface(");
128 writeln!(out, " minWidthDp: Float = 0f,");
129 writeln!(out, " minHeightDp: Float = 0f,");
130 writeln!(out, " maxWidthDp: Float = Float.POSITIVE_INFINITY,");
131 writeln!(out, " maxHeightDp: Float = Float.POSITIVE_INFINITY,");
132 writeln!(
133 out,
134 " flags: Int = NvRuntimeAbi.MEASURE_FLAG_DRY_RUN,"
135 );
136 writeln!(
137 out,
138 " ): SurfaceMeasure? = inner.measureSurface(minWidthDp, minHeightDp, maxWidthDp, maxHeightDp, flags)"
139 );
140 for m in &view.methods {
141 let mname = kotlin_ident(&to_camel_case(&m.name));
142 let params: Vec<String> = m
143 .params
144 .iter()
145 .map(|p| {
146 let pname = kotlin_ident(&to_camel_case(&p.name));
147 let pty = kotlin_type(&p.ty);
148 if matches!(p.ty, HybridType::Optional(_)) {
149 format!("{pname}: {pty} = null")
150 } else {
151 format!("{pname}: {pty}")
152 }
153 })
154 .collect();
155 writeln!(out);
156 writeln!(out, " fun {mname}({}) {{", params.join(", "));
157 if m.params.is_empty() {
158 writeln!(
159 out,
160 " inner.dispatchCustom(\"{}\") {{ _w -> val _m = _w.beginMap(0); _w.end(_m) }}",
161 escape_kotlin_string(&m.name)
162 );
163 } else {
164 writeln!(
165 out,
166 " inner.dispatchCustom(\"{}\") {{ _w ->",
167 escape_kotlin_string(&m.name)
168 );
169 let fixed = m
170 .params
171 .iter()
172 .filter(|p| !matches!(p.ty, HybridType::Optional(_)))
173 .count();
174 let has_opt = fixed < m.params.len();
175 if has_opt {
176 writeln!(out, " var _count = {fixed}");
177 for p in &m.params {
178 if matches!(p.ty, HybridType::Optional(_)) {
179 writeln!(
180 out,
181 " if ({} != null) _count++",
182 kotlin_ident(&to_camel_case(&p.name))
183 );
184 }
185 }
186 writeln!(out, " val _mark = _w.beginMap(_count)");
187 } else {
188 writeln!(out, " val _mark = _w.beginMap({fixed})");
189 }
190 for p in &m.params {
191 let pname = kotlin_ident(&to_camel_case(&p.name));
192 let key = escape_kotlin_string(&p.name);
193 if let HybridType::Optional(inner) = &p.ty {
194 writeln!(out, " if ({pname} != null) {{");
195 writeln!(out, " _w.writeMapKey(\"{key}\")");
196 emit_kotlin_bin_write_value(out, " ", "_w", &pname, inner, 0);
197 writeln!(out, " }}");
198 } else {
199 writeln!(out, " _w.writeMapKey(\"{key}\")");
200 emit_kotlin_bin_write_value(out, " ", "_w", &pname, &p.ty, 0);
201 }
202 }
203 writeln!(out, " _w.end(_mark)");
204 writeln!(out, " }}");
205 }
206 writeln!(out, " }}");
207 }
208 writeln!(out, "}}");
209 writeln!(out);
210
211 writeln!(out, "@Composable");
212 writeln!(out, "fun remember{name}Controller(");
213 writeln!(out, " source: NvSource? = null,");
214 writeln!(out, " surfaceId: Int = 1,");
215 writeln!(
216 out,
217 " hostFactory: ((surfaceId: Int, widthDp: Float, heightDp: Float, density: Float, ownerThread: Executor) -> NvRuntimeHost)? = null,"
218 );
219 writeln!(out, "): {name}Controller {{");
220 writeln!(out, " val _context = LocalContext.current");
221 writeln!(out, " val _resolvedSource = remember(source, _context) {{");
222 writeln!(
223 out,
224 " source ?: NvSource.App(_context.applicationInfo.nativeLibraryDir + \"/lib{snake}.so\")"
225 );
226 writeln!(out, " }}");
227 writeln!(
228 out,
229 " val _inner = rememberNvSurfaceController(_resolvedSource, surfaceId, hostFactory)"
230 );
231 writeln!(out, " return remember(_inner) {{ {name}Controller(_inner) }}");
232 writeln!(out, "}}");
233 writeln!(out);
234}
235
236fn emit_kotlin_composable(out: &mut CodeWriter, view: &HybridViewSpec) {
237 let name = &view.name;
238 if let Some(doc) = &view.doc {
239 writeln!(out, "/**");
240 for line in sanitize_block_comment(doc).lines() {
241 writeln!(out, " * {line}");
242 }
243 writeln!(out, " */");
244 }
245 writeln!(out, "@Composable");
246 writeln!(out, "fun {name}(");
247 for prop in &view.props {
248 let param = kotlin_ident(&to_camel_case(&prop.name));
249 let ty = kotlin_type(&prop.ty);
250 if let Some(def) = prop
251 .default_value
252 .as_ref()
253 .and_then(|d| kotlin_default_expr(&prop.ty, d))
254 {
255 writeln!(out, " {param}: {ty} = {def},");
256 } else if matches!(prop.ty, HybridType::Optional(_)) {
257 writeln!(out, " {param}: {ty} = null,");
258 } else {
259 writeln!(out, " {param}: {ty},");
260 }
261 }
262 for ev in &view.events {
263 let cb = kotlin_ident(&event_handler_name(&ev.name));
264 let cb_ty = compose_event_lambda_type(name, ev);
265 writeln!(out, " {cb}: ({cb_ty})? = null,");
266 }
267 writeln!(out, " modifier: Modifier = Modifier,");
268 writeln!(out, " controller: {name}Controller? = null,");
269 writeln!(out, " source: NvSource? = null,");
270 writeln!(out, " hostBridge: NvHostBridge? = null,");
271 writeln!(out, ") {{");
272 writeln!(
273 out,
274 " val _activeController = controller ?: remember{name}Controller(source)"
275 );
276 if !view.props.is_empty() {
277 let prop_args: Vec<String> = view
278 .props
279 .iter()
280 .map(|p| kotlin_ident(&to_camel_case(&p.name)))
281 .collect();
282 let mut keys = Vec::with_capacity(prop_args.len() + 2);
283 keys.push("_activeController".to_owned());
284 keys.push("source".to_owned());
285 keys.extend(prop_args.iter().cloned());
286 writeln!(out, " LaunchedEffect({}) {{", keys.join(", "));
287 writeln!(out, " _activeController.inner.setProps {{ _w ->");
288 writeln!(
289 out,
290 " {name}DirectPropsWriter.encodeTo(_w, {})",
291 prop_args.join(", ")
292 );
293 writeln!(out, " }}");
294 writeln!(out, " }}");
295 }
296 writeln!(out);
297 writeln!(out, " NvSurface(");
298 writeln!(out, " controller = _activeController.inner,");
299 writeln!(out, " modifier = modifier,");
300 if !view.events.is_empty() {
301 writeln!(out, " onEvent = {{ _event: NvEmittedEvent ->");
302 writeln!(out, " if (_event.isCustom) {{");
303 writeln!(out, " when (_event.name) {{");
304 for ev in &view.events {
305 let cb = kotlin_ident(&event_handler_name(&ev.name));
306 let aliases: Vec<String> = event_wire_aliases(&ev.name)
307 .iter()
308 .map(|a| format!("\"{}\"", escape_kotlin_string(a)))
309 .collect();
310 writeln!(out, " {} -> {{", aliases.join(", "));
311 if ev.params.is_empty() {
312 writeln!(out, " {cb}?.invoke()");
313 } else {
314 let ev_cls = compose_event_class_name(name, ev);
315 writeln!(
316 out,
317 " {ev_cls}.fromBinBytes(_event.payloadBytes)?.let {{ {cb}?.invoke(it) }}"
318 );
319 }
320 writeln!(out, " }}");
321 }
322 writeln!(out, " }}");
323 writeln!(out, " }}");
324 writeln!(out, " }},");
325 }
326 writeln!(out, " hostBridge = hostBridge,");
327 writeln!(out, " )");
328 writeln!(out, "}}");
329}
330
331fn emit_kotlin_direct_props_writer(out: &mut CodeWriter, view: &HybridViewSpec) {
332 let name = &view.name;
333 writeln!(
334 out,
335 "/** Typed binary encoder writing `{}` props directly into `io.github.nativeview.host.BinWriter`. */",
336 sanitize_block_comment(name)
337 );
338 writeln!(out, "object {name}DirectPropsWriter {{");
339 let params: Vec<String> = view
340 .props
341 .iter()
342 .map(|p| format!("{}: {}", kotlin_ident(&to_camel_case(&p.name)), kotlin_type(&p.ty)))
343 .collect();
344 let args: Vec<String> = view
345 .props
346 .iter()
347 .map(|p| kotlin_ident(&to_camel_case(&p.name)))
348 .collect();
349 writeln!(out, " fun encodeTo(_w: BinWriter, {}) {{", params.join(", "));
350 writeln!(out, " val _mark = _w.beginMap({})", view.props.len());
351 for prop in &view.props {
352 let key = escape_kotlin_string(&prop.name);
353 let param = kotlin_ident(&to_camel_case(&prop.name));
354 writeln!(out, " _w.writeMapKey(\"{key}\")");
355 emit_kotlin_bin_write_value(out, " ", "_w", ¶m, &prop.ty, 0);
356 }
357 writeln!(out, " _w.end(_mark)");
358 writeln!(out, " }}");
359 writeln!(out);
360 writeln!(out, " fun encode({}): ByteArray {{", params.join(", "));
361 writeln!(out, " val _w = BinWriter()");
362 writeln!(out, " encodeTo(_w, {})", args.join(", "));
363 writeln!(out, " return _w.toByteArray()");
364 writeln!(out, " }}");
365 writeln!(out, "}}");
366 writeln!(out);
367}
368
369fn compose_event_class_name(comp_name: &str, ev: &HybridEventSpec) -> String {
370 format!("{comp_name}{}Event", event_stem_pascal(&ev.name))
371}
372
373fn emit_kotlin_event_data_class(
374 out: &mut CodeWriter,
375 file: &HybridFileSpec,
376 comp_name: &str,
377 ev: &HybridEventSpec,
378) {
379 if ev.params.is_empty() {
380 return;
381 }
382 let cls = compose_event_class_name(comp_name, ev);
383 writeln!(out, "@Immutable");
384 writeln!(out, "data class {cls}(");
385 for p in &ev.params {
386 let pname = kotlin_ident(&to_camel_case(&p.name));
387 writeln!(out, " val {pname}: {},", kotlin_type(&p.ty));
388 }
389 writeln!(out, ") {{");
390 writeln!(out, " companion object {{");
391 writeln!(out, " fun fromBinReader(_r: BinReader): {cls} {{");
392 for p in &ev.params {
393 let pname = kotlin_ident(&to_camel_case(&p.name));
394 let pty = kotlin_type(&p.ty);
395 let init = kotlin_zero_default(file, &p.ty);
396 writeln!(out, " var {pname}: {pty} = {init}");
397 }
398 writeln!(out, " if (_r.peekTag() == BinTag.MAP) {{");
399 writeln!(out, " val _mark = _r.beginMap()");
400 writeln!(out, " for (_i in 0 until _mark.count) {{");
401 writeln!(out, " when (_r.readMapKey()) {{");
402 for p in &ev.params {
403 let pname = kotlin_ident(&to_camel_case(&p.name));
404 let key = escape_kotlin_string(&p.name);
405 writeln!(out, " \"{key}\" -> {{");
406 emit_kotlin_bin_read_value(out, " ", "_r", &pname, false, &p.ty, 0);
407 writeln!(out, " }}");
408 }
409 writeln!(out, " else -> _r.skipValue()");
410 writeln!(out, " }}");
411 writeln!(out, " }}");
412 writeln!(out, " _r.end(_mark)");
413 writeln!(out, " }}");
414 writeln!(out, " return {cls}(");
415 for p in &ev.params {
416 let pname = kotlin_ident(&to_camel_case(&p.name));
417 writeln!(out, " {pname} = {pname},");
418 }
419 writeln!(out, " )");
420 writeln!(out, " }}");
421 writeln!(out);
422 writeln!(out, " fun fromBinBytes(_bytes: ByteArray): {cls}? {{");
423 writeln!(out, " if (_bytes.isEmpty()) return null");
424 writeln!(out, " return runCatching {{");
425 writeln!(out, " val _r = BinReader(_bytes)");
426 writeln!(out, " val _result = fromBinReader(_r)");
427 writeln!(out, " _r.expectEnd()");
428 writeln!(out, " _result");
429 writeln!(out, " }}.getOrNull()");
430 writeln!(out, " }}");
431 writeln!(out, " }}");
432 writeln!(out, "}}");
433 writeln!(out);
434}
435
436fn compose_event_lambda_type(comp_name: &str, ev: &HybridEventSpec) -> String {
437 if ev.params.is_empty() {
438 "() -> Unit".to_owned()
439 } else {
440 format!("({}) -> Unit", compose_event_class_name(comp_name, ev))
441 }
442}