Esempio n. 1
0
static void layoutNodeImpl(css_node_t *node, float parentMaxWidth) {
  /** START_GENERATED **/
  css_flex_direction_t mainAxis = getFlexDirection(node);
  css_flex_direction_t crossAxis = mainAxis == CSS_FLEX_DIRECTION_ROW ?
    CSS_FLEX_DIRECTION_COLUMN :
    CSS_FLEX_DIRECTION_ROW;

  // Handle width and height style attributes
  setDimensionFromStyle(node, mainAxis);
  setDimensionFromStyle(node, crossAxis);

  // The position is set by the parent, but we need to complete it with a
  // delta composed of the margin and left/top/right/bottom
  node->layout.position[leading[mainAxis]] += getMargin(node, leading[mainAxis]) +
    getRelativePosition(node, mainAxis);
  node->layout.position[leading[crossAxis]] += getMargin(node, leading[crossAxis]) +
    getRelativePosition(node, crossAxis);

  if (isMeasureDefined(node)) {
    float width = CSS_UNDEFINED;
    if (isDimDefined(node, CSS_FLEX_DIRECTION_ROW)) {
      width = node->style.dimensions[CSS_WIDTH];
    } else if (!isUndefined(node->layout.dimensions[dim[CSS_FLEX_DIRECTION_ROW]])) {
      width = node->layout.dimensions[dim[CSS_FLEX_DIRECTION_ROW]];
    } else {
      width = parentMaxWidth -
        getMarginAxis(node, CSS_FLEX_DIRECTION_ROW);
    }
    width -= getPaddingAndBorderAxis(node, CSS_FLEX_DIRECTION_ROW);

    // We only need to give a dimension for the text if we haven't got any
    // for it computed yet. It can either be from the style attribute or because
    // the element is flexible.
    bool isRowUndefined = !isDimDefined(node, CSS_FLEX_DIRECTION_ROW) &&
      isUndefined(node->layout.dimensions[dim[CSS_FLEX_DIRECTION_ROW]]);
    bool isColumnUndefined = !isDimDefined(node, CSS_FLEX_DIRECTION_COLUMN) &&
      isUndefined(node->layout.dimensions[dim[CSS_FLEX_DIRECTION_COLUMN]]);

    // Let's not measure the text if we already know both dimensions
    if (isRowUndefined || isColumnUndefined) {
      css_dim_t measure_dim = node->measure(
        node->context,
        width
      );
      if (isRowUndefined) {
        node->layout.dimensions[CSS_WIDTH] = measure_dim.dimensions[CSS_WIDTH] +
          getPaddingAndBorderAxis(node, CSS_FLEX_DIRECTION_ROW);
      }
      if (isColumnUndefined) {
        node->layout.dimensions[CSS_HEIGHT] = measure_dim.dimensions[CSS_HEIGHT] +
          getPaddingAndBorderAxis(node, CSS_FLEX_DIRECTION_COLUMN);
      }
    }
    return;
  }

  // Pre-fill some dimensions straight from the parent
  for (int i = 0; i < node->children_count; ++i) {
    css_node_t* child = node->get_child(node->context, i);
    // Pre-fill cross axis dimensions when the child is using stretch before
    // we call the recursive layout pass
    if (getAlignItem(node, child) == CSS_ALIGN_STRETCH &&
        getPositionType(child) == CSS_POSITION_RELATIVE &&
        !isUndefined(node->layout.dimensions[dim[crossAxis]]) &&
        !isDimDefined(child, crossAxis)) {
      child->layout.dimensions[dim[crossAxis]] = fmaxf(
        node->layout.dimensions[dim[crossAxis]] -
          getPaddingAndBorderAxis(node, crossAxis) -
          getMarginAxis(child, crossAxis),
        // You never want to go smaller than padding
        getPaddingAndBorderAxis(child, crossAxis)
      );
    } else if (getPositionType(child) == CSS_POSITION_ABSOLUTE) {
      // Pre-fill dimensions when using absolute position and both offsets for the axis are defined (either both
      // left and right or top and bottom).
      for (int ii = 0; ii < 2; ii++) {
        css_flex_direction_t axis = (ii != 0) ? CSS_FLEX_DIRECTION_ROW : CSS_FLEX_DIRECTION_COLUMN;
        if (!isUndefined(node->layout.dimensions[dim[axis]]) &&
            !isDimDefined(child, axis) &&
            isPosDefined(child, leading[axis]) &&
            isPosDefined(child, trailing[axis])) {
          child->layout.dimensions[dim[axis]] = fmaxf(
            node->layout.dimensions[dim[axis]] -
            getPaddingAndBorderAxis(node, axis) -
            getMarginAxis(child, axis) -
            getPosition(child, leading[axis]) -
            getPosition(child, trailing[axis]),
            // You never want to go smaller than padding
            getPaddingAndBorderAxis(child, axis)
          );
        }
      }
    }
  }

  float definedMainDim = CSS_UNDEFINED;
  if (!isUndefined(node->layout.dimensions[dim[mainAxis]])) {
    definedMainDim = node->layout.dimensions[dim[mainAxis]] -
        getPaddingAndBorderAxis(node, mainAxis);
  }

  // We want to execute the next two loops one per line with flex-wrap
  int startLine = 0;
  int endLine = 0;
  int nextLine = 0;
  // We aggregate the total dimensions of the container in those two variables
  float linesCrossDim = 0;
  float linesMainDim = 0;
  while (endLine != node->children_count) {
    // <Loop A> Layout non flexible children and count children by type

    // mainContentDim is accumulation of the dimensions and margin of all the
    // non flexible children. This will be used in order to either set the
    // dimensions of the node if none already exist, or to compute the
    // remaining space left for the flexible children.
    float mainContentDim = 0;

    // There are three kind of children, non flexible, flexible and absolute.
    // We need to know how many there are in order to distribute the space.
    int flexibleChildrenCount = 0;
    float totalFlexible = 0;
    int nonFlexibleChildrenCount = 0;
    for (int i = startLine; i < node->children_count; ++i) {
      css_node_t* child = node->get_child(node->context, i);
      float nextContentDim = 0;

      // It only makes sense to consider a child flexible if we have a computed
      // dimension for the node->
      if (!isUndefined(node->layout.dimensions[dim[mainAxis]]) && isFlex(child)) {
        flexibleChildrenCount++;
        totalFlexible += getFlex(child);

        // Even if we don't know its exact size yet, we already know the padding,
        // border and margin. We'll use this partial information to compute the
        // remaining space.
        nextContentDim = getPaddingAndBorderAxis(child, mainAxis) +
          getMarginAxis(child, mainAxis);

      } else {
        float maxWidth = CSS_UNDEFINED;
        if (mainAxis == CSS_FLEX_DIRECTION_ROW) {
          // do nothing
        } else if (isDimDefined(node, CSS_FLEX_DIRECTION_ROW)) {
          maxWidth = node->layout.dimensions[dim[CSS_FLEX_DIRECTION_ROW]] -
            getPaddingAndBorderAxis(node, CSS_FLEX_DIRECTION_ROW);
        } else {
          maxWidth = parentMaxWidth -
            getMarginAxis(node, CSS_FLEX_DIRECTION_ROW) -
            getPaddingAndBorderAxis(node, CSS_FLEX_DIRECTION_ROW);
        }

        // This is the main recursive call. We layout non flexible children.
        if (nextLine == 0) {
          layoutNode(child, maxWidth);
        }

        // Absolute positioned elements do not take part of the layout, so we
        // don't use them to compute mainContentDim
        if (getPositionType(child) == CSS_POSITION_RELATIVE) {
          nonFlexibleChildrenCount++;
          // At this point we know the final size and margin of the element.
          nextContentDim = getDimWithMargin(child, mainAxis);
        }
      }

      // The element we are about to add would make us go to the next line
      if (isFlexWrap(node) &&
          !isUndefined(node->layout.dimensions[dim[mainAxis]]) &&
          mainContentDim + nextContentDim > definedMainDim) {
        nextLine = i + 1;
        break;
      }
      nextLine = 0;
      mainContentDim += nextContentDim;
      endLine = i + 1;
    }

    // <Loop B> Layout flexible children and allocate empty space

    // In order to position the elements in the main axis, we have two
    // controls. The space between the beginning and the first element
    // and the space between each two elements.
    float leadingMainDim = 0;
    float betweenMainDim = 0;

    // The remaining available space that needs to be allocated
    float remainingMainDim = 0;
    if (!isUndefined(node->layout.dimensions[dim[mainAxis]])) {
      remainingMainDim = definedMainDim - mainContentDim;
    } else {
      remainingMainDim = fmaxf(mainContentDim, 0) - mainContentDim;
    }

    // If there are flexible children in the mix, they are going to fill the
    // remaining space
    if (flexibleChildrenCount != 0) {
      float flexibleMainDim = remainingMainDim / totalFlexible;

      // The non flexible children can overflow the container, in this case
      // we should just assume that there is no space available.
      if (flexibleMainDim < 0) {
        flexibleMainDim = 0;
      }
      // We iterate over the full array and only apply the action on flexible
      // children. This is faster than actually allocating a new array that
      // contains only flexible children.
      for (int i = startLine; i < endLine; ++i) {
        css_node_t* child = node->get_child(node->context, i);
        if (isFlex(child)) {
          // At this point we know the final size of the element in the main
          // dimension
          child->layout.dimensions[dim[mainAxis]] = flexibleMainDim * getFlex(child) +
            getPaddingAndBorderAxis(child, mainAxis);

          float maxWidth = CSS_UNDEFINED;
          if (mainAxis == CSS_FLEX_DIRECTION_ROW) {
            // do nothing
          } else if (isDimDefined(node, CSS_FLEX_DIRECTION_ROW)) {
            maxWidth = node->layout.dimensions[dim[CSS_FLEX_DIRECTION_ROW]] -
              getPaddingAndBorderAxis(node, CSS_FLEX_DIRECTION_ROW);
          } else {
            maxWidth = parentMaxWidth -
              getMarginAxis(node, CSS_FLEX_DIRECTION_ROW) -
              getPaddingAndBorderAxis(node, CSS_FLEX_DIRECTION_ROW);
          }

          // And we recursively call the layout algorithm for this child
          layoutNode(child, maxWidth);
        }
      }

    // We use justifyContent to figure out how to allocate the remaining
    // space available
    } else {
      css_justify_t justifyContent = getJustifyContent(node);
      if (justifyContent == CSS_JUSTIFY_FLEX_START) {
        // Do nothing
      } else if (justifyContent == CSS_JUSTIFY_CENTER) {
        leadingMainDim = remainingMainDim / 2;
      } else if (justifyContent == CSS_JUSTIFY_FLEX_END) {
        leadingMainDim = remainingMainDim;
      } else if (justifyContent == CSS_JUSTIFY_SPACE_BETWEEN) {
        remainingMainDim = fmaxf(remainingMainDim, 0);
        if (flexibleChildrenCount + nonFlexibleChildrenCount - 1 != 0) {
          betweenMainDim = remainingMainDim /
            (flexibleChildrenCount + nonFlexibleChildrenCount - 1);
        } else {
          betweenMainDim = 0;
        }
      } else if (justifyContent == CSS_JUSTIFY_SPACE_AROUND) {
        // Space on the edges is half of the space between elements
        betweenMainDim = remainingMainDim /
          (flexibleChildrenCount + nonFlexibleChildrenCount);
        leadingMainDim = betweenMainDim / 2;
      }
    }

    // <Loop C> Position elements in the main axis and compute dimensions

    // At this point, all the children have their dimensions set. We need to
    // find their position. In order to do that, we accumulate data in
    // variables that are also useful to compute the total dimensions of the
    // container!
    float crossDim = 0;
    float mainDim = leadingMainDim +
      getPaddingAndBorder(node, leading[mainAxis]);

    for (int i = startLine; i < endLine; ++i) {
      css_node_t* child = node->get_child(node->context, i);

      if (getPositionType(child) == CSS_POSITION_ABSOLUTE &&
          isPosDefined(child, leading[mainAxis])) {
        // In case the child is position absolute and has left/top being
        // defined, we override the position to whatever the user said
        // (and margin/border).
        child->layout.position[pos[mainAxis]] = getPosition(child, leading[mainAxis]) +
          getBorder(node, leading[mainAxis]) +
          getMargin(child, leading[mainAxis]);
      } else {
        // If the child is position absolute (without top/left) or relative,
        // we put it at the current accumulated offset.
        child->layout.position[pos[mainAxis]] += mainDim;
      }

      // Now that we placed the element, we need to update the variables
      // We only need to do that for relative elements. Absolute elements
      // do not take part in that phase.
      if (getPositionType(child) == CSS_POSITION_RELATIVE) {
        // The main dimension is the sum of all the elements dimension plus
        // the spacing.
        mainDim += betweenMainDim + getDimWithMargin(child, mainAxis);
        // The cross dimension is the max of the elements dimension since there
        // can only be one element in that cross dimension.
        crossDim = fmaxf(crossDim, getDimWithMargin(child, crossAxis));
      }
    }

    float containerMainAxis = node->layout.dimensions[dim[mainAxis]];
    // If the user didn't specify a width or height, and it has not been set
    // by the container, then we set it via the children.
    if (isUndefined(node->layout.dimensions[dim[mainAxis]])) {
      containerMainAxis = fmaxf(
        // We're missing the last padding at this point to get the final
        // dimension
        mainDim + getPaddingAndBorder(node, trailing[mainAxis]),
        // We can never assign a width smaller than the padding and borders
        getPaddingAndBorderAxis(node, mainAxis)
      );
    }

    float containerCrossAxis = node->layout.dimensions[dim[crossAxis]];
    if (isUndefined(node->layout.dimensions[dim[crossAxis]])) {
      containerCrossAxis = fmaxf(
        // For the cross dim, we add both sides at the end because the value
        // is aggregate via a max function. Intermediate negative values
        // can mess this computation otherwise
        crossDim + getPaddingAndBorderAxis(node, crossAxis),
        getPaddingAndBorderAxis(node, crossAxis)
      );
    }

    // <Loop D> Position elements in the cross axis

    for (int i = startLine; i < endLine; ++i) {
      css_node_t* child = node->get_child(node->context, i);

      if (getPositionType(child) == CSS_POSITION_ABSOLUTE &&
          isPosDefined(child, leading[crossAxis])) {
        // In case the child is absolutely positionned and has a
        // top/left/bottom/right being set, we override all the previously
        // computed positions to set it correctly.
        child->layout.position[pos[crossAxis]] = getPosition(child, leading[crossAxis]) +
          getBorder(node, leading[crossAxis]) +
          getMargin(child, leading[crossAxis]);

      } else {
        float leadingCrossDim = getPaddingAndBorder(node, leading[crossAxis]);

        // For a relative children, we're either using alignItems (parent) or
        // alignSelf (child) in order to determine the position in the cross axis
        if (getPositionType(child) == CSS_POSITION_RELATIVE) {
          css_align_t alignItem = getAlignItem(node, child);
          if (alignItem == CSS_ALIGN_FLEX_START) {
            // Do nothing
          } else if (alignItem == CSS_ALIGN_STRETCH) {
            // You can only stretch if the dimension has not already been set
            // previously.
            if (!isDimDefined(child, crossAxis)) {
              child->layout.dimensions[dim[crossAxis]] = fmaxf(
                containerCrossAxis -
                  getPaddingAndBorderAxis(node, crossAxis) -
                  getMarginAxis(child, crossAxis),
                // You never want to go smaller than padding
                getPaddingAndBorderAxis(child, crossAxis)
              );
            }
          } else {
            // The remaining space between the parent dimensions+padding and child
            // dimensions+margin.
            float remainingCrossDim = containerCrossAxis -
              getPaddingAndBorderAxis(node, crossAxis) -
              getDimWithMargin(child, crossAxis);

            if (alignItem == CSS_ALIGN_CENTER) {
              leadingCrossDim += remainingCrossDim / 2;
            } else { // CSS_ALIGN_FLEX_END
              leadingCrossDim += remainingCrossDim;
            }
          }
        }

        // And we apply the position
        child->layout.position[pos[crossAxis]] += linesCrossDim + leadingCrossDim;
      }
    }

    linesCrossDim += crossDim;
    linesMainDim = fmaxf(linesMainDim, mainDim);
    startLine = endLine;
  }

  // If the user didn't specify a width or height, and it has not been set
  // by the container, then we set it via the children.
  if (isUndefined(node->layout.dimensions[dim[mainAxis]])) {
    node->layout.dimensions[dim[mainAxis]] = fmaxf(
      // We're missing the last padding at this point to get the final
      // dimension
      linesMainDim + getPaddingAndBorder(node, trailing[mainAxis]),
      // We can never assign a width smaller than the padding and borders
      getPaddingAndBorderAxis(node, mainAxis)
    );
  }

  if (isUndefined(node->layout.dimensions[dim[crossAxis]])) {
    node->layout.dimensions[dim[crossAxis]] = fmaxf(
      // For the cross dim, we add both sides at the end because the value
      // is aggregate via a max function. Intermediate negative values
      // can mess this computation otherwise
      linesCrossDim + getPaddingAndBorderAxis(node, crossAxis),
      getPaddingAndBorderAxis(node, crossAxis)
    );
  }

  // <Loop E> Calculate dimensions for absolutely positioned elements

  for (int i = 0; i < node->children_count; ++i) {
    css_node_t* child = node->get_child(node->context, i);
    if (getPositionType(child) == CSS_POSITION_ABSOLUTE) {
      // Pre-fill dimensions when using absolute position and both offsets for the axis are defined (either both
      // left and right or top and bottom).
      for (int ii = 0; ii < 2; ii++) {
        css_flex_direction_t axis = (ii != 0) ? CSS_FLEX_DIRECTION_ROW : CSS_FLEX_DIRECTION_COLUMN;
        if (!isUndefined(node->layout.dimensions[dim[axis]]) &&
            !isDimDefined(child, axis) &&
            isPosDefined(child, leading[axis]) &&
            isPosDefined(child, trailing[axis])) {
          child->layout.dimensions[dim[axis]] = fmaxf(
            node->layout.dimensions[dim[axis]] -
            getPaddingAndBorderAxis(node, axis) -
            getMarginAxis(child, axis) -
            getPosition(child, leading[axis]) -
            getPosition(child, trailing[axis]),
            // You never want to go smaller than padding
            getPaddingAndBorderAxis(child, axis)
          );
        }
      }
      for (int ii = 0; ii < 2; ii++) {
        css_flex_direction_t axis = (ii != 0) ? CSS_FLEX_DIRECTION_ROW : CSS_FLEX_DIRECTION_COLUMN;
        if (isPosDefined(child, trailing[axis]) &&
            !isPosDefined(child, leading[axis])) {
          child->layout.position[leading[axis]] =
            node->layout.dimensions[dim[axis]] -
            child->layout.dimensions[dim[axis]] -
            getPosition(child, trailing[axis]);
        }
      }
    }
  }
  /** END_GENERATED **/
}
void ofxDOMFlexBoxLayout::align(FlexDirection direction){

	bool horizontal = direction == FlexDirection::ROW;

	float paddingHorizontal = DOMLH::getPaddingHorizontal(_parent);
	float paddingVertical = DOMLH::getPaddingVertical(_parent);

	float wParent = ofGetWidth();
	float hParent = ofGetHeight();
	if(_parent->parent()){
		wParent = _parent->getSizeByParent().x;
		hParent = _parent->getSizeByParent().y;
	}

	float totalWidth = DOMLH::getDesiredWidthStretched(_parent, wParent) - paddingHorizontal;
	float totalHeight = DOMLH::getDesiredHeightStretched(_parent, hParent) - paddingVertical;

//	if(ofxGuiElement* el = dynamic_cast<ofxGuiElement*>(_parent)){
//		cout << el->getName() << " total size: " << totalWidth << " " << totalHeight << endl;
//	}

	vector<vector<DOM::Element*>> lines;
	vector<vector<DOM::Element*>> noFlexItems;
	vector<vector<DOM::Element*>> flexItems;
	vector<vector<float>> flexItemsBasis;
	vector<float> totalSpaceMainAxis;

	float mainAxisSize =  horizontal ? totalWidth : totalHeight;
	float crossAxisSize = horizontal ? totalHeight : totalWidth;

	int linecount = 0;

	if(children().size() > 0){
		//newline
		lines.push_back(vector<DOM::Element*>());
		noFlexItems.push_back(vector<DOM::Element*>());
		flexItems.push_back(vector<DOM::Element*>());
		flexItemsBasis.push_back(vector<float>());
		totalSpaceMainAxis.push_back(mainAxisSize);
	}

	//sort children according to flex attribute and main size of children

	for(unsigned int i = 0; i < children().size(); i++){

		DOM::Element* element = children().at(i);
		float w, h;
		if(horizontal){
			w = DOMLH::getDesiredWidth(element, totalWidth);
			h = DOMLH::getDesiredHeight(element, totalHeight);
		}else{
			w = DOMLH::getDesiredWidth(element, totalWidth);
			h = DOMLH::getDesiredHeight(element, totalHeight);
		}

		float elementMainSize = horizontal ? w : h;
		float elementCrossSize = horizontal ? h : w;

		if(element){
			if(elementFlexing(element)){

//				element->setSizeByParent(totalWidth, totalHeight);

				// set to minimal size on main axis
				if(horizontal){
					element->setSizeByParent(elementMainSize + DOMLH::getMarginHorizontal(element), elementCrossSize + DOMLH::getMarginVertical(element));
					element->setLayoutSize(elementMainSize, elementCrossSize, true);
					elementMainSize = element->getWidth() + DOMLH::getMarginHorizontal(element);
				}else {
					element->setSizeByParent(elementCrossSize + DOMLH::getMarginHorizontal(element), elementMainSize + DOMLH::getMarginVertical(element));
					element->setLayoutSize(elementCrossSize, elementMainSize, true);
					elementMainSize = element->getHeight() + DOMLH::getMarginVertical(element);
				}

				//if element is flexible, add it to the current line and save the items flex basis
				if(element->hasAttribute("_flex")){
					std::string flexval = element->getAttribute<std::string>("_flex");
					if(flexval == "auto"){
						lines.at(linecount).push_back(element);
						flexItems.at(linecount).push_back(element);
						flexItemsBasis.at(linecount).push_back(1);
						continue;
					}
					if(isFloat(ofTrim(flexval))){
						float intflexval = ofToFloat(flexval);
						if(intflexval > 0){
							lines.at(linecount).push_back(element);
							flexItems.at(linecount).push_back(element);
							flexItemsBasis.at(linecount).push_back(intflexval);
							continue;
						}
					}
				}

				// not flexible or no valid flex attribute, not flexing on main axis

				// add to new line if it does not fit and flex-wrap is on
				if((int)totalSpaceMainAxis.at(linecount) - (int)elementMainSize < 0){
					FlexWrap _wrap = getFlexWrap(_parent);
					if(_wrap == FlexWrap::NOWRAP || i == 0){
						//no new line
					}else{
						//new line
						linecount++;
						lines.push_back(vector<DOM::Element*>());
						flexItems.push_back(vector<DOM::Element*>());
						flexItemsBasis.push_back(vector<float>());
						totalSpaceMainAxis.push_back(mainAxisSize);
					}
				}

				lines.at(linecount).push_back(element);
				totalSpaceMainAxis.at(linecount) -= elementMainSize;
			}else {
				//set an absolute positioned element to its desired independent size
				if(DOMLH::elementAbsolutePositioned(element)){

					element->setLayoutSize(w, h);

				}
			}
		}
	}

	//set main size of flex items if they are flexible

	for(unsigned int i = 0; i < flexItems.size(); i++){
		int partscount = 0;
		for(int parts : flexItemsBasis.at(i)){
			partscount += parts;
		}

		if(partscount > 0){

			float partsize = totalSpaceMainAxis.at(i)/partscount;

			totalSpaceMainAxis.at(i) = 0;

			for(unsigned int j = 0; j < flexItems.at(i).size(); j++){
				DOM::Element* element = flexItems.at(i).at(j);
				if(horizontal){
					element->setSizeByParent(flexItemsBasis.at(i).at(j)*partsize, element->getSizeByParent().y);
					setLayoutWidthMinusMargin(element, flexItemsBasis.at(i).at(j)*partsize);
				}else{
					element->setSizeByParent(element->getSizeByParent().x, flexItemsBasis.at(i).at(j)*partsize);
					setLayoutHeightMinusMargin(element, flexItemsBasis.at(i).at(j)*partsize);
				}
			}
		}

	}

	//set cross size of items if they stretch

	AlignItems alignItems = getAlignItems(_parent);

	vector<float> lineSizes;
	float totalSpaceCrossAxis = crossAxisSize;

	for(unsigned int i = 0; i < lines.size(); i++){

		float lineSize = 0;
		for(auto e : lines.at(i)){
			float elementCrossSize = horizontal ?
						e->getHeight()+DOMLH::getMarginVertical(e) :
						e->getWidth()+DOMLH::getMarginHorizontal(e);
			AlignSelf alignSelf = getAlignSelf(e);
			if(((alignSelf != AlignSelf::AUTO) && (alignSelf != AlignSelf::STRETCH)) ||
			  ((alignSelf == AlignSelf::AUTO) && (alignItems != AlignItems::STRETCH))){
				if(elementCrossSize > lineSize){
					lineSize = elementCrossSize;
				}
			}
		}
		totalSpaceCrossAxis -= lineSize;
		lineSizes.push_back(lineSize);
	}

	// count how many lines do not have a fixed size
	int zerolines = 0;
	for(int lineSize : lineSizes){
		if(lineSize == 0){
			zerolines++;
		}
	}

	// if there are lines without fixed height, take the remaining height of the parent
	// and share it between the lines without fixed height
	if(zerolines > 0){
		for(unsigned int i = 0; i < lineSizes.size(); i++){
			if(lineSizes[i] == 0){
				lineSizes[i] = totalSpaceCrossAxis / zerolines;
			}
		}
		totalSpaceCrossAxis = 0;
	}

	// check if lines are not big enough to fit in all elements minimal size
	for(unsigned int i = 0; i < lines.size(); i++){

		float lineSize = lineSizes.at(i);
		for(auto e : lines.at(i)){
			float elementCrossSize = horizontal ?
						e->getHeight()+DOMLH::getMarginVertical(e) :
						e->getWidth()+DOMLH::getMarginHorizontal(e);

			if(elementCrossSize > lineSize){
				lineSize = elementCrossSize;
			}
		}
		lineSizes.at(i) = lineSize;
	}

	float newCrossAxisSize = 0;
	for(int size : lineSizes){
		newCrossAxisSize += size;
	}
	if(newCrossAxisSize > crossAxisSize){
		totalSpaceCrossAxis = 0;
//		if(horizontal){
//			setHeightInLayoutAddPadding_parent, newCrossAxisSize);
//		}else {
//			setWidthInLayoutAddPadding(_parent, newCrossAxisSize);
//		}
	}

	//take care of empty space on cross axis
	int spacingCrossAxisStart = 0;
	int spacingCrossAxisBetween = 0;
	if(lines.size() > 1){
		if(totalSpaceCrossAxis > 0){
			switch(getAlignContent(_parent)){
				case AlignContent::CENTER:
					spacingCrossAxisStart = totalSpaceCrossAxis/2;
					break;
				case AlignContent::FLEX_END:
					spacingCrossAxisStart = totalSpaceCrossAxis;
					break;
				case AlignContent::SPACE_AROUND:
					spacingCrossAxisStart = totalSpaceCrossAxis/(lines.size()+1);
					spacingCrossAxisBetween = spacingCrossAxisStart;
					break;
				case AlignContent::SPACE_BETWEEN:
					spacingCrossAxisBetween = totalSpaceCrossAxis/(lines.size()-1);
					break;
				case AlignContent::STRETCH:
					spacingCrossAxisBetween = totalSpaceCrossAxis/lines.size();
					break;
				default:break;
			}
		}
	}else{
		if(lines.size()>0){
			lineSizes.at(0) = max(lineSizes.at(0),crossAxisSize);
		}
	}

	totalWidth += paddingHorizontal;
	totalHeight += paddingVertical;

	float parentPaddingLeft = DOMLH::getPaddingLeft(_parent);
	float parentPaddingTop = DOMLH::getPaddingTop(_parent);

	float currentMainPos = 0;
	float currentCrossPos = spacingCrossAxisStart;
	currentCrossPos += horizontal ? parentPaddingTop : parentPaddingLeft;

	for(unsigned int i = 0; i < lines.size(); i++){

		//take care of empty space on main axis
		int spacingMainAxisStart = horizontal ? parentPaddingLeft : parentPaddingTop;
		int spacingMainAxisBetween = 0;
		if(totalSpaceMainAxis.at(i) > 0){
			switch(getJustifyContent(_parent)){
				case JustifyContent::CENTER:
					spacingMainAxisStart += totalSpaceMainAxis.at(i)/2;
					break;
				case JustifyContent::FLEX_END:
					spacingMainAxisStart += totalSpaceMainAxis.at(i);
					break;
				case JustifyContent::SPACE_AROUND:
					spacingMainAxisStart += totalSpaceMainAxis.at(i)/(lines.at(i).size()+1);
					spacingMainAxisBetween = spacingMainAxisStart;
					break;
				case JustifyContent::SPACE_BETWEEN:
					spacingMainAxisBetween = totalSpaceMainAxis.at(i)/(lines.at(i).size()-1);
					break;
				default:break;
			}
		}

		currentMainPos = spacingMainAxisStart;

		for(unsigned int j = 0; j < lines.at(i).size(); j++){

			// set cross size of item

			DOM::Element* element = lines.at(i).at(j);
			AlignSelf alignSelf = getAlignSelf(element);
			if(alignSelf == AlignSelf::STRETCH ||
			  ((alignSelf == AlignSelf::AUTO) && (alignItems == AlignItems::STRETCH))){
				if(horizontal){
					element->setSizeByParent(element->getSizeByParent().x, lineSizes.at(i));
					setLayoutHeightMinusMargin(element, lineSizes.at(i));
				}else{
					element->setSizeByParent(lineSizes.at(i), element->getSizeByParent().y);
					setLayoutWidthMinusMargin(element, lineSizes.at(i));
				}
			}

			//align item

			float elementMainPos = currentMainPos;
			float elementCrossPos = currentCrossPos;
			float elementMainSize = horizontal ? getWidthPlusMargin(element) : getHeightPlusMargin(element);
			float elementCrossSize = horizontal ? getHeightPlusMargin(element) : getWidthPlusMargin(element);

			//align item on cross axis

			AlignItems alignItem = alignItems;
			if(alignSelf != AlignSelf::AUTO){
				switch(alignSelf){
					case AlignSelf::CENTER:
						alignItem = AlignItems::CENTER;
						break;
					case AlignSelf::STRETCH:
					case AlignSelf::FLEX_START:
						alignItem = AlignItems::FLEX_START;
						break;
					case AlignSelf::FLEX_END:
						alignItem = AlignItems::FLEX_END;
						break;
					default:
						break;
				}
			}

			switch(alignItem){
				case AlignItems::FLEX_END:
					elementCrossPos += lineSizes.at(i)-elementCrossSize;
					break;
				case AlignItems::CENTER:
					elementCrossPos += (lineSizes.at(i)-elementCrossSize)/2.;
					break;
				default:
					break;
			}

			//set final element position
			if(horizontal){
				DOMLH::setPosition(element, ofPoint(elementMainPos, elementCrossPos));
			}else{
				DOMLH::setPosition(element, ofPoint(elementCrossPos, elementMainPos));
			}

			totalWidth = max(totalWidth, element->getShape().getRight()+DOMLH::getMarginRight(element)+DOMLH::getPaddingRight(_parent));
			totalHeight = max(totalHeight, element->getShape().getBottom()+DOMLH::getMarginBottom(element)+DOMLH::getPaddingBottom(_parent));

			currentMainPos += elementMainSize + spacingMainAxisBetween;

		}

		currentCrossPos += lineSizes.at(i) + spacingCrossAxisBetween;

	}


	//make sure parent element contains all child elements on the main axis
//	maxX += DOMLH::getPaddingRight(_parent);
//	maxY += DOMLH::getPaddingBottom(_parent);
//	if(horizontal){
//		_parent->setLayoutSize(max(maxX,_parent->getWidth()), max(maxY,_parent->getHeight()));
//	}else{
//		_parent->setLayoutSize(max(maxX,_parent->getWidth()), max(maxY,_parent->getHeight()));
//	}

//	if(ofxGuiElement* el = dynamic_cast<ofxGuiElement*>(_parent)){
//		cout << el->getName() << " total size end: " << totalWidth << " " << totalHeight << endl;
//	}

	_parent->setLayoutSize(totalWidth, totalHeight, false);
	_parent->setNeedsRedraw();

}
Esempio n. 3
0
static void layoutNodeImpl(css_node_t *node, float parentMaxWidth, css_direction_t parentDirection) {
  /** START_GENERATED **/
  css_direction_t direction = resolveDirection(node, parentDirection);
  css_flex_direction_t mainAxis = resolveAxis(getFlexDirection(node), direction);
  css_flex_direction_t crossAxis = getCrossFlexDirection(mainAxis, direction);
  css_flex_direction_t resolvedRowAxis = resolveAxis(CSS_FLEX_DIRECTION_ROW, direction);

  // Handle width and height style attributes
  setDimensionFromStyle(node, mainAxis);
  setDimensionFromStyle(node, crossAxis);

  // Set the resolved resolution in the node's layout
  node->layout.direction = direction;

  // The position is set by the parent, but we need to complete it with a
  // delta composed of the margin and left/top/right/bottom
  node->layout.position[leading[mainAxis]] += getLeadingMargin(node, mainAxis) +
    getRelativePosition(node, mainAxis);
  node->layout.position[trailing[mainAxis]] += getTrailingMargin(node, mainAxis) +
    getRelativePosition(node, mainAxis);
  node->layout.position[leading[crossAxis]] += getLeadingMargin(node, crossAxis) +
    getRelativePosition(node, crossAxis);
  node->layout.position[trailing[crossAxis]] += getTrailingMargin(node, crossAxis) +
    getRelativePosition(node, crossAxis);

  if (isMeasureDefined(node)) {
    float width = CSS_UNDEFINED;
    if (isDimDefined(node, resolvedRowAxis)) {
      width = node->style.dimensions[CSS_WIDTH];
    } else if (!isUndefined(node->layout.dimensions[dim[resolvedRowAxis]])) {
      width = node->layout.dimensions[dim[resolvedRowAxis]];
    } else {
      width = parentMaxWidth -
        getMarginAxis(node, resolvedRowAxis);
    }
    width -= getPaddingAndBorderAxis(node, resolvedRowAxis);

    // We only need to give a dimension for the text if we haven't got any
    // for it computed yet. It can either be from the style attribute or because
    // the element is flexible.
    bool isRowUndefined = !isDimDefined(node, resolvedRowAxis) &&
      isUndefined(node->layout.dimensions[dim[resolvedRowAxis]]);
    bool isColumnUndefined = !isDimDefined(node, CSS_FLEX_DIRECTION_COLUMN) &&
      isUndefined(node->layout.dimensions[dim[CSS_FLEX_DIRECTION_COLUMN]]);

    // Let's not measure the text if we already know both dimensions
    if (isRowUndefined || isColumnUndefined) {
      css_dim_t measureDim = node->measure(
        node->context,
        
        
        width
      );
      if (isRowUndefined) {
        node->layout.dimensions[CSS_WIDTH] = measureDim.dimensions[CSS_WIDTH] +
          getPaddingAndBorderAxis(node, resolvedRowAxis);
      }
      if (isColumnUndefined) {
        node->layout.dimensions[CSS_HEIGHT] = measureDim.dimensions[CSS_HEIGHT] +
          getPaddingAndBorderAxis(node, CSS_FLEX_DIRECTION_COLUMN);
      }
    }
    if (node->children_count == 0) {
      return;
    }
  }

  int i;
  int ii;
  css_node_t* child;
  css_flex_direction_t axis;

  // Pre-fill some dimensions straight from the parent
  for (i = 0; i < node->children_count; ++i) {
    child = node->get_child(node->context, i);
    // Pre-fill cross axis dimensions when the child is using stretch before
    // we call the recursive layout pass
    if (getAlignItem(node, child) == CSS_ALIGN_STRETCH &&
        getPositionType(child) == CSS_POSITION_RELATIVE &&
        !isUndefined(node->layout.dimensions[dim[crossAxis]]) &&
        !isDimDefined(child, crossAxis)) {
      child->layout.dimensions[dim[crossAxis]] = fmaxf(
        boundAxis(child, crossAxis, node->layout.dimensions[dim[crossAxis]] -
          getPaddingAndBorderAxis(node, crossAxis) -
          getMarginAxis(child, crossAxis)),
        // You never want to go smaller than padding
        getPaddingAndBorderAxis(child, crossAxis)
      );
    } else if (getPositionType(child) == CSS_POSITION_ABSOLUTE) {
      // Pre-fill dimensions when using absolute position and both offsets for the axis are defined (either both
      // left and right or top and bottom).
      for (ii = 0; ii < 2; ii++) {
        axis = (ii != 0) ? CSS_FLEX_DIRECTION_ROW : CSS_FLEX_DIRECTION_COLUMN;
        if (!isUndefined(node->layout.dimensions[dim[axis]]) &&
            !isDimDefined(child, axis) &&
            isPosDefined(child, leading[axis]) &&
            isPosDefined(child, trailing[axis])) {
          child->layout.dimensions[dim[axis]] = fmaxf(
            boundAxis(child, axis, node->layout.dimensions[dim[axis]] -
              getPaddingAndBorderAxis(node, axis) -
              getMarginAxis(child, axis) -
              getPosition(child, leading[axis]) -
              getPosition(child, trailing[axis])),
            // You never want to go smaller than padding
            getPaddingAndBorderAxis(child, axis)
          );
        }
      }
    }
  }

  float definedMainDim = CSS_UNDEFINED;
  if (!isUndefined(node->layout.dimensions[dim[mainAxis]])) {
    definedMainDim = node->layout.dimensions[dim[mainAxis]] -
        getPaddingAndBorderAxis(node, mainAxis);
  }

  // We want to execute the next two loops one per line with flex-wrap
  int startLine = 0;
  int endLine = 0;
  // int nextOffset = 0;
  int alreadyComputedNextLayout = 0;
  // We aggregate the total dimensions of the container in those two variables
  float linesCrossDim = 0;
  float linesMainDim = 0;
  int linesCount = 0;
  while (endLine < node->children_count) {
    // <Loop A> Layout non flexible children and count children by type

    // mainContentDim is accumulation of the dimensions and margin of all the
    // non flexible children. This will be used in order to either set the
    // dimensions of the node if none already exist, or to compute the
    // remaining space left for the flexible children.
    float mainContentDim = 0;

    // There are three kind of children, non flexible, flexible and absolute.
    // We need to know how many there are in order to distribute the space.
    int flexibleChildrenCount = 0;
    float totalFlexible = 0;
    int nonFlexibleChildrenCount = 0;

    float maxWidth;
    for (i = startLine; i < node->children_count; ++i) {
      child = node->get_child(node->context, i);
      float nextContentDim = 0;

      // It only makes sense to consider a child flexible if we have a computed
      // dimension for the node->
      if (!isUndefined(node->layout.dimensions[dim[mainAxis]]) && isFlex(child)) {
        flexibleChildrenCount++;
        totalFlexible += getFlex(child);

        // Even if we don't know its exact size yet, we already know the padding,
        // border and margin. We'll use this partial information, which represents
        // the smallest possible size for the child, to compute the remaining
        // available space.
        nextContentDim = getPaddingAndBorderAxis(child, mainAxis) +
          getMarginAxis(child, mainAxis);

      } else {
        maxWidth = CSS_UNDEFINED;
        if (!isRowDirection(mainAxis)) {
          maxWidth = parentMaxWidth -
            getMarginAxis(node, resolvedRowAxis) -
            getPaddingAndBorderAxis(node, resolvedRowAxis);

          if (isDimDefined(node, resolvedRowAxis)) {
            maxWidth = node->layout.dimensions[dim[resolvedRowAxis]] -
              getPaddingAndBorderAxis(node, resolvedRowAxis);
          }
        }

        // This is the main recursive call. We layout non flexible children.
        if (alreadyComputedNextLayout == 0) {
          layoutNode(child, maxWidth, direction);
        }

        // Absolute positioned elements do not take part of the layout, so we
        // don't use them to compute mainContentDim
        if (getPositionType(child) == CSS_POSITION_RELATIVE) {
          nonFlexibleChildrenCount++;
          // At this point we know the final size and margin of the element.
          nextContentDim = getDimWithMargin(child, mainAxis);
        }
      }

      // The element we are about to add would make us go to the next line
      if (isFlexWrap(node) &&
          !isUndefined(node->layout.dimensions[dim[mainAxis]]) &&
          mainContentDim + nextContentDim > definedMainDim &&
          // If there's only one element, then it's bigger than the content
          // and needs its own line
          i != startLine) {
        nonFlexibleChildrenCount--;
        alreadyComputedNextLayout = 1;
        break;
      }
      alreadyComputedNextLayout = 0;
      mainContentDim += nextContentDim;
      endLine = i + 1;
    }

    // <Loop B> Layout flexible children and allocate empty space

    // In order to position the elements in the main axis, we have two
    // controls. The space between the beginning and the first element
    // and the space between each two elements.
    float leadingMainDim = 0;
    float betweenMainDim = 0;

    // The remaining available space that needs to be allocated
    float remainingMainDim = 0;
    if (!isUndefined(node->layout.dimensions[dim[mainAxis]])) {
      remainingMainDim = definedMainDim - mainContentDim;
    } else {
      remainingMainDim = fmaxf(mainContentDim, 0) - mainContentDim;
    }

    // If there are flexible children in the mix, they are going to fill the
    // remaining space
    if (flexibleChildrenCount != 0) {
      float flexibleMainDim = remainingMainDim / totalFlexible;
      float baseMainDim;
      float boundMainDim;

      // Iterate over every child in the axis. If the flex share of remaining
      // space doesn't meet min/max bounds, remove this child from flex
      // calculations.
      for (i = startLine; i < endLine; ++i) {
        child = node->get_child(node->context, i);
        if (isFlex(child)) {
          baseMainDim = flexibleMainDim * getFlex(child) +
              getPaddingAndBorderAxis(child, mainAxis);
          boundMainDim = boundAxis(child, mainAxis, baseMainDim);

          if (baseMainDim != boundMainDim) {
            remainingMainDim -= boundMainDim;
            totalFlexible -= getFlex(child);
          }
        }
      }
      flexibleMainDim = remainingMainDim / totalFlexible;

      // The non flexible children can overflow the container, in this case
      // we should just assume that there is no space available.
      if (flexibleMainDim < 0) {
        flexibleMainDim = 0;
      }
      // We iterate over the full array and only apply the action on flexible
      // children. This is faster than actually allocating a new array that
      // contains only flexible children.
      for (i = startLine; i < endLine; ++i) {
        child = node->get_child(node->context, i);
        if (isFlex(child)) {
          // At this point we know the final size of the element in the main
          // dimension
          child->layout.dimensions[dim[mainAxis]] = boundAxis(child, mainAxis,
            flexibleMainDim * getFlex(child) + getPaddingAndBorderAxis(child, mainAxis)
          );

          maxWidth = CSS_UNDEFINED;
          if (isDimDefined(node, resolvedRowAxis)) {
            maxWidth = node->layout.dimensions[dim[resolvedRowAxis]] -
              getPaddingAndBorderAxis(node, resolvedRowAxis);
          } else if (!isRowDirection(mainAxis)) {
            maxWidth = parentMaxWidth -
              getMarginAxis(node, resolvedRowAxis) -
              getPaddingAndBorderAxis(node, resolvedRowAxis);
          }

          // And we recursively call the layout algorithm for this child
          layoutNode(child, maxWidth, direction);
        }
      }

    // We use justifyContent to figure out how to allocate the remaining
    // space available
    } else {
      css_justify_t justifyContent = getJustifyContent(node);
      if (justifyContent == CSS_JUSTIFY_CENTER) {
        leadingMainDim = remainingMainDim / 2;
      } else if (justifyContent == CSS_JUSTIFY_FLEX_END) {
        leadingMainDim = remainingMainDim;
      } else if (justifyContent == CSS_JUSTIFY_SPACE_BETWEEN) {
        remainingMainDim = fmaxf(remainingMainDim, 0);
        if (flexibleChildrenCount + nonFlexibleChildrenCount - 1 != 0) {
          betweenMainDim = remainingMainDim /
            (flexibleChildrenCount + nonFlexibleChildrenCount - 1);
        } else {
          betweenMainDim = 0;
        }
      } else if (justifyContent == CSS_JUSTIFY_SPACE_AROUND) {
        // Space on the edges is half of the space between elements
        betweenMainDim = remainingMainDim /
          (flexibleChildrenCount + nonFlexibleChildrenCount);
        leadingMainDim = betweenMainDim / 2;
      }
    }

    // <Loop C> Position elements in the main axis and compute dimensions

    // At this point, all the children have their dimensions set. We need to
    // find their position. In order to do that, we accumulate data in
    // variables that are also useful to compute the total dimensions of the
    // container!
    float crossDim = 0;
    float mainDim = leadingMainDim +
      getLeadingPaddingAndBorder(node, mainAxis);

    for (i = startLine; i < endLine; ++i) {
      child = node->get_child(node->context, i);
      child->line_index = linesCount;

      if (getPositionType(child) == CSS_POSITION_ABSOLUTE &&
          isPosDefined(child, leading[mainAxis])) {
        // In case the child is position absolute and has left/top being
        // defined, we override the position to whatever the user said
        // (and margin/border).
        child->layout.position[pos[mainAxis]] = getPosition(child, leading[mainAxis]) +
          getLeadingBorder(node, mainAxis) +
          getLeadingMargin(child, mainAxis);
      } else {
        // If the child is position absolute (without top/left) or relative,
        // we put it at the current accumulated offset.
        child->layout.position[pos[mainAxis]] += mainDim;

        // Define the trailing position accordingly.
        if (!isUndefined(node->layout.dimensions[dim[mainAxis]])) {
          setTrailingPosition(node, child, mainAxis);
        }
      }

      // Now that we placed the element, we need to update the variables
      // We only need to do that for relative elements. Absolute elements
      // do not take part in that phase.
      if (getPositionType(child) == CSS_POSITION_RELATIVE) {
        // The main dimension is the sum of all the elements dimension plus
        // the spacing.
        mainDim += betweenMainDim + getDimWithMargin(child, mainAxis);
        // The cross dimension is the max of the elements dimension since there
        // can only be one element in that cross dimension.
        crossDim = fmaxf(crossDim, boundAxis(child, crossAxis, getDimWithMargin(child, crossAxis)));
      }
    }

    float containerCrossAxis = node->layout.dimensions[dim[crossAxis]];
    if (isUndefined(node->layout.dimensions[dim[crossAxis]])) {
      containerCrossAxis = fmaxf(
        // For the cross dim, we add both sides at the end because the value
        // is aggregate via a max function. Intermediate negative values
        // can mess this computation otherwise
        boundAxis(node, crossAxis, crossDim + getPaddingAndBorderAxis(node, crossAxis)),
        getPaddingAndBorderAxis(node, crossAxis)
      );
    }

    // <Loop D> Position elements in the cross axis
    for (i = startLine; i < endLine; ++i) {
      child = node->get_child(node->context, i);

      if (getPositionType(child) == CSS_POSITION_ABSOLUTE &&
          isPosDefined(child, leading[crossAxis])) {
        // In case the child is absolutely positionned and has a
        // top/left/bottom/right being set, we override all the previously
        // computed positions to set it correctly.
        child->layout.position[pos[crossAxis]] = getPosition(child, leading[crossAxis]) +
          getLeadingBorder(node, crossAxis) +
          getLeadingMargin(child, crossAxis);

      } else {
        float leadingCrossDim = getLeadingPaddingAndBorder(node, crossAxis);

        // For a relative children, we're either using alignItems (parent) or
        // alignSelf (child) in order to determine the position in the cross axis
        if (getPositionType(child) == CSS_POSITION_RELATIVE) {
          css_align_t alignItem = getAlignItem(node, child);
          if (alignItem == CSS_ALIGN_STRETCH) {
            // You can only stretch if the dimension has not already been set
            // previously.
            if (!isDimDefined(child, crossAxis)) {
              child->layout.dimensions[dim[crossAxis]] = fmaxf(
                boundAxis(child, crossAxis, containerCrossAxis -
                  getPaddingAndBorderAxis(node, crossAxis) -
                  getMarginAxis(child, crossAxis)),
                // You never want to go smaller than padding
                getPaddingAndBorderAxis(child, crossAxis)
              );
            }
          } else if (alignItem != CSS_ALIGN_FLEX_START) {
            // The remaining space between the parent dimensions+padding and child
            // dimensions+margin.
            float remainingCrossDim = containerCrossAxis -
              getPaddingAndBorderAxis(node, crossAxis) -
              getDimWithMargin(child, crossAxis);

            if (alignItem == CSS_ALIGN_CENTER) {
              leadingCrossDim += remainingCrossDim / 2;
            } else { // CSS_ALIGN_FLEX_END
              leadingCrossDim += remainingCrossDim;
            }
          }
        }

        // And we apply the position
        child->layout.position[pos[crossAxis]] += linesCrossDim + leadingCrossDim;

        // Define the trailing position accordingly.
        if (!isUndefined(node->layout.dimensions[dim[crossAxis]])) {
          setTrailingPosition(node, child, crossAxis);
        }
      }
    }

    linesCrossDim += crossDim;
    linesMainDim = fmaxf(linesMainDim, mainDim);
    linesCount += 1;
    startLine = endLine;
  }

  // <Loop E>
  //
  // Note(prenaux): More than one line, we need to layout the crossAxis
  // according to alignContent.
  //
  // Note that we could probably remove <Loop D> and handle the one line case
  // here too, but for the moment this is safer since it won't interfere with
  // previously working code.
  //
  // See specs:
  // http://www.w3.org/TR/2012/CR-css3-flexbox-20120918/#layout-algorithm
  // section 9.4
  //
  if (linesCount > 1 &&
      !isUndefined(node->layout.dimensions[dim[crossAxis]])) {
    float nodeCrossAxisInnerSize = node->layout.dimensions[dim[crossAxis]] -
        getPaddingAndBorderAxis(node, crossAxis);
    float remainingAlignContentDim = nodeCrossAxisInnerSize - linesCrossDim;

    float crossDimLead = 0;
    float currentLead = getLeadingPaddingAndBorder(node, crossAxis);

    css_align_t alignContent = getAlignContent(node);
    if (alignContent == CSS_ALIGN_FLEX_END) {
      currentLead += remainingAlignContentDim;
    } else if (alignContent == CSS_ALIGN_CENTER) {
      currentLead += remainingAlignContentDim / 2;
    } else if (alignContent == CSS_ALIGN_STRETCH) {
      if (nodeCrossAxisInnerSize > linesCrossDim) {
        crossDimLead = (remainingAlignContentDim / linesCount);
      }
    }

    int endIndex = 0;
    for (i = 0; i < linesCount; ++i) {
      int startIndex = endIndex;

      // compute the line's height and find the endIndex
      float lineHeight = 0;
      for (ii = startIndex; ii < node->children_count; ++ii) {
        child = node->get_child(node->context, ii);
        if (getPositionType(child) != CSS_POSITION_RELATIVE) {
          continue;
        }
        if (child->line_index != i) {
          break;
        }
        if (!isUndefined(child->layout.dimensions[dim[crossAxis]])) {
          lineHeight = fmaxf(
            lineHeight,
            child->layout.dimensions[dim[crossAxis]] + getMarginAxis(child, crossAxis)
          );
        }
      }
      endIndex = ii;
      lineHeight += crossDimLead;

      for (ii = startIndex; ii < endIndex; ++ii) {
        child = node->get_child(node->context, ii);
        if (getPositionType(child) != CSS_POSITION_RELATIVE) {
          continue;
        }

        css_align_t alignContentAlignItem = getAlignItem(node, child);
        if (alignContentAlignItem == CSS_ALIGN_FLEX_START) {
          child->layout.position[pos[crossAxis]] = currentLead + getLeadingMargin(child, crossAxis);
        } else if (alignContentAlignItem == CSS_ALIGN_FLEX_END) {
          child->layout.position[pos[crossAxis]] = currentLead + lineHeight - getTrailingMargin(child, crossAxis) - child->layout.dimensions[dim[crossAxis]];
        } else if (alignContentAlignItem == CSS_ALIGN_CENTER) {
          float childHeight = child->layout.dimensions[dim[crossAxis]];
          child->layout.position[pos[crossAxis]] = currentLead + (lineHeight - childHeight) / 2;
        } else if (alignContentAlignItem == CSS_ALIGN_STRETCH) {
          child->layout.position[pos[crossAxis]] = currentLead + getLeadingMargin(child, crossAxis);
          // TODO(prenaux): Correctly set the height of items with undefined
          //                (auto) crossAxis dimension.
        }
      }

      currentLead += lineHeight;
    }
  }

  bool needsMainTrailingPos = false;
  bool needsCrossTrailingPos = false;

  // If the user didn't specify a width or height, and it has not been set
  // by the container, then we set it via the children.
  if (isUndefined(node->layout.dimensions[dim[mainAxis]])) {
    node->layout.dimensions[dim[mainAxis]] = fmaxf(
      // We're missing the last padding at this point to get the final
      // dimension
      boundAxis(node, mainAxis, linesMainDim + getTrailingPaddingAndBorder(node, mainAxis)),
      // We can never assign a width smaller than the padding and borders
      getPaddingAndBorderAxis(node, mainAxis)
    );

    needsMainTrailingPos = true;
  }

  if (isUndefined(node->layout.dimensions[dim[crossAxis]])) {
    node->layout.dimensions[dim[crossAxis]] = fmaxf(
      // For the cross dim, we add both sides at the end because the value
      // is aggregate via a max function. Intermediate negative values
      // can mess this computation otherwise
      boundAxis(node, crossAxis, linesCrossDim + getPaddingAndBorderAxis(node, crossAxis)),
      getPaddingAndBorderAxis(node, crossAxis)
    );

    needsCrossTrailingPos = true;
  }

  // <Loop F> Set trailing position if necessary
  if (needsMainTrailingPos || needsCrossTrailingPos) {
    for (i = 0; i < node->children_count; ++i) {
      child = node->get_child(node->context, i);

      if (needsMainTrailingPos) {
        setTrailingPosition(node, child, mainAxis);
      }

      if (needsCrossTrailingPos) {
        setTrailingPosition(node, child, crossAxis);
      }
    }
  }

  // <Loop G> Calculate dimensions for absolutely positioned elements
  for (i = 0; i < node->children_count; ++i) {
    child = node->get_child(node->context, i);
    if (getPositionType(child) == CSS_POSITION_ABSOLUTE) {
      // Pre-fill dimensions when using absolute position and both offsets for the axis are defined (either both
      // left and right or top and bottom).
      for (ii = 0; ii < 2; ii++) {
        axis = (ii != 0) ? CSS_FLEX_DIRECTION_ROW : CSS_FLEX_DIRECTION_COLUMN;
        if (!isUndefined(node->layout.dimensions[dim[axis]]) &&
            !isDimDefined(child, axis) &&
            isPosDefined(child, leading[axis]) &&
            isPosDefined(child, trailing[axis])) {
          child->layout.dimensions[dim[axis]] = fmaxf(
            boundAxis(child, axis, node->layout.dimensions[dim[axis]] -
              getBorderAxis(node, axis) -
              getMarginAxis(child, axis) -
              getPosition(child, leading[axis]) -
              getPosition(child, trailing[axis])
            ),
            // You never want to go smaller than padding
            getPaddingAndBorderAxis(child, axis)
          );
        }
      }
      for (ii = 0; ii < 2; ii++) {
        axis = (ii != 0) ? CSS_FLEX_DIRECTION_ROW : CSS_FLEX_DIRECTION_COLUMN;
        if (isPosDefined(child, trailing[axis]) &&
            !isPosDefined(child, leading[axis])) {
          child->layout.position[leading[axis]] =
            node->layout.dimensions[dim[axis]] -
            child->layout.dimensions[dim[axis]] -
            getPosition(child, trailing[axis]);
        }
      }
    }
  }
  /** END_GENERATED **/
}