├── .github └── workflows │ └── gradle-javacpp.yml ├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── LICENSE.txt ├── README.md ├── build.gradle ├── samples ├── javacv-demo-kotlin │ ├── build.gradle.kts │ ├── settings.gradle.kts │ └── src │ │ └── main │ │ └── kotlin │ │ └── org.bytedeco.javacv.samples │ │ └── Demo.kt ├── javacv-demo │ ├── build.gradle │ ├── settings.gradle │ └── src │ │ └── main │ │ └── java │ │ └── org │ │ └── bytedeco │ │ └── javacv │ │ └── samples │ │ └── Demo.java └── zlib │ ├── build.gradle │ ├── build.sh │ ├── settings.gradle │ └── src │ ├── main │ └── java │ │ └── org │ │ └── bytedeco │ │ └── zlib │ │ └── presets │ │ └── zlib.java │ └── test │ └── java │ └── org │ └── bytedeco │ └── zlib │ └── UnitTest.java ├── settings.gradle └── src ├── main └── java │ └── org │ └── bytedeco │ └── gradle │ └── javacpp │ ├── BuildExecutor.java │ ├── BuildExtension.java │ ├── BuildPlugin.java │ ├── BuildTask.java │ ├── PlatformPlugin.java │ └── PlatformRule.java └── test └── java └── org └── bytedeco └── gradle └── javacpp ├── BuildPluginTest.java └── PlatformPluginTest.java /.github/workflows/gradle-javacpp.yml: -------------------------------------------------------------------------------- 1 | name: gradle-javacpp 2 | on: [push, pull_request, workflow_dispatch] 3 | env: 4 | CI_DEPLOY_MODULE: . 5 | CI_DEPLOY_NEED_GRADLE: 1 6 | CI_DEPLOY_PLATFORM: ${{ github.job }} 7 | CI_DEPLOY_SETTINGS: ${{ secrets.CI_DEPLOY_SETTINGS }} 8 | CI_DEPLOY_USERNAME: ${{ secrets.CI_DEPLOY_USERNAME }} 9 | CI_DEPLOY_PASSWORD: ${{ secrets.CI_DEPLOY_PASSWORD }} 10 | STAGING_REPOSITORY: ${{ secrets.STAGING_REPOSITORY }} 11 | jobs: 12 | linux-x86_64: 13 | runs-on: ubuntu-20.04 14 | steps: 15 | - uses: bytedeco/javacpp-presets/.github/actions/deploy-ubuntu@actions 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | **/.gradle/** 2 | **/build/** 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: xenial 2 | before_cache: 3 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock 4 | - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ 5 | cache: 6 | directories: 7 | - $HOME/.m2/repository/ 8 | - $HOME/.gradle/caches/ 9 | - $HOME/.gradle/wrapper/ 10 | language: java 11 | jdk: openjdk8 12 | 13 | before_install: 14 | - > 15 | if [[ "$TRAVIS_PULL_REQUEST" != "false" ]]; then 16 | export GRADLE_PUBLISH="publishToMavenLocal"; 17 | elif [[ "$TRAVIS_BRANCH" != "release" ]]; then 18 | export GRADLE_PUBLISH="publish"; 19 | else 20 | curl -L "https://drive.google.com/uc?export=download&id=$GDOWNLOAD_ID" -o $HOME/settings.tar.gz; 21 | tar -xzf $HOME/settings.tar.gz -C $HOME; 22 | export GNUPGHOME="$HOME/.gnupg/"; 23 | export GRADLE_PUBLISH="publish"; 24 | fi 25 | 26 | script: 27 | - gradle build $GRADLE_PUBLISH --info 28 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 2 | ### January 29, 2024 version 1.5.10 3 | * Fix compatibility with Gradle 8.x ([pull #31](https://github.com/bytedeco/gradle-javacpp/issues/31)) 4 | 5 | ### June 6, 2023 version 1.5.9 6 | * Fix compatibility with Gradle 7.6.x ([issue #28](https://github.com/bytedeco/gradle-javacpp/issues/28)) 7 | 8 | ### November 2, 2022 version 1.5.8 9 | * Remove lambda expressions since Gradle dislikes them ([issue #23](https://github.com/bytedeco/gradle-javacpp/issues/23)) 10 | * Update instructions to integrate `BuildTask` with Android Studio ([issue #22](https://github.com/bytedeco/gradle-javacpp/issues/22)) 11 | 12 | ### February 11, 2022 version 1.5.7 13 | * Update README.md with sample `javacppExtract` task for Android App Bundles (AABs) 14 | 15 | ### August 2, 2021 version 1.5.6 16 | * Fix compatibility with Gradle 7.x ([issue #17](https://github.com/bytedeco/gradle-javacpp/issues/17)) 17 | * Make `BuildTask` properties `public` to allow access with Kotlin DSL ([pull #16](https://github.com/bytedeco/gradle-javacpp/issues/16)) 18 | * Fix `BuildPlugin` incorrectly resetting `javacppBuildParser.outputDirectory` in subprojects ([pull #12](https://github.com/bytedeco/gradle-javacpp/issues/12)) 19 | 20 | ### March 8, 2021 version 1.5.5 21 | * Add `javacppPlatformExtension` property to `BuildPlugin` and map it to `platform.extension` property 22 | * Add instructions to integrate `BuildTask` with Android Studio ([issue #5](https://github.com/bytedeco/gradle-javacpp/issues/5)) 23 | * Fix `PlatformPlugin` evaluating `javacppPlatform` too early ([issue #8](https://github.com/bytedeco/gradle-javacpp/issues/8)) 24 | * Honor the `skip` property in `BuildTask` ([pull #7](https://github.com/bytedeco/gradle-javacpp/issues/7)) 25 | * Add `BuildExtension` helper for `maven-publish` and update zlib sample project 26 | * Add builds for Android to zlib sample project ([issue #5](https://github.com/bytedeco/gradle-javacpp/issues/5)) 27 | 28 | ### September 9, 2020 version 1.5.4 29 | * Initial release 30 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | You may use this work under the terms of either the Apache License, 2 | Version 2.0, or the GNU General Public License (GPL), either version 2, 3 | or any later version, with "Classpath" exception (details below). 4 | 5 | You don't have to do anything special to choose one license or the other 6 | and you don't have to notify anyone which license you are using. You are 7 | free to use this work in any project (even commercial projects) as long 8 | as the copyright header is left intact. 9 | 10 | =============================================================================== 11 | 12 | Apache License 13 | Version 2.0, January 2004 14 | http://www.apache.org/licenses/ 15 | 16 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 17 | 18 | 1. Definitions. 19 | 20 | "License" shall mean the terms and conditions for use, reproduction, 21 | and distribution as defined by Sections 1 through 9 of this document. 22 | 23 | "Licensor" shall mean the copyright owner or entity authorized by 24 | the copyright owner that is granting the License. 25 | 26 | "Legal Entity" shall mean the union of the acting entity and all 27 | other entities that control, are controlled by, or are under common 28 | control with that entity. For the purposes of this definition, 29 | "control" means (i) the power, direct or indirect, to cause the 30 | direction or management of such entity, whether by contract or 31 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 32 | outstanding shares, or (iii) beneficial ownership of such entity. 33 | 34 | "You" (or "Your") shall mean an individual or Legal Entity 35 | exercising permissions granted by this License. 36 | 37 | "Source" form shall mean the preferred form for making modifications, 38 | including but not limited to software source code, documentation 39 | source, and configuration files. 40 | 41 | "Object" form shall mean any form resulting from mechanical 42 | transformation or translation of a Source form, including but 43 | not limited to compiled object code, generated documentation, 44 | and conversions to other media types. 45 | 46 | "Work" shall mean the work of authorship, whether in Source or 47 | Object form, made available under the License, as indicated by a 48 | copyright notice that is included in or attached to the work 49 | (an example is provided in the Appendix below). 50 | 51 | "Derivative Works" shall mean any work, whether in Source or Object 52 | form, that is based on (or derived from) the Work and for which the 53 | editorial revisions, annotations, elaborations, or other modifications 54 | represent, as a whole, an original work of authorship. For the purposes 55 | of this License, Derivative Works shall not include works that remain 56 | separable from, or merely link (or bind by name) to the interfaces of, 57 | the Work and Derivative Works thereof. 58 | 59 | "Contribution" shall mean any work of authorship, including 60 | the original version of the Work and any modifications or additions 61 | to that Work or Derivative Works thereof, that is intentionally 62 | submitted to Licensor for inclusion in the Work by the copyright owner 63 | or by an individual or Legal Entity authorized to submit on behalf of 64 | the copyright owner. For the purposes of this definition, "submitted" 65 | means any form of electronic, verbal, or written communication sent 66 | to the Licensor or its representatives, including but not limited to 67 | communication on electronic mailing lists, source code control systems, 68 | and issue tracking systems that are managed by, or on behalf of, the 69 | Licensor for the purpose of discussing and improving the Work, but 70 | excluding communication that is conspicuously marked or otherwise 71 | designated in writing by the copyright owner as "Not a Contribution." 72 | 73 | "Contributor" shall mean Licensor and any individual or Legal Entity 74 | on behalf of whom a Contribution has been received by Licensor and 75 | subsequently incorporated within the Work. 76 | 77 | 2. Grant of Copyright License. Subject to the terms and conditions of 78 | this License, each Contributor hereby grants to You a perpetual, 79 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 80 | copyright license to reproduce, prepare Derivative Works of, 81 | publicly display, publicly perform, sublicense, and distribute the 82 | Work and such Derivative Works in Source or Object form. 83 | 84 | 3. Grant of Patent License. Subject to the terms and conditions of 85 | this License, each Contributor hereby grants to You a perpetual, 86 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 87 | (except as stated in this section) patent license to make, have made, 88 | use, offer to sell, sell, import, and otherwise transfer the Work, 89 | where such license applies only to those patent claims licensable 90 | by such Contributor that are necessarily infringed by their 91 | Contribution(s) alone or by combination of their Contribution(s) 92 | with the Work to which such Contribution(s) was submitted. If You 93 | institute patent litigation against any entity (including a 94 | cross-claim or counterclaim in a lawsuit) alleging that the Work 95 | or a Contribution incorporated within the Work constitutes direct 96 | or contributory patent infringement, then any patent licenses 97 | granted to You under this License for that Work shall terminate 98 | as of the date such litigation is filed. 99 | 100 | 4. Redistribution. You may reproduce and distribute copies of the 101 | Work or Derivative Works thereof in any medium, with or without 102 | modifications, and in Source or Object form, provided that You 103 | meet the following conditions: 104 | 105 | (a) You must give any other recipients of the Work or 106 | Derivative Works a copy of this License; and 107 | 108 | (b) You must cause any modified files to carry prominent notices 109 | stating that You changed the files; and 110 | 111 | (c) You must retain, in the Source form of any Derivative Works 112 | that You distribute, all copyright, patent, trademark, and 113 | attribution notices from the Source form of the Work, 114 | excluding those notices that do not pertain to any part of 115 | the Derivative Works; and 116 | 117 | (d) If the Work includes a "NOTICE" text file as part of its 118 | distribution, then any Derivative Works that You distribute must 119 | include a readable copy of the attribution notices contained 120 | within such NOTICE file, excluding those notices that do not 121 | pertain to any part of the Derivative Works, in at least one 122 | of the following places: within a NOTICE text file distributed 123 | as part of the Derivative Works; within the Source form or 124 | documentation, if provided along with the Derivative Works; or, 125 | within a display generated by the Derivative Works, if and 126 | wherever such third-party notices normally appear. The contents 127 | of the NOTICE file are for informational purposes only and 128 | do not modify the License. You may add Your own attribution 129 | notices within Derivative Works that You distribute, alongside 130 | or as an addendum to the NOTICE text from the Work, provided 131 | that such additional attribution notices cannot be construed 132 | as modifying the License. 133 | 134 | You may add Your own copyright statement to Your modifications and 135 | may provide additional or different license terms and conditions 136 | for use, reproduction, or distribution of Your modifications, or 137 | for any such Derivative Works as a whole, provided Your use, 138 | reproduction, and distribution of the Work otherwise complies with 139 | the conditions stated in this License. 140 | 141 | 5. Submission of Contributions. Unless You explicitly state otherwise, 142 | any Contribution intentionally submitted for inclusion in the Work 143 | by You to the Licensor shall be under the terms and conditions of 144 | this License, without any additional terms or conditions. 145 | Notwithstanding the above, nothing herein shall supersede or modify 146 | the terms of any separate license agreement you may have executed 147 | with Licensor regarding such Contributions. 148 | 149 | 6. Trademarks. This License does not grant permission to use the trade 150 | names, trademarks, service marks, or product names of the Licensor, 151 | except as required for reasonable and customary use in describing the 152 | origin of the Work and reproducing the content of the NOTICE file. 153 | 154 | 7. Disclaimer of Warranty. Unless required by applicable law or 155 | agreed to in writing, Licensor provides the Work (and each 156 | Contributor provides its Contributions) on an "AS IS" BASIS, 157 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 158 | implied, including, without limitation, any warranties or conditions 159 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 160 | PARTICULAR PURPOSE. You are solely responsible for determining the 161 | appropriateness of using or redistributing the Work and assume any 162 | risks associated with Your exercise of permissions under this License. 163 | 164 | 8. Limitation of Liability. In no event and under no legal theory, 165 | whether in tort (including negligence), contract, or otherwise, 166 | unless required by applicable law (such as deliberate and grossly 167 | negligent acts) or agreed to in writing, shall any Contributor be 168 | liable to You for damages, including any direct, indirect, special, 169 | incidental, or consequential damages of any character arising as a 170 | result of this License or out of the use or inability to use the 171 | Work (including but not limited to damages for loss of goodwill, 172 | work stoppage, computer failure or malfunction, or any and all 173 | other commercial damages or losses), even if such Contributor 174 | has been advised of the possibility of such damages. 175 | 176 | 9. Accepting Warranty or Additional Liability. While redistributing 177 | the Work or Derivative Works thereof, You may choose to offer, 178 | and charge a fee for, acceptance of support, warranty, indemnity, 179 | or other liability obligations and/or rights consistent with this 180 | License. However, in accepting such obligations, You may act only 181 | on Your own behalf and on Your sole responsibility, not on behalf 182 | of any other Contributor, and only if You agree to indemnify, 183 | defend, and hold each Contributor harmless for any liability 184 | incurred by, or claims asserted against, such Contributor by reason 185 | of your accepting any such warranty or additional liability. 186 | 187 | END OF TERMS AND CONDITIONS 188 | 189 | APPENDIX: How to apply the Apache License to your work. 190 | 191 | To apply the Apache License to your work, attach the following 192 | boilerplate notice, with the fields enclosed by brackets "[]" 193 | replaced with your own identifying information. (Don't include 194 | the brackets!) The text should be enclosed in the appropriate 195 | comment syntax for the file format. We also recommend that a 196 | file or class name and description of purpose be included on the 197 | same "printed page" as the copyright notice for easier 198 | identification within third-party archives. 199 | 200 | Copyright [yyyy] [name of copyright owner] 201 | 202 | Licensed under the Apache License, Version 2.0 (the "License"); 203 | you may not use this file except in compliance with the License. 204 | You may obtain a copy of the License at 205 | 206 | http://www.apache.org/licenses/LICENSE-2.0 207 | 208 | Unless required by applicable law or agreed to in writing, software 209 | distributed under the License is distributed on an "AS IS" BASIS, 210 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 211 | See the License for the specific language governing permissions and 212 | limitations under the License. 213 | 214 | =============================================================================== 215 | 216 | GNU GENERAL PUBLIC LICENSE 217 | Version 2, June 1991 218 | 219 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 220 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 221 | Everyone is permitted to copy and distribute verbatim copies 222 | of this license document, but changing it is not allowed. 223 | 224 | Preamble 225 | 226 | The licenses for most software are designed to take away your 227 | freedom to share and change it. By contrast, the GNU General Public 228 | License is intended to guarantee your freedom to share and change free 229 | software--to make sure the software is free for all its users. This 230 | General Public License applies to most of the Free Software 231 | Foundation's software and to any other program whose authors commit to 232 | using it. (Some other Free Software Foundation software is covered by 233 | the GNU Lesser General Public License instead.) You can apply it to 234 | your programs, too. 235 | 236 | When we speak of free software, we are referring to freedom, not 237 | price. Our General Public Licenses are designed to make sure that you 238 | have the freedom to distribute copies of free software (and charge for 239 | this service if you wish), that you receive source code or can get it 240 | if you want it, that you can change the software or use pieces of it 241 | in new free programs; and that you know you can do these things. 242 | 243 | To protect your rights, we need to make restrictions that forbid 244 | anyone to deny you these rights or to ask you to surrender the rights. 245 | These restrictions translate to certain responsibilities for you if you 246 | distribute copies of the software, or if you modify it. 247 | 248 | For example, if you distribute copies of such a program, whether 249 | gratis or for a fee, you must give the recipients all the rights that 250 | you have. You must make sure that they, too, receive or can get the 251 | source code. And you must show them these terms so they know their 252 | rights. 253 | 254 | We protect your rights with two steps: (1) copyright the software, and 255 | (2) offer you this license which gives you legal permission to copy, 256 | distribute and/or modify the software. 257 | 258 | Also, for each author's protection and ours, we want to make certain 259 | that everyone understands that there is no warranty for this free 260 | software. If the software is modified by someone else and passed on, we 261 | want its recipients to know that what they have is not the original, so 262 | that any problems introduced by others will not reflect on the original 263 | authors' reputations. 264 | 265 | Finally, any free program is threatened constantly by software 266 | patents. We wish to avoid the danger that redistributors of a free 267 | program will individually obtain patent licenses, in effect making the 268 | program proprietary. To prevent this, we have made it clear that any 269 | patent must be licensed for everyone's free use or not licensed at all. 270 | 271 | The precise terms and conditions for copying, distribution and 272 | modification follow. 273 | 274 | GNU GENERAL PUBLIC LICENSE 275 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 276 | 277 | 0. This License applies to any program or other work which contains 278 | a notice placed by the copyright holder saying it may be distributed 279 | under the terms of this General Public License. The "Program", below, 280 | refers to any such program or work, and a "work based on the Program" 281 | means either the Program or any derivative work under copyright law: 282 | that is to say, a work containing the Program or a portion of it, 283 | either verbatim or with modifications and/or translated into another 284 | language. (Hereinafter, translation is included without limitation in 285 | the term "modification".) Each licensee is addressed as "you". 286 | 287 | Activities other than copying, distribution and modification are not 288 | covered by this License; they are outside its scope. The act of 289 | running the Program is not restricted, and the output from the Program 290 | is covered only if its contents constitute a work based on the 291 | Program (independent of having been made by running the Program). 292 | Whether that is true depends on what the Program does. 293 | 294 | 1. You may copy and distribute verbatim copies of the Program's 295 | source code as you receive it, in any medium, provided that you 296 | conspicuously and appropriately publish on each copy an appropriate 297 | copyright notice and disclaimer of warranty; keep intact all the 298 | notices that refer to this License and to the absence of any warranty; 299 | and give any other recipients of the Program a copy of this License 300 | along with the Program. 301 | 302 | You may charge a fee for the physical act of transferring a copy, and 303 | you may at your option offer warranty protection in exchange for a fee. 304 | 305 | 2. You may modify your copy or copies of the Program or any portion 306 | of it, thus forming a work based on the Program, and copy and 307 | distribute such modifications or work under the terms of Section 1 308 | above, provided that you also meet all of these conditions: 309 | 310 | a) You must cause the modified files to carry prominent notices 311 | stating that you changed the files and the date of any change. 312 | 313 | b) You must cause any work that you distribute or publish, that in 314 | whole or in part contains or is derived from the Program or any 315 | part thereof, to be licensed as a whole at no charge to all third 316 | parties under the terms of this License. 317 | 318 | c) If the modified program normally reads commands interactively 319 | when run, you must cause it, when started running for such 320 | interactive use in the most ordinary way, to print or display an 321 | announcement including an appropriate copyright notice and a 322 | notice that there is no warranty (or else, saying that you provide 323 | a warranty) and that users may redistribute the program under 324 | these conditions, and telling the user how to view a copy of this 325 | License. (Exception: if the Program itself is interactive but 326 | does not normally print such an announcement, your work based on 327 | the Program is not required to print an announcement.) 328 | 329 | These requirements apply to the modified work as a whole. If 330 | identifiable sections of that work are not derived from the Program, 331 | and can be reasonably considered independent and separate works in 332 | themselves, then this License, and its terms, do not apply to those 333 | sections when you distribute them as separate works. But when you 334 | distribute the same sections as part of a whole which is a work based 335 | on the Program, the distribution of the whole must be on the terms of 336 | this License, whose permissions for other licensees extend to the 337 | entire whole, and thus to each and every part regardless of who wrote it. 338 | 339 | Thus, it is not the intent of this section to claim rights or contest 340 | your rights to work written entirely by you; rather, the intent is to 341 | exercise the right to control the distribution of derivative or 342 | collective works based on the Program. 343 | 344 | In addition, mere aggregation of another work not based on the Program 345 | with the Program (or with a work based on the Program) on a volume of 346 | a storage or distribution medium does not bring the other work under 347 | the scope of this License. 348 | 349 | 3. You may copy and distribute the Program (or a work based on it, 350 | under Section 2) in object code or executable form under the terms of 351 | Sections 1 and 2 above provided that you also do one of the following: 352 | 353 | a) Accompany it with the complete corresponding machine-readable 354 | source code, which must be distributed under the terms of Sections 355 | 1 and 2 above on a medium customarily used for software interchange; or, 356 | 357 | b) Accompany it with a written offer, valid for at least three 358 | years, to give any third party, for a charge no more than your 359 | cost of physically performing source distribution, a complete 360 | machine-readable copy of the corresponding source code, to be 361 | distributed under the terms of Sections 1 and 2 above on a medium 362 | customarily used for software interchange; or, 363 | 364 | c) Accompany it with the information you received as to the offer 365 | to distribute corresponding source code. (This alternative is 366 | allowed only for noncommercial distribution and only if you 367 | received the program in object code or executable form with such 368 | an offer, in accord with Subsection b above.) 369 | 370 | The source code for a work means the preferred form of the work for 371 | making modifications to it. For an executable work, complete source 372 | code means all the source code for all modules it contains, plus any 373 | associated interface definition files, plus the scripts used to 374 | control compilation and installation of the executable. However, as a 375 | special exception, the source code distributed need not include 376 | anything that is normally distributed (in either source or binary 377 | form) with the major components (compiler, kernel, and so on) of the 378 | operating system on which the executable runs, unless that component 379 | itself accompanies the executable. 380 | 381 | If distribution of executable or object code is made by offering 382 | access to copy from a designated place, then offering equivalent 383 | access to copy the source code from the same place counts as 384 | distribution of the source code, even though third parties are not 385 | compelled to copy the source along with the object code. 386 | 387 | 4. You may not copy, modify, sublicense, or distribute the Program 388 | except as expressly provided under this License. Any attempt 389 | otherwise to copy, modify, sublicense or distribute the Program is 390 | void, and will automatically terminate your rights under this License. 391 | However, parties who have received copies, or rights, from you under 392 | this License will not have their licenses terminated so long as such 393 | parties remain in full compliance. 394 | 395 | 5. You are not required to accept this License, since you have not 396 | signed it. However, nothing else grants you permission to modify or 397 | distribute the Program or its derivative works. These actions are 398 | prohibited by law if you do not accept this License. Therefore, by 399 | modifying or distributing the Program (or any work based on the 400 | Program), you indicate your acceptance of this License to do so, and 401 | all its terms and conditions for copying, distributing or modifying 402 | the Program or works based on it. 403 | 404 | 6. Each time you redistribute the Program (or any work based on the 405 | Program), the recipient automatically receives a license from the 406 | original licensor to copy, distribute or modify the Program subject to 407 | these terms and conditions. You may not impose any further 408 | restrictions on the recipients' exercise of the rights granted herein. 409 | You are not responsible for enforcing compliance by third parties to 410 | this License. 411 | 412 | 7. If, as a consequence of a court judgment or allegation of patent 413 | infringement or for any other reason (not limited to patent issues), 414 | conditions are imposed on you (whether by court order, agreement or 415 | otherwise) that contradict the conditions of this License, they do not 416 | excuse you from the conditions of this License. If you cannot 417 | distribute so as to satisfy simultaneously your obligations under this 418 | License and any other pertinent obligations, then as a consequence you 419 | may not distribute the Program at all. For example, if a patent 420 | license would not permit royalty-free redistribution of the Program by 421 | all those who receive copies directly or indirectly through you, then 422 | the only way you could satisfy both it and this License would be to 423 | refrain entirely from distribution of the Program. 424 | 425 | If any portion of this section is held invalid or unenforceable under 426 | any particular circumstance, the balance of the section is intended to 427 | apply and the section as a whole is intended to apply in other 428 | circumstances. 429 | 430 | It is not the purpose of this section to induce you to infringe any 431 | patents or other property right claims or to contest validity of any 432 | such claims; this section has the sole purpose of protecting the 433 | integrity of the free software distribution system, which is 434 | implemented by public license practices. Many people have made 435 | generous contributions to the wide range of software distributed 436 | through that system in reliance on consistent application of that 437 | system; it is up to the author/donor to decide if he or she is willing 438 | to distribute software through any other system and a licensee cannot 439 | impose that choice. 440 | 441 | This section is intended to make thoroughly clear what is believed to 442 | be a consequence of the rest of this License. 443 | 444 | 8. If the distribution and/or use of the Program is restricted in 445 | certain countries either by patents or by copyrighted interfaces, the 446 | original copyright holder who places the Program under this License 447 | may add an explicit geographical distribution limitation excluding 448 | those countries, so that distribution is permitted only in or among 449 | countries not thus excluded. In such case, this License incorporates 450 | the limitation as if written in the body of this License. 451 | 452 | 9. The Free Software Foundation may publish revised and/or new versions 453 | of the General Public License from time to time. Such new versions will 454 | be similar in spirit to the present version, but may differ in detail to 455 | address new problems or concerns. 456 | 457 | Each version is given a distinguishing version number. If the Program 458 | specifies a version number of this License which applies to it and "any 459 | later version", you have the option of following the terms and conditions 460 | either of that version or of any later version published by the Free 461 | Software Foundation. If the Program does not specify a version number of 462 | this License, you may choose any version ever published by the Free Software 463 | Foundation. 464 | 465 | 10. If you wish to incorporate parts of the Program into other free 466 | programs whose distribution conditions are different, write to the author 467 | to ask for permission. For software which is copyrighted by the Free 468 | Software Foundation, write to the Free Software Foundation; we sometimes 469 | make exceptions for this. Our decision will be guided by the two goals 470 | of preserving the free status of all derivatives of our free software and 471 | of promoting the sharing and reuse of software generally. 472 | 473 | NO WARRANTY 474 | 475 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 476 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 477 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 478 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 479 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 480 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 481 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 482 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 483 | REPAIR OR CORRECTION. 484 | 485 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 486 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 487 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 488 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 489 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 490 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 491 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 492 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 493 | POSSIBILITY OF SUCH DAMAGES. 494 | 495 | END OF TERMS AND CONDITIONS 496 | 497 | How to Apply These Terms to Your New Programs 498 | 499 | If you develop a new program, and you want it to be of the greatest 500 | possible use to the public, the best way to achieve this is to make it 501 | free software which everyone can redistribute and change under these terms. 502 | 503 | To do so, attach the following notices to the program. It is safest 504 | to attach them to the start of each source file to most effectively 505 | convey the exclusion of warranty; and each file should have at least 506 | the "copyright" line and a pointer to where the full notice is found. 507 | 508 | 509 | Copyright (C) 510 | 511 | This program is free software; you can redistribute it and/or modify 512 | it under the terms of the GNU General Public License as published by 513 | the Free Software Foundation; either version 2 of the License, or 514 | (at your option) any later version. 515 | 516 | This program is distributed in the hope that it will be useful, 517 | but WITHOUT ANY WARRANTY; without even the implied warranty of 518 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 519 | GNU General Public License for more details. 520 | 521 | You should have received a copy of the GNU General Public License along 522 | with this program; if not, write to the Free Software Foundation, Inc., 523 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 524 | 525 | Also add information on how to contact you by electronic and paper mail. 526 | 527 | If the program is interactive, make it output a short notice like this 528 | when it starts in an interactive mode: 529 | 530 | Gnomovision version 69, Copyright (C) year name of author 531 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 532 | This is free software, and you are welcome to redistribute it 533 | under certain conditions; type `show c' for details. 534 | 535 | The hypothetical commands `show w' and `show c' should show the appropriate 536 | parts of the General Public License. Of course, the commands you use may 537 | be called something other than `show w' and `show c'; they could even be 538 | mouse-clicks or menu items--whatever suits your program. 539 | 540 | You should also get your employer (if you work as a programmer) or your 541 | school, if any, to sign a "copyright disclaimer" for the program, if 542 | necessary. Here is a sample; alter the names: 543 | 544 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 545 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 546 | 547 | , 1 April 1989 548 | Ty Coon, President of Vice 549 | 550 | This General Public License does not permit incorporating your program into 551 | proprietary programs. If your program is a subroutine library, you may 552 | consider it more useful to permit linking proprietary applications with the 553 | library. If this is what you want to do, use the GNU Lesser General 554 | Public License instead of this License. 555 | 556 | 557 | "CLASSPATH" EXCEPTION TO THE GPL 558 | 559 | Linking this library statically or dynamically with other modules is making 560 | a combined work based on this library. Thus, the terms and conditions of 561 | the GNU General Public License cover the whole combination. 562 | 563 | As a special exception, the copyright holders of this library give you 564 | permission to link this library with independent modules to produce an 565 | executable, regardless of the license terms of these independent modules, 566 | and to copy and distribute the resulting executable under terms of your 567 | choice, provided that you also meet, for each linked independent module, 568 | the terms and conditions of the license of that module. An independent 569 | module is a module which is not derived from or based on this library. If 570 | you modify this library, you may extend this exception to your version of 571 | the library, but you are not obligated to do so. If you do not wish to do 572 | so, delete this exception statement from your version. 573 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Gradle JavaCPP 2 | ============== 3 | 4 | [![Gitter](https://badges.gitter.im/bytedeco/javacpp.svg)](https://gitter.im/bytedeco/javacpp) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.bytedeco/gradle-javacpp/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.bytedeco/gradle-javacpp) [![Sonatype Nexus (Snapshots)](https://img.shields.io/nexus/s/https/oss.sonatype.org/org.bytedeco/gradle-javacpp.svg)](http://bytedeco.org/builds/) [![Build Status](https://travis-ci.org/bytedeco/gradle-javacpp.svg?branch=master)](https://travis-ci.org/bytedeco/gradle-javacpp) Commercial support: [![xscode](https://img.shields.io/badge/Available%20on-xs%3Acode-blue?style=?style=plastic&logo=appveyor&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAZQTFRF////////VXz1bAAAAAJ0Uk5T/wDltzBKAAAAlUlEQVR42uzXSwqAMAwE0Mn9L+3Ggtgkk35QwcnSJo9S+yGwM9DCooCbgn4YrJ4CIPUcQF7/XSBbx2TEz4sAZ2q1RAECBAiYBlCtvwN+KiYAlG7UDGj59MViT9hOwEqAhYCtAsUZvL6I6W8c2wcbd+LIWSCHSTeSAAECngN4xxIDSK9f4B9t377Wd7H5Nt7/Xz8eAgwAvesLRjYYPuUAAAAASUVORK5CYII=)](https://xscode.com/bytedeco/gradle-javacpp) 5 | 6 | 7 | Introduction 8 | ------------ 9 | Gradle JavaCPP offers plugins that make it easy to use [JavaCPP](https://github.com/bytedeco/javacpp) and [JavaCV](https://github.com/bytedeco/javacv) as part of the Gradle build system. 10 | 11 | Please feel free to ask questions on [the mailing list](http://groups.google.com/group/javacpp-project) if you encounter any problems with the software! I am sure it is far from perfect... 12 | 13 | 14 | Required Software 15 | ----------------- 16 | To use Gradle JavaCPP, you will need to download and install the following software: 17 | 18 | * An implementation of Java SE 8 or newer: 19 | * OpenJDK http://openjdk.java.net/install/ or 20 | * Oracle JDK http://www.oracle.com/technetwork/java/javase/downloads/ or 21 | * IBM JDK http://www.ibm.com/developerworks/java/jdk/ 22 | * Gradle 6.0 or newer: https://gradle.org/releases/ 23 | 24 | 25 | Getting Started 26 | --------------- 27 | Gradle JavaCPP comes with 2 plugins: 28 | 29 | * [The build plugin](#the-build-plugin) to create new packages containing native libraries using JavaCPP, and 30 | * [The platform plugin](#the-platform-plugin) to select from existing artifacts the ones corresponding to user-specified platforms. 31 | 32 | Fully functional sample projects are also provided in the [`samples`](samples) subdirectory and can be used as templates. 33 | 34 | 35 | ### The Build Plugin 36 | To understand how [JavaCPP](https://github.com/bytedeco/javacpp) is meant to be used, one should first take a look at the [Mapping Recipes for C/C++ Libraries](https://github.com/bytedeco/javacpp/wiki/Mapping-Recipes), but a high-level overview of the [Basic Architecture](https://github.com/bytedeco/javacpp/wiki/Basic-Architecture) is also available to understand the bigger picture. 37 | 38 | Once comfortable enough with the command line interface, the build plugin for Gradle can be used to integrate easily that workflow as part of `build.gradle` as shown below. By default, for Java libraries and applications, it creates a `javacppJar` task that archives the native libraries into a separate JAR file and sets its classifier to `$javacppPlatform$javacppPlatformExtension`, while excluding those files from the default `jar` task. To customize the behavior, there are properties that can be modified and whose documentation is available as part of the source code in these files: 39 | 40 | * [`BuildTask.java`](src/main/java/org/bytedeco/gradle/javacpp/BuildTask.java) 41 | * [`BuildPlugin.java`](src/main/java/org/bytedeco/gradle/javacpp/BuildPlugin.java) 42 | * [`BuildExtension.java`](src/main/java/org/bytedeco/gradle/javacpp/BuildExtension.java) 43 | 44 | ```groovy 45 | plugins { 46 | id 'java-library' 47 | id 'org.bytedeco.gradle-javacpp-build' version "$javacppVersion" 48 | } 49 | 50 | // We can set this on the command line too this way: -PjavacppPlatform=android-arm64 51 | ext { 52 | javacppPlatform = 'android-arm64' // or any other platform, defaults to Loader.getPlatform() 53 | } 54 | 55 | dependencies { 56 | api "org.bytedeco:javacpp:$javacppVersion" 57 | } 58 | 59 | tasks.withType(org.bytedeco.gradle.javacpp.BuildTask) { 60 | // set here default values for all build tasks below, typically just includePath and linkPath, 61 | // but also properties to set the path to the NDK and its compiler in the case of Android 62 | } 63 | 64 | javacppBuildCommand { 65 | // typically set here the buildCommand to the script that fills up includePath and linkPath 66 | } 67 | 68 | javacppBuildParser { 69 | // typically set here the classOrPackageNames to class names implementing InfoMap 70 | } 71 | 72 | javacppBuildCompiler { 73 | // typically set here boolean flags like copyLibs 74 | } 75 | ``` 76 | 77 | 78 | #### Integration with Android Studio 79 | 80 | It is also possible to integrate the `BuildTask` with Android Studio for projects with C/C++ support by: 81 | 82 | 1. Following the instructions at https://developer.android.com/studio/projects/add-native-code , 83 | 2. Adding something like below to the `app/build.gradle` file, and 84 | ```groovy 85 | android.applicationVariants.all { variant -> 86 | def variantName = variant.name.capitalize() // either "Debug" or "Release" 87 | def javaCompile = project.tasks.getByName("compile${variantName}JavaWithJavac") 88 | def configureCMake = project.tasks.findAll { 89 | it.name.startsWith("configureCMake$variantName") 90 | } 91 | 92 | // Compiles NativeLibraryConfig.java 93 | task "javacppCompileJava$variantName"(type: JavaCompile) { 94 | include 'com/example/myapplication/NativeLibraryConfig.java' 95 | source = javaCompile.source 96 | classpath = javaCompile.classpath 97 | destinationDir = javaCompile.destinationDir 98 | } 99 | 100 | // Parses NativeLibrary.h and outputs NativeLibrary.java 101 | task "javacppBuildParser$variantName"(type: org.bytedeco.gradle.javacpp.BuildTask) { 102 | dependsOn "javacppCompileJava$variantName" 103 | classPath = [javaCompile.destinationDir] 104 | includePath = ["$projectDir/src/main/cpp/"] 105 | classOrPackageNames = ['com.example.myapplication.NativeLibraryConfig'] 106 | outputDirectory = file("$projectDir/src/main/java/") 107 | } 108 | 109 | // Compiles NativeLibrary.java and everything else 110 | javaCompile.dependsOn "javacppBuildParser$variantName" 111 | 112 | // Generates jnijavacpp.cpp and jniNativeLibrary.cpp 113 | task "javacppBuildCompiler$variantName"(type: org.bytedeco.gradle.javacpp.BuildTask) { 114 | dependsOn javaCompile 115 | classPath = [javaCompile.destinationDir] 116 | classOrPackageNames = ['com.example.myapplication.NativeLibrary'] 117 | compile = false 118 | deleteJniFiles = false 119 | outputDirectory = file("$projectDir/src/main/cpp/") 120 | } 121 | 122 | // Picks up the C++ files listed in CMakeLists.txt 123 | configureCMake.forEach { 124 | it.dependsOn "javacppBuildCompiler$variantName" 125 | } 126 | } 127 | ``` 128 | 3. Updating the `CMakeLists.txt` file to include the generated `.cpp` files. 129 | 130 | 131 | ### The Platform Plugin 132 | With Maven, we are able to modify dependencies transitively using profiles, and although Gradle doesn't provide such functionality out of the box, it can be emulated via plugins. After adding a single line to the `build.gradle` script as shown below, the platform plugin will filter the dependencies of artifacts whose names contain "-platform" using the comma-separated values given in `$javacppPlatform`. To understand better how this works, it may be worth taking a look at the source code of the plugin: 133 | 134 | * [`PlatformRule.java`](src/main/java/org/bytedeco/gradle/javacpp/PlatformRule.java) 135 | * [`PlatformPlugin.java`](src/main/java/org/bytedeco/gradle/javacpp/PlatformPlugin.java) 136 | 137 | ```groovy 138 | plugins { 139 | id 'java-library' 140 | id 'org.bytedeco.gradle-javacpp-platform' version "$javacppVersion" 141 | } 142 | 143 | // We can set this on the command line too this way: -PjavacppPlatform=linux-x86_64,macosx-x86_64,windows-x86_64,etc 144 | ext { 145 | javacppPlatform = 'linux-x86_64,macosx-x86_64,windows-x86_64,etc' // defaults to Loader.getPlatform() 146 | } 147 | 148 | dependencies { 149 | api "org.bytedeco:javacv-platform:$javacvVersion" // or any other "-platform" artifacts 150 | } 151 | ``` 152 | 153 | Moreover, in the case of Android, its plugin is not able to use native libraries found in JAR files when building Android App Bundles (AAB files). However, to work around this limitation we can easily use Gradle to extract the files automatically, for example, in the following manner with an additional `javacppExtract` task inside `app/build.gradle`: 154 | 155 | ```groovy 156 | configurations { 157 | javacpp 158 | } 159 | 160 | task javacppExtract(type: Copy) { 161 | dependsOn configurations.javacpp 162 | 163 | from { configurations.javacpp.collect { zipTree(it) } } 164 | include "lib/**" 165 | into "$buildDir/javacpp/" 166 | android.sourceSets.main.jniLibs.srcDirs += ["$buildDir/javacpp/lib/"] 167 | 168 | tasks.getByName('preBuild').dependsOn javacppExtract 169 | } 170 | 171 | dependencies { 172 | implementation group: 'org.bytedeco', name: 'javacv', version: "$javacvVersion" 173 | javacpp group: 'org.bytedeco', name: 'openblas-platform', version: "$openblasVersion-$javacppVersion" 174 | javacpp group: 'org.bytedeco', name: 'opencv-platform', version: "$opencvVersion-$javacppVersion" 175 | javacpp group: 'org.bytedeco', name: 'ffmpeg-platform', version: "$ffmpegVersion-$javacppVersion" 176 | ... 177 | } 178 | ``` 179 | 180 | 181 | ---- 182 | Project lead: Samuel Audet [samuel.audet `at` gmail.com](mailto:samuel.audet at gmail.com) 183 | Developer site: https://github.com/bytedeco/gradle-javacpp 184 | Discussion group: http://groups.google.com/group/javacpp-project 185 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java-library' 3 | id 'java-gradle-plugin' 4 | id 'maven-publish' 5 | id 'signing' 6 | } 7 | 8 | group = 'org.bytedeco' 9 | version = '1.5.12-SNAPSHOT' 10 | 11 | sourceCompatibility = 1.7 12 | targetCompatibility = 1.7 13 | 14 | repositories { 15 | mavenLocal() 16 | mavenCentral() 17 | maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' } 18 | } 19 | 20 | dependencies { 21 | api "org.bytedeco:javacpp:$version" 22 | testImplementation 'junit:junit:4.13.2' 23 | } 24 | 25 | gradlePlugin { 26 | // need to sign before publishing 27 | automatedPublishing = false 28 | plugins { 29 | build { 30 | id = 'org.bytedeco.gradle-javacpp-build' 31 | implementationClass = 'org.bytedeco.gradle.javacpp.BuildPlugin' 32 | } 33 | platform { 34 | id = 'org.bytedeco.gradle-javacpp-platform' 35 | implementationClass = 'org.bytedeco.gradle.javacpp.PlatformPlugin' 36 | } 37 | } 38 | } 39 | 40 | jar { 41 | manifest { 42 | attributes 'Implementation-Title': 'Gradle JavaCPP', 43 | 'Implementation-Vendor': 'Bytedeco', 44 | 'Implementation-Version': project.version, 45 | 'Specification-Title': 'Gradle JavaCPP', 46 | 'Specification-Vendor': 'Bytedeco', 47 | 'Specification-Version': project.version 48 | } 49 | } 50 | 51 | javadoc { 52 | options.memberLevel = JavadocMemberLevel.PRIVATE 53 | options.links = ['https://docs.oracle.com/javase/8/docs/api', 54 | 'https://docs.gradle.org/current/javadoc', 55 | 'http://bytedeco.org/javacpp/apidocs', 56 | 'http://www.slf4j.org/apidocs', 57 | 'http://junit.org/junit4/javadoc/4.13.2'] 58 | } 59 | 60 | java { 61 | withJavadocJar() 62 | withSourcesJar() 63 | } 64 | 65 | def pomClosure = { 66 | name = 'Gradle JavaCPP' 67 | delegate.description = 'Gradle plugins to automate the build process of JavaCPP and JavaCV' 68 | url = 'http://bytedeco.org/gradle-javacpp/' 69 | licenses { 70 | license { 71 | name = 'Apache License, Version 2.0' 72 | url = 'http://www.apache.org/licenses/LICENSE-2.0' 73 | distribution = 'repo' 74 | } 75 | license { 76 | name = 'GNU General Public License (GPL) version 2, or any later version' 77 | url = 'http://www.gnu.org/licenses/' 78 | distribution = 'repo' 79 | } 80 | license { 81 | name = 'GPLv2 with Classpath exception' 82 | url = 'http://www.gnu.org/software/classpath/license.html' 83 | distribution = 'repo' 84 | } 85 | } 86 | developers { 87 | developer { 88 | id = 'saudet' 89 | name = 'Samuel Audet' 90 | email = 'samuel.audet@gmail.com' 91 | } 92 | } 93 | scm { 94 | url = 'https://github.com/bytedeco/gradle-javacpp' 95 | connection = 'scm:git:git://github.com/bytedeco/gradle-javacpp.git' 96 | developerConnection = 'scm:git:ssh://git@github.com/bytedeco/gradle-javacpp.git' 97 | } 98 | } 99 | 100 | publishing { 101 | publications { 102 | mavenJava(MavenPublication) { 103 | from components.java 104 | pom pomClosure 105 | } 106 | buildPluginMarkerMaven(MavenPublication) { 107 | groupId gradlePlugin.plugins.build.id 108 | artifactId gradlePlugin.plugins.build.id + ".gradle.plugin" 109 | pom pomClosure 110 | pom.withXml { 111 | def dependency = asNode().appendNode('dependencies').appendNode('dependency') 112 | dependency.appendNode('groupId', group) 113 | dependency.appendNode('artifactId', rootProject.name) 114 | dependency.appendNode('version', version) 115 | } 116 | } 117 | platformPluginMarkerMaven(MavenPublication) { 118 | groupId gradlePlugin.plugins.platform.id 119 | artifactId gradlePlugin.plugins.platform.id + ".gradle.plugin" 120 | pom pomClosure 121 | pom.withXml { 122 | def dependency = asNode().appendNode('dependencies').appendNode('dependency') 123 | dependency.appendNode('groupId', group) 124 | dependency.appendNode('artifactId', rootProject.name) 125 | dependency.appendNode('version', version) 126 | } 127 | } 128 | } 129 | repositories { 130 | maven { 131 | def releasesRepoUrl = 'https://oss.sonatype.org/service/local/staging/deploy/maven2/' 132 | def snapshotsRepoUrl = 'https://oss.sonatype.org/content/repositories/snapshots/' 133 | url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl 134 | credentials { 135 | username System.getenv('CI_DEPLOY_USERNAME') 136 | password System.getenv('CI_DEPLOY_PASSWORD') 137 | } 138 | } 139 | } 140 | } 141 | 142 | signing { 143 | useGpgCmd() 144 | if (!version.endsWith('SNAPSHOT')) { 145 | sign publishing.publications.mavenJava 146 | sign publishing.publications.buildPluginMarkerMaven 147 | sign publishing.publications.platformPluginMarkerMaven 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /samples/javacv-demo-kotlin/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | // Apply the Kotlin JVM plugin to add support for Kotlin. 3 | kotlin("jvm").version("1.3.72") 4 | // Apply the java-library plugin for API and implementation separation. 5 | `java-library` 6 | id("org.bytedeco.gradle-javacpp-platform").version("1.5.10") 7 | } 8 | 9 | repositories { 10 | jcenter() 11 | mavenLocal() 12 | mavenCentral() 13 | maven { url = uri("https://oss.sonatype.org/content/repositories/snapshots/") } 14 | } 15 | 16 | dependencies { 17 | implementation(kotlin("stdlib-jdk8")) 18 | implementation("org.bytedeco:javacv-platform:1.5.10") 19 | } 20 | 21 | tasks { 22 | withType { 23 | duplicatesStrategy = DuplicatesStrategy.INCLUDE // allow duplicates 24 | // Otherwise you'll get a "No main manifest attribute" error 25 | manifest { 26 | attributes["Main-Class"] = "org.bytedeco.javacv.samples.Demo" 27 | } 28 | 29 | // To add all of the dependencies otherwise a "NoClassDefFoundError" error 30 | from(sourceSets.main.get().output) 31 | 32 | dependsOn(configurations.runtimeClasspath) 33 | from({ 34 | configurations.runtimeClasspath.get().filter { it.name.endsWith("jar") }.map { zipTree(it) } 35 | }) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /samples/javacv-demo-kotlin/settings.gradle.kts: -------------------------------------------------------------------------------- 1 | /* 2 | * This file was generated by the Gradle 'init' task. 3 | * 4 | * The settings file is used to specify which projects to include in your build. 5 | * 6 | * Detailed information about configuring a multi-project build in Gradle can be found 7 | * in the user manual at https://docs.gradle.org/6.5/userguide/multi_project_builds.html 8 | */ 9 | 10 | pluginManagement { 11 | repositories { 12 | gradlePluginPortal() 13 | jcenter() 14 | mavenLocal() 15 | mavenCentral() 16 | maven { url = uri("https://oss.sonatype.org/content/repositories/snapshots/") } 17 | } 18 | } 19 | 20 | rootProject.name = "javacv-demo-kotlin" 21 | -------------------------------------------------------------------------------- /samples/javacv-demo-kotlin/src/main/kotlin/org.bytedeco.javacv.samples/Demo.kt: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2009-2018 Samuel Audet 3 | * 4 | * Licensed either under the Apache License, Version 2.0, or (at your option) 5 | * under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation (subject to the "Classpath" exception), 7 | * either version 2, or any later version (collectively, the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * http://www.gnu.org/licenses/ 13 | * http://www.gnu.org/software/classpath/license.html 14 | * 15 | * or as provided in the LICENSE.txt file that accompanied this code. 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | package org.bytedeco.javacv.samples 23 | 24 | import org.bytedeco.javacpp.Loader 25 | import org.bytedeco.javacpp.indexer.DoubleIndexer 26 | import org.bytedeco.javacv.CanvasFrame 27 | import org.bytedeco.javacv.FrameGrabber 28 | import org.bytedeco.javacv.FrameRecorder 29 | import org.bytedeco.javacv.OpenCVFrameConverter.ToMat 30 | import org.bytedeco.opencv.global.opencv_calib3d 31 | import org.bytedeco.opencv.global.opencv_core 32 | import org.bytedeco.opencv.global.opencv_imgproc 33 | import org.bytedeco.opencv.opencv_core.* 34 | import org.bytedeco.opencv.opencv_objdetect.CascadeClassifier 35 | import java.net.URL 36 | 37 | 38 | object Demo { 39 | @Throws(Exception::class) 40 | @JvmStatic 41 | fun main(args: Array) { 42 | val classifierName = if (args.size > 0) { 43 | args[0] 44 | } else { 45 | val url = URL("https://raw.github.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_alt.xml") 46 | val file = Loader.cacheResource(url) 47 | file.absolutePath 48 | } 49 | 50 | // We can "cast" Pointer objects by instantiating a new object of the desired class. 51 | val classifier = CascadeClassifier(classifierName) 52 | 53 | // The available FrameGrabber classes include OpenCVFrameGrabber (opencv_videoio), 54 | // DC1394FrameGrabber, FlyCapture2FrameGrabber, OpenKinectFrameGrabber, OpenKinect2FrameGrabber, 55 | // RealSenseFrameGrabber, RealSense2FrameGrabber, PS3EyeFrameGrabber, VideoInputFrameGrabber, and FFmpegFrameGrabber. 56 | val grabber = FrameGrabber.createDefault(0) 57 | grabber.start() 58 | 59 | // CanvasFrame, FrameGrabber, and FrameRecorder use Frame objects to communicate image data. 60 | // We need a FrameConverter to interface with other APIs (Android, Java 2D, JavaFX, Tesseract, OpenCV, etc). 61 | val converter = ToMat() 62 | 63 | // FAQ about IplImage and Mat objects from OpenCV: 64 | // - For custom raw processing of data, createBuffer() returns an NIO direct 65 | // buffer wrapped around the memory pointed by imageData, and under Android we can 66 | // also use that Buffer with Bitmap.copyPixelsFromBuffer() and copyPixelsToBuffer(). 67 | // - To get a BufferedImage from an IplImage, or vice versa, we can chain calls to 68 | // Java2DFrameConverter and OpenCVFrameConverter, one after the other. 69 | // - Java2DFrameConverter also has static copy() methods that we can use to transfer 70 | // data more directly between BufferedImage and IplImage or Mat via Frame objects. 71 | var grabbedImage = converter.convert(grabber.grab()) 72 | val height = grabbedImage.rows() 73 | val width = grabbedImage.cols() 74 | 75 | // Objects allocated with `new`, clone(), or a create*() factory method are automatically released 76 | // by the garbage collector, but may still be explicitly released by calling deallocate(). 77 | // You shall NOT call cvReleaseImage(), cvReleaseMemStorage(), etc. on objects allocated this way. 78 | val grayImage = Mat(height, width, opencv_core.CV_8UC1) 79 | val rotatedImage = grabbedImage.clone() 80 | 81 | // The OpenCVFrameRecorder class simply uses the VideoWriter of opencv_videoio, 82 | // but FFmpegFrameRecorder also exists as a more versatile alternative. 83 | val recorder = FrameRecorder.createDefault("output.avi", width, height) 84 | recorder.start() 85 | 86 | // CanvasFrame is a JFrame containing a Canvas component, which is hardware accelerated. 87 | // It can also switch into full-screen mode when called with a screenNumber. 88 | // We should also specify the relative monitor/camera response for proper gamma correction. 89 | val frame = CanvasFrame("Some Title", CanvasFrame.getDefaultGamma() / grabber.gamma) 90 | 91 | // Let's create some random 3D rotation... 92 | val randomR = Mat(3, 3, opencv_core.CV_64FC1) 93 | val randomAxis = Mat(3, 1, opencv_core.CV_64FC1) 94 | // We can easily and efficiently access the elements of matrices and images 95 | // through an Indexer object with the set of get() and put() methods. 96 | val Ridx = randomR.createIndexer() 97 | val axisIdx = randomAxis.createIndexer() 98 | axisIdx.put(0, (Math.random() - 0.5) / 4, 99 | (Math.random() - 0.5) / 4, 100 | (Math.random() - 0.5) / 4) 101 | opencv_calib3d.Rodrigues(randomAxis, randomR) 102 | val f = (width + height) / 2.0 103 | Ridx.put(0, 2, Ridx[0, 2] * f) 104 | Ridx.put(1, 2, Ridx[1, 2] * f) 105 | Ridx.put(2, 0, Ridx[2, 0] / f) 106 | Ridx.put(2, 1, Ridx[2, 1] / f) 107 | println(Ridx) 108 | 109 | // We can allocate native arrays using constructors taking an integer as argument. 110 | val hatPoints = Point(3) 111 | while (frame.isVisible && converter.convert(grabber.grab()).also { grabbedImage = it } != null) { 112 | // Let's try to detect some faces! but we need a grayscale image... 113 | opencv_imgproc.cvtColor(grabbedImage, grayImage, opencv_imgproc.CV_BGR2GRAY) 114 | val faces = RectVector() 115 | classifier.detectMultiScale(grayImage, faces) 116 | val total = faces.size() 117 | for (i in 0 until total) { 118 | val r = faces[i] 119 | val x = r.x() 120 | val y = r.y() 121 | val w = r.width() 122 | val h = r.height() 123 | opencv_imgproc.rectangle(grabbedImage, Point(x, y), Point(x + w, y + h), Scalar.RED, 1, opencv_imgproc.CV_AA, 0) 124 | 125 | // To access or pass as argument the elements of a native array, call position() before. 126 | hatPoints.position(0).x(x - w / 10).y(y - h / 10) 127 | hatPoints.position(1).x(x + w * 11 / 10).y(y - h / 10) 128 | hatPoints.position(2).x(x + w / 2).y(y - h / 2) 129 | opencv_imgproc.fillConvexPoly(grabbedImage, hatPoints.position(0), 3, Scalar.GREEN, opencv_imgproc.CV_AA, 0) 130 | } 131 | 132 | // Let's find some contours! but first some thresholding... 133 | opencv_imgproc.threshold(grayImage, grayImage, 64.0, 255.0, opencv_imgproc.CV_THRESH_BINARY) 134 | 135 | // To check if an output argument is null we may call either isNull() or equals(null). 136 | val contours = MatVector() 137 | opencv_imgproc.findContours(grayImage, contours, opencv_imgproc.CV_RETR_LIST, opencv_imgproc.CV_CHAIN_APPROX_SIMPLE) 138 | val n = contours.size() 139 | for (i in 0 until n) { 140 | val contour = contours[i] 141 | val points = Mat() 142 | opencv_imgproc.approxPolyDP(contour, points, opencv_imgproc.arcLength(contour, true) * 0.02, true) 143 | opencv_imgproc.drawContours(grabbedImage, MatVector(points), -1, Scalar.BLUE) 144 | } 145 | opencv_imgproc.warpPerspective(grabbedImage, rotatedImage, randomR, rotatedImage.size()) 146 | val rotatedFrame = converter.convert(rotatedImage) 147 | frame.showImage(rotatedFrame) 148 | recorder.record(rotatedFrame) 149 | } 150 | frame.dispose() 151 | recorder.stop() 152 | grabber.stop() 153 | } 154 | } -------------------------------------------------------------------------------- /samples/javacv-demo/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java-library' 3 | id 'org.bytedeco.gradle-javacpp-platform' version '1.5.10' 4 | } 5 | 6 | group = 'org.bytedeco' 7 | version = '1.5.10' 8 | 9 | repositories { 10 | mavenLocal() 11 | mavenCentral() 12 | maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' } 13 | } 14 | 15 | dependencies { 16 | api "org.bytedeco:javacv-platform:1.5.10" 17 | // api "org.bytedeco:opencv-platform-gpu:4.7.0-$version" 18 | // api "org.bytedeco:ffmpeg-platform-gpl:6.0-$version" 19 | testImplementation 'junit:junit:4.13.2' 20 | } 21 | 22 | // Let's create a standalone "uber JAR" to see what we get in it 23 | jar { 24 | duplicatesStrategy = DuplicatesStrategy.INCLUDE // allow duplicates 25 | manifest.attributes "Main-Class": "org.bytedeco.javacv.samples.Demo" 26 | from { 27 | configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } 28 | } 29 | } 30 | 31 | -------------------------------------------------------------------------------- /samples/javacv-demo/settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | mavenLocal() 4 | mavenCentral() 5 | maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' } 6 | gradlePluginPortal() 7 | } 8 | } 9 | 10 | rootProject.name = 'javacv-demo' 11 | 12 | gradle.rootProject { ext.javacppVersion = '1.5.10' } 13 | -------------------------------------------------------------------------------- /samples/javacv-demo/src/main/java/org/bytedeco/javacv/samples/Demo.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2009-2018 Samuel Audet 3 | * 4 | * Licensed either under the Apache License, Version 2.0, or (at your option) 5 | * under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation (subject to the "Classpath" exception), 7 | * either version 2, or any later version (collectively, the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * http://www.gnu.org/licenses/ 13 | * http://www.gnu.org/software/classpath/license.html 14 | * 15 | * or as provided in the LICENSE.txt file that accompanied this code. 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | package org.bytedeco.javacv.samples; 23 | 24 | import java.io.File; 25 | import java.net.URL; 26 | import org.bytedeco.javacv.*; 27 | import org.bytedeco.javacpp.*; 28 | import org.bytedeco.javacpp.indexer.*; 29 | import org.bytedeco.opencv.opencv_core.*; 30 | import org.bytedeco.opencv.opencv_imgproc.*; 31 | import org.bytedeco.opencv.opencv_calib3d.*; 32 | import org.bytedeco.opencv.opencv_objdetect.*; 33 | import static org.bytedeco.opencv.global.opencv_core.*; 34 | import static org.bytedeco.opencv.global.opencv_imgproc.*; 35 | import static org.bytedeco.opencv.global.opencv_calib3d.*; 36 | import static org.bytedeco.opencv.global.opencv_objdetect.*; 37 | 38 | public class Demo { 39 | public static void main(String[] args) throws Exception { 40 | String classifierName = null; 41 | if (args.length > 0) { 42 | classifierName = args[0]; 43 | } else { 44 | URL url = new URL("https://raw.github.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_alt.xml"); 45 | File file = Loader.cacheResource(url); 46 | classifierName = file.getAbsolutePath(); 47 | } 48 | 49 | // We can "cast" Pointer objects by instantiating a new object of the desired class. 50 | CascadeClassifier classifier = new CascadeClassifier(classifierName); 51 | if (classifier == null) { 52 | System.err.println("Error loading classifier file \"" + classifierName + "\"."); 53 | System.exit(1); 54 | } 55 | 56 | // The available FrameGrabber classes include OpenCVFrameGrabber (opencv_videoio), 57 | // DC1394FrameGrabber, FlyCapture2FrameGrabber, OpenKinectFrameGrabber, OpenKinect2FrameGrabber, 58 | // RealSenseFrameGrabber, RealSense2FrameGrabber, PS3EyeFrameGrabber, VideoInputFrameGrabber, and FFmpegFrameGrabber. 59 | FrameGrabber grabber = FrameGrabber.createDefault(0); 60 | grabber.start(); 61 | 62 | // CanvasFrame, FrameGrabber, and FrameRecorder use Frame objects to communicate image data. 63 | // We need a FrameConverter to interface with other APIs (Android, Java 2D, JavaFX, Tesseract, OpenCV, etc). 64 | OpenCVFrameConverter.ToMat converter = new OpenCVFrameConverter.ToMat(); 65 | 66 | // FAQ about IplImage and Mat objects from OpenCV: 67 | // - For custom raw processing of data, createBuffer() returns an NIO direct 68 | // buffer wrapped around the memory pointed by imageData, and under Android we can 69 | // also use that Buffer with Bitmap.copyPixelsFromBuffer() and copyPixelsToBuffer(). 70 | // - To get a BufferedImage from an IplImage, or vice versa, we can chain calls to 71 | // Java2DFrameConverter and OpenCVFrameConverter, one after the other. 72 | // - Java2DFrameConverter also has static copy() methods that we can use to transfer 73 | // data more directly between BufferedImage and IplImage or Mat via Frame objects. 74 | Mat grabbedImage = converter.convert(grabber.grab()); 75 | int height = grabbedImage.rows(); 76 | int width = grabbedImage.cols(); 77 | 78 | // Objects allocated with `new`, clone(), or a create*() factory method are automatically released 79 | // by the garbage collector, but may still be explicitly released by calling deallocate(). 80 | // You shall NOT call cvReleaseImage(), cvReleaseMemStorage(), etc. on objects allocated this way. 81 | Mat grayImage = new Mat(height, width, CV_8UC1); 82 | Mat rotatedImage = grabbedImage.clone(); 83 | 84 | // The OpenCVFrameRecorder class simply uses the VideoWriter of opencv_videoio, 85 | // but FFmpegFrameRecorder also exists as a more versatile alternative. 86 | FrameRecorder recorder = FrameRecorder.createDefault("output.avi", width, height); 87 | recorder.start(); 88 | 89 | // CanvasFrame is a JFrame containing a Canvas component, which is hardware accelerated. 90 | // It can also switch into full-screen mode when called with a screenNumber. 91 | // We should also specify the relative monitor/camera response for proper gamma correction. 92 | CanvasFrame frame = new CanvasFrame("Some Title", CanvasFrame.getDefaultGamma()/grabber.getGamma()); 93 | 94 | // Let's create some random 3D rotation... 95 | Mat randomR = new Mat(3, 3, CV_64FC1), 96 | randomAxis = new Mat(3, 1, CV_64FC1); 97 | // We can easily and efficiently access the elements of matrices and images 98 | // through an Indexer object with the set of get() and put() methods. 99 | DoubleIndexer Ridx = randomR.createIndexer(), 100 | axisIdx = randomAxis.createIndexer(); 101 | axisIdx.put(0, (Math.random() - 0.5) / 4, 102 | (Math.random() - 0.5) / 4, 103 | (Math.random() - 0.5) / 4); 104 | Rodrigues(randomAxis, randomR); 105 | double f = (width + height) / 2.0; Ridx.put(0, 2, Ridx.get(0, 2) * f); 106 | Ridx.put(1, 2, Ridx.get(1, 2) * f); 107 | Ridx.put(2, 0, Ridx.get(2, 0) / f); Ridx.put(2, 1, Ridx.get(2, 1) / f); 108 | System.out.println(Ridx); 109 | 110 | // We can allocate native arrays using constructors taking an integer as argument. 111 | Point hatPoints = new Point(3); 112 | 113 | while (frame.isVisible() && (grabbedImage = converter.convert(grabber.grab())) != null) { 114 | // Let's try to detect some faces! but we need a grayscale image... 115 | cvtColor(grabbedImage, grayImage, CV_BGR2GRAY); 116 | RectVector faces = new RectVector(); 117 | classifier.detectMultiScale(grayImage, faces); 118 | long total = faces.size(); 119 | for (long i = 0; i < total; i++) { 120 | Rect r = faces.get(i); 121 | int x = r.x(), y = r.y(), w = r.width(), h = r.height(); 122 | rectangle(grabbedImage, new Point(x, y), new Point(x + w, y + h), Scalar.RED, 1, CV_AA, 0); 123 | 124 | // To access or pass as argument the elements of a native array, call position() before. 125 | hatPoints.position(0).x(x - w / 10 ).y(y - h / 10); 126 | hatPoints.position(1).x(x + w * 11 / 10).y(y - h / 10); 127 | hatPoints.position(2).x(x + w / 2 ).y(y - h / 2 ); 128 | fillConvexPoly(grabbedImage, hatPoints.position(0), 3, Scalar.GREEN, CV_AA, 0); 129 | } 130 | 131 | // Let's find some contours! but first some thresholding... 132 | threshold(grayImage, grayImage, 64, 255, CV_THRESH_BINARY); 133 | 134 | // To check if an output argument is null we may call either isNull() or equals(null). 135 | MatVector contours = new MatVector(); 136 | findContours(grayImage, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE); 137 | long n = contours.size(); 138 | for (long i = 0; i < n; i++) { 139 | Mat contour = contours.get(i); 140 | Mat points = new Mat(); 141 | approxPolyDP(contour, points, arcLength(contour, true) * 0.02, true); 142 | drawContours(grabbedImage, new MatVector(points), -1, Scalar.BLUE); 143 | } 144 | 145 | warpPerspective(grabbedImage, rotatedImage, randomR, rotatedImage.size()); 146 | 147 | Frame rotatedFrame = converter.convert(rotatedImage); 148 | frame.showImage(rotatedFrame); 149 | recorder.record(rotatedFrame); 150 | } 151 | frame.dispose(); 152 | recorder.stop(); 153 | grabber.stop(); 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /samples/zlib/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java-library' 3 | id 'org.bytedeco.gradle-javacpp-build' version '1.5.10' 4 | id 'maven-publish' 5 | id 'signing' 6 | } 7 | 8 | group = 'org.bytedeco' 9 | version = "1.3.1-$javacppVersion" 10 | 11 | repositories { 12 | mavenLocal() 13 | mavenCentral() 14 | maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' } 15 | } 16 | 17 | dependencies { 18 | api "org.bytedeco:javacpp:$javacppVersion" 19 | javacppPlatform "org.bytedeco:javacpp-platform:$javacppVersion" 20 | javacppPlatform "org.bytedeco:zlib:$version:android-arm" 21 | javacppPlatform "org.bytedeco:zlib:$version:android-arm64" 22 | javacppPlatform "org.bytedeco:zlib:$version:android-x86" 23 | javacppPlatform "org.bytedeco:zlib:$version:android-x86_64" 24 | javacppPlatform "org.bytedeco:zlib:$version:linux-x86" 25 | javacppPlatform "org.bytedeco:zlib:$version:linux-x86_64" 26 | javacppPlatform "org.bytedeco:zlib:$version:macosx-x86_64" 27 | javacppPlatform "org.bytedeco:zlib:$version:windows-x86" 28 | javacppPlatform "org.bytedeco:zlib:$version:windows-x86_64" 29 | testRuntimeOnly "org.bytedeco:javacpp:$javacppVersion:$javacppPlatform" 30 | testImplementation 'junit:junit:4.13.2' 31 | } 32 | 33 | tasks.withType(org.bytedeco.gradle.javacpp.BuildTask) { 34 | if (javacppPlatform.startsWith("android")) { 35 | properties = "$javacppPlatform-clang" 36 | propertyKeysAndValues = [ 'platform.root' : System.getProperty('user.home') + '/Android/Sdk/ndk-bundle/', 37 | 'platform.compiler' : "$buildDir/$javacppPlatform/toolchain/bin/clang++".toString() ] 38 | test.enabled = false 39 | } 40 | includePath = ["$buildDir/$javacppPlatform/include"] 41 | linkPath = ["$buildDir/$javacppPlatform/lib"] 42 | } 43 | 44 | javacppBuildCommand { 45 | buildCommand = ['bash', 'build.sh'] 46 | } 47 | 48 | javacppBuildParser { 49 | classOrPackageNames = ['org.bytedeco.zlib.presets.*'] 50 | outputDirectory = file("$buildDir/generated/sources/javacpp/") 51 | } 52 | 53 | javacppBuildCompiler { 54 | copyLibs = true 55 | } 56 | 57 | jar { 58 | manifest { 59 | attributes 'Class-Path': configurations.runtimeClasspath.collect { it.getName() }.join(' '), 60 | 'Implementation-Title': 'JavaCPP Presets for zlib', 61 | 'Implementation-Vendor': 'Bytedeco', 62 | 'Implementation-Version': project.version, 63 | 'Specification-Title': 'JavaCPP Presets for zlib', 64 | 'Specification-Vendor': 'Bytedeco', 65 | 'Specification-Version': project.version 66 | } 67 | } 68 | 69 | javadoc { 70 | failOnError = false 71 | options.links = ['http://bytedeco.org/javacpp/apidocs'] 72 | } 73 | 74 | java { 75 | withJavadocJar() 76 | withSourcesJar() 77 | } 78 | 79 | def pomClosure = { 80 | name = 'JavaCPP Presets for zlib' 81 | delegate.description = 'Sample project for the build plugin of Gradle JavaCPP' 82 | url = 'http://bytedeco.org/gradle-javacpp/' 83 | licenses { 84 | license { 85 | name = 'Apache License, Version 2.0' 86 | url = 'http://www.apache.org/licenses/LICENSE-2.0' 87 | distribution = 'repo' 88 | } 89 | license { 90 | name = 'GNU General Public License (GPL) version 2, or any later version' 91 | url = 'http://www.gnu.org/licenses/' 92 | distribution = 'repo' 93 | } 94 | license { 95 | name = 'GPLv2 with Classpath exception' 96 | url = 'http://www.gnu.org/software/classpath/license.html' 97 | distribution = 'repo' 98 | } 99 | } 100 | developers { 101 | developer { 102 | id = 'saudet' 103 | name = 'Samuel Audet' 104 | email = 'samuel.audet@gmail.com' 105 | } 106 | } 107 | scm { 108 | url = 'https://github.com/bytedeco/gradle-javacpp' 109 | connection = 'scm:git:git://github.com/bytedeco/gradle-javacpp.git' 110 | developerConnection = 'scm:git:ssh://git@github.com/bytedeco/gradle-javacpp.git' 111 | } 112 | } 113 | 114 | publishing { 115 | publications { 116 | mavenJava(MavenPublication) { 117 | from components.java 118 | artifacts = [jar, javacppJar, javadocJar, sourcesJar] + javacppBuild.existingArtifacts(configurations.javacppPlatform) 119 | pom pomClosure 120 | } 121 | mavenJavacppPlatform(MavenPublication) { 122 | groupId project.group 123 | artifactId project.name + "-platform" 124 | artifacts = [javacppPlatformJar, javacppPlatformJavadocJar, javacppPlatformSourcesJar] 125 | pom pomClosure 126 | pom.withXml javacppBuild.xmlAction(configurations.javacppPlatform) 127 | } 128 | } 129 | repositories { 130 | maven { 131 | def releasesRepoUrl = 'https://oss.sonatype.org/service/local/staging/deploy/maven2/' 132 | def snapshotsRepoUrl = 'https://oss.sonatype.org/content/repositories/snapshots/' 133 | url = version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl 134 | credentials { 135 | username System.getenv('CI_DEPLOY_USERNAME') 136 | password System.getenv('CI_DEPLOY_PASSWORD') 137 | } 138 | } 139 | } 140 | } 141 | 142 | signing { 143 | useGpgCmd() 144 | if (!version.endsWith('SNAPSHOT')) { 145 | sign publishing.publications.mavenJava 146 | sign publishing.publications.mavenJavacppPlatform 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /samples/zlib/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | mkdir -p build/$PLATFORM 5 | cd build/$PLATFORM 6 | 7 | ZLIB_VERSION=1.3.1 8 | if [[ ! -e "zlib-$ZLIB_VERSION.tar.gz" ]]; then 9 | curl -L "http://zlib.net/zlib-$ZLIB_VERSION.tar.gz" -o "zlib-$ZLIB_VERSION.tar.gz" 10 | fi 11 | echo "9a93b2b7dfdac77ceba5a558a580e74667dd6fede4585b91eefb60f03b72df23 zlib-$ZLIB_VERSION.tar.gz" | shasum -a 256 -c - 12 | 13 | echo "Decompressing archives..." 14 | tar --totals -xf "zlib-$ZLIB_VERSION.tar.gz" 15 | cd zlib-$ZLIB_VERSION 16 | 17 | case $PLATFORM in 18 | android-arm) 19 | $PLATFORM_ROOT/build/tools/make_standalone_toolchain.py --arch arm --api 21 --install-dir=../toolchain 20 | export PATH=`pwd`/../toolchain/bin/:$PATH 21 | CC="arm-linux-androideabi-clang -fPIC" ./configure --prefix=.. --static 22 | make -j $MAKEJ 23 | make install 24 | ;; 25 | android-arm64) 26 | $PLATFORM_ROOT/build/tools/make_standalone_toolchain.py --arch arm64 --api 21 --install-dir=../toolchain 27 | export PATH=`pwd`/../toolchain/bin/:$PATH 28 | CC="aarch64-linux-android-clang -fPIC" ./configure --prefix=.. --static 29 | make -j $MAKEJ 30 | make install 31 | ;; 32 | android-x86) 33 | $PLATFORM_ROOT/build/tools/make_standalone_toolchain.py --arch x86 --api 21 --install-dir=../toolchain 34 | export PATH=`pwd`/../toolchain/bin/:$PATH 35 | CC="i686-linux-android-clang -fPIC" ./configure --prefix=.. --static 36 | make -j $MAKEJ 37 | make install 38 | ;; 39 | android-x86_64) 40 | $PLATFORM_ROOT/build/tools/make_standalone_toolchain.py --arch x86_64 --api 21 --install-dir=../toolchain 41 | export PATH=`pwd`/../toolchain/bin/:$PATH 42 | CC="x86_64-linux-android-clang -fPIC" ./configure --prefix=.. --static 43 | make -j $MAKEJ 44 | make install 45 | ;; 46 | linux-x86) 47 | CC="gcc -m32 -fPIC" ./configure --prefix=.. --static 48 | make -j $MAKEJ 49 | make install 50 | ;; 51 | linux-x86_64) 52 | CC="gcc -m64 -fPIC" ./configure --prefix=.. --static 53 | make -j $MAKEJ 54 | make install 55 | ;; 56 | macosx-x86_64) 57 | ./configure --prefix=.. --static 58 | make -j $MAKEJ 59 | make install 60 | ;; 61 | windows-x86) 62 | nmake -f win32/Makefile.msc zlib.lib 63 | mkdir -p ../include ../lib 64 | cp zconf.h zlib.h ../include/ 65 | cp zlib.lib ../lib/ 66 | ;; 67 | windows-x86_64) 68 | nmake -f win32/Makefile.msc zlib.lib 69 | mkdir -p ../include ../lib 70 | cp zconf.h zlib.h ../include/ 71 | cp zlib.lib ../lib/ 72 | ;; 73 | *) 74 | echo "Error: Platform \"$PLATFORM\" is not supported" 75 | ;; 76 | esac 77 | 78 | cd ../../.. 79 | -------------------------------------------------------------------------------- /samples/zlib/settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | mavenLocal() 4 | mavenCentral() 5 | maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' } 6 | gradlePluginPortal() 7 | } 8 | } 9 | 10 | rootProject.name = 'zlib' 11 | 12 | gradle.rootProject { ext.javacppVersion = '1.5.10' } 13 | -------------------------------------------------------------------------------- /samples/zlib/src/main/java/org/bytedeco/zlib/presets/zlib.java: -------------------------------------------------------------------------------- 1 | package org.bytedeco.zlib.presets; 2 | 3 | import org.bytedeco.javacpp.*; 4 | import org.bytedeco.javacpp.annotation.*; 5 | import org.bytedeco.javacpp.tools.*; 6 | 7 | @Properties( 8 | value = { 9 | @Platform(include = "", link = "z@.1#"), 10 | @Platform(value = "windows", link = "zlib#") 11 | }, 12 | target = "org.bytedeco.zlib", 13 | global = "org.bytedeco.zlib.global.zlib" 14 | ) 15 | public class zlib implements InfoMapper { 16 | static { Loader.checkVersion("org.bytedeco", "zlib"); } 17 | 18 | public void map(InfoMap infoMap) { 19 | infoMap.put(new Info("ZEXTERN", "ZEXPORT", "z_const", "zlib_version").cppTypes().annotations()) 20 | .put(new Info("FAR").cppText("#define FAR")) 21 | .put(new Info("OF").cppText("#define OF(args) args")) 22 | .put(new Info("Z_ARG").cppText("#define Z_ARG(args) args")) 23 | .put(new Info("Byte", "Bytef", "charf").cast().valueTypes("byte").pointerTypes("BytePointer")) 24 | .put(new Info("uInt", "uIntf").cast().valueTypes("int").pointerTypes("IntPointer")) 25 | .put(new Info("uLong", "uLongf", "z_crc_t", "z_off_t", "z_size_t").cast().valueTypes("long").pointerTypes("CLongPointer")) 26 | .put(new Info("z_off64_t").cast().valueTypes("long").pointerTypes("LongPointer")) 27 | .put(new Info("voidp", "voidpc", "voidpf").valueTypes("Pointer")) 28 | .put(new Info("gzFile_s").pointerTypes("gzFile")) 29 | .put(new Info("gzFile").valueTypes("gzFile")) 30 | .put(new Info("Z_LARGE64", "!defined(ZLIB_INTERNAL) && defined(Z_WANT64)").define(false)) 31 | .put(new Info("inflateGetDictionary", "gzopen_w", "gzvprintf").skip()); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /samples/zlib/src/test/java/org/bytedeco/zlib/UnitTest.java: -------------------------------------------------------------------------------- 1 | package org.bytedeco.zlib; 2 | 3 | import org.junit.Test; 4 | import static org.bytedeco.zlib.global.zlib.*; 5 | 6 | public class UnitTest { 7 | @Test public void test() { 8 | System.out.println(zlibVersion().getString()); 9 | } 10 | } 11 | 12 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'gradle-javacpp' 2 | -------------------------------------------------------------------------------- /src/main/java/org/bytedeco/gradle/javacpp/BuildExecutor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 Samuel Audet 3 | * 4 | * Licensed either under the Apache License, Version 2.0, or (at your option) 5 | * under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation (subject to the "Classpath" exception), 7 | * either version 2, or any later version (collectively, the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * http://www.gnu.org/licenses/ 13 | * http://www.gnu.org/software/classpath/license.html 14 | * 15 | * or as provided in the LICENSE.txt file that accompanied this code. 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | package org.bytedeco.gradle.javacpp; 23 | 24 | import java.io.File; 25 | import java.io.IOException; 26 | import java.util.List; 27 | import java.util.Map; 28 | import org.bytedeco.javacpp.tools.CommandExecutor; 29 | import org.bytedeco.javacpp.tools.Logger; 30 | import org.gradle.initialization.DefaultBuildCancellationToken; 31 | import org.gradle.internal.concurrent.DefaultExecutorFactory; 32 | import org.gradle.internal.concurrent.ManagedExecutor; 33 | import org.gradle.internal.file.PathToFileResolver; 34 | import org.gradle.process.internal.DefaultExecAction; 35 | 36 | /** 37 | * Overrides use of ProcessBuilder with something that works within Gradle. 38 | * 39 | * @author Samuel Audet 40 | */ 41 | public class BuildExecutor extends CommandExecutor { 42 | public BuildExecutor(Logger logger) { 43 | super(logger); 44 | } 45 | 46 | @Override public int executeCommand(List command, File workingDirectory, 47 | Map environmentVariables) throws IOException, InterruptedException { 48 | PathToFileResolver resolver = new PathToFileResolver() { 49 | @Override public File resolve(Object path) { return (File)path; } 50 | @Override public PathToFileResolver newResolver(File baseDir) { return this; } 51 | @Override public boolean canResolveRelativePath() { return true; } 52 | }; 53 | ManagedExecutor executor = new DefaultExecutorFactory().create("BuildExecutor"); 54 | try { 55 | DefaultExecAction action = new DefaultExecAction(resolver, executor, new DefaultBuildCancellationToken()); 56 | action.setCommandLine(command); 57 | if (workingDirectory != null) { 58 | action.workingDir(workingDirectory); 59 | } else { 60 | try { 61 | action.workingDir(new File(".").getCanonicalFile()); 62 | } catch (IOException ex) { 63 | action.workingDir(new File(".").getAbsoluteFile()); 64 | } 65 | } 66 | if (environmentVariables != null) { 67 | for (Map.Entry e : environmentVariables.entrySet()) { 68 | if (e.getKey() != null && e.getValue() != null) { 69 | action.environment(e.getKey(), e.getValue()); 70 | } 71 | } 72 | } 73 | return action.execute().getExitValue(); 74 | } finally { 75 | executor.shutdownNow(); 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/org/bytedeco/gradle/javacpp/BuildExtension.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020-2022 Samuel Audet 3 | * 4 | * Licensed either under the Apache License, Version 2.0, or (at your option) 5 | * under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation (subject to the "Classpath" exception), 7 | * either version 2, or any later version (collectively, the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * http://www.gnu.org/licenses/ 13 | * http://www.gnu.org/software/classpath/license.html 14 | * 15 | * or as provided in the LICENSE.txt file that accompanied this code. 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | package org.bytedeco.gradle.javacpp; 23 | 24 | import groovy.util.Node; 25 | import java.io.File; 26 | import java.io.IOException; 27 | import java.lang.reflect.Constructor; 28 | import java.lang.reflect.Field; 29 | import java.nio.file.Files; 30 | import java.nio.file.StandardCopyOption; 31 | import java.util.ArrayList; 32 | import java.util.List; 33 | import org.gradle.api.Action; 34 | import org.gradle.api.Project; 35 | import org.gradle.api.XmlProvider; 36 | import org.gradle.api.artifacts.Configuration; 37 | import org.gradle.api.artifacts.ResolvedArtifact; 38 | import org.gradle.api.artifacts.ResolvedDependency; 39 | import org.gradle.api.internal.project.DefaultProject; 40 | import org.gradle.api.internal.tasks.DefaultTaskDependencyFactory; 41 | import org.gradle.api.internal.tasks.TaskDependencyFactory; 42 | import org.gradle.api.plugins.BasePluginConvention; 43 | import org.gradle.api.publish.maven.MavenArtifact; 44 | import org.gradle.api.publish.maven.MavenPom; 45 | import org.gradle.api.publish.maven.internal.artifact.FileBasedMavenArtifact; 46 | import org.slf4j.Logger; 47 | import org.slf4j.LoggerFactory; 48 | 49 | /** 50 | * Provides helper methods intended to be used with the "maven-publish" plugin. 51 | * 52 | * @author Samuel Audet 53 | */ 54 | public class BuildExtension { 55 | private static final Constructor compatibleArtifactConstructor; 56 | private static final boolean isLegacy; 57 | private final Logger logger = LoggerFactory.getLogger(BuildExtension.class); 58 | 59 | BuildPlugin plugin; 60 | Project project; 61 | 62 | static { 63 | boolean legacyCheck; 64 | Constructor compatibleConstructor; 65 | try { 66 | // If gradle version is lower than 6.2, use legacy constructor. 67 | compatibleConstructor = FileBasedMavenArtifact.class.getConstructor(File.class); 68 | legacyCheck = true; 69 | } catch (NoSuchMethodException e) { 70 | try { 71 | // If gradle version is equals or higher than 6.2, use latest constructor. 72 | compatibleConstructor = FileBasedMavenArtifact.class.getConstructor(File.class, TaskDependencyFactory.class); 73 | legacyCheck = false; 74 | } catch (NoSuchMethodException e2) { 75 | // If no compatible constructor found, constructor signature modified on latest version and do not compatible with this code. 76 | // Throw exception to prevent build. 77 | throw new RuntimeException("Could not find constructor for FileBasedMavenArtifact (Incompatible with this gradle version)", e); 78 | } 79 | } 80 | isLegacy = legacyCheck; 81 | compatibleArtifactConstructor = compatibleConstructor; 82 | } 83 | 84 | public BuildExtension(BuildPlugin plugin) { 85 | this.plugin = plugin; 86 | this.project = plugin.project; 87 | } 88 | 89 | /** 90 | * Copies artifacts that can be resolved from the configuration's dependencies, while 91 | * excluding the JAR file being built. With this, we can easily republish all JAR files 92 | * with classifiers at the same time, successfully working around Gradle's limitations. 93 | * 94 | * @param configuration containing dependencies to use 95 | * @return copies of existing artifacts 96 | * @throws java.io.IOException when JAR files cannot be copied into the project's build libs directory 97 | * @see https://github.com/gradle/gradle/issues/2882 98 | */ 99 | public List existingArtifacts(Configuration configuration) throws IOException { 100 | ArrayList artifacts = new ArrayList(); 101 | BasePluginConvention bc = project.getConvention().getPlugin(BasePluginConvention.class); 102 | File libsDir = new File(project.getBuildDir(), bc.getLibsDirName()); 103 | libsDir.mkdirs(); 104 | try { 105 | // Temporarily rename our project to prevent Gradle from resolving the artifacts to project dependencies without files. 106 | Field nameField = DefaultProject.class.getDeclaredField("name"); 107 | nameField.setAccessible(true); 108 | String name = (String)nameField.get(project); 109 | nameField.set(project, name + "-renamed"); 110 | for (ResolvedDependency rd : configuration.getResolvedConfiguration().getLenientConfiguration().getFirstLevelModuleDependencies()) { 111 | if (rd.getModuleGroup().equals(project.getGroup()) && rd.getModuleName().equals(name)) { 112 | for (ResolvedArtifact ra : rd.getModuleArtifacts()) { 113 | if (ra.getClassifier() != null && !ra.getClassifier().equals(plugin.getPlatform() + plugin.getPlatformExtension())) { 114 | try { 115 | File in = ra.getFile(); 116 | File out = new File(libsDir, in.getName()); 117 | Files.copy(in.toPath(), out.toPath(), StandardCopyOption.REPLACE_EXISTING); 118 | MavenArtifact ma = isLegacy ? compatibleArtifactConstructor.newInstance(out) : 119 | compatibleArtifactConstructor.newInstance(out, DefaultTaskDependencyFactory.withNoAssociatedProject()); 120 | ma.setClassifier(ra.getClassifier()); 121 | artifacts.add(ma); 122 | } catch (RuntimeException e) { 123 | // probably ArtifactNotFoundException -> ignore 124 | } 125 | } 126 | } 127 | } 128 | } 129 | nameField.set(project, name); 130 | } catch (ReflectiveOperationException e) { 131 | logger.warn("Could not get artifacts: " + e); 132 | } 133 | return artifacts; 134 | } 135 | 136 | /** Returns {@code xmlAction(configuration, null)}. */ 137 | public Action xmlAction(Configuration configuration) { 138 | return xmlAction(configuration, null); 139 | } 140 | /** 141 | * Returns object to be called with {@link MavenPom#withXml(Action)} to create a pom.xml file for "-platform" artifacts. 142 | * 143 | * @param configuration containing dependencies to use 144 | * @param extension like "-gpl", "-gpu", "-python", etc (optional) 145 | * @return an {@link Action} that fills up an {@link XmlProvider} 146 | * @see PlatformPlugin 147 | * @see Reducing the Number of Dependencies 148 | */ 149 | public Action xmlAction(final Configuration configuration, final String extension) { 150 | return new Action() { public void execute(XmlProvider xml) { 151 | String[] allPlatforms = {"android-arm", "android-arm64", "android-x86", "android-x86_64", 152 | "ios-arm", "ios-arm64", "ios-x86", "ios-x86_64", 153 | "linux-armhf", "linux-arm64", "linux-ppc64le", "linux-x86", "linux-x86_64", 154 | "macosx-arm64", "macosx-x86_64", "windows-x86", "windows-x86_64"}; 155 | 156 | String[] osNameFrom = {"linux", "mac os x", "windows"}; 157 | String[] osNameKernel = {"linux", "darwin", "windows"}; 158 | String[] osNameType = {"name", "name", "family"}; 159 | String[] osNameTo = {"linux", "macosx", "windows"}; 160 | 161 | String[] osArchFrom = {"arm", "aarch64", "armv8", "ppc64le", "i386", "i486", "i586", "i686", "amd64", "x86-64"}; 162 | String[] osArchTo = {"armhf", "arm64", "arm64", "ppc64le", "x86", "x86", "x86", "x86", "x86_64", "x86_64"}; 163 | 164 | ArrayList platforms = new ArrayList(); 165 | Node propertiesNode = xml.asNode().appendNode("properties"); 166 | Node dependenciesNode = xml.asNode().appendNode("dependencies"); 167 | for (ResolvedDependency rd : configuration.getResolvedConfiguration().getLenientConfiguration().getFirstLevelModuleDependencies()) { 168 | if (rd.getModuleGroup().equals(project.getGroup()) && rd.getModuleName().equals(project.getName())) { 169 | Node dependencyNode = dependenciesNode.appendNode("dependency"); 170 | dependencyNode.appendNode("groupId", rd.getModuleGroup()); 171 | dependencyNode.appendNode("artifactId", rd.getModuleName()); 172 | dependencyNode.appendNode("version", rd.getModuleVersion()); 173 | } 174 | for (ResolvedArtifact ra : rd.getModuleArtifacts()) { 175 | Node dependencyNode = dependenciesNode.appendNode("dependency"); 176 | dependencyNode.appendNode("groupId", rd.getModuleGroup()); 177 | dependencyNode.appendNode("artifactId", rd.getModuleName()); 178 | dependencyNode.appendNode("version", rd.getModuleVersion()); 179 | if (ra.getClassifier() != null) { 180 | String platform = ra.getClassifier(); 181 | if (extension != null && platform.endsWith(extension)) { 182 | platform = platform.substring(0, platform.length() - extension.length()); 183 | } 184 | dependencyNode.appendNode("classifier", "${javacpp.platform." + platform + "}"); 185 | platforms.add(platform); 186 | } 187 | } 188 | } 189 | 190 | propertiesNode.appendNode("javacpp.platform.extension", extension != null ? extension : ""); 191 | for (String platform : platforms) { 192 | propertiesNode.appendNode("javacpp.platform." + platform, platform + "${javacpp.platform.extension}"); 193 | } 194 | 195 | Node profilesNode = xml.asNode().appendNode("profiles"); 196 | Node profileNode = profilesNode.appendNode("profile"); 197 | profileNode.appendNode("id", "javacpp-platform-default"); 198 | profileNode.appendNode("activation").appendNode("property").appendNode("name", "!javacpp.platform"); 199 | propertiesNode = profileNode.appendNode("properties"); 200 | propertiesNode.appendNode("javacpp.platform", "${os.name}-${os.arch}"); 201 | 202 | profileNode = profilesNode.appendNode("profile"); 203 | profileNode.appendNode("id", "javacpp-platform-custom"); 204 | profileNode.appendNode("activation").appendNode("property").appendNode("name", "javacpp.platform"); 205 | propertiesNode = profileNode.appendNode("properties"); 206 | for (String profilePlatform : platforms) { 207 | propertiesNode.appendNode("javacpp.platform." + profilePlatform, "${javacpp.platform}${javacpp.platform.extension}"); 208 | } 209 | 210 | profileNode = profilesNode.appendNode("profile"); 211 | profileNode.appendNode("id", "javacpp-platform-host"); 212 | profileNode.appendNode("activation").appendNode("property").appendNode("name", "javacpp.platform.host"); 213 | propertiesNode = profileNode.appendNode("properties"); 214 | propertiesNode.appendNode("javacpp.platform", "${os.name}-${os.arch}${javacpp.platform.extension}"); 215 | for (String profilePlatform : platforms) { 216 | propertiesNode.appendNode("javacpp.platform." + profilePlatform, "${os.name}-${os.arch}${javacpp.platform.extension}"); 217 | } 218 | 219 | profileNode = profilesNode.appendNode("profile"); 220 | profileNode.appendNode("id", "javacpp.platform.custom-true"); 221 | profileNode.appendNode("activation").appendNode("property").appendNode("name", "javacpp.platform.custom"); 222 | propertiesNode = profileNode.appendNode("properties"); 223 | propertiesNode.appendNode("javacpp.platform", ""); 224 | for (String profilePlatform : platforms) { 225 | propertiesNode.appendNode("javacpp.platform." + profilePlatform, ""); 226 | } 227 | 228 | profileNode = profilesNode.appendNode("profile"); 229 | profileNode.appendNode("id", "javacpp-platform-none"); 230 | profileNode.appendNode("activation").appendNode("property").appendNode("name", "javacpp.platform.none"); 231 | propertiesNode = profileNode.appendNode("properties"); 232 | propertiesNode.appendNode("javacpp.platform", ""); 233 | for (String profilePlatform : platforms) { 234 | propertiesNode.appendNode("javacpp.platform." + profilePlatform, ""); 235 | } 236 | 237 | for (String platform : platforms) { 238 | profileNode = profilesNode.appendNode("profile"); 239 | profileNode.appendNode("id", "javacpp-platform-" + platform); 240 | Node activationPropertyNode = profileNode.appendNode("activation").appendNode("property"); 241 | activationPropertyNode.appendNode("name", "javacpp.platform"); 242 | activationPropertyNode.appendNode("value", platform); 243 | propertiesNode = profileNode.appendNode("properties"); 244 | propertiesNode.appendNode("javacpp.platform", platform); 245 | for (String profilePlatform : platforms) { 246 | propertiesNode.appendNode("javacpp.platform." + profilePlatform, 247 | platform == profilePlatform ? "${javacpp.platform}${javacpp.platform.extension}" : ""); 248 | } 249 | } 250 | 251 | // Profiles to modify the transitive dependencies when picked up from other pom.xml files, for example: 252 | // mvn -Djavacpp.platform.custom -Djavacpp.platform.host -Djavacpp.platform.linux-x86_64 -Djavacpp.platform.windows-x86_64 ... 253 | for (String platform : platforms) { 254 | profileNode = profilesNode.appendNode("profile"); 255 | profileNode.appendNode("id", "javacpp.platform." + platform + "-true"); 256 | profileNode.appendNode("activation").appendNode("property").appendNode("name", "javacpp.platform." + platform); 257 | profileNode.appendNode("properties").appendNode("javacpp.platform." + platform, platform + "${javacpp.platform.extension}"); 258 | } 259 | 260 | for (int i = 0; i < osNameFrom.length; i++) { 261 | for (int j = 0; j < osArchFrom.length; j++) { 262 | String[] osArchs = osArchFrom[j].equals(osArchTo[j]) || (j + 1 < osArchTo.length && osArchTo[j].equals(osArchTo[j + 1])) 263 | ? new String[] { osArchFrom[j] } 264 | : new String[] { osArchFrom[j], osArchTo[j] }; 265 | for (String osArch : osArchs) { 266 | String platform = osNameTo[i] + "-" + osArchTo[j]; 267 | if (platforms.contains(platform)) { 268 | profileNode = profilesNode.appendNode("profile"); 269 | profileNode.appendNode("id", "javacpp.platform.custom-" + osNameTo[i] + "-" + osArch); 270 | Node activationNode = profileNode.appendNode("activation"); 271 | activationNode.appendNode("property").appendNode("name", "javacpp.platform.host"); 272 | Node osNode = activationNode.appendNode("os"); 273 | osNode.appendNode(osNameType[i], osNameFrom[i]); 274 | osNode.appendNode("arch", osArch); 275 | profileNode.appendNode("properties").appendNode("javacpp.platform." + platform, platform + "${javacpp.platform.extension}"); 276 | } 277 | } 278 | } 279 | } 280 | 281 | // Profiles to set the default javacpp.platform property: If someone knows a better way to do this, please do let me know! 282 | for (int i = 0; i < osNameFrom.length; i++) { 283 | profileNode = profilesNode.appendNode("profile"); 284 | profileNode.appendNode("id", osNameTo[i]); 285 | profileNode.appendNode("activation").appendNode("os").appendNode(osNameType[i], osNameFrom[i]); 286 | propertiesNode = profileNode.appendNode("properties"); 287 | propertiesNode.appendNode("os.kernel", osNameKernel[i]); 288 | propertiesNode.appendNode("os.name", osNameTo[i]); 289 | } 290 | 291 | for (int i = 0; i < osArchFrom.length; i++) { 292 | if (!osArchFrom[i].equals(osArchTo[i])) { 293 | profileNode = profilesNode.appendNode("profile"); 294 | profileNode.appendNode("id", osArchFrom[i]); 295 | profileNode.appendNode("activation").appendNode("os").appendNode("arch", osArchFrom[i]); 296 | profileNode.appendNode("properties").appendNode("os.arch", osArchTo[i]); 297 | } 298 | } 299 | }}; 300 | } 301 | } 302 | -------------------------------------------------------------------------------- /src/main/java/org/bytedeco/gradle/javacpp/BuildPlugin.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020-2022 Samuel Audet 3 | * 4 | * Licensed either under the Apache License, Version 2.0, or (at your option) 5 | * under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation (subject to the "Classpath" exception), 7 | * either version 2, or any later version (collectively, the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * http://www.gnu.org/licenses/ 13 | * http://www.gnu.org/software/classpath/license.html 14 | * 15 | * or as provided in the LICENSE.txt file that accompanied this code. 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | package org.bytedeco.gradle.javacpp; 23 | 24 | import java.io.File; 25 | import java.io.IOException; 26 | import java.lang.reflect.InvocationTargetException; 27 | import java.lang.reflect.Method; 28 | import java.util.Arrays; 29 | import java.util.Properties; 30 | import java.util.Set; 31 | import org.bytedeco.javacpp.Loader; 32 | import org.gradle.api.Action; 33 | import org.gradle.api.Project; 34 | import org.gradle.api.Plugin; 35 | import org.gradle.api.Task; 36 | import org.gradle.api.file.FileTreeElement; 37 | import org.gradle.api.plugins.JavaPlugin; 38 | import org.gradle.api.plugins.JavaPluginConvention; 39 | import org.gradle.api.provider.Property; 40 | import org.gradle.api.specs.Spec; 41 | import org.gradle.api.tasks.SourceSet; 42 | import org.gradle.api.tasks.TaskProvider; 43 | import org.gradle.api.tasks.WriteProperties; 44 | import org.gradle.api.tasks.bundling.Jar; 45 | import org.gradle.api.tasks.compile.JavaCompile; 46 | 47 | /** 48 | * This plugin creates new packages containing native libraries using JavaCPP. 49 | * It defines the following extra property: 50 | *

    51 | *
  • "javacppPlatform", which defaults to {@link Loader#getPlatform()}, 52 | *
  • "javacppPlatformExtension", which defaults to an empty string, 53 | *

54 | * 55 | * creates the following extension: 56 | *

    57 | *
  • "javacppBuild", an instance of {@link BuildExtension}, 58 | *

59 | * 60 | * as well as the following configuration: 61 | *

    62 | *
  • "javacppPlatform", to be used to specify dependencies for the "-platform" artifact, 63 | *

64 | * 65 | * and registers the following tasks: 66 | *

    67 | *
  • "javacppBuildCommand" to execute {@link BuildTask#buildCommand}, 68 | *
  • "javacppCompileJava" to compile classes needed by the parser, 69 | *
  • "javacppBuildParser" to run the parser on these classes, 70 | *
  • "javacppBuildCompiler" to generate and compile JNI code, 71 | *
  • "javacppPomProperties" to write version information to pom.properties, 72 | *
  • "javacppJar" to archive the native libraries in a separate JAR file, 73 | *
  • "javacppPlatformJar", to create an empty JAR file for the main "-platform" artifact, 74 | *
  • "javacppPlatformJavadocJar", to create an empty JAR file for the "-platform" javadoc artifact, and 75 | *
  • "javacppPlatformSourcesJar", to create an empty JAR file for the "-platform" sources artifact, 76 | *

77 | * 78 | * @author Samuel Audet 79 | */ 80 | public class BuildPlugin implements Plugin { 81 | Project project; 82 | 83 | String getPlatform() { 84 | return (String)project.findProperty("javacppPlatform"); 85 | } 86 | 87 | String getPlatformExtension() { 88 | return (String)project.findProperty("javacppPlatformExtension"); 89 | } 90 | 91 | boolean isLibraryPath(String path) { 92 | String p = (String)project.findProperty("javacpp.platform.library.path"); 93 | return p != null && p.length() > 0 ? path.startsWith(p) : path.contains("/" + getPlatform() + getPlatformExtension() + "/"); 94 | } 95 | 96 | private void setProperty(String originalMethod, String propertyField, Object target, T value) { 97 | Method method = findMethod(target.getClass(), originalMethod, value.getClass()); 98 | if (method != null) { 99 | try { 100 | invoke(method, target, value); 101 | } catch (Exception e) { 102 | throw new RuntimeException("Cannot set property " + method.getName() + " in " + target.getClass(), e); 103 | } 104 | } else { 105 | Method propertyGetter = findMethod(target.getClass(), propertyField); 106 | if (propertyGetter == null) { 107 | throw new RuntimeException("Cannot find property getter method " + propertyField + " in " + target.getClass()); 108 | } 109 | ((Property) invoke(propertyGetter, target)).set(value); 110 | } 111 | } 112 | 113 | private T getProperty(String originalMethod, String propertyMethod, Object target) { 114 | Method method = findMethod(target.getClass(), originalMethod); 115 | if (method != null) { 116 | return (T) invoke(method, target); 117 | } 118 | Method propertyGetter = findMethod(target.getClass(), propertyMethod); 119 | if (propertyGetter == null) { 120 | throw new RuntimeException("Cannot find property getter method " + propertyMethod + " in " + target.getClass()); 121 | } 122 | return ((Property) invoke(propertyGetter, target)).get(); 123 | } 124 | 125 | private Method findMethod(Class cls, String methodName) { 126 | for (Method method : cls.getMethods()) { 127 | if (method.getName().equals(methodName)) { 128 | return method; 129 | } 130 | } 131 | return null; 132 | } 133 | 134 | private Method findMethod(Class cls, String methodName, Class... parameterTypes) { 135 | try { 136 | return cls.getMethod(methodName, parameterTypes); 137 | } catch (NoSuchMethodException e) { 138 | return null; 139 | } 140 | } 141 | 142 | private T invoke(Method method, Object target, Object... parameter) { 143 | try { 144 | return (T) method.invoke(target, parameter); 145 | } catch (IllegalAccessException | InvocationTargetException e) { 146 | throw new RuntimeException(e); 147 | } 148 | } 149 | 150 | @Override public void apply(final Project project) { 151 | this.project = project; 152 | if (!project.hasProperty("javacppPlatform")) { 153 | project.getExtensions().getExtraProperties().set("javacppPlatform", Loader.Detector.getPlatform()); 154 | } 155 | if (!project.hasProperty("javacppPlatformExtension")) { 156 | project.getExtensions().getExtraProperties().set("javacppPlatformExtension", ""); 157 | } 158 | if (project.getExtensions().findByName("javacppBuild") == null) { 159 | project.getExtensions().create("javacppBuild", BuildExtension.class, this); 160 | } 161 | 162 | project.getPlugins().withType(JavaPlugin.class, new Action() { public void execute(JavaPlugin javaPlugin) { 163 | final JavaPluginConvention jc = project.getConvention().getPlugin(JavaPluginConvention.class); 164 | final SourceSet main = jc.getSourceSets().getByName("main"); 165 | final Set files = main.getOutput().getClassesDirs().getFiles(); 166 | final String[] paths = new String[files.size()]; 167 | int n = 0; 168 | for (File file : files) { 169 | try { 170 | paths[n++] = file.getCanonicalPath(); 171 | } catch (IOException ex) { 172 | paths[n++] = file.getAbsolutePath(); 173 | } 174 | } 175 | 176 | project.getTasks().register("javacppBuildCommand", 177 | BuildTask.class, new Action() { public void execute(BuildTask task) { 178 | task.classPath = paths; 179 | task.properties = getPlatform(); 180 | if (getPlatformExtension() != null && getPlatformExtension().length() > 0) { 181 | task.propertyKeysAndValues = new Properties(); 182 | task.propertyKeysAndValues.setProperty("platform.extension", getPlatformExtension()); 183 | } 184 | task.classOrPackageNames = new String[0]; 185 | task.workingDirectory = project.getProjectDir(); 186 | }}); 187 | 188 | project.getTasks().register("javacppCompileJava", 189 | JavaCompile.class, new Action() { public void execute(JavaCompile task) { 190 | task.setSource(main.getJava()); 191 | task.setClasspath(main.getCompileClasspath()); 192 | setProperty( 193 | "setDestinationDir", // Deprecated in 7.1, will be removed in Gradle 9.0 194 | "getDestinationDirectory", // Since 6.1 195 | task, 196 | getProperty( 197 | "getOutputDir", // Deprecated in 7.1, removed in Gradle 8.0 198 | "getClassesDirectory", // Since 6.1 199 | main.getJava() 200 | ) 201 | ); 202 | task.dependsOn("javacppBuildCommand"); 203 | }}); 204 | 205 | project.getTasks().register("javacppBuildParser", 206 | BuildTask.class, new Action() { public void execute(final BuildTask task) { 207 | task.classPath = paths; 208 | task.properties = getPlatform(); 209 | if (getPlatformExtension() != null && getPlatformExtension().length() > 0) { 210 | task.propertyKeysAndValues = new Properties(); 211 | task.propertyKeysAndValues.setProperty("platform.extension", getPlatformExtension()); 212 | } 213 | if (task.outputDirectory == null) { 214 | task.outputDirectory = main.getJava().getSrcDirs().iterator().next(); 215 | } 216 | task.dependsOn("javacppCompileJava"); 217 | task.doFirst(new Action() { public void execute(Task t) { main.getJava().srcDir(task.outputDirectory); }}); 218 | }}); 219 | 220 | project.getTasks().getByName("compileJava").dependsOn("javacppBuildParser"); 221 | 222 | project.getTasks().register("javacppBuildCompiler", 223 | BuildTask.class, new Action() { public void execute(BuildTask task) { 224 | task.classPath = paths; 225 | task.properties = getPlatform(); 226 | if (getPlatformExtension() != null && getPlatformExtension().length() > 0) { 227 | task.propertyKeysAndValues = new Properties(); 228 | task.propertyKeysAndValues.setProperty("platform.extension", getPlatformExtension()); 229 | } 230 | task.dependsOn("compileJava"); 231 | }}); 232 | 233 | project.getTasks().getByName("classes").dependsOn("javacppBuildCompiler"); 234 | 235 | project.getTasks().register("javacppPomProperties", 236 | WriteProperties.class, new Action() { public void execute(WriteProperties task) { 237 | Object group = project.findProperty("group"); 238 | Object name = project.findProperty("name"); 239 | Object version = project.findProperty("version"); 240 | task.property("groupId", group); 241 | task.property("artifactId", name); 242 | task.property("version", version); 243 | task.setOutputFile(new File(main.getOutput().getResourcesDir(), "META-INF/maven/" + group + "/" + name + "/pom.properties")); 244 | }}); 245 | 246 | Jar jarTask = (Jar)project.getTasks().getByName("jar"); 247 | jarTask.dependsOn("javacppPomProperties"); 248 | jarTask.exclude(new Spec() { public boolean isSatisfiedBy(FileTreeElement file) { 249 | return isLibraryPath(file.getPath()); 250 | }}); 251 | 252 | TaskProvider javacppJarTask = project.getTasks().register("javacppJar", 253 | Jar.class, new Action() { public void execute(Jar task) { 254 | task.from(main.getOutput()); 255 | setProperty( 256 | "setClassifier", // Deprecated in 7.0, removed in 8.0 257 | "getArchiveClassifier", // Since 5.1 258 | task, 259 | getPlatform() + getPlatformExtension()); 260 | task.include(new Spec() { public boolean isSatisfiedBy(FileTreeElement file) { 261 | return file.isDirectory() || isLibraryPath(file.getPath()); 262 | }}); 263 | task.dependsOn("jar"); 264 | }}); 265 | 266 | project.getArtifacts().add("archives", javacppJarTask); 267 | 268 | TaskProvider javacppPlatformJarTask = project.getTasks().register("javacppPlatformJar", 269 | Jar.class, new Action() { public void execute(Jar task) { 270 | setProperty( 271 | "setBaseName", // Deprecated in 7.0, removed in 8.0 272 | "getArchiveBaseName", // Since 5.1 273 | task, 274 | project.getName() + "-platform"); 275 | task.dependsOn("javacppJar"); 276 | }}); 277 | 278 | TaskProvider javacppPlatformJavadocJarTask = project.getTasks().register("javacppPlatformJavadocJar", 279 | Jar.class, new Action() { public void execute(Jar task) { 280 | setProperty( 281 | "setBaseName", // Deprecated in 7.0, removed in 8.0 282 | "getArchiveBaseName", // Since 5.1 283 | task, 284 | project.getName() + "-platform"); 285 | setProperty( 286 | "setClassifier", // Deprecated in 7.0, removed in 8.0 287 | "getArchiveClassifier", // Since 5.1 288 | task, 289 | "javadoc"); 290 | task.dependsOn("javacppPlatformJar"); 291 | }}); 292 | 293 | TaskProvider javacppPlatformSourcesTask = project.getTasks().register("javacppPlatformSourcesJar", 294 | Jar.class, new Action() { public void execute(Jar task) { 295 | setProperty( 296 | "setBaseName", // Deprecated in 7.0, removed in 8.0 297 | "getArchiveBaseName", // Since 5.1 298 | task, 299 | project.getName() + "-platform"); 300 | setProperty("setClassifier", "getArchiveClassifier", task, "sources"); 301 | task.dependsOn("javacppPlatformJar"); 302 | }}); 303 | 304 | project.getConfigurations().maybeCreate("javacppPlatform"); 305 | project.getArtifacts().add("javacppPlatform", javacppPlatformJarTask); 306 | project.getArtifacts().add("javacppPlatform", javacppPlatformJavadocJarTask); 307 | project.getArtifacts().add("javacppPlatform", javacppPlatformSourcesTask); 308 | }}); 309 | } 310 | } 311 | -------------------------------------------------------------------------------- /src/main/java/org/bytedeco/gradle/javacpp/BuildTask.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020-2022 Samuel Audet 3 | * 4 | * Licensed either under the Apache License, Version 2.0, or (at your option) 5 | * under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation (subject to the "Classpath" exception), 7 | * either version 2, or any later version (collectively, the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * http://www.gnu.org/licenses/ 13 | * http://www.gnu.org/software/classpath/license.html 14 | * 15 | * or as provided in the LICENSE.txt file that accompanied this code. 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | package org.bytedeco.gradle.javacpp; 23 | 24 | import java.io.File; 25 | import java.io.IOException; 26 | import java.util.Arrays; 27 | import java.util.Map; 28 | import java.util.Properties; 29 | import org.bytedeco.javacpp.Loader; 30 | import org.bytedeco.javacpp.tools.Builder; 31 | import org.bytedeco.javacpp.tools.Logger; 32 | import org.bytedeco.javacpp.tools.ParserException; 33 | import org.bytedeco.javacpp.tools.Slf4jLogger; 34 | import org.gradle.api.DefaultTask; 35 | import org.gradle.api.Task; 36 | import org.gradle.api.plugins.ExtraPropertiesExtension; 37 | import org.gradle.api.specs.Spec; 38 | import org.gradle.api.tasks.Classpath; 39 | import org.gradle.api.tasks.Input; 40 | import org.gradle.api.tasks.InputDirectory; 41 | import org.gradle.api.tasks.InputFile; 42 | import org.gradle.api.tasks.InputFiles; 43 | import org.gradle.api.tasks.Optional; 44 | import org.gradle.api.tasks.OutputDirectory; 45 | import org.gradle.api.tasks.TaskAction; 46 | 47 | /** 48 | * A Gradle task that wraps {@link Builder}. 49 | * 50 | * @author Samuel Audet 51 | */ 52 | public class BuildTask extends DefaultTask { 53 | /** Load user classes from classPath. */ 54 | String[] classPath = null; 55 | 56 | /** Add the path to the "platform.includepath" property. */ 57 | String[] includePath = null; 58 | 59 | /** Add the path to the "platform.includeresource" property. */ 60 | String[] includeResource = null; 61 | 62 | /** Add the path to the "platform.buildpath" property. */ 63 | String[] buildPath = null; 64 | 65 | /** Add the path to the "platform.buildresource" property. */ 66 | String[] buildResource = null; 67 | 68 | /** Add the path to the "platform.linkpath" property. */ 69 | String[] linkPath = null; 70 | 71 | /** Add the path to the "platform.linkresource" property. */ 72 | String[] linkResource = null; 73 | 74 | /** Add the path to the "platform.preloadpath" property. */ 75 | String[] preloadPath = null; 76 | 77 | /** Add the path to the "platform.preloadresource" property. */ 78 | String[] preloadResource = null; 79 | 80 | /** Add the path to the "platform.resourcepath" property. */ 81 | String[] resourcePath = null; 82 | 83 | /** Add the path to the "platform.executablepath" property. */ 84 | String[] executablePath = null; 85 | 86 | /** Specify the character encoding used for input and output. */ 87 | String encoding = null; 88 | 89 | /** Output all generated files to outputDirectory. */ 90 | File outputDirectory = null; 91 | 92 | /** Output everything in a file named after given outputName. */ 93 | String outputName = null; 94 | 95 | /** Delete all files from {@link #outputDirectory} before generating anything in it. */ 96 | boolean clean = false; 97 | 98 | /** Generate .cpp files from Java interfaces if found, parsing from header files if not. */ 99 | boolean generate = true; 100 | 101 | /** Compile and delete the generated .cpp files. */ 102 | boolean compile = true; 103 | 104 | /** Delete generated C++ JNI files after compilation */ 105 | boolean deleteJniFiles = true; 106 | 107 | /** Generate header file with declarations of callbacks functions. */ 108 | boolean header = false; 109 | 110 | /** Copy to output directory dependent libraries (link and preload). */ 111 | boolean copyLibs = false; 112 | 113 | /** Copy to output directory resources listed in properties. */ 114 | boolean copyResources = false; 115 | 116 | /** Also create config files for GraalVM native-image in directory. */ 117 | File configDirectory = null; 118 | 119 | /** Also create a JAR file named {@code -.jar}. */ 120 | String jarPrefix = null; 121 | 122 | /** Load all properties from resource. */ 123 | String properties = null; 124 | 125 | /** Load all properties from file. */ 126 | File propertyFile = null; 127 | 128 | /** Set property keys to values. */ 129 | Properties propertyKeysAndValues = null; 130 | 131 | /** Process only these classes or packages (suffixed with .* or .**). */ 132 | String[] classOrPackageNames = null; 133 | 134 | /** Execute a build command instead of JavaCPP itself, and return. */ 135 | String[] buildCommand = null; 136 | 137 | /** Add to Maven project source directory of Java files generated by buildCommand. */ 138 | String[] targetDirectory = null; 139 | 140 | /** Set the working directory of the build subprocess. */ 141 | File workingDirectory = null; 142 | 143 | /** Add environment variables to the compiler subprocess. */ 144 | Map environmentVariables = null; 145 | 146 | /** Pass compilerOptions directly to compiler. */ 147 | String[] compilerOptions = null; 148 | 149 | /** Skip the execution. */ 150 | boolean skip = false; 151 | 152 | public BuildTask() { 153 | // disable incremental builds until we get proper support for them 154 | getOutputs().upToDateWhen(new Spec() { public boolean isSatisfiedBy(Task t) { return false; }}); 155 | } 156 | 157 | @Optional @Classpath 158 | @InputFiles public String[] getClassPath() { return classPath; } public void setClassPath (String[] s) { classPath = s; } 159 | @Optional @Input public String[] getIncludePath() { return includePath; } public void setIncludePath (String[] s) { includePath = s; } 160 | @Optional @Input public String[] getIncludeResource() { return includeResource; } public void setIncludeResource(String[] s) { includeResource = s; } 161 | @Optional @Input public String[] getBuildPath() { return buildPath; } public void setBuildPath (String[] s) { buildPath = s; } 162 | @Optional @Input public String[] getBuildResource() { return buildResource; } public void setBuildResource (String[] s) { buildResource = s; } 163 | @Optional @Input public String[] getLinkPath() { return linkPath; } public void setLinkPath (String[] s) { linkPath = s; } 164 | @Optional @Input public String[] getLinkResource() { return linkResource; } public void setLinkResource (String[] s) { linkResource = s; } 165 | @Optional @Input public String[] getPreloadPath() { return preloadPath; } public void setPreloadPath (String[] s) { preloadPath = s; } 166 | @Optional @Input public String[] getPreloadResource() { return preloadResource; } public void setPreloadResource(String[] s) { preloadResource = s; } 167 | @Optional @Input public String[] getResourcePath() { return resourcePath; } public void setResourcePath (String[] s) { resourcePath = s; } 168 | @Optional @Input public String[] getExecutablePath() { return executablePath; } public void setExecutablePath (String[] s) { executablePath = s; } 169 | @Optional @Input public String getEncoding() { return encoding; } public void setEncoding (String s) { encoding = s; } 170 | @Optional 171 | @OutputDirectory public File getOutputDirectory() { return outputDirectory; } public void setOutputDirectory(File f) { outputDirectory = f; } 172 | @Optional @Input public String getOutputName() { return outputName; } public void setOutputName (String s) { outputName = s; } 173 | @Input public boolean getClean() { return clean; } public void setClean (boolean b) { clean = b; } 174 | @Input public boolean getGenerate() { return generate; } public void setGenerate (boolean b) { generate = b; } 175 | @Input public boolean getCompile() { return compile; } public void setCompile (boolean b) { compile = b; } 176 | @Input public boolean getDeleteJniFiles() { return deleteJniFiles; } public void setDeleteJniFiles (boolean b) { deleteJniFiles = b; } 177 | @Input public boolean getHeader() { return header; } public void setHeader (boolean b) { header = b; } 178 | @Input public boolean getCopyLibs() { return copyLibs; } public void setCopyLibs (boolean b) { copyLibs = b; } 179 | @Input public boolean getCopyResources() { return copyResources; } public void setCopyResources (boolean b) { copyResources = b; } 180 | @Optional 181 | @OutputDirectory public File getConfigDirectory() { return configDirectory; } public void setConfigDirectory(File f) { configDirectory = f; } 182 | @Optional @Input public String getJarPrefix() { return jarPrefix; } public void setJarPrefix (String s) { jarPrefix = s; } 183 | @Optional @Input public String getProperties() { return properties; } public void setProperties (String s) { properties = s; } 184 | @Optional @InputFile public File getPropertyFile() { return propertyFile; } public void setPropertyFile (File f) { propertyFile = f; } 185 | @Optional @Input public Properties getPropertyKeysAndValues() { return propertyKeysAndValues; } public void setPropertyKeysAndValues(Properties p) { propertyKeysAndValues = p; } 186 | @Optional @Input public String[] getClassOrPackageNames() { return classOrPackageNames; } public void setClassOrPackageNames (String[] s) { classOrPackageNames = s; } 187 | @Optional @Input public String[] getBuildCommand() { return buildCommand; } public void setBuildCommand (String[] s) { buildCommand = s; } 188 | @Optional @Input public String[] getTargetDirectory() { return targetDirectory; } public void setTargetDirectory (String[] s) { targetDirectory = s; } 189 | @Optional 190 | @InputDirectory public File getWorkingDirectory() { return workingDirectory; } public void setWorkingDirectory (File f) { workingDirectory = f; } 191 | @Optional @Input public Map getEnvironmentVariables() { return environmentVariables; } public void setEnvironmentVariables (Map m) { environmentVariables = m; } 192 | @Optional @Input public String[] getCompilerOptions() { return compilerOptions; } public void setCompilerOptions (String[] s) { compilerOptions = s; } 193 | @Input public boolean getSkip() { return skip; } public void setSkip (boolean b) { skip = b; } 194 | 195 | @TaskAction public void build() throws IOException, ClassNotFoundException, NoClassDefFoundError, InterruptedException, ParserException { 196 | Logger logger = new Slf4jLogger(Builder.class); 197 | 198 | if (getSkip()) { 199 | logger.info("Skipping execution of JavaCPP Builder"); 200 | return; 201 | } 202 | 203 | Builder builder = new Builder(logger) 204 | .classPaths(getClassPath()) 205 | .encoding(getEncoding()) 206 | .outputDirectory(getOutputDirectory()) 207 | .outputName(getOutputName()) 208 | .clean(getClean()) 209 | .generate(getGenerate()) 210 | .compile(getCompile()) 211 | .deleteJniFiles(getDeleteJniFiles()) 212 | .header(getHeader()) 213 | .copyLibs(getCopyLibs()) 214 | .copyResources(getCopyResources()) 215 | .configDirectory(getConfigDirectory()) 216 | .jarPrefix(getJarPrefix()) 217 | .properties(getProperties()) 218 | .propertyFile(getPropertyFile()) 219 | .properties(getPropertyKeysAndValues()) 220 | .classesOrPackages(getClassOrPackageNames()) 221 | .buildCommand(getBuildCommand()) 222 | .workingDirectory(getWorkingDirectory()) 223 | .environmentVariables(getEnvironmentVariables()) 224 | .compilerOptions(getCompilerOptions()) 225 | .commandExecutor(new BuildExecutor(logger)) 226 | 227 | .addProperty("platform.buildpath", getBuildPath()) 228 | .addProperty("platform.buildresource", getBuildResource()) 229 | .addProperty("platform.includepath", getIncludePath()) 230 | .addProperty("platform.includeresource", getIncludeResource()) 231 | .addProperty("platform.linkpath", getLinkPath()) 232 | .addProperty("platform.linkresource", getLinkResource()) 233 | .addProperty("platform.preloadpath", getPreloadPath()) 234 | .addProperty("platform.preloadresource", getPreloadResource()) 235 | .addProperty("platform.resourcepath", getResourcePath()) 236 | .addProperty("platform.executablepath", getExecutablePath()); 237 | 238 | String extension = builder.getProperty("platform.extension"); 239 | getLogger().info("Detected platform \"" + Loader.Detector.getPlatform() + "\""); 240 | getLogger().info("Building platform \"" + builder.getProperty("platform") + "\"" 241 | + (extension != null && extension.length() > 0 ? " with extension \"" + extension + "\"" : "")); 242 | 243 | ExtraPropertiesExtension projectProperties = getProject().getExtensions().getExtraProperties(); 244 | for (String key : builder.getProperties().stringPropertyNames()) { 245 | projectProperties.set("javacpp." + key, builder.getProperties().getProperty(key)); 246 | } 247 | 248 | File[] outputFiles = builder.build(); 249 | 250 | if (getLogger().isDebugEnabled()) { 251 | getLogger().debug("outputFiles: " + Arrays.deepToString(outputFiles)); 252 | } 253 | } 254 | } 255 | -------------------------------------------------------------------------------- /src/main/java/org/bytedeco/gradle/javacpp/PlatformPlugin.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020-2022 Samuel Audet 3 | * 4 | * Licensed either under the Apache License, Version 2.0, or (at your option) 5 | * under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation (subject to the "Classpath" exception), 7 | * either version 2, or any later version (collectively, the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * http://www.gnu.org/licenses/ 13 | * http://www.gnu.org/software/classpath/license.html 14 | * 15 | * or as provided in the LICENSE.txt file that accompanied this code. 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | package org.bytedeco.gradle.javacpp; 23 | 24 | import org.bytedeco.javacpp.Loader; 25 | import org.gradle.api.Action; 26 | import org.gradle.api.ActionConfiguration; 27 | import org.gradle.api.Plugin; 28 | import org.gradle.api.Project; 29 | 30 | /** 31 | * This plugin selects from existing artifacts the ones corresponding to user-specified platforms. 32 | * It defines the following extra property: 33 | *

    34 | *
  • "javacppPlatform", a comma-separated list, which defaults to {@link Loader#getPlatform()}; 35 | *

36 | * 37 | * and adds the following rule: 38 | *

    39 | *
  • {@link PlatformRule} that removes any platform dependencies not in "javacppPlatform". 40 | *

41 | 42 | * @author Samuel Audet 43 | */ 44 | public class PlatformPlugin implements Plugin { 45 | @Override public void apply(Project project) { 46 | if (!project.hasProperty("javacppPlatform")) { 47 | project.getExtensions().getExtraProperties().set("javacppPlatform", Loader.Detector.getPlatform()); 48 | } 49 | 50 | project.afterEvaluate(new Action() { public void execute(final Project p) { 51 | p.getDependencies().getComponents().all(PlatformRule.class, 52 | new Action() { public void execute(ActionConfiguration rule) { 53 | rule.setParams(p.findProperty("javacppPlatform")); 54 | }}); 55 | }}); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/org/bytedeco/gradle/javacpp/PlatformRule.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020-2022 Samuel Audet 3 | * 4 | * Licensed either under the Apache License, Version 2.0, or (at your option) 5 | * under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation (subject to the "Classpath" exception), 7 | * either version 2, or any later version (collectively, the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * http://www.gnu.org/licenses/ 13 | * http://www.gnu.org/software/classpath/license.html 14 | * 15 | * or as provided in the LICENSE.txt file that accompanied this code. 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | package org.bytedeco.gradle.javacpp; 23 | 24 | import java.lang.reflect.Method; 25 | import java.util.Arrays; 26 | import java.util.Iterator; 27 | import java.util.List; 28 | import java.util.function.Predicate; 29 | import javax.inject.Inject; 30 | import org.gradle.api.Action; 31 | import org.gradle.api.artifacts.ComponentMetadataContext; 32 | import org.gradle.api.artifacts.ComponentMetadataDetails; 33 | import org.gradle.api.artifacts.ComponentMetadataRule; 34 | import org.gradle.api.artifacts.DirectDependencyMetadata; 35 | import org.gradle.api.artifacts.DirectDependenciesMetadata; 36 | import org.gradle.api.artifacts.VariantMetadata; 37 | import org.gradle.api.internal.artifacts.repositories.resolver.AbstractDependencyMetadataAdapter; 38 | import org.gradle.internal.component.external.model.ConfigurationBoundExternalDependencyMetadata; 39 | import org.gradle.internal.component.external.model.ExternalDependencyDescriptor; 40 | import org.gradle.internal.component.external.model.maven.MavenDependencyDescriptor; 41 | import org.gradle.internal.component.model.IvyArtifactName; 42 | import org.slf4j.Logger; 43 | import org.slf4j.LoggerFactory; 44 | 45 | /** 46 | * A rule that looks at dependencies of artifacts containing "-platform" in their names, and 47 | * removes any dependency whose classifier doesn't start with values in the "javacppPlatform" property, 48 | * which allows matches against platform extensions such as "-gpu" without specifying them. 49 | * 50 | * @author Samuel Audet 51 | */ 52 | class PlatformRule implements ComponentMetadataRule { 53 | private final Logger logger = LoggerFactory.getLogger(PlatformRule.class); 54 | 55 | final List platform; 56 | 57 | /** Takes a comma-separated list of platform names to keep. */ 58 | @Inject public PlatformRule(String platform) { 59 | this.platform = Arrays.asList(platform.split(",")); 60 | } 61 | 62 | @Override public void execute(ComponentMetadataContext context) { 63 | ComponentMetadataDetails component = context.getDetails(); 64 | if (!component.getId().getName().contains("-platform")) { 65 | return; 66 | } 67 | component.allVariants(new Action() { public void execute(VariantMetadata variant) { 68 | variant.withDependencies(new Action() { public void execute(DirectDependenciesMetadata dependencies) { 69 | Iterator i = dependencies.iterator(); 70 | while (i.hasNext()) { 71 | DirectDependencyMetadata d = i.next(); 72 | String classifier = null; 73 | try { 74 | // This only works starting with Gradle 6.3: 75 | List as = d.getArtifactSelectors(); 76 | if (as != null && as.size() > 0) { 77 | classifier = as.get(0).getClassifier(); 78 | } 79 | } catch (NoSuchMethodError ex) { 80 | // So try to get the classifier some other way... 81 | try { 82 | if (d instanceof AbstractDependencyMetadataAdapter) { 83 | Method getMetadata = AbstractDependencyMetadataAdapter.class.getDeclaredMethod("getOriginalMetadata"); 84 | getMetadata.setAccessible(true); 85 | Object o = getMetadata.invoke(d); 86 | if (o instanceof ConfigurationBoundExternalDependencyMetadata) { 87 | ConfigurationBoundExternalDependencyMetadata m = (ConfigurationBoundExternalDependencyMetadata)o; 88 | ExternalDependencyDescriptor dd = m.getDependencyDescriptor(); 89 | if (dd instanceof MavenDependencyDescriptor) { 90 | MavenDependencyDescriptor mdd = (MavenDependencyDescriptor)dd; 91 | IvyArtifactName da = mdd.getDependencyArtifact(); 92 | if (da != null) { 93 | classifier = da.getClassifier(); 94 | } 95 | } 96 | } 97 | } 98 | } catch (ReflectiveOperationException e) { 99 | logger.warn("Could not get the classifier of " + d + ": " + e); 100 | } 101 | } 102 | final String c = classifier; 103 | if (classifier != null && platform.stream() 104 | .filter(new Predicate() { public boolean test(String p) { return c.startsWith(p); }}).count() == 0) { 105 | i.remove(); 106 | } 107 | } 108 | }}); 109 | }}); 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /src/test/java/org/bytedeco/gradle/javacpp/BuildPluginTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 Samuel Audet 3 | * 4 | * Licensed either under the Apache License, Version 2.0, or (at your option) 5 | * under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation (subject to the "Classpath" exception), 7 | * either version 2, or any later version (collectively, the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * http://www.gnu.org/licenses/ 13 | * http://www.gnu.org/software/classpath/license.html 14 | * 15 | * or as provided in the LICENSE.txt file that accompanied this code. 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | package org.bytedeco.gradle.javacpp; 23 | 24 | import org.bytedeco.javacpp.Loader; 25 | import org.gradle.testfixtures.ProjectBuilder; 26 | import org.gradle.api.Project; 27 | import org.junit.Test; 28 | import static org.junit.Assert.*; 29 | 30 | public class BuildPluginTest { 31 | @Test public void pluginRegistersTasks() { 32 | Project project = ProjectBuilder.builder().build(); 33 | project.getPlugins().apply("java"); 34 | project.getPlugins().apply("org.bytedeco.gradle-javacpp-build"); 35 | 36 | assertEquals(Loader.Detector.getPlatform(), project.findProperty("javacppPlatform")); 37 | assertTrue(project.getExtensions().findByName("javacppBuild") instanceof BuildExtension); 38 | assertNotNull(project.getTasks().findByName("javacppBuildCommand")); 39 | assertNotNull(project.getTasks().findByName("javacppCompileJava")); 40 | assertNotNull(project.getTasks().findByName("javacppBuildParser")); 41 | assertNotNull(project.getTasks().findByName("javacppBuildCompiler")); 42 | assertNotNull(project.getTasks().findByName("javacppPomProperties")); 43 | assertNotNull(project.getTasks().findByName("javacppJar")); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/test/java/org/bytedeco/gradle/javacpp/PlatformPluginTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2020 Samuel Audet 3 | * 4 | * Licensed either under the Apache License, Version 2.0, or (at your option) 5 | * under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation (subject to the "Classpath" exception), 7 | * either version 2, or any later version (collectively, the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * http://www.gnu.org/licenses/ 13 | * http://www.gnu.org/software/classpath/license.html 14 | * 15 | * or as provided in the LICENSE.txt file that accompanied this code. 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | package org.bytedeco.gradle.javacpp; 23 | 24 | import java.lang.reflect.Field; 25 | import java.lang.reflect.InvocationTargetException; 26 | import org.bytedeco.javacpp.Loader; 27 | import org.gradle.testfixtures.ProjectBuilder; 28 | import org.gradle.api.Project; 29 | import org.gradle.api.artifacts.dsl.ComponentMetadataHandler; 30 | import org.gradle.api.internal.artifacts.dsl.DefaultComponentMetadataHandler; 31 | import org.gradle.api.internal.project.DefaultProject; 32 | import org.junit.Test; 33 | import static org.junit.Assert.*; 34 | 35 | public class PlatformPluginTest { 36 | @Test public void pluginAddsRule() throws IllegalAccessException, InvocationTargetException, NoSuchFieldException { 37 | Project project = ProjectBuilder.builder().build(); 38 | project.getPlugins().apply("java"); 39 | project.getPlugins().apply("org.bytedeco.gradle-javacpp-platform"); 40 | 41 | assertEquals(Loader.Detector.getPlatform(), project.findProperty("javacppPlatform")); 42 | project.getExtensions().getExtraProperties().set("javacppPlatform", "linux-armhf,linux-arm64"); 43 | ((DefaultProject)project).evaluate(); 44 | assertEquals("linux-armhf,linux-arm64", project.findProperty("javacppPlatform")); 45 | 46 | ComponentMetadataHandler h = project.getDependencies().getComponents(); 47 | Field f = DefaultComponentMetadataHandler.class.getDeclaredField("metadataRuleContainer"); 48 | f.setAccessible(true); 49 | Iterable i = (Iterable)f.get(h); 50 | assertTrue(i.iterator().hasNext()); 51 | } 52 | } 53 | --------------------------------------------------------------------------------