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