Skip to main content

nativeview_codegen/targets/c_cpp/export/
windows.rs

1//! `<Name>RnwComponentView.generated.hpp` (`react-native-windows` Fabric registration) emitter for `export_rn`.
2//!
3//! Targets `hosts/windows-shell`: `NvRnwComponentView.hpp` (registration) over `NvWinHost` (the
4//! runtime surface).
5
6use crate::naming::{cpp_ident, escape_c_like_string, to_snake_case};
7use crate::schema::hybrid::{HybridFileSpec, HybridViewSpec};
8use crate::targets::export_common::{event_handler_name, event_wire_aliases};
9use crate::writer::CodeWriter;
10
11pub(crate) fn emit_windows_rnw_component_view_hpp(
12    file: &HybridFileSpec,
13    view: &HybridViewSpec,
14) -> String {
15    let name = &view.name;
16    let snake = to_snake_case(name);
17    let vtable_sym = view.vtable_symbol(file);
18    let mut out = CodeWriter::with_capacity(3072);
19
20    writeln!(out, "#pragma once");
21    writeln!(out);
22    writeln!(
23        out,
24        "// @generated by nativeview-codegen (`export_rn`) — DO NOT EDIT."
25    );
26    writeln!(
27        out,
28        "// `react-native-windows` Fabric component over `hosts/windows-shell` (`NvRnwComponentView.hpp`, `NvWinHost`)."
29    );
30    writeln!(out);
31    writeln!(out, "#include \"NvRnwComponentView.hpp\"");
32    writeln!(out, "#include \"NvWinHost.hpp\"");
33    writeln!(out);
34    writeln!(out, "#include <functional>");
35    writeln!(out, "#include <memory>");
36    writeln!(out, "#include <span>");
37    writeln!(out, "#include <string>");
38    writeln!(out, "#include <string_view>");
39    writeln!(out, "#include <utility>");
40    writeln!(out);
41    writeln!(
42        out,
43        "extern \"C\" const void* {vtable_sym}(uint32_t interface_id);"
44    );
45    writeln!(out);
46    writeln!(out, "namespace nv::exported {{");
47    writeln!(out);
48    writeln!(
49        out,
50        "inline constexpr std::wstring_view k{name}RnwComponentName = L\"{}\";",
51        escape_c_like_string(name)
52    );
53    writeln!(
54        out,
55        "inline constexpr bool k{name}RnwDefaultContentIsland = false;"
56    );
57    writeln!(out);
58    writeln!(
59        out,
60        "/// `{name}` custom events by name; `payload_bin` is the `nv.custom` `NvEvent`'s binary payload slice (empty otherwise)."
61    );
62    writeln!(out, "struct {name}RnwEventCallbacks {{");
63    for ev in &view.events {
64        writeln!(
65            out,
66            "  std::function<void(NvBufferSlice payload_bin)> {};",
67            cpp_ident(&event_handler_name(&ev.name))
68        );
69    }
70    writeln!(out, "}};");
71    writeln!(out);
72    writeln!(out, "class {name}RnwComponentView {{");
73    writeln!(out, " public:");
74    writeln!(
75        out,
76        "  explicit {name}RnwComponentView(std::shared_ptr<nv::win::NvWinHost> host, {name}RnwEventCallbacks callbacks = {{}})"
77    );
78    writeln!(
79        out,
80        "      : host_(std::move(host)), callbacks_(std::move(callbacks)) {{"
81    );
82    writeln!(out, "    if (host_ == nullptr) return;");
83    writeln!(
84        out,
85        "    host_->set_event_callback([this](NvEventBatch batch) {{"
86    );
87    writeln!(out, "      if (batch.events == nullptr) return;");
88    writeln!(
89        out,
90        "      for (uint32_t i = 0u; i < batch.event_count; ++i) dispatch_event(batch.events[i], batch);"
91    );
92    writeln!(out, "    }});");
93    writeln!(out, "  }}");
94    writeln!(
95        out,
96        "  ~{name}RnwComponentView() {{ if (host_ != nullptr) host_->set_event_callback({{}}); }}"
97    );
98    writeln!(
99        out,
100        "  {name}RnwComponentView(const {name}RnwComponentView&) = delete;"
101    );
102    writeln!(
103        out,
104        "  {name}RnwComponentView& operator=(const {name}RnwComponentView&) = delete;"
105    );
106    writeln!(out);
107    writeln!(
108        out,
109        "  bool attach(NvGetInterfaceFn interface_override = nullptr) {{"
110    );
111    writeln!(
112        out,
113        "    return host_ != nullptr && host_->attach_interface(interface_override != nullptr ? interface_override : &{vtable_sym});"
114    );
115    writeln!(out, "  }}");
116    writeln!(
117        out,
118        "  bool update_props(std::span<const NvMapEntry> props) {{ return host_ != nullptr && host_->apply_props(props); }}"
119    );
120    writeln!(
121        out,
122        "  void set_callbacks({name}RnwEventCallbacks callbacks) {{ callbacks_ = std::move(callbacks); }}"
123    );
124    writeln!(
125        out,
126        "  [[nodiscard]] nv::win::NvWinHost* host() noexcept {{ return host_.get(); }}"
127    );
128    writeln!(out);
129    writeln!(out, " private:");
130    writeln!(
131        out,
132        "  void dispatch_event(const NvEvent& ev, NvEventBatch batch) {{"
133    );
134    writeln!(
135        out,
136        "    if (ev.table != NV_TABLE_CUSTOM || (ev.flags & NV_EVENT_FLAG_CUSTOM_NAMED) == 0u) return;"
137    );
138    writeln!(
139        out,
140        "    if (batch.bytes == nullptr || ev.bytes.offset > batch.bytes_len || ev.bytes.len > batch.bytes_len - ev.bytes.offset) return;"
141    );
142    writeln!(out, "    const uint32_t name_len = ev.payload[0];");
143    writeln!(out, "    if (name_len > ev.bytes.len) return;");
144    writeln!(
145        out,
146        "    const uint8_t* const base = batch.bytes + ev.bytes.offset;"
147    );
148    writeln!(
149        out,
150        "    const std::string_view event(reinterpret_cast<const char*>(base), name_len);"
151    );
152    writeln!(
153        out,
154        "    const uint32_t payload_len = ev.bytes.len - name_len;"
155    );
156    writeln!(
157        out,
158        "    const NvBufferSlice payload_bin{{payload_len > 0u ? base + name_len : nullptr, payload_len}};"
159    );
160    for (idx, ev) in view.events.iter().enumerate() {
161        let cb_name = cpp_ident(&event_handler_name(&ev.name));
162        let kw = if idx == 0 { "if" } else { "} else if" };
163        let cond = event_wire_aliases(&ev.name)
164            .iter()
165            .map(|a| format!("event == \"{}\"", escape_c_like_string(a)))
166            .collect::<Vec<_>>()
167            .join(" || ");
168        writeln!(out, "    {kw} ({cond}) {{");
169        writeln!(
170            out,
171            "      if (callbacks_.{cb_name}) callbacks_.{cb_name}(payload_bin);"
172        );
173    }
174    if !view.events.is_empty() {
175        writeln!(out, "    }}");
176    }
177    writeln!(out, "    (void)event;");
178    writeln!(out, "    (void)payload_bin;");
179    writeln!(out, "  }}");
180    writeln!(out);
181    writeln!(out, "  std::shared_ptr<nv::win::NvWinHost> host_;");
182    writeln!(out, "  {name}RnwEventCallbacks callbacks_;");
183    writeln!(out, "}};");
184    writeln!(out);
185    writeln!(
186        out,
187        "#if defined(_WIN32) && defined(NV_WITH_RNW_FABRIC) && NV_WITH_RNW_FABRIC"
188    );
189    writeln!(
190        out,
191        "inline nv::win::NvRnwComponentRegistrationConfig make_{snake}_rnw_registration_config("
192    );
193    writeln!(out, "    NvGetInterfaceFn interface_override = nullptr,");
194    writeln!(
195        out,
196        "    bool use_content_island = k{name}RnwDefaultContentIsland) {{"
197    );
198    writeln!(out, "  nv::win::NvRnwComponentRegistrationConfig cfg{{}};");
199    writeln!(
200        out,
201        "  cfg.component_name = std::wstring(k{name}RnwComponentName);"
202    );
203    writeln!(
204        out,
205        "  cfg.default_interface = interface_override != nullptr ? interface_override : &{vtable_sym};"
206    );
207    writeln!(out, "  cfg.use_content_island = use_content_island;");
208    writeln!(out, "  return cfg;");
209    writeln!(out, "}}");
210    writeln!(out);
211    writeln!(out, "inline bool register_{snake}_rnw_component(");
212    writeln!(
213        out,
214        "    winrt::Microsoft::ReactNative::IReactPackageBuilder const& package_builder,"
215    );
216    writeln!(out, "    NvGetInterfaceFn interface_override = nullptr,");
217    writeln!(
218        out,
219        "    bool use_content_island = k{name}RnwDefaultContentIsland) {{"
220    );
221    writeln!(out, "  return nv::win::register_nv_rnw_component(");
222    writeln!(out, "      package_builder,");
223    writeln!(
224        out,
225        "      make_{snake}_rnw_registration_config(interface_override, use_content_island));"
226    );
227    writeln!(out, "}}");
228    writeln!(
229        out,
230        "#endif // defined(_WIN32) && defined(NV_WITH_RNW_FABRIC) && NV_WITH_RNW_FABRIC"
231    );
232    writeln!(out);
233    writeln!(out, "}} // namespace nv::exported");
234    out.into_string()
235}