Skip to main content

nativeview_codegen/targets/c_cpp/export/
ios.rs

1//! `<Name>ComponentView.generated.mm` (iOS ObjC++ Fabric view) emitter for `export_rn`.
2//!
3//! Encodes all view props directly into `NvBinValue` via `nv::host::BinWriter` (zero
4//! `NSDictionary` boxing) and decodes outbound events from `onNvEventBytes` via
5//! `nv::host::BinReader` into typed `{Name}EventEmitter::{Event}` structs.
6
7use crate::naming::{cpp_ident, escape_c_like_string, to_camel_case, to_pascal_case};
8use crate::schema::hybrid::{HybridEventSpec, HybridFileSpec, HybridViewSpec};
9use crate::targets::export_common::{
10    default_ios_module_name, event_handler_name, event_wire_aliases, ios_core_framework_name,
11    rn_codegen_spec_name,
12};
13use crate::writer::CodeWriter;
14
15use super::ios_codec::{
16    emit_cpp_read_expr, emit_cpp_write_expr, emit_objc_codec_helpers, emit_objc_ns_arg_write,
17};
18
19pub(crate) fn emit_ios_component_view_mm(
20    file: &HybridFileSpec,
21    view: &HybridViewSpec,
22    ios_module_name: Option<&str>,
23) -> String {
24    let name = &view.name;
25    let codegen_spec = rn_codegen_spec_name(file);
26    let vtable_sym = view.vtable_symbol(file);
27    let mod_name = ios_module_name
28        .filter(|s| !s.is_empty())
29        .map(str::to_owned)
30        .unwrap_or_else(|| default_ios_module_name(file));
31    let framework_name = ios_core_framework_name(&mod_name);
32    let escaped_fw = escape_c_like_string(&framework_name);
33    let escaped_sym = escape_c_like_string(&vtable_sym);
34    let (_enums, structs) = view.referenced_types(file);
35    let mut out = CodeWriter::with_capacity(4096);
36
37    writeln!(
38        out,
39        "// @generated by nativeview-codegen (`export_rn`) — DO NOT EDIT."
40    );
41    writeln!(
42        out,
43        "// iOS ObjC++ Fabric ComponentView subclassing `RCTNvComponentView` over binary `NvBinValue`."
44    );
45    writeln!(out);
46    writeln!(out, "#import \"RCTNvComponentView.h\"");
47    writeln!(out, "#include <dispatch/dispatch.h>");
48    writeln!(out, "#include <dlfcn.h>");
49    writeln!(out, "#include <nv/host/bin_codec.hpp>");
50    writeln!(out, "#include <algorithm>");
51    writeln!(out, "#include <cmath>");
52    writeln!(out, "#include <cstdint>");
53    writeln!(out, "#include <limits>");
54    writeln!(out, "#include <optional>");
55    writeln!(out, "#include <span>");
56    writeln!(out, "#include <string>");
57    writeln!(out, "#include <string_view>");
58    writeln!(out, "#include <type_traits>");
59    writeln!(out, "#include <vector>");
60    writeln!(out);
61    writeln!(out, "static NvGetInterfaceFn _Nullable nvResolve{name}Interface(void) {{");
62    writeln!(out, "  static NvGetInterfaceFn resolved = nullptr;");
63    writeln!(out, "  static dispatch_once_t onceToken;");
64    writeln!(out, "  dispatch_once(&onceToken, ^{{");
65    writeln!(
66        out,
67        "    void *handle = dlopen(\"@rpath/{escaped_fw}.framework/{escaped_fw}\", RTLD_NOW | RTLD_LOCAL);"
68    );
69    writeln!(out, "    if (handle != nullptr) {{");
70    writeln!(
71        out,
72        "      resolved = reinterpret_cast<NvGetInterfaceFn>(dlsym(handle, \"{escaped_sym}\"));"
73    );
74    writeln!(out, "    }}");
75    writeln!(out, "  }});");
76    writeln!(out, "  return resolved;");
77    writeln!(out, "}}");
78    writeln!(out);
79    writeln!(out, "@class {name}ComponentView;");
80    writeln!(out);
81    writeln!(out, "#if defined(NV_WITH_RN_FABRIC) && NV_WITH_RN_FABRIC");
82    writeln!(out, "#include <nv/host/runtime_session.hpp>");
83    writeln!(out, "#include <nv/host/value_tree.hpp>");
84    writeln!(out, "#include <mutex>");
85    writeln!(out, "#import <React/RCTConversions.h>");
86    writeln!(out, "#include <react/renderer/core/LayoutConstraints.h>");
87    writeln!(
88        out,
89        "#import <react/renderer/components/{codegen_spec}/ComponentDescriptors.h>"
90    );
91    writeln!(
92        out,
93        "#import <react/renderer/components/{codegen_spec}/EventEmitters.h>"
94    );
95    writeln!(out, "#import <react/renderer/components/{codegen_spec}/Props.h>");
96    writeln!(
97        out,
98        "#import <react/renderer/components/{codegen_spec}/RCTComponentViewHelpers.h>"
99    );
100    writeln!(
101        out,
102        "#import <react/renderer/components/{codegen_spec}/ShadowNodes.h>"
103    );
104    writeln!(out, "using namespace facebook::react;");
105    writeln!(out);
106
107    emit_objc_codec_helpers(&mut out, file, view, &structs);
108    emit_encode_props_helper(&mut out, view);
109    emit_fabric_measure_descriptor(&mut out, name, !view.props.is_empty());
110    writeln!(out, "#endif");
111    writeln!(out);
112
113    writeln!(out, "@interface {name}ComponentView : RCTNvComponentView");
114    writeln!(out, "@end");
115    writeln!(out);
116    writeln!(out, "@implementation {name}ComponentView {{");
117    writeln!(out, "#if defined(NV_WITH_RN_FABRIC) && NV_WITH_RN_FABRIC");
118    writeln!(out, "  nv::host::BinWriter _propsWriter;");
119    writeln!(out, "#endif");
120    writeln!(out, "}}");
121    writeln!(out);
122
123    writeln!(out, "- (instancetype)initWithFrame:(CGRect)frame {{");
124    writeln!(out, "  if ((self = [super initWithFrame:frame])) {{");
125    writeln!(out, "#if defined(NV_WITH_RN_FABRIC) && NV_WITH_RN_FABRIC");
126    writeln!(out, "    static const auto defaultProps = std::make_shared<const {name}Props>();");
127    writeln!(out, "    _props = defaultProps;");
128    writeln!(out, "#endif");
129    writeln!(out, "    __weak {name}ComponentView *weakSelf = self;");
130    writeln!(
131        out,
132        "    self.onNvEventBytes = ^(NSString *eventName, NSData *payloadBytes) {{"
133    );
134    writeln!(
135        out,
136        "      [weakSelf dispatchNvEventBytes:eventName payloadBytes:payloadBytes];"
137    );
138    writeln!(out, "    }};");
139    writeln!(out, "  }}");
140    writeln!(out, "  return self;");
141    writeln!(out, "}}");
142    writeln!(out);
143
144    writeln!(out, "- (nullable NvGetInterfaceFn)defaultNvGetInterface {{");
145    writeln!(out, "  return nvResolve{name}Interface();");
146    writeln!(out, "}}");
147    writeln!(out);
148
149    writeln!(out, "- (CGSize)sizeThatFits:(CGSize)size {{");
150    writeln!(out, "  CGSize measured = CGSizeZero;");
151    writeln!(
152        out,
153        "  return [self measureNvSurfaceWithMaxWidth:size.width maxHeight:size.height outSize:&measured]"
154    );
155    writeln!(out, "             ? measured");
156    writeln!(out, "             : [super sizeThatFits:size];");
157    writeln!(out, "}}");
158    writeln!(out);
159
160    writeln!(out, "- (CGSize)intrinsicContentSize {{");
161    writeln!(
162        out,
163        "  return [self measureNvSurfaceWithMaxWidth:CGFLOAT_MAX maxHeight:CGFLOAT_MAX];"
164    );
165    writeln!(out, "}}");
166    writeln!(out);
167
168    writeln!(out, "#if defined(NV_WITH_RN_FABRIC) && NV_WITH_RN_FABRIC");
169    writeln!(
170        out,
171        "+ (ComponentDescriptorProvider)componentDescriptorProvider {{"
172    );
173    writeln!(
174        out,
175        "  return concreteComponentDescriptorProvider<{name}NvComponentDescriptor>();"
176    );
177    writeln!(out, "}}");
178    writeln!(out);
179
180    emit_update_props(&mut out, view);
181    if !view.methods.is_empty() {
182        emit_handle_command(&mut out, view);
183    }
184    writeln!(out, "#endif");
185    writeln!(out);
186
187    emit_dispatch_event_bytes(&mut out, view);
188
189    writeln!(out, "@end");
190    writeln!(out);
191    writeln!(out, "#if defined(NV_WITH_RN_FABRIC) && NV_WITH_RN_FABRIC");
192    writeln!(out, "Class<RCTComponentViewProtocol> {name}Cls(void) {{");
193    writeln!(out, "  return {name}ComponentView.class;");
194    writeln!(out, "}}");
195    writeln!(out, "#endif");
196
197    out.into_string()
198}
199
200fn emit_encode_props_helper(out: &mut CodeWriter, view: &HybridViewSpec) {
201    let name = &view.name;
202    writeln!(
203        out,
204        "static void nvEncode{name}Props(nv::host::BinWriter &writer, const {name}Props &viewProps) {{"
205    );
206    writeln!(out, "  writer.clear();");
207    if view.props.is_empty() {
208        writeln!(out, "  (void)viewProps;");
209        writeln!(out, "  auto _mark = writer.begin_map(0u);");
210        writeln!(out, "  writer.end(_mark);");
211    } else {
212        writeln!(out, "  auto _mark = writer.begin_map({});", view.props.len());
213        for prop in &view.props {
214            let key = escape_c_like_string(&prop.name);
215            let field = cpp_ident(&to_camel_case(&prop.name));
216            writeln!(out, "  writer.write_map_key(\"{key}\");");
217            emit_cpp_write_expr(
218                out,
219                "  ",
220                "writer",
221                &format!("viewProps.{field}"),
222                &prop.ty,
223                0,
224            );
225        }
226        writeln!(out, "  writer.end(_mark);");
227    }
228    writeln!(out, "}}");
229    writeln!(out);
230}
231
232fn emit_fabric_measure_descriptor(
233    out: &mut CodeWriter,
234    name: &str,
235    has_props: bool,
236) {
237    writeln!(out, "struct {name}MeasureRuntime {{");
238    writeln!(out, "  std::mutex mu;");
239    writeln!(out, "  std::optional<nv::host::RuntimeSession> session;");
240    writeln!(out, "  nv::host::BinWriter propsWriter;");
241    writeln!(out, "  nv::host::NvValueTree propsTree;");
242    writeln!(out, "  bool initialized = false;");
243    writeln!(out);
244    writeln!(
245        out,
246        "  facebook::react::Size measure(const {name}Props &props, const LayoutConstraints &constraints) {{"
247    );
248    writeln!(out, "    std::lock_guard<std::mutex> lock(mu);");
249    writeln!(out, "    if (!initialized) {{");
250    writeln!(out, "      initialized = true;");
251    writeln!(
252        out,
253        "      session = nv::host::RuntimeSession::create(nv_runtime_get_interface(NV_RUNTIME_ABI_VERSION));"
254    );
255    writeln!(out, "      if (session.has_value()) {{");
256    writeln!(out, "        if (const NvGetInterfaceFn fn = nvResolve{name}Interface()) {{");
257    writeln!(out, "          (void)session->attach_app_interface(fn);");
258    writeln!(out, "        }}");
259    writeln!(out, "      }}");
260    writeln!(out, "    }}");
261    writeln!(out, "    if (!session.has_value()) return constraints.clamp({{0.0f, 0.0f}});");
262    if has_props {
263        writeln!(out, "    nvEncode{name}Props(propsWriter, props);");
264        writeln!(out, "    nv::host::BinReader reader(propsWriter.bytes());");
265        writeln!(out, "    propsTree.clear();");
266        writeln!(out, "    const NvValue root = propsTree.read_value(reader);");
267        writeln!(out, "    if (reader.ok() && reader.at_end() && root.tag == NV_VAL_MAP) {{");
268        writeln!(
269            out,
270            "      (void)session->set_props(root.data.map_val.ptr, static_cast<uint32_t>(root.data.map_val.len));"
271        );
272        writeln!(out, "    }}");
273        writeln!(out, "    propsTree.clear();");
274    } else {
275        writeln!(out, "    (void)props;");
276    }
277    writeln!(
278        out,
279        "    const float minW = std::isfinite(constraints.minimumSize.width) ? std::max(0.0f, static_cast<float>(constraints.minimumSize.width)) : 0.0f;"
280    );
281    writeln!(
282        out,
283        "    const float minH = std::isfinite(constraints.minimumSize.height) ? std::max(0.0f, static_cast<float>(constraints.minimumSize.height)) : 0.0f;"
284    );
285    writeln!(
286        out,
287        "    const float maxW = std::isfinite(constraints.maximumSize.width) ? static_cast<float>(constraints.maximumSize.width) : std::numeric_limits<float>::infinity();"
288    );
289    writeln!(
290        out,
291        "    const float maxH = std::isfinite(constraints.maximumSize.height) ? static_cast<float>(constraints.maximumSize.height) : std::numeric_limits<float>::infinity();"
292    );
293    writeln!(out, "    const NvSizeConstraints c{{minW, minH, maxW, maxH}};");
294    writeln!(
295        out,
296        "    const uint32_t flags = NV_MEASURE_FLAG_DRY_RUN | ((std::isinf(maxW) && std::isinf(maxH)) ? NV_MEASURE_FLAG_IDEAL : 0u);"
297    );
298    writeln!(out, "    NvSurfaceMeasure out{{}};");
299    writeln!(
300        out,
301        "    if (session->measure_surface(c, flags, &out) != NV_RUNTIME_OK || !std::isfinite(out.width) || !std::isfinite(out.height)) {{"
302    );
303    writeln!(out, "      return constraints.clamp({{0.0f, 0.0f}});");
304    writeln!(out, "    }}");
305    writeln!(
306        out,
307        "    return constraints.clamp({{static_cast<Float>(std::max(0.0f, out.width)), static_cast<Float>(std::max(0.0f, out.height))}});"
308    );
309    writeln!(out, "  }}");
310    writeln!(out, "}};");
311    writeln!(out);
312    writeln!(out, "static {name}MeasureRuntime &nv{name}MeasureRuntime(void) {{");
313    writeln!(out, "  static {name}MeasureRuntime rt;");
314    writeln!(out, "  return rt;");
315    writeln!(out, "}}");
316    writeln!(out);
317    writeln!(
318        out,
319        "class {name}NvShadowNode final : public {name}ShadowNode {{"
320    );
321    writeln!(out, " public:");
322    writeln!(out, "  using {name}ShadowNode::{name}ShadowNode;");
323    writeln!(out);
324    writeln!(out, "  static ShadowNodeTraits BaseTraits() {{");
325    writeln!(out, "    auto traits = {name}ShadowNode::BaseTraits();");
326    writeln!(out, "    traits.set(ShadowNodeTraits::Trait::LeafYogaNode);");
327    writeln!(out, "    traits.set(ShadowNodeTraits::Trait::MeasurableYogaNode);");
328    writeln!(out, "    return traits;");
329    writeln!(out, "  }}");
330    writeln!(out);
331    writeln!(
332        out,
333        "  facebook::react::Size measureContent(const LayoutContext &layoutContext, const LayoutConstraints &layoutConstraints) const override {{"
334    );
335    writeln!(out, "    (void)layoutContext;");
336    writeln!(
337        out,
338        "    return nv{name}MeasureRuntime().measure(getConcreteProps(), layoutConstraints);"
339    );
340    writeln!(out, "  }}");
341    writeln!(out, "}};");
342    writeln!(out);
343    writeln!(
344        out,
345        "using {name}NvComponentDescriptor = ConcreteComponentDescriptor<{name}NvShadowNode>;"
346    );
347    writeln!(out);
348}
349
350fn emit_update_props(out: &mut CodeWriter, view: &HybridViewSpec) {
351    let name = &view.name;
352    writeln!(
353        out,
354        "- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps {{"
355    );
356    writeln!(
357        out,
358        "  const auto &oldViewProps = *std::static_pointer_cast<{name}Props const>(_props);"
359    );
360    writeln!(
361        out,
362        "  const auto &newViewProps = *std::static_pointer_cast<{name}Props const>(props);"
363    );
364    writeln!(out, "  if (!newViewProps.pairUrl.empty() && (newViewProps.pairUrl != oldViewProps.pairUrl || newViewProps.pairToken != oldViewProps.pairToken)) {{");
365    writeln!(
366        out,
367        "    NSString *url = [NSString stringWithUTF8String:newViewProps.pairUrl.c_str()];"
368    );
369    writeln!(
370        out,
371        "    NSString *tok = [NSString stringWithUTF8String:newViewProps.pairToken.c_str()];"
372    );
373    writeln!(
374        out,
375        "    [self connectPairedEndpoint:url token:tok surfaceId:self.nvSurfaceId error:nil];"
376    );
377    writeln!(out, "  }}");
378    if !view.props.is_empty() {
379        writeln!(out, "  nvEncode{name}Props(_propsWriter, newViewProps);");
380        writeln!(
381            out,
382            "  NSData *propsData = [NSData dataWithBytesNoCopy:(void *)_propsWriter.bytes().data() length:_propsWriter.bytes().size() freeWhenDone:NO];"
383        );
384        writeln!(out, "  [self applyNvPropsBytes:propsData];");
385    }
386    writeln!(out, "  [self drainNvEmittedEvents];");
387    writeln!(out, "  [super updateProps:props oldProps:oldProps];");
388    writeln!(out, "}}");
389    writeln!(out);
390}
391
392fn emit_handle_command(out: &mut CodeWriter, view: &HybridViewSpec) {
393    writeln!(
394        out,
395        "- (void)handleCommand:(const NSString *)commandName args:(const NSArray *)args {{"
396    );
397    for (idx, m) in view.methods.iter().enumerate() {
398        let kw = if idx == 0 { "if" } else { "else if" };
399        let cname = to_camel_case(&m.name);
400        let raw_name = escape_c_like_string(&m.name);
401        writeln!(
402            out,
403            "  {kw} ([commandName isEqualToString:@\"{}\"] || [commandName isEqualToString:@\"{raw_name}\"]) {{",
404            escape_c_like_string(&cname)
405        );
406        writeln!(out, "    _propsWriter.clear();");
407        writeln!(out, "    auto _m = _propsWriter.begin_map({});", m.params.len());
408        for (pidx, p) in m.params.iter().enumerate() {
409            let pkey = escape_c_like_string(&p.name);
410            writeln!(out, "    _propsWriter.write_map_key(\"{pkey}\");");
411            writeln!(
412                out,
413                "    if (args.count > {pidx} && ![args[{pidx}] isKindOfClass:[NSNull class]]) {{"
414            );
415            emit_objc_ns_arg_write(out, "      ", "_propsWriter", &format!("args[{pidx}]"), &p.ty, 0);
416            writeln!(out, "    }} else {{ _propsWriter.write_null(); }}");
417        }
418        writeln!(out, "    _propsWriter.end(_m);");
419        writeln!(
420            out,
421            "    NSData *cmdData = [NSData dataWithBytesNoCopy:(void *)_propsWriter.bytes().data() length:_propsWriter.bytes().size() freeWhenDone:NO];"
422        );
423        writeln!(
424            out,
425            "    [self dispatchNvCustomEvent:@\"{raw_name}\" payloadBytes:cmdData];"
426        );
427        writeln!(out, "  }}");
428    }
429    writeln!(out, "}}");
430    writeln!(out);
431}
432
433fn emit_dispatch_event_bytes(out: &mut CodeWriter, view: &HybridViewSpec) {
434    let name = &view.name;
435    let has_event_payloads = view.events.iter().any(|e| !e.params.is_empty());
436    writeln!(
437        out,
438        "- (void)dispatchNvEventBytes:(NSString *)eventName payloadBytes:(NSData *)payloadBytes {{"
439    );
440    writeln!(out, "#if defined(NV_WITH_RN_FABRIC) && NV_WITH_RN_FABRIC");
441    if has_event_payloads {
442        writeln!(
443            out,
444            "  const auto *bytes = static_cast<const uint8_t *>(payloadBytes.bytes);"
445        );
446        writeln!(
447            out,
448            "  const size_t length = static_cast<size_t>(payloadBytes.length);"
449        );
450    } else {
451        writeln!(out, "  (void)payloadBytes;");
452    }
453    if view.events.is_empty() {
454        writeln!(out, "  (void)eventName;");
455    } else {
456        writeln!(out, "  if (_eventEmitter != nullptr) {{");
457        writeln!(
458            out,
459            "    auto emitter = std::static_pointer_cast<const {name}EventEmitter>(_eventEmitter);"
460        );
461        for (idx, ev) in view.events.iter().enumerate() {
462            emit_event_branch(out, name, ev, idx == 0);
463        }
464        writeln!(out, "  }}");
465    }
466    writeln!(out, "#else");
467    writeln!(out, "  (void)eventName; (void)payloadBytes;");
468    writeln!(out, "#endif");
469    writeln!(out, "}}");
470    writeln!(out);
471}
472
473fn emit_event_branch(
474    out: &mut CodeWriter,
475    name: &str,
476    ev: &HybridEventSpec,
477    first: bool,
478) {
479    let kw = if first { "if" } else { "else if" };
480    let cond = event_wire_aliases(&ev.name)
481        .iter()
482        .map(|a| format!("[eventName isEqualToString:@\"{}\"]", escape_c_like_string(a)))
483        .collect::<Vec<_>>()
484        .join(" || ");
485    let handler = event_handler_name(&ev.name);
486    let ev_method = cpp_ident(&handler);
487    let ev_struct = to_pascal_case(&handler);
488    writeln!(out, "    {kw} ({cond}) {{");
489    writeln!(out, "      {name}EventEmitter::{ev_struct} eventPayload{{}};");
490    if !ev.params.is_empty() {
491        writeln!(out, "      if (bytes != nullptr && length > 0u) {{");
492        writeln!(
493            out,
494            "        nv::host::BinReader reader(std::span<const uint8_t>(bytes, length));"
495        );
496        writeln!(
497            out,
498            "        if (reader.peek_tag() == nv::host::BinTag::Map) {{"
499        );
500        writeln!(out, "          auto _m = reader.begin_map();");
501        writeln!(
502            out,
503            "          for (uint32_t _i = 0; _i < _m.count && reader.ok(); ++_i) {{"
504        );
505        writeln!(out, "            const std::string_view _k = reader.read_map_key();");
506        for (pidx, p) in ev.params.iter().enumerate() {
507            let pkw = if pidx == 0 { "if" } else { "else if" };
508            let pkey = escape_c_like_string(&p.name);
509            let pfield = cpp_ident(&to_camel_case(&p.name));
510            writeln!(out, "            {pkw} (_k == \"{pkey}\") {{");
511            emit_cpp_read_expr(
512                out,
513                "              ",
514                "reader",
515                &format!("eventPayload.{pfield}"),
516                &p.ty,
517                0,
518            );
519            writeln!(out, "            }}");
520        }
521        writeln!(out, "            else {{ reader.skip_value(); }}");
522        writeln!(out, "          }}");
523        writeln!(out, "          reader.end(_m);");
524        writeln!(out, "        }}");
525        writeln!(out, "      }}");
526    }
527    writeln!(out, "      emitter->{ev_method}(std::move(eventPayload));");
528    writeln!(out, "    }}");
529}