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.

1265 lines
50KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  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 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. namespace juce
  20. {
  21. struct Grid::SizeCalculation
  22. {
  23. static float getTotalAbsoluteSize (const juce::Array<Grid::TrackInfo>& tracks, Px gapSize) noexcept
  24. {
  25. float totalCellSize = 0.0f;
  26. for (const auto& trackInfo : tracks)
  27. if (! trackInfo.isFraction || trackInfo.hasKeyword)
  28. totalCellSize += trackInfo.size;
  29. float totalGap = tracks.size() > 1 ? static_cast<float> ((tracks.size() - 1) * gapSize.pixels)
  30. : 0.0f;
  31. return totalCellSize + totalGap;
  32. }
  33. static float getRelativeUnitSize (float size, float totalAbsolute, const juce::Array<Grid::TrackInfo>& tracks) noexcept
  34. {
  35. const float totalRelative = juce::jlimit (0.0f, size, size - totalAbsolute);
  36. float factorsSum = 0.0f;
  37. for (const auto& trackInfo : tracks)
  38. if (trackInfo.isFraction)
  39. factorsSum += trackInfo.size;
  40. jassert (factorsSum != 0.0f);
  41. return totalRelative / factorsSum;
  42. }
  43. //==============================================================================
  44. static float getTotalAbsoluteHeight (const juce::Array<Grid::TrackInfo>& rowTracks, Px rowGap)
  45. {
  46. return getTotalAbsoluteSize (rowTracks, rowGap);
  47. }
  48. static float getTotalAbsoluteWidth (const juce::Array<Grid::TrackInfo>& columnTracks, Px columnGap)
  49. {
  50. return getTotalAbsoluteSize (columnTracks, columnGap);
  51. }
  52. static float getRelativeWidthUnit (float gridWidth, Px columnGap, const juce::Array<Grid::TrackInfo>& columnTracks)
  53. {
  54. return getRelativeUnitSize (gridWidth, getTotalAbsoluteWidth (columnTracks, columnGap), columnTracks);
  55. }
  56. static float getRelativeHeightUnit (float gridHeight, Px rowGap, const juce::Array<Grid::TrackInfo>& rowTracks)
  57. {
  58. return getRelativeUnitSize (gridHeight, getTotalAbsoluteHeight (rowTracks, rowGap), rowTracks);
  59. }
  60. //==============================================================================
  61. static bool hasAnyFractions (const juce::Array<Grid::TrackInfo>& tracks)
  62. {
  63. for (auto& t : tracks)
  64. if (t.isFraction)
  65. return true;
  66. return false;
  67. }
  68. void computeSizes (float gridWidth, float gridHeight,
  69. Px columnGapToUse, Px rowGapToUse,
  70. const juce::Array<Grid::TrackInfo>& columnTracks,
  71. const juce::Array<Grid::TrackInfo>& rowTracks)
  72. {
  73. if (hasAnyFractions (columnTracks))
  74. relativeWidthUnit = getRelativeWidthUnit (gridWidth, columnGapToUse, columnTracks);
  75. else
  76. remainingWidth = gridWidth - getTotalAbsoluteSize (columnTracks, columnGapToUse);
  77. if (hasAnyFractions (rowTracks))
  78. relativeHeightUnit = getRelativeHeightUnit (gridHeight, rowGapToUse, rowTracks);
  79. else
  80. remainingHeight = gridHeight - getTotalAbsoluteSize (rowTracks, rowGapToUse);
  81. }
  82. float relativeWidthUnit = 0.0f;
  83. float relativeHeightUnit = 0.0f;
  84. float remainingWidth = 0.0f;
  85. float remainingHeight = 0.0f;
  86. };
  87. //==============================================================================
  88. struct Grid::PlacementHelpers
  89. {
  90. enum { invalid = -999999 };
  91. static constexpr auto emptyAreaCharacter = ".";
  92. //==============================================================================
  93. struct LineRange { int start, end; };
  94. struct LineArea { LineRange column, row; };
  95. struct LineInfo { juce::StringArray lineNames; };
  96. struct NamedArea
  97. {
  98. juce::String name;
  99. LineArea lines;
  100. };
  101. //==============================================================================
  102. static juce::Array<LineInfo> getArrayOfLinesFromTracks (const juce::Array<Grid::TrackInfo>& tracks)
  103. {
  104. // fill line info array
  105. juce::Array<LineInfo> lines;
  106. for (int i = 1; i <= tracks.size(); ++i)
  107. {
  108. const auto& currentTrack = tracks.getReference (i - 1);
  109. if (i == 1) // start line
  110. {
  111. LineInfo li;
  112. li.lineNames.add (currentTrack.startLineName);
  113. lines.add (li);
  114. }
  115. if (i > 1 && i <= tracks.size()) // two lines in between tracks
  116. {
  117. const auto& prevTrack = tracks.getReference (i - 2);
  118. LineInfo li;
  119. li.lineNames.add (prevTrack.endLineName);
  120. li.lineNames.add (currentTrack.startLineName);
  121. lines.add (li);
  122. }
  123. if (i == tracks.size()) // end line
  124. {
  125. LineInfo li;
  126. li.lineNames.add (currentTrack.endLineName);
  127. lines.add (li);
  128. }
  129. }
  130. jassert (lines.size() == tracks.size() + 1);
  131. return lines;
  132. }
  133. //==============================================================================
  134. static int deduceAbsoluteLineNumberFromLineName (GridItem::Property prop,
  135. const juce::Array<Grid::TrackInfo>& tracks)
  136. {
  137. jassert (prop.hasAbsolute());
  138. const auto lines = getArrayOfLinesFromTracks (tracks);
  139. int count = 0;
  140. for (int i = 0; i < lines.size(); i++)
  141. {
  142. for (const auto& name : lines.getReference (i).lineNames)
  143. {
  144. if (prop.name == name)
  145. {
  146. ++count;
  147. break;
  148. }
  149. }
  150. if (count == prop.number)
  151. return i + 1;
  152. }
  153. jassertfalse;
  154. return count;
  155. }
  156. static int deduceAbsoluteLineNumber (GridItem::Property prop,
  157. const juce::Array<Grid::TrackInfo>& tracks)
  158. {
  159. jassert (prop.hasAbsolute());
  160. if (prop.hasName())
  161. return deduceAbsoluteLineNumberFromLineName (prop, tracks);
  162. return prop.number > 0 ? prop.number : tracks.size() + 2 + prop.number;
  163. }
  164. static int deduceAbsoluteLineNumberFromNamedSpan (int startLineNumber,
  165. GridItem::Property propertyWithSpan,
  166. const juce::Array<Grid::TrackInfo>& tracks)
  167. {
  168. jassert (propertyWithSpan.hasSpan());
  169. const auto lines = getArrayOfLinesFromTracks (tracks);
  170. int count = 0;
  171. for (int i = startLineNumber; i < lines.size(); i++)
  172. {
  173. for (const auto& name : lines.getReference (i).lineNames)
  174. {
  175. if (propertyWithSpan.name == name)
  176. {
  177. ++count;
  178. break;
  179. }
  180. }
  181. if (count == propertyWithSpan.number)
  182. return i + 1;
  183. }
  184. jassertfalse;
  185. return count;
  186. }
  187. static int deduceAbsoluteLineNumberBasedOnSpan (int startLineNumber,
  188. GridItem::Property propertyWithSpan,
  189. const juce::Array<Grid::TrackInfo>& tracks)
  190. {
  191. jassert (propertyWithSpan.hasSpan());
  192. if (propertyWithSpan.hasName())
  193. return deduceAbsoluteLineNumberFromNamedSpan (startLineNumber, propertyWithSpan, tracks);
  194. return startLineNumber + propertyWithSpan.number;
  195. }
  196. //==============================================================================
  197. static LineRange deduceLineRange (GridItem::StartAndEndProperty prop, const juce::Array<Grid::TrackInfo>& tracks)
  198. {
  199. LineRange s;
  200. jassert (! (prop.start.hasAuto() && prop.end.hasAuto()));
  201. if (prop.start.hasAbsolute() && prop.end.hasAuto())
  202. {
  203. prop.end = GridItem::Span (1);
  204. }
  205. else if (prop.start.hasAuto() && prop.end.hasAbsolute())
  206. {
  207. prop.start = GridItem::Span (1);
  208. }
  209. if (prop.start.hasAbsolute() && prop.end.hasAbsolute())
  210. {
  211. s.start = deduceAbsoluteLineNumber (prop.start, tracks);
  212. s.end = deduceAbsoluteLineNumber (prop.end, tracks);
  213. }
  214. else if (prop.start.hasAbsolute() && prop.end.hasSpan())
  215. {
  216. s.start = deduceAbsoluteLineNumber (prop.start, tracks);
  217. s.end = deduceAbsoluteLineNumberBasedOnSpan (s.start, prop.end, tracks);
  218. }
  219. else if (prop.start.hasSpan() && prop.end.hasAbsolute())
  220. {
  221. s.start = deduceAbsoluteLineNumber (prop.end, tracks);
  222. s.end = deduceAbsoluteLineNumberBasedOnSpan (s.start, prop.start, tracks);
  223. }
  224. else
  225. {
  226. // Can't have an item with spans on both start and end.
  227. jassertfalse;
  228. s.start = s.end = {};
  229. }
  230. // swap if start overtakes end
  231. if (s.start > s.end)
  232. std::swap (s.start, s.end);
  233. else if (s.start == s.end)
  234. s.end = s.start + 1;
  235. return s;
  236. }
  237. static LineArea deduceLineArea (const GridItem& item,
  238. const Grid& grid,
  239. const std::map<juce::String, LineArea>& namedAreas)
  240. {
  241. if (item.area.isNotEmpty() && ! grid.templateAreas.isEmpty())
  242. {
  243. // Must be a named area!
  244. jassert (namedAreas.count (item.area) != 0);
  245. return namedAreas.at (item.area);
  246. }
  247. return { deduceLineRange (item.column, grid.templateColumns),
  248. deduceLineRange (item.row, grid.templateRows) };
  249. }
  250. //==============================================================================
  251. static juce::Array<juce::StringArray> parseAreasProperty (const juce::StringArray& areasStrings)
  252. {
  253. juce::Array<juce::StringArray> strings;
  254. for (const auto& areaString : areasStrings)
  255. strings.add (juce::StringArray::fromTokens (areaString, false));
  256. if (strings.size() > 0)
  257. {
  258. for (auto s : strings)
  259. {
  260. jassert (s.size() == strings[0].size()); // all rows must have the same number of columns
  261. }
  262. }
  263. return strings;
  264. }
  265. static NamedArea findArea (juce::Array<juce::StringArray>& stringsArrays)
  266. {
  267. NamedArea area;
  268. for (auto& stringArray : stringsArrays)
  269. {
  270. for (auto& string : stringArray)
  271. {
  272. // find anchor
  273. if (area.name.isEmpty())
  274. {
  275. if (string != emptyAreaCharacter)
  276. {
  277. area.name = string;
  278. area.lines.row.start = stringsArrays.indexOf (stringArray) + 1; // non-zero indexed;
  279. area.lines.column.start = stringArray.indexOf (string) + 1; // non-zero indexed;
  280. area.lines.row.end = stringsArrays.indexOf (stringArray) + 2;
  281. area.lines.column.end = stringArray.indexOf (string) + 2;
  282. // mark as visited
  283. string = emptyAreaCharacter;
  284. }
  285. }
  286. else
  287. {
  288. if (string == area.name)
  289. {
  290. area.lines.row.end = stringsArrays.indexOf (stringArray) + 2;
  291. area.lines.column.end = stringArray.indexOf (string) + 2;
  292. // mark as visited
  293. string = emptyAreaCharacter;
  294. }
  295. }
  296. }
  297. }
  298. return area;
  299. }
  300. //==============================================================================
  301. static std::map<juce::String, LineArea> deduceNamedAreas (const juce::StringArray& areasStrings)
  302. {
  303. auto stringsArrays = parseAreasProperty (areasStrings);
  304. std::map<juce::String, LineArea> areas;
  305. for (auto area = findArea (stringsArrays); area.name.isNotEmpty(); area = findArea (stringsArrays))
  306. {
  307. if (areas.count (area.name) == 0)
  308. areas[area.name] = area.lines;
  309. else
  310. // Make sure your template-areas property only has one area with the same name and is well-formed
  311. jassertfalse;
  312. }
  313. return areas;
  314. }
  315. //==============================================================================
  316. static float getCoord (int trackNumber, float relativeUnit, Px gap, const juce::Array<Grid::TrackInfo>& tracks)
  317. {
  318. float c = 0;
  319. for (const auto* it = tracks.begin(); it != tracks.begin() + trackNumber - 1; ++it)
  320. c += (it->isFraction ? it->size * relativeUnit : it->size) + static_cast<float> (gap.pixels);
  321. return c;
  322. }
  323. static juce::Rectangle<float> getCellBounds (int columnNumber, int rowNumber,
  324. const juce::Array<Grid::TrackInfo>& columnTracks,
  325. const juce::Array<Grid::TrackInfo>& rowTracks,
  326. Grid::SizeCalculation calculation,
  327. Px columnGap, Px rowGap)
  328. {
  329. jassert (columnNumber >= 1 && columnNumber <= columnTracks.size());
  330. jassert (rowNumber >= 1 && rowNumber <= rowTracks.size());
  331. const auto x = getCoord (columnNumber, calculation.relativeWidthUnit, columnGap, columnTracks);
  332. const auto y = getCoord (rowNumber, calculation.relativeHeightUnit, rowGap, rowTracks);
  333. const auto& columnTrackInfo = columnTracks.getReference (columnNumber - 1);
  334. const float width = columnTrackInfo.isFraction ? columnTrackInfo.size * calculation.relativeWidthUnit
  335. : columnTrackInfo.size;
  336. const auto& rowTrackInfo = rowTracks.getReference (rowNumber - 1);
  337. const float height = rowTrackInfo.isFraction ? rowTrackInfo.size * calculation.relativeHeightUnit
  338. : rowTrackInfo.size;
  339. return { x, y, width, height };
  340. }
  341. static juce::Rectangle<float> alignCell (juce::Rectangle<float> area,
  342. int columnNumber, int rowNumber,
  343. int numberOfColumns, int numberOfRows,
  344. Grid::SizeCalculation calculation,
  345. Grid::AlignContent alignContent,
  346. Grid::JustifyContent justifyContent)
  347. {
  348. if (alignContent == Grid::AlignContent::end)
  349. area.setY (area.getY() + calculation.remainingHeight);
  350. if (justifyContent == Grid::JustifyContent::end)
  351. area.setX (area.getX() + calculation.remainingWidth);
  352. if (alignContent == Grid::AlignContent::center)
  353. area.setY (area.getY() + calculation.remainingHeight / 2);
  354. if (justifyContent == Grid::JustifyContent::center)
  355. area.setX (area.getX() + calculation.remainingWidth / 2);
  356. if (alignContent == Grid::AlignContent::spaceBetween)
  357. {
  358. const auto shift = ((rowNumber - 1) * (calculation.remainingHeight / float(numberOfRows - 1)));
  359. area.setY (area.getY() + shift);
  360. }
  361. if (justifyContent == Grid::JustifyContent::spaceBetween)
  362. {
  363. const auto shift = ((columnNumber - 1) * (calculation.remainingWidth / float(numberOfColumns - 1)));
  364. area.setX (area.getX() + shift);
  365. }
  366. if (alignContent == Grid::AlignContent::spaceEvenly)
  367. {
  368. const auto shift = (rowNumber * (calculation.remainingHeight / float(numberOfRows + 1)));
  369. area.setY (area.getY() + shift);
  370. }
  371. if (justifyContent == Grid::JustifyContent::spaceEvenly)
  372. {
  373. const auto shift = (columnNumber * (calculation.remainingWidth / float(numberOfColumns + 1)));
  374. area.setX (area.getX() + shift);
  375. }
  376. if (alignContent == Grid::AlignContent::spaceAround)
  377. {
  378. const auto inbetweenShift = calculation.remainingHeight / float(numberOfRows);
  379. const auto sidesShift = inbetweenShift / 2;
  380. auto shift = (rowNumber - 1) * inbetweenShift + sidesShift;
  381. area.setY (area.getY() + shift);
  382. }
  383. if (justifyContent == Grid::JustifyContent::spaceAround)
  384. {
  385. const auto inbetweenShift = calculation.remainingWidth / float(numberOfColumns);
  386. const auto sidesShift = inbetweenShift / 2;
  387. auto shift = (columnNumber - 1) * inbetweenShift + sidesShift;
  388. area.setX (area.getX() + shift);
  389. }
  390. return area;
  391. }
  392. static juce::Rectangle<float> getAreaBounds (int columnLineNumberStart, int columnLineNumberEnd,
  393. int rowLineNumberStart, int rowLineNumberEnd,
  394. const juce::Array<Grid::TrackInfo>& columnTracks,
  395. const juce::Array<Grid::TrackInfo>& rowTracks,
  396. Grid::SizeCalculation calculation,
  397. Grid::AlignContent alignContent,
  398. Grid::JustifyContent justifyContent,
  399. Px columnGap, Px rowGap)
  400. {
  401. auto startCell = getCellBounds (columnLineNumberStart, rowLineNumberStart,
  402. columnTracks, rowTracks,
  403. calculation,
  404. columnGap, rowGap);
  405. auto endCell = getCellBounds (columnLineNumberEnd - 1, rowLineNumberEnd - 1,
  406. columnTracks, rowTracks,
  407. calculation,
  408. columnGap, rowGap);
  409. startCell = alignCell (startCell,
  410. columnLineNumberStart, rowLineNumberStart,
  411. columnTracks.size(), rowTracks.size(),
  412. calculation,
  413. alignContent,
  414. justifyContent);
  415. endCell = alignCell (endCell,
  416. columnLineNumberEnd - 1, rowLineNumberEnd - 1,
  417. columnTracks.size(), rowTracks.size(),
  418. calculation,
  419. alignContent,
  420. justifyContent);
  421. auto horizontalRange = startCell.getHorizontalRange().getUnionWith (endCell.getHorizontalRange());
  422. auto verticalRange = startCell.getVerticalRange().getUnionWith (endCell.getVerticalRange());
  423. return { horizontalRange.getStart(), verticalRange.getStart(),
  424. horizontalRange.getLength(), verticalRange.getLength() };
  425. }
  426. };
  427. //==============================================================================
  428. struct Grid::AutoPlacement
  429. {
  430. using ItemPlacementArray = juce::Array<std::pair<GridItem*, Grid::PlacementHelpers::LineArea>>;
  431. //==============================================================================
  432. struct OccupancyPlane
  433. {
  434. struct Cell { int column, row; };
  435. OccupancyPlane (int highestColumnToUse, int highestRowToUse, bool isColumnFirst)
  436. : highestCrossDimension (isColumnFirst ? highestRowToUse : highestColumnToUse),
  437. columnFirst (isColumnFirst)
  438. {}
  439. Grid::PlacementHelpers::LineArea setCell (Cell cell, int columnSpan, int rowSpan)
  440. {
  441. for (int i = 0; i < columnSpan; i++)
  442. for (int j = 0; j < rowSpan; j++)
  443. setCell (cell.column + i, cell.row + j);
  444. return { { cell.column, cell.column + columnSpan }, { cell.row, cell.row + rowSpan } };
  445. }
  446. Grid::PlacementHelpers::LineArea setCell (Cell start, Cell end)
  447. {
  448. return setCell (start, std::abs (end.column - start.column),
  449. std::abs (end.row - start.row));
  450. }
  451. Cell nextAvailable (Cell referenceCell, int columnSpan, int rowSpan)
  452. {
  453. while (isOccupied (referenceCell, columnSpan, rowSpan) || isOutOfBounds (referenceCell, columnSpan, rowSpan))
  454. referenceCell = advance (referenceCell);
  455. return referenceCell;
  456. }
  457. Cell nextAvailableOnRow (Cell referenceCell, int columnSpan, int rowSpan, int rowNumber)
  458. {
  459. if (columnFirst && (rowNumber + rowSpan) > highestCrossDimension)
  460. highestCrossDimension = rowNumber + rowSpan;
  461. while (isOccupied (referenceCell, columnSpan, rowSpan)
  462. || (referenceCell.row != rowNumber))
  463. referenceCell = advance (referenceCell);
  464. return referenceCell;
  465. }
  466. Cell nextAvailableOnColumn (Cell referenceCell, int columnSpan, int rowSpan, int columnNumber)
  467. {
  468. if (! columnFirst && (columnNumber + columnSpan) > highestCrossDimension)
  469. highestCrossDimension = columnNumber + columnSpan;
  470. while (isOccupied (referenceCell, columnSpan, rowSpan)
  471. || (referenceCell.column != columnNumber))
  472. referenceCell = advance (referenceCell);
  473. return referenceCell;
  474. }
  475. private:
  476. struct SortableCell
  477. {
  478. int column, row;
  479. bool columnFirst;
  480. bool operator< (const SortableCell& other) const
  481. {
  482. if (columnFirst)
  483. {
  484. if (row == other.row)
  485. return column < other.column;
  486. return row < other.row;
  487. }
  488. if (row == other.row)
  489. return column < other.column;
  490. return row < other.row;
  491. }
  492. };
  493. void setCell (int column, int row)
  494. {
  495. occupiedCells.insert ({ column, row, columnFirst });
  496. }
  497. bool isOccupied (Cell cell) const
  498. {
  499. return occupiedCells.count ({ cell.column, cell.row, columnFirst }) > 0;
  500. }
  501. bool isOccupied (Cell cell, int columnSpan, int rowSpan) const
  502. {
  503. for (int i = 0; i < columnSpan; i++)
  504. for (int j = 0; j < rowSpan; j++)
  505. if (isOccupied ({ cell.column + i, cell.row + j }))
  506. return true;
  507. return false;
  508. }
  509. bool isOutOfBounds (Cell cell, int columnSpan, int rowSpan) const
  510. {
  511. const auto crossSpan = columnFirst ? rowSpan : columnSpan;
  512. return (getCrossDimension (cell) + crossSpan) > getHighestCrossDimension();
  513. }
  514. int getHighestCrossDimension() const
  515. {
  516. Cell cell { 1, 1 };
  517. if (occupiedCells.size() > 0)
  518. cell = { occupiedCells.crbegin()->column, occupiedCells.crbegin()->row };
  519. return std::max (getCrossDimension (cell), highestCrossDimension);
  520. }
  521. Cell advance (Cell cell) const
  522. {
  523. if ((getCrossDimension (cell) + 1) >= getHighestCrossDimension())
  524. return fromDimensions (getMainDimension (cell) + 1, 1);
  525. return fromDimensions (getMainDimension (cell), getCrossDimension (cell) + 1);
  526. }
  527. int getMainDimension (Cell cell) const { return columnFirst ? cell.column : cell.row; }
  528. int getCrossDimension (Cell cell) const { return columnFirst ? cell.row : cell.column; }
  529. Cell fromDimensions (int mainDimension, int crossDimension) const
  530. {
  531. if (columnFirst)
  532. return { mainDimension, crossDimension };
  533. return { crossDimension, mainDimension };
  534. }
  535. int highestCrossDimension;
  536. bool columnFirst;
  537. std::set<SortableCell> occupiedCells;
  538. };
  539. //==============================================================================
  540. static bool isFixed (GridItem::StartAndEndProperty prop)
  541. {
  542. return prop.start.hasName() || prop.start.hasAbsolute() || prop.end.hasName() || prop.end.hasAbsolute();
  543. }
  544. static bool hasFullyFixedPlacement (const GridItem& item)
  545. {
  546. if (item.area.isNotEmpty())
  547. return true;
  548. if (isFixed (item.column) && isFixed (item.row))
  549. return true;
  550. return false;
  551. }
  552. static bool hasPartialFixedPlacement (const GridItem& item)
  553. {
  554. if (item.area.isNotEmpty())
  555. return false;
  556. if (isFixed (item.column) ^ isFixed (item.row))
  557. return true;
  558. return false;
  559. }
  560. static bool hasAutoPlacement (const GridItem& item)
  561. {
  562. return ! hasFullyFixedPlacement (item) && ! hasPartialFixedPlacement (item);
  563. }
  564. //==============================================================================
  565. static bool hasDenseAutoFlow (Grid::AutoFlow autoFlow)
  566. {
  567. return autoFlow == Grid::AutoFlow::columnDense
  568. || autoFlow == Grid::AutoFlow::rowDense;
  569. }
  570. static bool isColumnAutoFlow (Grid::AutoFlow autoFlow)
  571. {
  572. return autoFlow == Grid::AutoFlow::column
  573. || autoFlow == Grid::AutoFlow::columnDense;
  574. }
  575. //==============================================================================
  576. static int getSpanFromAuto (GridItem::StartAndEndProperty prop)
  577. {
  578. if (prop.end.hasSpan())
  579. return prop.end.number;
  580. if (prop.start.hasSpan())
  581. return prop.start.number;
  582. return 1;
  583. }
  584. //==============================================================================
  585. ItemPlacementArray deduceAllItems (Grid& grid) const
  586. {
  587. const auto namedAreas = Grid::PlacementHelpers::deduceNamedAreas (grid.templateAreas);
  588. OccupancyPlane plane (juce::jmax (grid.templateColumns.size() + 1, 2),
  589. juce::jmax (grid.templateRows.size() + 1, 2),
  590. isColumnAutoFlow (grid.autoFlow));
  591. ItemPlacementArray itemPlacementArray;
  592. juce::Array<GridItem*> sortedItems;
  593. for (auto& item : grid.items)
  594. sortedItems.add (&item);
  595. std::stable_sort (sortedItems.begin(), sortedItems.end(),
  596. [] (const GridItem* i1, const GridItem* i2) { return i1->order < i2->order; });
  597. // place fixed items first
  598. for (auto* item : sortedItems)
  599. {
  600. if (hasFullyFixedPlacement (*item))
  601. {
  602. const auto a = Grid::PlacementHelpers::deduceLineArea (*item, grid, namedAreas);
  603. plane.setCell ({ a.column.start, a.row.start }, { a.column.end, a.row.end });
  604. itemPlacementArray.add ({ item, a });
  605. }
  606. }
  607. OccupancyPlane::Cell lastInsertionCell = { 1, 1 };
  608. for (auto* item : sortedItems)
  609. {
  610. if (hasPartialFixedPlacement (*item))
  611. {
  612. if (isFixed (item->column))
  613. {
  614. const auto p = Grid::PlacementHelpers::deduceLineRange (item->column, grid.templateColumns);
  615. const auto columnSpan = std::abs (p.start - p.end);
  616. const auto rowSpan = getSpanFromAuto (item->row);
  617. const auto insertionCell = hasDenseAutoFlow (grid.autoFlow) ? OccupancyPlane::Cell { p.start, 1 }
  618. : lastInsertionCell;
  619. const auto nextAvailableCell = plane.nextAvailableOnColumn (insertionCell, columnSpan, rowSpan, p.start);
  620. const auto lineArea = plane.setCell (nextAvailableCell, columnSpan, rowSpan);
  621. lastInsertionCell = nextAvailableCell;
  622. itemPlacementArray.add ({ item, lineArea });
  623. }
  624. else if (isFixed (item->row))
  625. {
  626. const auto p = Grid::PlacementHelpers::deduceLineRange (item->row, grid.templateRows);
  627. const auto columnSpan = getSpanFromAuto (item->column);
  628. const auto rowSpan = std::abs (p.start - p.end);
  629. const auto insertionCell = hasDenseAutoFlow (grid.autoFlow) ? OccupancyPlane::Cell { 1, p.start }
  630. : lastInsertionCell;
  631. const auto nextAvailableCell = plane.nextAvailableOnRow (insertionCell, columnSpan, rowSpan, p.start);
  632. const auto lineArea = plane.setCell (nextAvailableCell, columnSpan, rowSpan);
  633. lastInsertionCell = nextAvailableCell;
  634. itemPlacementArray.add ({ item, lineArea });
  635. }
  636. }
  637. }
  638. lastInsertionCell = { 1, 1 };
  639. for (auto* item : sortedItems)
  640. {
  641. if (hasAutoPlacement (*item))
  642. {
  643. const auto columnSpan = getSpanFromAuto (item->column);
  644. const auto rowSpan = getSpanFromAuto (item->row);
  645. const auto nextAvailableCell = plane.nextAvailable (lastInsertionCell, columnSpan, rowSpan);
  646. const auto lineArea = plane.setCell (nextAvailableCell, columnSpan, rowSpan);
  647. if (! hasDenseAutoFlow (grid.autoFlow))
  648. lastInsertionCell = nextAvailableCell;
  649. itemPlacementArray.add ({ item, lineArea });
  650. }
  651. }
  652. return itemPlacementArray;
  653. }
  654. //==============================================================================
  655. static std::pair<int, int> getHighestEndLinesNumbers (const ItemPlacementArray& items)
  656. {
  657. int columnEndLine = 1;
  658. int rowEndLine = 1;
  659. for (auto& item : items)
  660. {
  661. const auto p = item.second;
  662. columnEndLine = std::max (p.column.end, columnEndLine);
  663. rowEndLine = std::max (p.row.end, rowEndLine);
  664. }
  665. return { columnEndLine, rowEndLine };
  666. }
  667. static std::pair<juce::Array<TrackInfo>, juce::Array<TrackInfo>> createImplicitTracks (const Grid& grid,
  668. const ItemPlacementArray& items)
  669. {
  670. const auto columnAndRowLineEnds = getHighestEndLinesNumbers (items);
  671. juce::Array<TrackInfo> implicitColumnTracks, implicitRowTracks;
  672. for (int i = grid.templateColumns.size() + 1; i < columnAndRowLineEnds.first; i++)
  673. implicitColumnTracks.add (grid.autoColumns);
  674. for (int i = grid.templateRows.size() + 1; i < columnAndRowLineEnds.second; i++)
  675. implicitRowTracks.add (grid.autoRows);
  676. return { implicitColumnTracks, implicitRowTracks };
  677. }
  678. //==============================================================================
  679. static void applySizeForAutoTracks (juce::Array<Grid::TrackInfo>& columns,
  680. juce::Array<Grid::TrackInfo>& rows,
  681. const ItemPlacementArray& itemPlacementArray)
  682. {
  683. auto isSpan = [](Grid::PlacementHelpers::LineRange r) -> bool { return std::abs (r.end - r.start) > 1; };
  684. auto getHighestItemOnRow = [isSpan](int rowNumber, const ItemPlacementArray& itemPlacementArrayToUse) -> float
  685. {
  686. float highestRowSize = 0.0f;
  687. for (const auto& i : itemPlacementArrayToUse)
  688. if (! isSpan (i.second.row) && i.second.row.start == rowNumber)
  689. highestRowSize = std::max (highestRowSize, i.first->height + i.first->margin.top + i.first->margin.bottom);
  690. return highestRowSize;
  691. };
  692. auto getHighestItemOnColumn = [isSpan](int rowNumber, const ItemPlacementArray& itemPlacementArrayToUse) -> float
  693. {
  694. float highestColumnSize = 0.0f;
  695. for (const auto& i : itemPlacementArrayToUse)
  696. if (! isSpan (i.second.column) && i.second.column.start == rowNumber)
  697. highestColumnSize = std::max (highestColumnSize, i.first->width + i.first->margin.left + i.first->margin.right);
  698. return highestColumnSize;
  699. };
  700. for (int i = 0; i < rows.size(); i++)
  701. if (rows.getReference (i).hasKeyword)
  702. rows.getReference (i).size = getHighestItemOnRow (i + 1, itemPlacementArray);
  703. for (int i = 0; i < columns.size(); i++)
  704. if (columns.getReference (i).hasKeyword)
  705. columns.getReference (i).size = getHighestItemOnColumn (i + 1, itemPlacementArray);
  706. }
  707. };
  708. //==============================================================================
  709. struct Grid::BoxAlignment
  710. {
  711. static juce::Rectangle<float> alignItem (const GridItem& item,
  712. const Grid& grid,
  713. juce::Rectangle<float> area)
  714. {
  715. // if item align is auto, inherit value from grid
  716. Grid::AlignItems alignType = Grid::AlignItems::start;
  717. Grid::JustifyItems justifyType = Grid::JustifyItems::start;
  718. if (item.alignSelf == GridItem::AlignSelf::autoValue)
  719. alignType = grid.alignItems;
  720. else
  721. alignType = static_cast<Grid::AlignItems> (item.alignSelf);
  722. if (item.justifySelf == GridItem::JustifySelf::autoValue)
  723. justifyType = grid.justifyItems;
  724. else
  725. justifyType = static_cast<Grid::JustifyItems> (item.justifySelf);
  726. // subtract margin from area
  727. area = juce::BorderSize<float> (item.margin.top, item.margin.left, item.margin.bottom, item.margin.right)
  728. .subtractedFrom (area);
  729. // align and justify
  730. auto r = area;
  731. if (item.width != (float) GridItem::notAssigned) r.setWidth (item.width);
  732. if (item.height != (float) GridItem::notAssigned) r.setHeight (item.height);
  733. if (item.maxWidth != (float) GridItem::notAssigned) r.setWidth (jmin (item.maxWidth, r.getWidth()));
  734. if (item.minWidth > 0.0f) r.setWidth (jmax (item.minWidth, r.getWidth()));
  735. if (item.maxHeight != (float) GridItem::notAssigned) r.setHeight (jmin (item.maxHeight, r.getHeight()));
  736. if (item.minHeight > 0.0f) r.setHeight (jmax (item.minHeight, r.getHeight()));
  737. if (alignType == Grid::AlignItems::start && justifyType == Grid::JustifyItems::start)
  738. return r;
  739. if (alignType == Grid::AlignItems::end) r.setY (r.getY() + (area.getHeight() - r.getHeight()));
  740. if (justifyType == Grid::JustifyItems::end) r.setX (r.getX() + (area.getWidth() - r.getWidth()));
  741. if (alignType == Grid::AlignItems::center) r.setCentre (r.getCentreX(), area.getCentreY());
  742. if (justifyType == Grid::JustifyItems::center) r.setCentre (area.getCentreX(), r.getCentreY());
  743. return r;
  744. }
  745. };
  746. //==============================================================================
  747. Grid::TrackInfo::TrackInfo() noexcept : hasKeyword (true) {}
  748. Grid::TrackInfo::TrackInfo (Px sizeInPixels) noexcept : size (static_cast<float> (sizeInPixels.pixels)), isFraction (false) {}
  749. Grid::TrackInfo::TrackInfo (Fr fractionOfFreeSpace) noexcept : size ((float)fractionOfFreeSpace.fraction), isFraction (true) {}
  750. Grid::TrackInfo::TrackInfo (Px sizeInPixels, const juce::String& endLineNameToUse) noexcept : Grid::TrackInfo (sizeInPixels)
  751. {
  752. endLineName = endLineNameToUse;
  753. }
  754. Grid::TrackInfo::TrackInfo (Fr fractionOfFreeSpace, const juce::String& endLineNameToUse) noexcept : Grid::TrackInfo (fractionOfFreeSpace)
  755. {
  756. endLineName = endLineNameToUse;
  757. }
  758. Grid::TrackInfo::TrackInfo (const juce::String& startLineNameToUse, Px sizeInPixels) noexcept : Grid::TrackInfo (sizeInPixels)
  759. {
  760. startLineName = startLineNameToUse;
  761. }
  762. Grid::TrackInfo::TrackInfo (const juce::String& startLineNameToUse, Fr fractionOfFreeSpace) noexcept : Grid::TrackInfo (fractionOfFreeSpace)
  763. {
  764. startLineName = startLineNameToUse;
  765. }
  766. Grid::TrackInfo::TrackInfo (const juce::String& startLineNameToUse, Px sizeInPixels, const juce::String& endLineNameToUse) noexcept
  767. : Grid::TrackInfo (startLineNameToUse, sizeInPixels)
  768. {
  769. endLineName = endLineNameToUse;
  770. }
  771. Grid::TrackInfo::TrackInfo (const juce::String& startLineNameToUse, Fr fractionOfFreeSpace, const juce::String& endLineNameToUse) noexcept
  772. : Grid::TrackInfo (startLineNameToUse, fractionOfFreeSpace)
  773. {
  774. endLineName = endLineNameToUse;
  775. }
  776. //==============================================================================
  777. Grid::Grid() noexcept {}
  778. Grid::~Grid() noexcept {}
  779. //==============================================================================
  780. void Grid::performLayout (juce::Rectangle<int> targetArea)
  781. {
  782. const auto itemsAndAreas = Grid::AutoPlacement().deduceAllItems (*this);
  783. const auto implicitTracks = Grid::AutoPlacement::createImplicitTracks (*this, itemsAndAreas);
  784. auto columnTracks = templateColumns;
  785. auto rowTracks = templateRows;
  786. columnTracks.addArray (implicitTracks.first);
  787. rowTracks.addArray (implicitTracks.second);
  788. Grid::AutoPlacement::applySizeForAutoTracks (columnTracks, rowTracks, itemsAndAreas);
  789. Grid::SizeCalculation calculation;
  790. calculation.computeSizes (targetArea.toFloat().getWidth(),
  791. targetArea.toFloat().getHeight(),
  792. columnGap,
  793. rowGap,
  794. columnTracks,
  795. rowTracks);
  796. for (auto& itemAndArea : itemsAndAreas)
  797. {
  798. const auto a = itemAndArea.second;
  799. const auto areaBounds = Grid::PlacementHelpers::getAreaBounds (a.column.start, a.column.end,
  800. a.row.start, a.row.end,
  801. columnTracks,
  802. rowTracks,
  803. calculation,
  804. alignContent,
  805. justifyContent,
  806. columnGap,
  807. rowGap);
  808. auto* item = itemAndArea.first;
  809. item->currentBounds = Grid::BoxAlignment::alignItem (*item, *this, areaBounds)
  810. + targetArea.toFloat().getPosition();
  811. if (auto* c = item->associatedComponent)
  812. c->setBounds (item->currentBounds.toNearestIntEdges());
  813. }
  814. }
  815. //==============================================================================
  816. #if JUCE_UNIT_TESTS
  817. struct GridTests : public UnitTest
  818. {
  819. GridTests()
  820. : UnitTest ("Grid", UnitTestCategories::gui)
  821. {}
  822. void runTest() override
  823. {
  824. using Fr = Grid::Fr;
  825. using Tr = Grid::TrackInfo;
  826. using Rect = Rectangle<float>;
  827. {
  828. Grid grid;
  829. grid.templateColumns.add (Tr (1_fr));
  830. grid.templateRows.addArray ({ Tr (20_px), Tr (1_fr) });
  831. grid.items.addArray ({ GridItem().withArea (1, 1),
  832. GridItem().withArea (2, 1) });
  833. grid.performLayout (Rectangle<int> (200, 400));
  834. beginTest ("Layout calculation test: 1 column x 2 rows: no gap");
  835. expect (grid.items[0].currentBounds == Rect (0.0f, 0.0f, 200.f, 20.0f));
  836. expect (grid.items[1].currentBounds == Rect (0.0f, 20.0f, 200.f, 380.0f));
  837. grid.templateColumns.add (Tr (50_px));
  838. grid.templateRows.add (Tr (2_fr));
  839. grid.items.addArray ( { GridItem().withArea (1, 2),
  840. GridItem().withArea (2, 2),
  841. GridItem().withArea (3, 1),
  842. GridItem().withArea (3, 2) });
  843. grid.performLayout (Rectangle<int> (150, 170));
  844. beginTest ("Layout calculation test: 2 columns x 3 rows: no gap");
  845. expect (grid.items[0].currentBounds == Rect (0.0f, 0.0f, 100.0f, 20.0f));
  846. expect (grid.items[1].currentBounds == Rect (0.0f, 20.0f, 100.0f, 50.0f));
  847. expect (grid.items[2].currentBounds == Rect (100.0f, 0.0f, 50.0f, 20.0f));
  848. expect (grid.items[3].currentBounds == Rect (100.0f, 20.0f, 50.0f, 50.0f));
  849. expect (grid.items[4].currentBounds == Rect (0.0f, 70.0f, 100.0f, 100.0f));
  850. expect (grid.items[5].currentBounds == Rect (100.0f, 70.0f, 50.0f, 100.0f));
  851. grid.columnGap = 20_px;
  852. grid.rowGap = 10_px;
  853. grid.performLayout (Rectangle<int> (200, 310));
  854. beginTest ("Layout calculation test: 2 columns x 3 rows: rowGap of 10 and columnGap of 20");
  855. expect (grid.items[0].currentBounds == Rect (0.0f, 0.0f, 130.0f, 20.0f));
  856. expect (grid.items[1].currentBounds == Rect (0.0f, 30.0f, 130.0f, 90.0f));
  857. expect (grid.items[2].currentBounds == Rect (150.0f, 0.0f, 50.0f, 20.0f));
  858. expect (grid.items[3].currentBounds == Rect (150.0f, 30.0f, 50.0f, 90.0f));
  859. expect (grid.items[4].currentBounds == Rect (0.0f, 130.0f, 130.0f, 180.0f));
  860. expect (grid.items[5].currentBounds == Rect (150.0f, 130.0f, 50.0f, 180.0f));
  861. }
  862. {
  863. Grid grid;
  864. grid.templateColumns.addArray ({ Tr ("first", 20_px, "in"), Tr ("in", 1_fr, "in"), Tr (20_px, "last") });
  865. grid.templateRows.addArray ({ Tr (1_fr),
  866. Tr (20_px)});
  867. {
  868. beginTest ("Grid items placement tests: integer and custom ident, counting forward");
  869. GridItem i1, i2, i3, i4, i5;
  870. i1.column = { 1, 4 };
  871. i1.row = { 1, 2 };
  872. i2.column = { 1, 3 };
  873. i2.row = { 1, 3 };
  874. i3.column = { "first", "in" };
  875. i3.row = { 2, 3 };
  876. i4.column = { "first", { 2, "in" } };
  877. i4.row = { 1, 2 };
  878. i5.column = { "first", "last" };
  879. i5.row = { 1, 2 };
  880. grid.items.addArray ({ i1, i2, i3, i4, i5 });
  881. grid.performLayout ({ 140, 100 });
  882. expect (grid.items[0].currentBounds == Rect (0.0f, 0.0f, 140.0f, 80.0f));
  883. expect (grid.items[1].currentBounds == Rect (0.0f, 0.0f, 120.0f, 100.0f));
  884. expect (grid.items[2].currentBounds == Rect (0.0f, 80.0f, 20.0f, 20.0f));
  885. expect (grid.items[3].currentBounds == Rect (0.0f, 0.0f, 120.0f, 80.0f));
  886. expect (grid.items[4].currentBounds == Rect (0.0f, 0.0f, 140.0f, 80.0f));
  887. }
  888. }
  889. {
  890. Grid grid;
  891. grid.templateColumns.addArray ({ Tr ("first", 20_px, "in"), Tr ("in", 1_fr, "in"), Tr (20_px, "last") });
  892. grid.templateRows.addArray ({ Tr (1_fr),
  893. Tr (20_px)});
  894. beginTest ("Grid items placement tests: integer and custom ident, counting forward, reversed end and start");
  895. GridItem i1, i2, i3, i4, i5;
  896. i1.column = { 4, 1 };
  897. i1.row = { 2, 1 };
  898. i2.column = { 3, 1 };
  899. i2.row = { 3, 1 };
  900. i3.column = { "in", "first" };
  901. i3.row = { 3, 2 };
  902. i4.column = { "first", { 2, "in" } };
  903. i4.row = { 1, 2 };
  904. i5.column = { "last", "first" };
  905. i5.row = { 1, 2 };
  906. grid.items.addArray ({ i1, i2, i3, i4, i5 });
  907. grid.performLayout ({ 140, 100 });
  908. expect (grid.items[0].currentBounds == Rect (0.0f, 0.0f, 140.0f, 80.0f));
  909. expect (grid.items[1].currentBounds == Rect (0.0f, 0.0f, 120.0f, 100.0f));
  910. expect (grid.items[2].currentBounds == Rect (0.0f, 80.0f, 20.0f, 20.0f));
  911. expect (grid.items[3].currentBounds == Rect (0.0f, 0.0f, 120.0f, 80.0f));
  912. expect (grid.items[4].currentBounds == Rect (0.0f, 0.0f, 140.0f, 80.0f));
  913. }
  914. {
  915. beginTest ("Grid items placement tests: areas");
  916. Grid grid;
  917. grid.templateColumns = { Tr (50_px), Tr (100_px), Tr (Fr (1_fr)), Tr (50_px) };
  918. grid.templateRows = { Tr (50_px),
  919. Tr (1_fr),
  920. Tr (50_px) };
  921. grid.templateAreas = { "header header header header",
  922. "main main . sidebar",
  923. "footer footer footer footer" };
  924. grid.items.addArray ({ GridItem().withArea ("header"),
  925. GridItem().withArea ("main"),
  926. GridItem().withArea ("sidebar"),
  927. GridItem().withArea ("footer"),
  928. });
  929. grid.performLayout ({ 300, 150 });
  930. expect (grid.items[0].currentBounds == Rect (0.f, 0.f, 300.f, 50.f));
  931. expect (grid.items[1].currentBounds == Rect (0.f, 50.f, 150.f, 50.f));
  932. expect (grid.items[2].currentBounds == Rect (250.f, 50.f, 50.f, 50.f));
  933. expect (grid.items[3].currentBounds == Rect (0.f, 100.f, 300.f, 50.f));
  934. }
  935. {
  936. beginTest ("Grid implicit rows and columns: triggered by areas");
  937. Grid grid;
  938. grid.templateColumns = { Tr (50_px), Tr (100_px), Tr (1_fr), Tr (50_px) };
  939. grid.templateRows = { Tr (50_px),
  940. Tr (1_fr),
  941. Tr (50_px) };
  942. grid.autoRows = Tr (30_px);
  943. grid.autoColumns = Tr (30_px);
  944. grid.templateAreas = { "header header header header header",
  945. "main main . sidebar sidebar",
  946. "footer footer footer footer footer",
  947. "sub sub sub sub sub"};
  948. grid.items.addArray ({ GridItem().withArea ("header"),
  949. GridItem().withArea ("main"),
  950. GridItem().withArea ("sidebar"),
  951. GridItem().withArea ("footer"),
  952. GridItem().withArea ("sub"),
  953. });
  954. grid.performLayout ({ 330, 180 });
  955. expect (grid.items[0].currentBounds == Rect (0.f, 0.f, 330.f, 50.f));
  956. expect (grid.items[1].currentBounds == Rect (0.f, 50.f, 150.f, 50.f));
  957. expect (grid.items[2].currentBounds == Rect (250.f, 50.f, 80.f, 50.f));
  958. expect (grid.items[3].currentBounds == Rect (0.f, 100.f, 330.f, 50.f));
  959. expect (grid.items[4].currentBounds == Rect (0.f, 150.f, 330.f, 30.f));
  960. }
  961. {
  962. beginTest ("Grid implicit rows and columns: triggered by areas");
  963. Grid grid;
  964. grid.templateColumns = { Tr (50_px), Tr (100_px), Tr (1_fr), Tr (50_px) };
  965. grid.templateRows = { Tr (50_px),
  966. Tr (1_fr),
  967. Tr (50_px) };
  968. grid.autoRows = Tr (1_fr);
  969. grid.autoColumns = Tr (1_fr);
  970. grid.templateAreas = { "header header header header",
  971. "main main . sidebar",
  972. "footer footer footer footer" };
  973. grid.items.addArray ({ GridItem().withArea ("header"),
  974. GridItem().withArea ("main"),
  975. GridItem().withArea ("sidebar"),
  976. GridItem().withArea ("footer"),
  977. GridItem().withArea (4, 5, 6, 7)
  978. });
  979. grid.performLayout ({ 350, 250 });
  980. expect (grid.items[0].currentBounds == Rect (0.f, 0.f, 250.f, 50.f));
  981. expect (grid.items[1].currentBounds == Rect (0.f, 50.f, 150.f, 50.f));
  982. expect (grid.items[2].currentBounds == Rect (200.f, 50.f, 50.f, 50.f));
  983. expect (grid.items[3].currentBounds == Rect (0.f, 100.f, 250.f, 50.f));
  984. expect (grid.items[4].currentBounds == Rect (250.f, 150.f, 100.f, 100.f));
  985. }
  986. }
  987. };
  988. static GridTests gridUnitTests;
  989. #endif
  990. } // namespace juce