1 /*
2  * Copyright 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.compose.animation.scene
18 
19 /**
20  * A base class to create unique keys, associated to an [identity] that is used to check the
21  * equality of two key instances.
22  */
23 sealed class Key(val name: String, val identity: Any) {
24     override fun equals(other: Any?): Boolean {
25         if (this === other) return true
26         if (this.javaClass != other?.javaClass) return false
27         return identity == (other as? Key)?.identity
28     }
29 
30     override fun hashCode(): Int {
31         return identity.hashCode()
32     }
33 
34     override fun toString(): String {
35         return "Key(name=$name)"
36     }
37 }
38 
39 /** Key for a scene. */
40 class SceneKey(
41     name: String,
42     identity: Any = Object(),
43 ) : Key(name, identity) {
44 
45     /** The unique [ElementKey] identifying this scene's root element. */
46     val rootElementKey = ElementKey(name, identity)
47 
48     override fun toString(): String {
49         return "SceneKey(name=$name)"
50     }
51 }
52 
53 /** Key for an element. */
54 class ElementKey(
55     name: String,
56     identity: Any = Object(),
57 
58     /**
59      * Whether this element is a background and usually drawn below other elements. This should be
60      * set to true to make sure that shared backgrounds are drawn below elements of other scenes.
61      */
62     val isBackground: Boolean = false,
63 ) : Key(name, identity), ElementMatcher {
64     override fun matches(key: ElementKey): Boolean {
65         return key == this
66     }
67 
68     override fun toString(): String {
69         return "ElementKey(name=$name)"
70     }
71 
72     companion object {
73         /** Matches any element whose [key identity][ElementKey.identity] matches [predicate]. */
74         fun withIdentity(predicate: (Any) -> Boolean): ElementMatcher {
75             return object : ElementMatcher {
76                 override fun matches(key: ElementKey): Boolean = predicate(key.identity)
77             }
78         }
79     }
80 }
81 
82 /** Key for a shared value of an element. */
83 class ValueKey(name: String, identity: Any = Object()) : Key(name, identity) {
84     override fun toString(): String {
85         return "ValueKey(name=$name)"
86     }
87 }
88