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