The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1643 lines
68KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. namespace juce
  19. {
  20. template <typename Item>
  21. static Array<Item> operator+ (const Array<Item>& a, const Array<Item>& b)
  22. {
  23. auto copy = a;
  24. copy.addArray (b);
  25. return copy;
  26. }
  27. struct Grid::Helpers
  28. {
  29. struct AllTracksIncludingImplicit
  30. {
  31. Array<TrackInfo> items;
  32. int numImplicitLeading; // The number of implicit items before the explicit items
  33. };
  34. struct Tracks
  35. {
  36. AllTracksIncludingImplicit columns, rows;
  37. };
  38. struct NoRounding
  39. {
  40. template <typename T>
  41. T operator() (T t) const { return t; }
  42. };
  43. struct StandardRounding
  44. {
  45. template <typename T>
  46. T operator() (T t) const { return std::round (t); }
  47. };
  48. template <typename RoundingFunction>
  49. struct SizeCalculation
  50. {
  51. float getTotalAbsoluteSize (const Array<TrackInfo>& tracks, Px gapSize) noexcept
  52. {
  53. float totalCellSize = 0.0f;
  54. for (const auto& trackInfo : tracks)
  55. if (! trackInfo.isFractional() || trackInfo.isAuto())
  56. totalCellSize += roundingFunction (trackInfo.getSize());
  57. float totalGap = tracks.size() > 1 ? (float) (tracks.size() - 1) * roundingFunction ((float) gapSize.pixels)
  58. : 0.0f;
  59. return totalCellSize + totalGap;
  60. }
  61. static float getRelativeUnitSize (float size, float totalAbsolute, const Array<TrackInfo>& tracks) noexcept
  62. {
  63. const float totalRelative = jlimit (0.0f, size, size - totalAbsolute);
  64. float factorsSum = 0.0f;
  65. for (const auto& trackInfo : tracks)
  66. if (trackInfo.isFractional())
  67. factorsSum += trackInfo.getSize();
  68. jassert (! approximatelyEqual (factorsSum, 0.0f));
  69. return totalRelative / factorsSum;
  70. }
  71. //==============================================================================
  72. float getTotalAbsoluteHeight (const Array<TrackInfo>& rowTracks, Px rowGapSize)
  73. {
  74. return getTotalAbsoluteSize (rowTracks, rowGapSize);
  75. }
  76. float getTotalAbsoluteWidth (const Array<TrackInfo>& columnTracks, Px columnGapSize)
  77. {
  78. return getTotalAbsoluteSize (columnTracks, columnGapSize);
  79. }
  80. float getRelativeWidthUnit (float gridWidth, Px columnGapSize, const Array<TrackInfo>& columnTracks)
  81. {
  82. return getRelativeUnitSize (gridWidth, getTotalAbsoluteWidth (columnTracks, columnGapSize), columnTracks);
  83. }
  84. float getRelativeHeightUnit (float gridHeight, Px rowGapSize, const Array<TrackInfo>& rowTracks)
  85. {
  86. return getRelativeUnitSize (gridHeight, getTotalAbsoluteHeight (rowTracks, rowGapSize), rowTracks);
  87. }
  88. //==============================================================================
  89. static bool hasAnyFractions (const Array<TrackInfo>& tracks)
  90. {
  91. return std::any_of (tracks.begin(),
  92. tracks.end(),
  93. [] (const auto& t) { return t.isFractional(); });
  94. }
  95. void computeSizes (float gridWidth, float gridHeight,
  96. Px columnGapToUse, Px rowGapToUse,
  97. const Tracks& tracks)
  98. {
  99. if (hasAnyFractions (tracks.columns.items))
  100. {
  101. relativeWidthUnit = getRelativeWidthUnit (gridWidth, columnGapToUse, tracks.columns.items);
  102. fractionallyDividedWidth = gridWidth - getTotalAbsoluteSize (tracks.columns.items, columnGapToUse);
  103. }
  104. else
  105. {
  106. remainingWidth = gridWidth - getTotalAbsoluteSize (tracks.columns.items, columnGapToUse);
  107. }
  108. if (hasAnyFractions (tracks.rows.items))
  109. {
  110. relativeHeightUnit = getRelativeHeightUnit (gridHeight, rowGapToUse, tracks.rows.items);
  111. fractionallyDividedHeight = gridHeight - getTotalAbsoluteSize (tracks.rows.items, rowGapToUse);
  112. }
  113. else
  114. {
  115. remainingHeight = gridHeight - getTotalAbsoluteSize (tracks.rows.items, rowGapToUse);
  116. }
  117. const auto calculateTrackBounds = [&] (auto& outBounds,
  118. const auto& trackItems,
  119. auto relativeUnit,
  120. auto totalSizeForFractionalItems,
  121. auto gap)
  122. {
  123. const auto lastFractionalIndex = [&]
  124. {
  125. for (int i = trackItems.size() - 1; 0 <= i; --i)
  126. if (trackItems[i].isFractional())
  127. return i;
  128. return -1;
  129. }();
  130. float start = 0.0f;
  131. float carriedError = 0.0f;
  132. for (int i = 0; i < trackItems.size(); ++i)
  133. {
  134. const auto& currentItem = trackItems[i];
  135. const auto currentTrackSize = [&]
  136. {
  137. if (i == lastFractionalIndex)
  138. return totalSizeForFractionalItems;
  139. const auto absoluteSize = currentItem.getAbsoluteSize (relativeUnit);
  140. if (! currentItem.isFractional())
  141. return roundingFunction (absoluteSize);
  142. const auto result = roundingFunction (absoluteSize - carriedError);
  143. carriedError += result - absoluteSize;
  144. return result;
  145. }();
  146. if (currentItem.isFractional())
  147. totalSizeForFractionalItems -= currentTrackSize;
  148. const auto end = start + currentTrackSize;
  149. outBounds.emplace_back (start, end);
  150. start = end + roundingFunction (static_cast<float> (gap.pixels));
  151. }
  152. };
  153. calculateTrackBounds (columnTrackBounds,
  154. tracks.columns.items,
  155. relativeWidthUnit,
  156. fractionallyDividedWidth,
  157. columnGapToUse);
  158. calculateTrackBounds (rowTrackBounds,
  159. tracks.rows.items,
  160. relativeHeightUnit,
  161. fractionallyDividedHeight,
  162. rowGapToUse);
  163. }
  164. float relativeWidthUnit = 0.0f;
  165. float relativeHeightUnit = 0.0f;
  166. float fractionallyDividedWidth = 0.0f;
  167. float fractionallyDividedHeight = 0.0f;
  168. float remainingWidth = 0.0f;
  169. float remainingHeight = 0.0f;
  170. std::vector<Range<float>> columnTrackBounds;
  171. std::vector<Range<float>> rowTrackBounds;
  172. RoundingFunction roundingFunction;
  173. };
  174. //==============================================================================
  175. struct PlacementHelpers
  176. {
  177. enum { invalid = -999999 };
  178. static constexpr auto emptyAreaCharacter = ".";
  179. //==============================================================================
  180. struct LineRange { int start, end; };
  181. struct LineArea { LineRange column, row; };
  182. struct LineInfo { StringArray lineNames; };
  183. struct NamedArea
  184. {
  185. String name;
  186. LineArea lines;
  187. };
  188. //==============================================================================
  189. static Array<LineInfo> getArrayOfLinesFromTracks (const Array<TrackInfo>& tracks)
  190. {
  191. // fill line info array
  192. Array<LineInfo> lines;
  193. for (int i = 1; i <= tracks.size(); ++i)
  194. {
  195. const auto& currentTrack = tracks.getReference (i - 1);
  196. if (i == 1) // start line
  197. {
  198. LineInfo li;
  199. li.lineNames.add (currentTrack.getStartLineName());
  200. lines.add (li);
  201. }
  202. if (i > 1 && i <= tracks.size()) // two lines in between tracks
  203. {
  204. const auto& prevTrack = tracks.getReference (i - 2);
  205. LineInfo li;
  206. li.lineNames.add (prevTrack.getEndLineName());
  207. li.lineNames.add (currentTrack.getStartLineName());
  208. lines.add (li);
  209. }
  210. if (i == tracks.size()) // end line
  211. {
  212. LineInfo li;
  213. li.lineNames.add (currentTrack.getEndLineName());
  214. lines.add (li);
  215. }
  216. }
  217. jassert (lines.size() == tracks.size() + 1);
  218. return lines;
  219. }
  220. //==============================================================================
  221. static int deduceAbsoluteLineNumberFromLineName (GridItem::Property prop,
  222. const Array<TrackInfo>& tracks)
  223. {
  224. jassert (prop.hasAbsolute());
  225. const auto lines = getArrayOfLinesFromTracks (tracks);
  226. int count = 0;
  227. for (const auto [index, line] : enumerate (lines))
  228. {
  229. for (const auto& name : line.lineNames)
  230. {
  231. if (prop.getName() == name)
  232. {
  233. ++count;
  234. break;
  235. }
  236. }
  237. if (count == prop.getNumber())
  238. return (int) index + 1;
  239. }
  240. jassertfalse;
  241. return count;
  242. }
  243. static int deduceAbsoluteLineNumber (GridItem::Property prop,
  244. const Array<TrackInfo>& tracks)
  245. {
  246. jassert (prop.hasAbsolute());
  247. if (prop.hasName())
  248. return deduceAbsoluteLineNumberFromLineName (prop, tracks);
  249. if (prop.getNumber() > 0)
  250. return prop.getNumber();
  251. if (prop.getNumber() < 0)
  252. return tracks.size() + 2 + prop.getNumber();
  253. // An integer value of 0 is invalid
  254. jassertfalse;
  255. return 1;
  256. }
  257. static int deduceAbsoluteLineNumberFromNamedSpan (int startLineNumber,
  258. GridItem::Property propertyWithSpan,
  259. const Array<TrackInfo>& tracks)
  260. {
  261. jassert (propertyWithSpan.hasSpan());
  262. const auto lines = getArrayOfLinesFromTracks (tracks);
  263. int count = 0;
  264. const auto enumerated = enumerate (lines);
  265. for (const auto [index, line] : makeRange (enumerated.begin() + startLineNumber, enumerated.end()))
  266. {
  267. for (const auto& name : line.lineNames)
  268. {
  269. if (propertyWithSpan.getName() == name)
  270. {
  271. ++count;
  272. break;
  273. }
  274. }
  275. if (count == propertyWithSpan.getNumber())
  276. return (int) index + 1;
  277. }
  278. jassertfalse;
  279. return count;
  280. }
  281. static int deduceAbsoluteLineNumberBasedOnSpan (int startLineNumber,
  282. GridItem::Property propertyWithSpan,
  283. const Array<TrackInfo>& tracks)
  284. {
  285. jassert (propertyWithSpan.hasSpan());
  286. if (propertyWithSpan.hasName())
  287. return deduceAbsoluteLineNumberFromNamedSpan (startLineNumber, propertyWithSpan, tracks);
  288. return startLineNumber + propertyWithSpan.getNumber();
  289. }
  290. //==============================================================================
  291. static LineRange deduceLineRange (GridItem::StartAndEndProperty prop, const Array<TrackInfo>& tracks)
  292. {
  293. jassert (! (prop.start.hasAuto() && prop.end.hasAuto()));
  294. if (prop.start.hasAbsolute() && prop.end.hasAuto())
  295. {
  296. prop.end = GridItem::Span (1);
  297. }
  298. else if (prop.start.hasAuto() && prop.end.hasAbsolute())
  299. {
  300. prop.start = GridItem::Span (1);
  301. }
  302. auto s = [&]() -> LineRange
  303. {
  304. if (prop.start.hasAbsolute() && prop.end.hasAbsolute())
  305. {
  306. return { deduceAbsoluteLineNumber (prop.start, tracks),
  307. deduceAbsoluteLineNumber (prop.end, tracks) };
  308. }
  309. if (prop.start.hasAbsolute() && prop.end.hasSpan())
  310. {
  311. const auto start = deduceAbsoluteLineNumber (prop.start, tracks);
  312. return { start, deduceAbsoluteLineNumberBasedOnSpan (start, prop.end, tracks) };
  313. }
  314. if (prop.start.hasSpan() && prop.end.hasAbsolute())
  315. {
  316. const auto start = deduceAbsoluteLineNumber (prop.end, tracks);
  317. return { start, deduceAbsoluteLineNumberBasedOnSpan (start, prop.start, tracks) };
  318. }
  319. // Can't have an item with spans on both start and end.
  320. jassertfalse;
  321. return {};
  322. }();
  323. // swap if start overtakes end
  324. if (s.start > s.end)
  325. std::swap (s.start, s.end);
  326. else if (s.start == s.end)
  327. s.end = s.start + 1;
  328. return s;
  329. }
  330. static LineArea deduceLineArea (const GridItem& item,
  331. const Grid& grid,
  332. const std::map<String, LineArea>& namedAreas)
  333. {
  334. if (item.area.isNotEmpty() && ! grid.templateAreas.isEmpty())
  335. {
  336. // Must be a named area!
  337. jassert (namedAreas.count (item.area) != 0);
  338. return namedAreas.at (item.area);
  339. }
  340. return { deduceLineRange (item.column, grid.templateColumns),
  341. deduceLineRange (item.row, grid.templateRows) };
  342. }
  343. //==============================================================================
  344. static Array<StringArray> parseAreasProperty (const StringArray& areasStrings)
  345. {
  346. Array<StringArray> strings;
  347. for (const auto& areaString : areasStrings)
  348. strings.add (StringArray::fromTokens (areaString, false));
  349. if (strings.size() > 0)
  350. {
  351. for (auto s : strings)
  352. {
  353. jassert (s.size() == strings[0].size()); // all rows must have the same number of columns
  354. }
  355. }
  356. return strings;
  357. }
  358. static NamedArea findArea (Array<StringArray>& stringsArrays)
  359. {
  360. NamedArea area;
  361. for (auto& stringArray : stringsArrays)
  362. {
  363. for (auto& string : stringArray)
  364. {
  365. // find anchor
  366. if (area.name.isEmpty())
  367. {
  368. if (string != emptyAreaCharacter)
  369. {
  370. area.name = string;
  371. area.lines.row.start = stringsArrays.indexOf (stringArray) + 1; // non-zero indexed;
  372. area.lines.column.start = stringArray.indexOf (string) + 1; // non-zero indexed;
  373. area.lines.row.end = stringsArrays.indexOf (stringArray) + 2;
  374. area.lines.column.end = stringArray.indexOf (string) + 2;
  375. // mark as visited
  376. string = emptyAreaCharacter;
  377. }
  378. }
  379. else
  380. {
  381. if (string == area.name)
  382. {
  383. area.lines.row.end = stringsArrays.indexOf (stringArray) + 2;
  384. area.lines.column.end = stringArray.indexOf (string) + 2;
  385. // mark as visited
  386. string = emptyAreaCharacter;
  387. }
  388. }
  389. }
  390. }
  391. return area;
  392. }
  393. //==============================================================================
  394. static std::map<String, LineArea> deduceNamedAreas (const StringArray& areasStrings)
  395. {
  396. auto stringsArrays = parseAreasProperty (areasStrings);
  397. std::map<String, LineArea> areas;
  398. for (auto area = findArea (stringsArrays); area.name.isNotEmpty(); area = findArea (stringsArrays))
  399. {
  400. if (areas.count (area.name) == 0)
  401. areas[area.name] = area.lines;
  402. else
  403. // Make sure your template-areas property only has one area with the same name and is well-formed
  404. jassertfalse;
  405. }
  406. return areas;
  407. }
  408. //==============================================================================
  409. template <typename RoundingFunction>
  410. static Rectangle<float> getCellBounds (int columnNumber, int rowNumber,
  411. const Tracks& tracks,
  412. const SizeCalculation<RoundingFunction>& calculation)
  413. {
  414. const auto correctedColumn = columnNumber - 1 + tracks.columns.numImplicitLeading;
  415. const auto correctedRow = rowNumber - 1 + tracks.rows .numImplicitLeading;
  416. jassert (isPositiveAndBelow (correctedColumn, tracks.columns.items.size()));
  417. jassert (isPositiveAndBelow (correctedRow, tracks.rows .items.size()));
  418. return
  419. {
  420. calculation.columnTrackBounds[(size_t) correctedColumn].getStart(),
  421. calculation.rowTrackBounds[(size_t) correctedRow].getStart(),
  422. calculation.columnTrackBounds[(size_t) correctedColumn].getEnd() - calculation.columnTrackBounds[(size_t) correctedColumn].getStart(),
  423. calculation.rowTrackBounds[(size_t) correctedRow].getEnd() - calculation.rowTrackBounds[(size_t) correctedRow].getStart()
  424. };
  425. }
  426. template <typename RoundingFunction>
  427. static Rectangle<float> alignCell (Rectangle<float> area,
  428. int columnNumber, int rowNumber,
  429. int numberOfColumns, int numberOfRows,
  430. const SizeCalculation<RoundingFunction>& calculation,
  431. AlignContent alignContent,
  432. JustifyContent justifyContent)
  433. {
  434. if (alignContent == AlignContent::end)
  435. area.setY (area.getY() + calculation.remainingHeight);
  436. if (justifyContent == JustifyContent::end)
  437. area.setX (area.getX() + calculation.remainingWidth);
  438. if (alignContent == AlignContent::center)
  439. area.setY (area.getY() + calculation.remainingHeight / 2);
  440. if (justifyContent == JustifyContent::center)
  441. area.setX (area.getX() + calculation.remainingWidth / 2);
  442. if (alignContent == AlignContent::spaceBetween)
  443. {
  444. const auto shift = ((float) (rowNumber - 1) * (calculation.remainingHeight / float (numberOfRows - 1)));
  445. area.setY (area.getY() + shift);
  446. }
  447. if (justifyContent == JustifyContent::spaceBetween)
  448. {
  449. const auto shift = ((float) (columnNumber - 1) * (calculation.remainingWidth / float (numberOfColumns - 1)));
  450. area.setX (area.getX() + shift);
  451. }
  452. if (alignContent == AlignContent::spaceEvenly)
  453. {
  454. const auto shift = ((float) rowNumber * (calculation.remainingHeight / float (numberOfRows + 1)));
  455. area.setY (area.getY() + shift);
  456. }
  457. if (justifyContent == JustifyContent::spaceEvenly)
  458. {
  459. const auto shift = ((float) columnNumber * (calculation.remainingWidth / float (numberOfColumns + 1)));
  460. area.setX (area.getX() + shift);
  461. }
  462. if (alignContent == AlignContent::spaceAround)
  463. {
  464. const auto inbetweenShift = calculation.remainingHeight / float (numberOfRows);
  465. const auto sidesShift = inbetweenShift / 2;
  466. auto shift = (float) (rowNumber - 1) * inbetweenShift + sidesShift;
  467. area.setY (area.getY() + shift);
  468. }
  469. if (justifyContent == JustifyContent::spaceAround)
  470. {
  471. const auto inbetweenShift = calculation.remainingWidth / float (numberOfColumns);
  472. const auto sidesShift = inbetweenShift / 2;
  473. auto shift = (float) (columnNumber - 1) * inbetweenShift + sidesShift;
  474. area.setX (area.getX() + shift);
  475. }
  476. return area;
  477. }
  478. template <typename RoundingFunction>
  479. static Rectangle<float> getAreaBounds (PlacementHelpers::LineRange columnRange,
  480. PlacementHelpers::LineRange rowRange,
  481. const Tracks& tracks,
  482. const SizeCalculation<RoundingFunction>& calculation,
  483. AlignContent alignContent,
  484. JustifyContent justifyContent)
  485. {
  486. const auto findAlignedCell = [&] (int column, int row)
  487. {
  488. const auto cell = getCellBounds (column, row, tracks, calculation);
  489. return alignCell (cell,
  490. column,
  491. row,
  492. tracks.columns.items.size(),
  493. tracks.rows.items.size(),
  494. calculation,
  495. alignContent,
  496. justifyContent);
  497. };
  498. const auto startCell = findAlignedCell (columnRange.start, rowRange.start);
  499. const auto endCell = findAlignedCell (columnRange.end - 1, rowRange.end - 1);
  500. const auto horizontalRange = startCell.getHorizontalRange().getUnionWith (endCell.getHorizontalRange());
  501. const auto verticalRange = startCell.getVerticalRange() .getUnionWith (endCell.getVerticalRange());
  502. return { horizontalRange.getStart(), verticalRange.getStart(),
  503. horizontalRange.getLength(), verticalRange.getLength() };
  504. }
  505. };
  506. //==============================================================================
  507. struct AutoPlacement
  508. {
  509. using ItemPlacementArray = Array<std::pair<GridItem*, PlacementHelpers::LineArea>>;
  510. //==============================================================================
  511. struct OccupancyPlane
  512. {
  513. struct Cell { int column, row; };
  514. OccupancyPlane (int highestColumnToUse, int highestRowToUse, bool isColumnFirst)
  515. : highestCrossDimension (isColumnFirst ? highestRowToUse : highestColumnToUse),
  516. columnFirst (isColumnFirst)
  517. {}
  518. PlacementHelpers::LineArea setCell (Cell cell, int columnSpan, int rowSpan)
  519. {
  520. for (int i = 0; i < columnSpan; i++)
  521. for (int j = 0; j < rowSpan; j++)
  522. setCell (cell.column + i, cell.row + j);
  523. return { { cell.column, cell.column + columnSpan }, { cell.row, cell.row + rowSpan } };
  524. }
  525. PlacementHelpers::LineArea setCell (Cell start, Cell end)
  526. {
  527. return setCell (start, std::abs (end.column - start.column),
  528. std::abs (end.row - start.row));
  529. }
  530. Cell nextAvailable (Cell referenceCell, int columnSpan, int rowSpan)
  531. {
  532. while (isOccupied (referenceCell, columnSpan, rowSpan) || isOutOfBounds (referenceCell, columnSpan, rowSpan))
  533. referenceCell = advance (referenceCell);
  534. return referenceCell;
  535. }
  536. Cell nextAvailableOnRow (Cell referenceCell, int columnSpan, int rowSpan, int rowNumber)
  537. {
  538. if (columnFirst && (rowNumber + rowSpan) > highestCrossDimension)
  539. highestCrossDimension = rowNumber + rowSpan;
  540. while (isOccupied (referenceCell, columnSpan, rowSpan)
  541. || (referenceCell.row != rowNumber))
  542. referenceCell = advance (referenceCell);
  543. return referenceCell;
  544. }
  545. Cell nextAvailableOnColumn (Cell referenceCell, int columnSpan, int rowSpan, int columnNumber)
  546. {
  547. if (! columnFirst && (columnNumber + columnSpan) > highestCrossDimension)
  548. highestCrossDimension = columnNumber + columnSpan;
  549. while (isOccupied (referenceCell, columnSpan, rowSpan)
  550. || (referenceCell.column != columnNumber))
  551. referenceCell = advance (referenceCell);
  552. return referenceCell;
  553. }
  554. void updateMaxCrossDimensionFromAutoPlacementItem (int columnSpan, int rowSpan)
  555. {
  556. highestCrossDimension = jmax (highestCrossDimension, 1 + getCrossDimension ({ columnSpan, rowSpan }));
  557. }
  558. private:
  559. struct SortableCell
  560. {
  561. int column, row;
  562. bool columnFirst;
  563. bool operator< (const SortableCell& other) const
  564. {
  565. if (columnFirst)
  566. {
  567. if (row == other.row)
  568. return column < other.column;
  569. return row < other.row;
  570. }
  571. if (row == other.row)
  572. return column < other.column;
  573. return row < other.row;
  574. }
  575. };
  576. void setCell (int column, int row)
  577. {
  578. occupiedCells.insert ({ column, row, columnFirst });
  579. }
  580. bool isOccupied (Cell cell) const
  581. {
  582. return occupiedCells.count ({ cell.column, cell.row, columnFirst }) > 0;
  583. }
  584. bool isOccupied (Cell cell, int columnSpan, int rowSpan) const
  585. {
  586. for (int i = 0; i < columnSpan; i++)
  587. for (int j = 0; j < rowSpan; j++)
  588. if (isOccupied ({ cell.column + i, cell.row + j }))
  589. return true;
  590. return false;
  591. }
  592. bool isOutOfBounds (Cell cell, int columnSpan, int rowSpan) const
  593. {
  594. const auto highestIndexOfCell = getCrossDimension (cell) + getCrossDimension ({ columnSpan, rowSpan });
  595. const auto highestIndexOfGrid = getHighestCrossDimension();
  596. return highestIndexOfGrid < highestIndexOfCell;
  597. }
  598. int getHighestCrossDimension() const
  599. {
  600. Cell cell { 1, 1 };
  601. if (occupiedCells.size() > 0)
  602. cell = { occupiedCells.crbegin()->column, occupiedCells.crbegin()->row };
  603. return std::max (getCrossDimension (cell), highestCrossDimension);
  604. }
  605. Cell advance (Cell cell) const
  606. {
  607. if ((getCrossDimension (cell) + 1) >= getHighestCrossDimension())
  608. return fromDimensions (getMainDimension (cell) + 1, 1);
  609. return fromDimensions (getMainDimension (cell), getCrossDimension (cell) + 1);
  610. }
  611. int getMainDimension (Cell cell) const { return columnFirst ? cell.column : cell.row; }
  612. int getCrossDimension (Cell cell) const { return columnFirst ? cell.row : cell.column; }
  613. Cell fromDimensions (int mainDimension, int crossDimension) const
  614. {
  615. if (columnFirst)
  616. return { mainDimension, crossDimension };
  617. return { crossDimension, mainDimension };
  618. }
  619. int highestCrossDimension;
  620. bool columnFirst;
  621. std::set<SortableCell> occupiedCells;
  622. };
  623. //==============================================================================
  624. static bool isFixed (GridItem::StartAndEndProperty prop)
  625. {
  626. return prop.start.hasName() || prop.start.hasAbsolute() || prop.end.hasName() || prop.end.hasAbsolute();
  627. }
  628. static bool hasFullyFixedPlacement (const GridItem& item)
  629. {
  630. if (item.area.isNotEmpty())
  631. return true;
  632. if (isFixed (item.column) && isFixed (item.row))
  633. return true;
  634. return false;
  635. }
  636. static bool hasPartialFixedPlacement (const GridItem& item)
  637. {
  638. if (item.area.isNotEmpty())
  639. return false;
  640. if (isFixed (item.column) ^ isFixed (item.row))
  641. return true;
  642. return false;
  643. }
  644. static bool hasAutoPlacement (const GridItem& item)
  645. {
  646. return ! hasFullyFixedPlacement (item) && ! hasPartialFixedPlacement (item);
  647. }
  648. //==============================================================================
  649. static bool hasDenseAutoFlow (AutoFlow autoFlow)
  650. {
  651. return autoFlow == AutoFlow::columnDense
  652. || autoFlow == AutoFlow::rowDense;
  653. }
  654. static bool isColumnAutoFlow (AutoFlow autoFlow)
  655. {
  656. return autoFlow == AutoFlow::column
  657. || autoFlow == AutoFlow::columnDense;
  658. }
  659. //==============================================================================
  660. static int getSpanFromAuto (GridItem::StartAndEndProperty prop)
  661. {
  662. if (prop.end.hasSpan())
  663. return prop.end.getNumber();
  664. if (prop.start.hasSpan())
  665. return prop.start.getNumber();
  666. return 1;
  667. }
  668. //==============================================================================
  669. ItemPlacementArray deduceAllItems (Grid& grid) const
  670. {
  671. const auto namedAreas = PlacementHelpers::deduceNamedAreas (grid.templateAreas);
  672. OccupancyPlane plane (jmax (grid.templateColumns.size() + 1, 2),
  673. jmax (grid.templateRows.size() + 1, 2),
  674. isColumnAutoFlow (grid.autoFlow));
  675. ItemPlacementArray itemPlacementArray;
  676. Array<GridItem*> sortedItems;
  677. for (auto& item : grid.items)
  678. sortedItems.add (&item);
  679. std::stable_sort (sortedItems.begin(), sortedItems.end(),
  680. [] (const GridItem* i1, const GridItem* i2) { return i1->order < i2->order; });
  681. // place fixed items first
  682. for (auto* item : sortedItems)
  683. {
  684. if (hasFullyFixedPlacement (*item))
  685. {
  686. const auto a = PlacementHelpers::deduceLineArea (*item, grid, namedAreas);
  687. plane.setCell ({ a.column.start, a.row.start }, { a.column.end, a.row.end });
  688. itemPlacementArray.add ({ item, a });
  689. }
  690. }
  691. OccupancyPlane::Cell lastInsertionCell = { 1, 1 };
  692. for (auto* item : sortedItems)
  693. {
  694. if (hasPartialFixedPlacement (*item))
  695. {
  696. if (isFixed (item->column))
  697. {
  698. const auto p = PlacementHelpers::deduceLineRange (item->column, grid.templateColumns);
  699. const auto columnSpan = std::abs (p.start - p.end);
  700. const auto rowSpan = getSpanFromAuto (item->row);
  701. const auto insertionCell = hasDenseAutoFlow (grid.autoFlow) ? OccupancyPlane::Cell { p.start, 1 }
  702. : lastInsertionCell;
  703. const auto nextAvailableCell = plane.nextAvailableOnColumn (insertionCell, columnSpan, rowSpan, p.start);
  704. const auto lineArea = plane.setCell (nextAvailableCell, columnSpan, rowSpan);
  705. lastInsertionCell = nextAvailableCell;
  706. itemPlacementArray.add ({ item, lineArea });
  707. }
  708. else if (isFixed (item->row))
  709. {
  710. const auto p = PlacementHelpers::deduceLineRange (item->row, grid.templateRows);
  711. const auto columnSpan = getSpanFromAuto (item->column);
  712. const auto rowSpan = std::abs (p.start - p.end);
  713. const auto insertionCell = hasDenseAutoFlow (grid.autoFlow) ? OccupancyPlane::Cell { 1, p.start }
  714. : lastInsertionCell;
  715. const auto nextAvailableCell = plane.nextAvailableOnRow (insertionCell, columnSpan, rowSpan, p.start);
  716. const auto lineArea = plane.setCell (nextAvailableCell, columnSpan, rowSpan);
  717. lastInsertionCell = nextAvailableCell;
  718. itemPlacementArray.add ({ item, lineArea });
  719. }
  720. }
  721. }
  722. // https://www.w3.org/TR/css-grid-1/#auto-placement-algo step 3.3
  723. for (auto* item : sortedItems)
  724. if (hasAutoPlacement (*item))
  725. plane.updateMaxCrossDimensionFromAutoPlacementItem (getSpanFromAuto (item->column), getSpanFromAuto (item->row));
  726. lastInsertionCell = { 1, 1 };
  727. for (auto* item : sortedItems)
  728. {
  729. if (hasAutoPlacement (*item))
  730. {
  731. const auto columnSpan = getSpanFromAuto (item->column);
  732. const auto rowSpan = getSpanFromAuto (item->row);
  733. const auto nextAvailableCell = plane.nextAvailable (lastInsertionCell, columnSpan, rowSpan);
  734. const auto lineArea = plane.setCell (nextAvailableCell, columnSpan, rowSpan);
  735. if (! hasDenseAutoFlow (grid.autoFlow))
  736. lastInsertionCell = nextAvailableCell;
  737. itemPlacementArray.add ({ item, lineArea });
  738. }
  739. }
  740. return itemPlacementArray;
  741. }
  742. //==============================================================================
  743. template <typename Accessor>
  744. static PlacementHelpers::LineRange findFullLineRange (const ItemPlacementArray& items, Accessor&& accessor)
  745. {
  746. if (items.isEmpty())
  747. return { 1, 1 };
  748. const auto combine = [&accessor] (const auto& acc, const auto& item)
  749. {
  750. const auto newRange = accessor (item);
  751. return PlacementHelpers::LineRange { std::min (acc.start, newRange.start),
  752. std::max (acc.end, newRange.end) };
  753. };
  754. return std::accumulate (std::next (items.begin()), items.end(), accessor (*items.begin()), combine);
  755. }
  756. static PlacementHelpers::LineArea findFullLineArea (const ItemPlacementArray& items)
  757. {
  758. return { findFullLineRange (items, [] (const auto& item) { return item.second.column; }),
  759. findFullLineRange (items, [] (const auto& item) { return item.second.row; }) };
  760. }
  761. template <typename Item>
  762. static Array<Item> repeated (int repeats, const Item& item)
  763. {
  764. Array<Item> result;
  765. result.insertMultiple (-1, item, repeats);
  766. return result;
  767. }
  768. static Tracks createImplicitTracks (const Grid& grid, const ItemPlacementArray& items)
  769. {
  770. const auto fullArea = findFullLineArea (items);
  771. const auto leadingColumns = std::max (0, 1 - fullArea.column.start);
  772. const auto leadingRows = std::max (0, 1 - fullArea.row.start);
  773. const auto trailingColumns = std::max (0, fullArea.column.end - grid.templateColumns.size() - 1);
  774. const auto trailingRows = std::max (0, fullArea.row .end - grid.templateRows .size() - 1);
  775. return { { repeated (leadingColumns, grid.autoColumns) + grid.templateColumns + repeated (trailingColumns, grid.autoColumns),
  776. leadingColumns },
  777. { repeated (leadingRows, grid.autoRows) + grid.templateRows + repeated (trailingRows, grid.autoRows),
  778. leadingRows } };
  779. }
  780. //==============================================================================
  781. static void applySizeForAutoTracks (Tracks& tracks, const ItemPlacementArray& placements)
  782. {
  783. const auto setSizes = [&placements] (auto& tracksInDirection, const auto& getItem, const auto& getItemSize)
  784. {
  785. auto& array = tracksInDirection.items;
  786. for (int index = 0; index < array.size(); ++index)
  787. {
  788. if (array.getReference (index).isAuto())
  789. {
  790. const auto combiner = [&] (const auto acc, const auto& element)
  791. {
  792. const auto item = getItem (element.second);
  793. const auto isNotSpan = std::abs (item.end - item.start) <= 1;
  794. return isNotSpan && item.start == index + 1 - tracksInDirection.numImplicitLeading
  795. ? std::max (acc, getItemSize (*element.first))
  796. : acc;
  797. };
  798. array.getReference (index).size = std::accumulate (placements.begin(), placements.end(), 0.0f, combiner);
  799. }
  800. }
  801. };
  802. setSizes (tracks.rows,
  803. [] (const auto& i) { return i.row; },
  804. [] (const auto& i) { return i.height + i.margin.top + i.margin.bottom; });
  805. setSizes (tracks.columns,
  806. [] (const auto& i) { return i.column; },
  807. [] (const auto& i) { return i.width + i.margin.left + i.margin.right; });
  808. }
  809. };
  810. //==============================================================================
  811. struct BoxAlignment
  812. {
  813. static Rectangle<float> alignItem (const GridItem& item, const Grid& grid, Rectangle<float> area)
  814. {
  815. // if item align is auto, inherit value from grid
  816. const auto alignType = item.alignSelf == GridItem::AlignSelf::autoValue
  817. ? grid.alignItems
  818. : static_cast<AlignItems> (item.alignSelf);
  819. const auto justifyType = item.justifySelf == GridItem::JustifySelf::autoValue
  820. ? grid.justifyItems
  821. : static_cast<JustifyItems> (item.justifySelf);
  822. // subtract margin from area
  823. area = BorderSize<float> (item.margin.top, item.margin.left, item.margin.bottom, item.margin.right)
  824. .subtractedFrom (area);
  825. // align and justify
  826. auto r = area;
  827. if (! approximatelyEqual (item.width, (float) GridItem::notAssigned)) r.setWidth (item.width);
  828. if (! approximatelyEqual (item.height, (float) GridItem::notAssigned)) r.setHeight (item.height);
  829. if (! approximatelyEqual (item.maxWidth, (float) GridItem::notAssigned)) r.setWidth (jmin (item.maxWidth, r.getWidth()));
  830. if (item.minWidth > 0.0f) r.setWidth (jmax (item.minWidth, r.getWidth()));
  831. if (! approximatelyEqual (item.maxHeight, (float) GridItem::notAssigned)) r.setHeight (jmin (item.maxHeight, r.getHeight()));
  832. if (item.minHeight > 0.0f) r.setHeight (jmax (item.minHeight, r.getHeight()));
  833. if (alignType == AlignItems::start && justifyType == JustifyItems::start)
  834. return r;
  835. if (alignType == AlignItems::end) r.setY (r.getY() + (area.getHeight() - r.getHeight()));
  836. if (justifyType == JustifyItems::end) r.setX (r.getX() + (area.getWidth() - r.getWidth()));
  837. if (alignType == AlignItems::center) r.setCentre (r.getCentreX(), area.getCentreY());
  838. if (justifyType == JustifyItems::center) r.setCentre (area.getCentreX(), r.getCentreY());
  839. return r;
  840. }
  841. };
  842. };
  843. //==============================================================================
  844. Grid::TrackInfo::TrackInfo() noexcept : hasKeyword (true) {}
  845. Grid::TrackInfo::TrackInfo (Px sizeInPixels) noexcept
  846. : size (static_cast<float> (sizeInPixels.pixels)), isFraction (false) {}
  847. Grid::TrackInfo::TrackInfo (Fr fractionOfFreeSpace) noexcept
  848. : size ((float)fractionOfFreeSpace.fraction), isFraction (true) {}
  849. Grid::TrackInfo::TrackInfo (Px sizeInPixels, const String& endLineNameToUse) noexcept
  850. : TrackInfo (sizeInPixels)
  851. {
  852. endLineName = endLineNameToUse;
  853. }
  854. Grid::TrackInfo::TrackInfo (Fr fractionOfFreeSpace, const String& endLineNameToUse) noexcept
  855. : TrackInfo (fractionOfFreeSpace)
  856. {
  857. endLineName = endLineNameToUse;
  858. }
  859. Grid::TrackInfo::TrackInfo (const String& startLineNameToUse, Px sizeInPixels) noexcept
  860. : TrackInfo (sizeInPixels)
  861. {
  862. startLineName = startLineNameToUse;
  863. }
  864. Grid::TrackInfo::TrackInfo (const String& startLineNameToUse, Fr fractionOfFreeSpace) noexcept
  865. : TrackInfo (fractionOfFreeSpace)
  866. {
  867. startLineName = startLineNameToUse;
  868. }
  869. Grid::TrackInfo::TrackInfo (const String& startLineNameToUse, Px sizeInPixels, const String& endLineNameToUse) noexcept
  870. : TrackInfo (startLineNameToUse, sizeInPixels)
  871. {
  872. endLineName = endLineNameToUse;
  873. }
  874. Grid::TrackInfo::TrackInfo (const String& startLineNameToUse, Fr fractionOfFreeSpace, const String& endLineNameToUse) noexcept
  875. : TrackInfo (startLineNameToUse, fractionOfFreeSpace)
  876. {
  877. endLineName = endLineNameToUse;
  878. }
  879. float Grid::TrackInfo::getAbsoluteSize (float relativeFractionalUnit) const
  880. {
  881. return isFractional() ? size * relativeFractionalUnit : size;
  882. }
  883. //==============================================================================
  884. void Grid::performLayout (Rectangle<int> targetArea)
  885. {
  886. const auto itemsAndAreas = Helpers::AutoPlacement().deduceAllItems (*this);
  887. auto implicitTracks = Helpers::AutoPlacement::createImplicitTracks (*this, itemsAndAreas);
  888. Helpers::AutoPlacement::applySizeForAutoTracks (implicitTracks, itemsAndAreas);
  889. Helpers::SizeCalculation<Helpers::NoRounding> calculation;
  890. Helpers::SizeCalculation<Helpers::StandardRounding> roundedCalculation;
  891. const auto doComputeSizes = [&] (auto& sizeCalculation)
  892. {
  893. sizeCalculation.computeSizes (targetArea.toFloat().getWidth(),
  894. targetArea.toFloat().getHeight(),
  895. columnGap,
  896. rowGap,
  897. implicitTracks);
  898. };
  899. doComputeSizes (calculation);
  900. doComputeSizes (roundedCalculation);
  901. for (auto& itemAndArea : itemsAndAreas)
  902. {
  903. auto* item = itemAndArea.first;
  904. const auto getBounds = [&] (const auto& sizeCalculation)
  905. {
  906. const auto a = itemAndArea.second;
  907. const auto areaBounds = Helpers::PlacementHelpers::getAreaBounds (a.column,
  908. a.row,
  909. implicitTracks,
  910. sizeCalculation,
  911. alignContent,
  912. justifyContent);
  913. const auto rounded = [&] (auto rect) -> decltype (rect)
  914. {
  915. return { sizeCalculation.roundingFunction (rect.getX()),
  916. sizeCalculation.roundingFunction (rect.getY()),
  917. sizeCalculation.roundingFunction (rect.getWidth()),
  918. sizeCalculation.roundingFunction (rect.getHeight()) };
  919. };
  920. return rounded (Helpers::BoxAlignment::alignItem (*item, *this, areaBounds));
  921. };
  922. item->currentBounds = getBounds (calculation) + targetArea.toFloat().getPosition();
  923. if (auto* c = item->associatedComponent)
  924. c->setBounds (getBounds (roundedCalculation).toNearestIntEdges() + targetArea.getPosition());
  925. }
  926. }
  927. //==============================================================================
  928. #if JUCE_UNIT_TESTS
  929. struct GridTests final : public UnitTest
  930. {
  931. GridTests()
  932. : UnitTest ("Grid", UnitTestCategories::gui)
  933. {}
  934. void runTest() override
  935. {
  936. using Fr = Grid::Fr;
  937. using Tr = Grid::TrackInfo;
  938. using Rect = Rectangle<float>;
  939. beginTest ("Layout calculation of an empty grid is a no-op");
  940. {
  941. const Rectangle<int> bounds { 100, 200 };
  942. Grid grid;
  943. grid.performLayout (bounds);
  944. }
  945. {
  946. Grid grid;
  947. grid.templateColumns.add (Tr (1_fr));
  948. grid.templateRows.addArray ({ Tr (20_px), Tr (1_fr) });
  949. grid.items.addArray ({ GridItem().withArea (1, 1),
  950. GridItem().withArea (2, 1) });
  951. grid.performLayout (Rectangle<int> (200, 400));
  952. beginTest ("Layout calculation test: 1 column x 2 rows: no gap");
  953. expect (grid.items[0].currentBounds == Rect (0.0f, 0.0f, 200.f, 20.0f));
  954. expect (grid.items[1].currentBounds == Rect (0.0f, 20.0f, 200.f, 380.0f));
  955. grid.templateColumns.add (Tr (50_px));
  956. grid.templateRows.add (Tr (2_fr));
  957. grid.items.addArray ( { GridItem().withArea (1, 2),
  958. GridItem().withArea (2, 2),
  959. GridItem().withArea (3, 1),
  960. GridItem().withArea (3, 2) });
  961. grid.performLayout (Rectangle<int> (150, 170));
  962. beginTest ("Layout calculation test: 2 columns x 3 rows: no gap");
  963. expect (grid.items[0].currentBounds == Rect (0.0f, 0.0f, 100.0f, 20.0f));
  964. expect (grid.items[1].currentBounds == Rect (0.0f, 20.0f, 100.0f, 50.0f));
  965. expect (grid.items[2].currentBounds == Rect (100.0f, 0.0f, 50.0f, 20.0f));
  966. expect (grid.items[3].currentBounds == Rect (100.0f, 20.0f, 50.0f, 50.0f));
  967. expect (grid.items[4].currentBounds == Rect (0.0f, 70.0f, 100.0f, 100.0f));
  968. expect (grid.items[5].currentBounds == Rect (100.0f, 70.0f, 50.0f, 100.0f));
  969. grid.columnGap = 20_px;
  970. grid.rowGap = 10_px;
  971. grid.performLayout (Rectangle<int> (200, 310));
  972. beginTest ("Layout calculation test: 2 columns x 3 rows: rowGap of 10 and columnGap of 20");
  973. expect (grid.items[0].currentBounds == Rect (0.0f, 0.0f, 130.0f, 20.0f));
  974. expect (grid.items[1].currentBounds == Rect (0.0f, 30.0f, 130.0f, 90.0f));
  975. expect (grid.items[2].currentBounds == Rect (150.0f, 0.0f, 50.0f, 20.0f));
  976. expect (grid.items[3].currentBounds == Rect (150.0f, 30.0f, 50.0f, 90.0f));
  977. expect (grid.items[4].currentBounds == Rect (0.0f, 130.0f, 130.0f, 180.0f));
  978. expect (grid.items[5].currentBounds == Rect (150.0f, 130.0f, 50.0f, 180.0f));
  979. }
  980. {
  981. Grid grid;
  982. grid.templateColumns.addArray ({ Tr ("first", 20_px, "in"), Tr ("in", 1_fr, "in"), Tr (20_px, "last") });
  983. grid.templateRows.addArray ({ Tr (1_fr),
  984. Tr (20_px)});
  985. {
  986. beginTest ("Grid items placement tests: integer and custom ident, counting forward");
  987. GridItem i1, i2, i3, i4, i5;
  988. i1.column = { 1, 4 };
  989. i1.row = { 1, 2 };
  990. i2.column = { 1, 3 };
  991. i2.row = { 1, 3 };
  992. i3.column = { "first", "in" };
  993. i3.row = { 2, 3 };
  994. i4.column = { "first", { 2, "in" } };
  995. i4.row = { 1, 2 };
  996. i5.column = { "first", "last" };
  997. i5.row = { 1, 2 };
  998. grid.items.addArray ({ i1, i2, i3, i4, i5 });
  999. grid.performLayout ({ 140, 100 });
  1000. expect (grid.items[0].currentBounds == Rect (0.0f, 0.0f, 140.0f, 80.0f));
  1001. expect (grid.items[1].currentBounds == Rect (0.0f, 0.0f, 120.0f, 100.0f));
  1002. expect (grid.items[2].currentBounds == Rect (0.0f, 80.0f, 20.0f, 20.0f));
  1003. expect (grid.items[3].currentBounds == Rect (0.0f, 0.0f, 120.0f, 80.0f));
  1004. expect (grid.items[4].currentBounds == Rect (0.0f, 0.0f, 140.0f, 80.0f));
  1005. }
  1006. }
  1007. {
  1008. Grid grid;
  1009. grid.templateColumns.addArray ({ Tr ("first", 20_px, "in"), Tr ("in", 1_fr, "in"), Tr (20_px, "last") });
  1010. grid.templateRows.addArray ({ Tr (1_fr),
  1011. Tr (20_px)});
  1012. beginTest ("Grid items placement tests: integer and custom ident, counting forward, reversed end and start");
  1013. GridItem i1, i2, i3, i4, i5;
  1014. i1.column = { 4, 1 };
  1015. i1.row = { 2, 1 };
  1016. i2.column = { 3, 1 };
  1017. i2.row = { 3, 1 };
  1018. i3.column = { "in", "first" };
  1019. i3.row = { 3, 2 };
  1020. i4.column = { "first", { 2, "in" } };
  1021. i4.row = { 1, 2 };
  1022. i5.column = { "last", "first" };
  1023. i5.row = { 1, 2 };
  1024. grid.items.addArray ({ i1, i2, i3, i4, i5 });
  1025. grid.performLayout ({ 140, 100 });
  1026. expect (grid.items[0].currentBounds == Rect (0.0f, 0.0f, 140.0f, 80.0f));
  1027. expect (grid.items[1].currentBounds == Rect (0.0f, 0.0f, 120.0f, 100.0f));
  1028. expect (grid.items[2].currentBounds == Rect (0.0f, 80.0f, 20.0f, 20.0f));
  1029. expect (grid.items[3].currentBounds == Rect (0.0f, 0.0f, 120.0f, 80.0f));
  1030. expect (grid.items[4].currentBounds == Rect (0.0f, 0.0f, 140.0f, 80.0f));
  1031. }
  1032. {
  1033. Grid grid;
  1034. grid.templateColumns = { Tr ("first", 20_px, "in"), Tr ("in", 1_fr, "in"), Tr (20_px, "last") };
  1035. grid.templateRows = { Tr (1_fr), Tr (20_px) };
  1036. beginTest ("Grid items placement tests: integer, counting backward");
  1037. grid.items = { GridItem{}.withColumn ({ -2, -1 }).withRow ({ 1, 3 }),
  1038. GridItem{}.withColumn ({ -10, -1 }).withRow ({ 1, -1 }) };
  1039. grid.performLayout ({ 140, 100 });
  1040. expect (grid.items[0].currentBounds == Rect (120.0f, 0.0f, 20.0f, 100.0f));
  1041. expect (grid.items[1].currentBounds == Rect (0.0f, 0.0f, 140.0f, 100.0f));
  1042. }
  1043. {
  1044. beginTest ("Grid items placement tests: areas");
  1045. Grid grid;
  1046. grid.templateColumns = { Tr (50_px), Tr (100_px), Tr (Fr (1_fr)), Tr (50_px) };
  1047. grid.templateRows = { Tr (50_px),
  1048. Tr (1_fr),
  1049. Tr (50_px) };
  1050. grid.templateAreas = { "header header header header",
  1051. "main main . sidebar",
  1052. "footer footer footer footer" };
  1053. grid.items.addArray ({ GridItem().withArea ("header"),
  1054. GridItem().withArea ("main"),
  1055. GridItem().withArea ("sidebar"),
  1056. GridItem().withArea ("footer"),
  1057. });
  1058. grid.performLayout ({ 300, 150 });
  1059. expect (grid.items[0].currentBounds == Rect (0.f, 0.f, 300.f, 50.f));
  1060. expect (grid.items[1].currentBounds == Rect (0.f, 50.f, 150.f, 50.f));
  1061. expect (grid.items[2].currentBounds == Rect (250.f, 50.f, 50.f, 50.f));
  1062. expect (grid.items[3].currentBounds == Rect (0.f, 100.f, 300.f, 50.f));
  1063. }
  1064. {
  1065. beginTest ("Grid implicit rows and columns: triggered by areas");
  1066. Grid grid;
  1067. grid.templateColumns = { Tr (50_px), Tr (100_px), Tr (1_fr), Tr (50_px) };
  1068. grid.templateRows = { Tr (50_px),
  1069. Tr (1_fr),
  1070. Tr (50_px) };
  1071. grid.autoRows = Tr (30_px);
  1072. grid.autoColumns = Tr (30_px);
  1073. grid.templateAreas = { "header header header header header",
  1074. "main main . sidebar sidebar",
  1075. "footer footer footer footer footer",
  1076. "sub sub sub sub sub"};
  1077. grid.items.addArray ({ GridItem().withArea ("header"),
  1078. GridItem().withArea ("main"),
  1079. GridItem().withArea ("sidebar"),
  1080. GridItem().withArea ("footer"),
  1081. GridItem().withArea ("sub"),
  1082. });
  1083. grid.performLayout ({ 330, 180 });
  1084. expect (grid.items[0].currentBounds == Rect (0.f, 0.f, 330.f, 50.f));
  1085. expect (grid.items[1].currentBounds == Rect (0.f, 50.f, 150.f, 50.f));
  1086. expect (grid.items[2].currentBounds == Rect (250.f, 50.f, 80.f, 50.f));
  1087. expect (grid.items[3].currentBounds == Rect (0.f, 100.f, 330.f, 50.f));
  1088. expect (grid.items[4].currentBounds == Rect (0.f, 150.f, 330.f, 30.f));
  1089. }
  1090. {
  1091. beginTest ("Grid implicit rows and columns: triggered by areas");
  1092. Grid grid;
  1093. grid.templateColumns = { Tr (50_px), Tr (100_px), Tr (1_fr), Tr (50_px) };
  1094. grid.templateRows = { Tr (50_px),
  1095. Tr (1_fr),
  1096. Tr (50_px) };
  1097. grid.autoRows = Tr (1_fr);
  1098. grid.autoColumns = Tr (1_fr);
  1099. grid.templateAreas = { "header header header header",
  1100. "main main . sidebar",
  1101. "footer footer footer footer" };
  1102. grid.items.addArray ({ GridItem().withArea ("header"),
  1103. GridItem().withArea ("main"),
  1104. GridItem().withArea ("sidebar"),
  1105. GridItem().withArea ("footer"),
  1106. GridItem().withArea (4, 5, 6, 7)
  1107. });
  1108. grid.performLayout ({ 350, 250 });
  1109. expect (grid.items[0].currentBounds == Rect (0.f, 0.f, 250.f, 50.f));
  1110. expect (grid.items[1].currentBounds == Rect (0.f, 50.f, 150.f, 50.f));
  1111. expect (grid.items[2].currentBounds == Rect (200.f, 50.f, 50.f, 50.f));
  1112. expect (grid.items[3].currentBounds == Rect (0.f, 100.f, 250.f, 50.f));
  1113. expect (grid.items[4].currentBounds == Rect (250.f, 150.f, 100.f, 100.f));
  1114. }
  1115. {
  1116. beginTest ("Grid implicit rows and columns: triggered by out-of-bounds indices");
  1117. Grid grid;
  1118. grid.templateColumns = { Tr (1_fr), Tr (1_fr) };
  1119. grid.templateRows = { Tr (60_px), Tr (60_px) };
  1120. grid.autoColumns = Tr (20_px);
  1121. grid.autoRows = Tr (1_fr);
  1122. grid.items = { GridItem{}.withColumn ({ 5, 8 }).withRow ({ -5, -4 }),
  1123. GridItem{}.withColumn ({ 4, 7 }).withRow ({ -4, -3 }),
  1124. GridItem{}.withColumn ({ -2, -1 }).withRow ({ 4, 5 }) };
  1125. grid.performLayout ({ 500, 400 });
  1126. // -3 -2 -1
  1127. // 1 2 3 4 5 6 7 8
  1128. // -5 +---+---+---+---+---+---+---+ 0
  1129. // | | | | | 0 | 0 | 0 |
  1130. // -4 +---+---+---+---+---+---+---+ 70
  1131. // | | | | 1 | 1 | 1 | |
  1132. // -3 1 +---+---+---+---+---+---+---+ 140
  1133. // | x | x | | | | | |
  1134. // -2 2 +---+---+---+---+---+---+---+ 200 y positions
  1135. // | x | x | | | | | |
  1136. // -1 3 +---+---+---+---+---+---+---+ 260
  1137. // | | | | | | | |
  1138. // 4 +---+---+---+---+---+---+---+ 330
  1139. // | | 2 | | | | | |
  1140. // 5 +---+---+---+---+---+---+---+ 400
  1141. //
  1142. // 0 200 400 420 440 460 480 500
  1143. // x positions
  1144. //
  1145. // The cells marked "x" are the explicit cells specified by the template rows
  1146. // and columns.
  1147. //
  1148. // The cells marked 0/1/2 correspond to the GridItems at those indices in the
  1149. // items array.
  1150. //
  1151. // Note that negative indices count back from the last explicit line
  1152. // number in that direction, so "2" and "-2" both correspond to the same line.
  1153. expect (grid.items[0].currentBounds == Rect (440.0f, 0.0f, 60.0f, 70.0f));
  1154. expect (grid.items[1].currentBounds == Rect (420.0f, 70.0f, 60.0f, 70.0f));
  1155. expect (grid.items[2].currentBounds == Rect (200.0f, 330.0f, 200.0f, 70.0f));
  1156. }
  1157. {
  1158. beginTest ("Items with specified sizes should translate to correctly rounded Component dimensions");
  1159. static constexpr int targetSize = 100;
  1160. juce::Component component;
  1161. juce::GridItem item { component };
  1162. item.alignSelf = juce::GridItem::AlignSelf::center;
  1163. item.justifySelf = juce::GridItem::JustifySelf::center;
  1164. item.width = (float) targetSize;
  1165. item.height = (float) targetSize;
  1166. juce::Grid grid;
  1167. grid.templateColumns = { juce::Grid::Fr { 1 } };
  1168. grid.templateRows = { juce::Grid::Fr { 1 } };
  1169. grid.items = { item };
  1170. for (int totalSize = 100 - 20; totalSize < 100 + 20; ++totalSize)
  1171. {
  1172. Rectangle<int> bounds { 0, 0, totalSize, totalSize };
  1173. grid.performLayout (bounds);
  1174. expectEquals (component.getWidth(), targetSize);
  1175. expectEquals (component.getHeight(), targetSize);
  1176. }
  1177. }
  1178. {
  1179. beginTest ("Track sizes specified in Px should translate to correctly rounded Component dimensions");
  1180. static constexpr int targetSize = 100;
  1181. juce::Component component;
  1182. juce::GridItem item { component };
  1183. item.alignSelf = juce::GridItem::AlignSelf::center;
  1184. item.justifySelf = juce::GridItem::JustifySelf::center;
  1185. item.setArea (1, 3);
  1186. juce::Grid grid;
  1187. grid.templateColumns = { juce::Grid::Fr { 1 },
  1188. juce::Grid::Fr { 1 },
  1189. juce::Grid::Px { targetSize },
  1190. juce::Grid::Fr { 1 } };
  1191. grid.templateRows = { juce::Grid::Fr { 1 } };
  1192. grid.items = { item };
  1193. for (int totalSize = 100 - 20; totalSize < 100 + 20; ++totalSize)
  1194. {
  1195. Rectangle<int> bounds { 0, 0, totalSize, totalSize };
  1196. grid.performLayout (bounds);
  1197. expectEquals (component.getWidth(), targetSize);
  1198. }
  1199. }
  1200. {
  1201. beginTest ("Evaluate invariants on randomised Grid layouts");
  1202. struct Solution
  1203. {
  1204. Grid grid;
  1205. std::deque<Component> components;
  1206. int absoluteWidth;
  1207. Rectangle<int> bounds;
  1208. };
  1209. auto createSolution = [this] (int numColumns,
  1210. float probabilityOfFractionalColumn,
  1211. Rectangle<int> bounds) -> Solution
  1212. {
  1213. auto random = getRandom();
  1214. Grid grid;
  1215. grid.templateRows = { Grid::Fr { 1 } };
  1216. // Ensuring that the sum of absolute item widths never exceed total width
  1217. const auto widthOfAbsolute = (int) ((float) bounds.getWidth() / (float) (numColumns + 1));
  1218. for (int i = 0; i < numColumns; ++i)
  1219. {
  1220. if (random.nextFloat() < probabilityOfFractionalColumn)
  1221. grid.templateColumns.add (Grid::Fr { 1 });
  1222. else
  1223. grid.templateColumns.add (Grid::Px { widthOfAbsolute });
  1224. }
  1225. std::deque<Component> itemComponents (static_cast<size_t> (grid.templateColumns.size()));
  1226. for (auto& c : itemComponents)
  1227. grid.items.add (GridItem { c });
  1228. grid.performLayout (bounds);
  1229. return { std::move (grid), std::move (itemComponents), widthOfAbsolute, bounds };
  1230. };
  1231. const auto getFractionalComponentWidths = [] (const Solution& solution)
  1232. {
  1233. std::vector<int> result;
  1234. for (int i = 0; i < solution.grid.templateColumns.size(); ++i)
  1235. if (solution.grid.templateColumns[i].isFractional())
  1236. result.push_back (solution.components[(size_t) i].getWidth());
  1237. return result;
  1238. };
  1239. const auto getAbsoluteComponentWidths = [] (const Solution& solution)
  1240. {
  1241. std::vector<int> result;
  1242. for (int i = 0; i < solution.grid.templateColumns.size(); ++i)
  1243. if (! solution.grid.templateColumns[i].isFractional())
  1244. result.push_back (solution.components[(size_t) i].getWidth());
  1245. return result;
  1246. };
  1247. const auto evaluateInvariants = [&] (const Solution& solution)
  1248. {
  1249. const auto fractionalWidths = getFractionalComponentWidths (solution);
  1250. if (! fractionalWidths.empty())
  1251. {
  1252. const auto [min, max] = std::minmax_element (fractionalWidths.begin(),
  1253. fractionalWidths.end());
  1254. expectLessOrEqual (*max - *min, 1, "Fr { 1 } items are expected to share the "
  1255. "rounding errors equally and hence couldn't "
  1256. "deviate in size by more than 1 px");
  1257. }
  1258. const auto absoluteWidths = getAbsoluteComponentWidths (solution);
  1259. for (const auto& w : absoluteWidths)
  1260. expectEquals (w, solution.absoluteWidth, "Sizes specified in absolute dimensions should "
  1261. "be preserved");
  1262. Rectangle<int> unionOfComponentBounds;
  1263. for (const auto& c : solution.components)
  1264. unionOfComponentBounds = unionOfComponentBounds.getUnion (c.getBoundsInParent());
  1265. if ((size_t) solution.grid.templateColumns.size() == absoluteWidths.size())
  1266. expect (solution.bounds.contains (unionOfComponentBounds), "Non-oversized absolute Components "
  1267. "should never be placed outside the "
  1268. "provided bounds.");
  1269. else
  1270. expect (unionOfComponentBounds == solution.bounds, "With fractional items, positioned items "
  1271. "should cover the provided bounds exactly");
  1272. };
  1273. const auto knownPreviousBad = createSolution (5, 1.0f, Rectangle<int> { 0, 0, 600, 200 }.reduced (16));
  1274. evaluateInvariants (knownPreviousBad);
  1275. auto random = getRandom();
  1276. for (int i = 0; i < 1000; ++i)
  1277. {
  1278. const auto numColumns = random.nextInt (Range<int> { 1, 26 });
  1279. const auto probabilityOfFractionalColumn = random.nextFloat();
  1280. const auto bounds = Rectangle<int> { random.nextInt (Range<int> { 0, 3 }),
  1281. random.nextInt (Range<int> { 0, 3 }),
  1282. random.nextInt (Range<int> { 300, 1200 }),
  1283. random.nextInt (Range<int> { 100, 500 }) }
  1284. .reduced (random.nextInt (Range<int> { 0, 16 }));
  1285. const auto randomSolution = createSolution (numColumns, probabilityOfFractionalColumn, bounds);
  1286. evaluateInvariants (randomSolution);
  1287. }
  1288. }
  1289. }
  1290. };
  1291. static GridTests gridUnitTests;
  1292. #endif
  1293. } // namespace juce