Audio plugin host https://kx.studio/carla
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.

juce_Grid.cpp 39KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  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. return namedAreas.at (item.area);
  243. return { deduceLineRange (item.column, grid.templateColumns),
  244. deduceLineRange (item.row, grid.templateRows) };
  245. }
  246. //==============================================================================
  247. static juce::Array<juce::StringArray> parseAreasProperty (const juce::StringArray& areasStrings)
  248. {
  249. juce::Array<juce::StringArray> strings;
  250. for (const auto& areaString : areasStrings)
  251. strings.add (juce::StringArray::fromTokens (areaString, false));
  252. if (strings.size() > 0)
  253. for (auto s : strings)
  254. jassert (s.size() == strings[0].size()); // all rows must have the same number of columns
  255. return strings;
  256. }
  257. static NamedArea findArea (juce::Array<juce::StringArray>& stringsArrays)
  258. {
  259. NamedArea area;
  260. for (auto& stringArray : stringsArrays)
  261. {
  262. for (auto& string : stringArray)
  263. {
  264. // find anchor
  265. if (area.name.isEmpty())
  266. {
  267. if (string != emptyAreaCharacter)
  268. {
  269. area.name = string;
  270. area.lines.row.start = stringsArrays.indexOf (stringArray) + 1; // non-zero indexed;
  271. area.lines.column.start = stringArray.indexOf (string) + 1; // non-zero indexed;
  272. area.lines.row.end = stringsArrays.indexOf (stringArray) + 2;
  273. area.lines.column.end = stringArray.indexOf (string) + 2;
  274. // mark as visited
  275. string = emptyAreaCharacter;
  276. }
  277. }
  278. else
  279. {
  280. if (string == emptyAreaCharacter)
  281. {
  282. break;
  283. }
  284. else if (string == area.name)
  285. {
  286. area.lines.row.end = stringsArrays.indexOf (stringArray) + 2;
  287. area.lines.column.end = stringArray.indexOf (string) + 2;
  288. // mark as visited
  289. string = emptyAreaCharacter;
  290. }
  291. }
  292. }
  293. }
  294. return area;
  295. }
  296. //==============================================================================
  297. static std::map<juce::String, LineArea> deduceNamedAreas (const juce::StringArray& areasStrings)
  298. {
  299. auto stringsArrays = parseAreasProperty (areasStrings);
  300. std::map<juce::String, LineArea> areas;
  301. for (auto area = findArea (stringsArrays); area.name.isNotEmpty(); area = findArea (stringsArrays))
  302. {
  303. if (areas.count (area.name) == 0)
  304. areas[area.name] = area.lines;
  305. else
  306. // Make sure your template-areas property only has one area with the same name and is well-formed
  307. jassertfalse;
  308. }
  309. return areas;
  310. }
  311. //==============================================================================
  312. static float getCoord (int trackNumber, float relativeUnit, Px gap, const juce::Array<Grid::TrackInfo>& tracks)
  313. {
  314. float c = 0;
  315. for (const auto* it = tracks.begin(); it != tracks.begin() + trackNumber - 1; ++it)
  316. c += (it->isFraction ? it->size * relativeUnit : it->size) + static_cast<float> (gap.pixels);
  317. return c;
  318. }
  319. static juce::Rectangle<float> getCellBounds (int columnNumber, int rowNumber,
  320. const juce::Array<Grid::TrackInfo>& columnTracks,
  321. const juce::Array<Grid::TrackInfo>& rowTracks,
  322. Grid::SizeCalculation calculation,
  323. Px columnGap, Px rowGap)
  324. {
  325. jassert (columnNumber >= 1 && columnNumber <= columnTracks.size());
  326. jassert (rowNumber >= 1 && rowNumber <= rowTracks.size());
  327. const auto x = getCoord (columnNumber, calculation.relativeWidthUnit, columnGap, columnTracks);
  328. const auto y = getCoord (rowNumber, calculation.relativeHeightUnit, rowGap, rowTracks);
  329. const auto& columnTrackInfo = columnTracks.getReference (columnNumber - 1);
  330. const float width = columnTrackInfo.isFraction ? columnTrackInfo.size * calculation.relativeWidthUnit
  331. : columnTrackInfo.size;
  332. const auto& rowTrackInfo = rowTracks.getReference (rowNumber - 1);
  333. const float height = rowTrackInfo.isFraction ? rowTrackInfo.size * calculation.relativeHeightUnit
  334. : rowTrackInfo.size;
  335. return { x, y, width, height };
  336. }
  337. static juce::Rectangle<float> alignCell (juce::Rectangle<float> area,
  338. int columnNumber, int rowNumber,
  339. int numberOfColumns, int numberOfRows,
  340. Grid::SizeCalculation calculation,
  341. Grid::AlignContent alignContent,
  342. Grid::JustifyContent justifyContent)
  343. {
  344. if (alignContent == Grid::AlignContent::end)
  345. area.setY (area.getY() + calculation.remainingHeight);
  346. if (justifyContent == Grid::JustifyContent::end)
  347. area.setX (area.getX() + calculation.remainingWidth);
  348. if (alignContent == Grid::AlignContent::center)
  349. area.setY (area.getY() + calculation.remainingHeight / 2);
  350. if (justifyContent == Grid::JustifyContent::center)
  351. area.setX (area.getX() + calculation.remainingWidth / 2);
  352. if (alignContent == Grid::AlignContent::spaceBetween)
  353. {
  354. const auto shift = ((rowNumber - 1) * (calculation.remainingHeight / float(numberOfRows - 1)));
  355. area.setY (area.getY() + shift);
  356. }
  357. if (justifyContent == Grid::JustifyContent::spaceBetween)
  358. {
  359. const auto shift = ((columnNumber - 1) * (calculation.remainingWidth / float(numberOfColumns - 1)));
  360. area.setX (area.getX() + shift);
  361. }
  362. if (alignContent == Grid::AlignContent::spaceEvenly)
  363. {
  364. const auto shift = (rowNumber * (calculation.remainingHeight / float(numberOfRows + 1)));
  365. area.setY (area.getY() + shift);
  366. }
  367. if (justifyContent == Grid::JustifyContent::spaceEvenly)
  368. {
  369. const auto shift = (columnNumber * (calculation.remainingWidth / float(numberOfColumns + 1)));
  370. area.setX (area.getX() + shift);
  371. }
  372. if (alignContent == Grid::AlignContent::spaceAround)
  373. {
  374. const auto inbetweenShift = calculation.remainingHeight / float(numberOfRows);
  375. const auto sidesShift = inbetweenShift / 2;
  376. auto shift = (rowNumber - 1) * inbetweenShift + sidesShift;
  377. area.setY (area.getY() + shift);
  378. }
  379. if (justifyContent == Grid::JustifyContent::spaceAround)
  380. {
  381. const auto inbetweenShift = calculation.remainingWidth / float(numberOfColumns);
  382. const auto sidesShift = inbetweenShift / 2;
  383. auto shift = (columnNumber - 1) * inbetweenShift + sidesShift;
  384. area.setX (area.getX() + shift);
  385. }
  386. return area;
  387. }
  388. static juce::Rectangle<float> getAreaBounds (int columnLineNumberStart, int columnLineNumberEnd,
  389. int rowLineNumberStart, int rowLineNumberEnd,
  390. const juce::Array<Grid::TrackInfo>& columnTracks,
  391. const juce::Array<Grid::TrackInfo>& rowTracks,
  392. Grid::SizeCalculation calculation,
  393. Grid::AlignContent alignContent,
  394. Grid::JustifyContent justifyContent,
  395. Px columnGap, Px rowGap)
  396. {
  397. auto startCell = getCellBounds (columnLineNumberStart, rowLineNumberStart,
  398. columnTracks, rowTracks,
  399. calculation,
  400. columnGap, rowGap);
  401. auto endCell = getCellBounds (columnLineNumberEnd - 1, rowLineNumberEnd - 1,
  402. columnTracks, rowTracks,
  403. calculation,
  404. columnGap, rowGap);
  405. startCell = alignCell (startCell,
  406. columnLineNumberStart, rowLineNumberStart,
  407. columnTracks.size(), rowTracks.size(),
  408. calculation,
  409. alignContent,
  410. justifyContent);
  411. endCell = alignCell (endCell,
  412. columnLineNumberEnd - 1, rowLineNumberEnd - 1,
  413. columnTracks.size(), rowTracks.size(),
  414. calculation,
  415. alignContent,
  416. justifyContent);
  417. return startCell.getUnion (endCell);
  418. }
  419. };
  420. //==============================================================================
  421. struct Grid::AutoPlacement
  422. {
  423. using ItemPlacementArray = juce::Array<std::pair<GridItem*, Grid::PlacementHelpers::LineArea>>;
  424. //==============================================================================
  425. struct OccupancyPlane
  426. {
  427. struct Cell { int column, row; };
  428. OccupancyPlane (int highestColumnToUse, int highestRowToUse, bool isColoumnFirst)
  429. : highestCrossDimension (isColoumnFirst ? highestRowToUse : highestColumnToUse),
  430. columnFirst (isColoumnFirst)
  431. {}
  432. Grid::PlacementHelpers::LineArea setCell (Cell cell, int columnSpan, int rowSpan)
  433. {
  434. for (int i = 0; i < columnSpan; i++)
  435. for (int j = 0; j < rowSpan; j++)
  436. setCell (cell.column + i, cell.row + j);
  437. return { { cell.column, cell.column + columnSpan }, { cell.row, cell.row + rowSpan } };
  438. }
  439. Grid::PlacementHelpers::LineArea setCell (Cell start, Cell end)
  440. {
  441. return setCell (start, std::abs (end.column - start.column),
  442. std::abs (end.row - start.row));
  443. }
  444. Cell nextAvailable (Cell referenceCell, int columnSpan, int rowSpan)
  445. {
  446. while (isOccupied (referenceCell, columnSpan, rowSpan) || isOutOfBounds (referenceCell, columnSpan, rowSpan))
  447. referenceCell = advance (referenceCell);
  448. return referenceCell;
  449. }
  450. Cell nextAvailableOnRow (Cell referenceCell, int columnSpan, int rowSpan, int rowNumber)
  451. {
  452. if (columnFirst && (rowNumber + rowSpan) > highestCrossDimension)
  453. highestCrossDimension = rowNumber + rowSpan;
  454. while (isOccupied (referenceCell, columnSpan, rowSpan)
  455. || (referenceCell.row != rowNumber))
  456. referenceCell = advance (referenceCell);
  457. return referenceCell;
  458. }
  459. Cell nextAvailableOnColumn (Cell referenceCell, int columnSpan, int rowSpan, int columnNumber)
  460. {
  461. if (! columnFirst && (columnNumber + columnSpan) > highestCrossDimension)
  462. highestCrossDimension = columnNumber + columnSpan;
  463. while (isOccupied (referenceCell, columnSpan, rowSpan)
  464. || (referenceCell.column != columnNumber))
  465. referenceCell = advance (referenceCell);
  466. return referenceCell;
  467. }
  468. private:
  469. struct SortableCell
  470. {
  471. int column, row;
  472. bool columnFirst;
  473. bool operator< (const SortableCell& other) const
  474. {
  475. if (columnFirst)
  476. {
  477. if (row == other.row)
  478. return column < other.column;
  479. return row < other.row;
  480. }
  481. if (row == other.row)
  482. return column < other.column;
  483. return row < other.row;
  484. }
  485. };
  486. void setCell (int column, int row)
  487. {
  488. occupiedCells.insert ({ column, row, columnFirst });
  489. }
  490. bool isOccupied (Cell cell) const
  491. {
  492. return occupiedCells.count ({ cell.column, cell.row, columnFirst }) > 0;
  493. }
  494. bool isOccupied (Cell cell, int columnSpan, int rowSpan) const
  495. {
  496. for (int i = 0; i < columnSpan; i++)
  497. for (int j = 0; j < rowSpan; j++)
  498. if (isOccupied ({ cell.column + i, cell.row + j }))
  499. return true;
  500. return false;
  501. }
  502. bool isOutOfBounds (Cell cell, int columnSpan, int rowSpan) const
  503. {
  504. const auto crossSpan = columnFirst ? rowSpan : columnSpan;
  505. return (getCrossDimension (cell) + crossSpan) > getHighestCrossDimension();
  506. }
  507. int getHighestCrossDimension() const
  508. {
  509. Cell cell { 1, 1 };
  510. if (occupiedCells.size() > 0)
  511. cell = { occupiedCells.crbegin()->column, occupiedCells.crbegin()->row };
  512. return std::max (getCrossDimension (cell), highestCrossDimension);
  513. }
  514. Cell advance (Cell cell) const
  515. {
  516. if ((getCrossDimension (cell) + 1) >= getHighestCrossDimension())
  517. return fromDimensions (getMainDimension (cell) + 1, 1);
  518. return fromDimensions (getMainDimension (cell), getCrossDimension (cell) + 1);
  519. }
  520. int getMainDimension (Cell cell) const { return columnFirst ? cell.column : cell.row; }
  521. int getCrossDimension (Cell cell) const { return columnFirst ? cell.row : cell.column; }
  522. Cell fromDimensions (int mainDimension, int crossDimension) const
  523. {
  524. if (columnFirst)
  525. return { mainDimension, crossDimension };
  526. return { crossDimension, mainDimension };
  527. }
  528. int highestCrossDimension;
  529. bool columnFirst;
  530. std::set<SortableCell> occupiedCells;
  531. };
  532. //==============================================================================
  533. static bool isFixed (GridItem::StartAndEndProperty prop)
  534. {
  535. return prop.start.hasName() || prop.start.hasAbsolute() || prop.end.hasName() || prop.end.hasAbsolute();
  536. }
  537. static bool hasFullyFixedPlacement (const GridItem& item)
  538. {
  539. if (item.area.isNotEmpty())
  540. return true;
  541. if (isFixed (item.column) && isFixed (item.row))
  542. return true;
  543. return false;
  544. }
  545. static bool hasPartialFixedPlacement (const GridItem& item)
  546. {
  547. if (item.area.isNotEmpty())
  548. return false;
  549. if (isFixed (item.column) ^ isFixed (item.row))
  550. return true;
  551. return false;
  552. }
  553. static bool hasAutoPlacement (const GridItem& item)
  554. {
  555. return ! hasFullyFixedPlacement (item) && ! hasPartialFixedPlacement (item);
  556. }
  557. //==============================================================================
  558. static bool hasDenseAutoFlow (Grid::AutoFlow autoFlow)
  559. {
  560. return autoFlow == Grid::AutoFlow::columnDense
  561. || autoFlow == Grid::AutoFlow::rowDense;
  562. }
  563. static bool isColumnAutoFlow (Grid::AutoFlow autoFlow)
  564. {
  565. return autoFlow == Grid::AutoFlow::column
  566. || autoFlow == Grid::AutoFlow::columnDense;
  567. }
  568. //==============================================================================
  569. static int getSpanFromAuto (GridItem::StartAndEndProperty prop)
  570. {
  571. if (prop.end.hasSpan())
  572. return prop.end.number;
  573. if (prop.start.hasSpan())
  574. return prop.start.number;
  575. return 1;
  576. }
  577. //==============================================================================
  578. ItemPlacementArray deduceAllItems (Grid& grid) const
  579. {
  580. const auto namedAreas = Grid::PlacementHelpers::deduceNamedAreas (grid.templateAreas);
  581. OccupancyPlane plane (juce::jmax (grid.templateColumns.size() + 1, 2),
  582. juce::jmax (grid.templateRows.size() + 1, 2),
  583. isColumnAutoFlow (grid.autoFlow));
  584. ItemPlacementArray itemPlacementArray;
  585. juce::Array<GridItem*> sortedItems;
  586. for (auto& item : grid.items)
  587. sortedItems.add (&item);
  588. sortedItems.sort (*this, true);
  589. // place fixed items first
  590. for (auto* item : sortedItems)
  591. {
  592. if (hasFullyFixedPlacement (*item))
  593. {
  594. const auto a = Grid::PlacementHelpers::deduceLineArea (*item, grid, namedAreas);
  595. plane.setCell ({ a.column.start, a.row.start }, { a.column.end, a.row.end });
  596. itemPlacementArray.add ({ item, a });
  597. }
  598. }
  599. OccupancyPlane::Cell lastInsertionCell = { 1, 1 };
  600. for (auto* item : sortedItems)
  601. {
  602. if (hasPartialFixedPlacement (*item))
  603. {
  604. if (isFixed (item->column))
  605. {
  606. const auto p = Grid::PlacementHelpers::deduceLineRange (item->column, grid.templateColumns);
  607. const auto columnSpan = std::abs (p.start - p.end);
  608. const auto rowSpan = getSpanFromAuto (item->row);
  609. const auto insertionCell = hasDenseAutoFlow (grid.autoFlow) ? OccupancyPlane::Cell { p.start, 1 }
  610. : lastInsertionCell;
  611. const auto nextAvailableCell = plane.nextAvailableOnColumn (insertionCell, columnSpan, rowSpan, p.start);
  612. const auto lineArea = plane.setCell (nextAvailableCell, columnSpan, rowSpan);
  613. lastInsertionCell = nextAvailableCell;
  614. itemPlacementArray.add ({ item, lineArea });
  615. }
  616. else if (isFixed (item->row))
  617. {
  618. const auto p = Grid::PlacementHelpers::deduceLineRange (item->row, grid.templateRows);
  619. const auto columnSpan = getSpanFromAuto (item->column);
  620. const auto rowSpan = std::abs (p.start - p.end);
  621. const auto insertionCell = hasDenseAutoFlow (grid.autoFlow) ? OccupancyPlane::Cell { 1, p.start }
  622. : lastInsertionCell;
  623. const auto nextAvailableCell = plane.nextAvailableOnRow (insertionCell, columnSpan, rowSpan, p.start);
  624. const auto lineArea = plane.setCell (nextAvailableCell, columnSpan, rowSpan);
  625. lastInsertionCell = nextAvailableCell;
  626. itemPlacementArray.add ({ item, lineArea });
  627. }
  628. }
  629. }
  630. lastInsertionCell = { 1, 1 };
  631. for (auto* item : sortedItems)
  632. {
  633. if (hasAutoPlacement (*item))
  634. {
  635. const auto columnSpan = getSpanFromAuto (item->column);
  636. const auto rowSpan = getSpanFromAuto (item->row);
  637. const auto nextAvailableCell = plane.nextAvailable (lastInsertionCell, columnSpan, rowSpan);
  638. const auto lineArea = plane.setCell (nextAvailableCell, columnSpan, rowSpan);
  639. if (! hasDenseAutoFlow (grid.autoFlow))
  640. lastInsertionCell = nextAvailableCell;
  641. itemPlacementArray.add ({ item, lineArea });
  642. }
  643. }
  644. return itemPlacementArray;
  645. }
  646. //==============================================================================
  647. static std::pair<int, int> getHighestEndLinesNumbers (const ItemPlacementArray& items)
  648. {
  649. int columnEndLine = 1;
  650. int rowEndLine = 1;
  651. for (auto& item : items)
  652. {
  653. const auto p = item.second;
  654. columnEndLine = std::max (p.column.end, columnEndLine);
  655. rowEndLine = std::max (p.row.end, rowEndLine);
  656. }
  657. return { columnEndLine, rowEndLine };
  658. }
  659. static std::pair<juce::Array<TrackInfo>, juce::Array<TrackInfo>> createImplicitTracks (const Grid& grid,
  660. const ItemPlacementArray& items)
  661. {
  662. const auto columnAndRowLineEnds = getHighestEndLinesNumbers (items);
  663. juce::Array<TrackInfo> implicitColumnTracks, implicitRowTracks;
  664. for (int i = grid.templateColumns.size() + 1; i < columnAndRowLineEnds.first; i++)
  665. implicitColumnTracks.add (grid.autoColumns);
  666. for (int i = grid.templateRows.size() + 1; i < columnAndRowLineEnds.second; i++)
  667. implicitRowTracks.add (grid.autoRows);
  668. return { implicitColumnTracks, implicitRowTracks };
  669. }
  670. //==============================================================================
  671. static int compareElements (const GridItem* i1, const GridItem* i2) noexcept
  672. {
  673. return i1->order < i2->order ? -1 : (i2->order < i1->order ? 1 : 0);
  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.toNearestInt());
  812. }
  813. }
  814. } // namespace juce