stacklayout.d 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. module renderable.stacklayout;
  2. import app;
  3. import renderable.rect;
  4. import renderable.renderable;
  5. import vector;
  6. import color;
  7. import cell;
  8. import std.stdio;
  9. import std.algorithm;
  10. import renderable.cellcachecontainer;
  11. import stacklayouttype;
  12. class StackLayout : Renderable {
  13. StackLayoutType stackLayoutType;
  14. int spacing;
  15. Color backgroundColor;
  16. Renderable[] children;
  17. private CellCacheContainer container;
  18. private Vector cursor = Vector(0, 0);
  19. this(StackLayoutType stackLayoutType, Color backgroundColor) {
  20. this(stackLayoutType, 0, backgroundColor);
  21. }
  22. this(StackLayoutType stackLayoutType, int spacing = 0, Color backgroundColor = Color.terminal()) {
  23. this.stackLayoutType = stackLayoutType;
  24. this.spacing = spacing;
  25. this.backgroundColor = backgroundColor;
  26. container = new CellCacheContainer();
  27. }
  28. void add(Renderable renderable) {
  29. container.updateCache(renderable, cursor);
  30. children ~= renderable;
  31. updateCursor();
  32. if (stackLayoutType == StackLayoutType.row) {
  33. this.dimension. x = cursor.x - spacing;
  34. this.dimension. y = children.maxElement!(child => child.dimension. y ).dimension. y ;
  35. } else {
  36. this.dimension. x = children.maxElement!(child => child.dimension. x ).dimension. x ;
  37. this.dimension. y = cursor.y - spacing;
  38. }
  39. }
  40. void add(Renderable[] renderableArr...) {
  41. foreach (renderable; renderableArr) {
  42. add(renderable);
  43. }
  44. }
  45. void add(Renderable renderable, int dup) {
  46. for (int i = 0; i < dup; ++i) {
  47. add(renderable);
  48. }
  49. }
  50. void updateCursor() {
  51. if (stackLayoutType == StackLayoutType.row) {
  52. this.cursor = Vector(children.map!(child => child.dimension. x ).sum() + (cast(int)(children.length) * spacing), 0);
  53. } else {
  54. this.cursor = Vector(0, children.map!(child => child.dimension. y ).sum() + (cast(int)(children.length) * spacing));
  55. }
  56. }
  57. override Cell[] render() {
  58. if (backgroundColor != Color.terminal()) {
  59. container.updateCache(Rect.withFill(dimension, backgroundColor), Vector(0, 0));
  60. }
  61. return container.cache;
  62. }
  63. }