-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathbuild_rdkit_csharp.py
More file actions
1680 lines (1480 loc) · 61.2 KB
/
Copy pathbuild_rdkit_csharp.py
File metadata and controls
1680 lines (1480 loc) · 61.2 KB
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
"""Script to make RDKit.DotNetWrapper.
Notes:
This is developed with rdkit-Release_2021_09_4.
"""
from enum import Enum
import argparse
import glob
import logging
import os
import platform
import re
import shutil
import subprocess
import sys
import typing
import xml.etree.ElementTree as ET
from os import PathLike
from pathlib import Path
from subprocess import PIPE
from typing import (
Callable,
Collection,
Dict,
Iterable,
List,
Literal,
Mapping,
Optional,
Sequence,
Set,
Tuple,
Union,
cast,
)
from xml.etree.ElementTree import Element, ElementTree, SubElement
logging.basicConfig(level=logging.DEBUG)
project_name: str = "RDKit.DotNetWrap"
VisualStudioVersion = Literal["15.0", "16.0"]
CpuModel = Literal["x86", "x64"]
MSPlatform = Literal["Win32", "x64"]
AddressModel = Literal[32, 64]
MSVCInternalVersion = Literal["14.1", "14.2"]
SupportedSystem = Literal["win", "linux"]
here = Path(__file__).parent.resolve()
class LangType(Enum):
CPlusPlus = 1
Java = 2
CSharp = 3
Python = 4
_LangType_to_str: Mapping[LangType, str] ={
LangType.CPlusPlus: "cpp",
LangType.Java: "java",
LangType.CSharp: "CSharp",
LangType.Python : "python",
}
_platform_system_to_system: Mapping[str, SupportedSystem] = {
"Windows": "win",
"Linux": "linux",
}
_vs_ver_to_cmake_option_catalog: Mapping[VisualStudioVersion, Mapping[CpuModel, Sequence[str]]] = {
"15.0": {
"x86": ['-G"Visual Studio 15 2017"'],
"x64": ['-G"Visual Studio 15 2017 Win64"'],
},
"16.0": {
"x86": ['-G"Visual Studio 16 2019"', "-AWin32"],
"x64": ['-G"Visual Studio 16 2019"'],
},
}
_platform_to_ms_form: Mapping[CpuModel, MSPlatform] = {
"x86": "Win32",
"x64": "x64",
}
_platform_to_address_model: Mapping[CpuModel, AddressModel] = {
"x86": 32,
"x64": 64,
}
_vs_to_msvc_internal_ver: Mapping[VisualStudioVersion, MSVCInternalVersion] = {
"15.0": "14.1",
"16.0": "14.2",
}
def get_os() -> SupportedSystem:
pf = platform.system()
if pf not in _platform_system_to_system:
raise RuntimeError
return _platform_system_to_system[pf]
def get_value(dic: Mapping[str, str], key: Optional[str]) -> str:
if key is None:
raise ValueError
if key not in dic:
raise ValueError
return dic[key]
def make_bak(filename: PathLike) -> None:
bak_filename = f"{filename}.bak"
if not os.path.exists(bak_filename):
shutil.copy2(filename, bak_filename)
def restore_from_bak(filename: PathLike) -> None:
bak_filename = f"{filename}.bak"
if os.path.exists(bak_filename):
shutil.copy2(bak_filename, filename)
def get_as_text(filename: PathLike) -> str:
with open(filename, "r", encoding="utf-8") as file:
filedata = file.read()
return filedata
def get_original_text(filename: PathLike) -> str:
bak_filename = f"{filename}.bak"
if os.path.exists(bak_filename):
filename = Path(bak_filename)
text = get_as_text(filename)
return text
def _replace_file_content(
filename: PathLike, replace_text: Callable[[str], str], make_backup: bool
) -> None:
if make_backup:
make_bak(filename)
curr_text = get_as_text(filename)
original_text = get_original_text(filename)
else:
curr_text = original_text = get_as_text(filename)
filedata = replace_text(original_text)
if filedata != curr_text:
with open(filename, "w", encoding="utf-8") as file:
file.write(filedata)
def replace_file_string(
filename: PathLike, pattern_replace: Sequence[Tuple[str, str]], make_backup: bool
) -> None:
def __replace_text(text: str) -> str:
for pattern, replace in pattern_replace:
text = re.sub(pattern, replace, text, flags=re.MULTILINE | re.DOTALL)
return text
_replace_file_content(filename, __replace_text, make_backup)
def insert_line_after(
filename: PathLike, insert_after: Mapping[str, str], make_backup: bool
) -> None:
def __replace_text(text: str) -> str:
new_lines: List[str] = []
lines = text.split("\n")
for line in lines:
new_lines.append(line)
if line in insert_after:
new_lines.append(insert_after[line])
return "\n".join(new_lines) + "\n"
_replace_file_content(filename, __replace_text, make_backup)
def call_subprocess(cmd: Sequence[str], show_info: bool = True) -> None:
try:
_env: Dict[str, str] = {}
_env.update(os.environ)
_CL_env_for_MSVC: Mapping[str, str] = {
"CL": "/source-charset:utf-8 /execution-charset:utf-8"
}
_env.update(_CL_env_for_MSVC)
logging.info(f"pwd={os.path.abspath(os.curdir)}")
def __t(text: str) -> str:
if '"' in text:
return text
if " " in text:
return '"' + text + '"'
return text
cmdline = " ".join([__t(s) for s in cmd if s])
logging.info(cmdline)
if get_os() == "win":
subprocess.check_call(cmdline, env=_env)
else:
subprocess.check_call(cmd, env=_env)
except subprocess.CalledProcessError as e:
logging.warning(e)
sys.exit(e.returncode)
def remove_if_exist(path: Path) -> None:
if path.exists():
if path.is_file():
path.unlink()
elif path.is_dir():
shutil.rmtree(path)
def remove_by_pattern(parent: Path, re_pattern: str, delete_on_match: bool) -> None:
pat = re.compile(re_pattern)
for p in parent.iterdir():
if delete_on_match:
if pat.match(p.name):
remove_if_exist(p)
else:
if not pat.match(p.name):
remove_if_exist(p)
def makefile_to_lines(filename: PathLike) -> Iterable[str]:
lines: List[str] = []
with open(filename, "r") as f:
for line in f.readlines():
if line.endswith("\n"):
line = line[:-1]
if line.endswith("\\"):
lines.append(line[:-1])
else:
lines.append(line)
yield re.sub("[ \\t]+", " ", "".join(lines))
lines = []
def match_and_add(pattern: re.Pattern, dest: List[str], line: str) -> None:
match = pattern.match(line)
if match:
for name in [s.strip() for s in match["name"].split(" ")]:
if name and name != "$(NULL)":
dest.append(name)
def get_value_from_env(env: str, default: Optional[str] = None) -> Optional[str]:
if env not in os.environ:
return default
return os.environ[env]
def get_vs_ver() -> VisualStudioVersion:
env_name = "VisualStudioVersion"
vs_version = get_value_from_env(env_name)
if not vs_version:
raise ValueError(f"{env_name} is empty.")
if vs_version not in typing.get_args(VisualStudioVersion):
raise ValueError(f"Unknown Visual Studio version: {vs_version}.")
return cast(VisualStudioVersion, vs_version)
def get_msvc_internal_ver() -> MSVCInternalVersion:
return _vs_to_msvc_internal_ver[get_vs_ver()]
def load_msbuild_xml(path: PathLike) -> ElementTree:
ns = {"msbuild": "http://schemas.microsoft.com/developer/msbuild/2003"}
ET.register_namespace("", ns["msbuild"])
tree = ET.parse(path)
return tree
def load_nuspec_xml(path: PathLike) -> ElementTree:
ns = {"nuspec": "http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"}
ET.register_namespace("", ns["nuspec"])
tree = ET.parse(path)
return tree
def get_elems(parent: Element, name: str, ns: Optional[str] = None) -> Iterable[Element]:
ns_name = name
if ns is not None:
ns_name = "{" + ns + "}" + ns_name
return (e for e in parent if e.tag == ns_name)
def get_elem(parent: Element, name: str, ns: Optional[str] = None) -> Element:
elms = list(get_elems(parent, name, ns))
if len(elms) != 1:
raise RuntimeError(f"Number of <{name}> is {len(elms)}.")
return elms[0]
class Config:
def __init__(self):
self.this_path: Optional[Path] = None
self.rdkit_path: Optional[Path] = None
self.boost_path: Optional[Path] = None
self.eigen_path: Optional[Path] = None
self.zlib_path: Optional[Path] = None
self.libpng_path: Optional[Path] = None
self.pixman_path: Optional[Path] = None
self.cairo_path: Optional[Path] = None
self.freetype_path: Optional[Path] = None
self.minor_version: int = 1
self.cairo_support: bool = False
self.freetype_support: bool = False
self.swig_patch_enabled: bool = True
self.use_boost: bool = False
self.test_enabled: bool = False
self.limit_external: bool = False
self.use_static_libs: bool = False
self.target_lang: LangType = LangType.CPlusPlus
self.more_functions: bool = False
def to_on_off(flag: bool) -> str:
return "ON" if flag else "OFF"
def get_shared_lib_names(binary_path: Path) -> Iterable[str]:
dependent_dll_names: Set[str] = set()
if get_os() == "win":
cmdline = f"dumpbin.exe /DEPENDENTS {binary_path}"
proc = subprocess.run(cmdline, shell=True, stdout=PIPE, text=True)
if proc.returncode != 0:
raise RuntimeError("Failed to execute dumpbin")
pat = re.compile(" ([a-zA-Z0-9_\\-]+\\.dll) ")
for name in re.findall(pat, proc.stdout, flags=0):
dependent_dll_names.add(name)
elif get_os() == "linux":
cmdline = f"ldd {binary_path}"
proc = subprocess.run(cmdline, shell=True, stdout=PIPE, text=True)
if proc.returncode != 0:
raise RuntimeError("Failed to execute ldd")
pat = re.compile(" ([a-zA-Z0-9_\\-]+\\.so\\.\\d+)\\s+\\=\\>")
for name in re.findall(pat, proc.stdout, flags=0):
dependent_dll_names.add(name)
else:
raise RuntimeError
return dependent_dll_names
def vcxproj_to_vscurr(proj_file: Path) -> None:
ns = "http://schemas.microsoft.com/developer/msbuild/2003"
tree = load_msbuild_xml(proj_file)
project = tree.getroot()
for prop_grp in get_elems(project, "PropertyGroup", ns):
if "Label" in prop_grp.attrib and prop_grp.attrib["Label"] == "Globals":
vc_proj_ver = get_elem(prop_grp, "VCProjectVersion", ns)
vc_proj_ver.text = get_vs_ver()
break
else:
raise RuntimeError(f"VCProjectVersion is missing in {proj_file}")
for prop_grp in get_elems(project, "PropertyGroup", ns):
for elm in prop_grp:
if elm.tag == "{" + ns + "}" + "PlatformToolset":
elm.text = "v" + get_msvc_internal_ver().replace(".", "")
tree.write(proj_file, "utf-8", True)
class NativeMaker:
def __init__(self, config: Config, build_platform: Optional[CpuModel] = None):
self.build_platform: Optional[CpuModel] = build_platform if build_platform else "x64"
self.config: Config = config
@property
def g_option_of_cmake(self) -> Sequence[str]:
if get_os() == "linux":
return ["-GUnix Makefiles"]
if get_os() == "win":
assert self.build_platform
return _vs_ver_to_cmake_option_catalog[get_vs_ver()][self.build_platform]
raise RuntimeError
@property
def build_dir_name(self) -> str:
"""Returns build path. Typically "buildx86".
Returns:
str: Directory name.
"""
assert self.build_platform
return f"build{self.build_platform}"
@property
def build_dir_name_of_rdkit(self) -> str:
"""Returns build path for RDKit. Typically "buildx86winCSharp".
Returns:
str: Directory name.
"""
assert self.build_platform
return f"build{get_os()}{self.build_platform}{_LangType_to_str[self.config.target_lang]}"
@property
def ms_build_platform(self) -> MSPlatform:
assert self.build_platform
return _platform_to_ms_form[self.build_platform]
@property
def address_model(self) -> AddressModel:
assert self.build_platform
return _platform_to_address_model[self.build_platform]
@property
def this_path(self) -> Path:
assert self.config.this_path
return self.config.this_path
@property
def rdkit_path(self) -> Path:
assert self.config.rdkit_path
return self.config.rdkit_path
@property
def boost_path(self) -> Path:
assert self.config.boost_path
return self.config.boost_path
@property
def eigen_path(self) -> Path:
assert self.config.eigen_path
return self.config.eigen_path
@property
def zlib_path(self) -> Path:
assert self.config.zlib_path
return self.config.zlib_path
@property
def libpng_path(self) -> Path:
assert self.config.libpng_path
return self.config.libpng_path
@property
def pixman_path(self) -> Path:
assert self.config.pixman_path
return self.config.pixman_path
@property
def freetype_path(self) -> Path:
assert self.config.freetype_path
return self.config.freetype_path
@property
def cairo_path(self) -> Path:
assert self.config.cairo_path
return self.config.cairo_path
@property
def boost_bin_path(self) -> Path:
return self.boost_path / f"lib{self.address_model}-msvc-{get_msvc_internal_ver()}"
@property
def rdkit_build_path(self) -> Path:
return self.rdkit_path / self.build_dir_name_of_rdkit
@property
def rdkit_wrapper_path(self) -> Path:
dic: Mapping[LangType, str] = {
LangType.Java: "gmwrapper",
LangType.CSharp: "csharp_wrapper",
}
if self.config.target_lang not in dic:
raise AssertionError
return self.rdkit_path / "Code" / "JavaWrappers" / dic[self.config.target_lang]
@property
def rdkit_swig_csharp_path(self) -> Path:
return self.rdkit_wrapper_path / "swig_csharp"
def get_rdkit_version(self) -> int:
return int(re.sub(r".*_(\d\d\d\d)_(\d\d)_(\d)", r"\1\2\3", str(self.config.rdkit_path)))
def get_version_for_nuget(self) -> str:
return f"0.{self.get_rdkit_version()}.{self.config.minor_version}"
def get_version_for_rdkit_dotnetwrap(self) -> str:
num = self.get_rdkit_version()
major, minor, build, revision = (
0,
(num // 10) % 10000,
num % 10,
self.config.minor_version,
)
return f"{major}.{minor}.{build}.{revision}"
def get_version_for_rdkit(self) -> str:
num = self.get_rdkit_version()
return f"{num // 1000}_{('00' + str((num % 1000) // 10))[-2:]}_{num % 10}"
def get_version_for_boost(self) -> str:
return re.sub(r".*(\d+_\d+_\d+)", r"\1", str(self.boost_path))
def get_version_for_eigen(self) -> str:
return re.sub(r".*(\d+\.\d+\.\d+)", r"\1", str(self.eigen_path))
def get_version_for_zlib(self) -> str:
return re.sub(r".*(\d+\.\d+\.\d+)", r"\1", str(self.zlib_path))
def get_version_for_libpng(self) -> str:
return re.sub(r".*lpng(\d)(\d)(\d\d)", r"\1.\2.\3", str(self.libpng_path))
def get_version_for_freetype(self) -> str:
return re.sub(r".*(\d+\.\d+\.\d+)", r"\1", str(self.freetype_path))
def get_version_for_pixman(self) -> str:
return re.sub(r".*(\d+\.\d+\.\d+)", r"\1", str(self.pixman_path))
def get_version_for_cairo(self) -> str:
return re.sub(r".*(\d+\.\d+\.\d+)", r"\1", str(self.cairo_path))
@property
def zlib_lib_path(self):
return (
self.zlib_path
/ self.build_dir_name
/ "Release"
/ ("zlibstatic.lib" if self.config.use_static_libs else "zlib.lib")
)
def run_msbuild(self, proj: Union[PathLike, str], platform: Optional[str] = None) -> None:
if not platform:
platform = self.ms_build_platform
cmd = [
"MSBuild",
str(proj),
f"/p:Configuration=Release,Platform={platform}",
"/maxcpucount",
]
call_subprocess(cmd)
def make_zlib(self) -> None:
build_path = self.zlib_path / self.build_dir_name
build_path.mkdir(exist_ok=True)
_curdir = os.path.abspath(os.curdir)
try:
os.chdir(build_path)
cmd = ["cmake", str(self.zlib_path)] + list(self.g_option_of_cmake)
call_subprocess(cmd)
self.run_msbuild("zlib.sln")
shutil.copy2(build_path / "zconf.h", self.zlib_path)
finally:
os.chdir(_curdir)
def make_libpng(self) -> None:
build_path = self.libpng_path / self.build_dir_name
build_path.mkdir(exist_ok=True)
_curdir = os.path.abspath(os.curdir)
try:
os.chdir(build_path)
cmd = (
["cmake", str(self.libpng_path)]
+ list(self.g_option_of_cmake)
+ [
f'-DZLIB_LIBRARY="{str(self.zlib_lib_path)}"',
f'-DZLIB_INCLUDE_DIR="{str(self.zlib_path)}"',
f"-DPNG_SHARED={to_on_off(not self.config.use_static_libs)}",
f"-DPNG_STATIC={to_on_off(self.config.use_static_libs)}",
]
)
call_subprocess(cmd)
self.run_msbuild("libpng.sln")
finally:
os.chdir(_curdir)
def make_pixman(self) -> None:
_curdir = os.path.abspath(os.curdir)
try:
proj_dir = self.pixman_path / "vc2017"
proj_dir.mkdir(exist_ok=True)
os.chdir(proj_dir)
files_dir = self.this_path / "files" / "pixman"
vcxproj = "pixman.vcxproj"
shutil.copy2(files_dir / vcxproj, proj_dir)
proj_file = proj_dir / vcxproj
shutil.copy2(files_dir / "config.h", self.pixman_path / "pixman")
vcxproj_to_vscurr(proj_file)
makefile_win32 = self.pixman_path / "pixman" / "Makefile.win32"
makefile_sources = self.pixman_path / "pixman" / "Makefile.sources"
c_files: List[str] = []
i_files: List[str] = []
pattern_c = re.compile("^libpixman_sources\\s*\\=(?P<name>.*)$")
pattern_h = re.compile("^libpixman_headers\\s*\\=(?P<name>.*)$")
for line in makefile_to_lines(makefile_sources):
match_and_add(pattern_c, c_files, line)
match_and_add(pattern_h, i_files, line)
pattern_c = re.compile("^\\s*libpixman_sources\\s*\\+\\=(?P<name>.*)$")
for line in makefile_to_lines(makefile_win32):
match_and_add(pattern_c, c_files, line)
tree = load_msbuild_xml(proj_file)
root = tree.getroot()
item_group = SubElement(root, "ItemGroup")
for name in c_files:
node = SubElement(item_group, "ClCompile")
node.attrib["Include"] = f"..\\pixman\\{name}"
for name in i_files:
node = SubElement(item_group, "ClInclude")
node.attrib["Include"] = f"..\\pixman\\{name}"
tree.write(proj_file, "utf-8", True)
self.run_msbuild(proj_file)
finally:
os.chdir(_curdir)
def make_cairo(self) -> None:
# TODO: get file names from src\Makefile.sources
_curdir = os.path.abspath(os.curdir)
try:
proj_dir = self.cairo_path / "vc2017"
proj_dir.mkdir(exist_ok=True)
os.chdir(proj_dir)
files_dir = self.this_path / "files" / "cairo"
vcxproj = "cairo.vcxproj"
shutil.copy2(files_dir / vcxproj, proj_dir)
proj_file = proj_dir / vcxproj
shutil.copy2(files_dir / "cairo-features.h", self.cairo_path / "src")
vcxproj_to_vscurr(proj_file)
replace_file_string(
proj_file,
[
(
"__CAIRODIR__",
str(self.cairo_path).replace("\\", "\\\\"),
),
(
"__LIBPNGDIR__",
str(self.libpng_path).replace("\\", "\\\\"),
),
(
"__ZLIBDIR__",
str(self.zlib_path).replace("\\", "\\\\"),
),
(
"__PIXMANDIR__",
str(self.pixman_path).replace("\\", "\\\\"),
),
(
"__FREETYPEDIR__",
str(self.freetype_path).replace("\\", "\\\\"),
),
],
make_backup=False,
)
self.run_msbuild(vcxproj)
finally:
os.chdir(_curdir)
def make_freetype(self) -> None:
_curdir = os.path.abspath(os.curdir)
try:
os.chdir(self.freetype_path)
shutil.copy2(
self.this_path / "files" / "freetype" / "freetype.vcxproj",
self.freetype_path / "builds" / "windows" / "vc2010",
)
os.chdir(self.freetype_path / "builds" / "windows" / "vc2010")
logging.debug(f"current dir = {os.getcwd()}")
self.run_msbuild("freetype.sln")
finally:
os.chdir(_curdir)
@property
def path_streams_cpp(self) -> Path:
return self.rdkit_path / "Code" / "RDStreams" / "streams.cpp"
@property
def path_streams_h(self) -> Path:
return self.rdkit_path / "Code" / "RDStreams" / "streams.h"
@property
def path_GraphMolCSharp_i(self) -> Path:
return self.rdkit_wrapper_path / "GraphMolCSharp.i"
@property
def path_Descriptors_i(self) -> Path:
return self.rdkit_path / "Code" / "JavaWrappers" / "Descriptors.i"
@property
def path_MolDescriptors_h(self) -> Path:
return self.rdkit_path / "Code" / "GraphMol" / "Descriptors" / "MolDescriptors.h"
@property
def path_MolSupplier_i(self) -> Path:
return self.rdkit_path / "Code" / "JavaWrappers" / "MolSupplier.i"
@property
def path_Streams_i(self) -> Path:
return self.rdkit_path / "Code" / "JavaWrappers" / "Streams.i"
@property
def path_MolDraw2D_i(self) -> Path:
return self.rdkit_path / "Code" / "JavaWrappers" / "MolDraw2D.i"
@property
def path_MolDraw2D_h(self) -> Path:
return self.rdkit_path / "Code" / "GraphMol" / "MolDraw2D" / "MolDraw2D.h"
@property
def _path_csharp_wrapper_CMakeLists_txt(self) -> Path:
return self.rdkit_path / "Code" / "JavaWrappers" / "csharp_wrapper" / "CMakeLists.txt"
@property
def bakable_files(self) -> Iterable[Path]:
return [
self.path_streams_cpp,
self.path_streams_h,
self.path_GraphMolCSharp_i,
self.path_Descriptors_i,
self.path_MolDescriptors_h,
self.path_MolSupplier_i,
self.path_Streams_i,
self.path_MolDraw2D_i,
self.path_MolDraw2D_h,
self._path_csharp_wrapper_CMakeLists_txt,
]
@property
def path_RDKit2DotNet_folder(self):
return self.rdkit_wrapper_path / "RDKit2DotNet"
def build_cmake_rdkit(self) -> Sequence[str]:
self.rdkit_build_path.mkdir(exist_ok=True)
_curdir = os.path.abspath(os.curdir)
os.chdir(self.rdkit_build_path)
try:
self._patch_i_files()
cmd = self._make_rdkit_cmake()
return cmd
finally:
os.chdir(_curdir)
def build_rdkit(self) -> None:
self.rdkit_build_path.mkdir(exist_ok=True)
_curdir = os.path.abspath(os.curdir)
os.chdir(self.rdkit_build_path)
try:
if get_os() == "win":
self.run_msbuild("RDKit.sln")
else:
cmd = ["make", "-j"]
if self.config.target_lang in (LangType.CPlusPlus,):
pass
elif self.config.target_lang in (LangType.CSharp,):
cmd += ["RDKFuncs"]
elif self.config.target_lang in (LangType.Java,):
cmd += ["install"]
else:
raise AssertionError
call_subprocess(cmd)
finally:
os.chdir(_curdir)
def copy_rdkit_dlls(self) -> None:
self._copy_dlls()
def _patch_GraphMolCSharp_i(self):
dic: Dict[str, str] = dict()
_line = r"%shared_ptr(RDKit::QueryOps)"
_insert = r"%shared_ptr(RDKit::MolBundle)" + "\n"
_insert += r"%shared_ptr(RDKit::FixedMolSizeMolBundle)"
dic.update({_line: _insert})
_line = r"%shared_ptr(RDKit::SmilesParseException)"
_insert = r"%shared_ptr(RDKit::MolPicklerException)"
dic.update({_line: _insert})
_line = r'%include "../QueryOps.i"'
_insert = r'%include "../MolBundle.i"'
dic.update({_line: _insert})
_line = r'%include "../Trajectory.i"'
_insert = r'%include "../MolStandardize.i"'
dic.update({_line: _insert})
_line = r'%include "../SubstanceGroup.i"'
_insert = r'%include "../MolEnumerator.i"'
dic.update({_line: _insert})
insert_line_after(self.path_GraphMolCSharp_i, dic, make_backup=True)
if self.config.swig_patch_enabled and self.get_rdkit_version() < 2021032:
replace_file_string(
self.path_GraphMolCSharp_i,
[("boost::int32_t", "int32_t"), ("boost::uint32_t", "uint32_t")],
make_backup=False, # backed up above
)
def _patch_MolDraw2D_i(self):
dic: Dict[str, str] = dict()
_svg_h = "<GraphMol/MolDraw2D/MolDraw2DSVG.h>"
_cairo_h = "<GraphMol/MolDraw2D/MolDraw2DCairo.h>"
_line = f"#include {_svg_h}"
_insert = f"\n#ifdef RDK_BUILD_CAIRO_SUPPORT\n#include {_cairo_h}\n#endif\n"
dic.update({_line: _insert})
_line = f"%include {_svg_h}"
_insert = f"\n#ifdef RDK_BUILD_CAIRO_SUPPORT\n%include {_cairo_h}\n#endif\n"
dic.update({_line: _insert})
_line = "%template(Int_Vect_Vect) std::vector<std::vector<int> >;"
_insert = "\n"
_insert += "%template(UInt_Vect_Vect) std::vector<std::vector<unsigned int> >;\n"
_insert += "%template(Double_Vect_Vect) std::vector<std::vector<double> >;\n"
_insert += "%template(Point3D_Const_Vect) std::vector<const RDGeom::Point3D *>;\n"
_insert += "%template(Point3D_Val_Vect) std::vector<RDGeom::Point3D>;\n"
insert_line_after(self.path_MolDraw2D_i, dic, make_backup=True)
def _patch_MolDraw2D_h(self) -> None:
dic: Dict[str, str] = dict()
_line = r" const MolDrawOptions &drawOptions() const { return options_; }"
_insert = (
r"void setDrawOptions(const RDKit::MolDrawOptions &opts) { drawOptions() = opts; }"
)
dic.update({_line: _insert})
insert_line_after(self.path_MolDraw2D_h, dic, make_backup=True)
def _patch_MolDescriptors_h(self) -> None:
dic: Dict[str, str] = dict()
_line = r"SET(CMAKE_SWIG_OUTDIR ${CMAKE_CURRENT_SOURCE_DIR}/swig_csharp )"
_inserts = [
"if(RDK_BUILD_DESCRIPTORS3D)"
"SET(CMAKE_SWIG_FLAGS \"-DRDK_BUILD_DESCRIPTORS3D\" \"-DRDK_HAS_EIGEN3\" ${CMAKE_SWIG_FLAGS} )",
"endif()",
"if(RDK_BUILD_CAIRO_SUPPORT)",
"SET(CMAKE_SWIG_FLAGS \"-DRDK_BUILD_CAIRO_SUPPORT\" ${CMAKE_SWIG_FLAGS} )",
"endif()",
]
_insert = "\n" + "\n".join(_inserts) + "\n"
dic.update({_line: _insert})
insert_line_after(self._path_csharp_wrapper_CMakeLists_txt, dic, make_backup=True)
_line = r"#include <GraphMol/Descriptors/MolDescriptors.h>"
_inserts = [
"#include <GraphMol/Descriptors/AtomFeat.h>",
"#include <GraphMol/Descriptors/USRDescriptor.h>",
"#include <GraphMol/Depictor/RDDepictor.h>",
"#ifdef RDK_BUILD_DESCRIPTORS3D",
"#include <GraphMol/Descriptors/MolDescriptors3D.h>",
"#endif",
]
_insert = "\n" + "\n".join(_inserts) + "\n"
dic.update({_line: _insert})
_line = r"%include <GraphMol/Descriptors/MQN.h>"
_inserts = [
"%include <GraphMol/Descriptors/AUTOCORR2D.h>",
"%include <GraphMol/Descriptors/AtomFeat.h>",
"%include <GraphMol/Descriptors/USRDescriptor.h>",
"%include <GraphMol/Depictor/RDDepictor.h>",
"#ifdef RDK_HAS_EIGEN3",
"%include <GraphMol/Descriptors/BCUT.h>",
"#endif",
"#ifdef RDK_BUILD_DESCRIPTORS3D",
"%include <GraphMol/Descriptors/CoulombMat.h>",
"%include <GraphMol/Descriptors/EEM.h>",
"%include <GraphMol/Descriptors/PBF.h>",
"%include <GraphMol/Descriptors/RDF.h>",
"%include <GraphMol/Descriptors/MORSE.h>",
"%include <GraphMol/Descriptors/WHIM.h>",
"%include <GraphMol/Descriptors/GETAWAY.h>",
"%include <GraphMol/Descriptors/AUTOCORR3D.h>",
"%include <GraphMol/Descriptors/PMI.h>",
"#endif",
]
_insert = "\n" + "\n".join(_inserts) + "\n"
dic.update({_line: _insert})
insert_line_after(self.path_Descriptors_i, dic, make_backup=True)
dic = dict()
_line = "#include <GraphMol/Descriptors/MQN.h>"
_insert = "#include <GraphMol/Descriptors/BCUT.h>"
dic.update({_line: _insert})
insert_line_after(self.path_MolDescriptors_h, dic, make_backup=True)
def _patch_MolSupplier_i(self):
__t0 = "%extend RDKit::ForwardSDMolSupplier {\n"
__t1 = "};\n"
replace_file_string(
self.path_MolSupplier_i,
[
(__t0, "#ifdef RDK_USE_BOOST_IOSTREAMS\n" + __t0),
(__t1, __t1 + "#endif\n"),
],
make_backup=True,
)
def _patch_Streams_i(self):
__t2 = "%extend RDKit::gzstream {\n"
__t3 = "%include <../RDStreams/streams.h>"
replace_file_string(
self.path_Streams_i,
[
(__t2, "#ifdef RDK_USE_BOOST_IOSTREAMS\n" + __t2),
(__t3, "#endif\n" + __t3),
],
make_backup=True,
)
def _patch_i_files(self):
if self.config.target_lang == LangType.CSharp:
if self.config.more_functions:
self._patch_GraphMolCSharp_i()
self._patch_MolDraw2D_i()
self._patch_MolDraw2D_h()
if self.config.more_functions:
self._patch_MolDescriptors_h()
self._patch_MolSupplier_i()
self._patch_Streams_i()
def _make_rdkit_cmake(self) -> Sequence[str]:
cmd: List[str] = self._get_cmake_rdkit_cmd_line()
if get_os() == "win":
cmd = [a.replace("\\", "/") for a in cmd]
call_subprocess(cmd)
return cmd
def _get_cmake_rdkit_cmd_line(self) -> List[str]:
def f_test() -> str:
return to_on_off(self.config.test_enabled)
def f_boost() -> str:
return to_on_off(self.config.use_boost)
def f_no_limit_external() -> str:
return to_on_off(not self.config.limit_external)
args = [f"{str(self.rdkit_path)}"]
args += ["-Wdev"]
args += self.g_option_of_cmake
if self.config.target_lang == LangType.CPlusPlus:
args += [
"-DRDK_BUILD_SWIG_WRAPPERS=OFF",
"-DRDK_BUILD_SWIG_CSHARP_WRAPPER=OFF",
"-DRDK_BUILD_SWIG_JAVA_WRAPPER=OFF",
"-DRDK_BUILD_PYTHON_WRAPPERS=OFF",
]
elif self.config.target_lang == LangType.CSharp:
args += [
"-DRDK_BUILD_SWIG_WRAPPERS=ON",
"-DRDK_BUILD_SWIG_CSHARP_WRAPPER=ON",
"-DRDK_BUILD_SWIG_JAVA_WRAPPER=OFF",
"-DRDK_BUILD_PYTHON_WRAPPERS=OFF",
]
elif self.config.target_lang == LangType.Java:
args += [
"-DRDK_BUILD_SWIG_WRAPPERS=ON",
"-DRDK_BUILD_SWIG_CSHARP_WRAPPER=OFF",
"-DRDK_BUILD_SWIG_JAVA_WRAPPER=ON",
"-DRDK_BUILD_PYTHON_WRAPPERS=OFF",
]
else:
raise RuntimeError(f"Not supported. {self.config.target_lang}")
if self.config.boost_path:
args += [
f"-DBOOST_ROOT={str(self.boost_path)}",
f"-DBOOST_INCLUDEDIR={str(self.boost_path)}",
f"-DBOOST_LIBRARYDIR={str(self.boost_bin_path)}",
]
if self.config.eigen_path:
args += [f"-DEIGEN3_INCLUDE_DIR={str(self.eigen_path)}"]
if self.config.zlib_path:
zlib_lib_path = (
self.zlib_path
/ self.build_dir_name
/ "Release"
/ ("zlibstatic.lib" if self.config.use_static_libs else "zlib.lib")
)
args += [
f'-DZLIB_LIBRARIES="{zlib_lib_path}"',
f'-DZLIB_INCLUDE_DIRS="{self.zlib_path}"',
]
if self.config.cairo_support:
if self.config.cairo_path:
cairo_lib_path = (
self.cairo_path / "vc2017" / self.ms_build_platform / "Release" / "cairo.lib"
)
args += [
f'-DCAIRO_INCLUDE_DIRS={self.cairo_path / "src"}',
f"-DCAIRO_LIBRARIES={cairo_lib_path}",
]
args += [
"-DRDK_INSTALL_INTREE=ON",
f"-DRDK_BUILD_CPP_TESTS={f_test()}",
f"-DRDK_USE_BOOST_SERIALIZATION={f_boost()}",
f"-DRDK_USE_BOOST_IOSTREAMS={f_boost()}",
f"-DRDK_USE_BOOST_REGEX={f_boost()}",
"-DBoost_NO_BOOST_CMAKE=ON",
f"-DRDK_BUILD_COORDGEN_SUPPORT={f_no_limit_external()}",
f"-DRDK_BUILD_MAEPARSER_SUPPORT={f_no_limit_external()}",
"-DRDK_OPTIMIZE_POPCNT=ON",
f"-DRDK_BUILD_FREESASA_SUPPORT={f_no_limit_external()}",
f"-DRDK_BUILD_CAIRO_SUPPORT={to_on_off(self.config.cairo_support)}",
f"-DRDK_BUILD_FREETYPE_SUPPORT={to_on_off(self.config.cairo_support)}",
"-DRDK_BUILD_THREADSAFE_SSS=ON",
f"-DRDK_BUILD_INCHI_SUPPORT={f_no_limit_external()}",
f"-DRDK_BUILD_AVALON_SUPPORT={f_no_limit_external()}",
# do not install comic fonts because of incorrect md5 checksum.
# see https://salsa.debian.org/debichem-team/rdkit/-/commit/15da2bc1796c507e0c3afa36eecfc1961d16c13e # NOQA
"-DRDK_INSTALL_COMIC_FONTS=OFF",
f"-DRDK_BUILD_TEST_GZIP={f_test()}",
]
if self.get_rdkit_version() >= 2020091: