build.rs

  1#![cfg_attr(any(not(target_os = "macos"), feature = "macos-blade"), allow(unused))]
  2
  3//TODO: consider generating shader code for WGSL
  4//TODO: deprecate "runtime-shaders" and "macos-blade"
  5
  6use std::env;
  7
  8fn main() {
  9    let target = env::var("CARGO_CFG_TARGET_OS");
 10    println!("cargo::rustc-check-cfg=cfg(gles)");
 11    match target.as_deref() {
 12        Ok("macos") => {
 13            #[cfg(target_os = "macos")]
 14            macos::build();
 15        }
 16        Ok("windows") => {
 17            let manifest = std::path::Path::new("resources/windows/gpui.manifest.xml");
 18            let rc_file = std::path::Path::new("resources/windows/gpui.rc");
 19            println!("cargo:rerun-if-changed={}", manifest.display());
 20            println!("cargo:rerun-if-changed={}", rc_file.display());
 21            embed_resource::compile(rc_file, embed_resource::NONE);
 22        }
 23        _ => (),
 24    };
 25}
 26
 27#[cfg(target_os = "macos")]
 28mod macos {
 29    use std::{
 30        env,
 31        path::{Path, PathBuf},
 32    };
 33
 34    use cbindgen::Config;
 35
 36    pub(super) fn build() {
 37        generate_dispatch_bindings();
 38        #[cfg(not(feature = "macos-blade"))]
 39        {
 40            let header_path = generate_shader_bindings();
 41
 42            #[cfg(feature = "runtime_shaders")]
 43            emit_stitched_shaders(&header_path);
 44            #[cfg(not(feature = "runtime_shaders"))]
 45            compile_metal_shaders(&header_path);
 46        }
 47    }
 48
 49    fn generate_dispatch_bindings() {
 50        println!("cargo:rustc-link-lib=framework=System");
 51        println!("cargo:rerun-if-changed=src/platform/mac/dispatch.h");
 52
 53        let bindings = bindgen::Builder::default()
 54            .header("src/platform/mac/dispatch.h")
 55            .allowlist_var("_dispatch_main_q")
 56            .allowlist_var("_dispatch_source_type_data_add")
 57            .allowlist_var("DISPATCH_QUEUE_PRIORITY_HIGH")
 58            .allowlist_var("DISPATCH_TIME_NOW")
 59            .allowlist_function("dispatch_get_global_queue")
 60            .allowlist_function("dispatch_async_f")
 61            .allowlist_function("dispatch_after_f")
 62            .allowlist_function("dispatch_time")
 63            .allowlist_function("dispatch_source_merge_data")
 64            .allowlist_function("dispatch_source_create")
 65            .allowlist_function("dispatch_source_set_event_handler_f")
 66            .allowlist_function("dispatch_resume")
 67            .allowlist_function("dispatch_suspend")
 68            .allowlist_function("dispatch_source_cancel")
 69            .allowlist_function("dispatch_set_context")
 70            .parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
 71            .layout_tests(false)
 72            .generate()
 73            .expect("unable to generate bindings");
 74
 75        let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
 76        bindings
 77            .write_to_file(out_path.join("dispatch_sys.rs"))
 78            .expect("couldn't write dispatch bindings");
 79    }
 80
 81    fn generate_shader_bindings() -> PathBuf {
 82        let output_path = PathBuf::from(env::var("OUT_DIR").unwrap()).join("scene.h");
 83        let crate_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
 84        let mut config = Config {
 85            include_guard: Some("SCENE_H".into()),
 86            language: cbindgen::Language::C,
 87            no_includes: true,
 88            ..Default::default()
 89        };
 90        config.export.include.extend([
 91            "Bounds".into(),
 92            "Corners".into(),
 93            "Edges".into(),
 94            "Size".into(),
 95            "Pixels".into(),
 96            "PointF".into(),
 97            "Hsla".into(),
 98            "ContentMask".into(),
 99            "Uniforms".into(),
100            "AtlasTile".into(),
101            "PathRasterizationInputIndex".into(),
102            "PathVertex_ScaledPixels".into(),
103            "ShadowInputIndex".into(),
104            "Shadow".into(),
105            "QuadInputIndex".into(),
106            "Underline".into(),
107            "UnderlineInputIndex".into(),
108            "Quad".into(),
109            "SpriteInputIndex".into(),
110            "MonochromeSprite".into(),
111            "PolychromeSprite".into(),
112            "PathSprite".into(),
113            "SurfaceInputIndex".into(),
114            "SurfaceBounds".into(),
115            "TransformationMatrix".into(),
116        ]);
117        config.no_includes = true;
118        config.enumeration.prefix_with_name = true;
119
120        let mut builder = cbindgen::Builder::new();
121
122        let src_paths = [
123            crate_dir.join("src/scene.rs"),
124            crate_dir.join("src/geometry.rs"),
125            crate_dir.join("src/color.rs"),
126            crate_dir.join("src/window.rs"),
127            crate_dir.join("src/platform.rs"),
128            crate_dir.join("src/platform/mac/metal_renderer.rs"),
129        ];
130        for src_path in src_paths {
131            println!("cargo:rerun-if-changed={}", src_path.display());
132            builder = builder.with_src(src_path);
133        }
134
135        builder
136            .with_config(config)
137            .generate()
138            .expect("Unable to generate bindings")
139            .write_to_file(&output_path);
140
141        output_path
142    }
143
144    /// To enable runtime compilation, we need to "stitch" the shaders file with the generated header
145    /// so that it is self-contained.
146    #[cfg(feature = "runtime_shaders")]
147    fn emit_stitched_shaders(header_path: &Path) {
148        use std::str::FromStr;
149        fn stitch_header(header: &Path, shader_path: &Path) -> std::io::Result<PathBuf> {
150            let header_contents = std::fs::read_to_string(header)?;
151            let shader_contents = std::fs::read_to_string(shader_path)?;
152            let stitched_contents = format!("{header_contents}\n{shader_contents}");
153            let out_path =
154                PathBuf::from(env::var("OUT_DIR").unwrap()).join("stitched_shaders.metal");
155            std::fs::write(&out_path, stitched_contents)?;
156            Ok(out_path)
157        }
158        let shader_source_path = "./src/platform/mac/shaders.metal";
159        let shader_path = PathBuf::from_str(shader_source_path).unwrap();
160        stitch_header(header_path, &shader_path).unwrap();
161        println!("cargo:rerun-if-changed={}", &shader_source_path);
162    }
163
164    #[cfg(not(feature = "runtime_shaders"))]
165    fn compile_metal_shaders(header_path: &Path) {
166        use std::process::{self, Command};
167        let shader_path = "./src/platform/mac/shaders.metal";
168        let air_output_path = PathBuf::from(env::var("OUT_DIR").unwrap()).join("shaders.air");
169        let metallib_output_path =
170            PathBuf::from(env::var("OUT_DIR").unwrap()).join("shaders.metallib");
171        println!("cargo:rerun-if-changed={}", shader_path);
172
173        let output = Command::new("xcrun")
174            .args([
175                "-sdk",
176                "macosx",
177                "metal",
178                "-gline-tables-only",
179                "-mmacosx-version-min=10.15.7",
180                "-MO",
181                "-c",
182                shader_path,
183                "-include",
184                (header_path.to_str().unwrap()),
185                "-o",
186            ])
187            .arg(&air_output_path)
188            .output()
189            .unwrap();
190
191        if !output.status.success() {
192            eprintln!(
193                "metal shader compilation failed:\n{}",
194                String::from_utf8_lossy(&output.stderr)
195            );
196            process::exit(1);
197        }
198
199        let output = Command::new("xcrun")
200            .args(["-sdk", "macosx", "metallib"])
201            .arg(air_output_path)
202            .arg("-o")
203            .arg(metallib_output_path)
204            .output()
205            .unwrap();
206
207        if !output.status.success() {
208            eprintln!(
209                "metallib compilation failed:\n{}",
210                String::from_utf8_lossy(&output.stderr)
211            );
212            process::exit(1);
213        }
214    }
215}