tikz-gallery-generator

Custum build of stapix for tikz.pablopie.xyz

NameSizeMode
..
mupdf-sys/build.rs 10K -rw-r--r--
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
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
use std::{
  env::{self, current_dir},
  error::Error,
  ffi::{OsStr, OsString},
  io::ErrorKind,
  path::{Path, PathBuf},
  process::{Command, exit},
  fs,
  result,
  thread,
};

const SUPPORTED_TARGETS: &[&str] = &["linux", "openbsd", "netbsd", "macos"];
const BINDINGS_PATH:     &str    = "src/wrapper.c";

type Result<T> = result::Result<T, Box<dyn Error>>;

fn main() {
  if let Err(e) = run() {
    eprintln!("\n{e}");
    exit(1);
  }
}

fn run() -> Result<()> {
  if fs::read_dir("mupdf").map_or(true, |d| d.count() == 0) {
    Err(
      "The `mupdf` directory is empty, did you forget to pull the submodules?\n\
            Try `git submodule update --init --recursive`",
    )?
  }

  let target = Target::from_cargo().map_err(|e| {
    format!(
      "Unable to detect target: {e}\n\
            Cargo is required to build mupdf"
    )
  })?;

  if !SUPPORTED_TARGETS.contains(&target.os.as_str()) {
    Err(format!("Target {:?} is unsupported!", target.os))?
  }

  let src_dir = current_dir().unwrap().join("mupdf");
  let out_dir =
    PathBuf::from(env::var_os("OUT_DIR").ok_or("Missing OUT_DIR environment variable")?);

  let docs = env::var_os("DOCS_RS").is_some();
  if !docs {
    let build_dir = out_dir.join("build");
    let build_dir = build_dir.to_str().ok_or_else(|| {
      format!("Build dir path is required to be valid UTF-8, got {build_dir:?}")
    })?;

    if let Err(e) = fs::remove_dir_all(build_dir) {
      if e.kind() != ErrorKind::NotFound {
        println!("cargo:warning=Unable to clear {build_dir:?}. This may lead to flaky builds that might not incorporate configurations changes: {e}");
      }
    }

    copy_recursive(&src_dir, build_dir.as_ref(), &[".git".as_ref()])?;

    // ========================================================================
    let mut make = Make::default();
    make.define("FZ_ENABLE_PDF",  "1");
    make.define("FZ_ENABLE_SVG",  "1");
    make.define("FZ_ENABLE_CBZ",  "0");
    make.define("FZ_ENABLE_IMG",  "0");
    make.define("FZ_ENABLE_HTML", "0");
    make.define("FZ_ENABLE_EPUB", "0");
    make.define("FZ_ENABLE_JS",   "0");

    // NOTE: see https://github.com/ArtifexSoftware/mupdf/blob/master/source/fitz/noto.c
    make.define("TOFU",        "1");
    make.define("TOFU_CJK",    "1");
    make.define("TOFU_NOTO",   "1");
    make.define("TOFU_SYMBOL", "1");
    make.define("TOFU_EMOJI",  "1");
    make.define("TOFU_SIL",    "1");

    make.build(&target, build_dir)?;

    // ========================================================================
    build_wrapper()
      .map_err(|e| format!("Unable to compile mupdf wrapper:\n  {e}"))?;
  }

  generate_bindings(&out_dir.join("bindings.rs"))
    .map_err(|e| format!("Unable to generate mupdf bindings using bindgen:\n  {e}"))?;

  Ok(())
}

fn copy_recursive(src: &Path, dst: &Path, ignore: &[&OsStr]) -> Result<()> {
  if let Err(e) = fs::create_dir(dst) {
    if e.kind() != ErrorKind::AlreadyExists {
      Err(format!("Unable to create {dst:?}: {e}"))?;
    }
  }

  for entry in fs::read_dir(src)? {
    let entry = entry?;
    if ignore.contains(&&*entry.file_name()) {
      continue;
    }

    let src_path = entry.path();
    let dst_path = dst.join(entry.file_name());

    let file_type = entry.file_type()?;

    if file_type.is_symlink() {
      let link = fs::read_link(&src_path)
        .map_err(|e| format!("Couldn't read symlink {src_path:?}: {e}"))?;
      let err = std::os::unix::fs::symlink(&link, &dst_path);

      match err {
        Ok(_) => continue,
        Err(e) => println!(
          "cargo:warning=Couldn't create symlink {dst_path:?} pointing to {link:?}. This might increase the size of your target folder: {e}"
        ),
      }
    }

    if file_type.is_file() || fs::metadata(&src_path)?.is_file() {
      fs::copy(&src_path, &dst_path)
        .map_err(|e| format!("Couldn't copy {src_path:?} to {dst_path:?}: {e}"))?;
      } else {
        copy_recursive(&src_path, &dst_path, ignore)?;
    }
  }
  Ok(())
}

fn build_wrapper() -> Result<()> {
  let mut build = cc::Build::new();

  build
    .file(BINDINGS_PATH)
    .include("mupdf/include")
    .extra_warnings(true)
    .flag("-Wno-clobbered") // NOTE: remove stupid warnings on src/wrapper.c
    .debug(true)
    .try_compile("mupdf-wrapper")?;

  Ok(())
}

fn generate_bindings(path: &Path) -> Result<()> {
  let mut builder = bindgen::builder();

  builder = builder
    .clang_arg("-Imupdf/include")
    .header(BINDINGS_PATH);

  builder = builder
    .allowlist_recursively(false)
    .allowlist_type("wchar_t")
    .allowlist_type("FILE")
    .opaque_type("FILE")
    .allowlist_item("max_align_t")
    .opaque_type("max_align_t");

  builder = builder
    .allowlist_item("fz_.*")
    .allowlist_item("FZ_.*")
    .allowlist_item("pdf_.*")
    .allowlist_item("PDF_.*")
    .allowlist_type("cmap_splay")
    .allowlist_item("ucdn_.*")
    .allowlist_item("UCDN_.*")
    .allowlist_item("Memento_.*")
    .allowlist_item("mupdf_.*");

  // remove va_list functions as for all of these versions using ... exist
  builder = builder
    .blocklist_function("Memento_vasprintf")    // Memento_asprintf
    .blocklist_function("fz_vthrow")            // fz_throw
    .blocklist_function("fz_vwarn")             // fz_warn
    .blocklist_function("fz_vlog_error_printf") // fz_log_error_printf
    .blocklist_function("fz_append_vprintf")    // fz_append_printf
    .blocklist_function("fz_write_vprintf")     // fz_write_printf
    .blocklist_function("fz_vsnprintf")         // fz_snprintf
    .blocklist_function("fz_format_string");    // mupdf_format_string

  // TODO: make "FZ_VERSION.*" private
  // build config
  builder = builder
    .blocklist_var("FZ_ENABLE_.*")
    .blocklist_var("FZ_PLOTTERS_.*");

  // internal implementation details, considered private
  builder = builder
    .blocklist_item("fz_jmp_buf")
    .blocklist_function("fz_var_imp")
    .blocklist_function("fz_push_try")
    .blocklist_function("fz_do_.*")
    .blocklist_var("FZ_JMPBUF_ALIGN")
    .blocklist_type("fz_error_stack_slot")
    .blocklist_type("fz_error_context")
    .blocklist_type("fz_warn_context")
    .blocklist_type("fz_aa_context")
    .blocklist_type("fz_activity_.*")
    .blocklist_function("fz_register_activity_logger")
    .opaque_type("fz_context")
    .blocklist_type("fz_new_context_imp")
    .blocklist_type("fz_lock")
    .blocklist_type("fz_unlock");

  builder = builder
    .parse_callbacks(Box::new(bindgen::CargoCallbacks::new()));

  builder
    .prepend_enum_name(false)
    .use_core()
    .generate()?
    .write_to_file(path)?;

  Ok(())
}

#[derive(Default)]
struct Make {
  build:      cc::Build,
  make_flags: Vec<OsString>,
}

impl Make {
  pub fn define(&mut self, var: &str, val: &str) {
    self.build.define(var, val);
  }

  fn make_var(&mut self, var: &str, val: impl AsRef<OsStr>) {
    let mut flag = OsString::from(var);
    flag.push("=");
    flag.push(val);
    self.make_flags.push(flag);
  }

  fn make_bool(&mut self, var: &str, val: bool) {
    self.make_var(var, if val { "yes" } else { "no" });
  }

  fn cpu_flags(
    &mut self,
    target: &Target,
    feature: &str,
    flag: &str,
    make_flag: &str,
    define: Option<&str>,
  ) {
    let contains = target.cpu_features.iter().any(|f| f == feature)
      && self.build.is_flag_supported(flag).unwrap_or(true);
    if contains {
      self.build.flag(flag);
      self.make_bool(make_flag, true);
    }

    if let Some(define) = define {
      self.define(define, if contains { "1" } else { "0" });
    }
  }

  pub fn build(mut self, target: &Target, build_dir: &str) -> Result<()> {
    self.make_var(
      "build",
      if target.small_profile() {
        "small"
      } else if target.debug_profile() {
        "debug"
      } else {
        "release"
      },
    );

    self.make_var("OUT", build_dir);

    self.make_bool("HAVE_X11",  false);
    self.make_bool("HAVE_GLUT", false);
    self.make_bool("HAVE_CURL", false);

    self.make_bool("verbose", true);

    // ========================================================================
    self.make_bool("USE_TESSERACT",  false);
    self.make_bool("USE_ZXINGCPP",   false);
    self.make_bool("USE_LIBARCHIVE", false);

    // ========================================================================
    self.cpu_flags(
      target,
      "sse4.1",
      "-msse4.1",
      "HAVE_SSE4_1",
      Some("ARCH_HAS_SSE"),
    );
    self.cpu_flags(target, "avx",  "-mavx",  "HAVE_AVX", None);
    self.cpu_flags(target, "avx2", "-mavx2", "HAVE_AVX2", None);
    self.cpu_flags(target, "fma",  "-mfma",  "HAVE_FMA", None);

    // NOTE: arm
    self.cpu_flags(
      target,
      "neon",
      "-mfpu=neon",
      "HAVE_NEON",
      Some("ARCH_HAS_NEON"),
    );
    // ========================================================================
    if let Ok(n) = thread::available_parallelism() {
      self.make_flags.push(format!("-j{n}").into());
    }

    self.build.warnings(false);

    let compiler = self.build.get_compiler();
    self.make_var("CC", compiler.path());
    self.make_var("XCFLAGS", compiler.cflags_env());

    self.build.cpp(true);
    let compiler = self.build.get_compiler();
    self.make_var("CXX", compiler.path());
    self.make_var("XCXXFLAGS", compiler.cflags_env());

    let make = if cfg!(any(
        target_os = "freebsd",
        target_os = "openbsd",
        target_os = "netbsd"
    )) {
      "gmake"
    } else {
      "make"
    };

    let status = Command::new(make)
      .arg("libs")
      .args(&self.make_flags)
      .current_dir(build_dir)
      .status()
      .map_err(|e| format!("Failed to call {make}: {e}"))?;
    if !status.success() {
      Err(match status.code() {
        Some(code) => format!("{make} invocation failed with status {code}"),
        None => format!("{make} invocation failed"),
      })?;
    }

    println!("cargo:rustc-link-search=native={build_dir}");
    println!("cargo:rustc-link-lib=static=mupdf");
    println!("cargo:rustc-link-lib=static=mupdf-third");

    Ok(())
  }
}

struct Target {
  debug:     bool,
  opt_level: String,
  os:        String,

  cpu_features: Vec<String>,
}

impl Target {
  fn from_cargo() -> Result<Self> {
    Ok(Self {
      debug:     env::var_os("DEBUG").is_some_and(|s| s != "0" && s != "false"),
      opt_level: env::var("OPT_LEVEL")?,
      os:        env::var("CARGO_CFG_TARGET_OS")?,

      cpu_features: env::var("CARGO_CFG_TARGET_FEATURE")?
        .split(',')
        .map(str::to_owned)
        .collect(),
    })
  }

  fn small_profile(&self) -> bool {
    !self.debug && matches!(&*self.opt_level, "s" | "z")
  }

  fn debug_profile(&self) -> bool {
    self.debug && !matches!(&*self.opt_level, "2" | "3")
  }
}