dear-implot-sys 0.8.0

Low-level FFI bindings for ImPlot via cimplot (C API)
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
use std::{
    env,
    path::{Path, PathBuf},
};

#[derive(Clone, Debug)]
struct BuildConfig {
    manifest_dir: PathBuf,
    out_dir: PathBuf,
    target_os: String,
    target_env: String,
    target_arch: String,
    docs_rs: bool,
}

impl BuildConfig {
    fn new() -> Self {
        Self {
            manifest_dir: PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()),
            out_dir: PathBuf::from(env::var("OUT_DIR").unwrap()),
            target_os: env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(),
            target_env: env::var("CARGO_CFG_TARGET_ENV").unwrap_or_default(),
            target_arch: env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default(),
            docs_rs: env::var("DOCS_RS").is_ok(),
        }
    }
    fn is_msvc(&self) -> bool {
        self.target_env == "msvc"
    }
    fn is_windows(&self) -> bool {
        self.target_os == "windows"
    }
    fn use_static_crt(&self) -> bool {
        self.is_msvc()
            && self.is_windows()
            && env::var("CARGO_CFG_TARGET_FEATURE")
                .unwrap_or_default()
                .split(',')
                .any(|f| f == "crt-static")
    }
}

fn use_cmake_requested() -> bool {
    matches!(env::var("IMPLOT_SYS_USE_CMAKE"), Ok(v) if !v.is_empty())
}

fn resolve_imgui_includes(cfg: &BuildConfig) -> (PathBuf, PathBuf) {
    // Prefer paths exported by dear-imgui-sys build script (prefix comes from links = "dear-imgui")
    let imgui_src = env::var_os("DEP_DEAR_IMGUI_IMGUI_INCLUDE_PATH")
        .or_else(|| env::var_os("DEP_DEAR_IMGUI_THIRD_PARTY"))
        .map(PathBuf::from)
        .unwrap_or_else(|| cfg.manifest_dir.join("../../dear-imgui-sys/imgui"));
    let cimgui_root = env::var_os("DEP_DEAR_IMGUI_CIMGUI_INCLUDE_PATH")
        .map(PathBuf::from)
        .unwrap_or_else(|| {
            cfg.manifest_dir
                .join("../../dear-imgui-sys/third-party/cimgui")
        });
    (imgui_src, cimgui_root)
}

fn generate_bindings(cfg: &BuildConfig, cimplot_root: &Path, imgui_src: &Path, cimgui_root: &Path) {
    // For wasm32 targets, we rely on pregenerated import-style bindings that
    // import symbols from the shared imgui-sys-v0 provider instead of running
    // bindgen in the build script (which requires a native C/C++ sysroot).
    if cfg.target_arch == "wasm32" {
        if !cfg!(feature = "wasm") {
            panic!(
                "dear-implot-sys: building for wasm32 requires the `wasm` feature.\n\
                 Enable it in your Cargo.toml: features = [\"wasm\"]"
            );
        }
        if use_pregenerated_wasm_bindings(&cfg.out_dir) {
            println!("cargo:warning=Using pregenerated wasm bindings for dear-implot-sys");
            return;
        }
        panic!(
            "dear-implot-sys: wasm32 target detected but src/wasm_bindings_pregenerated.rs not found.\n\
             Run: cargo run -p xtask -- wasm-bindgen-implot imgui-sys-v0"
        );
    }

    let bindings = bindgen::Builder::default()
        .header(cimplot_root.join("cimplot.h").to_string_lossy())
        .parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
        .allowlist_function("ImPlot.*")
        .allowlist_type("ImPlot.*")
        .allowlist_type("ImWchar32")
        .allowlist_var("ImPlot.*")
        .allowlist_var("IMPLOT_.*")
        .blocklist_type("ImVec2")
        .blocklist_type("ImVec4")
        .blocklist_type("ImGuiCond")
        .blocklist_type("ImTextureID")
        .blocklist_type("ImGuiContext")
        .blocklist_type("ImDrawList")
        .blocklist_type("ImGuiMouseButton")
        .blocklist_type("ImGuiDragDropFlags")
        .blocklist_type("ImGuiIO")
        .blocklist_type("ImFontAtlas")
        .blocklist_type("ImDrawData")
        .blocklist_type("ImGuiStyle")
        .blocklist_type("ImGuiKeyModFlags")
        .derive_default(true)
        .derive_debug(true)
        .derive_copy(true)
        .derive_eq(true)
        .derive_partialeq(true)
        .derive_hash(true)
        .prepend_enum_name(false)
        .layout_tests(false)
        .clang_arg(format!("-I{}", imgui_src.display()))
        .clang_arg(format!("-I{}", cimgui_root.display()))
        .clang_arg(format!("-I{}", cimplot_root.display()))
        .clang_arg(format!("-I{}", cimplot_root.join("implot").display()))
        .clang_arg("-DIMGUI_USE_WCHAR32")
        .clang_arg("-DCIMGUI_DEFINE_ENUMS_AND_STRUCTS")
        .clang_arg("-DCIMGUI_VARGS0")
        .clang_arg("-x")
        .clang_arg("c++")
        .clang_arg("-std=c++17")
        .generate()
        .expect("Unable to generate bindings");
    let out = cfg.out_dir.join("bindings.rs");
    bindings
        .write_to_file(&out)
        .expect("Couldn't write bindings!");
    sanitize_bindings_file(&out);
}

fn try_link_prebuilt_all(cfg: &BuildConfig) -> bool {
    let target_env = &cfg.target_env;
    if let Ok(dir) = env::var("IMPLOT_SYS_LIB_DIR") {
        if try_link_prebuilt(PathBuf::from(dir), target_env) {
            return true;
        }
        println!(
            "cargo:warning=IMPLOT_SYS_LIB_DIR set but no library found; falling back to build"
        );
    }
    if let Ok(url) = env::var("IMPLOT_SYS_PREBUILT_URL") {
        let cache_root = prebuilt_cache_root(cfg);
        if let Ok(dir) = try_download_prebuilt(&cache_root, &url, target_env) {
            if try_link_prebuilt(dir.clone(), target_env) {
                return true;
            }
            println!(
                "cargo:warning=Downloaded prebuilt library but failed to link from {}",
                dir.display()
            );
        }
    } else {
        let allow_feature = cfg!(feature = "prebuilt");
        let allow_env = matches!(
            env::var("IMPLOT_SYS_USE_PREBUILT").ok().as_deref(),
            Some("1") | Some("true") | Some("yes")
        );
        let allow_auto_prebuilt = allow_feature || allow_env;
        if allow_auto_prebuilt {
            let source = match (allow_feature, allow_env) {
                (true, true) => "feature+env",
                (true, false) => "feature",
                (false, true) => "env",
                _ => "",
            };
            let (owner, repo) = build_support::release_owner_repo();
            println!(
                "cargo:warning=auto-prebuilt enabled (dear-implot-sys): source={}, repo={}/{}",
                source, owner, repo
            );
            if let Some(dir) = try_download_prebuilt_from_release(cfg)
                && try_link_prebuilt(dir.clone(), target_env)
            {
                return true;
            }
        }
    }
    false
}

fn build_with_cc(cfg: &BuildConfig, cimplot_root: &Path, imgui_src: &Path, cimgui_root: &Path) {
    let cimplot_cpp = patched_cimplot_cpp(cfg, cimplot_root);

    let mut build = cc::Build::new();
    build.cpp(true).std("c++17");

    // MSVC flags align with dear-imgui-sys
    if cfg.is_msvc() && cfg.is_windows() {
        build.flag("/EHsc");
        let use_static = cfg.use_static_crt();
        build.static_crt(use_static);
        if use_static {
            build.flag("/MT");
        } else {
            build.flag("/MD");
        }
        let profile = env::var("PROFILE").unwrap_or_else(|_| "release".to_string());
        if profile == "debug" {
            build.debug(true).opt_level(0);
        } else {
            build.debug(false).opt_level(2);
        }
        build.flag("/D_ITERATOR_DEBUG_LEVEL=0");
    }

    // Inherit dear-imgui defines
    for (k, v) in env::vars() {
        let suffix = k
            .strip_prefix("DEP_DEAR_IMGUI_SYS_DEFINE_")
            .or_else(|| k.strip_prefix("DEP_DEAR_IMGUI_DEFINE_"));
        if let Some(suffix) = suffix {
            build.define(suffix, v.as_str());
        }
    }

    // Includes and defines
    build.define("IMGUI_DEFINE_MATH_OPERATORS", Some("1"));
    build.define("IMGUI_USE_WCHAR32", None);
    build.define("CIMGUI_VARGS0", None);
    build.include(imgui_src);
    build.include(cimgui_root);
    build.include(cimplot_root);
    build.include(cimplot_root.join("implot"));

    // Sources
    build.file(cimplot_cpp);
    build.file(cimplot_root.join("implot/implot.cpp"));
    build.file(cimplot_root.join("implot/implot_items.cpp"));
    build.file(cimplot_root.join("implot/implot_demo.cpp"));

    build.compile("dear_implot");
}

fn patched_cimplot_cpp(cfg: &BuildConfig, cimplot_root: &Path) -> PathBuf {
    // NOTE: This intentionally does not modify the git submodule on disk.
    //
    // cimplot's generated C++ wrapper currently contains an out-of-bounds array access:
    // `dest.FormatSpec[16] = src.FormatSpec[16];` for `char FormatSpec[16]`.
    // We compile a patched copy from OUT_DIR to avoid shipping C++ UB, while keeping the submodule
    // clean for upstream updates.
    let src = cimplot_root.join("cimplot.cpp");
    let Ok(mut text) = std::fs::read_to_string(&src) else {
        return src;
    };

    let needle = "dest.FormatSpec[16] = src.FormatSpec[16];";
    if !text.contains(needle) {
        return src;
    }

    if !text.contains("#include <string.h>") {
        if text.contains("#include \"cimplot.h\"") {
            text = text.replace(
                "#include \"cimplot.h\"\r\n",
                "#include \"cimplot.h\"\r\n#include <string.h>\r\n",
            );
            text = text.replace(
                "#include \"cimplot.h\"\n",
                "#include \"cimplot.h\"\n#include <string.h>\n",
            );
        } else {
            text = format!("#include <string.h>\n{text}");
        }
    }

    text = text.replace(
        needle,
        "memcpy(dest.FormatSpec, src.FormatSpec, sizeof(dest.FormatSpec));",
    );

    let out = cfg.out_dir.join("cimplot_patched.cpp");
    if std::fs::write(&out, text).is_ok() {
        println!(
            "cargo:warning=Using patched cimplot.cpp from {} (fixes known OOB FormatSpec copy; original submodule is unchanged)",
            out.display()
        );
        out
    } else {
        src
    }
}

fn main() {
    let cfg = BuildConfig::new();

    // Rerun hints
    println!("cargo:rerun-if-changed=build.rs");
    println!("cargo:rerun-if-changed=third-party/cimplot/cimplot.h");
    println!("cargo:rerun-if-changed=third-party/cimplot/cimplot.cpp");
    println!("cargo:rerun-if-changed=third-party/cimplot/implot/implot.h");
    println!("cargo:rerun-if-changed=third-party/cimplot/implot/implot.cpp");
    println!("cargo:rerun-if-changed=third-party/cimplot/implot/implot_items.cpp");
    println!("cargo:rerun-if-changed=../../dear-imgui-sys");
    println!("cargo:rerun-if-env-changed=IMPLOT_SYS_LIB_DIR");
    println!("cargo:rerun-if-env-changed=IMPLOT_SYS_SKIP_CC");
    println!("cargo:rerun-if-env-changed=IMPLOT_SYS_PREBUILT_URL");
    println!("cargo:rerun-if-env-changed=IMPLOT_SYS_FORCE_BUILD");
    println!("cargo:rerun-if-env-changed=IMPLOT_SYS_USE_CMAKE");

    let (imgui_src, cimgui_root) = resolve_imgui_includes(&cfg);
    let cimplot_root = cfg.manifest_dir.join("third-party/cimplot");

    // docs.rs: generate or use pregenerated bindings, skip native/source checks
    if cfg.docs_rs {
        docsrs_build(&cfg, &cimplot_root, &imgui_src, &cimgui_root);
        return;
    }

    // Maintainer workflow: regenerate bindings via bindgen without requiring native compilation.
    if build_support::parse_bool_env("DEAR_IMGUI_RS_REGEN_BINDINGS") {
        if !imgui_src.exists() {
            panic!(
                "ImGui source not found at {:?}. Did you forget to initialize git submodules?",
                imgui_src
            );
        }
        if !cimplot_root.exists() {
            panic!(
                "cimplot source not found at {:?}. Did you forget to initialize git submodules?",
                cimplot_root
            );
        }
        generate_bindings(&cfg, &cimplot_root, &imgui_src, &cimgui_root);
        return;
    }

    // When explicitly skipping native compilation, also skip bindgen and rely on
    // pregenerated bindings. This keeps `cargo check --target ...` working for
    // cross targets without requiring a C sysroot for bindgen/clang.
    if env::var("IMPLOT_SYS_SKIP_CC").is_ok() {
        let ok = if cfg.target_arch == "wasm32" {
            use_pregenerated_wasm_bindings(&cfg.out_dir)
        } else {
            use_pregenerated_bindings(&cfg.out_dir)
        };
        if !ok {
            panic!(
                "IMPLOT_SYS_SKIP_CC is set but no pregenerated bindings were found. \
                 Please ensure src/bindings_pregenerated.rs exists, or unset IMPLOT_SYS_SKIP_CC."
            );
        }

        // Optionally link prebuilt if available; otherwise type-checking still works.
        let _ = try_link_prebuilt_all(&cfg);
        return;
    }

    if !imgui_src.exists() {
        panic!(
            "ImGui source not found at {:?}. Did you forget to initialize git submodules?",
            imgui_src
        );
    }
    if !cimplot_root.exists() {
        panic!(
            "cimplot source not found at {:?}. Did you forget to initialize git submodules?",
            cimplot_root
        );
    }

    // Generate bindings (native/source build path)
    generate_bindings(&cfg, &cimplot_root, &imgui_src, &cimgui_root);

    // Features: build-from-source forces source build; prebuilt is opt-in
    let force_build =
        cfg!(feature = "build-from-source") || env::var("IMPLOT_SYS_FORCE_BUILD").is_ok();
    let linked_prebuilt = if force_build {
        false
    } else {
        try_link_prebuilt_all(&cfg)
    };
    if cfg.target_arch != "wasm32" {
        if !cfg.docs_rs
            && (force_build || (!linked_prebuilt && env::var("IMPLOT_SYS_SKIP_CC").is_err()))
        {
            if use_cmake_requested() && build_with_cmake(&cfg, &cimplot_root) {
                // built via CMake
            } else {
                build_with_cc(&cfg, &cimplot_root, &imgui_src, &cimgui_root);
            }
        }
    } else {
        println!(
            "cargo:warning=Skipping native ImPlot build for wasm32 (using import-style wasm bindings)"
        );
    }
}

fn docsrs_build(cfg: &BuildConfig, cimplot_root: &Path, imgui_src: &Path, cimgui_root: &Path) {
    println!("cargo:warning=DOCS_RS detected: generating bindings, skipping native build");
    println!("cargo:rustc-cfg=docsrs");

    if use_pregenerated_bindings(&cfg.out_dir) {
        return;
    }

    // Fallback: try to generate bindings from headers if available
    if !imgui_src.exists() || !cimgui_root.exists() || !cimplot_root.exists() {
        panic!(
            "DOCS_RS build: Required headers not found and no pregenerated bindings present.\n\
             Please add src/bindings_pregenerated.rs (full bindgen output) to enable docs.rs builds.\n\
             Run: cargo build -p dear-implot-sys && cp target/debug/build/dear-implot-sys-*/out/bindings.rs extensions/dear-implot-sys/src/bindings_pregenerated.rs"
        );
    }

    generate_bindings(cfg, cimplot_root, imgui_src, cimgui_root);
    println!("cargo:IMGUI_INCLUDE_PATH={}", imgui_src.display());
    println!("cargo:CIMGUI_INCLUDE_PATH={}", cimgui_root.display());
}

fn use_pregenerated_bindings(out_dir: &Path) -> bool {
    if build_support::parse_bool_env("DEAR_IMGUI_RS_REGEN_BINDINGS") {
        return false;
    }

    let preg = Path::new("src").join("bindings_pregenerated.rs");
    if preg.exists() {
        match std::fs::read_to_string(&preg).and_then(|content| {
            let sanitized = sanitize_bindings_string(&content);
            std::fs::write(out_dir.join("bindings.rs"), sanitized)
        }) {
            Ok(()) => {
                println!(
                    "cargo:warning=Using pregenerated bindings: {}",
                    preg.display()
                );
                true
            }
            Err(e) => {
                println!("cargo:warning=Failed to write pregenerated bindings: {}", e);
                false
            }
        }
    } else {
        false
    }
}

fn use_pregenerated_wasm_bindings(out_dir: &Path) -> bool {
    if build_support::parse_bool_env("DEAR_IMGUI_RS_REGEN_BINDINGS") {
        return false;
    }

    let preg = Path::new("src").join("wasm_bindings_pregenerated.rs");
    if preg.exists() {
        match std::fs::read_to_string(&preg).and_then(|content| {
            let sanitized = sanitize_bindings_string(&content);
            std::fs::write(out_dir.join("bindings.rs"), sanitized)
        }) {
            Ok(()) => {
                println!(
                    "cargo:warning=Using pregenerated wasm bindings: {}",
                    preg.display()
                );
                true
            }
            Err(e) => {
                println!(
                    "cargo:warning=Failed to write pregenerated wasm bindings: {}",
                    e
                );
                false
            }
        }
    } else {
        false
    }
}

fn sanitize_bindings_file(path: &Path) {
    if let Ok(content) = std::fs::read_to_string(path) {
        let sanitized = sanitize_bindings_string(&content);
        let _ = std::fs::write(path, sanitized);
    }
}

fn sanitize_bindings_string(content: &str) -> String {
    let mut out = String::with_capacity(content.len());
    let mut skip_next_blank = false;
    for line in content.lines() {
        let trimmed = line.trim_start();
        if trimmed.starts_with("#![") {
            skip_next_blank = true;
            continue;
        }
        if skip_next_blank {
            if trimmed.is_empty() {
                continue;
            }
            skip_next_blank = false;
        }
        out.push_str(line);
        out.push('\n');
    }
    out
}

fn build_with_cmake(cfg: &BuildConfig, cimplot_root: &Path) -> bool {
    // If the known cimplot OOB wrapper bug is present, prefer the `cc` build path where we can
    // compile a patched copy from OUT_DIR without modifying the submodule.
    if cimplot_needs_patch(cimplot_root) {
        println!(
            "cargo:warning=Skipping CMake build for cimplot because a known OOB wrapper bug was detected; falling back to cc build with a patched copy"
        );
        return false;
    }

    let cmake_lists = cimplot_root.join("CMakeLists.txt");
    if !cmake_lists.exists() {
        return false;
    }
    println!("cargo:warning=Building cimplot with CMake");
    let mut c = cmake::Config::new(cimplot_root);
    c.define("IMGUI_STATIC", "ON");
    c.cxxflag("-DCIMGUI_VARGS0");
    let profile = env::var("PROFILE").unwrap_or_else(|_| "release".into());
    let cmake_profile = if cfg.is_msvc() && cfg.is_windows() && profile == "debug" {
        "RelWithDebInfo"
    } else if profile == "debug" {
        "Debug"
    } else {
        "Release"
    };
    c.profile(cmake_profile);
    if cfg.is_msvc() && cfg.is_windows() {
        let tf = env::var("CARGO_CFG_TARGET_FEATURE").unwrap_or_default();
        let use_static = tf.split(',').any(|f| f == "crt-static");
        let msvc_runtime = if use_static {
            "MultiThreaded"
        } else {
            "MultiThreadedDLL"
        };
        c.define("CMAKE_MSVC_RUNTIME_LIBRARY", msvc_runtime);
    }
    let dst = c.build();
    let candidates = [
        dst.join("lib"),
        dst.join("build"),
        dst.clone(),
        dst.join("build").join("Release"),
        dst.join("build").join("RelWithDebInfo"),
        dst.join("build").join("Debug"),
        dst.join("Release"),
        dst.join("RelWithDebInfo"),
        dst.join("Debug"),
    ];
    let mut found = false;
    for lib_dir in &candidates {
        if lib_dir.exists() {
            println!("cargo:rustc-link-search=native={}", lib_dir.display());
            found = true;
        }
    }
    if !found {
        println!("cargo:warning=Could not locate CMake lib output dir; linking may fail");
    }
    println!("cargo:rustc-link-lib=static=cimplot");
    true
}

fn cimplot_needs_patch(cimplot_root: &Path) -> bool {
    let src = cimplot_root.join("cimplot.cpp");
    let Ok(text) = std::fs::read_to_string(&src) else {
        return false;
    };
    text.contains("dest.FormatSpec[16] = src.FormatSpec[16];")
}

fn expected_lib_name(target_env: &str) -> &'static str {
    if target_env == "msvc" {
        "dear_implot.lib"
    } else {
        "libdear_implot.a"
    }
}

fn prebuilt_manifest_has_feature(dir: &Path, feature: &str) -> bool {
    let mut candidates = Vec::with_capacity(2);
    candidates.push(dir.join("manifest.txt"));
    if let Some(parent) = dir.parent() {
        candidates.push(parent.join("manifest.txt"));
    }
    let Some(s) = candidates
        .into_iter()
        .find_map(|p| std::fs::read_to_string(&p).ok())
    else {
        return false;
    };
    let feature = feature.trim().to_ascii_lowercase();
    for line in s.lines() {
        if let Some(rest) = line.strip_prefix("features=") {
            return rest
                .split(',')
                .map(|f| f.trim().to_ascii_lowercase())
                .any(|f| f == feature);
        }
    }
    false
}

fn try_link_prebuilt(dir: PathBuf, target_env: &str) -> bool {
    let lib_name = expected_lib_name(target_env);
    let lib_path = dir.join(lib_name);
    if !lib_path.exists() {
        println!(
            "cargo:warning=prebuilt dear_implot not found at {}",
            lib_path.display()
        );
        return false;
    }
    if !prebuilt_manifest_has_feature(&dir, "wchar32") {
        return false;
    }
    println!("cargo:rustc-link-search=native={}", dir.display());
    println!("cargo:rustc-link-lib=static=dear_implot");
    true
}

// keep the existing expected_lib_name returning &'static str defined above

fn try_download_prebuilt(
    cache_root: &Path,
    url: &str,
    target_env: &str,
) -> Result<PathBuf, String> {
    let lib_name = expected_lib_name(target_env);
    build_support::download_prebuilt(cache_root, url, lib_name, target_env)
}

fn try_download_prebuilt_from_release(cfg: &BuildConfig) -> Option<PathBuf> {
    if build_support::is_offline() {
        return None;
    }

    let version = env::var("CARGO_PKG_VERSION").unwrap_or_default();
    let link_type = "static";
    let crt = if cfg.is_windows() && cfg.is_msvc() {
        if cfg.use_static_crt() { "mt" } else { "md" }
    } else {
        ""
    };
    let target = env::var("TARGET").unwrap_or_default();
    let archive_name =
        build_support::compose_archive_name("dear-implot", &version, &target, link_type, None, crt);
    let archive_name_no_crt =
        build_support::compose_archive_name("dear-implot", &version, &target, link_type, None, "");
    let tags = build_support::release_tags("dear-implot-sys", &version);
    if let Ok(pkg_dir) = env::var("IMPLOT_SYS_PACKAGE_DIR") {
        let pkg_dir = PathBuf::from(pkg_dir);
        for cand in [archive_name.clone(), archive_name_no_crt.clone()] {
            let archive_path = pkg_dir.join(&cand);
            if archive_path.exists() {
                let cache_root = prebuilt_cache_root(cfg);
                if let Ok(lib_dir) = build_support::extract_archive_to_cache(
                    &archive_path,
                    &cache_root,
                    expected_lib_name(&cfg.target_env),
                ) {
                    return Some(lib_dir);
                }
            }
        }
    }
    let cache_root = prebuilt_cache_root(cfg);
    let names = vec![archive_name, archive_name_no_crt];
    let urls = build_support::release_candidate_urls_env(&tags, &names);
    for url in urls {
        if let Ok(lib_dir) = try_download_prebuilt(&cache_root, &url, &cfg.target_env) {
            return Some(lib_dir);
        }
    }
    None
}

fn prebuilt_cache_root(cfg: &BuildConfig) -> PathBuf {
    build_support::prebuilt_cache_root_from_env_or_target(
        &cfg.manifest_dir,
        "IMPLOT_SYS_CACHE_DIR",
        "dear-implot-prebuilt",
    )
}

// (removed duplicate prebuilt_extract_dir_env/extract_archive_to_cache; using build_support equivalents)