libui-ng-sys 0.4.4

Bindings to libui-ng
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

#[macro_use]
extern crate build_cfg;

use std::{env, io, path::{Path, PathBuf}};

/// The error type returned by [`main`].
#[derive(Debug)]
pub enum Error {
    /// Failed to [sync](`dep::sync`) dependencies.
    SyncDep(anyhow::Error),
    /// Failed to [re-fetch](`repo::refetch_submodule`) a Git submodule.
    RefetchSubmodule(repo::Error),
    /// Failed to build *libui*.
    #[cfg(feature = "build")]
    BuildLibui(build::Error),
    /// Failed to include Windows resources.
    IncludeWinres(io::Error),
    /// Failed to generate bindings to *libui*.
    GenBindings(bindings::Error),
}

#[build_cfg_main]
fn main() -> Result<(), Error> {
    let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
    let libui_dir = out_dir.join("libui-ng");
    let meson_dir = out_dir.join("meson");
    let ninja_dir = out_dir.join("ninja");

    // Cargo will prevent this crate from being published if the build script modifies files outside
    // `$OUT_DIR` during its operation. To work around this for the purpose of building *libui*, we
    // copy all non-Rust build dependencies to `$OUT_DIR`.
    dep::sync("libui-ng", &libui_dir).map_err(Error::SyncDep)?;

    #[cfg(feature = "build")]
    if env::var("DOCS_RS").is_err() {
        let backend = build::Backend::default();

        dep::sync("meson", &meson_dir).map_err(Error::SyncDep)?;
        // Ninja only needs to be synced if it's selected as a build backend.
        if let build::Backend::Ninja = backend {
            // When downloading crates from *crates.io*, file execute permissions are *not*
            // respected. This is a problem for Ninja, which attempts to execute a file named
            // *inline.sh*. Re-fetching the submodule locally in entirety is a future-proof
            // solution to this issue, albeit slightly inefficient.
            repo::refetch_submodule("dep/ninja").map_err(Error::RefetchSubmodule)?;

            dep::sync("ninja", &ninja_dir).map_err(Error::SyncDep)?;
        }

        backend.build_libui(&libui_dir, &meson_dir, &ninja_dir).map_err(Error::BuildLibui)?;

        // Tell Cargo where to find the copy of *libui* that we just built.
        println!(
            "cargo:rustc-link-search={}",
            libui_dir.join("build/meson-out/").display(),
        );

        // Because we are building *libui* from scratch and placing it in `$OUT_DIR`, it makes sense
        // to link statically. Consequently, as static libraries *do not* contain information on the
        // shared objects that must be imported, we must tell Cargo (and, by extension, the dynamic
        // linker) which shared objects we need.
        import_dylibs();

        if build_cfg!(target_os = "windows") && cfg!(feature = "include-win-manifest") {
            include_winres().map_err(Error::IncludeWinres)?;
        }
    }

    // Instruct Cargo to link to *libui*.
    println!("cargo:rustc-link-lib={}=ui", link_kind());

    bindings::generate(&libui_dir, &out_dir).map_err(Error::GenBindings)?;

    // Recompile *libui-ng-sys* whenever this build script is modified.
    println!("cargo:rerun-if-changed=build.rs");

    Ok(())
}

#[cfg(feature = "build")]
fn import_dylibs() {
    macro_rules! dyn_link {
        ($($name:tt)*) => {
            $(
                println!("cargo:rustc-link-lib=dylib={}", stringify!($name));
            )*
        };
    }

    if build_cfg!(target_os = "linux") {
        // While unintuitive, we don't actually need to specify any shared objects here---the
        // `pkg_config` crate will do that automatically in [`bindings::ClangArgs::new_linux`].
    } else if build_cfg!(target_os = "windows") {
        // See `dep/libui-ng/windows/meson.build`.
        dyn_link! {
            comctl32
            comdlg32
            d2d1
            dwrite
            gdi32
            kernel32
            msimg32
            ole32
            oleacc
            oleaut32
            user32
            uuid
            uxtheme
            windowscodecs
        };
    }
}

fn include_winres() -> io::Result<()> {
    winres::WindowsResource::new()
        .set_manifest_file(&Path::new("res/libui.manifest").display().to_string())
        .compile()
}

fn link_kind() -> &'static str {
    if cfg!(feature = "build") {
        "static"
    } else {
        "dylib"
    }
}

mod repo {
    use std::{env, io};

    #[derive(Debug)]
    pub enum Error {
        ReadCurrentDir(io::Error),
        Open(git2::Error),
        ReadSubmodules(git2::Error),
        SubmoduleNotFound,
        UpdateSubmodule(git2::Error),
    }

    pub fn refetch_submodule(submodule_name: &str) -> Result<(), Error> {
        let repo_path = env::current_dir().map_err(Error::ReadCurrentDir)?;
        let repo = git2::Repository::open(repo_path).map_err(Error::Open)?;

        let mut submods = repo
            .submodules()
            .map_err(Error::ReadSubmodules)?;
        let submod = submods
            .iter_mut()
            .find(|submod| submod.name_bytes() == submodule_name.as_bytes())
            .ok_or(Error::SubmoduleNotFound)?;

        let mut update_opts = git2::SubmoduleUpdateOptions::new();
        update_opts.allow_fetch(true);
        submod.update(false, Some(&mut update_opts)).map_err(Error::UpdateSubmodule)?;

        Ok(())
    }
}

mod dep {
    use std::path::Path;

    pub fn sync(name: &str, to: &Path) -> Result<(), anyhow::Error> {
        rusync::Syncer::new(
            &Path::new("dep").join(name),
            to,
            rusync::SyncOptions {
                preserve_permissions: true,
            },
            Box::new(FakeProgressInfo),
        )
        .sync()
        .map(|_| ())
    }

    struct FakeProgressInfo;

    impl rusync::progress::ProgressInfo for FakeProgressInfo {}
}

mod build {
    use std::{env, fs, io, path::{Path, PathBuf}, process};

    /// The error type returned by [`Backend`] functions.
    #[derive(Debug)]
    pub enum Error {
        /// Failed to setup *libui*.
        SetupLibui(PythonError),
        /// Failed to build Ninja.
        BuildNinja(PythonError),
        /// Failed to compile *libui*.
        CompileLibui(PythonError),
        /// Failed to rename `libui.a` to `ui.lib`.
        ///
        /// This error *should* only occur when `$CARGO_CFG_TARGET_OS` is `windows`.
        RenameLibui(io::Error),
    }

    #[derive(Debug)]
    pub enum PythonError {
        /// Failed to run Python.
        RunPython(io::Error),
        /// The process run by Python failed.
        Python { out: process::Output },
    }

    pub enum Backend {
        Msvc,
        Ninja,
        Xcode,
    }

    impl Default for Backend {
        fn default() -> Self {
            if build_cfg!(feature = "build-with-msvc") {
                Self::Msvc
            } else if build_cfg!(feature = "build-with-xcode") {
                Self::Xcode
            // Ninja is last because it is the default option. This way, even if the user forgets to
            // pass `--no-default-options` and both `build-with-ninja` and, e.g., `build-with-msvc`
            // are enabled, only `build-with-msvc` will take effect, and the build backend will be
            // MSVC.
            } else if build_cfg!(feature = "build-with-ninja") {
                Self::Ninja
            } else {
                panic!(
                    "
                    The `build` feature is enabled but no `build-with-*` feature is not enabled. \
                    *libui-ng-sys* doesn't know which build backend to use. \
                    "
                );
            }
        }
    }

    impl Backend {
        /// Builds *libui*.
        pub fn build_libui(
            self,
            libui_dir: &Path,
            meson_dir: &Path,
            ninja_dir: &Path,
        ) -> Result<(), Error> {
            if Self::libui_path(libui_dir).exists() {
                // We'll give the benefit of the doubt that this is actually a complete, working
                // library.
                return Ok(());
            }

            if let Self::Ninja = self {
                // This must precede setting up *libui* as Meson requires Ninja even in the
                // configuration phase.
                Self::build_ninja(ninja_dir).map_err(Error::BuildNinja)?;
            }

            self.setup_libui(libui_dir, meson_dir, ninja_dir).map_err(Error::SetupLibui)?;
            self.compile_libui(libui_dir, meson_dir, ninja_dir)
                .map_err(Error::CompileLibui)?;
            self.rename_libui(libui_dir).map_err(Error::RenameLibui)?;

            Ok(())
        }

        fn libui_path(libui_dir: &Path) -> PathBuf {
            libui_dir.join("libui.a")
        }

        fn ninja_path(ninja_dir: &Path) -> PathBuf {
            let ext = env::consts::EXE_EXTENSION;
            ninja_dir.join("ninja").with_extension(ext)
        }

        fn run_python(
            f: impl Fn(&mut process::Command),
            ninja_dir: Option<&Path>,
        ) -> Result<(), PythonError> {
            let mut cmd = process::Command::new("python3");
            f(&mut cmd);

            if let Some(dir) = ninja_dir {
                cmd.env("NINJA", Self::ninja_path(dir));
            }

            let out = cmd.output().map_err(PythonError::RunPython)?;
            if out.status.success() {
                Ok(())
            } else {
                Err(PythonError::Python { out })
            }
        }

        /// Builds Ninja.
        fn build_ninja(ninja_dir: &Path) -> Result<(), PythonError> {
            if Self::ninja_path(ninja_dir).exists() {
                // We'll give the benefit of the doubt that this is actually a complete, working
                // binary.
                return Ok(());
            }

            Self::run_python(
                |cmd| {
                    cmd
                        .arg("configure.py")
                        .arg("--bootstrap")
                        .current_dir(ninja_dir);
                },
                None,
            )
        }

        /// Prepares *libui* to be built.
        fn setup_libui(
            &self,
            libui_dir: &Path,
            meson_dir: &Path,
            ninja_dir: &Path,
        ) -> Result<(), PythonError> {
            Self::run_python(
                |cmd| {
                    cmd
                        .arg(meson_dir.join("meson.py"))
                        .arg("setup")
                        .arg("--default-library=static")
                        .arg("--buildtype=release")
                        .arg(format!("--optimization={}", Self::optimization_level()))
                        .arg(format!("--backend={}", self.as_str()))
                        // It's OK that this option is hardcoded (which is MSVC-specific) for all
                        // backends; Meson will simply ignore it if MSVC isn't the selected backend.
                        .arg("-Db_vscrt=from_buildtype")
                        .arg(libui_dir.join("build"))
                        .arg(libui_dir);
                },
                Some(ninja_dir),
            )
        }

        // This may be used at some point.
        #[allow(dead_code)]
        fn is_debug() -> bool {
            !matches!(env::var("DEBUG").as_deref(), Ok("0" | "false"))
        }

        fn optimization_level() -> String {
            let level = env::var("OPT_LEVEL").expect("$OPT_LEVEL is unset");
            match level.as_str() {
                // Meson doesn't support "-Oz"; we'll try the next-closest option.
                "z" => String::from("s"),
                _ => level,
            }
        }

        fn as_str(&self) -> &'static str {
            match self {
                Self::Msvc => "vs",
                Self::Ninja => "ninja",
                Self::Xcode => "xcode",
            }
        }

        fn compile_libui(
            &self,
            libui_dir: &Path,
            meson_dir: &Path,
            ninja_dir: &Path,
        ) -> Result<(), PythonError> {
            Self::run_python(
                |cmd| {
                    cmd
                        .arg(meson_dir.join("meson.py"))
                        .arg("compile")
                        .arg(format!("-C={}", libui_dir.join("build").display()));
                },
                Some(ninja_dir),
            )
        }

        fn rename_libui(&self, libui_dir: &Path) -> Result<(), io::Error> {
            // Meson unconditionally names the library "libui.a", which prevents MSVC's `link.exe`
            // from finding it; we must manually rename it to "ui.lib".
            if let Self::Msvc = self {
                let build_dir = libui_dir.join("build/meson-out");
                fs::rename(Self::libui_path(libui_dir), build_dir.join("ui.lib"))?;
            }

            Ok(())
        }
    }
}

mod bindings {
    use std::{fmt, io, path::Path};

    /// The error type returned by binding functions.
    #[derive(Debug)]
    pub enum Error {
        /// Failed to generate bindings.
        Generate,
        /// Failed to write bindings to a file.
        WriteToFile(io::Error),
    }

    /// Generates bindings to *libui* and writes them to the given directory.
    pub fn generate(libui_dir: &Path, out_dir: &Path) -> Result<(), Error> {
        Header::main().generate(libui_dir, out_dir)?;
        Header::control_sigs().generate(libui_dir, out_dir)?;

        if build_cfg!(target_os = "macos") {
            Header::darwin().generate(libui_dir, out_dir)?;
        }
        if build_cfg!(target_os = "linux") {
            Header::unix().generate(libui_dir, out_dir)?;
        }
        if build_cfg!(target_os = "windows") {
            Header::windows().generate(libui_dir, out_dir)?;
        }

        Ok(())
    }

    struct Header {
        include_stmts: Vec<IncludeStmt>,
        filename: String,
        blocklists_main: bool,
    }

    impl Header {
        fn main() -> Self {
            Self {
                include_stmts: vec![
                    IncludeStmt {
                        kind: IncludeStmtKind::Local,
                        arg: "ui.h".to_string(),
                    },
                ],
                filename: "bindings".to_string(),
                blocklists_main: false,
            }
        }

        fn control_sigs() -> Self {
            Self {
                include_stmts: vec![
                    IncludeStmt {
                        kind: IncludeStmtKind::Local,
                        arg: "common/controlsigs.h".to_string(),
                    },
                ],
                filename: "bindings-control-sigs".to_string(),
                blocklists_main: true,
            }
        }

        fn darwin() -> Self {
            Self::ext("darwin", "Cocoa/Cocoa.h")
        }

        fn unix() -> Self {
            Self::ext("unix", "gtk/gtk.h")
        }

        fn windows() -> Self {
            Self::ext("windows", "windows.h")
        }

        fn ext(name: impl fmt::Display, dep: impl Into<String>) -> Self {
            Self {
                include_stmts: vec![
                    IncludeStmt {
                        kind: IncludeStmtKind::Local,
                        arg: "ui.h".to_string(),
                    },
                    IncludeStmt {
                        kind: IncludeStmtKind::System,
                        arg: dep.into(),
                    },
                    IncludeStmt {
                        kind: IncludeStmtKind::Local,
                        arg: format!("ui_{}.h", name),
                    },
                ],
                filename: format!("bindings-{}", name),
                blocklists_main: true,
            }
        }

        fn generate(self, libui_dir: &Path, out_dir: &Path) -> Result<(), Error> {
            static LIBUI_REGEX: &str = "ui(?:[A-Z][a-z0-9]*)*";

            let mut builder = bindgen::builder()
                .header_contents("wrapper.h", &self.contents(libui_dir))
                .parse_callbacks(Box::new(bindgen::CargoCallbacks))
                .allowlist_function(LIBUI_REGEX)
                .allowlist_type(LIBUI_REGEX)
                .allowlist_var(LIBUI_REGEX)
                .blocklist_item("_bindgen.*");

            // Note: Virtually every wrapper except that for "ui.h" should blocklist "ui.h".
            if self.blocklists_main {
                builder = builder.blocklist_file(".*ui\\.h");
            }

            builder
                .clang_args(ClangArgs::new().as_args())
                .layout_tests(false)
                .generate()
                .map_err(|_| Error::Generate)?
                .write_to_file(out_dir.join(format!("{}.rs", self.filename)))
                .map_err(Error::WriteToFile)
        }

        fn contents(&self, libui_dir: &Path) -> String {
            self
                .include_stmts
                .iter()
                .map(|stmt| stmt.to_string(libui_dir))
                .collect::<Vec<String>>()
                .join("\n")
        }
    }

    struct IncludeStmt {
        kind: IncludeStmtKind,
        arg: String,
    }

    enum IncludeStmtKind {
        System,
        Local,
    }

    impl IncludeStmt {
        fn to_string(&self, libui_dir: &Path) -> String {
            format!(
                "#include {}",
                match self.kind {
                    IncludeStmtKind::System => format!("<{}>", self.arg),
                    IncludeStmtKind::Local => format!(
                        "\"{}\"",
                        libui_dir.join(&self.arg).display(),
                    ),
                },
            )
        }
    }

    struct ClangArgs {
        defines: Vec<ClangDefine>,
        include_paths: Vec<String>,
    }

    struct ClangDefine {
        key: String,
        value: Option<String>,
    }

    impl ClangArgs {
        fn new() -> Self {
            if build_cfg!(target_os = "macos") {
                Self::new_macos()
            } else if build_cfg!(target_os = "linux") {
                Self::new_linux()
            } else if build_cfg!(target_os = "windows") {
                Self::new_windows()
            } else {
                unimplemented!("Unsupported target OS");
            }
        }

        fn new_macos() -> Self {
            Self {
                defines: Vec::new(),
                include_paths: Vec::new(),
            }
        }

        fn new_linux() -> Self {
            let gtk = pkg_config::Config::new()
                .atleast_version("3.10.0")
                .print_system_cflags(true)
                .print_system_libs(true)
                .probe("gtk+-3.0")
                .unwrap();

            let defines = gtk
                .defines
                .into_iter()
                .map(|(key, value)| {
                    ClangDefine { key, value }
                })
                .collect();

            let include_paths = gtk
                .include_paths
                .into_iter()
                .map(|path| path.display().to_string())
                .collect();

            Self {
                defines,
                include_paths,
            }
        }

        fn new_windows() -> Self {
            Self {
                defines: Vec::new(),
                include_paths: Vec::new(),
            }
        }

        fn as_args(self) -> Vec<String> {
            let defines = self
                .defines
                .into_iter()
                .flat_map(|define| {
                    vec![
                        "-D".to_string(),
                        format!(
                            "{}{}",
                            define.key,
                            define.value.map(|it| format!("={}", it)).unwrap_or_default(),
                        ),
                    ]
                });

            let includes = self
                .include_paths
                .into_iter()
                .flat_map(|path| {
                    vec![
                        "-I".to_string(),
                        path.to_string(),
                    ]
                });

            defines.chain(includes).collect()
        }
    }
}