Scoop API

scoop:scoop.ui.style:0.1.0

src/cache/filters.scoop

Selected production source · src/cache/filters.scoop

1package scoop.ui.style
3import scoop.graphics.*
5/** A single current filter graph, never a cache of subtree pixels. */
6internal class ContentFilterCache: Closeable {
7 private var inputs: Array<ContentEffect> = []
8 private var current: ImageFilter? = None
10 fun update(effects: Array<ContentEffect>): ImageFilter? {
11 if (sameEffects(inputs, effects))
12 return current
13 var next: ImageFilter? = None
14 try {
15 for (effect in effects) {
16 val part = createFilter(effect)
17 when (next) {
18 case Some(val previous) -> {
19 val joined =
20 try {
21 previous.then(part)
22 } finally {
23 part.close()
24 }
25 next = Some(joined)
26 previous.close()
27 }
28 case None -> next = Some(part)
29 }
30 }
31 } catch (error: Throwable) {
32 val failed = next
33 throwStyle(cleanupStyle(Some(error)) { failed?.close() })
34 throw error
35 }
36 val previous = current
37 current = next
38 inputs = effects
39 previous?.close()
40 return next
41 }
43 public override fun close() {
44 val previous = current
45 current = None
46 inputs = []
47 previous?.close()
48 }
51internal class BoxFilterCache: Closeable {
52 private var inputs: Array<BoxShadow> = []
53 private var current: Array<ImageFilter> = []
55 fun update(shadows: Array<BoxShadow>): Array<ImageFilter> {
56 if (sameShadows(inputs, shadows))
57 return current
58 val next = ArrayList<ImageFilter>()
59 try {
60 for (shadow in shadows)
61 next.add(
62 ImageFilter.dropShadowOnly(
63 shadow.offset,
64 shadow.sigmaX,
65 shadow.sigmaY,
66 shadow.color
67 )
68 )
69 } catch (error: Throwable) {
70 throwStyle(closeFilters(next.toArray(), Some(error)))
71 throw error
72 }
73 val previous = current
74 current = next.toArray()
75 inputs = shadows
76 throwStyle(closeFilters(previous))
77 return current
78 }
80 public override fun close() {
81 val previous = current
82 current = []
83 inputs = []
84 throwStyle(closeFilters(previous))
85 }
88private fun createFilter(effect: ContentEffect): ImageFilter =
89 when (effect) {
90 case Blur(val x, val y) -> ImageFilter.blur(x, y)
91 case DropShadow(val offset, val x, val y, val color) -> ImageFilter.dropShadow(offset, x, y, color)
92 case Glow(val x, val y, val color) -> ImageFilter.dropShadow(Point(0.0, 0.0), x, y, color)
93 }
95private fun sameEffects(a: Array<ContentEffect>, b: Array<ContentEffect>): Boolean {
96 if (a.size != b.size)
97 return false
98 for (i in 0L until a.size)
99 if (a[i] != b[i])
100 return false
101 return true
104private fun sameShadows(a: Array<BoxShadow>, b: Array<BoxShadow>): Boolean {
105 if (a.size != b.size)
106 return false
107 for (i in 0L until a.size)
108 if (a[i] != b[i])
109 return false
110 return true
113private fun closeFilters(values: Array<ImageFilter>, failure: Throwable? = None): Throwable? {
114 var result = failure
115 for (value in values)
116 result = cleanupStyle(result) { value.close() }
117 return result