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.

1030 lines
39KB

  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. return startCell.getUnion (endCell);
  422. }
  423. };
  424. //==============================================================================
  425. struct Grid::AutoPlacement
  426. {
  427. using ItemPlacementArray = juce::Array<std::pair<GridItem*, Grid::PlacementHelpers::LineArea>>;
  428. //==============================================================================
  429. struct OccupancyPlane
  430. {
  431. struct Cell { int column, row; };
  432. OccupancyPlane (int highestColumnToUse, int highestRowToUse, bool isColumnFirst)
  433. : highestCrossDimension (isColumnFirst ? highestRowToUse : highestColumnToUse),
  434. columnFirst (isColumnFirst)
  435. {}
  436. Grid::PlacementHelpers::LineArea setCell (Cell cell, int columnSpan, int rowSpan)
  437. {
  438. for (int i = 0; i < columnSpan; i++)
  439. for (int j = 0; j < rowSpan; j++)
  440. setCell (cell.column + i, cell.row + j);
  441. return { { cell.column, cell.column + columnSpan }, { cell.row, cell.row + rowSpan } };
  442. }
  443. Grid::PlacementHelpers::LineArea setCell (Cell start, Cell end)
  444. {
  445. return setCell (start, std::abs (end.column - start.column),
  446. std::abs (end.row - start.row));
  447. }
  448. Cell nextAvailable (Cell referenceCell, int columnSpan, int rowSpan)
  449. {
  450. while (isOccupied (referenceCell, columnSpan, rowSpan) || isOutOfBounds (referenceCell, columnSpan, rowSpan))
  451. referenceCell = advance (referenceCell);
  452. return referenceCell;
  453. }
  454. Cell nextAvailableOnRow (Cell referenceCell, int columnSpan, int rowSpan, int rowNumber)
  455. {
  456. if (columnFirst && (rowNumber + rowSpan) > highestCrossDimension)
  457. highestCrossDimension = rowNumber + rowSpan;
  458. while (isOccupied (referenceCell, columnSpan, rowSpan)
  459. || (referenceCell.row != rowNumber))
  460. referenceCell = advance (referenceCell);
  461. return referenceCell;
  462. }
  463. Cell nextAvailableOnColumn (Cell referenceCell, int columnSpan, int rowSpan, int columnNumber)
  464. {
  465. if (! columnFirst && (columnNumber + columnSpan) > highestCrossDimension)
  466. highestCrossDimension = columnNumber + columnSpan;
  467. while (isOccupied (referenceCell, columnSpan, rowSpan)
  468. || (referenceCell.column != columnNumber))
  469. referenceCell = advance (referenceCell);
  470. return referenceCell;
  471. }
  472. private:
  473. struct SortableCell
  474. {
  475. int column, row;
  476. bool columnFirst;
  477. bool operator< (const SortableCell& other) const
  478. {
  479. if (columnFirst)
  480. {
  481. if (row == other.row)
  482. return column < other.column;
  483. return row < other.row;
  484. }
  485. if (row == other.row)
  486. return column < other.column;
  487. return row < other.row;
  488. }
  489. };
  490. void setCell (int column, int row)
  491. {
  492. occupiedCells.insert ({ column, row, columnFirst });
  493. }
  494. bool isOccupied (Cell cell) const
  495. {
  496. return occupiedCells.count ({ cell.column, cell.row, columnFirst }) > 0;
  497. }
  498. bool isOccupied (Cell cell, int columnSpan, int rowSpan) const
  499. {
  500. for (int i = 0; i < columnSpan; i++)
  501. for (int j = 0; j < rowSpan; j++)
  502. if (isOccupied ({ cell.column + i, cell.row + j }))
  503. return true;
  504. return false;
  505. }
  506. bool isOutOfBounds (Cell cell, int columnSpan, int rowSpan) const
  507. {
  508. const auto crossSpan = columnFirst ? rowSpan : columnSpan;
  509. return (getCrossDimension (cell) + crossSpan) > getHighestCrossDimension();
  510. }
  511. int getHighestCrossDimension() const
  512. {
  513. Cell cell { 1, 1 };
  514. if (occupiedCells.size() > 0)
  515. cell = { occupiedCells.crbegin()->column, occupiedCells.crbegin()->row };
  516. return std::max (getCrossDimension (cell), highestCrossDimension);
  517. }
  518. Cell advance (Cell cell) const
  519. {
  520. if ((getCrossDimension (cell) + 1) >= getHighestCrossDimension())
  521. return fromDimensions (getMainDimension (cell) + 1, 1);
  522. return fromDimensions (getMainDimension (cell), getCrossDimension (cell) + 1);
  523. }
  524. int getMainDimension (Cell cell) const { return columnFirst ? cell.column : cell.row; }
  525. int getCrossDimension (Cell cell) const { return columnFirst ? cell.row : cell.column; }
  526. Cell fromDimensions (int mainDimension, int crossDimension) const
  527. {
  528. if (columnFirst)
  529. return { mainDimension, crossDimension };
  530. return { crossDimension, mainDimension };
  531. }
  532. int highestCrossDimension;
  533. bool columnFirst;
  534. std::set<SortableCell> occupiedCells;
  535. };
  536. //==============================================================================
  537. static bool isFixed (GridItem::StartAndEndProperty prop)
  538. {
  539. return prop.start.hasName() || prop.start.hasAbsolute() || prop.end.hasName() || prop.end.hasAbsolute();
  540. }
  541. static bool hasFullyFixedPlacement (const GridItem& item)
  542. {
  543. if (item.area.isNotEmpty())
  544. return true;
  545. if (isFixed (item.column) && isFixed (item.row))
  546. return true;
  547. return false;
  548. }
  549. static bool hasPartialFixedPlacement (const GridItem& item)
  550. {
  551. if (item.area.isNotEmpty())
  552. return false;
  553. if (isFixed (item.column) ^ isFixed (item.row))
  554. return true;
  555. return false;
  556. }
  557. static bool hasAutoPlacement (const GridItem& item)
  558. {
  559. return ! hasFullyFixedPlacement (item) && ! hasPartialFixedPlacement (item);
  560. }
  561. //==============================================================================
  562. static bool hasDenseAutoFlow (Grid::AutoFlow autoFlow)
  563. {
  564. return autoFlow == Grid::AutoFlow::columnDense
  565. || autoFlow == Grid::AutoFlow::rowDense;
  566. }
  567. static bool isColumnAutoFlow (Grid::AutoFlow autoFlow)
  568. {
  569. return autoFlow == Grid::AutoFlow::column
  570. || autoFlow == Grid::AutoFlow::columnDense;
  571. }
  572. //==============================================================================
  573. static int getSpanFromAuto (GridItem::StartAndEndProperty prop)
  574. {
  575. if (prop.end.hasSpan())
  576. return prop.end.number;
  577. if (prop.start.hasSpan())
  578. return prop.start.number;
  579. return 1;
  580. }
  581. //==============================================================================
  582. ItemPlacementArray deduceAllItems (Grid& grid) const
  583. {
  584. const auto namedAreas = Grid::PlacementHelpers::deduceNamedAreas (grid.templateAreas);
  585. OccupancyPlane plane (juce::jmax (grid.templateColumns.size() + 1, 2),
  586. juce::jmax (grid.templateRows.size() + 1, 2),
  587. isColumnAutoFlow (grid.autoFlow));
  588. ItemPlacementArray itemPlacementArray;
  589. juce::Array<GridItem*> sortedItems;
  590. for (auto& item : grid.items)
  591. sortedItems.add (&item);
  592. std::stable_sort (sortedItems.begin(), sortedItems.end(),
  593. [] (const GridItem* i1, const GridItem* i2) { return i1->order < i2->order; });
  594. // place fixed items first
  595. for (auto* item : sortedItems)
  596. {
  597. if (hasFullyFixedPlacement (*item))
  598. {
  599. const auto a = Grid::PlacementHelpers::deduceLineArea (*item, grid, namedAreas);
  600. plane.setCell ({ a.column.start, a.row.start }, { a.column.end, a.row.end });
  601. itemPlacementArray.add ({ item, a });
  602. }
  603. }
  604. OccupancyPlane::Cell lastInsertionCell = { 1, 1 };
  605. for (auto* item : sortedItems)
  606. {
  607. if (hasPartialFixedPlacement (*item))
  608. {
  609. if (isFixed (item->column))
  610. {
  611. const auto p = Grid::PlacementHelpers::deduceLineRange (item->column, grid.templateColumns);
  612. const auto columnSpan = std::abs (p.start - p.end);
  613. const auto rowSpan = getSpanFromAuto (item->row);
  614. const auto insertionCell = hasDenseAutoFlow (grid.autoFlow) ? OccupancyPlane::Cell { p.start, 1 }
  615. : lastInsertionCell;
  616. const auto nextAvailableCell = plane.nextAvailableOnColumn (insertionCell, columnSpan, rowSpan, p.start);
  617. const auto lineArea = plane.setCell (nextAvailableCell, columnSpan, rowSpan);
  618. lastInsertionCell = nextAvailableCell;
  619. itemPlacementArray.add ({ item, lineArea });
  620. }
  621. else if (isFixed (item->row))
  622. {
  623. const auto p = Grid::PlacementHelpers::deduceLineRange (item->row, grid.templateRows);
  624. const auto columnSpan = getSpanFromAuto (item->column);
  625. const auto rowSpan = std::abs (p.start - p.end);
  626. const auto insertionCell = hasDenseAutoFlow (grid.autoFlow) ? OccupancyPlane::Cell { 1, p.start }
  627. : lastInsertionCell;
  628. const auto nextAvailableCell = plane.nextAvailableOnRow (insertionCell, columnSpan, rowSpan, p.start);
  629. const auto lineArea = plane.setCell (nextAvailableCell, columnSpan, rowSpan);
  630. lastInsertionCell = nextAvailableCell;
  631. itemPlacementArray.add ({ item, lineArea });
  632. }
  633. }
  634. }
  635. lastInsertionCell = { 1, 1 };
  636. for (auto* item : sortedItems)
  637. {
  638. if (hasAutoPlacement (*item))
  639. {
  640. const auto columnSpan = getSpanFromAuto (item->column);
  641. const auto rowSpan = getSpanFromAuto (item->row);
  642. const auto nextAvailableCell = plane.nextAvailable (lastInsertionCell, columnSpan, rowSpan);
  643. const auto lineArea = plane.setCell (nextAvailableCell, columnSpan, rowSpan);
  644. if (! hasDenseAutoFlow (grid.autoFlow))
  645. lastInsertionCell = nextAvailableCell;
  646. itemPlacementArray.add ({ item, lineArea });
  647. }
  648. }
  649. return itemPlacementArray;
  650. }
  651. //==============================================================================
  652. static std::pair<int, int> getHighestEndLinesNumbers (const ItemPlacementArray& items)
  653. {
  654. int columnEndLine = 1;
  655. int rowEndLine = 1;
  656. for (auto& item : items)
  657. {
  658. const auto p = item.second;
  659. columnEndLine = std::max (p.column.end, columnEndLine);
  660. rowEndLine = std::max (p.row.end, rowEndLine);
  661. }
  662. return { columnEndLine, rowEndLine };
  663. }
  664. static std::pair<juce::Array<TrackInfo>, juce::Array<TrackInfo>> createImplicitTracks (const Grid& grid,
  665. const ItemPlacementArray& items)
  666. {
  667. const auto columnAndRowLineEnds = getHighestEndLinesNumbers (items);
  668. juce::Array<TrackInfo> implicitColumnTracks, implicitRowTracks;
  669. for (int i = grid.templateColumns.size() + 1; i < columnAndRowLineEnds.first; i++)
  670. implicitColumnTracks.add (grid.autoColumns);
  671. for (int i = grid.templateRows.size() + 1; i < columnAndRowLineEnds.second; i++)
  672. implicitRowTracks.add (grid.autoRows);
  673. return { implicitColumnTracks, implicitRowTracks };
  674. }
  675. //==============================================================================
  676. static void applySizeForAutoTracks (juce::Array<Grid::TrackInfo>& columns,
  677. juce::Array<Grid::TrackInfo>& rows,
  678. const ItemPlacementArray& itemPlacementArray)
  679. {
  680. auto isSpan = [](Grid::PlacementHelpers::LineRange r) -> bool { return std::abs (r.end - r.start) > 1; };
  681. auto getHighestItemOnRow = [isSpan](int rowNumber, const ItemPlacementArray& itemPlacementArrayToUse) -> float
  682. {
  683. float highestRowSize = 0.0f;
  684. for (const auto& i : itemPlacementArrayToUse)
  685. if (! isSpan (i.second.row) && i.second.row.start == rowNumber)
  686. highestRowSize = std::max (highestRowSize, i.first->height + i.first->margin.top + i.first->margin.bottom);
  687. return highestRowSize;
  688. };
  689. auto getHighestItemOnColumn = [isSpan](int rowNumber, const ItemPlacementArray& itemPlacementArrayToUse) -> float
  690. {
  691. float highestColumnSize = 0.0f;
  692. for (const auto& i : itemPlacementArrayToUse)
  693. if (! isSpan (i.second.column) && i.second.column.start == rowNumber)
  694. highestColumnSize = std::max (highestColumnSize, i.first->width + i.first->margin.left + i.first->margin.right);
  695. return highestColumnSize;
  696. };
  697. for (int i = 0; i < rows.size(); i++)
  698. if (rows.getReference (i).hasKeyword)
  699. rows.getReference (i).size = getHighestItemOnRow (i + 1, itemPlacementArray);
  700. for (int i = 0; i < columns.size(); i++)
  701. if (columns.getReference (i).hasKeyword)
  702. columns.getReference (i).size = getHighestItemOnColumn (i + 1, itemPlacementArray);
  703. }
  704. };
  705. //==============================================================================
  706. struct Grid::BoxAlignment
  707. {
  708. static juce::Rectangle<float> alignItem (const GridItem& item,
  709. const Grid& grid,
  710. juce::Rectangle<float> area)
  711. {
  712. // if item align is auto, inherit value from grid
  713. Grid::AlignItems alignType = Grid::AlignItems::start;
  714. Grid::JustifyItems justifyType = Grid::JustifyItems::start;
  715. if (item.alignSelf == GridItem::AlignSelf::autoValue)
  716. alignType = grid.alignItems;
  717. else
  718. alignType = static_cast<Grid::AlignItems> (item.alignSelf);
  719. if (item.justifySelf == GridItem::JustifySelf::autoValue)
  720. justifyType = grid.justifyItems;
  721. else
  722. justifyType = static_cast<Grid::JustifyItems> (item.justifySelf);
  723. // subtract margin from area
  724. area = juce::BorderSize<float> (item.margin.top, item.margin.left, item.margin.bottom, item.margin.right)
  725. .subtractedFrom (area);
  726. // align and justify
  727. auto r = area;
  728. if (item.width != GridItem::notAssigned)
  729. r.setWidth (item.width);
  730. if (item.height != GridItem::notAssigned)
  731. r.setHeight (item.height);
  732. if (alignType == Grid::AlignItems::start && justifyType == Grid::JustifyItems::start)
  733. return r;
  734. if (alignType == Grid::AlignItems::end)
  735. r.setY (r.getY() + (area.getHeight() - r.getHeight()));
  736. if (justifyType == Grid::JustifyItems::end)
  737. r.setX (r.getX() + (area.getWidth() - r.getWidth()));
  738. if (alignType == Grid::AlignItems::center)
  739. r.setCentre (r.getCentreX(), area.getCentreY());
  740. if (justifyType == Grid::JustifyItems::center)
  741. r.setCentre (area.getCentreX(), r.getCentreY());
  742. return r;
  743. }
  744. };
  745. //==============================================================================
  746. Grid::TrackInfo::TrackInfo() noexcept : hasKeyword (true) {}
  747. Grid::TrackInfo::TrackInfo (Px sizeInPixels) noexcept : size (static_cast<float> (sizeInPixels.pixels)), isFraction (false) {}
  748. Grid::TrackInfo::TrackInfo (Fr fractionOfFreeSpace) noexcept : size ((float)fractionOfFreeSpace.fraction), isFraction (true) {}
  749. Grid::TrackInfo::TrackInfo (Px sizeInPixels, const juce::String& endLineNameToUse) noexcept : Grid::TrackInfo (sizeInPixels)
  750. {
  751. endLineName = endLineNameToUse;
  752. }
  753. Grid::TrackInfo::TrackInfo (Fr fractionOfFreeSpace, const juce::String& endLineNameToUse) noexcept : Grid::TrackInfo (fractionOfFreeSpace)
  754. {
  755. endLineName = endLineNameToUse;
  756. }
  757. Grid::TrackInfo::TrackInfo (const juce::String& startLineNameToUse, Px sizeInPixels) noexcept : Grid::TrackInfo (sizeInPixels)
  758. {
  759. startLineName = startLineNameToUse;
  760. }
  761. Grid::TrackInfo::TrackInfo (const juce::String& startLineNameToUse, Fr fractionOfFreeSpace) noexcept : Grid::TrackInfo (fractionOfFreeSpace)
  762. {
  763. startLineName = startLineNameToUse;
  764. }
  765. Grid::TrackInfo::TrackInfo (const juce::String& startLineNameToUse, Px sizeInPixels, const juce::String& endLineNameToUse) noexcept
  766. : Grid::TrackInfo (startLineNameToUse, sizeInPixels)
  767. {
  768. endLineName = endLineNameToUse;
  769. }
  770. Grid::TrackInfo::TrackInfo (const juce::String& startLineNameToUse, Fr fractionOfFreeSpace, const juce::String& endLineNameToUse) noexcept
  771. : Grid::TrackInfo (startLineNameToUse, fractionOfFreeSpace)
  772. {
  773. endLineName = endLineNameToUse;
  774. }
  775. //==============================================================================
  776. Grid::Grid() noexcept {}
  777. Grid::~Grid() noexcept {}
  778. //==============================================================================
  779. void Grid::performLayout (juce::Rectangle<int> targetArea)
  780. {
  781. const auto itemsAndAreas = Grid::AutoPlacement().deduceAllItems (*this);
  782. const auto implicitTracks = Grid::AutoPlacement::createImplicitTracks (*this, itemsAndAreas);
  783. auto columnTracks = templateColumns;
  784. auto rowTracks = templateRows;
  785. columnTracks.addArray (implicitTracks.first);
  786. rowTracks.addArray (implicitTracks.second);
  787. Grid::AutoPlacement::applySizeForAutoTracks (columnTracks, rowTracks, itemsAndAreas);
  788. Grid::SizeCalculation calculation;
  789. calculation.computeSizes (targetArea.toFloat().getWidth(),
  790. targetArea.toFloat().getHeight(),
  791. columnGap,
  792. rowGap,
  793. columnTracks,
  794. rowTracks);
  795. for (auto& itemAndArea : itemsAndAreas)
  796. {
  797. const auto a = itemAndArea.second;
  798. const auto areaBounds = Grid::PlacementHelpers::getAreaBounds (a.column.start, a.column.end,
  799. a.row.start, a.row.end,
  800. columnTracks,
  801. rowTracks,
  802. calculation,
  803. alignContent,
  804. justifyContent,
  805. columnGap,
  806. rowGap);
  807. auto* item = itemAndArea.first;
  808. item->currentBounds = Grid::BoxAlignment::alignItem (*item, *this, areaBounds)
  809. + targetArea.toFloat().getPosition();
  810. if (auto* c = item->associatedComponent)
  811. c->setBounds (item->currentBounds.toNearestIntEdges());
  812. }
  813. }
  814. } // namespace juce