1/*
2 * Copyright (C) 2024 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
17import {assertDefined} from 'common/assert_utils';
18import {Computation} from 'trace/tree_node/computation';
19import {HierarchyTreeNode} from 'trace/tree_node/hierarchy_tree_node';
20import {DEFAULT_PROPERTY_TREE_NODE_FACTORY} from 'trace/tree_node/property_tree_node_factory';
21
22export class ZOrderPathsComputation implements Computation {
23  private root: HierarchyTreeNode | undefined;
24
25  setRoot(value: HierarchyTreeNode): ZOrderPathsComputation {
26    this.root = value;
27    return this;
28  }
29
30  executeInPlace(): void {
31    if (!this.root) {
32      throw new Error('root not set in SF z-order paths computation');
33    }
34    const layerIdToTreeNode = this.makeMapOfIdToNode();
35    this.updateZOrderParents(layerIdToTreeNode);
36  }
37
38  private makeMapOfIdToNode(): Map<number, HierarchyTreeNode> {
39    const layerIdToTreeNode = new Map<number, HierarchyTreeNode>();
40    assertDefined(this.root).forEachNodeDfs((node) => {
41      if (node.isRoot()) return;
42      layerIdToTreeNode.set(
43        assertDefined(node.getEagerPropertyByName('id')).getValue(),
44        node,
45      );
46    });
47    return layerIdToTreeNode;
48  }
49
50  private updateZOrderParents(
51    layerIdToTreeNode: Map<number, HierarchyTreeNode>,
52  ) {
53    assertDefined(this.root).forEachNodeDfs((node) => {
54      const zOrderRelativeOf = node
55        .getEagerPropertyByName('zOrderRelativeOf')
56        ?.getValue();
57      if (zOrderRelativeOf && zOrderRelativeOf !== -1) {
58        const zParent = layerIdToTreeNode.get(zOrderRelativeOf);
59        if (!zParent) {
60          node.addEagerProperty(
61            DEFAULT_PROPERTY_TREE_NODE_FACTORY.makeCalculatedProperty(
62              node.id,
63              'isMissingZParent',
64              true,
65            ),
66          );
67          return;
68        }
69        node.setZParent(zParent);
70        zParent.addRelativeChild(node);
71      }
72    });
73  }
74}
75