forked from rust-skia/rust-skia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
skia.rs
1451 lines (1304 loc) · 49.2 KB
/
skia.rs
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Full build support for the Skia library, SkiaBindings library and bindings.rs file.
use crate::build_support::{android, binaries, cargo, clang, ios, llvm, vs, xcode};
use bindgen::{CodegenConfig, EnumVariation};
use cc::Build;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::{env, fs};
/// The libraries to link with.
mod lib {
pub const SKIA: &str = "skia";
pub const SKIA_BINDINGS: &str = "skia-bindings";
pub const SKSHAPER: &str = "skshaper";
pub const SKPARAGRAPH: &str = "skparagraph";
}
/// Feature identifiers define the additional configuration parts of the binaries to download.
mod feature_id {
pub const GL: &str = "gl";
pub const VULKAN: &str = "vulkan";
pub const METAL: &str = "metal";
pub const D3D: &str = "d3d";
pub const TEXTLAYOUT: &str = "textlayout";
pub const WEBPE: &str = "webpe";
pub const WEBPD: &str = "webpd";
}
/// The defaults for the Skia build configuration.
impl Default for BuildConfiguration {
fn default() -> Self {
let skia_debug = matches!(cargo::env_var("SKIA_DEBUG"), Some(v) if v != "0");
BuildConfiguration {
on_windows: cargo::host().is_windows(),
skia_debug,
features: Features {
gl: cfg!(feature = "gl"),
vulkan: cfg!(feature = "vulkan"),
metal: cfg!(feature = "metal"),
d3d: cfg!(feature = "d3d"),
text_layout: cfg!(feature = "textlayout"),
webp_encode: cfg!(feature = "webp-encode"),
webp_decode: cfg!(feature = "webp-decode"),
animation: false,
dng: false,
particles: false,
},
definitions: Vec::new(),
}
}
}
/// The build configuration for Skia.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct BuildConfiguration {
/// Do we build _on_ a Windows OS?
on_windows: bool,
/// Build Skia in a debug configuration?
skia_debug: bool,
/// The Skia feature set to compile.
features: Features,
/// Additional preprocessor definitions that will override predefined ones.
definitions: Definitions,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Features {
/// Build with OpenGL / EGL support?
pub gl: bool,
/// Build with Vulkan support?
pub vulkan: bool,
/// Build with Metal support?
pub metal: bool,
/// Build with Direct3D support?
pub d3d: bool,
/// Features related to text layout. Modules skshaper and skparagraph.
pub text_layout: bool,
/// Support the encoding of bitmap data to the WEBP image format.
pub webp_encode: bool,
/// Support the decoding of the WEBP image format to bitmap data.
pub webp_decode: bool,
/// Build with animation support (yet unsupported, no wrappers).
pub animation: bool,
/// Support DNG file format (currently unsupported because of build errors).
pub dng: bool,
/// Build the particles module (unsupported, no wrappers).
pub particles: bool,
}
impl Features {
pub fn gpu(&self) -> bool {
self.gl || self.vulkan || self.metal || self.d3d
}
/// Feature Ids used to look up prebuilt binaries.
pub fn ids(&self) -> Vec<&str> {
let mut feature_ids = Vec::new();
if self.gl {
feature_ids.push(feature_id::GL);
}
if self.vulkan {
feature_ids.push(feature_id::VULKAN);
}
if self.metal {
feature_ids.push(feature_id::METAL);
}
if self.d3d {
feature_ids.push(feature_id::D3D);
}
if self.text_layout {
feature_ids.push(feature_id::TEXTLAYOUT);
}
if self.webp_encode {
feature_ids.push(feature_id::WEBPE);
}
if self.webp_decode {
feature_ids.push(feature_id::WEBPD);
}
feature_ids
}
}
/// This is the final, low level build configuration.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct FinalBuildConfiguration {
/// The Skia source directory.
pub skia_source_dir: PathBuf,
/// The name value pairs passed as arguments to gn.
pub gn_args: Vec<(String, String)>,
/// ninja files that need to be parsed for further definitions.
pub ninja_files: Vec<PathBuf>,
/// The additional definitions (cloned from the definitions of
/// the BuildConfiguration).
pub definitions: Definitions,
/// The binding source files to compile.
pub binding_sources: Vec<PathBuf>,
}
impl FinalBuildConfiguration {
#[allow(clippy::cognitive_complexity)]
pub fn from_build_configuration(
build: &BuildConfiguration,
skia_source_dir: &Path,
) -> FinalBuildConfiguration {
let features = &build.features;
let gn_args = {
fn quote(s: &str) -> String {
format!("\"{}\"", s)
}
let mut args: Vec<(&str, String)> = vec![
("is_official_build", yes_if(!build.skia_debug)),
("is_debug", yes_if(build.skia_debug)),
("skia_enable_gpu", yes_if(features.gpu())),
("skia_use_gl", yes_if(features.gl)),
("skia_use_system_libjpeg_turbo", no()),
("skia_use_system_libpng", no()),
("skia_use_libwebp_encode", yes_if(features.webp_encode)),
("skia_use_libwebp_decode", yes_if(features.webp_decode)),
("skia_use_system_zlib", no()),
("skia_use_xps", no()),
("skia_use_dng_sdk", yes_if(features.dng)),
("cc", quote("clang")),
("cxx", quote("clang++")),
];
if features.vulkan {
args.push(("skia_use_vulkan", yes()));
args.push(("skia_enable_spirv_validation", no()));
}
if features.metal {
args.push(("skia_use_metal", yes()));
}
if features.d3d {
args.push(("skia_use_direct3d", yes()))
}
// further flags that limit the components of Skia debug builds.
if build.skia_debug {
args.push(("skia_enable_spirv_validation", no()));
args.push(("skia_enable_tools", no()));
args.push(("skia_enable_vulkan_debug_layers", no()));
args.push(("skia_use_libheif", no()));
args.push(("skia_use_lua", no()));
}
if features.text_layout {
args.extend(vec![
("skia_enable_skshaper", yes()),
("skia_use_icu", yes()),
("skia_use_system_icu", no()),
("skia_use_harfbuzz", yes()),
("skia_pdf_subset_harfbuzz", yes()),
("skia_use_system_harfbuzz", no()),
("skia_use_sfntly", no()),
("skia_enable_skparagraph", yes()),
// note: currently, tests need to be enabled, because modules/skparagraph
// is not included in the default dependency configuration.
// ("paragraph_tests_enabled", no()),
]);
} else {
args.push(("skia_use_icu", no()));
}
if features.webp_encode || features.webp_decode {
args.push(("skia_use_system_libwebp", no()))
}
let mut flags: Vec<&str> = vec![];
let mut use_expat = true;
// target specific gn args.
let target = cargo::target();
match target.as_strs() {
(_, _, "windows", Some("msvc")) if build.on_windows => {
if let Some(win_vc) = vs::resolve_win_vc() {
args.push(("win_vc", quote(win_vc.to_str().unwrap())))
}
// Code on MSVC needs to be compiled differently (e.g. with /MT or /MD) depending on the runtime being linked.
// (See https://doc.rust-lang.org/reference/linkage.html#static-and-dynamic-c-runtimes)
// When static feature is enabled (target-feature=+crt-static) the C runtime should be statically linked
// and the compiler has to place the library name LIBCMT.lib into the .obj
// See https://docs.microsoft.com/en-us/cpp/build/reference/md-mt-ld-use-run-time-library?view=vs-2019
if cargo::target_crt_static() {
flags.push("/MT");
}
// otherwise the C runtime should be linked dynamically
else {
flags.push("/MD");
}
// Tell Skia's build system where LLVM is supposed to be located.
if let Some(llvm_home) = llvm::win::find_llvm_home() {
args.push(("clang_win", quote(&llvm_home)));
} else {
panic!(
"Unable to locate LLVM installation. skia-bindings can not be built."
);
}
}
(arch, "linux", "android", _) | (arch, "linux", "androideabi", _) => {
args.push(("ndk", quote(&android::ndk())));
// TODO: make API-level configurable?
args.push(("ndk_api", android::API_LEVEL.into()));
args.push(("target_cpu", quote(clang::target_arch(arch))));
args.push(("skia_use_system_freetype2", no()));
args.push(("skia_enable_fontmgr_android", yes()));
// Enabling fontmgr_android implicitly enables expat.
// We make this explicit to avoid relying on an expat installed
// in the system.
use_expat = true;
}
(arch, "apple", "ios", _) => {
args.push(("target_os", quote("ios")));
args.push(("target_cpu", quote(clang::target_arch(arch))));
}
("wasm32", "unknown", "emscripten", _) |
("wasm32", "unknown", "unknown", _) => {
args.push(("cc", quote("emcc")));
args.push(("cxx", quote("em++")));
args.push(("skia_enable_fontmgr_custom", yes()));
args.push(("skia_gl_standard", quote("webgl")));
args.push(("skia_use_freetype", yes()));
args.push(("skia_use_system_freetype2", no()));
args.push(("skia_use_webgl", yes())); // yes_if(features.gpu())
args.push(("target_cpu", quote("wasm")));
}
_ => {}
}
if use_expat {
args.push(("skia_use_expat", yes()));
args.push(("skia_use_system_expat", no()));
} else {
args.push(("skia_use_expat", no()));
}
if !flags.is_empty() {
let flags: String = {
let v: Vec<String> = flags.into_iter().map(quote).collect();
v.join(",")
};
args.push(("extra_cflags", format!("[{}]", flags)));
}
args.into_iter()
.map(|(key, value)| (key.to_string(), value))
.collect()
};
let ninja_files = {
let mut files = Vec::new();
files.push("obj/skia.ninja".into());
if features.text_layout {
files.extend(vec![
"obj/modules/skshaper/skshaper.ninja".into(),
"obj/modules/skparagraph/skparagraph.ninja".into(),
]);
}
files
};
let binding_sources = {
let mut sources: Vec<PathBuf> = Vec::new();
sources.push("src/bindings.cpp".into());
if features.gl {
sources.push("src/gl.cpp".into());
}
if features.vulkan {
sources.push("src/vulkan.cpp".into());
}
if features.metal {
sources.push("src/metal.cpp".into());
}
if features.d3d {
sources.push("src/d3d.cpp".into());
}
if features.gpu() {
sources.push("src/gpu.cpp".into());
}
if features.text_layout {
sources.extend(vec!["src/shaper.cpp".into(), "src/paragraph.cpp".into()]);
}
sources.push("src/svg.cpp".into());
sources
};
FinalBuildConfiguration {
skia_source_dir: skia_source_dir.into(),
gn_args,
ninja_files,
definitions: build.definitions.clone(),
binding_sources,
}
}
}
fn yes() -> String {
"true".into()
}
fn no() -> String {
"false".into()
}
fn yes_if(y: bool) -> String {
if y {
yes()
} else {
no()
}
}
/// The configuration of the resulting binaries.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct BinariesConfiguration {
/// The feature identifiers we built with.
pub feature_ids: Vec<String>,
/// The output directory of the libraries we build and we need to inform cargo about.
pub output_directory: PathBuf,
/// The TARGET specific link libraries we need to inform cargo about.
pub link_libraries: Vec<String>,
/// The static Skia libraries skia-bindings provides and dependent projects need to link with.
pub built_libraries: Vec<String>,
/// Additional files relative to the output_directory
/// that are needed to build dependent projects.
pub additional_files: Vec<PathBuf>,
/// `true` if the skia libraries are built with debugging information.
pub skia_debug: bool,
}
const SKIA_OUTPUT_DIR: &str = "skia";
const ICUDTL_DAT: &str = "icudtl.dat";
impl BinariesConfiguration {
/// Build a binaries configuration based on the current environment cargo
/// supplies us with and a Skia build configuration.
pub fn from_cargo_env(build: &BuildConfiguration) -> Self {
let features = &build.features;
let target = cargo::target();
let mut built_libraries = Vec::new();
let mut additional_files = Vec::new();
let feature_ids = features.ids();
if features.text_layout {
additional_files.push(ICUDTL_DAT.into());
built_libraries.push(lib::SKPARAGRAPH.into());
built_libraries.push(lib::SKSHAPER.into());
}
let mut link_libraries = Vec::new();
match target.as_strs() {
(_, "unknown", "linux", Some("gnu")) => {
link_libraries.extend(vec!["stdc++", "fontconfig", "freetype"]);
if features.gl {
link_libraries.push("GL");
}
}
(_, "apple", "darwin", _) => {
link_libraries.extend(vec!["c++", "framework=ApplicationServices"]);
if features.gl {
link_libraries.push("framework=OpenGL");
}
if features.metal {
link_libraries.push("framework=Metal");
// MetalKit was added in m87 BUILD.gn.
link_libraries.push("framework=MetalKit");
link_libraries.push("framework=Foundation");
}
}
(_, _, "windows", Some("msvc")) => {
link_libraries.extend(&["usp10", "ole32", "user32", "gdi32", "fontsub"]);
if features.gl {
link_libraries.push("opengl32");
}
if features.d3d {
link_libraries.extend(&["d3d12", "dxgi", "d3dcompiler"]);
}
}
(_, "linux", "android", _) | (_, "linux", "androideabi", _) => {
link_libraries.extend(android::link_libraries(features));
}
(_, "apple", "ios", _) => {
link_libraries.extend(ios::link_libraries(features));
}
("wasm32", "unknown", "emscripten", _) |
("wasm32", "unknown", "unknown", _) => {
link_libraries.extend(vec!["GL"]);
}
_ => panic!("unsupported target: {:?}", cargo::target()),
};
let output_directory = cargo::output_directory()
.join(SKIA_OUTPUT_DIR)
.to_str()
.unwrap()
.into();
built_libraries.push(lib::SKIA.into());
built_libraries.push(lib::SKIA_BINDINGS.into());
BinariesConfiguration {
feature_ids: feature_ids.into_iter().map(|f| f.to_string()).collect(),
output_directory,
link_libraries: link_libraries
.into_iter()
.map(|lib| lib.to_string())
.collect(),
built_libraries,
additional_files,
skia_debug: build.skia_debug,
}
}
/// Inform cargo that the library files of the given configuration are available and
/// can be used as dependencies.
pub fn commit_to_cargo(&self) {
cargo::add_link_search(self.output_directory.to_str().unwrap());
// On Linux, the order is significant, first the static libraries we built, and then
// the system libraries.
let target = cargo::target();
for lib in &self.built_libraries {
// Prefixing the libraries we built with `static=` causes linker errors on Windows.
// https://github.com/rust-skia/rust-skia/pull/354
let kind_prefix = {
if target.is_windows() {
""
} else {
"static="
}
};
cargo::add_link_lib(format!("{}{}", kind_prefix, lib));
}
cargo::add_link_libs(&self.link_libraries);
}
pub fn key(&self, repository_short_hash: &str) -> String {
binaries::key(repository_short_hash, &self.feature_ids, self.skia_debug)
}
}
/// The full build of Skia, skia-bindings, and the generation of bindings.rs.
pub fn build(build: &FinalBuildConfiguration, config: &BinariesConfiguration) {
let python2 = &prerequisites::locate_python2_cmd();
println!("Python 2 found: {:?}", python2);
let ninja = fetch_dependencies(&python2);
configure_skia(build, config, &python2, None);
build_skia(build, config, &ninja);
}
/// Build Skia without any network access.
///
/// An offline build expects the Skia source tree including all third party dependencies
/// to be available.
pub fn build_offline(
build: &FinalBuildConfiguration,
config: &BinariesConfiguration,
ninja_command: Option<&Path>,
gn_command: Option<&Path>,
) {
let python2 = prerequisites::locate_python2_cmd();
configure_skia(&build, &config, &python2, gn_command);
build_skia(
&build,
&config,
ninja_command.unwrap_or(&ninja::default_exe_name()),
);
}
/// Prepares the build and returns the ninja command to use for building Skia.
pub fn fetch_dependencies(python2: &Path) -> PathBuf {
prerequisites::resolve_dependencies();
// call Skia's git-sync-deps
println!("Synchronizing Skia dependencies");
assert!(
Command::new(python2)
.arg("skia/tools/git-sync-deps")
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.status()
.unwrap()
.success(),
"`skia/tools/git-sync-deps` failed"
);
env::current_dir()
.unwrap()
.join("depot_tools")
.join(ninja::default_exe_name())
}
/// Configures Skia by calling gn
pub fn configure_skia(
build: &FinalBuildConfiguration,
config: &BinariesConfiguration,
python2: &Path,
gn_command: Option<&Path>,
) {
let gn_args = build
.gn_args
.iter()
.map(|(name, value)| name.clone() + "=" + value)
.collect::<Vec<String>>()
.join(" ");
let gn_command = gn_command
.map(|p| p.to_owned())
.unwrap_or_else(|| build.skia_source_dir.join("bin").join("gn"));
println!("Skia args: {}", &gn_args);
let output = Command::new(gn_command)
.args(&[
"gen",
config.output_directory.to_str().unwrap(),
&format!("--script-executable={}", python2.to_str().unwrap()),
&format!("--args={}", gn_args),
])
.envs(env::vars())
.current_dir(&build.skia_source_dir)
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.output()
.expect("gn error");
if output.status.code() != Some(0) {
panic!("{:?}", String::from_utf8(output.stdout).unwrap());
}
}
/// Builds Skia.
///
/// This function assumes that all prerequisites are in place and that the output directory
/// contains a fully configured Skia source tree generated by gn.
pub fn build_skia(
build: &FinalBuildConfiguration,
config: &BinariesConfiguration,
ninja_command: &Path,
) {
let ninja_status = Command::new(ninja_command)
.args(&["-C", config.output_directory.to_str().unwrap()])
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.status();
assert!(
ninja_status
.expect("failed to run `ninja`, does the directory depot_tools/ exist?")
.success(),
"`ninja` returned an error, please check the output for details."
);
generate_bindings(build, &config.output_directory)
}
fn generate_bindings(build: &FinalBuildConfiguration, output_directory: &Path) {
let mut builder = bindgen::Builder::default()
.generate_comments(false)
.layout_tests(true)
// on macOS some arrays that are used in opaque types get too large to support Debug.
// (for example High Sierra: [u16; 105])
// TODO: may reenable when const generics land in stable.
.derive_debug(true)
.default_enum_style(EnumVariation::Rust {
non_exhaustive: false,
})
.size_t_is_usize(true)
.parse_callbacks(Box::new(ParseCallbacks))
.raw_line("#![allow(clippy::all)]")
// GrVkBackendContext contains u128 fields on macOS
.raw_line("#![allow(improper_ctypes)]")
.whitelist_function("C_.*")
.constified_enum(".*Mask")
.constified_enum(".*Flags")
.constified_enum(".*Bits")
.constified_enum("SkCanvas_SaveLayerFlagsSet")
.constified_enum("GrVkAlloc_Flag")
.constified_enum("GrGLBackendState")
// not used:
.blacklist_type("SkPathRef_Editor")
.blacklist_function("SkPathRef_Editor_Editor")
// private types that pull in inline functions that cannot be linked:
// https://github.com/rust-skia/rust-skia/issues/318
.raw_line("pub enum GrContext_Base {}")
.blacklist_type("GrContext_Base")
.blacklist_function("GrContext_Base_.*")
.raw_line("pub enum GrImageContext {}")
.blacklist_type("GrImageContext")
.raw_line("pub enum GrImageContextPriv {}")
.blacklist_type("GrImageContextPriv")
.raw_line("pub enum GrContextThreadSafeProxy {}")
.blacklist_type("GrContextThreadSafeProxy")
.raw_line("pub enum GrContextThreadSafeProxyPriv {}")
.blacklist_type("GrContextThreadSafeProxyPriv")
.raw_line("pub enum GrRecordingContextPriv {}")
.blacklist_type("GrRecordingContextPriv")
.raw_line("pub enum GrContextPriv {}")
.blacklist_type("GrContextPriv")
.blacklist_function("GrContext_priv.*")
.blacklist_function("SkDeferredDisplayList_priv.*")
.raw_line("pub enum SkVerticesPriv {}")
.blacklist_type("SkVerticesPriv")
.blacklist_function("SkVertices_priv.*")
.blacklist_function("std::bitset_flip.*")
// Vulkan reexports that got swallowed by making them opaque.
// (these can not be whitelisted by a extern "C" function)
.whitelist_type("VkPhysicalDeviceFeatures")
.whitelist_type("VkPhysicalDeviceFeatures2")
// misc
.whitelist_var("SK_Color.*")
.whitelist_var("kAll_GrBackendState")
//
// don't generate destructors: https://github.com/rust-skia/rust-skia/issues/318
.with_codegen_config({
let mut config = CodegenConfig::default();
config.remove(CodegenConfig::DESTRUCTORS);
config
})
//
.use_core()
.clang_arg("-std=c++17")
// required for macOS LLVM 8 to pick up C++ headers:
.clang_args(&["-x", "c++"])
.clang_arg("-v");
// wasm: blacklist due to unknown/emscripten abi incompatibilties
builder = builder
.blacklist_function("C_SkFontArguments_setVariationDesignPosition")
.blacklist_function("SkM44_setRotate")
.blacklist_function("SkM44_setRotateUnitSinCos")
.blacklist_function("SkFont_getPos");
for function in WHITELISTED_FUNCTIONS {
builder = builder.whitelist_function(function)
}
for opaque_type in OPAQUE_TYPES {
builder = builder.opaque_type(opaque_type)
}
for t in BLACKLISTED_TYPES {
builder = builder.blacklist_type(t);
}
let mut cc_build = Build::new();
for source in &build.binding_sources {
cc_build.file(source);
let source = source.to_str().unwrap();
cargo::rerun_if_changed(source);
builder = builder.header(source);
}
let include_path = &build.skia_source_dir;
cargo::rerun_if_changed(include_path.join("include"));
builder = builder.clang_arg(format!("-I{}", include_path.display()));
cc_build.include(include_path);
let definitions = {
let mut definitions = Vec::new();
for ninja_file in &build.ninja_files {
let ninja_file = output_directory.join(ninja_file);
let contents = fs::read_to_string(ninja_file).unwrap();
definitions = definitions::combine(definitions, definitions::from_ninja(contents))
}
definitions::combine(definitions, build.definitions.clone())
};
// Whether GIF decoding is supported,
// is decided by BUILD.gn based on the existence of the libgifcodec directory:
if !definitions.iter().any(|(v, _)| v == "SK_USE_LIBGIFCODEC") {
cargo::warning("GIF decoding support may be missing, does the directory skia/third_party/externals/libgifcodec/ exist?")
}
for (name, value) in &definitions {
match value {
Some(value) => {
cc_build.define(name, value.as_str());
builder = builder.clang_arg(format!("-D{}={}", name, value));
}
None => {
cc_build.define(name, "");
builder = builder.clang_arg(format!("-D{}", name));
}
}
}
cc_build.cpp(true).out_dir(output_directory);
if !cfg!(windows) {
cc_build.flag("-std=c++17");
}
let target = cargo::target();
match target.as_strs() {
(_, "apple", "darwin", _) => {
if let Some(sdk) = xcode::get_sdk_path("macosx") {
builder = builder.clang_arg(format!("-isysroot{}", sdk.to_str().unwrap()));
} else {
cargo::warning("failed to get macosx SDK path")
}
}
(arch, "linux", "android", _) | (arch, "linux", "androideabi", _) => {
let target = &target.to_string();
cc_build.target(target);
for arg in android::additional_clang_args(target, arch) {
builder = builder.clang_arg(arg);
}
}
(arch, "apple", "ios", _) => {
for arg in ios::additional_clang_args(arch) {
builder = builder.clang_arg(arg);
}
}
("wasm32", "unknown", "emscripten", _) |
("wasm32", "unknown", "unknown", _) => {
cc_build.compiler("em++");
cc_build.flag("-fno-exceptions");
cc_build.flag("-fno-rtti");
cc_build.flag("-DSK_FORCE_8_BYTE_ALIGNMENT");
let add_sys_include = |builder: bindgen::Builder, path: &str| -> bindgen::Builder {
let emsdk = env!("EMSDK");
let cflag = format!("-isystem{}/upstream/emscripten/system/{}", emsdk, path);
builder.clang_arg(&cflag)
};
// visibility=default, otherwise some types may be missing:
// https://github.com/rust-lang/rust-bindgen/issues/751#issuecomment-555735577
builder = builder.clang_arg("-fvisibility=default");
builder = builder.clang_arg("--target=wasm32-unknown-emscripten");
// Add C++ includes (otherwise build will fail with <cmath> not found)
builder = builder.clang_arg("-nobuiltininc");
builder = add_sys_include(builder, "lib/libc/musl/arch/emscripten");
builder = add_sys_include(builder, "include/libcxx");
builder = add_sys_include(builder, "include/libc");
builder = add_sys_include(builder, "include");
}
_ => {}
}
println!("COMPILING BINDINGS: {:?}", build.binding_sources);
// we add skia-bindings later on.
cc_build.cargo_metadata(false);
cc_build.compile(lib::SKIA_BINDINGS);
println!("GENERATING BINDINGS");
let bindings = builder.generate().expect("Unable to generate bindings");
let out_path = PathBuf::from("src");
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Couldn't write bindings!");
}
const WHITELISTED_FUNCTIONS: &[&str] = &[
"SkAnnotateRectWithURL",
"SkAnnotateNamedDestination",
"SkAnnotateLinkToDestination",
"SkColorTypeBytesPerPixel",
"SkColorTypeIsAlwaysOpaque",
"SkColorTypeValidateAlphaType",
"SkRGBToHSV",
// this function does not whitelist (probably because of inlining):
"SkColorToHSV",
"SkHSVToColor",
"SkPreMultiplyARGB",
"SkPreMultiplyColor",
"SkBlendMode_AsCoeff",
"SkBlendMode_Name",
"SkSwapRB",
// functions for which the doc generation fails
"SkColorFilter_asComponentTable",
// pathops/
"Op",
"Simplify",
"TightBounds",
"AsWinding",
// utils/
"Sk3LookAt",
"Sk3Perspective",
"Sk3MapPts",
"SkUnitCubicInterp",
];
const OPAQUE_TYPES: &[&str] = &[
// Types for which the binding generator pulls in stuff that can not be compiled.
"SkDeferredDisplayList",
"SkDeferredDisplayList_PendingPathsMap",
// Types for which a bindgen layout is wrong causing types that contain
// fields of them to fail their layout test.
// Windows:
"std::atomic",
"std::function",
"std::unique_ptr",
"SkAutoTMalloc",
"SkTHashMap",
// Ubuntu 18 LLVM 6: all types derived from SkWeakRefCnt
"SkWeakRefCnt",
"GrContext",
"GrGLInterface",
"GrSurfaceProxy",
"Sk2DPathEffect",
"SkCornerPathEffect",
"SkDataTable",
"SkDiscretePathEffect",
"SkDrawable",
"SkLine2DPathEffect",
"SkPath2DPathEffect",
"SkPathRef_GenIDChangeListener",
"SkPicture",
"SkPixelRef",
"SkSurface",
// Types not needed (for now):
"SkDeque",
"SkDeque_Iter",
"GrGLInterface_Functions",
// SkShaper (m77) Trivial*Iterator classes create two vtable pointers.
"SkShaper_TrivialBiDiRunIterator",
"SkShaper_TrivialFontRunIterator",
"SkShaper_TrivialLanguageRunIterator",
"SkShaper_TrivialScriptRunIterator",
// skparagraph
"std::vector",
"std::u16string",
// skparagraph (m78), (layout fails on macOS and Linux, not sure why, looks like an obscure alignment problem)
"skia::textlayout::FontCollection",
// skparagraph (m79), std::map is used in LineMetrics
"std::map",
// Vulkan reexports with the wrong field naming conventions.
"VkPhysicalDeviceFeatures",
"VkPhysicalDeviceFeatures2",
// Since Rust 1.39 beta (TODO: investigate why, and re-test when 1.39 goes stable).
"GrContextOptions_PersistentCache",
"GrContextOptions_ShaderErrorHandler",
"Sk1DPathEffect",
"SkBBoxHierarchy", // vtable
"SkBBHFactory",
"SkBitmap_Allocator",
"SkBitmap_HeapAllocator",
"SkColorFilter",
"SkDeque_F2BIter",
"SkDrawLooper",
"SkDrawLooper_Context",
"SkDrawable_GpuDrawHandler",
"SkFlattenable",
"SkFontMgr",
"SkFontStyleSet",
"SkMaskFilter",
"SkPathEffect",
"SkPicture_AbortCallback",
"SkPixelRef_GenIDChangeListener",
"SkRasterHandleAllocator",
"SkRefCnt",
"SkShader",
"SkStream",
"SkStreamAsset",
"SkStreamMemory",
"SkStreamRewindable",
"SkStreamSeekable",
"SkTypeface_LocalizedStrings",
"SkWStream",
"GrVkMemoryAllocator",
"SkShaper",
"SkShaper_BiDiRunIterator",
"SkShaper_FontRunIterator",
"SkShaper_LanguageRunIterator",
"SkShaper_RunHandler",
"SkShaper_RunIterator",
"SkShaper_ScriptRunIterator",
"SkContourMeasure",
"SkDocument",
// m81: tuples:
"SkRuntimeEffect_EffectResult",
"SkRuntimeEffect_ByteCodeResult",
"SkRuntimeEffect_SpecializeResult",
// m81: derives from std::string
"SkSL::String",
"std::basic_string",
"std::basic_string_value_type",
// m81: wrong size on macOS and Linux
"SkRuntimeEffect",
"GrShaderCaps",
// more stuff we don't need that was tracked down fixing:
// https://github.com/rust-skia/rust-skia/issues/318
// referred from SkPath, but not used:
"SkPathRef",
"SkMutex",
// m82: private
"SkIDChangeListener",
// m86:
"GrRecordingContext",
"GrDirectContext",
// m87:
"GrD3DAlloc",
"GrD3DMemoryAllocator",
];
const BLACKLISTED_TYPES: &[&str] = &[
// modules/skparagraph
// pulls in a std::map<>, which we treat as opaque, but bindgen creates wrong bindings for
// std::_Tree* types
"std::_Tree.*",
"std::map.*",
// debug builds:
"SkLRUCache",
"SkLRUCache_Entry",
// not used at all:
"std::vector.*",
// too much template magic:
"SkRuntimeEffect_ConstIterable.*",
// Linux LLVM9 c++17
"std::_Rb_tree.*",
// Linux LLVM9 c++17 with SKIA_DEBUG=1
"std::__cxx.*",
"std::array.*",
];
#[derive(Debug)]
struct ParseCallbacks;
impl bindgen::callbacks::ParseCallbacks for ParseCallbacks {