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.

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