Compare commits

..

85 Commits
1.8.0 ... 1.9.0

Author SHA1 Message Date
Scott Wolchok
e9e2ae28e0 Tidy up YGFloatOptional
Summary: Just some convention/weird style things. `float` should be passed by value, weird use of ?: operator instead of ||.

Reviewed By: priteshrnandgaonkar

Differential Revision: D8804407

fbshipit-source-id: e0d67363ccde36ec5bccec7497ed0ffd364b3fcf
2018-07-12 08:42:41 -07:00
David Aurelio
4ed3dd4b82 Add YogaNodeProperties interface
Summary:
`YogaNodeProperties` will serve as abstraction over JNI adapters / storage backends in follow-ups.

@public

Reviewed By: IanChilds

Differential Revision: D8818805

fbshipit-source-id: 7998a56daebea60dd13b07228dffdf14be852554
2018-07-12 07:58:04 -07:00
Marc Terns
a7f430a5ef Feature podspec modules (#793)
Summary:
This PR adds support for using Yoga Swift dependents when Yoga is pulled as a static library.

Currently swift projects trying to pull static libraries are unable to import the module. The reason for that is because the `DEFINES_MODULES` build setting is set to`NO`.  If a Swift Framework is trying to `pod spec lint --use-libraries` with `Yoga` as a dependency, the validation will fail. With the `DEFINES_MODULE` enabled, the product will be treated as defining its own module. This enables automatic production of LLVM module map files when appropriate, and allows the product to be imported as a module.

A workaround to this issue would be passing the `:modular_headers` flag to the `Podfile`, but that would not fix the `pod spec lint` validation for framework/library dependencies, it would just allow consuming applications to build and run.

An example of this issue would be [SonarKit](https://github.com/facebook/Sonar/blob/master/iOS/SonarKit.podspec). `SonarKit` wasn't able to validate its podspec due to `YogaKit` (Swift Framework) depending on `Yoga` and SonarKit validating with the `--use-libraries` flag due to the c++ dependencies. We had to create a new version of [Yoga 1.9 podspec](https://github.com/facebook/Sonar/blob/master/Specs/Yoga/1.9/Yoga.podspec.json) and make sure to set the `DEFINES_MODULE` flag of the pod target. After that, we were able to `pod spec lint` `SonarKit.podspec` successfully.

After merging a new `tag` should be created and the new podspec should be pushed to cocoapods master repository.
Pull Request resolved: https://github.com/facebook/yoga/pull/793

Reviewed By: passy

Differential Revision: D8820126

Pulled By: priteshrnandgaonkar

fbshipit-source-id: 98eae3c31ec67a03c0fe97e05ab9e79446fa9f78
2018-07-12 07:27:16 -07:00
Valentin Shergin
89ba4f282d Removed misleading comment in YGPersistenceTest
Summary:
Trivial... but quite confusing. :)

Created from Diffusion's 'Open in Editor' feature.

Reviewed By: priteshrnandgaonkar

Differential Revision: D7151891

fbshipit-source-id: d09a6434d6327736c2d5ce672b3e9c5b5573508a
2018-07-11 20:12:37 -07:00
David Aurelio
b6231ee0ed Lint java files
Summary:
@public

Applies lint auto-fixes to java files.

Reviewed By: priteshrnandgaonkar

Differential Revision: D8803814

fbshipit-source-id: 2e4dc285b233091a9fbadf38fc22dd6e36f11f8e
2018-07-11 09:43:09 -07:00
Scott Wolchok
e384002878 Inline simple YGNode getters/setters
Summary: Simple getters/setters are usually inlined like this.

Reviewed By: priteshrnandgaonkar, davidaurelio

Differential Revision: D8793588

fbshipit-source-id: 436bd54880e41a5e403e3f4ae0d9dd4a413df79c
2018-07-11 09:02:36 -07:00
Scott Wolchok
9ceed4b601 Remove unused YGNode::*nextChild
Summary: This linked list was never used, and YGNodeDeepClone was doing scary things to maintain it.

Reviewed By: davidaurelio

Differential Revision: D8792864

fbshipit-source-id: c578fabe65c837f0791aa9ac3e18f31d93691abd
2018-07-11 09:02:36 -07:00
Scott Wolchok
765bb85d1e Fix warnings when building benchmark
Summary: There were a few missing prototypes and a -Wshadow violation. Merged YGBenchmark.h into YGBenchmark.c, added static where needed, fixed shadow violation.

Reviewed By: davidaurelio

Differential Revision: D8793124

fbshipit-source-id: c4b2dd348c38aa599169b5e9bea543c172439432
2018-07-11 09:02:34 -07:00
Pritesh Nandgaonkar
6548dddec3 Fix SingleFlex Child condition
Summary:
Fixes the improper `singleFlexChild` optimization. In the case when all the childs have `flex-grow:0 flex-grow:0` except one child with `flex-grow:1 flex-shrink:1`, then one can simply measure all the non-flexing children and then give the flexing child all the remaining space.

Also added a test case which reproduced the bug

Reviewed By: IanChilds

Differential Revision: D8782684

fbshipit-source-id: ffd4d35b6122f82111b987540efb23bd2a8da5a2
2018-07-11 06:01:35 -07:00
David Aurelio
966f5ece4a guards instead of nested if
Summary:
Replaces two nested if-blocks with guards. This is intended to help with restructuring this function in follow-ups.

@public

Reviewed By: priteshrnandgaonkar

Differential Revision: D8785659

fbshipit-source-id: 7b9d63e9814b83b999397c016ad67ad348bb0f72
2018-07-11 04:13:01 -07:00
David Aurelio
ede2888326 Lint / reformat YGJNI.cpp
Summary:
Run clangformat on `YGJNI.cpp`

@public

Reviewed By: priteshrnandgaonkar

Differential Revision: D8785660

fbshipit-source-id: 9748a5297e7b55e897de0280a79c2ea6ae1c1298
2018-07-11 04:13:00 -07:00
Daniel Büchele
2eda444bbf update dependencies
Summary:
Updates all dependencies of the website to their latest version. This is made due to CVE-2018-3728 and a vunerable version of `hoek` used in s transitive dependency of the website. This updates `hoek` to v 4.2.1 which is not affected.

allow-large-files

Reviewed By: astreet

Differential Revision: D8734272

fbshipit-source-id: 3e96ea5890190f7d7b83cc4c18121fc925411f69
2018-07-05 08:58:03 -07:00
Daniel Büchele
7c4319181b fixing landing page layout on server render
Summary:
On the first render the landing page was missing a CSS class. This ls probably related to https://github.com/gatsbyjs/gatsby/issues/5136
It is fixed by wrapping the page in a <div>

Reviewed By: priteshrnandgaonkar

Differential Revision: D8660801

fbshipit-source-id: dd1ac4145831f2556e2c7ceeaddb2a423447f833
2018-07-03 10:21:22 -07:00
David Vacca
f4d29e6f11 Avoid cleaning up Owner of YGNode during clonning
Summary:
This diff refactors the cloning mechanism for YogaNode used from Fabric UI renderer and RN iOS graphs.
Previously, we were cleaning the owner of the child's cloned node inside the C++ implementation of YogaNode. This was a mistake because this modified the last commited YogaTree, causing side effect in RN iOS graphs.

Reviewed By: shergin

Differential Revision: D8672627

fbshipit-source-id: c9902d00690e0361fd58aed84b506c42258bd995
2018-06-28 22:47:50 -07:00
Peter van der Zee
77ea79490f Upgrade Prettier to 1.13.6 on fbsource
Reviewed By: zertosh

Differential Revision: D8638504

fbshipit-source-id: c6991b2e884e14868ddc1d9047a78191219d673f
2018-06-27 03:28:16 -07:00
Pascal Hartig
46c96ee2cb Upgrade fbjni
Summary:
Sync fbjni with `libaries/fbjni`.

This includes a hack to fix a deadlock we found for cmake-debug variants only. This still gets us back in sync with other fbjni consumers which is going to save us trouble in the future if Yoga ever wants to make use of a newer feature.

Manual changes made in addition to the hand-crafted CMakeLists and cxx buck rules:

- `jni::isObjectRefType` has SDK lookup disabled.
- `fbjni/` path is changed back to `fb/` to retain compatibility with Yoga.

Reviewed By: priteshrnandgaonkar

Differential Revision: D8531991

fbshipit-source-id: 776f519e2e5f9bea37f55990348f7ed81c4860b4
2018-06-26 04:58:58 -07:00
Taras Tsugrii
a67c555320 Fix deprecated glob usage.
Summary: https://our.intern.facebook.com/intern/wiki/Buck/python-to-skylark/

Differential Revision: D8595731

fbshipit-source-id: 0e3046a7fd2a25e9b13462713ae9a008ad546770
2018-06-23 18:27:38 -07:00
David Vacca
cdb1ee21a0 Clean-up parent / owner reference of children during clonning
Summary: This diff cleans up the parent / owner references for children of ReactShadowNode / YogaNode during cloning. The reason of this behavior is to avoid retaining every generation of trees during cloning. This fixes a memory leak detected when running the ProgressBarExample.android.js in catalyst app

Reviewed By: fkgozali

Differential Revision: D8019894

fbshipit-source-id: b0d38f0c836ffec534f64fa1adbd7511ecf3473d
2018-06-22 11:44:14 -07:00
Oleksii Dykan
2ce219ef42 Fix componentkit generator (#785)
Summary:
Fixes some inconsistencies in yoga playground
Closes https://github.com/facebook/yoga/pull/785

Reviewed By: danielbuechele

Differential Revision: D8480993

Pulled By: alickbass

fbshipit-source-id: 395d77bae28462d3e03d666287bdc64137b84c68
2018-06-18 09:12:49 -07:00
Simon Egersand
c5f826de83 Use correct spelling ('then' -> 'than') (#782)
Summary:
Might be the smallest PR in the world, but it caught my eye reading the
docs so I figured I should fix it.
Closes https://github.com/facebook/yoga/pull/782

Reviewed By: emilsjolander

Differential Revision: D8351525

Pulled By: jknoxville

fbshipit-source-id: fc7a881f062e07d2e28b5ca2da8c52f20bad53be
2018-06-12 04:12:23 -07:00
Vince Mi
526ca42d04 Add back deprecated getParent methods for non-breaking API change (#775)
Summary:
I'm not totally sure what I'm doing so if this needs changes let me know.
Closes https://github.com/facebook/yoga/pull/775

Reviewed By: emilsjolander

Differential Revision: D8331892

Pulled By: passy

fbshipit-source-id: eb1023e666322d2472e4081fd4a4e72a7b43d049
2018-06-11 04:12:26 -07:00
Peter van der Zee
b47f0ce41a Bump Prettier to 1.13.4 on xplat
Summary:
@public

Bump Prettier to use version 1.13.4
All code changes are caused by running Prettier and should only affect files that have an `format` header.
All other changes caused by yarn.

Reviewed By: ryanmce

Differential Revision: D8251255

fbshipit-source-id: 0b4445c35f1269d72730f2000002a27c1bc35914
2018-06-06 05:44:55 -07:00
Andres Suarez
eb7cb11ffd Run buildifier over BUCK and TARGETS files
Reviewed By: scottrice

Differential Revision: D8163151

fbshipit-source-id: 700a77c09c6ab1bef8fd24a2a3133a4b50e3b3a3
2018-05-25 11:25:46 -07:00
Daniel Büchele
f9df990177 link to playground in embedded playgrounds
Summary:
The "copy share URL" button only works in the standalone playground, not the ones embedded on the landing page or the documentation, because, we don't want people to share a link to a modified documentation page.

This diff replaces the share URL button with a link to a standalone playground which then can be shared.

Reviewed By: astreet

Differential Revision: D8125135

fbshipit-source-id: 8b69b69caeadf5d598ed89b0abd9b742f5f07a9c
2018-05-24 12:25:52 -07:00
Andres Suarez
684dccb7b9 Run buildifier over all bzl files
Reviewed By: yfeldblum, ttsugriy

Differential Revision: D8087092

fbshipit-source-id: 3b298d0a81ed65454649df8c80bffca2ec5651de
2018-05-22 07:33:43 -07:00
Taras Tsugrii
6c51eb4f72 Re-format BUCK to use recommended style.
Summary:
This uses the latest version of `buildifier` that supports many
more Skylark syntax features.

Reviewed By: yfeldblum

Differential Revision: D8073585

fbshipit-source-id: 12322aebc09b89d5af9cc257b16c1bc0fbb066c1
2018-05-20 23:40:18 -07:00
Taras Tsugrii
ca485dfb50 Re-format .bzl to use recommended style.
Summary:
This is to make them `buildifier` compatible in order to start using
`buildifier` for all .bzl files.

Differential Revision: D8069457

fbshipit-source-id: f5bce02a3e6ba8dc4ccbf5bae70de224c30cbd64
2018-05-19 18:12:01 -07:00
Emil Sjölander
50e3714b21 bump pod version
Reviewed By: priteshrnandgaonkar

Differential Revision: D8025017

fbshipit-source-id: 187c4a3b0ec47bc7bcbc599049941bed069dc2f7
2018-05-16 08:44:29 -07:00
Pritesh Nandgaonkar
c52c7cdd1e Fix podspec issue
Summary: Fix yoga podspec issue. The newly released versiong of Yoga i.e 1.8.0 was not building on iOS. So fixing the bug. Want to use this pod in SonarKitLayout

Reviewed By: emilsjolander

Differential Revision: D8024641

fbshipit-source-id: c8d7279e654145199fbee6655909e1c10d8b2114
2018-05-16 07:19:15 -07:00
Daniel Büchele
11200f3d75 fixing playground responsive bahavior
Summary: The error message saying the playground is only available on bigger screens also was shown on big screens.

Reviewed By: emilsjolander

Differential Revision: D7989482

fbshipit-source-id: f444ca2d6608b868c4ff4d38fa6798d80b57c047
2018-05-14 10:22:41 -07:00
Daniel Büchele
5dbe3c128b adding support for min/max-width/height
Summary: Adding controls for min/max height/width to the playground

Reviewed By: emilsjolander

Differential Revision: D7988400

fbshipit-source-id: bae487e2504906788552d6c1a29ed74c39cb5ac0
2018-05-14 07:46:21 -07:00
Jonathan Kim
3564ccf6e4 Use wrapped cxx_binary
Summary: Introduce `yoga_cxx_binary`

Reviewed By: grzmiel

Differential Revision: D7809271

fbshipit-source-id: 1b66ce59a73e4a63b670f7d3bcadfbb6cbfbc220
2018-04-28 21:32:13 -07:00
Peter van der Zee
e1c19cecad Upgrade Prettier to v1.12.1 on fbsource
Summary:
Updates Prettier to v1.12.1, using `xplat/js/scripts/prettier-bump.js` based on the playbook by https://our.intern.facebook.com/intern/wiki/Prettier/upgrade-guide/

All changes related to upgrading or running Prettier

allow-many-files
allow-large-files
bypass-lint
drop-conflicts
ignore-conflict-markers
ignore-signed-source
ignore-nocommit

Reviewed By: benjaffe, ryanmce, yungsters

Differential Revision: D7652946

fbshipit-source-id: 396d45c675e93f2298cd2920d927630c81867447
2018-04-19 03:05:38 -07:00
Pascal Hartig
8e4f3a3084 Add getParent() method for easier migration
Summary:
External partners have asked us to provide an easier way to migrate and this was
a breaking change in the most recent release.

Reviewed By: emilsjolander

Differential Revision: D7654526

fbshipit-source-id: efe44807caa97f495c5e5691dedcf281760fa23e
2018-04-18 04:45:12 -07:00
Jakub Grzmiel
9b8323ff38 Clean up BUCK files for missing dependencies and tests
Summary: Several of dependencies and tests in repository are missing (e.g. because we don't support building certain library for MacOSX). Clean up those mistakes.

Differential Revision: D7625433

fbshipit-source-id: 332b7ff7eaed82cb52f459921f1ae67b702a1636
2018-04-14 15:35:24 -07:00
Jakub Grzmiel
5b7adda620 Unbreak the build
Summary: build-break

Differential Revision: D7629493

fbshipit-source-id: baf5ca7cec2078a8ba9e34afe84da76c2edbb3b3
2018-04-14 14:58:08 -07:00
Jakub Grzmiel
ba2a3b8c91 Clean up BUCK files for missing dependencies and tests
Summary: Several of dependencies and tests in repository are missing (e.g. because we don't support building certain library for MacOSX). Clean up those mistakes.

Differential Revision: D7618360

fbshipit-source-id: 421834892519998ad088a138b3fc3d96afe34d79
2018-04-14 13:17:59 -07:00
Jonathan Kim
eb15939c23 Make yoga wrapper macros start with yoga_
Summary: Rename macros

Reviewed By: mzlee

Differential Revision: D7606834

fbshipit-source-id: a2089260dbe46f30f49a207737c83472e2fb3c63
2018-04-14 12:43:03 -07:00
Pascal Hartig
b9fa60fd74 Re-enable matrix build for Java snapshots
Summary:
Change the travis platform to Java and install Node via nvm instead. This
manually reinstalls buck and then publishes a snapshot if it builds and tests
correctly.

Reviewed By: emilsjolander, danielbuechele

Differential Revision: D7567862

fbshipit-source-id: fabdbbb13117ab8ead4eb9f10402a71d30f29c12
2018-04-10 05:33:13 -07:00
Pascal Hartig
d397aa04d7 1.8.1-SNAPSHOT
Summary: Back to snapshot release.

Reviewed By: marco-cova

Differential Revision: D7550851

fbshipit-source-id: f98983799dc9ea2a44d658fd50a2676f1d6e31d5
2018-04-09 04:03:11 -07:00
Pascal Hartig
adb1b11055 1.8.0
Summary: New release.

Reviewed By: marco-cova

Differential Revision: D7550852

fbshipit-source-id: eac5662179daa88d9d62c55566b3a31428c4117a
2018-04-09 02:41:21 -07:00
David Vacca
2e234473ca [yoga re-add assertion to check for owner reference before adding child.
Summary: this diff re-add the assertion to check for owner reference before adding child that was removed by mistake in previous diff

Reviewed By: emilsjolander

Differential Revision: D7495417

fbshipit-source-id: b81174aeea3f2796d76ccdae4a8eddd0beace0aa
2018-04-04 10:57:52 -07:00
Lukas Wöhrl
6b08db68bb Fix compilation on MSVC by moving YGConfig to C++
Summary:
This PR fixes the compilation on MSVC. I moved the `YGConfig` creation to a C++ constructor.

Addionally it removes the "dot" notation on `YGValue`, I didn't want to change that type to a C++ constructor, because I think this will break the ABI.
Closes https://github.com/facebook/yoga/pull/746

Differential Revision: D7498141

Pulled By: emilsjolander

fbshipit-source-id: 5f5308ff838dcd803065785ddc08b2404524acb9
2018-04-04 09:55:45 -07:00
Pritesh Nandgaonkar
9550126f76 clean up experimental setup and keep using ffast-math flag
Summary: Remove experimental setup of fast-math and add `-ffast-math` as a compiler flag for yoga.

Reviewed By: emilsjolander

Differential Revision: D7414228

fbshipit-source-id: 320e1b1953f6af867b13e617af7872eb8999160e
2018-04-04 08:29:43 -07:00
Pritesh Nandgaonkar
bad262b961 Change the return type of getMarginForAxis to YGFloatOptional
Summary: Change the return type of getMarginForAxis to YGFloatOptional

Reviewed By: emilsjolander

Differential Revision: D7350337

fbshipit-source-id: dd1ee2fcd295ccd14f7d414ab0c24090b24e91e0
2018-04-04 08:29:43 -07:00
Pritesh Nandgaonkar
3c6c10075a Change the return type of getTrailingMargin to YGFloatOptional
Summary: Change the return type of getTrailingMargin to YGFloatOptional

Reviewed By: emilsjolander

Differential Revision: D7350221

fbshipit-source-id: 61a67364c1975ec6dd1883bc2cb4968b830c73df
2018-04-04 08:29:43 -07:00
Pritesh Nandgaonkar
6a77a6939e Changed the return type of getLeadingMargin to YGFloatOptional
Summary: Changed the return type of getLeadingMargin to YGFloatOptional

Reviewed By: emilsjolander

Differential Revision: D7349907

fbshipit-source-id: b20894fbc33fd5b29a28f3c9174d1b5f406774ab
2018-04-04 08:29:43 -07:00
Pritesh Nandgaonkar
b725a4a140 Refactored relativePosition private method to YGFloatOptional return type
Summary: Refactored relativePosition private method to YGFloatOptional return type

Reviewed By: emilsjolander

Differential Revision: D7344939

fbshipit-source-id: 72443d38426a211d3e84be814e6a61baf4d26703
2018-04-04 08:29:43 -07:00
Pritesh Nandgaonkar
2b714a5b5d Change the type of getTrailingPosition to YGFloatOptional
Summary: Change the type of getTrailingPosition to YGFloatOptional

Reviewed By: emilsjolander

Differential Revision: D7344710

fbshipit-source-id: eb4c422b6e0f55d90b083221aa8ff1ab797d58a8
2018-04-04 08:29:43 -07:00
Pritesh Nandgaonkar
572546088f Changed the type of return value of getLeadingPosition to YGFloatOptional
Summary: Changed the type of return value of getLeadingPosition to YGFloatOptional

Reviewed By: emilsjolander

Differential Revision: D7344367

fbshipit-source-id: 0f5a667ca357b2ce056c86763aa3e9e4c54b82f0
2018-04-04 08:29:43 -07:00
Pritesh Nandgaonkar
5b109578d3 Changed the type of computedFlexBasis to YGFloatOptional in YGLayout
Summary: Changed the type of computedFlexBasis to YGFloatOptional in YGLayout

Reviewed By: emilsjolander

Differential Revision: D7340413

fbshipit-source-id: 39247b2b582a682e602f49f58b4bbd2bf0c995af
2018-04-04 08:29:43 -07:00
Pritesh Nandgaonkar
77b720f9a5 Fixed types of getLeadingPaddingAndBorder and getTrailingPaddingAndBorder to YGFloatOptional
Summary: Fixed types of getLeadingPaddingAndBorder and getTrailingPaddingAndBorder to YGFloatOptional

Reviewed By: emilsjolander

Differential Revision: D7339998

fbshipit-source-id: aa24335c2db1cd895b9711214b72195add718c32
2018-04-04 08:29:43 -07:00
Pritesh Nandgaonkar
de954eb9cc Changed the return type of trailing padding to YGFloatOptional
Summary: Changed the return type of trailing padding to YGFloatOptional

Reviewed By: emilsjolander

Differential Revision: D7339712

fbshipit-source-id: 483c5886838c14b17cb731c81abb9fc80f519956
2018-04-04 08:29:42 -07:00
Pritesh Nandgaonkar
3e322e60e4 Updated the implementation of leading padding
Summary: Changed the arguments for the getter of leading padding to avoid copies. Added an assetion in getter of leading padding, as padding would always be defined even in the case when the user has not explicitly defined the value. In these cases it would take the default value of 0. So changing the type of `getLayoutPadding` to `YGFloatOptional`, doesn't make sense.

Reviewed By: emilsjolander

Differential Revision: D7336690

fbshipit-source-id: b2a2f010026f26fc2cc9fb35ad921da8f7017c9f
2018-04-04 08:29:42 -07:00
Pritesh Nandgaonkar
a3642541d0 Make the return type of YGNodeBoundAxisWithinMinAndMax to YGFloatOptional
Summary: Make the return type of YGNodeBoundAxisWithinMinAndMax to YGFloatOptional

Reviewed By: emilsjolander

Differential Revision: D7323382

fbshipit-source-id: 8e3eb4f3744b5f3f9e2b353f56184905f7557191
2018-04-04 08:29:42 -07:00
Pritesh Nandgaonkar
bb139d3f91 Remove the use of YGUnwrapOptional from YGConstrainedMaxSizeForMode
Summary: Remove the use of YGUnwrapOptional from YGConstrainedMaxSizeForMode

Reviewed By: emilsjolander

Differential Revision: D7322743

fbshipit-source-id: d825c60bcdc9ecdc0c784a215dc6b1b8a7a7860e
2018-04-04 08:29:42 -07:00
Pritesh Nandgaonkar
08743a42e2 Made the acccessors method to return const references
Summary: Made the acccessors method to return const references

Reviewed By: emilsjolander

Differential Revision: D7321801

fbshipit-source-id: 9fc4da724bc2f58a0d95824ca3c0b5bf1690bccf
2018-04-04 08:29:42 -07:00
Lukas Wöhrl
cb6e76973d Fix float type mismatch on endOfLineIndex and inside rounding
Summary:
This PR fixes a type mismatch on `endOfLineIndex` where it should be of type `uint32_t` while it is of type `float`

Additonally it fixes some `double` casting in the rounding methods.
Closes https://github.com/facebook/yoga/pull/745

Differential Revision: D7494519

Pulled By: emilsjolander

fbshipit-source-id: 30a86574ce163458a6888f61a902d0640c1874fb
2018-04-04 07:04:23 -07:00
Pritesh Nandgaonkar
4b760fa9bc Changed the return type of YGResolveValueMargin to YGFloatOptional
Summary: Changed the return type of YGResolveValueMargin to YGFloatOptional

Reviewed By: emilsjolander

Differential Revision: D7304090

fbshipit-source-id: cbec03a9367cf34976d083ad475d4da0b736e6d2
2018-04-03 15:12:07 -07:00
Pritesh Nandgaonkar
5730be093e Move equaltiy function from utils to an operator on YGFloatOptional
Summary: Move equaltiy function from utils to an operator on YGFloatOptional

Reviewed By: emilsjolander

Differential Revision: D7303460

fbshipit-source-id: 41ec0076ace621ec1a5bdbab00b72eea57780fff
2018-04-03 15:12:05 -07:00
Pritesh Nandgaonkar
d85e2ee9c3 Change the type of aspect Ratio to YGFloatOptional
Summary: Change the type of aspect Ratio to YGFloatOptional

Reviewed By: emilsjolander

Differential Revision: D7302651

fbshipit-source-id: 53e3b4c9627207a379f927b1f3485e36a9c70601
2018-04-03 15:12:02 -07:00
Pritesh Nandgaonkar
fe433b012f Remove the usage of YGUndefined for kYGValueAuto and fix setter and getter of dimensions
Summary: Removes the use of YGUndefined from kYGValueAuto. Also fixed the setter and getter of dimensions. This diff also fixes a typo

Reviewed By: emilsjolander

Differential Revision: D7302453

fbshipit-source-id: e002a1ddd75bfc6fe142a7275e7913c064972e16
2018-04-03 15:11:58 -07:00
David Vacca
5e3ffb39a2 Extend Yoga to be able clone Yoga Node with new children
Summary:
This diff includes the following changes:

1 ) I extended the Java implementation of YogaNode to be able to get a full copy of a YogaNode object without copying the List of children of the original YogaNode. In other words, the new copy of the YogaNode will have the same data of the original YogaNode, but with an empty list of children.

2 ) We created a new method in Yoga.cpp called YGNodeInsertSharedChild. This new method is going to be used by Fabric in order to temporarily share a YogaNode between two "Yoga Trees" (the "current Yoga" tree and a partial "clone of the current Yoga tree"). We exposed this new functionality in the java implementation of Yoga (method addSharedChildAt)

I'm including sebmarkbage for more context.

Reviewed By: emilsjolander

Differential Revision: D7245421

fbshipit-source-id: 72578c8261f29e4a12fc6c72a91f2f891cd58d48
2018-04-01 18:35:13 -07:00
David Vacca
f0edefdbb7 Rename YogaNode.parent -> YogaNode.owner
Summary:
In the persistent version of Yoga, a YogaNode can be shared between two YogaTrees, that means that a YogaNode could have more than one Parent at one point in time. That's why the concept of Parent of a YogaNode is not a 1-1 relationship anymore.
This diff changes the semantic of Parent of a YogaNode to Owner of a Yoga Node. CC sebmarkbage and priteshrnandgaonkar for more context.

Technically this diff renames the field YogaNode.parent to YogaNode.owner (and every internal field, Getter and Setter that is related to parent)

Note that as part of this diff I also modified the CSSLayoutDEPRECATED version of Yoga in order to keep compatibility with the C++ implementation.

Reviewed By: priteshrnandgaonkar

Differential Revision: D7352778

fbshipit-source-id: dcf1af5e72bfc3063b5c4bda197d7952a9194768
2018-04-01 18:35:13 -07:00
David Vacca
17901ea5c2 Refactor cloning of YogaNode
Summary: see Test Plan

Reviewed By: priteshrnandgaonkar

Differential Revision: D7339832

fbshipit-source-id: 2de6f47ae7601ac083d3b9fbe10ffaf6307ae760
2018-04-01 18:35:13 -07:00
Jonathan Dann
187fc54596 Add YGNodeSetChildren(), YGNodeTraversePreOrder()
Summary:
We had functions for inserting/removing a specific child, but not for simply replacing the child set with another list.

`YGNodeSetChildren()` will unhook child nodes from the parent that don't appear in the new set. We set the disconnected child node layouts to `YGLayout()` b/c that's what the rest of the code does.

`YGTraversePreOrder()` walks the tree and calls a labmda for each node. We could very easily add a post-order traversal and the ability to stop traversal if we ever want, but for now this is an MVP.

Reviewed By: Woody17

Differential Revision: D7360203

fbshipit-source-id: 32df8e1213ead03bc0a026ec4bf453bc799bb9ce
2018-03-25 13:59:44 -07:00
Pritesh Nandgaonkar
c951ad7c7b Push Yoga 1.8.0 to cocoapods
Summary:
Podspec to push yoga 1.8.0 to cocoapods. There is an issue with cocoapods and it fails to lint those projects with C++ in its header, which is the case with yoga too.

Follow this thread https://github.com/CocoaPods/CocoaPods/issues/5152. To make the lint pass, one would have to change `app_target_helper.rb` cocoapod source file in the local machine. Follow my [gist](https://gist.github.com/priteshrnandgaonkar/dcca9639a3bc0a3b9adecae3a2b3b0c4).

I am able to pass the lint, but not able to push the pod in cocoapods as I am not the admin. @[759512522:emilsj], please push it on Cocoapods or give me permission.

Podspec now also exposes public header explicitly.

Reviewed By: gkassabli

Differential Revision: D7375018

fbshipit-source-id: 4e82e1c0b6340c3f8d3b8a96ecadbcb711d4bcd8
2018-03-23 05:33:59 -07:00
Daniel Büchele
9785975f77 add documentation about JS library usage. fixes #733
Summary: Adds an example of how to use yoga from JavaScript to the documentation pages.

Reviewed By: priteshrnandgaonkar

Differential Revision: D7354390

fbshipit-source-id: 0dbc08e5341c06b621acd99bfb9ce7e789b67a45
2018-03-22 04:53:24 -07:00
Jonathan Dann
79281049f2 Mark more member functions as const
Summary: These don't mutate internal state.

Reviewed By: priteshrnandgaonkar

Differential Revision: D7291364

fbshipit-source-id: 2e7d96cfe0345692ffa411bb21a80eb7a859880b
2018-03-21 16:14:21 -07:00
Jonathan Dann
7d2b84aab6 Pass some constructor argumetns by const-reference
Summary: These don't need to be copied twice.

Reviewed By: priteshrnandgaonkar

Differential Revision: D7291363

fbshipit-source-id: 22e606d0b3fa1133d7e0334c8cf9f5f1f32fe64b
2018-03-21 16:14:21 -07:00
Jonathan Dann
cda328fa7e Pass-by-reference in YGNode::setStyle() ::setChildren() ::setLayout()
Summary: These shouldn't be copying the arguments when they pass by value. Instead these only get copied when assigning the value to the member.

Reviewed By: priteshrnandgaonkar

Differential Revision: D7291096

fbshipit-source-id: 7a4025831811d622050adbb5f86608855b94d68e
2018-03-21 16:14:20 -07:00
Pritesh Nandgaonkar
5d7b75a47a Moved YGFloatOptional from C struct to C++ struct
Summary:
Earlier `YGfloatOptional` was plain struct with no privacy around the variables. This diff adds privacy and also enforces checks when one tries to access value of an undefined `YGFloatOptional`

This diff also adds a behaviour in which when a value of an undefined YGFloatOptional is accessed, it will normally terminate(Several cleanup steps are performed).

Reviewed By: emilsjolander

Differential Revision: D7288555

fbshipit-source-id: f61cc92c8fd0d48d2fc1f4d0e6fcef155f19ff8a
2018-03-15 13:04:51 -07:00
Pritesh Nandgaonkar
ae86824636 Fixed a typo and added a test case
Summary: Fixed a typo of flexshrink and added a test case

Reviewed By: emilsjolander

Differential Revision: D7289221

fbshipit-source-id: 48ee9ccfac4adee51d515a366b5a11790f7236fc
2018-03-15 13:04:51 -07:00
Pritesh Nandgaonkar
0dde40ce0b Fix getters and setters if min and max Dimension
Summary: Fix getters and setters of min and max Dimension to behave exactly the same way as it was before fast math changes

Reviewed By: emilsjolander

Differential Revision: D7274807

fbshipit-source-id: 7c1a4c19e8d0552b089a410c3330392cb26a6a47
2018-03-15 07:27:55 -07:00
Pritesh Nandgaonkar
369c9ad12a Fix setter and getter of margin, position, border and padding
Summary:
This diff fixes the setter and getter of margin, position, border and padding to the previous behaviour of yoga, before floatoptional change

This diff also removes the unrequired `#define`

Reviewed By: emilsjolander

Differential Revision: D7274115

fbshipit-source-id: 942a91e6562ef789ae79102a828f397889468fa7
2018-03-15 07:27:55 -07:00
Pritesh Nandgaonkar
cfb9eeca20 Fix failing float max test
Summary:
Earlier YGUndefined was NAN, but recently it was replaced with 10E20 and the check for `isUndefined` is as follows

```
  public static boolean isUndefined(float value) {
    return (Float.compare(value, (float) 10E8) >= 0 || Float.compare(value, (float) -10E8) <= 0);
}
```

If the number is in (-inf, -10E8] and [10E8, inf) then it is considered as undefined. Failing test passed values in this range, so thats why the test was failing. Current diff fixes this issue, and passes a big number which is outside the range as the result of measure function.

Reviewed By: emilsjolander

Differential Revision: D7272325

fbshipit-source-id: 81a77117c65c5dc0cec920f50f0735ec0a7433d1
2018-03-14 09:21:15 -07:00
Pritesh Nandgaonkar
3dfb68887d Expose layout diffing flag to java
Summary:
This diff exposes `shouldDiffLayoutWithoutLegacyStretchBehaviour` from YGConfig and `doesLegacyStretchFlagAffectsLayout` from YGLayout to YogaConfig and YogaNode respectively

Also added a positive test case. Didn't find the negative test case example. @[508947467:ianc] or @[759512522:emilsj], can you suggest a negative test case example.

Reviewed By: emilsjolander

Differential Revision: D7272067

fbshipit-source-id: e67e82eb057e4c7124904c715f9dca4dcfea21ea
2018-03-14 08:43:01 -07:00
Pritesh Nandgaonkar
d567885070 Remove the use of YGUndefined for flex-basis
Summary: Remove the use of YGUndefined for default flex-basis value

Reviewed By: emilsjolander

Differential Revision: D7243924

fbshipit-source-id: 2bfaca1a5e3da40d5292a273cabf705f59c9d666
2018-03-14 04:36:53 -07:00
Pritesh Nandgaonkar
877c275a13 Change the type of flexShrink to YGFloatOptional
Summary: Change the type of flexShrink to YGFloatOptional

Reviewed By: emilsjolander

Differential Revision: D7232171

fbshipit-source-id: 3111119d3d74a7035c01132bff61b30cf44e120a
2018-03-14 04:36:53 -07:00
Pritesh Nandgaonkar
8aadae8ce4 Change the type of flexGrow to YGFloatOptional
Summary: Change the type of flexGrow to YGFloatOptional

Reviewed By: emilsjolander

Differential Revision: D7215355

fbshipit-source-id: 1298ee332551d44e4d070169a1e4103d005c4f43
2018-03-14 04:36:53 -07:00
Pritesh Nandgaonkar
2232d7603a Change the type of flex to YGFloatOptional
Summary: Change the type of flex to YGFloatOptional internally, but keeping the public facing API the same as before

Reviewed By: emilsjolander

Differential Revision: D7211327

fbshipit-source-id: 0d979b6ba00317317b98bbc6e63979c7f1feb2da
2018-03-14 04:36:52 -07:00
Pritesh Nandgaonkar
b3f8851bc2 Changed the return type of YGResolveValue
Summary: Changed the return type of YGResolveValue

Reviewed By: emilsjolander

Differential Revision: D7195099

fbshipit-source-id: 72c4163cd08691cf6e40df05394cc52e83b0de14
2018-03-14 04:36:52 -07:00
Pritesh Nandgaonkar
47ad3f63cf Remove the usage of YGUndefined in the default values of Border in YGStyle
Summary: Remove the usage of YGUndefined in the default values of Border in YGStyle. In the getter of Border function, YGUndefined is used just to keep it logically consistent. The proper solution would be to change the api in `Yoga.h` to accept `YGFloatOptional`, but that would require to change lot of the code in client of this library. Will make a separate diff for that.

Reviewed By: emilsjolander

Differential Revision: D7195115

fbshipit-source-id: e635cf55ac94d8a90caef6cafce281579da2cbfc
2018-03-14 04:36:52 -07:00
Tomer Shalev
c75adb0671 solves the Android pixel bug
Summary:
emilsjolander hi,
this PR solves the following common and probable layout pixel scenario:
the older code is presented for reference:

```java
view.measure(
    View.MeasureSpec.makeMeasureSpec(
        Math.round(node.getLayoutWidth()),
        View.MeasureSpec.EXACTLY),
    View.MeasureSpec.makeMeasureSpec(
        Math.round(node.getLayoutHeight()),
        View.MeasureSpec.EXACTLY));
view.layout(
    Math.round(xOffset + node.getLayoutX()),
    Math.round(yOffset + node.getLayoutY()),
    Math.round(xOffset + node.getLayoutX() + node.getLayoutWidth()),
    Math.round(yOffset + node.getLayoutY() + node.getLayoutHeight()));

```

suppose now the following:
- `xOffset + node.getLayoutX() = 2.2`
- `node.getLayoutWidth() = 0.4` ==> `Math.round(node.getLayoutWidth()) = 0`
- `Math.round(xOffset + node.getLayoutX() + node.getLayoutWidth()) = Math.round(2.2 + 0.4) = 3`

this induces, the following measurements:
```java
view.measure(
    View.MeasureSpec.makeMeasureSpec(
        0,
        View.MeasureSpec.EXACTLY),
    View.MeasureSpec.makeMeasureSpec(
        Math.round(node.getLayoutHeight()),
        View.MeasureSpec.EXACTLY));
view.layout(
    2,
    Math.round(yOffset + node.getLayoutY()),
    3,
    Math.round(yOffset + node.getLayoutY() + node.getLayoutHeight()));

```

the width measurement of the view is 0, while the layout is `(3 - 2 = 1)`.
my proposed solution is to measure the view the way it is now, but when layouting
I use the `#getMeasuredWidth/Height()` methods, this will stop this problem
from happening.

I also want to note that this bug happens with high probability.
Closes https://github.com/facebook/yoga/pull/712

Reviewed By: emilsjolander

Differential Revision: D7231798

Pulled By: priteshrnandgaonkar

fbshipit-source-id: 171da519639dbecd75416a574bccc4456aa22f31
2018-03-13 03:13:00 -07:00
Héctor Ramos
178b8f5f64 Update config files to use LICENSE-examples
Summary: Use examples license in config files.

Reviewed By: sophiebits

Differential Revision: D7174444

fbshipit-source-id: 50c2369b18abd9d7fff9b4a66788fd67a5b40a0c
2018-03-08 10:21:51 -08:00
96 changed files with 4576 additions and 15317 deletions

View File

@@ -1,23 +1,58 @@
# Copyright (c) 2014-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
language: java
language: node_js
node_js:
- "8"
env:
- TARGET: website
- TARGET: android
install:
- cd website
- yarn --ignore-scripts
- cd ..
cache:
directories:
- $HOME/buck
- $HOME/.gradle
before_install:
- |
if [[ -n "$encrypted_d27e803291ff_iv" ]]; then
openssl aes-256-cbc -K $encrypted_d27e803291ff_key -iv $encrypted_d27e803291ff_iv -in scripts/setup-keys.enc -d >> gradle.properties;
fi
# Android
- |
if [[ $TARGET = "android" ]]; then
pushd $HOME
git clone --depth 1 https://github.com/facebook/buck.git
cd buck
ant
popd
export PATH=$PATH:$HOME/buck/bin/
buck --version
export TERMINAL=dumb
source scripts/android-setup.sh && installAndroidSDK
export ANDROID_SDK=$ANDROID_HOME
export ANDROID_NDK_REPOSITORY=$HOME/android-ndk
export ANDROID_NDK_HOME=$ANDROID_NDK_REPOSITORY/android-ndk-r15c
fi
# Website
- |
if [[ $TARGET = "website" ]]; then
nvm install 8
nvm use 8
fi
script:
- cd website
- yarn build
- cd ..
- |
if [[ $TARGET = "android" ]]; then
./gradlew testDebugUnit && scripts/publish-snapshot.sh
fi
- |
if [[ $TARGET = "website" ]]; then
pushd website
yarn build
popd
fi
deploy:
provider: pages
@@ -30,3 +65,4 @@ deploy:
keep-history: true
on:
branch: master
condition: $TARGET = website

21
BUCK
View File

@@ -2,8 +2,7 @@
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
load("//:yoga_defs.bzl", "LIBRARY_COMPILER_FLAGS", "BASE_COMPILER_FLAGS", "GTEST_TARGET", "yoga_dep", "cxx_library", "cxx_test")
load("//:yoga_defs.bzl", "BASE_COMPILER_FLAGS", "GTEST_TARGET", "LIBRARY_COMPILER_FLAGS", "subdir_glob", "yoga_cxx_library", "yoga_cxx_test", "yoga_dep")
GMOCK_OVERRIDE_FLAGS = [
# gmock does not mark mocked methods as override, ignore the warnings in tests
@@ -18,7 +17,7 @@ TEST_COMPILER_FLAGS = BASE_COMPILER_FLAGS + GMOCK_OVERRIDE_FLAGS + [
"-std=c++1y",
]
cxx_library(
yoga_cxx_library(
name = "yoga",
srcs = glob(["yoga/*.cpp"]),
header_namespace = "",
@@ -32,21 +31,7 @@ cxx_library(
],
)
cxx_library(
name = "yogafastmath",
srcs = glob(["yoga/*.cpp"]),
header_namespace = "",
exported_headers = subdir_glob([("", "yoga/*.h")]),
compiler_flags = COMPILER_FLAGS + ["-ffast-math"],
soname = "libyogafastmathcore.$(ext)",
tests = [":YogaTests"],
visibility = ["PUBLIC"],
deps = [
yoga_dep("lib/fb:ndklog"),
],
)
cxx_test(
yoga_cxx_test(
name = "YogaTests",
srcs = glob(["tests/*.cpp"]),
compiler_flags = TEST_COMPILER_FLAGS,

View File

@@ -1,9 +1,9 @@
Pod::Spec.new do |spec|
spec.name = 'Yoga'
spec.version = '1.7.0'
spec.version = '1.9.0'
spec.license = { :type => 'MIT', :file => "LICENSE" }
spec.homepage = 'https://facebook.github.io/yoga/'
spec.documentation_url = 'https://facebook.github.io/yoga/docs/api/c/'
spec.homepage = 'https://yogalayout.com/'
spec.documentation_url = 'https://yogalayout.com/docs'
spec.summary = 'Yoga is a cross-platform layout engine which implements Flexbox.'
spec.description = 'Yoga is a cross-platform layout engine enabling maximum collaboration within your team by implementing an API many designers are familiar with, and opening it up to developers across different platforms.'
@@ -11,11 +11,14 @@ Pod::Spec.new do |spec|
spec.authors = 'Facebook'
spec.source = {
:git => 'https://github.com/facebook/yoga.git',
:tag => '1.7.0',
:tag => spec.version.to_s,
}
spec.platforms = { :ios => "8.0", :tvos => "10.0" }
spec.module_name = 'yoga'
spec.requires_arc = false
spec.pod_target_xcconfig = {
'DEFINES_MODULE' => 'YES'
}
spec.compiler_flags = [
'-fno-omit-frame-pointer',
'-fexceptions',
@@ -25,4 +28,6 @@ Pod::Spec.new do |spec|
'-fPIC'
]
spec.source_files = 'yoga/**/*.{c,h,cpp}'
spec.public_header_files = 'yoga/{Yoga,YGEnums,YGMacros}.h'
end

View File

@@ -1,6 +1,6 @@
podspec = Pod::Spec.new do |spec|
spec.name = 'YogaKit'
spec.version = '1.7.0'
spec.version = '1.9.0'
spec.license = { :type => 'MIT', :file => "LICENSE" }
spec.homepage = 'https://facebook.github.io/yoga/'
spec.documentation_url = 'https://facebook.github.io/yoga/docs/api/yogakit/'
@@ -11,14 +11,14 @@ podspec = Pod::Spec.new do |spec|
spec.authors = 'Facebook'
spec.source = {
:git => 'https://github.com/facebook/yoga.git',
:tag => '1.7.0',
:tag => spec.version.to_s,
}
spec.platform = :ios
spec.ios.deployment_target = '8.0'
spec.ios.frameworks = 'UIKit'
spec.dependency 'Yoga', '~> 1.7'
spec.dependency 'Yoga', '~> 1.9'
spec.source_files = 'YogaKit/Source/*.{h,m,swift}'
spec.public_header_files = 'YogaKit/Source/{YGLayout,UIView+Yoga}.h'
spec.private_header_files = 'YogaKit/Source/YGLayout+Private.h'

View File

@@ -2,8 +2,7 @@
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
load("//:yoga_defs.bzl", "yoga_dep", "apple_library", "apple_test")
load("//:yoga_defs.bzl", "subdir_glob", "yoga_apple_library", "yoga_apple_test", "yoga_dep")
COMPILER_FLAGS = [
"-fobjc-arc",
@@ -25,7 +24,7 @@ COMPILER_FLAGS = [
"-Wunused-value",
]
apple_library(
yoga_apple_library(
name = "YogaKit",
srcs = glob(["Source/**/*.m"]),
header_namespace = "",
@@ -49,7 +48,7 @@ apple_library(
],
)
apple_test(
yoga_apple_test(
name = "YogaKitTests",
srcs = glob(["Tests/**/*.m"]),
compiler_flags = COMPILER_FLAGS,

View File

@@ -3,9 +3,9 @@
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
load("//:yoga_defs.bzl", "ANDROID_JAVA_TARGET", "ANDROID_RES_TARGET", "INFER_ANNOTATIONS_TARGET", "JAVA_TARGET", "PROGRUARD_ANNOTATIONS_TARGET", "android_aar", "android_resource")
load("//:yoga_defs.bzl", "ANDROID_JAVA_TARGET", "ANDROID_RES_TARGET", "INFER_ANNOTATIONS_TARGET", "JAVA_TARGET", "PROGRUARD_ANNOTATIONS_TARGET", "yoga_android_aar", "yoga_android_resource")
android_aar(
yoga_android_aar(
name = "android",
manifest_skeleton = "src/main/AndroidManifest.xml",
visibility = [
@@ -20,7 +20,7 @@ android_aar(
],
)
android_resource(
yoga_android_resource(
name = "res",
package = "com.facebook.yoga.android",
res = "src/main/res",

View File

@@ -4,9 +4,9 @@
# This source code is licensed under the license found in the
# LICENSE-examples file in the root directory of this source tree.
load("//:yoga_defs.bzl", "ANDROID_SAMPLE_JAVA_TARGET", "ANDROID_SAMPLE_RES_TARGET", "ANDROID_RES_TARGET", "android_binary", "android_resource")
load("//:yoga_defs.bzl", "ANDROID_RES_TARGET", "ANDROID_SAMPLE_JAVA_TARGET", "ANDROID_SAMPLE_RES_TARGET", "yoga_android_binary", "yoga_android_resource")
android_binary(
yoga_android_binary(
name = "sample",
keystore = ":debug_keystore",
manifest = "AndroidManifest.xml",
@@ -16,7 +16,7 @@ android_binary(
],
)
android_resource(
yoga_android_resource(
name = "res",
package = "com.facebook.samples.yoga",
res = "res",

View File

@@ -1,13 +1,11 @@
# Copyright (c) 2014-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
# This source code is licensed under the license found in the
# LICENSE-examples file in the root directory of this source tree.
load("//:yoga_defs.bzl", "ANDROID_JAVA_TARGET", "ANDROID_SAMPLE_RES_TARGET", "ANDROID_SUPPORT_TARGET", "APPCOMPAT_TARGET", "SOLOADER_TARGET", "android_library")
load("//:yoga_defs.bzl", "ANDROID_JAVA_TARGET", "ANDROID_SAMPLE_RES_TARGET", "ANDROID_SUPPORT_TARGET", "APPCOMPAT_TARGET", "SOLOADER_TARGET", "yoga_android_library")
android_library(
yoga_android_library(
name = "yoga",
srcs = glob(["**/*.java"]),
visibility = [

View File

@@ -3,9 +3,9 @@
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
load("//:yoga_defs.bzl", "ANDROID_RES_TARGET", "INFER_ANNOTATIONS_TARGET", "JAVA_TARGET", "JSR_305_TARGET", "SOLOADER_TARGET", "android_library")
load("//:yoga_defs.bzl", "ANDROID_RES_TARGET", "INFER_ANNOTATIONS_TARGET", "JAVA_TARGET", "JSR_305_TARGET", "SOLOADER_TARGET", "yoga_android_library")
android_library(
yoga_android_library(
name = "android",
srcs = glob(["**/*.java"]),
visibility = [

View File

@@ -7,9 +7,6 @@
package com.facebook.yoga.android;
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.TypedArray;
@@ -21,9 +18,6 @@ import android.util.SparseArray;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.util.Log;
import com.facebook.yoga.android.R;
import com.facebook.yoga.YogaAlign;
import com.facebook.yoga.YogaConstants;
import com.facebook.yoga.YogaDirection;
@@ -35,10 +29,11 @@ import com.facebook.yoga.YogaMeasureFunction;
import com.facebook.yoga.YogaMeasureMode;
import com.facebook.yoga.YogaMeasureOutput;
import com.facebook.yoga.YogaNode;
import com.facebook.yoga.YogaNode;
import com.facebook.yoga.YogaOverflow;
import com.facebook.yoga.YogaPositionType;
import com.facebook.yoga.YogaWrap;
import java.util.HashMap;
import java.util.Map;
/**
* A {@code ViewGroup} based on the Yoga layout engine.
@@ -51,14 +46,14 @@ import com.facebook.yoga.YogaWrap;
* <YogaLayout
* xmlns:android="http://schemas.android.com/apk/res/android"
* xmlns:yoga="http://schemas.android.com/apk/com.facebook.yoga.android"
* android:layout_width="match_parent"
* android:layout_height="match_parent"
* android:layout_width="match_owner"
* android:layout_height="match_owner"
* yoga:flex_direction="row"
* yoga:padding_all="10dp"
* >
* <TextView
* android:layout_width="match_parent"
* android:layout_height="match_parent"
* android:layout_width="match_owner"
* android:layout_height="match_owner"
* android:text="Hello, World!"
* yoga:flex="1"
* />
@@ -267,11 +262,11 @@ public class YogaLayout extends ViewGroup {
return;
}
final YogaNode parent = node.getParent();
final YogaNode owner = node.getOwner();
for (int i = 0; i < parent.getChildCount(); i++) {
if (parent.getChildAt(i).equals(node)) {
parent.removeChildAt(i);
for (int i = 0; i < owner.getChildCount(); i++) {
if (owner.getChildAt(i).equals(node)) {
owner.removeChildAt(i);
break;
}
}
@@ -291,6 +286,8 @@ public class YogaLayout extends ViewGroup {
if (view.getVisibility() == GONE) {
return;
}
int left = Math.round(xOffset + node.getLayoutX());
int top = Math.round(yOffset + node.getLayoutY());
view.measure(
View.MeasureSpec.makeMeasureSpec(
Math.round(node.getLayoutWidth()),
@@ -298,11 +295,7 @@ public class YogaLayout extends ViewGroup {
View.MeasureSpec.makeMeasureSpec(
Math.round(node.getLayoutHeight()),
View.MeasureSpec.EXACTLY));
view.layout(
Math.round(xOffset + node.getLayoutX()),
Math.round(yOffset + node.getLayoutY()),
Math.round(xOffset + node.getLayoutX() + node.getLayoutWidth()),
Math.round(yOffset + node.getLayoutY() + node.getLayoutHeight()));
view.layout(left, top, left + view.getMeasuredWidth(), top + view.getMeasuredHeight());
}
final int childrenCount = node.getChildCount();
@@ -322,7 +315,7 @@ public class YogaLayout extends ViewGroup {
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// Either we are a root of a tree, or this function is called by our parent's onLayout, in which
// Either we are a root of a tree, or this function is called by our owner's onLayout, in which
// case our r-l and b-t are the size of our node.
if (!(getParent() instanceof YogaLayout)) {
createLayout(
@@ -706,7 +699,7 @@ public class YogaLayout extends ViewGroup {
/**
* Constructs a set of layout params, given width and height specs. In this case, we can set
* the {@code yoga:width} and {@code yoga:height} if we are given them explicitly. If other
* options (such as {@code match_parent} or {@code wrap_content} are given, then the parent
* options (such as {@code match_owner} or {@code wrap_content} are given, then the owner
* LayoutParams will store them, and we deal with them during layout. (see
* {@link YogaLayout#createLayout})
*
@@ -780,9 +773,9 @@ public class YogaLayout extends ViewGroup {
* {@code View}'s measure function.
*
* @param node The yoga node to measure
* @param width The suggested width from the parent
* @param width The suggested width from the owner
* @param widthMode The type of suggestion for the width
* @param height The suggested height from the parent
* @param height The suggested height from the owner
* @param heightMode The type of suggestion for the height
* @return A measurement output ({@code YogaMeasureOutput}) for the node
*/

View File

@@ -2,10 +2,9 @@
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
load("//:yoga_defs.bzl", "subdir_glob", "yoga_cxx_binary", "yoga_dep")
load("//:yoga_defs.bzl", "yoga_dep")
cxx_binary(
yoga_cxx_binary(
name = "benchmark",
srcs = glob(["*.c"]),
headers = subdir_glob([("", "*.h")]),

View File

@@ -5,10 +5,72 @@
* LICENSE file in the root directory of this source tree.
*/
#include "YGBenchmark.h"
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <yoga/Yoga.h>
#define NUM_REPETITIONS 1000
#define YGBENCHMARKS(BLOCK) \
int main(int argc, char const *argv[]) { \
clock_t __start; \
clock_t __endTimes[NUM_REPETITIONS]; \
{ BLOCK } \
return 0; \
}
#define YGBENCHMARK(NAME, BLOCK) \
__start = clock(); \
for (uint32_t __i = 0; __i < NUM_REPETITIONS; __i++) { \
{ BLOCK } \
__endTimes[__i] = clock(); \
} \
__printBenchmarkResult(NAME, __start, __endTimes);
static int __compareDoubles(const void *a, const void *b) {
double arg1 = *(const double *) a;
double arg2 = *(const double *) b;
if (arg1 < arg2) {
return -1;
}
if (arg1 > arg2) {
return 1;
}
return 0;
}
static void __printBenchmarkResult(char *name, clock_t start, clock_t *endTimes) {
double timesInMs[NUM_REPETITIONS];
double mean = 0;
clock_t lastEnd = start;
for (uint32_t i = 0; i < NUM_REPETITIONS; i++) {
timesInMs[i] = (endTimes[i] - lastEnd) / (double) CLOCKS_PER_SEC * 1000;
lastEnd = endTimes[i];
mean += timesInMs[i];
}
mean /= NUM_REPETITIONS;
qsort(timesInMs, NUM_REPETITIONS, sizeof(double), __compareDoubles);
double median = timesInMs[NUM_REPETITIONS / 2];
double variance = 0;
for (uint32_t i = 0; i < NUM_REPETITIONS; i++) {
variance += pow(timesInMs[i] - mean, 2);
}
variance /= NUM_REPETITIONS;
double stddev = sqrt(variance);
printf("%s: median: %lf ms, stddev: %lf ms\n", name, median, stddev);
}
static YGSize _measure(YGNodeRef node,
float width,
YGMeasureMode widthMode,
@@ -97,7 +159,7 @@ YGBENCHMARKS({
YGNodeStyleSetHeight(grandGrandChild, 10);
YGNodeInsertChild(grandChild, grandGrandChild, 0);
for (uint32_t iii = 0; iii < 10; iii++) {
for (uint32_t iiii = 0; iiii < 10; iiii++) {
const YGNodeRef grandGrandGrandChild = YGNodeNew();
YGNodeStyleSetFlexDirection(grandGrandGrandChild, YGFlexDirectionRow);
YGNodeStyleSetFlexGrow(grandGrandGrandChild, 1);

View File

@@ -1,71 +0,0 @@
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NUM_REPETITIONS 1000
#define YGBENCHMARKS(BLOCK) \
int main(int argc, char const *argv[]) { \
clock_t __start; \
clock_t __endTimes[NUM_REPETITIONS]; \
{ BLOCK } \
return 0; \
}
#define YGBENCHMARK(NAME, BLOCK) \
__start = clock(); \
for (uint32_t __i = 0; __i < NUM_REPETITIONS; __i++) { \
{ BLOCK } \
__endTimes[__i] = clock(); \
} \
__printBenchmarkResult(NAME, __start, __endTimes);
int __compareDoubles(const void *a, const void *b) {
double arg1 = *(const double *) a;
double arg2 = *(const double *) b;
if (arg1 < arg2) {
return -1;
}
if (arg1 > arg2) {
return 1;
}
return 0;
}
void __printBenchmarkResult(char *name, clock_t start, clock_t *endTimes) {
double timesInMs[NUM_REPETITIONS];
double mean = 0;
clock_t lastEnd = start;
for (uint32_t i = 0; i < NUM_REPETITIONS; i++) {
timesInMs[i] = (endTimes[i] - lastEnd) / (double) CLOCKS_PER_SEC * 1000;
lastEnd = endTimes[i];
mean += timesInMs[i];
}
mean /= NUM_REPETITIONS;
qsort(timesInMs, NUM_REPETITIONS, sizeof(double), __compareDoubles);
double median = timesInMs[NUM_REPETITIONS / 2];
double variance = 0;
for (uint32_t i = 0; i < NUM_REPETITIONS; i++) {
variance += pow(timesInMs[i] - mean, 2);
}
variance /= NUM_REPETITIONS;
double stddev = sqrt(variance);
printf("%s: median: %lf ms, stddev: %lf ms\n", name, median, stddev);
}

View File

@@ -3,7 +3,7 @@
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
load("//:yoga_defs.bzl", "BASE_COMPILER_FLAGS", "yoga_dep", "cxx_library", "is_apple_platform")
load("//:yoga_defs.bzl", "BASE_COMPILER_FLAGS", "is_apple_platform", "yoga_cxx_library", "yoga_dep")
COMPILER_FLAGS = BASE_COMPILER_FLAGS + ["-std=c++11"]
@@ -21,7 +21,7 @@ csharp_library(
framework_ver = "net45",
)
cxx_library(
yoga_cxx_library(
name = "yoganet",
srcs = glob(["Yoga/YGInterop.cpp"]),
compiler_flags = COMPILER_FLAGS,
@@ -33,39 +33,40 @@ cxx_library(
)
if is_apple_platform():
yoganet_ios_srcs = []
for arch in [
'iphonesimulator-x86_64', 'iphoneos-arm64'
]:
name = 'yoganet-' + arch
yoganet_ios_srcs.append(':' + name)
yoganet_ios_srcs = []
for arch in [
"iphonesimulator-x86_64",
"iphoneos-arm64",
]:
name = "yoganet-" + arch
yoganet_ios_srcs.append(":" + name)
genrule(
name = name,
srcs = [
yoga_dep(":yogaApple#%s,static" % arch),
yoga_dep("YogaKit:YogaKitApple#%s,static" % arch),
yoga_dep("csharp:yoganetApple#%s,static" % arch),
],
out = "libyoga-%s.a" % arch,
cmd = "libtool -static -o $OUT $SRCS",
visibility = [yoga_dep("csharp:yoganet-ios")],
)
genrule(
name = name,
srcs = [
yoga_dep(':yoga#%s,static' % arch),
yoga_dep('YogaKit:YogaKit#%s,static' % arch),
yoga_dep('csharp:yoganet#%s,static' % arch),
],
out = 'libyoga-%s.a' % arch,
cmd = 'libtool -static -o $OUT $SRCS',
visibility = [yoga_dep('csharp:yoganet-ios')],
name = "yoganet-ios",
srcs = yoganet_ios_srcs,
out = "libyoga.a",
cmd = "lipo $SRCS -create -output $OUT",
visibility = ["PUBLIC"],
)
genrule(
name = 'yoganet-ios',
srcs = yoganet_ios_srcs,
out = 'libyoga.a',
cmd = 'lipo $SRCS -create -output $OUT',
visibility = ['PUBLIC'],
)
yoganet_macosx_target = 'csharp:yoganet#macosx-%s,dynamic'
genrule(
name = 'yoganet-macosx',
srcs = [
yoga_dep(yoganet_macosx_target % 'x86_64')
],
out = 'libyoga.dylib',
cmd = 'lipo $SRCS -create -output $OUT',
visibility = ['PUBLIC'],
)
yoganet_macosx_target = "csharp:yoganetAppleMac#macosx-%s,dynamic"
genrule(
name = "yoganet-macosx",
srcs = [
yoga_dep(yoganet_macosx_target % "x86_64"),
],
out = "libyoga.dylib",
cmd = "lipo $SRCS -create -output $OUT",
visibility = ["PUBLIC"],
)

View File

@@ -227,19 +227,31 @@
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="..\..\yoga\Yoga.h" />
<ClInclude Include="..\..\yoga\Utils.h" />
<ClInclude Include="..\..\yoga\YGConfig.h" />
<ClInclude Include="..\..\yoga\YGEnums.h" />
<ClInclude Include="..\..\yoga\YGFloatOptional.h" />
<ClInclude Include="..\..\yoga\YGLayout.h" />
<ClInclude Include="..\..\yoga\YGMacros.h" />
<ClInclude Include="..\..\yoga\YGNodeList.h" />
<ClInclude Include="..\..\yoga\YGNode.h" />
<ClInclude Include="..\..\yoga\YGNodePrint.h" />
<ClInclude Include="..\..\yoga\YGStyle.h" />
<ClInclude Include="..\..\yoga\Yoga-internal.h" />
<ClInclude Include="..\..\yoga\Yoga.h" />
<ClInclude Include="resource.h" />
<ClInclude Include="YGInterop.h" />
<ClInclude Include="stdafx.h" />
<ClInclude Include="targetver.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\yoga\Yoga.c" />
<ClCompile Include="..\..\yoga\YGEnums.c" />
<ClCompile Include="..\..\yoga\YGNodeList.c" />
<ClCompile Include="..\..\yoga\Utils.cpp" />
<ClCompile Include="..\..\yoga\YGConfig.cpp" />
<ClCompile Include="..\..\yoga\YGEnums.cpp" />
<ClCompile Include="..\..\yoga\YGFloatOptional.cpp" />
<ClCompile Include="..\..\yoga\YGLayout.cpp" />
<ClCompile Include="..\..\yoga\YGNode.cpp" />
<ClCompile Include="..\..\yoga\YGNodePrint.cpp" />
<ClCompile Include="..\..\yoga\YGStyle.cpp" />
<ClCompile Include="..\..\yoga\Yoga.cpp" />
<ClCompile Include="YGInterop.cpp" />
<ClCompile Include="dllmain.cpp">
<CompileAsManaged Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</CompileAsManaged>

View File

@@ -21,19 +21,40 @@
<ClInclude Include="targetver.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\yoga\Yoga.h">
<ClInclude Include="resource.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\yoga\Utils.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\yoga\YGEnums.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\yoga\YGFloatOptional.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\yoga\YGLayout.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\yoga\YGMacros.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\yoga\YGNodeList.h">
<ClInclude Include="..\..\yoga\YGNode.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="YGInterop.h">
<ClInclude Include="..\..\yoga\YGNodePrint.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="resource.h">
<ClInclude Include="..\..\yoga\YGStyle.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\yoga\Yoga.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\yoga\Yoga-internal.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\yoga\YGConfig.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
@@ -44,15 +65,36 @@
<ClCompile Include="dllmain.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\yoga\Yoga.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\yoga\YGNodeList.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="YGInterop.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\yoga\Utils.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\yoga\YGEnums.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\yoga\YGFloatOptional.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\yoga\YGLayout.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\yoga\YGNode.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\yoga\YGNodePrint.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\yoga\YGStyle.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\yoga\Yoga.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\yoga\YGConfig.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="Yoga.rc">

View File

@@ -2,7 +2,7 @@
org.gradle.jvmargs=-Xmx1536M
VERSION_NAME=1.7.1-SNAPSHOT
VERSION_NAME=1.8.1-SNAPSHOT
POM_URL=https://github.com/facebook/yoga
POM_SCM_URL=https://github.com/facebook/yoga.git
POM_SCM_CONNECTION=scm:git:https://github.com/facebook/yoga.git

View File

@@ -3,9 +3,9 @@
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
load("//:yoga_defs.bzl", "FBJNI_TARGET", "JNI_TARGET", "INFER_ANNOTATIONS_TARGET", "JSR_305_TARGET", "PROGRUARD_ANNOTATIONS_TARGET", "SOLOADER_TARGET", "JUNIT_TARGET", "FBJNI_JAVA_TARGET", "CXX_LIBRARY_WHITELIST", "ANDROID", "yoga_dep", "cxx_library", "java_library", "java_test", "java_binary")
load("//:yoga_defs.bzl", "ANDROID", "CXX_LIBRARY_WHITELIST", "FBJNI_JAVA_TARGET", "FBJNI_TARGET", "INFER_ANNOTATIONS_TARGET", "JNI_TARGET", "JSR_305_TARGET", "JUNIT_TARGET", "PROGRUARD_ANNOTATIONS_TARGET", "SOLOADER_TARGET", "yoga_cxx_library", "yoga_dep", "yoga_java_binary", "yoga_java_library", "yoga_java_test")
cxx_library(
yoga_cxx_library(
name = "jni",
srcs = glob(["jni/*.cpp"]),
header_namespace = "",
@@ -28,30 +28,7 @@ cxx_library(
],
)
cxx_library(
name = "jniFastMath",
srcs = glob(["jni/*.cpp"]),
header_namespace = "",
compiler_flags = [
"-fno-omit-frame-pointer",
"-fexceptions",
"-fPIC",
"-Wall",
"-Werror",
"-O3",
"-std=c++11",
],
platforms = ANDROID,
soname = "libyogafastmath.$(ext)",
visibility = ["PUBLIC"],
deps = [
FBJNI_TARGET,
JNI_TARGET,
yoga_dep(":yogafastmath"),
],
)
java_library(
yoga_java_library(
name = "java",
srcs = glob(["com/facebook/yoga/*.java"]),
required_for_source_only_abi = True,
@@ -63,7 +40,6 @@ java_library(
visibility = ["PUBLIC"],
deps = [
":jni",
":jniFastMath",
INFER_ANNOTATIONS_TARGET,
JSR_305_TARGET,
PROGRUARD_ANNOTATIONS_TARGET,
@@ -71,7 +47,7 @@ java_library(
],
)
java_test(
yoga_java_test(
name = "tests",
srcs = glob(["tests/**/*.java"]),
cxx_library_whitelist = CXX_LIBRARY_WHITELIST,
@@ -83,7 +59,7 @@ java_test(
],
)
java_binary(
yoga_java_binary(
name = "yoga",
deps = [
":java",

View File

@@ -1,10 +1,10 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
import com.facebook.proguard.annotations.DoNotStrip;

View File

@@ -1,10 +1,10 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
import com.facebook.proguard.annotations.DoNotStrip;

View File

@@ -1,10 +1,10 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
import com.facebook.proguard.annotations.DoNotStrip;
@@ -16,16 +16,12 @@ public class YogaConfig {
public static int SPACING_TYPE = 1;
static {
if (YogaConstants.shouldUseFastMath) {
SoLoader.loadLibrary("yogafastmath");
} else {
SoLoader.loadLibrary("yoga");
}
}
long mNativePointer;
private YogaLogger mLogger;
private YogaNodeClonedFunction mNodeClonedFunction;
private YogaNodeCloneFunction mYogaNodeCloneFunction;
private native long jni_YGConfigNew();
public YogaConfig() {
@@ -74,6 +70,19 @@ public class YogaConfig {
jni_YGConfigSetUseLegacyStretchBehaviour(mNativePointer, useLegacyStretchBehaviour);
}
private native void jni_YGConfigSetShouldDiffLayoutWithoutLegacyStretchBehaviour(
long nativePointer, boolean shouldDiffLayoutWithoutLegacyStretchBehaviour);
/**
* If this flag is set then yoga would diff the layout without legacy flag and would set a bool in
* YogaNode(mDoesLegacyStretchFlagAffectsLayout) with true if the layouts were different and false
* if not
*/
public void setShouldDiffLayoutWithoutLegacyStretchBehaviour(
boolean shouldDiffLayoutWithoutLegacyStretchBehaviour) {
jni_YGConfigSetShouldDiffLayoutWithoutLegacyStretchBehaviour(
mNativePointer, shouldDiffLayoutWithoutLegacyStretchBehaviour);
}
private native void jni_YGConfigSetLogger(long nativePointer, Object logger);
public void setLogger(YogaLogger logger) {
mLogger = logger;
@@ -84,16 +93,15 @@ public class YogaConfig {
return mLogger;
}
private native void jni_YGConfigSetHasNodeClonedFunc(long nativePointer, boolean hasClonedFunc);
private native void jni_YGConfigSetHasCloneNodeFunc(long nativePointer, boolean hasClonedFunc);
public void setOnNodeCloned(YogaNodeClonedFunction nodeClonedFunction) {
mNodeClonedFunction = nodeClonedFunction;
jni_YGConfigSetHasNodeClonedFunc(mNativePointer, nodeClonedFunction != null);
public void setOnCloneNode(YogaNodeCloneFunction cloneYogaNodeFunction) {
mYogaNodeCloneFunction = cloneYogaNodeFunction;
jni_YGConfigSetHasCloneNodeFunc(mNativePointer, cloneYogaNodeFunction != null);
}
@DoNotStrip
public final void onNodeCloned(
YogaNode oldNode, YogaNode newNode, YogaNode parent, int childIndex) {
mNodeClonedFunction.onNodeCloned(oldNode, newNode, parent, childIndex);
private final YogaNode cloneNode(YogaNode oldNode, YogaNode parent, int childIndex) {
return mYogaNodeCloneFunction.cloneNode(oldNode, parent, childIndex);
}
}

View File

@@ -1,10 +1,10 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
public class YogaConstants {
@@ -18,8 +18,6 @@ public class YogaConstants {
*/
public static final float UNDEFINED = (float) (10E20);
public static boolean shouldUseFastMath = false;
public static boolean isUndefined(float value) {
// Value of a float in the case of it being not defined is 10.1E20. Earlier it used to be NAN,
// the benefit of which

View File

@@ -1,10 +1,10 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
import com.facebook.proguard.annotations.DoNotStrip;

View File

@@ -1,10 +1,10 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
import com.facebook.proguard.annotations.DoNotStrip;

View File

@@ -1,10 +1,10 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
import com.facebook.proguard.annotations.DoNotStrip;

View File

@@ -1,10 +1,10 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
import com.facebook.proguard.annotations.DoNotStrip;

View File

@@ -1,10 +1,10 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
import com.facebook.proguard.annotations.DoNotStrip;

View File

@@ -1,10 +1,10 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
import com.facebook.proguard.annotations.DoNotStrip;

View File

@@ -1,10 +1,10 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
import com.facebook.proguard.annotations.DoNotStrip;

View File

@@ -1,10 +1,10 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
import com.facebook.proguard.annotations.DoNotStrip;

View File

@@ -1,10 +1,10 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
import com.facebook.proguard.annotations.DoNotStrip;

View File

@@ -1,10 +1,10 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
import com.facebook.proguard.annotations.DoNotStrip;

View File

@@ -1,10 +1,10 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
import com.facebook.proguard.annotations.DoNotStrip;

View File

@@ -1,10 +1,10 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
/**

View File

@@ -1,8 +1,9 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
@@ -17,11 +18,7 @@ import javax.annotation.Nullable;
public class YogaNode implements Cloneable {
static {
if (YogaConstants.shouldUseFastMath) {
SoLoader.loadLibrary("yogafastmath");
} else {
SoLoader.loadLibrary("yoga");
}
}
/**
@@ -29,8 +26,8 @@ public class YogaNode implements Cloneable {
*/
static native int jni_YGNodeGetInstanceCount();
private YogaNode mParent;
private List<YogaNode> mChildren;
private YogaNode mOwner;
@Nullable private List<YogaNode> mChildren;
private YogaMeasureFunction mMeasureFunction;
private YogaBaselineFunction mBaselineFunction;
private long mNativePointer;
@@ -82,6 +79,7 @@ public class YogaNode implements Cloneable {
private int mLayoutDirection = 0;
@DoNotStrip
private boolean mHasNewLayout = true;
@DoNotStrip private boolean mDoesLegacyStretchFlagAffectsLayout = false;
private native long jni_YGNodeNew();
public YogaNode() {
@@ -136,6 +134,7 @@ public class YogaNode implements Cloneable {
mMeasureFunction = null;
mBaselineFunction = null;
mData = null;
mDoesLegacyStretchFlagAffectsLayout = false;
jni_YGNodeReset(mNativePointer);
}
@@ -145,12 +144,15 @@ public class YogaNode implements Cloneable {
}
public YogaNode getChildAt(int i) {
if (mChildren == null) {
throw new IllegalStateException("YogaNode does not have children");
}
return mChildren.get(i);
}
private native void jni_YGNodeInsertChild(long nativePointer, long childPointer, int index);
public void addChildAt(YogaNode child, int i) {
if (child.mParent != null) {
if (child.mOwner != null) {
throw new IllegalStateException("Child already has a parent, it must be removed first.");
}
@@ -158,35 +160,105 @@ public class YogaNode implements Cloneable {
mChildren = new ArrayList<>(4);
}
mChildren.add(i, child);
child.mParent = this;
child.mOwner = this;
jni_YGNodeInsertChild(mNativePointer, child.mNativePointer, i);
}
private native void jni_YGNodeInsertSharedChild(long nativePointer, long childPointer, int index);
public void addSharedChildAt(YogaNode child, int i) {
if (mChildren == null) {
mChildren = new ArrayList<>(4);
}
mChildren.add(i, child);
child.mOwner = null;
jni_YGNodeInsertSharedChild(mNativePointer, child.mNativePointer, i);
}
private native void jni_YGNodeSetOwner(long nativePointer, long newOwnerNativePointer);
private native long jni_YGNodeClone(long nativePointer, Object newNode);
@Override
public YogaNode clone() throws CloneNotSupportedException {
YogaNode clonedYogaNode = (YogaNode) super.clone();
long clonedNativePointer = jni_YGNodeClone(mNativePointer, clonedYogaNode);
clonedYogaNode.mNativePointer = clonedNativePointer;
clonedYogaNode.mChildren =
mChildren != null ? (List<YogaNode>) ((ArrayList) mChildren).clone() : null;
return clonedYogaNode;
public YogaNode clone() {
try {
YogaNode clonedYogaNode = (YogaNode) super.clone();
long clonedNativePointer = jni_YGNodeClone(mNativePointer, clonedYogaNode);
if (mChildren != null) {
for (YogaNode child : mChildren) {
child.jni_YGNodeSetOwner(child.mNativePointer, 0);
child.mOwner = null;
}
}
clonedYogaNode.mNativePointer = clonedNativePointer;
clonedYogaNode.mOwner = null;
clonedYogaNode.mChildren =
mChildren != null ? (List<YogaNode>) ((ArrayList) mChildren).clone() : null;
if (clonedYogaNode.mChildren != null) {
for (YogaNode child : clonedYogaNode.mChildren) {
child.mOwner = null;
}
}
return clonedYogaNode;
} catch (CloneNotSupportedException ex) {
// This class implements Cloneable, this should not happen
throw new RuntimeException(ex);
}
}
public YogaNode cloneWithNewChildren() {
try {
YogaNode clonedYogaNode = (YogaNode) super.clone();
long clonedNativePointer = jni_YGNodeClone(mNativePointer, clonedYogaNode);
clonedYogaNode.mOwner = null;
clonedYogaNode.mNativePointer = clonedNativePointer;
clonedYogaNode.clearChildren();
return clonedYogaNode;
} catch (CloneNotSupportedException ex) {
// This class implements Cloneable, this should not happen
throw new RuntimeException(ex);
}
}
private native void jni_YGNodeClearChildren(long nativePointer);
private void clearChildren() {
mChildren = null;
jni_YGNodeClearChildren(mNativePointer);
}
private native void jni_YGNodeRemoveChild(long nativePointer, long childPointer);
public YogaNode removeChildAt(int i) {
if (mChildren == null) {
throw new IllegalStateException(
"Trying to remove a child of a YogaNode that does not have children");
}
final YogaNode child = mChildren.remove(i);
child.mParent = null;
child.mOwner = null;
jni_YGNodeRemoveChild(mNativePointer, child.mNativePointer);
return child;
}
/**
* @returns the {@link YogaNode} that owns this {@link YogaNode}.
* The owner is used to identify the YogaTree that a {@link YogaNode} belongs
* to.
* This method will return the parent of the {@link YogaNode} when the
* {@link YogaNode} only belongs to one YogaTree or null when the
* {@link YogaNode} is shared between two or more YogaTrees.
*/
@Nullable
public
YogaNode getParent() {
return mParent;
public YogaNode getOwner() {
return mOwner;
}
/** @deprecated Use #getOwner() instead. This will be removed in the next version. */
@Deprecated
@Nullable
public YogaNode getParent() {
return getOwner();
}
public int indexOf(YogaNode child) {
@@ -573,6 +645,10 @@ public class YogaNode implements Cloneable {
return mHeight;
}
public boolean getDoesLegacyStretchFlagAffectsLayout() {
return mDoesLegacyStretchFlagAffectsLayout;
}
public float getLayoutMargin(YogaEdge edge) {
switch (edge) {
case LEFT:
@@ -691,4 +767,22 @@ public class YogaNode implements Cloneable {
public void print() {
jni_YGNodePrint(mNativePointer);
}
/**
* This method replaces the child at childIndex position with the newNode received by parameter.
* This is different than calling removeChildAt and addChildAt because this method ONLY replaces
* the child in the mChildren datastructure. @DoNotStrip: called from JNI
*
* @return the nativePointer of the newNode {@linl YogaNode}
*/
@DoNotStrip
private final long replaceChild(YogaNode newNode, int childIndex) {
if (mChildren == null) {
throw new IllegalStateException("Cannot replace child. YogaNode does not have children");
}
mChildren.remove(childIndex);
mChildren.add(childIndex, newNode);
newNode.mOwner = this;
return newNode.mNativePointer;
}
}

View File

@@ -0,0 +1,17 @@
/*
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
*/
package com.facebook.yoga;
import com.facebook.proguard.annotations.DoNotStrip;
@DoNotStrip
public interface YogaNodeCloneFunction {
@DoNotStrip
YogaNode cloneNode(YogaNode oldNode, YogaNode parent, int childIndex);
}

View File

@@ -1,17 +0,0 @@
/*
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
import com.facebook.proguard.annotations.DoNotStrip;
@DoNotStrip
public interface YogaNodeClonedFunction {
@DoNotStrip
void onNodeCloned(YogaNode oldNode, YogaNode newNode, YogaNode parent, int childIndex);
}

View File

@@ -0,0 +1,167 @@
/*
* Copyright (c) 2018-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
*/
package com.facebook.yoga;
public interface YogaNodeProperties {
YogaNodeProperties clone(YogaNode node);
long getNativePointer();
void onAfterCalculateLayout();
void reset();
boolean hasNewLayout();
boolean isDirty();
void markLayoutSeen();
YogaDirection getStyleDirection();
void setDirection(YogaDirection direction);
YogaFlexDirection getFlexDirection();
void setFlexDirection(YogaFlexDirection flexDirection);
YogaJustify getJustifyContent();
void setJustifyContent(YogaJustify justifyContent);
YogaAlign getAlignItems();
void setAlignItems(YogaAlign alignItems);
YogaAlign getAlignSelf();
void setAlignSelf(YogaAlign alignSelf);
YogaAlign getAlignContent();
void setAlignContent(YogaAlign alignContent);
YogaPositionType getPositionType();
void setPositionType(YogaPositionType positionType);
void setWrap(YogaWrap flexWrap);
YogaOverflow getOverflow();
void setOverflow(YogaOverflow overflow);
YogaDisplay getDisplay();
void setDisplay(YogaDisplay display);
void setFlex(float flex);
float getFlexGrow();
void setFlexGrow(float flexGrow);
float getFlexShrink();
void setFlexShrink(float flexShrink);
YogaValue getFlexBasis();
void setFlexBasis(float flexBasis);
void setFlexBasisPercent(float percent);
void setFlexBasisAuto();
YogaValue getMargin(YogaEdge edge);
void setMargin(YogaEdge edge, float margin);
void setMarginPercent(YogaEdge edge, float percent);
void setMarginAuto(YogaEdge edge);
YogaValue getPadding(YogaEdge edge);
void setPadding(YogaEdge edge, float padding);
void setPaddingPercent(YogaEdge edge, float percent);
float getBorder(YogaEdge edge);
void setBorder(YogaEdge edge, float border);
YogaValue getPosition(YogaEdge edge);
void setPosition(YogaEdge edge, float position);
void setPositionPercent(YogaEdge edge, float percent);
YogaValue getWidth();
void setWidth(float width);
void setWidthPercent(float percent);
void setWidthAuto();
YogaValue getHeight();
void setHeight(float height);
void setHeightPercent(float percent);
void setHeightAuto();
YogaValue getMinWidth();
void setMinWidth(float minWidth);
void setMinWidthPercent(float percent);
YogaValue getMinHeight();
void setMinHeight(float minHeight);
void setMinHeightPercent(float percent);
YogaValue getMaxWidth();
void setMaxWidth(float maxWidth);
void setMaxWidthPercent(float percent);
YogaValue getMaxHeight();
void setMaxHeight(float maxheight);
void setMaxHeightPercent(float percent);
float getAspectRatio();
void setAspectRatio(float aspectRatio);
float getLayoutX();
float getLayoutY();
float getLayoutWidth();
float getLayoutHeight();
boolean getDoesLegacyStretchFlagAffectsLayout();
float getLayoutMargin(YogaEdge edge);
float getLayoutPadding(YogaEdge edge);
float getLayoutBorder(YogaEdge edge);
YogaDirection getLayoutDirection();
}

View File

@@ -1,10 +1,10 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
import com.facebook.proguard.annotations.DoNotStrip;

View File

@@ -1,10 +1,10 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
import com.facebook.proguard.annotations.DoNotStrip;

View File

@@ -1,10 +1,10 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
import com.facebook.proguard.annotations.DoNotStrip;

View File

@@ -1,10 +1,10 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
import com.facebook.proguard.annotations.DoNotStrip;

View File

@@ -1,10 +1,10 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
import com.facebook.proguard.annotations.DoNotStrip;

View File

@@ -1,10 +1,10 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
import com.facebook.proguard.annotations.DoNotStrip;

View File

@@ -1,10 +1,10 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.yoga;
import com.facebook.proguard.annotations.DoNotStrip;

View File

@@ -1,10 +1,10 @@
/**
* Copyright (c) 2014-present, Facebook, Inc.
/*
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <fb/fbjni.h>
#include <yoga/YGNode.h>
#include <yoga/Yoga.h>
@@ -33,84 +33,121 @@ struct YGConfigContext {
}
};
static inline weak_ref<JYogaNode> *YGNodeJobject(YGNodeRef node) {
static inline weak_ref<JYogaNode>* YGNodeJobject(YGNodeRef node) {
return reinterpret_cast<weak_ref<JYogaNode>*>(node->getContext());
}
static void YGTransferLayoutDirection(YGNodeRef node, alias_ref<jobject> javaNode) {
static auto layoutDirectionField = javaNode->getClass()->getField<jint>("mLayoutDirection");
javaNode->setFieldValue(layoutDirectionField, static_cast<jint>(YGNodeLayoutGetDirection(node)));
static void YGTransferLayoutDirection(
YGNodeRef node,
alias_ref<jobject> javaNode) {
static auto layoutDirectionField =
javaNode->getClass()->getField<jint>("mLayoutDirection");
javaNode->setFieldValue(
layoutDirectionField, static_cast<jint>(YGNodeLayoutGetDirection(node)));
}
static void YGTransferLayoutOutputsRecursive(YGNodeRef root) {
if (root->getHasNewLayout()) {
if (auto obj = YGNodeJobject(root)->lockLocal()) {
static auto widthField = obj->getClass()->getField<jfloat>("mWidth");
static auto heightField = obj->getClass()->getField<jfloat>("mHeight");
static auto leftField = obj->getClass()->getField<jfloat>("mLeft");
static auto topField = obj->getClass()->getField<jfloat>("mTop");
if (!root->getHasNewLayout()) {
return;
}
auto obj = YGNodeJobject(root)->lockLocal();
if (!obj) {
YGLog(
root,
YGLogLevelError,
"Java YGNode was GCed during layout calculation\n");
return;
}
static auto marginLeftField = obj->getClass()->getField<jfloat>("mMarginLeft");
static auto marginTopField = obj->getClass()->getField<jfloat>("mMarginTop");
static auto marginRightField = obj->getClass()->getField<jfloat>("mMarginRight");
static auto marginBottomField = obj->getClass()->getField<jfloat>("mMarginBottom");
static auto widthField = obj->getClass()->getField<jfloat>("mWidth");
static auto heightField = obj->getClass()->getField<jfloat>("mHeight");
static auto leftField = obj->getClass()->getField<jfloat>("mLeft");
static auto topField = obj->getClass()->getField<jfloat>("mTop");
static auto paddingLeftField = obj->getClass()->getField<jfloat>("mPaddingLeft");
static auto paddingTopField = obj->getClass()->getField<jfloat>("mPaddingTop");
static auto paddingRightField = obj->getClass()->getField<jfloat>("mPaddingRight");
static auto paddingBottomField = obj->getClass()->getField<jfloat>("mPaddingBottom");
static auto marginLeftField =
obj->getClass()->getField<jfloat>("mMarginLeft");
static auto marginTopField = obj->getClass()->getField<jfloat>("mMarginTop");
static auto marginRightField =
obj->getClass()->getField<jfloat>("mMarginRight");
static auto marginBottomField =
obj->getClass()->getField<jfloat>("mMarginBottom");
static auto borderLeftField = obj->getClass()->getField<jfloat>("mBorderLeft");
static auto borderTopField = obj->getClass()->getField<jfloat>("mBorderTop");
static auto borderRightField = obj->getClass()->getField<jfloat>("mBorderRight");
static auto borderBottomField = obj->getClass()->getField<jfloat>("mBorderBottom");
static auto paddingLeftField =
obj->getClass()->getField<jfloat>("mPaddingLeft");
static auto paddingTopField =
obj->getClass()->getField<jfloat>("mPaddingTop");
static auto paddingRightField =
obj->getClass()->getField<jfloat>("mPaddingRight");
static auto paddingBottomField =
obj->getClass()->getField<jfloat>("mPaddingBottom");
static auto edgeSetFlagField = obj->getClass()->getField<jint>("mEdgeSetFlag");
static auto hasNewLayoutField = obj->getClass()->getField<jboolean>("mHasNewLayout");
static auto borderLeftField =
obj->getClass()->getField<jfloat>("mBorderLeft");
static auto borderTopField = obj->getClass()->getField<jfloat>("mBorderTop");
static auto borderRightField =
obj->getClass()->getField<jfloat>("mBorderRight");
static auto borderBottomField =
obj->getClass()->getField<jfloat>("mBorderBottom");
/* Those flags needs be in sync with YogaNode.java */
const int MARGIN = 1;
const int PADDING = 2;
const int BORDER = 4;
static auto edgeSetFlagField =
obj->getClass()->getField<jint>("mEdgeSetFlag");
static auto hasNewLayoutField =
obj->getClass()->getField<jboolean>("mHasNewLayout");
static auto doesLegacyStretchBehaviour = obj->getClass()->getField<jboolean>(
"mDoesLegacyStretchFlagAffectsLayout");
int hasEdgeSetFlag = (int) obj->getFieldValue(edgeSetFlagField);
/* Those flags needs be in sync with YogaNode.java */
const int MARGIN = 1;
const int PADDING = 2;
const int BORDER = 4;
obj->setFieldValue(widthField, YGNodeLayoutGetWidth(root));
obj->setFieldValue(heightField, YGNodeLayoutGetHeight(root));
obj->setFieldValue(leftField, YGNodeLayoutGetLeft(root));
obj->setFieldValue(topField, YGNodeLayoutGetTop(root));
int hasEdgeSetFlag = (int)obj->getFieldValue(edgeSetFlagField);
if ((hasEdgeSetFlag & MARGIN) == MARGIN) {
obj->setFieldValue(marginLeftField, YGNodeLayoutGetMargin(root, YGEdgeLeft));
obj->setFieldValue(marginTopField, YGNodeLayoutGetMargin(root, YGEdgeTop));
obj->setFieldValue(marginRightField, YGNodeLayoutGetMargin(root, YGEdgeRight));
obj->setFieldValue(marginBottomField, YGNodeLayoutGetMargin(root, YGEdgeBottom));
}
obj->setFieldValue(widthField, YGNodeLayoutGetWidth(root));
obj->setFieldValue(heightField, YGNodeLayoutGetHeight(root));
obj->setFieldValue(leftField, YGNodeLayoutGetLeft(root));
obj->setFieldValue(topField, YGNodeLayoutGetTop(root));
obj->setFieldValue<jboolean>(
doesLegacyStretchBehaviour,
YGNodeLayoutGetDidLegacyStretchFlagAffectLayout(root));
if ((hasEdgeSetFlag & PADDING) == PADDING) {
obj->setFieldValue(paddingLeftField, YGNodeLayoutGetPadding(root, YGEdgeLeft));
obj->setFieldValue(paddingTopField, YGNodeLayoutGetPadding(root, YGEdgeTop));
obj->setFieldValue(paddingRightField, YGNodeLayoutGetPadding(root, YGEdgeRight));
obj->setFieldValue(paddingBottomField, YGNodeLayoutGetPadding(root, YGEdgeBottom));
}
if ((hasEdgeSetFlag & MARGIN) == MARGIN) {
obj->setFieldValue(
marginLeftField, YGNodeLayoutGetMargin(root, YGEdgeLeft));
obj->setFieldValue(marginTopField, YGNodeLayoutGetMargin(root, YGEdgeTop));
obj->setFieldValue(
marginRightField, YGNodeLayoutGetMargin(root, YGEdgeRight));
obj->setFieldValue(
marginBottomField, YGNodeLayoutGetMargin(root, YGEdgeBottom));
}
if ((hasEdgeSetFlag & BORDER) == BORDER) {
obj->setFieldValue(borderLeftField, YGNodeLayoutGetBorder(root, YGEdgeLeft));
obj->setFieldValue(borderTopField, YGNodeLayoutGetBorder(root, YGEdgeTop));
obj->setFieldValue(borderRightField, YGNodeLayoutGetBorder(root, YGEdgeRight));
obj->setFieldValue(borderBottomField, YGNodeLayoutGetBorder(root, YGEdgeBottom));
}
if ((hasEdgeSetFlag & PADDING) == PADDING) {
obj->setFieldValue(
paddingLeftField, YGNodeLayoutGetPadding(root, YGEdgeLeft));
obj->setFieldValue(
paddingTopField, YGNodeLayoutGetPadding(root, YGEdgeTop));
obj->setFieldValue(
paddingRightField, YGNodeLayoutGetPadding(root, YGEdgeRight));
obj->setFieldValue(
paddingBottomField, YGNodeLayoutGetPadding(root, YGEdgeBottom));
}
obj->setFieldValue<jboolean>(hasNewLayoutField, true);
YGTransferLayoutDirection(root, obj);
root->setHasNewLayout(false);
if ((hasEdgeSetFlag & BORDER) == BORDER) {
obj->setFieldValue(
borderLeftField, YGNodeLayoutGetBorder(root, YGEdgeLeft));
obj->setFieldValue(borderTopField, YGNodeLayoutGetBorder(root, YGEdgeTop));
obj->setFieldValue(
borderRightField, YGNodeLayoutGetBorder(root, YGEdgeRight));
obj->setFieldValue(
borderBottomField, YGNodeLayoutGetBorder(root, YGEdgeBottom));
}
for (uint32_t i = 0; i < YGNodeGetChildCount(root); i++) {
YGTransferLayoutOutputsRecursive(YGNodeGetChild(root, i));
}
} else {
YGLog(root, YGLogLevelError, "Java YGNode was GCed during layout calculation\n");
}
obj->setFieldValue<jboolean>(hasNewLayoutField, true);
YGTransferLayoutDirection(root, obj);
root->setHasNewLayout(false);
for (uint32_t i = 0; i < YGNodeGetChildCount(root); i++) {
YGTransferLayoutOutputsRecursive(YGNodeGetChild(root, i));
}
}
@@ -118,45 +155,61 @@ static void YGPrint(YGNodeRef node) {
if (auto obj = YGNodeJobject(node)->lockLocal()) {
cout << obj->toString() << endl;
} else {
YGLog(node, YGLogLevelError, "Java YGNode was GCed during layout calculation\n");
YGLog(
node,
YGLogLevelError,
"Java YGNode was GCed during layout calculation\n");
}
}
static float YGJNIBaselineFunc(YGNodeRef node, float width, float height) {
if (auto obj = YGNodeJobject(node)->lockLocal()) {
static auto baselineFunc = findClassStatic("com/facebook/yoga/YogaNode")
->getMethod<jfloat(jfloat, jfloat)>("baseline");
static auto baselineFunc =
findClassStatic("com/facebook/yoga/YogaNode")
->getMethod<jfloat(jfloat, jfloat)>("baseline");
return baselineFunc(obj, width, height);
} else {
return height;
}
}
static void YGJNIOnNodeClonedFunc(
YGNodeRef oldNode,
YGNodeRef newNode,
YGNodeRef parent,
int childIndex) {
static inline YGNodeRef _jlong2YGNodeRef(jlong addr) {
return reinterpret_cast<YGNodeRef>(static_cast<intptr_t>(addr));
}
static inline YGConfigRef _jlong2YGConfigRef(jlong addr) {
return reinterpret_cast<YGConfigRef>(static_cast<intptr_t>(addr));
}
static YGNodeRef
YGJNIOnNodeClonedFunc(YGNodeRef oldNode, YGNodeRef owner, int childIndex) {
auto config = oldNode->getConfig();
if (!config) {
return;
return nullptr;
}
static auto onNodeClonedFunc = findClassStatic("com/facebook/yoga/YogaConfig")
->getMethod<void(
local_ref<JYogaNode>,
local_ref<JYogaNode>,
local_ref<JYogaNode>,
jint)>("onNodeCloned");
static auto onNodeClonedFunc =
findClassStatic("com/facebook/yoga/YogaConfig")
->getMethod<alias_ref<JYogaNode>(
local_ref<JYogaNode>, local_ref<JYogaNode>, jint)>("cloneNode");
auto context = reinterpret_cast<YGConfigContext*>(YGConfigGetContext(config));
auto javaConfig = context->config;
onNodeClonedFunc(
auto newNode = onNodeClonedFunc(
javaConfig->get(),
YGNodeJobject(oldNode)->lockLocal(),
YGNodeJobject(newNode)->lockLocal(),
YGNodeJobject(parent)->lockLocal(),
YGNodeJobject(owner)->lockLocal(),
childIndex);
static auto replaceChild =
findClassStatic("com/facebook/yoga/YogaNode")
->getMethod<jlong(local_ref<JYogaNode>, jint)>("replaceChild");
jlong newNodeNativePointer =
replaceChild(YGNodeJobject(owner)->lockLocal(), newNode, childIndex);
return _jlong2YGNodeRef(newNodeNativePointer);
}
static YGSize YGJNIMeasureFunc(
@@ -166,24 +219,30 @@ static YGSize YGJNIMeasureFunc(
float height,
YGMeasureMode heightMode) {
if (auto obj = YGNodeJobject(node)->lockLocal()) {
static auto measureFunc = findClassStatic("com/facebook/yoga/YogaNode")
->getMethod<jlong(jfloat, jint, jfloat, jint)>("measure");
static auto measureFunc =
findClassStatic("com/facebook/yoga/YogaNode")
->getMethod<jlong(jfloat, jint, jfloat, jint)>("measure");
YGTransferLayoutDirection(node, obj);
const auto measureResult = measureFunc(obj, width, widthMode, height, heightMode);
const auto measureResult =
measureFunc(obj, width, widthMode, height, heightMode);
static_assert(sizeof(measureResult) == 8,
"Expected measureResult to be 8 bytes, or two 32 bit ints");
static_assert(
sizeof(measureResult) == 8,
"Expected measureResult to be 8 bytes, or two 32 bit ints");
int32_t wBits = 0xFFFFFFFF & (measureResult >> 32);
int32_t hBits = 0xFFFFFFFF & measureResult;
const float *measuredWidth = reinterpret_cast<float *>(&wBits);
const float *measuredHeight = reinterpret_cast<float *>(&hBits);
const float* measuredWidth = reinterpret_cast<float*>(&wBits);
const float* measuredHeight = reinterpret_cast<float*>(&hBits);
return YGSize{*measuredWidth, *measuredHeight};
} else {
YGLog(node, YGLogLevelError, "Java YGNode was GCed during layout calculation\n");
YGLog(
node,
YGLogLevelError,
"Java YGNode was GCed during layout calculation\n");
return YGSize{
widthMode == YGMeasureModeUndefined ? 0 : width,
heightMode == YGMeasureModeUndefined ? 0 : height,
@@ -195,24 +254,28 @@ struct JYogaLogLevel : public JavaClass<JYogaLogLevel> {
static constexpr auto kJavaDescriptor = "Lcom/facebook/yoga/YogaLogLevel;";
};
static int YGJNILogFunc(const YGConfigRef config,
const YGNodeRef node,
YGLogLevel level,
const char *format,
va_list args) {
static int YGJNILogFunc(
const YGConfigRef config,
const YGNodeRef node,
YGLogLevel level,
const char* format,
va_list args) {
int result = vsnprintf(NULL, 0, format, args);
std::vector<char> buffer(1 + result);
vsnprintf(buffer.data(), buffer.size(), format, args);
static auto logFunc =
findClassStatic("com/facebook/yoga/YogaLogger")
->getMethod<void(local_ref<JYogaNode>, local_ref<JYogaLogLevel>, jstring)>("log");
->getMethod<void(
local_ref<JYogaNode>, local_ref<JYogaLogLevel>, jstring)>("log");
static auto logLevelFromInt =
JYogaLogLevel::javaClassStatic()->getStaticMethod<JYogaLogLevel::javaobject(jint)>("fromInt");
JYogaLogLevel::javaClassStatic()
->getStaticMethod<JYogaLogLevel::javaobject(jint)>("fromInt");
if (auto obj = YGNodeJobject(node)->lockLocal()) {
auto jlogger = reinterpret_cast<global_ref<jobject> *>(YGConfigGetContext(config));
auto jlogger =
reinterpret_cast<global_ref<jobject>*>(YGConfigGetContext(config));
logFunc(
jlogger->get(),
obj,
@@ -224,14 +287,6 @@ static int YGJNILogFunc(const YGConfigRef config,
return result;
}
static inline YGNodeRef _jlong2YGNodeRef(jlong addr) {
return reinterpret_cast<YGNodeRef>(static_cast<intptr_t>(addr));
}
static inline YGConfigRef _jlong2YGConfigRef(jlong addr) {
return reinterpret_cast<YGConfigRef>(static_cast<intptr_t>(addr));
}
jlong jni_YGNodeNew(alias_ref<jobject> thiz) {
const YGNodeRef node = YGNodeNew();
node->setContext(new weak_ref<jobject>(make_weak(thiz)));
@@ -248,6 +303,16 @@ jlong jni_YGNodeNewWithConfig(alias_ref<jobject> thiz, jlong configPointer) {
return reinterpret_cast<jlong>(node);
}
void jni_YGNodeSetOwner(
alias_ref<jobject> thiz,
jlong nativePointer,
jlong newOwnerNativePointer) {
const YGNodeRef node = _jlong2YGNodeRef(nativePointer);
const YGNodeRef newOwnerNode = _jlong2YGNodeRef(newOwnerNativePointer);
node->setOwner(newOwnerNode);
}
jlong jni_YGNodeClone(
alias_ref<jobject> thiz,
jlong nativePointer,
@@ -264,6 +329,11 @@ void jni_YGNodeFree(alias_ref<jobject> thiz, jlong nativePointer) {
YGNodeFree(node);
}
void jni_YGNodeClearChildren(alias_ref<jobject> thiz, jlong nativePointer) {
const YGNodeRef node = _jlong2YGNodeRef(nativePointer);
node->clearChildren();
}
void jni_YGNodeReset(alias_ref<jobject> thiz, jlong nativePointer) {
const YGNodeRef node = _jlong2YGNodeRef(nativePointer);
void* context = node->getContext();
@@ -274,28 +344,49 @@ void jni_YGNodeReset(alias_ref<jobject> thiz, jlong nativePointer) {
void jni_YGNodePrint(alias_ref<jobject> thiz, jlong nativePointer) {
const YGNodeRef node = _jlong2YGNodeRef(nativePointer);
YGNodePrint(node,
(YGPrintOptions)(YGPrintOptionsStyle | YGPrintOptionsLayout |
YGPrintOptionsChildren));
YGNodePrint(
node,
(YGPrintOptions)(
YGPrintOptionsStyle | YGPrintOptionsLayout | YGPrintOptionsChildren));
}
void jni_YGNodeInsertChild(alias_ref<jobject>, jlong nativePointer, jlong childPointer, jint index) {
YGNodeInsertChild(_jlong2YGNodeRef(nativePointer), _jlong2YGNodeRef(childPointer), index);
void jni_YGNodeInsertChild(
alias_ref<jobject>,
jlong nativePointer,
jlong childPointer,
jint index) {
YGNodeInsertChild(
_jlong2YGNodeRef(nativePointer), _jlong2YGNodeRef(childPointer), index);
}
void jni_YGNodeRemoveChild(alias_ref<jobject>, jlong nativePointer, jlong childPointer) {
YGNodeRemoveChild(_jlong2YGNodeRef(nativePointer), _jlong2YGNodeRef(childPointer));
void jni_YGNodeInsertSharedChild(
alias_ref<jobject>,
jlong nativePointer,
jlong childPointer,
jint index) {
YGNodeInsertSharedChild(
_jlong2YGNodeRef(nativePointer), _jlong2YGNodeRef(childPointer), index);
}
void jni_YGNodeCalculateLayout(alias_ref<jobject>,
jlong nativePointer,
jfloat width,
jfloat height) {
void jni_YGNodeRemoveChild(
alias_ref<jobject>,
jlong nativePointer,
jlong childPointer) {
YGNodeRemoveChild(
_jlong2YGNodeRef(nativePointer), _jlong2YGNodeRef(childPointer));
}
void jni_YGNodeCalculateLayout(
alias_ref<jobject>,
jlong nativePointer,
jfloat width,
jfloat height) {
const YGNodeRef root = _jlong2YGNodeRef(nativePointer);
YGNodeCalculateLayout(root,
static_cast<float>(width),
static_cast<float>(height),
YGNodeStyleGetDirection(_jlong2YGNodeRef(nativePointer)));
YGNodeCalculateLayout(
root,
static_cast<float>(width),
static_cast<float>(height),
YGNodeStyleGetDirection(_jlong2YGNodeRef(nativePointer)));
YGTransferLayoutOutputsRecursive(root);
}
@@ -313,20 +404,28 @@ jboolean jni_YGNodeIsDirty(alias_ref<jobject>, jlong nativePointer) {
return (jboolean)_jlong2YGNodeRef(nativePointer)->isDirty();
}
void jni_YGNodeSetHasMeasureFunc(alias_ref<jobject>, jlong nativePointer, jboolean hasMeasureFunc) {
void jni_YGNodeSetHasMeasureFunc(
alias_ref<jobject>,
jlong nativePointer,
jboolean hasMeasureFunc) {
_jlong2YGNodeRef(nativePointer)
->setMeasureFunc(hasMeasureFunc ? YGJNIMeasureFunc : nullptr);
}
void jni_YGNodeSetHasBaselineFunc(alias_ref<jobject>,
jlong nativePointer,
jboolean hasBaselineFunc) {
void jni_YGNodeSetHasBaselineFunc(
alias_ref<jobject>,
jlong nativePointer,
jboolean hasBaselineFunc) {
_jlong2YGNodeRef(nativePointer)
->setBaseLineFunc(hasBaselineFunc ? YGJNIBaselineFunc : nullptr);
}
void jni_YGNodeCopyStyle(alias_ref<jobject>, jlong dstNativePointer, jlong srcNativePointer) {
YGNodeCopyStyle(_jlong2YGNodeRef(dstNativePointer), _jlong2YGNodeRef(srcNativePointer));
void jni_YGNodeCopyStyle(
alias_ref<jobject>,
jlong dstNativePointer,
jlong srcNativePointer) {
YGNodeCopyStyle(
_jlong2YGNodeRef(dstNativePointer), _jlong2YGNodeRef(srcNativePointer));
}
struct JYogaValue : public JavaClass<JYogaValue> {
@@ -348,67 +447,76 @@ struct JYogaValue : public JavaClass<JYogaValue> {
_jlong2YGNodeRef(nativePointer), static_cast<type>(value)); \
}
#define YG_NODE_JNI_STYLE_UNIT_PROP(name) \
local_ref<jobject> jni_YGNodeStyleGet##name(alias_ref<jobject>, jlong nativePointer) { \
return JYogaValue::create(YGNodeStyleGet##name(_jlong2YGNodeRef(nativePointer))); \
} \
\
void jni_YGNodeStyleSet##name(alias_ref<jobject>, jlong nativePointer, jfloat value) { \
YGNodeStyleSet##name(_jlong2YGNodeRef(nativePointer), static_cast<float>(value)); \
} \
\
void jni_YGNodeStyleSet##name##Percent(alias_ref<jobject>, jlong nativePointer, jfloat value) { \
YGNodeStyleSet##name##Percent(_jlong2YGNodeRef(nativePointer), static_cast<float>(value)); \
#define YG_NODE_JNI_STYLE_UNIT_PROP(name) \
local_ref<jobject> jni_YGNodeStyleGet##name( \
alias_ref<jobject>, jlong nativePointer) { \
return JYogaValue::create( \
YGNodeStyleGet##name(_jlong2YGNodeRef(nativePointer))); \
} \
\
void jni_YGNodeStyleSet##name( \
alias_ref<jobject>, jlong nativePointer, jfloat value) { \
YGNodeStyleSet##name( \
_jlong2YGNodeRef(nativePointer), static_cast<float>(value)); \
} \
\
void jni_YGNodeStyleSet##name##Percent( \
alias_ref<jobject>, jlong nativePointer, jfloat value) { \
YGNodeStyleSet##name##Percent( \
_jlong2YGNodeRef(nativePointer), static_cast<float>(value)); \
}
#define YG_NODE_JNI_STYLE_UNIT_PROP_AUTO(name) \
YG_NODE_JNI_STYLE_UNIT_PROP(name) \
void jni_YGNodeStyleSet##name##Auto(alias_ref<jobject>, jlong nativePointer) { \
YGNodeStyleSet##name##Auto(_jlong2YGNodeRef(nativePointer)); \
#define YG_NODE_JNI_STYLE_UNIT_PROP_AUTO(name) \
YG_NODE_JNI_STYLE_UNIT_PROP(name) \
void jni_YGNodeStyleSet##name##Auto( \
alias_ref<jobject>, jlong nativePointer) { \
YGNodeStyleSet##name##Auto(_jlong2YGNodeRef(nativePointer)); \
}
#define YG_NODE_JNI_STYLE_EDGE_PROP(javatype, type, name) \
javatype jni_YGNodeStyleGet##name(alias_ref<jobject>, jlong nativePointer, jint edge) { \
return (javatype) YGNodeStyleGet##name(_jlong2YGNodeRef(nativePointer), \
static_cast<YGEdge>(edge)); \
} \
\
void jni_YGNodeStyleSet##name(alias_ref<jobject>, \
jlong nativePointer, \
jint edge, \
javatype value) { \
YGNodeStyleSet##name(_jlong2YGNodeRef(nativePointer), \
static_cast<YGEdge>(edge), \
static_cast<type>(value)); \
#define YG_NODE_JNI_STYLE_EDGE_PROP(javatype, type, name) \
javatype jni_YGNodeStyleGet##name( \
alias_ref<jobject>, jlong nativePointer, jint edge) { \
return (javatype)YGNodeStyleGet##name( \
_jlong2YGNodeRef(nativePointer), static_cast<YGEdge>(edge)); \
} \
\
void jni_YGNodeStyleSet##name( \
alias_ref<jobject>, jlong nativePointer, jint edge, javatype value) { \
YGNodeStyleSet##name( \
_jlong2YGNodeRef(nativePointer), \
static_cast<YGEdge>(edge), \
static_cast<type>(value)); \
}
#define YG_NODE_JNI_STYLE_EDGE_UNIT_PROP(name) \
local_ref<jobject> jni_YGNodeStyleGet##name(alias_ref<jobject>, \
jlong nativePointer, \
jint edge) { \
return JYogaValue::create( \
YGNodeStyleGet##name(_jlong2YGNodeRef(nativePointer), static_cast<YGEdge>(edge))); \
} \
\
void jni_YGNodeStyleSet##name(alias_ref<jobject>, jlong nativePointer, jint edge, jfloat value) { \
YGNodeStyleSet##name(_jlong2YGNodeRef(nativePointer), \
static_cast<YGEdge>(edge), \
static_cast<float>(value)); \
} \
\
void jni_YGNodeStyleSet##name##Percent(alias_ref<jobject>, \
jlong nativePointer, \
jint edge, \
jfloat value) { \
YGNodeStyleSet##name##Percent(_jlong2YGNodeRef(nativePointer), \
static_cast<YGEdge>(edge), \
static_cast<float>(value)); \
#define YG_NODE_JNI_STYLE_EDGE_UNIT_PROP(name) \
local_ref<jobject> jni_YGNodeStyleGet##name( \
alias_ref<jobject>, jlong nativePointer, jint edge) { \
return JYogaValue::create(YGNodeStyleGet##name( \
_jlong2YGNodeRef(nativePointer), static_cast<YGEdge>(edge))); \
} \
\
void jni_YGNodeStyleSet##name( \
alias_ref<jobject>, jlong nativePointer, jint edge, jfloat value) { \
YGNodeStyleSet##name( \
_jlong2YGNodeRef(nativePointer), \
static_cast<YGEdge>(edge), \
static_cast<float>(value)); \
} \
\
void jni_YGNodeStyleSet##name##Percent( \
alias_ref<jobject>, jlong nativePointer, jint edge, jfloat value) { \
YGNodeStyleSet##name##Percent( \
_jlong2YGNodeRef(nativePointer), \
static_cast<YGEdge>(edge), \
static_cast<float>(value)); \
}
#define YG_NODE_JNI_STYLE_EDGE_UNIT_PROP_AUTO(name) \
YG_NODE_JNI_STYLE_EDGE_UNIT_PROP(name) \
void jni_YGNodeStyleSet##name##Auto(alias_ref<jobject>, jlong nativePointer, jint edge) { \
YGNodeStyleSet##name##Auto(_jlong2YGNodeRef(nativePointer), static_cast<YGEdge>(edge)); \
#define YG_NODE_JNI_STYLE_EDGE_UNIT_PROP_AUTO(name) \
YG_NODE_JNI_STYLE_EDGE_UNIT_PROP(name) \
void jni_YGNodeStyleSet##name##Auto( \
alias_ref<jobject>, jlong nativePointer, jint edge) { \
YGNodeStyleSet##name##Auto( \
_jlong2YGNodeRef(nativePointer), static_cast<YGEdge>(edge)); \
}
YG_NODE_JNI_STYLE_PROP(jint, YGDirection, Direction);
@@ -422,8 +530,12 @@ YG_NODE_JNI_STYLE_PROP(jint, YGWrap, FlexWrap);
YG_NODE_JNI_STYLE_PROP(jint, YGOverflow, Overflow);
YG_NODE_JNI_STYLE_PROP(jint, YGDisplay, Display);
void jni_YGNodeStyleSetFlex(alias_ref<jobject>, jlong nativePointer, jfloat value) {
YGNodeStyleSetFlex(_jlong2YGNodeRef(nativePointer), static_cast<float>(value));
void jni_YGNodeStyleSetFlex(
alias_ref<jobject>,
jlong nativePointer,
jfloat value) {
YGNodeStyleSetFlex(
_jlong2YGNodeRef(nativePointer), static_cast<float>(value));
}
YG_NODE_JNI_STYLE_PROP(jfloat, float, FlexGrow);
YG_NODE_JNI_STYLE_PROP(jfloat, float, FlexShrink);
@@ -457,41 +569,52 @@ void jni_YGConfigFree(alias_ref<jobject>, jlong nativePointer) {
YGConfigFree(config);
}
void jni_YGConfigSetExperimentalFeatureEnabled(alias_ref<jobject>,
jlong nativePointer,
jint feature,
jboolean enabled) {
void jni_YGConfigSetExperimentalFeatureEnabled(
alias_ref<jobject>,
jlong nativePointer,
jint feature,
jboolean enabled) {
const YGConfigRef config = _jlong2YGConfigRef(nativePointer);
YGConfigSetExperimentalFeatureEnabled(config,
static_cast<YGExperimentalFeature>(feature),
enabled);
YGConfigSetExperimentalFeatureEnabled(
config, static_cast<YGExperimentalFeature>(feature), enabled);
}
void jni_YGConfigSetUseWebDefaults(alias_ref<jobject>,
jlong nativePointer,
jboolean useWebDefaults) {
void jni_YGConfigSetShouldDiffLayoutWithoutLegacyStretchBehaviour(
alias_ref<jobject>,
jlong nativePointer,
jboolean enabled) {
const YGConfigRef config = _jlong2YGConfigRef(nativePointer);
YGConfigSetShouldDiffLayoutWithoutLegacyStretchBehaviour(config, enabled);
}
void jni_YGConfigSetUseWebDefaults(
alias_ref<jobject>,
jlong nativePointer,
jboolean useWebDefaults) {
const YGConfigRef config = _jlong2YGConfigRef(nativePointer);
YGConfigSetUseWebDefaults(config, useWebDefaults);
}
void jni_YGConfigSetPointScaleFactor(alias_ref<jobject>,
jlong nativePointer,
jfloat pixelsInPoint) {
void jni_YGConfigSetPointScaleFactor(
alias_ref<jobject>,
jlong nativePointer,
jfloat pixelsInPoint) {
const YGConfigRef config = _jlong2YGConfigRef(nativePointer);
YGConfigSetPointScaleFactor(config, pixelsInPoint);
}
void jni_YGConfigSetUseLegacyStretchBehaviour(alias_ref<jobject>,
jlong nativePointer,
jboolean useLegacyStretchBehaviour) {
void jni_YGConfigSetUseLegacyStretchBehaviour(
alias_ref<jobject>,
jlong nativePointer,
jboolean useLegacyStretchBehaviour) {
const YGConfigRef config = _jlong2YGConfigRef(nativePointer);
YGConfigSetUseLegacyStretchBehaviour(config, useLegacyStretchBehaviour);
}
void jni_YGConfigSetHasNodeClonedFunc(
void jni_YGConfigSetHasCloneNodeFunc(
alias_ref<jobject> thiz,
jlong nativePointer,
jboolean hasNodeClonedFunc) {
jboolean hasCloneNodeFunc) {
const YGConfigRef config = _jlong2YGConfigRef(nativePointer);
auto context = reinterpret_cast<YGConfigContext*>(YGConfigGetContext(config));
if (context && context->config) {
@@ -499,15 +622,15 @@ void jni_YGConfigSetHasNodeClonedFunc(
context->config = nullptr;
}
if (hasNodeClonedFunc) {
if (hasCloneNodeFunc) {
if (!context) {
context = new YGConfigContext();
YGConfigSetContext(config, context);
}
context->config = new global_ref<jobject>(make_global(thiz));
YGConfigSetNodeClonedFunc(config, YGJNIOnNodeClonedFunc);
YGConfigSetCloneNodeFunc(config, YGJNIOnNodeClonedFunc);
} else {
YGConfigSetNodeClonedFunc(config, nullptr);
YGConfigSetCloneNodeFunc(config, nullptr);
}
}
@@ -540,7 +663,7 @@ jint jni_YGNodeGetInstanceCount(alias_ref<jclass> clazz) {
#define YGMakeNativeMethod(name) makeNativeMethod(#name, name)
jint JNI_OnLoad(JavaVM *vm, void *) {
jint JNI_OnLoad(JavaVM* vm, void*) {
return initialize(vm, [] {
registerNatives(
"com/facebook/yoga/YogaNode",
@@ -549,7 +672,9 @@ jint JNI_OnLoad(JavaVM *vm, void *) {
YGMakeNativeMethod(jni_YGNodeNewWithConfig),
YGMakeNativeMethod(jni_YGNodeFree),
YGMakeNativeMethod(jni_YGNodeReset),
YGMakeNativeMethod(jni_YGNodeClearChildren),
YGMakeNativeMethod(jni_YGNodeInsertChild),
YGMakeNativeMethod(jni_YGNodeInsertSharedChild),
YGMakeNativeMethod(jni_YGNodeRemoveChild),
YGMakeNativeMethod(jni_YGNodeCalculateLayout),
YGMakeNativeMethod(jni_YGNodeMarkDirty),
@@ -623,17 +748,21 @@ jint JNI_OnLoad(JavaVM *vm, void *) {
YGMakeNativeMethod(jni_YGNodeGetInstanceCount),
YGMakeNativeMethod(jni_YGNodePrint),
YGMakeNativeMethod(jni_YGNodeClone),
YGMakeNativeMethod(jni_YGNodeSetOwner),
});
registerNatives(
"com/facebook/yoga/YogaConfig",
{
YGMakeNativeMethod(jni_YGConfigNew),
YGMakeNativeMethod(jni_YGConfigFree),
YGMakeNativeMethod(jni_YGConfigSetExperimentalFeatureEnabled),
YGMakeNativeMethod(jni_YGConfigSetUseWebDefaults),
YGMakeNativeMethod(jni_YGConfigSetPointScaleFactor),
YGMakeNativeMethod(jni_YGConfigSetUseLegacyStretchBehaviour),
YGMakeNativeMethod(jni_YGConfigSetLogger),
YGMakeNativeMethod(jni_YGConfigSetHasCloneNodeFunc),
YGMakeNativeMethod(
jni_YGConfigSetShouldDiffLayoutWithoutLegacyStretchBehaviour),
});
registerNatives("com/facebook/yoga/YogaConfig",
{
YGMakeNativeMethod(jni_YGConfigNew),
YGMakeNativeMethod(jni_YGConfigFree),
YGMakeNativeMethod(jni_YGConfigSetExperimentalFeatureEnabled),
YGMakeNativeMethod(jni_YGConfigSetUseWebDefaults),
YGMakeNativeMethod(jni_YGConfigSetPointScaleFactor),
YGMakeNativeMethod(jni_YGConfigSetUseLegacyStretchBehaviour),
YGMakeNativeMethod(jni_YGConfigSetLogger),
YGMakeNativeMethod(jni_YGConfigSetHasNodeClonedFunc),
});
});
}

View File

@@ -3,9 +3,9 @@
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
load("//:yoga_defs.bzl", "YOGA_ROOTS", "java_library")
load("//:yoga_defs.bzl", "YOGA_ROOTS", "yoga_java_library")
java_library(
yoga_java_library(
name = "annotations",
srcs = glob(["*.java"]),
source = "1.7",

View File

@@ -8,7 +8,9 @@
package com.facebook.yoga;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@@ -109,21 +111,23 @@ public class YogaNodeTest {
}
@Test
public void testMeasureFloatMax() {
public void testMeasureFloatBigNumber() {
final YogaNode node = new YogaNode();
node.setMeasureFunction(new YogaMeasureFunction() {
public long measure(
YogaNode node,
float width,
YogaMeasureMode widthMode,
float height,
YogaMeasureMode heightMode) {
return YogaMeasureOutput.make(Float.MAX_VALUE, Float.MAX_VALUE);
}
});
final float bigNumber = (float) 10E5;
node.setMeasureFunction(
new YogaMeasureFunction() {
public long measure(
YogaNode node,
float width,
YogaMeasureMode widthMode,
float height,
YogaMeasureMode heightMode) {
return YogaMeasureOutput.make(bigNumber, bigNumber);
}
});
node.calculateLayout(YogaConstants.UNDEFINED, YogaConstants.UNDEFINED);
assertEquals(Float.MAX_VALUE, node.getLayoutWidth(), 0.01f);
assertEquals(Float.MAX_VALUE, node.getLayoutHeight(), 0.01f);
assertEquals(bigNumber, node.getLayoutWidth(), 0.01f);
assertEquals(bigNumber, node.getLayoutHeight(), 0.01f);
}
@Test
@@ -248,16 +252,58 @@ public class YogaNodeTest {
assertEquals(1, clonedChild.getChildCount());
}
@Test
public void testCloneWithNewChildren() throws Exception {
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
YogaNode child = new YogaNode(config);
YogaNode grandChild = new YogaNode(config);
root.addChildAt(child, 0);
child.addChildAt(grandChild, 0);
child.setFlexDirection(YogaFlexDirection.ROW);
YogaNode clonedChild = child.cloneWithNewChildren();
assertNotSame(clonedChild, child);
assertEquals(YogaFlexDirection.ROW, clonedChild.getFlexDirection());
assertEquals(child.getFlexDirection(), clonedChild.getFlexDirection());
assertEquals(0, clonedChild.getChildCount());
assertEquals(1, child.getChildCount());
}
@Test
public void testAddSharedChildCloneWithNewChildren() throws Exception {
YogaConfig config = new YogaConfig();
YogaNode root = new YogaNode(config);
YogaNode child = new YogaNode(config);
YogaNode grandChild = new YogaNode(config);
root.addChildAt(child, 0);
child.addChildAt(grandChild, 0);
child.setFlexDirection(YogaFlexDirection.ROW);
YogaNode clonedChild = child.cloneWithNewChildren();
assertNotSame(clonedChild, child);
assertEquals(YogaFlexDirection.ROW, clonedChild.getFlexDirection());
assertEquals(child.getFlexDirection(), clonedChild.getFlexDirection());
assertEquals(0, clonedChild.getChildCount());
assertEquals(1, child.getChildCount());
clonedChild.addSharedChildAt(grandChild, 0);
assertEquals(1, clonedChild.getChildCount());
assertNull(grandChild.getOwner());
}
@Test
public void testCloneNodeListener() throws Exception {
final AtomicBoolean onNodeClonedExecuted = new AtomicBoolean(false);
YogaConfig config = new YogaConfig();
config.setOnNodeCloned(
new YogaNodeClonedFunction() {
config.setOnCloneNode(
new YogaNodeCloneFunction() {
@Override
public void onNodeCloned(
YogaNode oldNode, YogaNode newNode, YogaNode parent, int childIndex) {
public YogaNode cloneNode(YogaNode oldNode, YogaNode owner, int childIndex) {
onNodeClonedExecuted.set(true);
return oldNode.clone();
}
});
YogaNode root = new YogaNode(config);
@@ -265,6 +311,7 @@ public class YogaNodeTest {
root.setHeight(100f);
YogaNode child0 = new YogaNode(config);
root.addChildAt(child0, 0);
child0.setWidth(50f);
root.calculateLayout(YogaConstants.UNDEFINED, YogaConstants.UNDEFINED);
// Force a clone to happen.
@@ -273,20 +320,24 @@ public class YogaNodeTest {
root2.calculateLayout(YogaConstants.UNDEFINED, YogaConstants.UNDEFINED);
assertTrue(onNodeClonedExecuted.get());
assertEquals(1, root2.getChildCount());
YogaNode clonedNode = root2.getChildAt(0);
assertNotSame(child0, clonedNode);
assertEquals(child0.getWidth(), clonedNode.getWidth());
assertEquals(50f, clonedNode.getWidth().value, 0.01f);
}
@Test
public void testOnNodeClonedLeak() throws Exception {
YogaConfig config = new YogaConfig();
config.setOnNodeCloned(
new YogaNodeClonedFunction() {
config.setOnCloneNode(
new YogaNodeCloneFunction() {
@Override
public void onNodeCloned(
YogaNode oldNode, YogaNode newNode, YogaNode parent, int childIndex) {
// Do nothing
public YogaNode cloneNode(YogaNode oldNode, YogaNode owner, int childIndex) {
return oldNode.clone();
}
});
config.setOnNodeCloned(null);
config.setOnCloneNode(null);
WeakReference<Object> ref = new WeakReference<Object>(config);
// noinspection UnusedAssignment
config = null;
@@ -302,4 +353,27 @@ public class YogaNodeTest {
}
fail("YogaConfig leaked");
}
@Test
public void testFlagShouldDiffLayoutWithoutLegacyStretchBehaviour() throws Exception {
YogaConfig config = new YogaConfig();
config.setShouldDiffLayoutWithoutLegacyStretchBehaviour(true);
config.setUseLegacyStretchBehaviour(true);
YogaNode root = new YogaNode(config);
root.setWidth(500);
root.setHeight(500);
YogaNode root_child0 = new YogaNode(config);
root_child0.setAlignItems(YogaAlign.FLEX_START);
root.addChildAt(root_child0, 0);
YogaNode root_child0_child0 = new YogaNode(config);
root_child0_child0.setFlexGrow(1);
root_child0_child0.setFlexShrink(1);
root_child0.addChildAt(root_child0_child0, 0);
YogaNode root_child0_child0_child0 = new YogaNode(config);
root_child0_child0_child0.setFlexGrow(1);
root_child0_child0_child0.setFlexShrink(1);
root_child0_child0.addChildAt(root_child0_child0_child0, 0);
root.calculateLayout(YogaConstants.UNDEFINED, YogaConstants.UNDEFINED);
assertFalse(root.getDoesLegacyStretchFlagAffectsLayout());
}
}

View File

@@ -61,7 +61,7 @@ for (let [name, results] of testResults) {
for (let [type, result] of results) {
console.log(
` - ${type}: ${result}ms (${Math.round(result / min * 10000) / 100}%)`,
` - ${type}: ${result}ms (${Math.round((result / min) * 10000) / 100}%)`,
);
}
}

View File

@@ -3,9 +3,9 @@
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
load("//:yoga_defs.bzl", "YOGA_ROOTS", "prebuilt_jar")
load("//:yoga_defs.bzl", "YOGA_ROOTS", "yoga_prebuilt_jar")
prebuilt_jar(
yoga_prebuilt_jar(
name = "android-support",
binary_jar = "android-support-v4.jar",
visibility = YOGA_ROOTS,

View File

@@ -2,10 +2,9 @@
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
load("//:yoga_defs.bzl", "ANDROID", "FBJNI_JAVA_TARGET", "JNI_TARGET", "YOGA_ROOTS", "subdir_glob", "yoga_cxx_library", "yoga_prebuilt_cxx_library")
include_defs("//yoga_defs.bzl")
prebuilt_cxx_library(
yoga_prebuilt_cxx_library(
name = "ndklog",
exported_platform_linker_flags = [
(
@@ -17,7 +16,7 @@ prebuilt_cxx_library(
visibility = YOGA_ROOTS,
)
cxx_library(
yoga_cxx_library(
name = "fbjni",
srcs = glob(["src/main/cpp/**/*.cpp"]),
header_namespace = "",
@@ -35,6 +34,7 @@ cxx_library(
"-Wno-unused-parameter",
"-std=c++11",
],
platforms = (ANDROID,),
visibility = ["PUBLIC"],
deps = [
":ndklog",

View File

@@ -3,9 +3,9 @@
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
load("//:yoga_defs.bzl", "PROGRUARD_ANNOTATIONS_TARGET", "SOLOADER_TARGET", "JSR_305_TARGET", "java_library")
load("//:yoga_defs.bzl", "JSR_305_TARGET", "PROGRUARD_ANNOTATIONS_TARGET", "SOLOADER_TARGET", "yoga_java_library")
java_library(
yoga_java_library(
name = "jni",
srcs = glob(["**/*.java"]),
proguard_config = "fbjni.pro",

View File

@@ -2,15 +2,14 @@
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
load("//:yoga_defs.bzl", "cxx_library", "YOGA_ROOTS")
load("//:yoga_defs.bzl", "YOGA_ROOTS", "subdir_glob", "yoga_cxx_library")
COMPILER_FLAGS = [
"-std=c++11",
"-Wno-missing-prototypes",
]
cxx_library(
yoga_cxx_library(
name = "gtest",
srcs = glob(["googletest/googletest/src/*.cc"]),
header_namespace = "",

View File

@@ -3,17 +3,17 @@
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
load("//:yoga_defs.bzl", "YOGA_ROOTS", "prebuilt_jar", "java_library")
load("//:yoga_defs.bzl", "YOGA_ROOTS", "yoga_java_library", "yoga_prebuilt_jar")
prebuilt_jar(
yoga_prebuilt_jar(
name = "infer-annotations-jar",
binary_jar = "infer-annotations-1.4.jar",
)
java_library(
yoga_java_library(
name = "infer-annotations",
visibility = YOGA_ROOTS,
exported_deps = [
":infer-annotations-jar",
],
visibility = YOGA_ROOTS,
)

View File

@@ -3,9 +3,9 @@
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
load("//:yoga_defs.bzl", "cxx_library")
load("//:yoga_defs.bzl", "yoga_cxx_library")
cxx_library(
yoga_cxx_library(
name = "jni",
header_namespace = "",
exported_headers = [

View File

@@ -3,17 +3,17 @@
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
load("//:yoga_defs.bzl", "YOGA_ROOTS", "prebuilt_jar", "java_library")
load("//:yoga_defs.bzl", "YOGA_ROOTS", "yoga_java_library", "yoga_prebuilt_jar")
prebuilt_jar(
yoga_prebuilt_jar(
name = "jsr305-jar",
binary_jar = "jsr305.jar",
)
java_library(
yoga_java_library(
name = "jsr-305",
visibility = YOGA_ROOTS,
exported_deps = [
":jsr305-jar",
],
visibility = YOGA_ROOTS,
)

View File

@@ -3,17 +3,17 @@
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
load("//:yoga_defs.bzl", "YOGA_ROOTS", "prebuilt_jar", "java_library")
load("//:yoga_defs.bzl", "YOGA_ROOTS", "yoga_java_library", "yoga_prebuilt_jar")
prebuilt_jar(
yoga_prebuilt_jar(
name = "junit-jar",
binary_jar = "junit4.jar",
)
java_library(
yoga_java_library(
name = "junit",
visibility = YOGA_ROOTS,
exported_deps = [
":junit-jar",
],
visibility = YOGA_ROOTS,
)

View File

@@ -1,7 +1,8 @@
set -e
function download() {
echo "Downloading '$1' to '$2' ..."
if hash curl 2>/dev/null; then
curl --retry 10 -L -o "$2" "$1"
curl -s -L -o "$2" "$1"
elif hash wget 2>/dev/null; then
wget -O "$2" "$1"
else
@@ -12,38 +13,38 @@ function download() {
function installsdk() {
PROXY_ARGS=""
if [[ ! -z "$https_proxy" ]]; then
PROXY_HOST="$(cut -d : "$https_proxy" -f 1,1)"
PROXY_PORT="$(cut -d : "$https_proxy" -f 2,2)"
if [[ ! -z "$HTTPS_PROXY" ]]; then
PROXY_HOST="$(echo $HTTPS_PROXY | cut -d : -f 1,1)"
PROXY_PORT="$(echo $HTTPS_PROXY | cut -d : -f 2,2)"
PROXY_ARGS="--proxy=http --proxy_host=$PROXY_HOST --proxy_port=$PROXY_PORT"
fi
yes | "$ANDROID_HOME/tools/bin/sdkmanager" $PROXY_ARGS $@
echo y | "$ANDROID_HOME"/tools/bin/sdkmanager $PROXY_ARGS "$@"
}
function installAndroidSDK {
export ANDROID_HOME=$HOME/android-sdk
export ANDROID_NDK_REPOSITORY=$HOME/android-ndk
export PATH="$ANDROID_HOME/platform-tools:$ANDROID_HOME/tools:$ANDROID_HOME/tools/bin:$PATH"
if [[ ! -f "$ANDROID_HOME/tools/bin/sdkmanager" ]]; then
if [[ ! -d "$HOME/android-sdk" ]]; then
TMP=/tmp/sdk$$.zip
download 'https://dl.google.com/android/repository/sdk-tools-darwin-3859397.zip' $TMP
unzip -qod "$ANDROID_HOME" "$TMP"
download 'https://dl.google.com/android/repository/tools_r25.2.3-linux.zip' $TMP
unzip -qod "$HOME/android-sdk" $TMP
rm $TMP
fi
export ANDROID_NDK_REPOSITORY=$HOME/android-ndk
if [[ ! -d "$ANDROID_NDK_REPOSITORY/android-ndk-r15c" ]]; then
TMP=/tmp/ndk$$.zip
mkdir -p "$ANDROID_NDK_REPOSITORY"
download 'https://dl.google.com/android/repository/android-ndk-r15c-darwin-x86_64.zip' $TMP
download 'https://dl.google.com/android/repository/android-ndk-r15c-linux-x86_64.zip' $TMP
unzip -qod "$ANDROID_NDK_REPOSITORY" "$TMP"
rm $TMP
fi
mkdir -p "$ANDROID_HOME/licenses/"
echo > "$ANDROID_HOME/licenses/android-sdk-license"
echo -n d56f5187479451eabf01fb78af6dfcb131a6481e >> "$ANDROID_HOME/licenses/android-sdk-license"
export ANDROID_HOME=$HOME/android-sdk
export PATH="$ANDROID_HOME/platform-tools:$ANDROID_HOME/tools:$ANDROID_HOME/tools/bin:$PATH"
installsdk 'build-tools;26.0.2' 'platform-tools' 'platforms;android-23' 'platforms;android-25' 'extras;android;m2repository'
mkdir -p $ANDROID_HOME/licenses/
echo > $ANDROID_HOME/licenses/android-sdk-license
echo -n d56f5187479451eabf01fb78af6dfcb131a6481e > $ANDROID_HOME/licenses/android-sdk-license
installsdk 'build-tools;25.0.3' 'build-tools;26.0.2' 'platforms;android-25' 'platforms;android-26' 'ndk-bundle' 'extras;android;m2repository'
}

View File

@@ -1,10 +1,10 @@
/**
* Copyright (c) 2014-present, Facebook, Inc.
/*
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// @Generated by gentest/gentest.rb from gentest/fixtures/YGFlexTest.html
#include <gtest/gtest.h>
@@ -64,6 +64,90 @@ TEST(YogaTest, flex_basis_flex_grow_column) {
YGConfigFree(config);
}
TEST(YogaTest, flex_shrink_flex_grow_row) {
const YGConfigRef config = YGConfigNew();
const YGNodeRef root = YGNodeNewWithConfig(config);
YGNodeStyleSetFlexDirection(root, YGFlexDirectionRow);
YGNodeStyleSetWidth(root, 500);
YGNodeStyleSetHeight(root, 500);
const YGNodeRef root_child0 = YGNodeNewWithConfig(config);
YGNodeStyleSetFlexGrow(root_child0, 0);
YGNodeStyleSetFlexShrink(root_child0, 1);
YGNodeStyleSetWidth(root_child0, 500);
YGNodeStyleSetHeight(root_child0, 100);
YGNodeInsertChild(root, root_child0, 0);
const YGNodeRef root_child1 = YGNodeNewWithConfig(config);
YGNodeStyleSetFlexGrow(root_child1, 0);
YGNodeStyleSetFlexShrink(root_child1, 1);
YGNodeStyleSetWidth(root_child1, 500);
YGNodeStyleSetHeight(root_child1, 100);
YGNodeInsertChild(root, root_child1, 1);
YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionLTR);
ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root));
ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root));
ASSERT_FLOAT_EQ(500, YGNodeLayoutGetWidth(root));
ASSERT_FLOAT_EQ(500, YGNodeLayoutGetHeight(root));
ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root_child0));
ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root_child0));
ASSERT_FLOAT_EQ(250, YGNodeLayoutGetWidth(root_child0));
ASSERT_FLOAT_EQ(100, YGNodeLayoutGetHeight(root_child0));
ASSERT_FLOAT_EQ(250, YGNodeLayoutGetLeft(root_child1));
ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root_child1));
ASSERT_FLOAT_EQ(250, YGNodeLayoutGetWidth(root_child1));
ASSERT_FLOAT_EQ(100, YGNodeLayoutGetHeight(root_child1));
YGNodeFreeRecursive(root);
YGConfigFree(config);
}
TEST(YogaTest, flex_shrink_flex_grow_child_flex_shrink_other_child) {
const YGConfigRef config = YGConfigNew();
const YGNodeRef root = YGNodeNewWithConfig(config);
YGNodeStyleSetFlexDirection(root, YGFlexDirectionRow);
YGNodeStyleSetWidth(root, 500);
YGNodeStyleSetHeight(root, 500);
const YGNodeRef root_child0 = YGNodeNewWithConfig(config);
YGNodeStyleSetFlexGrow(root_child0, 0);
YGNodeStyleSetFlexShrink(root_child0, 1);
YGNodeStyleSetWidth(root_child0, 500);
YGNodeStyleSetHeight(root_child0, 100);
YGNodeInsertChild(root, root_child0, 0);
const YGNodeRef root_child1 = YGNodeNewWithConfig(config);
YGNodeStyleSetFlexGrow(root_child1, 1);
YGNodeStyleSetFlexShrink(root_child1, 1);
YGNodeStyleSetWidth(root_child1, 500);
YGNodeStyleSetHeight(root_child1, 100);
YGNodeInsertChild(root, root_child1, 1);
YGNodeCalculateLayout(root, YGUndefined, YGUndefined, YGDirectionLTR);
ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root));
ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root));
ASSERT_FLOAT_EQ(500, YGNodeLayoutGetWidth(root));
ASSERT_FLOAT_EQ(500, YGNodeLayoutGetHeight(root));
ASSERT_FLOAT_EQ(0, YGNodeLayoutGetLeft(root_child0));
ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root_child0));
ASSERT_FLOAT_EQ(250, YGNodeLayoutGetWidth(root_child0));
ASSERT_FLOAT_EQ(100, YGNodeLayoutGetHeight(root_child0));
ASSERT_FLOAT_EQ(250, YGNodeLayoutGetLeft(root_child1));
ASSERT_FLOAT_EQ(0, YGNodeLayoutGetTop(root_child1));
ASSERT_FLOAT_EQ(250, YGNodeLayoutGetWidth(root_child1));
ASSERT_FLOAT_EQ(100, YGNodeLayoutGetHeight(root_child1));
YGNodeFreeRecursive(root);
YGConfigFree(config);
}
TEST(YogaTest, flex_basis_flex_grow_row) {
const YGConfigRef config = YGConfigNew();

View File

@@ -1,10 +1,10 @@
/**
* Copyright (c) 2014-present, Facebook, Inc.
/*
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <gtest/gtest.h>
#include <yoga/YGNode.h>
#include <yoga/Yoga.h>

View File

@@ -5,8 +5,6 @@
* LICENSE file in the root directory of this source tree.
*/
// @Generated by gentest/gentest.rb from gentest/fixtures/YGPercentageTest.html
#include <gtest/gtest.h>
#include <yoga/Yoga.h>

View File

@@ -57,3 +57,26 @@ TEST(YogaTest, copy_style_modified_same) {
YGNodeFree(node0);
YGNodeFree(node1);
}
TEST(YogaTest, initialise_flexShrink_flexGrow) {
const YGNodeRef node0 = YGNodeNew();
YGNodeStyleSetFlexShrink(node0, 1);
ASSERT_EQ(1, YGNodeStyleGetFlexShrink(node0));
YGNodeStyleSetFlexShrink(node0, YGUndefined);
YGNodeStyleSetFlexGrow(node0, 3);
ASSERT_EQ(
0,
YGNodeStyleGetFlexShrink(
node0)); // Default value is Zero, if flex shrink is not defined
ASSERT_EQ(3, YGNodeStyleGetFlexGrow(node0));
YGNodeStyleSetFlexGrow(node0, YGUndefined);
YGNodeStyleSetFlexShrink(node0, 3);
ASSERT_EQ(
0,
YGNodeStyleGetFlexGrow(
node0)); // Default value is Zero, if flex grow is not defined
ASSERT_EQ(3, YGNodeStyleGetFlexShrink(node0));
YGNodeFree(node0);
}

34
tests/YGTraversalTest.cpp Normal file
View File

@@ -0,0 +1,34 @@
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <gtest/gtest.h>
#include <yoga/Yoga.h>
TEST(YogaTest, pre_order_traversal) {
YGNodeRef const root = YGNodeNew();
YGNodeRef const root_child0 = YGNodeNew();
YGNodeRef const root_child1 = YGNodeNew();
YGNodeRef const root_child0_child0 = YGNodeNew();
YGNodeSetChildren(root, {root_child0, root_child1});
YGNodeInsertChild(root_child0, root_child0_child0, 0);
std::vector<YGNodeRef> visited;
YGTraversePreOrder(root, [&visited](YGNodeRef node) {
visited.push_back(node);
});
const std::vector<YGNodeRef> expected = {
root,
root_child0,
root_child0_child0,
root_child1
};
ASSERT_EQ(visited, expected);
YGNodeFreeRecursive(root);
}

View File

@@ -0,0 +1,111 @@
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <gtest/gtest.h>
#include <yoga/Yoga.h>
static std::vector<YGNodeRef> getChildren(YGNodeRef const node)
{
const uint32_t count = YGNodeGetChildCount(node);
std::vector<YGNodeRef> children;
children.reserve(count);
for (uint32_t i = 0 ; i < count ; i++) {
children.push_back(YGNodeGetChild(node, i));
}
return children;
}
TEST(YogaTest, set_children_adds_children_to_parent) {
YGNodeRef const root = YGNodeNew();
YGNodeRef const root_child0 = YGNodeNew();
YGNodeRef const root_child1 = YGNodeNew();
YGNodeSetChildren(root, {root_child0, root_child1});
const std::vector<YGNodeRef> children = getChildren(root);
const std::vector<YGNodeRef> expectedChildren = {root_child0, root_child1};
ASSERT_EQ(children, expectedChildren);
const std::vector<YGNodeRef> owners = {YGNodeGetOwner(root_child0), YGNodeGetOwner(root_child1)};
const std::vector<YGNodeRef> expectedOwners = {root, root};
ASSERT_EQ(owners, expectedOwners);
YGNodeFreeRecursive(root);
}
TEST(YogaTest, set_children_to_empty_removes_old_children) {
YGNodeRef const root = YGNodeNew();
YGNodeRef const root_child0 = YGNodeNew();
YGNodeRef const root_child1 = YGNodeNew();
YGNodeSetChildren(root, {root_child0, root_child1});
YGNodeSetChildren(root, {});
const std::vector<YGNodeRef> children = getChildren(root);
const std::vector<YGNodeRef> expectedChildren = {};
ASSERT_EQ(children, expectedChildren);
const std::vector<YGNodeRef> owners = {YGNodeGetOwner(root_child0), YGNodeGetOwner(root_child1)};
const std::vector<YGNodeRef> expectedOwners = {nullptr, nullptr};
ASSERT_EQ(owners, expectedOwners);
YGNodeFreeRecursive(root);
}
TEST(YogaTest, set_children_replaces_non_common_children) {
YGNodeRef const root = YGNodeNew();
YGNodeRef const root_child0 = YGNodeNew();
YGNodeRef const root_child1 = YGNodeNew();
YGNodeSetChildren(root, {root_child0, root_child1});
YGNodeRef const root_child2 = YGNodeNew();
YGNodeRef const root_child3 = YGNodeNew();
YGNodeSetChildren(root, {root_child2, root_child3});
const std::vector<YGNodeRef> children = getChildren(root);
const std::vector<YGNodeRef> expectedChildren = {root_child2, root_child3};
ASSERT_EQ(children, expectedChildren);
const std::vector<YGNodeRef> owners = {YGNodeGetOwner(root_child0), YGNodeGetOwner(root_child1)};
const std::vector<YGNodeRef> expectedOwners = {nullptr, nullptr};
ASSERT_EQ(owners, expectedOwners);
YGNodeFreeRecursive(root);
YGNodeFree(root_child0);
YGNodeFree(root_child1);
}
TEST(YogaTest, set_children_keeps_and_reorders_common_children) {
YGNodeRef const root = YGNodeNew();
YGNodeRef const root_child0 = YGNodeNew();
YGNodeRef const root_child1 = YGNodeNew();
YGNodeRef const root_child2 = YGNodeNew();
YGNodeSetChildren(root, {root_child0, root_child1, root_child2});
YGNodeRef const root_child3 = YGNodeNew();
YGNodeSetChildren(root, {root_child2, root_child1, root_child3});
const std::vector<YGNodeRef> children = getChildren(root);
const std::vector<YGNodeRef> expectedChildren = {root_child2, root_child1, root_child3};
ASSERT_EQ(children, expectedChildren);
const std::vector<YGNodeRef> owners = {
YGNodeGetOwner(root_child0),
YGNodeGetOwner(root_child1),
YGNodeGetOwner(root_child2),
YGNodeGetOwner(root_child3)
};
const std::vector<YGNodeRef> expectedOwners = {nullptr, root, root, root};
ASSERT_EQ(owners, expectedOwners);
YGNodeFreeRecursive(root);
YGNodeFree(root_child0);
}

View File

@@ -18,10 +18,45 @@ dependencies {
### Javascript
The JavaScript bindings for Yoga can be used from node.js and within the browser.
When using Yoga from node.js the native library is used, in browesers a pure JS
version is used (corss-compiled using [emscripten](http://kripken.github.io/emscripten-site/)).
```
$> yarn add yoga-layout
```
This is an example on how to use Yoga in JavaScript, for a full API reference,
have a look at the [flow-type definitions](https://github.com/facebook/yoga/blob/master/javascript/sources/entry-common.js#L123).
```js
import yoga, {Node} from 'yoga-layout';
const root = Node.create();
root.setWidth(500);
root.setHeight(300);
root.setJustifyContent(yoga.JUSTIFY_CENTER);
const node1 = Node.create();
node1.setWidth(100);
node1.setHeight(100);
const node2 = Node.create();
node2.setWidth(100);
node2.setHeight(100);
root.insertChild(node1, 0);
root.insertChild(node2, 1);
root.calculateLayout(500, 300, yoga.DIRECTION_LTR);
console.log(root.getComputedLayout());
// {left: 0, top: 0, width: 500, height: 300}
console.log(node1.getComputedLayout());
// {left: 150, top: 0, width: 100, height: 100}
console.log(node2.getComputedLayout());
// {left: 250, top: 0, width: 100, height: 100}
```
### iOS
```

12381
website/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -4,21 +4,22 @@
"version": "1.0.0",
"author": "Kyle Mathews <mathews.kyle@gmail.com>",
"dependencies": {
"antd": "^3.2.0",
"atob": "^2.0.3",
"gatsby": "^1.9.158",
"gatsby-link": "^1.6.34",
"gatsby-plugin-antd": "^1.0.10",
"gatsby-plugin-google-analytics": "^1.0.19",
"gatsby-plugin-less": "^1.1.4",
"gatsby-plugin-react-helmet": "^2.0.3",
"gatsby-plugin-react-next": "^1.0.8",
"gatsby-remark-prismjs": "^1.2.14",
"gatsby-source-filesystem": "^1.5.18",
"gatsby-transformer-remark": "^1.7.31",
"antd": "^3.6.5",
"atob": "^2.1.1",
"btoa": "^1.2.1",
"gatsby": "^1.9.273",
"gatsby-link": "^1.6.45",
"gatsby-plugin-antd": "^1.0.12",
"gatsby-plugin-google-analytics": "^1.0.31",
"gatsby-plugin-less": "^1.1.8",
"gatsby-plugin-react-helmet": "^2.0.11",
"gatsby-plugin-react-next": "^1.0.11",
"gatsby-remark-prismjs": "^2.0.4",
"gatsby-source-filesystem": "^1.5.39",
"gatsby-transformer-remark": "^1.7.44",
"immutable": "^4.0.0-rc.9",
"react-helmet": "^5.2.0",
"react-syntax-highlighter": "^7.0.0",
"react-syntax-highlighter": "^8.0.0",
"yoga-layout": "^1.9.3"
},
"keywords": [
@@ -31,6 +32,6 @@
"develop": "gatsby develop"
},
"devDependencies": {
"prettier": "^1.10.2"
"prettier": "1.13.7"
}
}

View File

@@ -10,10 +10,12 @@
import React, {Component} from 'react';
export default () => <svg viewBox="0 0 1133.9 1133.9">
<g>
<path d="M 498.3 3.7 c 153.6 88.9 307.3 177.7 461.1 266.2 c 7.6 4.4 10.3 9.1 10.3 17.8 c -0.3 179.1 -0.2 358.3 0 537.4 c 0 8.1 -2.4 12.8 -9.7 17.1 c -154.5 88.9 -308.8 178.1 -462.9 267.5 c -9 5.2 -15.5 5.3 -24.6 0.1 c -153.9 -89.2 -307.9 -178 -462.1 -266.8 C 3 838.8 0 833.9 0 825.1 c 0.3 -179.1 0.2 -358.3 0 -537.4 c 0 -8.6 2.6 -13.6 10.2 -18 C 164.4 180.9 318.4 92 472.4 3 C 477 -1.5 494.3 -0.7 498.3 3.7 Z M 48.8 555.3 c 0 79.9 0.2 159.9 -0.2 239.8 c -0.1 10 3 15.6 11.7 20.6 c 137.2 78.8 274.2 157.8 411 237.3 c 9.9 5.7 17 5.7 26.8 0.1 c 137.5 -79.8 275.2 -159.2 412.9 -238.5 c 7.4 -4.3 10.5 -8.9 10.5 -17.8 c -0.3 -160.2 -0.3 -320.5 0 -480.7 c 0 -8.8 -2.8 -13.6 -10.3 -18 C 772.1 218 633.1 137.8 494.2 57.4 c -6.5 -3.8 -11.5 -4.5 -18.5 -0.5 C 336.8 137.4 197.9 217.7 58.8 297.7 c -7.7 4.4 -10.2 9.2 -10.2 17.9 C 48.9 395.5 48.8 475.4 48.8 555.3 Z" />
<path d="M 184.4 555.9 c 0 -33.3 -1 -66.7 0.3 -100 c 1.9 -48 24.1 -86 64.7 -110.9 c 54.8 -33.6 110.7 -65.5 167 -96.6 c 45.7 -25.2 92.9 -24.7 138.6 1 c 54.4 30.6 108.7 61.5 162.2 93.7 c 44 26.5 67.3 66.8 68 118.4 c 0.9 63.2 0.9 126.5 0 189.7 c -0.7 50.6 -23.4 90.7 -66.6 116.9 c -55 33.4 -110.8 65.4 -167.1 96.5 c -43.4 24 -89 24.2 -132.3 0.5 c -57.5 -31.3 -114.2 -64 -170 -98.3 c -41 -25.1 -62.9 -63.7 -64.5 -112.2 C 183.5 621.9 184.3 588.9 184.4 555.9 Z M 232.9 556.3 c 0 29.5 0.5 59.1 -0.1 88.6 c -0.8 39.2 16.9 67.1 50.2 86.2 c 51.2 29.4 102.2 59.2 153.4 88.4 c 31.4 17.9 63.6 18.3 95 0.6 c 53.7 -30.3 107.1 -61.2 160.3 -92.5 c 29.7 -17.5 45 -44.5 45.3 -78.8 c 0.6 -61.7 0.5 -123.5 0 -185.2 c -0.3 -34.4 -15.3 -61.5 -44.9 -79 C 637.7 352.6 583 320.8 527.9 290 c -27.5 -15.4 -57.2 -16.1 -84.7 -0.7 c -56.9 31.6 -113.4 64 -169.1 97.6 c -26.4 15.9 -40.7 41.3 -41.1 72.9 C 232.6 491.9 232.9 524.1 232.9 556.3 Z" />
<path d="M 484.9 424.4 c 69.8 -2.8 133.2 57.8 132.6 132 C 617 630 558.5 688.7 484.9 689.1 c -75.1 0.4 -132.6 -63.6 -132.7 -132.7 C 352.1 485 413.4 421.5 484.9 424.4 Z M 401.3 556.7 c -3.4 37.2 30.5 83.6 83 84.1 c 46.6 0.4 84.8 -37.6 84.9 -84 c 0.1 -46.6 -37.2 -84.4 -84.2 -84.6 C 432.2 472.1 397.9 518.3 401.3 556.7 Z" />
</g>
</svg>
export default () => (
<svg viewBox="0 0 1133.9 1133.9">
<g>
<path d="M 498.3 3.7 c 153.6 88.9 307.3 177.7 461.1 266.2 c 7.6 4.4 10.3 9.1 10.3 17.8 c -0.3 179.1 -0.2 358.3 0 537.4 c 0 8.1 -2.4 12.8 -9.7 17.1 c -154.5 88.9 -308.8 178.1 -462.9 267.5 c -9 5.2 -15.5 5.3 -24.6 0.1 c -153.9 -89.2 -307.9 -178 -462.1 -266.8 C 3 838.8 0 833.9 0 825.1 c 0.3 -179.1 0.2 -358.3 0 -537.4 c 0 -8.6 2.6 -13.6 10.2 -18 C 164.4 180.9 318.4 92 472.4 3 C 477 -1.5 494.3 -0.7 498.3 3.7 Z M 48.8 555.3 c 0 79.9 0.2 159.9 -0.2 239.8 c -0.1 10 3 15.6 11.7 20.6 c 137.2 78.8 274.2 157.8 411 237.3 c 9.9 5.7 17 5.7 26.8 0.1 c 137.5 -79.8 275.2 -159.2 412.9 -238.5 c 7.4 -4.3 10.5 -8.9 10.5 -17.8 c -0.3 -160.2 -0.3 -320.5 0 -480.7 c 0 -8.8 -2.8 -13.6 -10.3 -18 C 772.1 218 633.1 137.8 494.2 57.4 c -6.5 -3.8 -11.5 -4.5 -18.5 -0.5 C 336.8 137.4 197.9 217.7 58.8 297.7 c -7.7 4.4 -10.2 9.2 -10.2 17.9 C 48.9 395.5 48.8 475.4 48.8 555.3 Z" />
<path d="M 184.4 555.9 c 0 -33.3 -1 -66.7 0.3 -100 c 1.9 -48 24.1 -86 64.7 -110.9 c 54.8 -33.6 110.7 -65.5 167 -96.6 c 45.7 -25.2 92.9 -24.7 138.6 1 c 54.4 30.6 108.7 61.5 162.2 93.7 c 44 26.5 67.3 66.8 68 118.4 c 0.9 63.2 0.9 126.5 0 189.7 c -0.7 50.6 -23.4 90.7 -66.6 116.9 c -55 33.4 -110.8 65.4 -167.1 96.5 c -43.4 24 -89 24.2 -132.3 0.5 c -57.5 -31.3 -114.2 -64 -170 -98.3 c -41 -25.1 -62.9 -63.7 -64.5 -112.2 C 183.5 621.9 184.3 588.9 184.4 555.9 Z M 232.9 556.3 c 0 29.5 0.5 59.1 -0.1 88.6 c -0.8 39.2 16.9 67.1 50.2 86.2 c 51.2 29.4 102.2 59.2 153.4 88.4 c 31.4 17.9 63.6 18.3 95 0.6 c 53.7 -30.3 107.1 -61.2 160.3 -92.5 c 29.7 -17.5 45 -44.5 45.3 -78.8 c 0.6 -61.7 0.5 -123.5 0 -185.2 c -0.3 -34.4 -15.3 -61.5 -44.9 -79 C 637.7 352.6 583 320.8 527.9 290 c -27.5 -15.4 -57.2 -16.1 -84.7 -0.7 c -56.9 31.6 -113.4 64 -169.1 97.6 c -26.4 15.9 -40.7 41.3 -41.1 72.9 C 232.6 491.9 232.9 524.1 232.9 556.3 Z" />
<path d="M 484.9 424.4 c 69.8 -2.8 133.2 57.8 132.6 132 C 617 630 558.5 688.7 484.9 689.1 c -75.1 0.4 -132.6 -63.6 -132.7 -132.7 C 352.1 485 413.4 421.5 484.9 424.4 Z M 401.3 556.7 c -3.4 37.2 30.5 83.6 83 84.1 c 46.6 0.4 84.8 -37.6 84.9 -84 c 0.1 -46.6 -37.2 -84.4 -84.2 -84.6 C 432.2 472.1 397.9 518.3 401.3 556.7 Z" />
</g>
</svg>
);

View File

@@ -137,9 +137,9 @@ function getLayoutCode(
)}\n${indent}\t},`,
),
);
lines.push(indent + `}]${isRoot ? ';' : ''}`);
lines.push(indent + `}]${isRoot ? ';' : ','}`);
} else {
lines[lines.length - 1] += ']';
lines[lines.length - 1] += '],';
CKFlexboxComponentChild.forEach(key => {
let line = renderKey(node, key, indent);
if (line) {
@@ -165,7 +165,7 @@ function renderKey(node: Yoga$Node, key: string, indent: string): ?string {
);
}
['top', 'left', 'right', 'bottom'].forEach(pKey => {
['top', 'start', 'end', 'bottom'].forEach(pKey => {
if (node[key][pKey]) {
lines.push(indent + `\t.${pKey} = ${getValue(node[key][pKey])},`);
}

View File

@@ -46,7 +46,9 @@ function dipOrPercent(value) {
console.log(value);
return value === 'auto'
? 'Auto'
: typeof value === 'string' && /%$/.test(value) ? 'Percent' : 'Dip';
: typeof value === 'string' && /%$/.test(value)
? 'Percent'
: 'Dip';
}
function getValue(value) {

View File

@@ -33,7 +33,7 @@ export default (props: Props<*>) => {
type="text"
{...props}
onChange={e => props.onChange(props.property, e.target.value)}
placeholder="undefined"
placeholder={props.placeholder || 'undefined'}
onFocus={e => e.target.select()}
value={Number.isNaN(props.value) ? '' : props.value}
/>

View File

@@ -89,6 +89,7 @@ export default class Editor extends Component<Props> {
<EditValue
type="text"
property="flexBasis"
placeholder="auto"
disabled={disabled || selectedNodeIsRoot}
value={node ? node.flexBasis : undefined}
onChange={this.props.onChangeLayout}
@@ -104,6 +105,7 @@ export default class Editor extends Component<Props> {
<EditValue
type="text"
property="flexGrow"
placeholder="0"
disabled={disabled || selectedNodeIsRoot}
value={node ? node.flexGrow : undefined}
onChange={this.props.onChangeLayout}
@@ -120,6 +122,7 @@ export default class Editor extends Component<Props> {
<EditValue
type="text"
property="flexShrink"
placeholder="1"
disabled={disabled || selectedNodeIsRoot}
value={node ? node.flexShrink : undefined}
onChange={this.props.onChangeLayout}
@@ -222,6 +225,62 @@ export default class Editor extends Component<Props> {
/>
</Col>
</Row>
<h2>
Max-Width &times; Max-Height
<InfoText doclink="/docs/min-max">
Maximum dimensions of the node
</InfoText>
</h2>
<Row gutter={15}>
<Col span={12}>
<EditValue
type="text"
placeholder="none"
property="maxWidth"
disabled={disabled}
value={node ? node.maxWidth : undefined}
onChange={this.props.onChangeLayout}
/>
</Col>
<Col span={12}>
<EditValue
type="text"
placeholder="none"
property="maxHeight"
disabled={disabled}
value={node ? node.maxHeight : undefined}
onChange={this.props.onChangeLayout}
/>
</Col>
</Row>
<h2>
Min-Width &times; Min-Height
<InfoText doclink="/docs/min-max">
Minimum dimensions of the node
</InfoText>
</h2>
<Row gutter={15}>
<Col span={12}>
<EditValue
type="text"
placeholder="0"
property="minWidth"
disabled={disabled}
value={node ? node.minWidth : undefined}
onChange={this.props.onChangeLayout}
/>
</Col>
<Col span={12}>
<EditValue
type="text"
placeholder="0"
property="minHeight"
disabled={disabled}
value={node ? node.minHeight : undefined}
onChange={this.props.onChangeLayout}
/>
</Col>
</Row>
<h2>
Aspect Ratio

View File

@@ -19,18 +19,22 @@ import type {
Yoga$JustifyContent,
Yoga$FlexDirection,
Yoga$FlexWrap,
Yoga$YogaPositionType,
Yoga$PositionType,
} from 'yoga-layout';
export type LayoutRecordT = RecordOf<{
width?: ?number,
height?: ?number,
minWidth?: ?number,
minHeight?: ?number,
maxWidth?: ?number,
maxHeight?: ?number,
justifyContent?: Yoga$JustifyContent,
padding: PositionRecordT,
border: PositionRecordT,
margin: PositionRecordT,
position: PositionRecordT,
positionType: Yoga$YogaPositionType,
positionType: Yoga$PositionType,
alignItems?: Yoga$Align,
alignSelf?: Yoga$Align,
alignContent?: Yoga$Align,
@@ -51,6 +55,10 @@ export type LayoutRecordT = RecordOf<{
const r: LayoutRecordT = Record({
width: 'auto',
height: 'auto',
minWidth: 0,
minHeight: 0,
maxWidth: 'none',
maxHeight: 'none',
justifyContent: yoga.JUSTIFY_FLEX_START,
alignItems: yoga.ALIGN_STRETCH,
alignSelf: yoga.ALIGN_AUTO,

View File

@@ -49,7 +49,7 @@ export default class URLShortener extends Component<{}, State> {
window.ga('send', {
hitType: 'event',
eventCategory: 'URLShortener',
eventAction: 'created'
eventAction: 'created',
});
}

View File

@@ -18,7 +18,8 @@ import {List, setIn} from 'immutable';
import PositionRecord from './PositionRecord';
import LayoutRecord from './LayoutRecord';
import Sidebar from './Sidebar';
import {Row, Col} from 'antd';
import {Row, Col, Button} from 'antd';
import btoa from 'btoa';
import type {LayoutRecordT} from './LayoutRecord';
import type {Yoga$Direction} from 'yoga-layout';
import './index.css';
@@ -164,12 +165,15 @@ export default class Playground extends Component<Props, State> {
});
if (this.props.persist) {
window.location.hash = btoa(
JSON.stringify(this.removeUnchangedProperties(layoutDefinition)),
);
window.location.hash = this.getHash(layoutDefinition);
}
}
getHash = (
layoutDefinition: LayoutRecordT = this.state.layoutDefinition,
): string =>
btoa(JSON.stringify(this.removeUnchangedProperties(layoutDefinition)));
removeUnchangedProperties = (node: LayoutRecordT): Object => {
const untouchedLayout = LayoutRecord({});
const untouchedPosition = PositionRecord({});
@@ -243,7 +247,15 @@ export default class Playground extends Component<Props, State> {
/>
</Col>
<Col span={12}>
<URLShortener />
{this.props.persist ? (
<URLShortener />
) : (
<Button
href={`/playground#${this.getHash()}`}
type="primary">
Open Playground
</Button>
)}
</Col>
</Row>
</div>

View File

@@ -34,7 +34,7 @@ export default ({data}) => (
comes with an interactive playground for you to explore that
feature. The examples section showcases some of the most common
layouts and how to build them. This is a community projects and
contributions within documentation, code, and tests are more then
contributions within documentation, code, and tests are more than
welcome. The contributing section below covers how to get started.
</p>
</Col>

View File

@@ -183,12 +183,14 @@ const AboutSectionTwo = () => (
);
export default () => (
<Page className="landing-page" title="A cross-platform layout engine">
<HeroSection />
<PlaygroundSection />
<AboutSectionOne />
<hr />
<AboutSectionTwo />
<Footer />
</Page>
<div>
<Page className="landing-page" title="A cross-platform layout engine">
<HeroSection />
<PlaygroundSection />
<AboutSectionOne />
<hr />
<AboutSectionTwo />
<Footer />
</Page>
</div>
);

View File

@@ -3,11 +3,13 @@
flex: 1;
}
.playground-page .error-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
@media (max-width: 991px) {
.playground-page .error-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
}
.playground-page .error-text {

File diff suppressed because it is too large Load Diff

View File

@@ -49,3 +49,20 @@ bool YGFloatsEqual(const float a, const float b) {
}
return YGFloatIsUndefined(a) && YGFloatIsUndefined(b);
}
float YGFloatSanitize(const float& val) {
return YGFloatIsUndefined(val) ? 0 : val;
}
float YGUnwrapFloatOptional(const YGFloatOptional& op) {
return op.isUndefined() ? YGUndefined : op.getValue();
}
YGFloatOptional YGFloatOptionalMax(
const YGFloatOptional& op1,
const YGFloatOptional& op2) {
if (!op1.isUndefined() && !op2.isUndefined()) {
return op1.getValue() > op2.getValue() ? op1 : op2;
}
return op1.isUndefined() ? op2 : op1;
}

View File

@@ -40,12 +40,12 @@ struct YGCollectFlexItemsRowValues {
float sizeConsumedOnCurrentLine;
float totalFlexGrowFactors;
float totalFlexShrinkScaledFactors;
float endOfLineIndex;
uint32_t endOfLineIndex;
std::vector<YGNodeRef> relativeChildren;
float remainingFreeSpace;
// The size of the mainDim for the row after considering size, padding, margin
// and border of flex items. This is used to calculate maxLineDim after going
// through all the rows to decide on the main axis size of parent.
// through all the rows to decide on the main axis size of owner.
float mainDim;
// The size of the crossDim for the row after considering size, padding,
// margin and border of flex items. Used for calculating containers crossSize.
@@ -65,6 +65,10 @@ bool YGFloatsEqual(const float a, const float b);
// compiler flag.
float YGFloatMax(const float a, const float b);
YGFloatOptional YGFloatOptionalMax(
const YGFloatOptional& op1,
const YGFloatOptional& op2);
// We need custom min function, since we want that, if one argument is
// YGUndefined then the min funtion should return the other argument as the min
// value. We wouldn't have needed a custom min function if YGUndefined was NAN
@@ -86,6 +90,14 @@ bool YGFloatArrayEqual(
return areEqual;
}
// This function returns 0 if YGFloatIsUndefined(val) is true and val otherwise
float YGFloatSanitize(const float& val);
// This function unwraps optional and returns YGUndefined if not defined or
// op.value otherwise
// TODO: Get rid off this function
float YGUnwrapFloatOptional(const YGFloatOptional& op);
YGFlexDirection YGFlexDirectionCross(
const YGFlexDirection flexDirection,
const YGDirection direction);
@@ -95,17 +107,18 @@ inline bool YGFlexDirectionIsRow(const YGFlexDirection flexDirection) {
flexDirection == YGFlexDirectionRowReverse;
}
inline float YGResolveValue(const YGValue value, const float parentSize) {
inline YGFloatOptional YGResolveValue(const YGValue value, const float ownerSize) {
switch (value.unit) {
case YGUnitUndefined:
case YGUnitAuto:
return YGUndefined;
return YGFloatOptional();
case YGUnitPoint:
return value.value;
return YGFloatOptional(value.value);
case YGUnitPercent:
return value.value * parentSize * 0.01;
return YGFloatOptional(
static_cast<float>(value.value * ownerSize * 0.01));
}
return YGUndefined;
return YGFloatOptional();
}
inline bool YGFlexDirectionIsColumn(const YGFlexDirection flexDirection) {
@@ -127,8 +140,9 @@ inline YGFlexDirection YGResolveFlexDirection(
return flexDirection;
}
static inline float YGResolveValueMargin(
static inline YGFloatOptional YGResolveValueMargin(
const YGValue value,
const float parentSize) {
return value.unit == YGUnitAuto ? 0 : YGResolveValue(value, parentSize);
const float ownerSize) {
return value.unit == YGUnitAuto ? YGFloatOptional(0)
: YGResolveValue(value, ownerSize);
}

19
yoga/YGConfig.cpp Normal file
View File

@@ -0,0 +1,19 @@
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "YGConfig.h"
const std::array<bool, YGExperimentalFeatureCount>
kYGDefaultExperimentalFeatures = {{false}};
YGConfig::YGConfig(YGLogger logger)
: experimentalFeatures(kYGDefaultExperimentalFeatures),
useWebDefaults(false),
useLegacyStretchBehaviour(false),
shouldDiffLayoutWithoutLegacyStretchBehaviour(false),
pointScaleFactor(1.0f), logger(logger), cloneNodeCallback(nullptr),
context(nullptr) {}

23
yoga/YGConfig.h Normal file
View File

@@ -0,0 +1,23 @@
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include "Yoga-internal.h"
#include "Yoga.h"
struct YGConfig {
std::array<bool, YGExperimentalFeatureCount> experimentalFeatures;
bool useWebDefaults;
bool useLegacyStretchBehaviour;
bool shouldDiffLayoutWithoutLegacyStretchBehaviour;
float pointScaleFactor;
YGLogger logger;
YGCloneNodeFunc cloneNodeCallback;
void* context;
YGConfig(YGLogger logger);
};

83
yoga/YGFloatOptional.cpp Normal file
View File

@@ -0,0 +1,83 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
*/
#include "YGFloatOptional.h"
#include <cstdlib>
#include <iostream>
#include "Yoga.h"
YGFloatOptional::YGFloatOptional(float value) {
if (YGFloatIsUndefined(value)) {
isUndefined_ = true;
value_ = 0;
} else {
value_ = value;
isUndefined_ = false;
}
}
YGFloatOptional::YGFloatOptional() : value_(0), isUndefined_(true) {}
const float& YGFloatOptional::getValue() const {
if (isUndefined_) {
// Abort, accessing a value of an undefined float optional
std::cerr << "Tried to get value of an undefined YGFloatOptional\n";
std::exit(EXIT_FAILURE);
}
return value_;
}
bool YGFloatOptional::operator==(const YGFloatOptional& op) const {
if (isUndefined_ == op.isUndefined()) {
return isUndefined_ || value_ == op.getValue();
}
return false;
}
bool YGFloatOptional::operator!=(const YGFloatOptional& op) const {
return !(*this == op);
}
bool YGFloatOptional::operator==(float val) const {
if (YGFloatIsUndefined(val) == isUndefined_) {
return isUndefined_ || val == value_;
}
return false;
}
bool YGFloatOptional::operator!=(float val) const {
return !(*this == val);
}
YGFloatOptional YGFloatOptional::operator+(const YGFloatOptional& op) {
if (!isUndefined_ && !op.isUndefined_) {
return YGFloatOptional(value_ + op.value_);
}
return YGFloatOptional();
}
bool YGFloatOptional::operator>(const YGFloatOptional& op) const {
if (isUndefined_ || op.isUndefined_) {
return false;
}
return value_ > op.value_;
}
bool YGFloatOptional::operator<(const YGFloatOptional& op) const {
if (isUndefined_ || op.isUndefined_) {
return false;
}
return value_ < op.value_;
}
bool YGFloatOptional::operator>=(const YGFloatOptional& op) const {
return *this == op || *this > op;
}
bool YGFloatOptional::operator<=(const YGFloatOptional& op) const {
return *this == op || *this < op;
}

44
yoga/YGFloatOptional.h Normal file
View File

@@ -0,0 +1,44 @@
/*
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*
*/
#pragma once
struct YGFloatOptional {
private:
float value_;
bool isUndefined_;
public:
explicit YGFloatOptional(float value);
explicit YGFloatOptional();
// Program will terminate if the value of an undefined is accessed. Please
// make sure to check if the optional is defined before calling this function.
// To check if float optional is defined, use `isUndefined()`.
const float& getValue() const;
// Sets the value of float optional, and thus isUndefined is assigned false.
void setValue(float val) {
value_ = val;
isUndefined_ = false;
}
bool isUndefined() const {
return isUndefined_;
}
YGFloatOptional operator+(const YGFloatOptional& op);
bool operator>(const YGFloatOptional& op) const;
bool operator<(const YGFloatOptional& op) const;
bool operator>=(const YGFloatOptional& op) const;
bool operator<=(const YGFloatOptional& op) const;
bool operator==(const YGFloatOptional& op) const;
bool operator!=(const YGFloatOptional& op) const;
bool operator==(float val) const;
bool operator!=(float val) const;
};

View File

@@ -19,10 +19,10 @@ YGLayout::YGLayout()
padding(),
direction(YGDirectionInherit),
computedFlexBasisGeneration(0),
computedFlexBasis(YGUndefined),
computedFlexBasis(YGFloatOptional()),
hadOverflow(false),
generationCount(0),
lastParentDirection((YGDirection)-1),
lastOwnerDirection((YGDirection)-1),
nextCachedMeasurementsIndex(0),
cachedMeasurements(),
measuredDimensions(kYGDefaultDimensionValues),
@@ -37,18 +37,15 @@ bool YGLayout::operator==(YGLayout layout) const {
YGFloatArrayEqual(border, layout.border) &&
YGFloatArrayEqual(padding, layout.padding) &&
direction == layout.direction && hadOverflow == layout.hadOverflow &&
lastParentDirection == layout.lastParentDirection &&
lastOwnerDirection == layout.lastOwnerDirection &&
nextCachedMeasurementsIndex == layout.nextCachedMeasurementsIndex &&
cachedLayout == layout.cachedLayout;
cachedLayout == layout.cachedLayout &&
computedFlexBasis == layout.computedFlexBasis;
for (uint32_t i = 0; i < YG_MAX_CACHED_RESULT_COUNT && isEqual; ++i) {
isEqual = isEqual && cachedMeasurements[i] == layout.cachedMeasurements[i];
}
if (!YGFloatIsUndefined(computedFlexBasis) ||
!YGFloatIsUndefined(layout.computedFlexBasis)) {
isEqual = isEqual && (computedFlexBasis == layout.computedFlexBasis);
}
if (!YGFloatIsUndefined(measuredDimensions[0]) ||
!YGFloatIsUndefined(layout.measuredDimensions[0])) {
isEqual =

View File

@@ -6,6 +6,7 @@
*/
#pragma once
#include "YGFloatOptional.h"
#include "Yoga-internal.h"
struct YGLayout {
@@ -17,13 +18,13 @@ struct YGLayout {
YGDirection direction;
uint32_t computedFlexBasisGeneration;
float computedFlexBasis;
YGFloatOptional computedFlexBasis;
bool hadOverflow;
// Instead of recomputing the entire layout every single time, we
// cache some information to break early when nothing changed
uint32_t generationCount;
YGDirection lastParentDirection;
YGDirection lastOwnerDirection;
uint32_t nextCachedMeasurementsIndex;
std::array<YGCachedMeasurement, YG_MAX_CACHED_RESULT_COUNT>

View File

@@ -9,85 +9,9 @@
#include <iostream>
#include "Utils.h"
void* YGNode::getContext() const {
return context_;
}
YGPrintFunc YGNode::getPrintFunc() const {
return print_;
}
bool YGNode::getHasNewLayout() const {
return hasNewLayout_;
}
YGNodeType YGNode::getNodeType() const {
return nodeType_;
}
YGMeasureFunc YGNode::getMeasure() const {
return measure_;
}
YGBaselineFunc YGNode::getBaseline() const {
return baseline_;
}
YGDirtiedFunc YGNode::getDirtied() const {
return dirtied_;
}
YGStyle& YGNode::getStyle() {
return style_;
}
YGLayout& YGNode::getLayout() {
return layout_;
}
uint32_t YGNode::getLineIndex() const {
return lineIndex_;
}
YGNodeRef YGNode::getParent() const {
return parent_;
}
YGVector YGNode::getChildren() const {
return children_;
}
uint32_t YGNode::getChildrenCount() const {
return static_cast<uint32_t>(children_.size());
}
YGNodeRef YGNode::getChild(uint32_t index) const {
return children_.at(index);
}
YGNodeRef YGNode::getNextChild() const {
return nextChild_;
}
YGConfigRef YGNode::getConfig() const {
return config_;
}
bool YGNode::isDirty() const {
return isDirty_;
}
YGValue YGNode::getResolvedDimension(int index) {
return resolvedDimensions_[index];
}
std::array<YGValue, 2> YGNode::getResolvedDimensions() const {
return resolvedDimensions_;
}
float YGNode::getLeadingPosition(
const YGFlexDirection axis,
const float axisSize) {
YGFloatOptional YGNode::getLeadingPosition(
const YGFlexDirection& axis,
const float& axisSize) const {
if (YGFlexDirectionIsRow(axis)) {
const YGValue* leadingPosition =
YGComputedEdgeValue(style_.position, YGEdgeStart, &YGValueUndefined);
@@ -100,13 +24,13 @@ float YGNode::getLeadingPosition(
YGComputedEdgeValue(style_.position, leading[axis], &YGValueUndefined);
return leadingPosition->unit == YGUnitUndefined
? 0.0f
? YGFloatOptional(0)
: YGResolveValue(*leadingPosition, axisSize);
}
float YGNode::getTrailingPosition(
const YGFlexDirection axis,
const float axisSize) {
YGFloatOptional YGNode::getTrailingPosition(
const YGFlexDirection& axis,
const float& axisSize) const {
if (YGFlexDirectionIsRow(axis)) {
const YGValue* trailingPosition =
YGComputedEdgeValue(style_.position, YGEdgeEnd, &YGValueUndefined);
@@ -119,11 +43,11 @@ float YGNode::getTrailingPosition(
YGComputedEdgeValue(style_.position, trailing[axis], &YGValueUndefined);
return trailingPosition->unit == YGUnitUndefined
? 0.0f
? YGFloatOptional(0)
: YGResolveValue(*trailingPosition, axisSize);
}
bool YGNode::isLeadingPositionDefined(const YGFlexDirection axis) {
bool YGNode::isLeadingPositionDefined(const YGFlexDirection& axis) const {
return (YGFlexDirectionIsRow(axis) &&
YGComputedEdgeValue(style_.position, YGEdgeStart, &YGValueUndefined)
->unit != YGUnitUndefined) ||
@@ -131,7 +55,7 @@ bool YGNode::isLeadingPositionDefined(const YGFlexDirection axis) {
->unit != YGUnitUndefined;
}
bool YGNode::isTrailingPosDefined(const YGFlexDirection axis) {
bool YGNode::isTrailingPosDefined(const YGFlexDirection& axis) const {
return (YGFlexDirectionIsRow(axis) &&
YGComputedEdgeValue(style_.position, YGEdgeEnd, &YGValueUndefined)
->unit != YGUnitUndefined) ||
@@ -139,9 +63,9 @@ bool YGNode::isTrailingPosDefined(const YGFlexDirection axis) {
->unit != YGUnitUndefined;
}
float YGNode::getLeadingMargin(
const YGFlexDirection axis,
const float widthSize) {
YGFloatOptional YGNode::getLeadingMargin(
const YGFlexDirection& axis,
const float& widthSize) const {
if (YGFlexDirectionIsRow(axis) &&
style_.margin[YGEdgeStart].unit != YGUnitUndefined) {
return YGResolveValueMargin(style_.margin[YGEdgeStart], widthSize);
@@ -152,9 +76,9 @@ float YGNode::getLeadingMargin(
widthSize);
}
float YGNode::getTrailingMargin(
const YGFlexDirection axis,
const float widthSize) {
YGFloatOptional YGNode::getTrailingMargin(
const YGFlexDirection& axis,
const float& widthSize) const {
if (YGFlexDirectionIsRow(axis) &&
style_.margin[YGEdgeEnd].unit != YGUnitUndefined) {
return YGResolveValueMargin(style_.margin[YGEdgeEnd], widthSize);
@@ -165,37 +89,15 @@ float YGNode::getTrailingMargin(
widthSize);
}
float YGNode::getMarginForAxis(
const YGFlexDirection axis,
const float widthSize) {
YGFloatOptional YGNode::getMarginForAxis(
const YGFlexDirection& axis,
const float& widthSize) const {
return getLeadingMargin(axis, widthSize) + getTrailingMargin(axis, widthSize);
}
// Setters
void YGNode::setContext(void* context) {
context_ = context;
}
void YGNode::setPrintFunc(YGPrintFunc printFunc) {
print_ = printFunc;
}
void YGNode::setHasNewLayout(bool hasNewLayout) {
hasNewLayout_ = hasNewLayout;
}
void YGNode::setNodeType(YGNodeType nodeType) {
nodeType_ = nodeType;
}
void YGNode::setStyleFlexDirection(YGFlexDirection direction) {
style_.flexDirection = direction;
}
void YGNode::setStyleAlignContent(YGAlign alignContent) {
style_.alignContent = alignContent;
}
void YGNode::setMeasureFunc(YGMeasureFunc measureFunc) {
if (measureFunc == nullptr) {
@@ -217,38 +119,6 @@ void YGNode::setMeasureFunc(YGMeasureFunc measureFunc) {
measure_ = measureFunc;
}
void YGNode::setBaseLineFunc(YGBaselineFunc baseLineFunc) {
baseline_ = baseLineFunc;
}
void YGNode::setDirtiedFunc(YGDirtiedFunc dirtiedFunc) {
dirtied_ = dirtiedFunc;
}
void YGNode::setStyle(YGStyle style) {
style_ = style;
}
void YGNode::setLayout(YGLayout layout) {
layout_ = layout;
}
void YGNode::setLineIndex(uint32_t lineIndex) {
lineIndex_ = lineIndex;
}
void YGNode::setParent(YGNodeRef parent) {
parent_ = parent;
}
void YGNode::setChildren(YGVector children) {
children_ = children;
}
void YGNode::setNextChild(YGNodeRef nextChild) {
nextChild_ = nextChild;
}
void YGNode::replaceChild(YGNodeRef child, uint32_t index) {
children_[index] = child;
}
@@ -261,10 +131,6 @@ void YGNode::insertChild(YGNodeRef child, uint32_t index) {
children_.insert(children_.begin() + index, child);
}
void YGNode::setConfig(YGConfigRef config) {
config_ = config;
}
void YGNode::setDirty(bool isDirty) {
if (isDirty == isDirty_) {
return;
@@ -305,11 +171,12 @@ void YGNode::setLayoutPadding(float padding, int index) {
layout_.padding[index] = padding;
}
void YGNode::setLayoutLastParentDirection(YGDirection direction) {
layout_.lastParentDirection = direction;
void YGNode::setLayoutLastOwnerDirection(YGDirection direction) {
layout_.lastOwnerDirection = direction;
}
void YGNode::setLayoutComputedFlexBasis(float computedFlexBasis) {
void YGNode::setLayoutComputedFlexBasis(
const YGFloatOptional& computedFlexBasis) {
layout_.computedFlexBasis = computedFlexBasis;
}
@@ -336,41 +203,54 @@ void YGNode::setLayoutDimension(float dimension, int index) {
// If both left and right are defined, then use left. Otherwise return
// +left or -right depending on which is defined.
float YGNode::relativePosition(
const YGFlexDirection axis,
const float axisSize) {
return isLeadingPositionDefined(axis) ? getLeadingPosition(axis, axisSize)
: -getTrailingPosition(axis, axisSize);
YGFloatOptional YGNode::relativePosition(
const YGFlexDirection& axis,
const float& axisSize) const {
if (isLeadingPositionDefined(axis)) {
return getLeadingPosition(axis, axisSize);
}
YGFloatOptional trailingPosition = getTrailingPosition(axis, axisSize);
if (!trailingPosition.isUndefined()) {
trailingPosition.setValue(-1 * trailingPosition.getValue());
}
return trailingPosition;
}
void YGNode::setPosition(
const YGDirection direction,
const float mainSize,
const float crossSize,
const float parentWidth) {
const float ownerWidth) {
/* Root nodes should be always layouted as LTR, so we don't return negative
* values. */
const YGDirection directionRespectingRoot =
parent_ != nullptr ? direction : YGDirectionLTR;
owner_ != nullptr ? direction : YGDirectionLTR;
const YGFlexDirection mainAxis =
YGResolveFlexDirection(style_.flexDirection, directionRespectingRoot);
const YGFlexDirection crossAxis =
YGFlexDirectionCross(mainAxis, directionRespectingRoot);
const float relativePositionMain = relativePosition(mainAxis, mainSize);
const float relativePositionCross = relativePosition(crossAxis, crossSize);
const YGFloatOptional relativePositionMain =
relativePosition(mainAxis, mainSize);
const YGFloatOptional relativePositionCross =
relativePosition(crossAxis, crossSize);
setLayoutPosition(
getLeadingMargin(mainAxis, parentWidth) + relativePositionMain,
YGUnwrapFloatOptional(
getLeadingMargin(mainAxis, ownerWidth) + relativePositionMain),
leading[mainAxis]);
setLayoutPosition(
getTrailingMargin(mainAxis, parentWidth) + relativePositionMain,
YGUnwrapFloatOptional(
getTrailingMargin(mainAxis, ownerWidth) + relativePositionMain),
trailing[mainAxis]);
setLayoutPosition(
getLeadingMargin(crossAxis, parentWidth) + relativePositionCross,
YGUnwrapFloatOptional(
getLeadingMargin(crossAxis, ownerWidth) + relativePositionCross),
leading[crossAxis]);
setLayoutPosition(
getTrailingMargin(crossAxis, parentWidth) + relativePositionCross,
YGUnwrapFloatOptional(
getTrailingMargin(crossAxis, ownerWidth) + relativePositionCross),
trailing[crossAxis]);
}
@@ -385,9 +265,8 @@ YGNode::YGNode()
style_(YGStyle()),
layout_(YGLayout()),
lineIndex_(0),
parent_(nullptr),
owner_(nullptr),
children_(YGVector()),
nextChild_(nullptr),
config_(nullptr),
isDirty_(false),
resolvedDimensions_({{YGValueUndefined, YGValueUndefined}}) {}
@@ -403,9 +282,8 @@ YGNode::YGNode(const YGNode& node)
style_(node.style_),
layout_(node.layout_),
lineIndex_(node.lineIndex_),
parent_(node.parent_),
owner_(node.owner_),
children_(node.children_),
nextChild_(node.nextChild_),
config_(node.config_),
isDirty_(node.isDirty_),
resolvedDimensions_(node.resolvedDimensions_) {}
@@ -423,11 +301,10 @@ YGNode::YGNode(
YGBaselineFunc baseline,
YGDirtiedFunc dirtied,
YGStyle style,
YGLayout layout,
const YGLayout& layout,
uint32_t lineIndex,
YGNodeRef parent,
YGVector children,
YGNodeRef nextChild,
YGNodeRef owner,
const YGVector& children,
YGConfigRef config,
bool isDirty,
std::array<YGValue, 2> resolvedDimensions)
@@ -441,9 +318,8 @@ YGNode::YGNode(
style_(style),
layout_(layout),
lineIndex_(lineIndex),
parent_(parent),
owner_(owner),
children_(children),
nextChild_(nextChild),
config_(config),
isDirty_(isDirty),
resolvedDimensions_(resolvedDimensions) {}
@@ -467,9 +343,8 @@ YGNode& YGNode::operator=(const YGNode& node) {
style_ = node.style_;
layout_ = node.layout_;
lineIndex_ = node.getLineIndex();
parent_ = node.getParent();
owner_ = node.getOwner();
children_ = node.getChildren();
nextChild_ = node.getNextChild();
config_ = node.getConfig();
isDirty_ = node.isDirty();
resolvedDimensions_ = node.getResolvedDimensions();
@@ -500,7 +375,7 @@ YGValue YGNode::resolveFlexBasisPtr() const {
if (flexBasis.unit != YGUnitAuto && flexBasis.unit != YGUnitUndefined) {
return flexBasis;
}
if (!YGFloatIsUndefined(style_.flex) && style_.flex > 0.0f) {
if (!style_.flex.isUndefined() && style_.flex.getValue() > 0.0f) {
return config_->useWebDefaults ? YGValueAuto : YGValueZero;
}
return YGValueAuto;
@@ -518,9 +393,9 @@ void YGNode::resolveDimension() {
}
}
YGDirection YGNode::resolveDirection(const YGDirection parentDirection) {
YGDirection YGNode::resolveDirection(const YGDirection ownerDirection) {
if (style_.direction == YGDirectionInherit) {
return parentDirection > YGDirectionInherit ? parentDirection
return ownerDirection > YGDirectionInherit ? ownerDirection
: YGDirectionLTR;
} else {
return style_.direction;
@@ -550,32 +425,35 @@ void YGNode::cloneChildrenIfNeeded() {
}
const YGNodeRef firstChild = children_.front();
if (firstChild->getParent() == this) {
// If the first child has this node as its parent, we assume that it is
if (firstChild->getOwner() == this) {
// If the first child has this node as its owner, we assume that it is
// already unique. We can do this because if we have it has a child, that
// means that its parent was at some point cloned which made that subtree
// means that its owner was at some point cloned which made that subtree
// immutable. We also assume that all its sibling are cloned as well.
return;
}
const YGNodeClonedFunc cloneNodeCallback = config_->cloneNodeCallback;
const YGCloneNodeFunc cloneNodeCallback = config_->cloneNodeCallback;
for (uint32_t i = 0; i < childCount; ++i) {
const YGNodeRef oldChild = children_[i];
const YGNodeRef newChild = YGNodeClone(oldChild);
replaceChild(newChild, i);
newChild->setParent(this);
YGNodeRef newChild = nullptr;
if (cloneNodeCallback) {
cloneNodeCallback(oldChild, newChild, this, i);
newChild = cloneNodeCallback(oldChild, this, i);
}
if (newChild == nullptr) {
newChild = YGNodeClone(oldChild);
}
replaceChild(newChild, i);
newChild->setOwner(this);
}
}
void YGNode::markDirtyAndPropogate() {
if (!isDirty_) {
setDirty(true);
setLayoutComputedFlexBasis(YGUndefined);
if (parent_) {
parent_->markDirtyAndPropogate();
setLayoutComputedFlexBasis(YGFloatOptional());
if (owner_) {
owner_->markDirtyAndPropogate();
}
}
}
@@ -589,28 +467,28 @@ void YGNode::markDirtyAndPropogateDownwards() {
float YGNode::resolveFlexGrow() {
// Root nodes flexGrow should always be 0
if (parent_ == nullptr) {
if (owner_ == nullptr) {
return 0.0;
}
if (!YGFloatIsUndefined(style_.flexGrow)) {
return style_.flexGrow;
if (!style_.flexGrow.isUndefined()) {
return style_.flexGrow.getValue();
}
if (!YGFloatIsUndefined(style_.flex) && style_.flex > 0.0f) {
return style_.flex;
if (!style_.flex.isUndefined() && style_.flex.getValue() > 0.0f) {
return style_.flex.getValue();
}
return kDefaultFlexGrow;
}
float YGNode::resolveFlexShrink() {
if (parent_ == nullptr) {
if (owner_ == nullptr) {
return 0.0;
}
if (!YGFloatIsUndefined(style_.flexShrink)) {
return style_.flexShrink;
if (!style_.flexShrink.isUndefined()) {
return style_.flexShrink.getValue();
}
if (!config_->useWebDefaults && !YGFloatIsUndefined(style_.flex) &&
style_.flex < 0.0f) {
return -style_.flex;
if (!config_->useWebDefaults && !style_.flex.isUndefined() &&
style_.flex.getValue() < 0.0f) {
return -style_.flex.getValue();
}
return config_->useWebDefaults ? kWebDefaultFlexShrink : kDefaultFlexShrink;
}
@@ -621,7 +499,7 @@ bool YGNode::isNodeFlexible() {
(resolveFlexGrow() != 0 || resolveFlexShrink() != 0));
}
float YGNode::getLeadingBorder(const YGFlexDirection axis) {
float YGNode::getLeadingBorder(const YGFlexDirection& axis) const {
if (YGFlexDirectionIsRow(axis) &&
style_.border[YGEdgeStart].unit != YGUnitUndefined &&
!YGFloatIsUndefined(style_.border[YGEdgeStart].value) &&
@@ -634,7 +512,7 @@ float YGNode::getLeadingBorder(const YGFlexDirection axis) {
return YGFloatMax(computedEdgeValue, 0.0f);
}
float YGNode::getTrailingBorder(const YGFlexDirection flexDirection) {
float YGNode::getTrailingBorder(const YGFlexDirection& flexDirection) const {
if (YGFlexDirectionIsRow(flexDirection) &&
style_.border[YGEdgeEnd].unit != YGUnitUndefined &&
!YGFloatIsUndefined(style_.border[YGEdgeEnd].value) &&
@@ -648,51 +526,52 @@ float YGNode::getTrailingBorder(const YGFlexDirection flexDirection) {
return YGFloatMax(computedEdgeValue, 0.0f);
}
float YGNode::getLeadingPadding(
const YGFlexDirection axis,
const float widthSize) {
YGFloatOptional YGNode::getLeadingPadding(
const YGFlexDirection& axis,
const float& widthSize) const {
const YGFloatOptional& paddingEdgeStart =
YGResolveValue(style_.padding[YGEdgeStart], widthSize);
if (YGFlexDirectionIsRow(axis) &&
style_.padding[YGEdgeStart].unit != YGUnitUndefined &&
!YGFloatIsUndefined(
YGResolveValue(style_.padding[YGEdgeStart], widthSize)) &&
YGResolveValue(style_.padding[YGEdgeStart], widthSize) > 0.0f) {
return YGResolveValue(style_.padding[YGEdgeStart], widthSize);
!paddingEdgeStart.isUndefined() && paddingEdgeStart.getValue() > 0.0f) {
return paddingEdgeStart;
}
float resolvedValue = YGResolveValue(
YGFloatOptional resolvedValue = YGResolveValue(
*YGComputedEdgeValue(style_.padding, leading[axis], &YGValueZero),
widthSize);
return YGFloatMax(resolvedValue, 0.0f);
return YGFloatOptionalMax(resolvedValue, YGFloatOptional(0.0f));
}
float YGNode::getTrailingPadding(
const YGFlexDirection axis,
const float widthSize) {
YGFloatOptional YGNode::getTrailingPadding(
const YGFlexDirection& axis,
const float& widthSize) const {
if (YGFlexDirectionIsRow(axis) &&
style_.padding[YGEdgeEnd].unit != YGUnitUndefined &&
!YGFloatIsUndefined(
YGResolveValue(style_.padding[YGEdgeEnd], widthSize)) &&
YGResolveValue(style_.padding[YGEdgeEnd], widthSize) >= 0.0f) {
!YGResolveValue(style_.padding[YGEdgeEnd], widthSize).isUndefined() &&
YGResolveValue(style_.padding[YGEdgeEnd], widthSize).getValue() >= 0.0f) {
return YGResolveValue(style_.padding[YGEdgeEnd], widthSize);
}
float resolvedValue = YGResolveValue(
YGFloatOptional resolvedValue = YGResolveValue(
*YGComputedEdgeValue(style_.padding, trailing[axis], &YGValueZero),
widthSize);
return YGFloatMax(resolvedValue, 0.0f);
return YGFloatOptionalMax(resolvedValue, YGFloatOptional(0.0f));
}
float YGNode::getLeadingPaddingAndBorder(
const YGFlexDirection axis,
const float widthSize) {
return getLeadingPadding(axis, widthSize) + getLeadingBorder(axis);
YGFloatOptional YGNode::getLeadingPaddingAndBorder(
const YGFlexDirection& axis,
const float& widthSize) const {
return getLeadingPadding(axis, widthSize) +
YGFloatOptional(getLeadingBorder(axis));
}
float YGNode::getTrailingPaddingAndBorder(
const YGFlexDirection axis,
const float widthSize) {
return getTrailingPadding(axis, widthSize) + getTrailingBorder(axis);
YGFloatOptional YGNode::getTrailingPaddingAndBorder(
const YGFlexDirection& axis,
const float& widthSize) const {
return getTrailingPadding(axis, widthSize) +
YGFloatOptional(getTrailingBorder(axis));
}
bool YGNode::didUseLegacyFlag() {

View File

@@ -7,6 +7,7 @@
#pragma once
#include <stdio.h>
#include "YGConfig.h"
#include "YGLayout.h"
#include "YGStyle.h"
#include "Yoga-internal.h"
@@ -23,14 +24,15 @@ struct YGNode {
YGStyle style_;
YGLayout layout_;
uint32_t lineIndex_;
YGNodeRef parent_;
YGNodeRef owner_;
YGVector children_;
YGNodeRef nextChild_;
YGConfigRef config_;
bool isDirty_;
std::array<YGValue, 2> resolvedDimensions_;
float relativePosition(const YGFlexDirection axis, const float axisSize);
YGFloatOptional relativePosition(
const YGFlexDirection& axis,
const float& axisSize) const;
public:
YGNode();
@@ -47,77 +49,203 @@ struct YGNode {
YGBaselineFunc baseline,
YGDirtiedFunc dirtied,
YGStyle style,
YGLayout layout,
const YGLayout& layout,
uint32_t lineIndex,
YGNodeRef parent,
YGVector children,
YGNodeRef nextChild,
YGNodeRef owner,
const YGVector& children,
YGConfigRef config,
bool isDirty,
std::array<YGValue, 2> resolvedDimensions);
// Getters
void* getContext() const;
YGPrintFunc getPrintFunc() const;
bool getHasNewLayout() const;
YGNodeType getNodeType() const;
YGMeasureFunc getMeasure() const;
YGBaselineFunc getBaseline() const;
YGDirtiedFunc getDirtied() const;
void* getContext() const {
return context_;
}
YGPrintFunc getPrintFunc() const {
return print_;
}
bool getHasNewLayout() const {
return hasNewLayout_;
}
YGNodeType getNodeType() const {
return nodeType_;
}
YGMeasureFunc getMeasure() const {
return measure_;
}
YGBaselineFunc getBaseline() const {
return baseline_;
}
YGDirtiedFunc getDirtied() const {
return dirtied_;
}
// For Performance reasons passing as reference.
YGStyle& getStyle();
YGStyle& getStyle() {
return style_;
}
const YGStyle& getStyle() const {
return style_;
}
// For Performance reasons passing as reference.
YGLayout& getLayout();
uint32_t getLineIndex() const;
YGNodeRef getParent() const;
YGVector getChildren() const;
uint32_t getChildrenCount() const;
YGNodeRef getChild(uint32_t index) const;
YGNodeRef getNextChild() const;
YGConfigRef getConfig() const;
bool isDirty() const;
std::array<YGValue, 2> getResolvedDimensions() const;
YGValue getResolvedDimension(int index);
YGLayout& getLayout() {
return layout_;
}
const YGLayout& getLayout() const {
return layout_;
}
uint32_t getLineIndex() const {
return lineIndex_;
}
// returns the YGNodeRef that owns this YGNode. An owner is used to identify
// the YogaTree that a YGNode belongs to.
// This method will return the parent of the YGNode when a YGNode only belongs
// to one YogaTree or nullptr when the YGNode is shared between two or more
// YogaTrees.
YGNodeRef getOwner() const {
return owner_;
}
// Deprecated, use getOwner() instead.
YGNodeRef getParent() const {
return getOwner();
}
YGVector getChildren() const {
return children_;
}
uint32_t getChildrenCount() const {
return static_cast<uint32_t>(children_.size());
}
YGNodeRef getChild(uint32_t index) const {
return children_.at(index);
}
YGConfigRef getConfig() const {
return config_;
}
bool isDirty() const {
return isDirty_;
}
std::array<YGValue, 2> getResolvedDimensions() const {
return resolvedDimensions_;
}
YGValue getResolvedDimension(int index) const {
return resolvedDimensions_[index];
}
// Methods related to positions, margin, padding and border
float getLeadingPosition(const YGFlexDirection axis, const float axisSize);
bool isLeadingPositionDefined(const YGFlexDirection axis);
bool isTrailingPosDefined(const YGFlexDirection axis);
float getTrailingPosition(const YGFlexDirection axis, const float axisSize);
float getLeadingMargin(const YGFlexDirection axis, const float widthSize);
float getTrailingMargin(const YGFlexDirection axis, const float widthSize);
float getLeadingBorder(const YGFlexDirection flexDirection);
float getTrailingBorder(const YGFlexDirection flexDirection);
float getLeadingPadding(const YGFlexDirection axis, const float widthSize);
float getTrailingPadding(const YGFlexDirection axis, const float widthSize);
float getLeadingPaddingAndBorder(
const YGFlexDirection axis,
const float widthSize);
float getTrailingPaddingAndBorder(
const YGFlexDirection axis,
const float widthSize);
float getMarginForAxis(const YGFlexDirection axis, const float widthSize);
YGFloatOptional getLeadingPosition(const YGFlexDirection& axis,
const float& axisSize) const;
bool isLeadingPositionDefined(const YGFlexDirection& axis) const;
bool isTrailingPosDefined(const YGFlexDirection& axis) const;
YGFloatOptional getTrailingPosition(
const YGFlexDirection& axis,
const float& axisSize) const;
YGFloatOptional getLeadingMargin(
const YGFlexDirection& axis,
const float& widthSize) const;
YGFloatOptional getTrailingMargin(
const YGFlexDirection& axis,
const float& widthSize) const;
float getLeadingBorder(const YGFlexDirection& flexDirection) const;
float getTrailingBorder(const YGFlexDirection& flexDirection) const;
YGFloatOptional getLeadingPadding(
const YGFlexDirection& axis,
const float& widthSize) const;
YGFloatOptional getTrailingPadding(
const YGFlexDirection& axis,
const float& widthSize) const;
YGFloatOptional getLeadingPaddingAndBorder(
const YGFlexDirection& axis,
const float& widthSize) const;
YGFloatOptional getTrailingPaddingAndBorder(
const YGFlexDirection& axis,
const float& widthSize) const;
YGFloatOptional getMarginForAxis(
const YGFlexDirection& axis,
const float& widthSize) const;
// Setters
void setContext(void* context);
void setPrintFunc(YGPrintFunc printFunc);
void setHasNewLayout(bool hasNewLayout);
void setNodeType(YGNodeType nodeTye);
void setContext(void* context) {
context_ = context;
}
void setPrintFunc(YGPrintFunc printFunc) {
print_ = printFunc;
}
void setHasNewLayout(bool hasNewLayout) {
hasNewLayout_ = hasNewLayout;
}
void setNodeType(YGNodeType nodeType) {
nodeType_ = nodeType;
}
void setStyleFlexDirection(YGFlexDirection direction) {
style_.flexDirection = direction;
}
void setStyleAlignContent(YGAlign alignContent) {
style_.alignContent = alignContent;
}
void setMeasureFunc(YGMeasureFunc measureFunc);
void setBaseLineFunc(YGBaselineFunc baseLineFunc);
void setDirtiedFunc(YGDirtiedFunc dirtiedFunc);
void setStyle(YGStyle style);
void setStyleFlexDirection(YGFlexDirection direction);
void setStyleAlignContent(YGAlign alignContent);
void setLayout(YGLayout layout);
void setLineIndex(uint32_t lineIndex);
void setParent(YGNodeRef parent);
void setChildren(YGVector children);
void setNextChild(YGNodeRef nextChild);
void setConfig(YGConfigRef config);
void setBaseLineFunc(YGBaselineFunc baseLineFunc) {
baseline_ = baseLineFunc;
}
void setDirtiedFunc(YGDirtiedFunc dirtiedFunc) {
dirtied_ = dirtiedFunc;
}
void setStyle(const YGStyle& style) {
style_ = style;
}
void setLayout(const YGLayout& layout) {
layout_ = layout;
}
void setLineIndex(uint32_t lineIndex) {
lineIndex_ = lineIndex;
}
void setOwner(YGNodeRef owner) {
owner_ = owner;
}
void setChildren(const YGVector& children) {
children_ = children;
}
// TODO: rvalue override for setChildren
void setConfig(YGConfigRef config) {
config_ = config;
}
void setDirty(bool isDirty);
void setLayoutLastParentDirection(YGDirection direction);
void setLayoutComputedFlexBasis(float computedFlexBasis);
void setLayoutLastOwnerDirection(YGDirection direction);
void setLayoutComputedFlexBasis(const YGFloatOptional& computedFlexBasis);
void setLayoutComputedFlexBasisGeneration(
uint32_t computedFlexBasisGeneration);
void setLayoutMeasuredDimension(float measuredDimension, int index);
@@ -132,7 +260,7 @@ struct YGNode {
const YGDirection direction,
const float mainSize,
const float crossSize,
const float parentWidth);
const float ownerWidth);
void setAndPropogateUseLegacyFlag(bool useLegacyFlag);
void setLayoutDoesLegacyFlagAffectsLayout(bool doesLegacyFlagAffectsLayout);
void setLayoutDidUseLegacyFlag(bool didUseLegacyFlag);
@@ -143,7 +271,7 @@ struct YGNode {
YGValue marginTrailingValue(const YGFlexDirection axis) const;
YGValue resolveFlexBasisPtr() const;
void resolveDimension();
YGDirection resolveDirection(const YGDirection parentDirection);
YGDirection resolveDirection(const YGDirection ownerDirection);
void clearChildren();
/// Replaces the occurrences of oldChild with newChild
void replaceChild(YGNodeRef oldChild, YGNodeRef newChild);

View File

@@ -39,10 +39,12 @@ static void appendFormatedString(string* str, const char* fmt, ...) {
str->append(result);
}
static void
appendFloatIfNotUndefined(string* base, const string key, const float num) {
if (!YGFloatIsUndefined(num)) {
appendFormatedString(base, "%s: %g; ", key.c_str(), num);
static void appendFloatOptionalIfDefined(
string* base,
const string key,
const YGFloatOptional num) {
if (!num.isUndefined()) {
appendFormatedString(base, "%s: %g; ", key.c_str(), num.getValue());
}
}
@@ -70,7 +72,10 @@ appendNumberIfNotAuto(string* base, const string& key, const YGValue number) {
static void
appendNumberIfNotZero(string* base, const string& str, const YGValue number) {
if (!YGFloatsEqual(number.value, 0)) {
if (number.unit == YGUnitAuto) {
base->append(str + ": auto; ");
} else if (!YGFloatsEqual(number.value, 0)) {
appendNumberIfNotUndefined(base, str, number);
}
}
@@ -152,10 +157,11 @@ void YGNodeToString(
appendFormatedString(
str, "align-self: %s; ", YGAlignToString(node->getStyle().alignSelf));
}
appendFloatIfNotUndefined(str, "flex-grow", node->getStyle().flexGrow);
appendFloatIfNotUndefined(str, "flex-shrink", node->getStyle().flexShrink);
appendFloatOptionalIfDefined(str, "flex-grow", node->getStyle().flexGrow);
appendFloatOptionalIfDefined(
str, "flex-shrink", node->getStyle().flexShrink);
appendNumberIfNotAuto(str, "flex-basis", node->getStyle().flexBasis);
appendFloatIfNotUndefined(str, "flex", node->getStyle().flex);
appendFloatOptionalIfDefined(str, "flex", node->getStyle().flex);
if (node->getStyle().flexWrap != YGNode().getStyle().flexWrap) {
appendFormatedString(

View File

@@ -7,9 +7,9 @@
#include "YGStyle.h"
const YGValue kYGValueUndefined = {YGUndefined, YGUnitUndefined};
const YGValue kYGValueUndefined = {0, YGUnitUndefined};
const YGValue kYGValueAuto = {YGUndefined, YGUnitAuto};
const YGValue kYGValueAuto = {0, YGUnitAuto};
const std::array<YGValue, YGEdgeCount> kYGDefaultEdgeValuesUnit = {
{kYGValueUndefined,
@@ -39,9 +39,9 @@ YGStyle::YGStyle()
flexWrap(YGWrapNoWrap),
overflow(YGOverflowVisible),
display(YGDisplayFlex),
flex(YGUndefined),
flexGrow(YGUndefined),
flexShrink(YGUndefined),
flex(YGFloatOptional()),
flexGrow(YGFloatOptional()),
flexShrink(YGFloatOptional()),
flexBasis(kYGValueAuto),
margin(kYGDefaultEdgeValuesUnit),
position(kYGDefaultEdgeValuesUnit),
@@ -50,7 +50,7 @@ YGStyle::YGStyle()
dimensions(kYGDefaultDimensionValuesAutoUnit),
minDimensions(kYGDefaultDimensionValuesUnit),
maxDimensions(kYGDefaultDimensionValuesUnit),
aspectRatio(YGUndefined) {}
aspectRatio(YGFloatOptional()) {}
// Yoga specific properties, not compatible with flexbox specification
bool YGStyle::operator==(const YGStyle& style) {
@@ -69,25 +69,31 @@ bool YGStyle::operator==(const YGStyle& style) {
YGValueArrayEqual(minDimensions, style.minDimensions) &&
YGValueArrayEqual(maxDimensions, style.maxDimensions);
if (!(YGFloatIsUndefined(flex) && YGFloatIsUndefined(style.flex))) {
areNonFloatValuesEqual = areNonFloatValuesEqual && flex == style.flex;
areNonFloatValuesEqual =
areNonFloatValuesEqual && flex.isUndefined() == style.flex.isUndefined();
if (areNonFloatValuesEqual && !flex.isUndefined() &&
!style.flex.isUndefined()) {
areNonFloatValuesEqual =
areNonFloatValuesEqual && flex.getValue() == style.flex.getValue();
}
if (!(YGFloatIsUndefined(flexGrow) && YGFloatIsUndefined(style.flexGrow))) {
areNonFloatValuesEqual =
areNonFloatValuesEqual && flexGrow == style.flexGrow;
areNonFloatValuesEqual = areNonFloatValuesEqual &&
flexGrow.isUndefined() == style.flexGrow.isUndefined();
if (areNonFloatValuesEqual && !flexGrow.isUndefined()) {
areNonFloatValuesEqual = areNonFloatValuesEqual &&
flexGrow.getValue() == style.flexGrow.getValue();
}
if (!(YGFloatIsUndefined(flexShrink) &&
YGFloatIsUndefined(style.flexShrink))) {
areNonFloatValuesEqual =
areNonFloatValuesEqual && flexShrink == style.flexShrink;
areNonFloatValuesEqual = areNonFloatValuesEqual &&
flexShrink.isUndefined() == style.flexShrink.isUndefined();
if (areNonFloatValuesEqual && !style.flexShrink.isUndefined()) {
areNonFloatValuesEqual = areNonFloatValuesEqual &&
flexShrink.getValue() == style.flexShrink.getValue();
}
if (!(YGFloatIsUndefined(aspectRatio) &&
YGFloatIsUndefined(style.aspectRatio))) {
areNonFloatValuesEqual =
areNonFloatValuesEqual && aspectRatio == style.aspectRatio;
if (!(aspectRatio.isUndefined() && style.aspectRatio.isUndefined())) {
areNonFloatValuesEqual = areNonFloatValuesEqual &&
aspectRatio.getValue() == style.aspectRatio.getValue();
}
return areNonFloatValuesEqual;

View File

@@ -6,6 +6,7 @@
*/
#pragma once
#include "YGFloatOptional.h"
#include "Yoga-internal.h"
#include "Yoga.h"
@@ -20,9 +21,9 @@ struct YGStyle {
YGWrap flexWrap;
YGOverflow overflow;
YGDisplay display;
float flex;
float flexGrow;
float flexShrink;
YGFloatOptional flex;
YGFloatOptional flexGrow;
YGFloatOptional flexShrink;
YGValue flexBasis;
std::array<YGValue, YGEdgeCount> margin;
std::array<YGValue, YGEdgeCount> position;
@@ -31,7 +32,7 @@ struct YGStyle {
std::array<YGValue, 2> dimensions;
std::array<YGValue, 2> minDimensions;
std::array<YGValue, 2> maxDimensions;
float aspectRatio;
YGFloatOptional aspectRatio;
YGStyle();
// Yoga specific properties, not compatible with flexbox specification

View File

@@ -87,16 +87,6 @@ struct YGCachedMeasurement {
// layouts should not require more than 16 entries to fit within the cache.
#define YG_MAX_CACHED_RESULT_COUNT 16
struct YGConfig {
bool experimentalFeatures[YGExperimentalFeatureCount + 1];
bool useWebDefaults;
bool useLegacyStretchBehaviour;
bool shouldDiffLayoutWithoutLegacyStretchBehaviour;
float pointScaleFactor;
YGLogger logger;
YGNodeClonedFunc cloneNodeCallback;
void* context;
};
static const float kDefaultFlexGrow = 0.0f;
static const float kDefaultFlexShrink = 0.0f;

File diff suppressed because it is too large Load Diff

View File

@@ -62,10 +62,8 @@ typedef int (*YGLogger)(const YGConfigRef config,
YGLogLevel level,
const char *format,
va_list args);
typedef void (*YGNodeClonedFunc)(YGNodeRef oldNode,
YGNodeRef newNode,
YGNodeRef parent,
int childIndex);
typedef YGNodeRef (
*YGCloneNodeFunc)(YGNodeRef oldNode, YGNodeRef owner, int childIndex);
// YGNode
WIN_EXPORT YGNodeRef YGNodeNew(void);
@@ -79,16 +77,32 @@ WIN_EXPORT int32_t YGNodeGetInstanceCount(void);
WIN_EXPORT void YGNodeInsertChild(const YGNodeRef node,
const YGNodeRef child,
const uint32_t index);
// This function inserts the child YGNodeRef as a children of the node received
// by parameter and set the Owner of the child object to null. This function is
// expected to be called when using Yoga in persistent mode in order to share a
// YGNodeRef object as a child of two different Yoga trees. The child YGNodeRef
// is expected to be referenced from its original owner and from a clone of its
// original owner.
WIN_EXPORT void YGNodeInsertSharedChild(
const YGNodeRef node,
const YGNodeRef child,
const uint32_t index);
WIN_EXPORT void YGNodeRemoveChild(const YGNodeRef node, const YGNodeRef child);
WIN_EXPORT void YGNodeRemoveAllChildren(const YGNodeRef node);
WIN_EXPORT YGNodeRef YGNodeGetChild(const YGNodeRef node, const uint32_t index);
WIN_EXPORT YGNodeRef YGNodeGetOwner(const YGNodeRef node);
WIN_EXPORT YGNodeRef YGNodeGetParent(const YGNodeRef node);
WIN_EXPORT uint32_t YGNodeGetChildCount(const YGNodeRef node);
WIN_EXPORT void YGNodeSetChildren(
YGNodeRef const owner,
const YGNodeRef children[],
const uint32_t count);
WIN_EXPORT void YGNodeCalculateLayout(const YGNodeRef node,
const float availableWidth,
const float availableHeight,
const YGDirection parentDirection);
const YGDirection ownerDirection);
// Mark a node as dirty. Only valid for nodes with a custom measure function
// set.
@@ -190,7 +204,6 @@ YG_NODE_STYLE_PROPERTY(YGPositionType, PositionType, positionType);
YG_NODE_STYLE_PROPERTY(YGWrap, FlexWrap, flexWrap);
YG_NODE_STYLE_PROPERTY(YGOverflow, Overflow, overflow);
YG_NODE_STYLE_PROPERTY(YGDisplay, Display, display);
YG_NODE_STYLE_PROPERTY(float, Flex, flex);
YG_NODE_STYLE_PROPERTY(float, FlexGrow, flexGrow);
YG_NODE_STYLE_PROPERTY(float, FlexShrink, flexShrink);
@@ -232,6 +245,7 @@ YG_NODE_LAYOUT_PROPERTY(float, Width);
YG_NODE_LAYOUT_PROPERTY(float, Height);
YG_NODE_LAYOUT_PROPERTY(YGDirection, Direction);
YG_NODE_LAYOUT_PROPERTY(bool, HadOverflow);
bool YGNodeLayoutGetDidLegacyStretchFlagAffectLayout(const YGNodeRef node);
// Get the computed values for these nodes after performing layout. If they were set using
// point values then the returned value will be the same as YGNodeStyleGetXXX. However if
@@ -249,10 +263,12 @@ WIN_EXPORT void YGAssertWithNode(const YGNodeRef node, const bool condition, con
WIN_EXPORT void YGAssertWithConfig(const YGConfigRef config,
const bool condition,
const char *message);
// Set this to number of pixels in 1 point to round calculation results
// If you want to avoid rounding - set PointScaleFactor to 0
WIN_EXPORT void YGConfigSetPointScaleFactor(const YGConfigRef config, const float pixelsInPoint);
void YGConfigSetShouldDiffLayoutWithoutLegacyStretchBehaviour(
const YGConfigRef config,
const bool shouldDiffLayout);
// Yoga previously had an error where containers would take the maximum space possible instead of
// the minimum
@@ -280,8 +296,8 @@ WIN_EXPORT bool YGConfigIsExperimentalFeatureEnabled(const YGConfigRef config,
WIN_EXPORT void YGConfigSetUseWebDefaults(const YGConfigRef config, const bool enabled);
WIN_EXPORT bool YGConfigGetUseWebDefaults(const YGConfigRef config);
WIN_EXPORT void YGConfigSetNodeClonedFunc(const YGConfigRef config,
const YGNodeClonedFunc callback);
WIN_EXPORT void YGConfigSetCloneNodeFunc(const YGConfigRef config,
const YGCloneNodeFunc callback);
// Export only for C#
WIN_EXPORT YGConfigRef YGConfigGetDefault(void);
@@ -296,3 +312,17 @@ WIN_EXPORT float YGRoundValueToPixelGrid(
const bool forceFloor);
YG_EXTERN_C_END
#ifdef __cplusplus
#include <functional>
#include <vector>
// Calls f on each node in the tree including the given node argument.
extern void YGTraversePreOrder(YGNodeRef const node, std::function<void(YGNodeRef node)>&& f);
extern void YGNodeSetChildren(
YGNodeRef const owner,
const std::vector<YGNodeRef>& children);
#endif

View File

@@ -1,115 +1,192 @@
"""Provides macros for working with yoga library."""
YOGA_ROOTS = ['//...']
JAVA_TARGET = '//java:java'
INFER_ANNOTATIONS_TARGET = '//lib/infer-annotations:infer-annotations'
JSR_305_TARGET = '//lib/jsr-305:jsr-305'
JUNIT_TARGET = '//lib/junit:junit'
PROGRUARD_ANNOTATIONS_TARGET = '//java/proguard-annotations/src/main/java/com/facebook/proguard/annotations:annotations'
SOLOADER_TARGET = '//lib/soloader:soloader'
GTEST_TARGET = '//lib/gtest:gtest'
JNI_TARGET = '//lib/jni:jni'
FBJNI_TARGET = '//lib/fb:fbjni'
FBJNI_JAVA_TARGET = '//lib/fb/src/main/java/com/facebook/jni:jni'
APPCOMPAT_TARGET = '//lib/appcompat:appcompat'
ANDROID = ''
ANDROID_SUPPORT_TARGET = '//lib/android-support:android-support'
ANDROID_TARGET = '//android:android'
ANDROID_JAVA_TARGET = '//android/src/main/java/com/facebook/yoga/android:android'
ANDROID_RES_TARGET = '//android:res'
ANDROID_SAMPLE_JAVA_TARGET = '//android/sample/java/com/facebook/samples/yoga:yoga'
ANDROID_SAMPLE_RES_TARGET = '//android/sample:res'
YOGA_ROOTS = ["//..."]
JAVA_TARGET = "//java:java"
INFER_ANNOTATIONS_TARGET = "//lib/infer-annotations:infer-annotations"
JSR_305_TARGET = "//lib/jsr-305:jsr-305"
JUNIT_TARGET = "//lib/junit:junit"
PROGRUARD_ANNOTATIONS_TARGET = "//java/proguard-annotations/src/main/java/com/facebook/proguard/annotations:annotations"
SOLOADER_TARGET = "//lib/soloader:soloader"
GTEST_TARGET = "//lib/gtest:gtest"
JNI_TARGET = "//lib/jni:jni"
FBJNI_TARGET = "//lib/fb:fbjni"
FBJNI_JAVA_TARGET = "//lib/fb/src/main/java/com/facebook/jni:jni"
APPCOMPAT_TARGET = "//lib/appcompat:appcompat"
APPLE = ""
ANDROID = ""
ANDROID_SUPPORT_TARGET = "//lib/android-support:android-support"
ANDROID_TARGET = "//android:android"
ANDROID_JAVA_TARGET = "//android/src/main/java/com/facebook/yoga/android:android"
ANDROID_RES_TARGET = "//android:res"
ANDROID_SAMPLE_JAVA_TARGET = "//android/sample/java/com/facebook/samples/yoga:yoga"
ANDROID_SAMPLE_RES_TARGET = "//android/sample:res"
CXX_LIBRARY_WHITELIST = [
'//:yoga',
'//lib/fb:fbjni',
'//java:jni',
"//:yoga",
"//lib/fb:fbjni",
"//java:jni",
]
BASE_COMPILER_FLAGS = [
'-fno-omit-frame-pointer',
'-fexceptions',
'-Wall',
'-Werror',
'-O3',
"-fno-omit-frame-pointer",
"-fexceptions",
"-Wall",
"-Werror",
"-O3",
"-ffast-math",
]
LIBRARY_COMPILER_FLAGS = BASE_COMPILER_FLAGS + [
'-fPIC',
"-fPIC",
]
def _paths_join(path, *others):
"""Joins one or more path components."""
result = path
for p in others:
if p.startswith("/"): # absolute
result = p
elif not result or result.endswith("/"):
result += p
else:
result += "/" + p
return result
def subdir_glob(glob_specs, exclude = None, prefix = ""):
"""Returns a dict of sub-directory relative paths to full paths.
The subdir_glob() function is useful for defining header maps for C/C++
libraries which should be relative the given sub-directory.
Given a list of tuples, the form of (relative-sub-directory, glob-pattern),
it returns a dict of sub-directory relative paths to full paths.
Please refer to native.glob() for explanations and examples of the pattern.
Args:
glob_specs: The array of tuples in form of
(relative-sub-directory, glob-pattern inside relative-sub-directory).
type: List[Tuple[str, str]]
exclude: A list of patterns to identify files that should be removed
from the set specified by the first argument. Defaults to [].
type: Optional[List[str]]
prefix: If is not None, prepends it to each key in the dictionary.
Defaults to None.
type: Optional[str]
Returns:
A dict of sub-directory relative paths to full paths.
"""
if exclude == None:
exclude = []
results = []
for dirpath, glob_pattern in glob_specs:
results.append(
_single_subdir_glob(dirpath, glob_pattern, exclude, prefix),
)
return _merge_maps(*results)
def _merge_maps(*file_maps):
result = {}
for file_map in file_maps:
for key in file_map:
if key in result and result[key] != file_map[key]:
fail(
"Conflicting files in file search paths. " +
"\"%s\" maps to both \"%s\" and \"%s\"." %
(key, result[key], file_map[key]),
)
result[key] = file_map[key]
return result
def _single_subdir_glob(dirpath, glob_pattern, exclude = None, prefix = None):
if exclude == None:
exclude = []
results = {}
files = native.glob([_paths_join(dirpath, glob_pattern)], exclude = exclude)
for f in files:
if dirpath:
key = f[len(dirpath) + 1:]
else:
key = f
if prefix:
key = _paths_join(prefix, key)
results[key] = f
return results
def yoga_dep(dep):
return '//' + dep
return "//" + dep
def yoga_android_aar(*args, **kwargs):
native.android_aar(*args, **kwargs)
_original_android_aar = android_aar
def android_aar(*args, **kwargs):
_original_android_aar(*args, **kwargs)
def yoga_android_binary(*args, **kwargs):
native.android_binary(*args, **kwargs)
def yoga_android_library(*args, **kwargs):
native.android_library(*args, **kwargs)
_original_android_binary = android_binary
def android_binary(*args, **kwargs):
_original_android_binary(*args, **kwargs)
def yoga_android_resource(*args, **kwargs):
native.android_resource(*args, **kwargs)
def yoga_apple_library(*args, **kwargs):
native.apple_library(*args, **kwargs)
_original_android_library = android_library
def android_library(*args, **kwargs):
_original_android_library(*args, **kwargs)
def yoga_apple_test(*args, **kwargs):
native.apple_test(*args, **kwargs)
def yoga_cxx_binary(*args, **kwargs):
kwargs.pop("platforms", None)
native.cxx_binary(*args, **kwargs)
_original_android_resource = android_resource
def android_resource(*args, **kwargs):
_original_android_resource(*args, **kwargs)
def yoga_cxx_library(*args, **kwargs):
# Currently unused
kwargs.pop("platforms", None)
native.cxx_library(*args, **kwargs)
def yoga_cxx_test(*args, **kwargs):
native.cxx_test(*args, **kwargs)
_original_apple_library = apple_library
def apple_library(*args, **kwargs):
_original_apple_library(*args, **kwargs)
def yoga_java_binary(*args, **kwargs):
native.java_binary(*args, **kwargs)
def yoga_java_library(*args, **kwargs):
native.java_library(*args, **kwargs)
_original_apple_test = apple_test
def apple_test(*args, **kwargs):
_original_apple_test(*args, **kwargs)
def yoga_java_test(*args, **kwargs):
native.java_test(*args, **kwargs)
def yoga_prebuilt_cxx_library(*args, **kwargs):
native.prebuilt_cxx_library(*args, **kwargs)
_original_cxx_library = cxx_library
def cxx_library(*args, **kwargs):
# Currently unused
kwargs.pop("platforms", None)
_original_cxx_library(*args, **kwargs)
_original_cxx_test = cxx_test
def cxx_test(*args, **kwargs):
_original_cxx_test(*args, **kwargs)
_original_java_binary = java_binary
def java_binary(*args, **kwargs):
_original_java_binary(*args, **kwargs)
_original_java_library = java_library
def java_library(*args, **kwargs):
_original_java_library(*args, **kwargs)
_original_java_test = java_test
def java_test(*args, **kwargs):
_original_java_test(*args, **kwargs)
_original_prebuilt_cxx_library = prebuilt_cxx_library
def prebuilt_cxx_library(*args, **kwargs):
_original_prebuilt_cxx_library(*args, **kwargs)
_original_prebuilt_jar = prebuilt_jar
def prebuilt_jar(*args, **kwargs):
_original_prebuilt_jar(*args, **kwargs)
def yoga_prebuilt_jar(*args, **kwargs):
native.prebuilt_jar(*args, **kwargs)
def is_apple_platform():
return True
return True