vips-sys 0.3.0

libvips bindings for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
// SPDX-License-Identifier: MIT
//
// Build script for vips-sys (MIT).
// Links against libvips, which is LGPL-2.1 — see README “License”.

use std::fs;
use std::{collections::HashSet, env, path::PathBuf};

#[path = "build_support/config.rs"]
mod config;
use config::BuildOptions;

#[path = "build_support/unix.rs"]
mod unix;
#[path = "build_support/windows.rs"]
mod windows;

type IncludePaths = Vec<PathBuf>;
type Defines = Vec<(String, Option<String>)>;
#[derive(Default)]
struct LibraryInfo {
    include_paths: IncludePaths,
    defines: Defines,
    version: Option<String>,
}

type ProbeResult = Option<LibraryInfo>;

fn pkg_info(lib: pkg_config::Library, options: &BuildOptions) -> LibraryInfo {
    let defines = if options.generate_bindings {
        lib.defines.into_iter().collect()
    } else {
        Vec::new()
    };
    LibraryInfo {
        include_paths: lib.include_paths,
        defines,
        version: Some(lib.version),
    }
}

fn vendor_root(options: &BuildOptions) -> Option<PathBuf> {
    if options.no_vendor {
        return None;
    }
    let root = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR")?).join("vendor/libvips");
    if root.is_dir() && root.join("meson.build").is_file() {
        Some(root)
    } else {
        None
    }
}

fn vendor_include_paths(options: &BuildOptions) -> Option<IncludePaths> {
    let root = vendor_root(options)?;
    let mut paths = Vec::new();
    let candidates = [
        root.join("libvips/include"),
        root.join("libvips/include/vips"),
        root.join("libvips"),
        root.join("libvips/build/vips"),
    ];
    for p in candidates {
        if p.is_dir() {
            paths.push(p);
        }
    }
    if paths.is_empty() { None } else { Some(paths) }
}

fn emit_link(kind: &str) {
    if kind == "static" {
        println!("cargo:rustc-link-lib=static=vips");
    } else {
        // Explicit dylib keeps the dynamic path obvious and avoids accidental static pull-in.
        println!("cargo:rustc-link-lib=dylib=vips");
    }
}

fn merge_includes(mut paths: IncludePaths, extra: IncludePaths) -> IncludePaths {
    let mut seen: HashSet<PathBuf> = paths.iter().cloned().collect();
    for p in extra {
        if seen.insert(p.clone()) {
            paths.push(p);
        }
    }
    paths
}

/// Used by the non-MSVC probe path and by feature `bindgen` (vendor headers).
fn glib_include_paths() -> IncludePaths {
    // GObject's .pc file already requires GLib; one probe supplies both.
    pkg_config::Config::new()
        .probe("gobject-2.0")
        .map(|lib| lib.include_paths)
        .unwrap_or_default()
}

fn find_libvips_msvc(options: &BuildOptions) -> ProbeResult {
    let mut config = windows::config(options.static_linking);
    if let Ok(root) = vcpkg::find_vcpkg_root(&config) {
        for path in [
            root.join("installed/vcpkg/status"),
            root.join("installed/vcpkg/updates"),
        ] {
            println!("cargo:rerun-if-changed={}", path.display());
        }
    }
    match windows::probe(&mut config) {
        Ok(lib) => {
            // vcpkg already resolved the selected triplet. Do not guess another
            // installation's headers or merge in an unrelated vendor version.
            let version = options.version.clone().or_else(|| {
                lib.include_paths.iter().find_map(|include| {
                    let header = include.join("vips/version.h");
                    if header.is_file() {
                        println!("cargo:rerun-if-changed={}", header.display());
                        fs::read_to_string(header)
                            .ok()
                            .and_then(|text| config::header_version(&text))
                    } else {
                        None
                    }
                })
            });
            Some(LibraryInfo {
                include_paths: windows::include_paths(lib),
                defines: Vec::new(),
                version,
            })
        }
        Err(err) => {
            println!(
                "cargo:warning=vips-sys: vcpkg could not find the libvips port ({err}); \
                 install `libvips` for the selected triplet; dynamic builds also need VCPKGRS_DYNAMIC=1. Set VCPKG_ROOT or LIBVIPS_LIB_DIR if needed"
            );
            // A header directory alone is not a linkable Windows library.
            None
        }
    }
}

fn find_libvips(options: &BuildOptions) -> ProbeResult {
    // An explicit installation is the common fast path for every target.
    if let Some(lib_dir) = &options.lib_dir {
        // Keep the installation's complete native dependency metadata when
        // available, including GObject symbols used by the safe wrapper.
        if !options.msvc
            && let Some(info) = unix::explicit(options, lib_dir)
        {
            return Some(info);
        }
        println!("cargo:rustc-link-search=native={}", lib_dir.display());
        emit_link(if options.static_linking {
            "static"
        } else {
            "dylib"
        });
        let mut include_paths = options
            .include_dir
            .clone()
            .map(|p| vec![p])
            .unwrap_or_default();
        if options.generate_bindings && include_paths.is_empty() {
            include_paths = vendor_include_paths(options).unwrap_or_default();
        }
        // The safe wrapper also calls GObject helpers directly. Their link
        // metadata is required even when bindings are pre-generated.
        if !options.msvc {
            include_paths = merge_includes(include_paths, glib_include_paths());
        }
        return Some(LibraryInfo {
            include_paths,
            defines: Vec::new(),
            version: options.version.clone(),
        });
    }
    if options.msvc {
        find_libvips_msvc(options)
    } else {
        unix::find(options)
    }
}

/// Generate bindings with bindgen (feature `bindgen` only).
/// Default builds use `src/bindings/prebuilt.rs` and skip this path entirely.
#[cfg(feature = "bindgen")]
fn generate_bindings(include_paths: &[PathBuf], defines: &Defines) {
    println!("cargo:rerun-if-changed=wrapper.h");
    println!("cargo:rerun-if-env-changed=LIBVIPS_NO_BINDGEN");
    println!("cargo:rerun-if-env-changed=LIBVIPS_LIB_DIR");
    println!("cargo:rerun-if-env-changed=LIBVIPS_INCLUDE_DIR");
    println!("cargo:rerun-if-env-changed=LIBVIPS_STATIC");
    println!("cargo:rerun-if-env-changed=LIBVIPS_NO_VENDOR");
    println!("cargo:rerun-if-env-changed=VCPKG_ROOT");

    let out = PathBuf::from(env::var_os("OUT_DIR").expect("OUT_DIR"));
    let binding_rs = out.join("binding.rs");
    if env::var_os("LIBVIPS_NO_BINDGEN").is_some() {
        fs::copy("src/bindings/prebuilt.rs", &binding_rs).expect("copy pregenerated bindings");
        return;
    }

    // CargoCallbacks registers every included header. Let Cargo track those
    // dependencies rather than skipping a rebuild with a partial fingerprint.
    let mut builder = bindgen::Builder::default()
        .header("wrapper.h")
        .parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
        // Allowlist keeps clang work and generated Rust small: only the libvips
        // surface plus the few GObject helpers the high-level crate needs.
        .allowlist_function("vips_.*")
        .allowlist_type("Vips.*")
        .allowlist_var("VIPS_.*")
        .allowlist_function("g_object_unref")
        .allowlist_function("g_object_ref")
        .allowlist_function("g_free")
        .allowlist_function("g_signal_connect_data")
        .allowlist_type("GConnectFlags")
        .use_core()
        .ctypes_prefix("core::ffi")
        // Only allowlisted enums are rustified; keep GConnectFlags as an enum
        // because high-level crates match on G_CONNECT_* variants.
        .rustified_enum(".*")
        .layout_tests(false)
        .generate_comments(false)
        .blocklist_type("max_align_t")
        .blocklist_item("FP_NAN")
        .blocklist_item("FP_INFINITE")
        .blocklist_item("FP_ZERO")
        .blocklist_item("FP_SUBNORMAL")
        .blocklist_item("FP_NORMAL");

    for p in include_paths {
        builder = builder.clang_arg(format!("-I{}", p.display()));
    }
    for (name, val) in defines {
        match val {
            Some(v) => builder = builder.clang_arg(format!("-D{}={}", name, v)),
            None => builder = builder.clang_arg(format!("-D{}", name)),
        }
    }

    let bindings = builder
        .generate()
        .expect("Unable to generate libvips bindings");

    // Normalize in memory and write once; unchanged contents retain their mtime.
    {
        let body = bindings.to_string();
        let header = concat!(
            "/* automatically generated by rust-bindgen (vips-sys)\n",
            " *\n",
            " * Pregenerated FFI declarations for the public libvips C API.\n",
            " * Part of vips-sys (MIT). The libvips library itself is LGPL-2.1;\n",
            " * linking/distributing against it requires LGPL-2.1 compliance.\n",
            " * See README “License”.\n",
            " */\n\n"
        );
        // Drop bindgen's own short banner if present, keep one notice.
        let body = body
            .strip_prefix("/* automatically generated by rust-bindgen")
            .and_then(|s| s.find("*/").map(|i| &s[i + 2..]))
            .map(|s| s.trim_start_matches('\n'))
            .unwrap_or(&body);
        // Normalize after generation so bindgen can still derive Copy/Clone
        // using the known scalar typedefs. GLib sizes are pointer-sized on
        // LLP64 Windows as well as Unix; C long does not have that guarantee.
        let mut normalized = String::with_capacity(body.len());
        for line in body.lines() {
            normalized.push_str(if line.starts_with("pub type gsize = ") {
                "pub type gsize = usize;"
            } else if line.starts_with("pub type gssize = ") {
                "pub type gssize = isize;"
            } else {
                line
            });
            normalized.push('\n');
        }
        let output = format!("{header}{normalized}");
        if fs::read_to_string(&binding_rs).ok().as_deref() != Some(output.as_str()) {
            fs::write(&binding_rs, output).expect("Couldn't write bindings");
        }
    }

    // Convenience for maintainers: print where to copy when refreshing prebuilt.rs
    println!(
        "cargo:warning=vips-sys: bindings ready at {} — use scripts/refresh-prebuilt.py to refresh defaults",
        binding_rs.display()
    );
}

fn apply_version_cfg(version: &str) {
    println!("cargo:rustc-env=LIBVIPS_VERSION={}", version);
    let mut parts = version.split('.');
    if let (Some(major), Some(minor)) = (parts.next(), parts.next())
        && let (Ok(major), Ok(minor)) = (major.parse::<u32>(), minor.parse::<u32>())
    {
        if cfg!(feature = "v8_18") && (major, minor) < (8, 18) {
            panic!("vips-sys: feature v8_18 requires libvips >= 8.18, found {version}");
        }
        if major > 8 || (major == 8 && minor >= 18) {
            println!("cargo:rustc-cfg=vips_8_18");
        }
        if major > 8 || (major == 8 && minor >= 17) {
            println!("cargo:rustc-cfg=vips_8_17");
        }
        if major > 8 || (major == 8 && minor >= 16) {
            println!("cargo:rustc-cfg=vips_8_16");
        }
    }
}

fn main() {
    println!("cargo:rerun-if-changed=build.rs");
    println!("cargo:rerun-if-changed=build_support/windows.rs");
    println!("cargo:rerun-if-changed=build_support/config.rs");
    println!("cargo:rerun-if-changed=build_support/unix.rs");
    for variable in [
        "MESON_PATH",
        "NINJA_PATH",
        "CXXSTDLIB",
        "VCPKGRS_TRIPLET",
        "VCPKGRS_DYNAMIC",
        "VCPKGRS_DISABLE",
        "NO_VCPKG",
        "VCPKGRS_NO_LIBVIPS",
        "LIBVIPS_NO_VCPKG",
    ] {
        println!("cargo:rerun-if-env-changed={variable}");
    }
    println!("cargo:rerun-if-env-changed=LIBVIPS_NO_VENDOR");
    println!("cargo:rerun-if-env-changed=LIBVIPS_LIB_DIR");
    println!("cargo:rerun-if-env-changed=LIBVIPS_INCLUDE_DIR");
    println!("cargo:rerun-if-env-changed=LIBVIPS_STATIC");
    println!("cargo:rerun-if-env-changed=PKG_CONFIG_PATH");
    println!("cargo:rerun-if-env-changed=VCPKG_ROOT");
    println!("cargo:rerun-if-env-changed=VCPKG_DEFAULT_TRIPLET");
    println!("cargo:rerun-if-env-changed=LIBVIPS_VERSION");
    println!("cargo:rerun-if-changed=stub/vips_stub.c");

    for cfg in ["vips_8_16", "vips_8_17", "vips_8_18"] {
        println!("cargo:rustc-check-cfg=cfg({cfg})");
    }
    println!("cargo:rerun-if-changed=src/bindings/prebuilt.rs");
    let options = BuildOptions::from_env();
    let found = find_libvips(&options);

    let LibraryInfo {
        include_paths,
        defines,
        version,
    } = match found {
        Some(library) => library,
        None => {
            // Prefer a real library whenever find_libvips succeeds; only fall
            // through here when nothing is installed.
            #[cfg(feature = "stub")]
            {
                println!(
                    "cargo:warning=vips-sys: no libvips library; linking stub/vips_stub.c \
                     (feature `stub`). Suitable for unit tests only — not for production."
                );
                cc::Build::new()
                    .file("stub/vips_stub.c")
                    .warnings(false)
                    .compile("vips");
            }
            #[cfg(not(feature = "stub"))]
            {
                #[cfg(not(feature = "bindgen"))]
                {
                    println!(
                        "cargo:warning=vips-sys: libvips not found at build time. \
                         Using pregenerated bindings; install libvips before linking binaries \
                         (pkg-config/vcpkg or LIBVIPS_LIB_DIR), or enable feature `stub` for tests."
                    );
                    emit_link(if options.static_linking {
                        "static"
                    } else {
                        "dylib"
                    });
                }
            }

            #[cfg(feature = "bindgen")]
            {
                if env::var_os("LIBVIPS_NO_BINDGEN").is_some() {
                    // This mode copies prebuilt.rs and needs no headers.
                    LibraryInfo::default()
                } else {
                    // Headers for bindgen: vendor tree or nothing.
                    let mut inc = vendor_include_paths(&options).unwrap_or_default();
                    if inc.is_empty() {
                        panic!(
                            "vips-sys: libvips headers not found (feature `bindgen`).\n\
                         - Unix/macOS: install libvips-dev and pkg-config\n\
                         - Windows MSVC: `vcpkg install libvips:x64-windows` (set VCPKG_ROOT)\n\
                         - Or set LIBVIPS_LIB_DIR / LIBVIPS_INCLUDE_DIR\n\
                         - Or `git submodule update --init` for vendor/libvips"
                        );
                    }
                    inc = merge_includes(inc, glib_include_paths());
                    LibraryInfo {
                        include_paths: inc,
                        ..LibraryInfo::default()
                    }
                }
            }
            #[cfg(not(feature = "bindgen"))]
            {
                LibraryInfo::default()
            }
        }
    };

    if let Some(v) = version.as_deref() {
        apply_version_cfg(v);
    }

    if !include_paths.is_empty() {
        let joined = env::join_paths(&include_paths).expect("valid include paths");
        println!("cargo:include={}", joined.to_string_lossy());
    }

    // Default builds compile `src/bindings/prebuilt.rs` — no clang required.
    #[cfg(feature = "bindgen")]
    generate_bindings(&include_paths, &defines);

    // Silence unused-parameter warnings when bindgen is disabled.
    #[cfg(not(feature = "bindgen"))]
    let _ = (&include_paths, &defines);
}