summaryrefslogtreecommitdiff
path: root/library/main/src/com/android/setupwizardlib/items/ItemGroup.java
blob: 246469f10cbcbf1d58ac4a40e7fdaff3e883cefb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.setupwizardlib.items;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseIntArray;
import java.util.ArrayList;
import java.util.List;

public class ItemGroup extends AbstractItemHierarchy
    implements ItemInflater.ItemParent, ItemHierarchy.Observer {

  /* static section */

  private static final String TAG = "ItemGroup";

  /**
   * Binary search for the closest value that's smaller than or equal to {@code value}, and return
   * the corresponding key.
   */
  private static int binarySearch(SparseIntArray array, int value) {
    final int size = array.size();
    int lo = 0;
    int hi = size - 1;

    while (lo <= hi) {
      final int mid = (lo + hi) >>> 1;
      final int midVal = array.valueAt(mid);

      if (midVal < value) {
        lo = mid + 1;
      } else if (midVal > value) {
        hi = mid - 1;
      } else {
        return array.keyAt(mid); // value found
      }
    }
    // Value not found. Return the last item before our search range, which is the closest
    // value smaller than the value we are looking for.
    return array.keyAt(lo - 1);
  }

  /**
   * Same as {@link List#indexOf(Object)}, but using identity comparison rather than {@link
   * Object#equals(Object)}.
   */
  private static <T> int identityIndexOf(List<T> list, T object) {
    final int count = list.size();
    for (int i = 0; i < count; i++) {
      if (list.get(i) == object) {
        return i;
      }
    }
    return -1;
  }

  /* non-static section */

  private final List<ItemHierarchy> children = new ArrayList<>();

  /**
   * A mapping from the index of an item hierarchy in children, to the first position in which the
   * corresponding child hierarchy represents. For example:
   *
   * <p>ItemHierarchy Item Item Position Index
   *
   * <p>0 [ Wi-Fi AP 1 ] 0 | Wi-Fi AP 2 | 1 | Wi-Fi AP 3 | 2 | Wi-Fi AP 4 | 3 [ Wi-Fi AP 5 ] 4
   *
   * <p>1 [ <Empty Item Hierarchy> ]
   *
   * <p>2 [ Use cellular data ] 5
   *
   * <p>3 [ Don't connect ] 6
   *
   * <p>For this example of Wi-Fi screen, the following mapping will be produced: [ 0 -> 0 | 2 -> 5
   * | 3 -> 6 ]
   *
   * <p>Also note how ItemHierarchy index 1 is not present in the map, because it is empty.
   *
   * <p>ItemGroup uses this map to look for which ItemHierarchy an item at a given position belongs
   * to.
   */
  private final SparseIntArray hierarchyStart = new SparseIntArray();

  private int count = 0;
  private boolean dirty = false;

  public ItemGroup() {
    super();
  }

  public ItemGroup(Context context, AttributeSet attrs) {
    // Constructor for XML inflation
    super(context, attrs);
  }

  /** Add a child hierarchy to this item group. */
  @Override
  public void addChild(ItemHierarchy child) {
    dirty = true;
    children.add(child);
    child.registerObserver(this);

    final int count = child.getCount();
    if (count > 0) {
      notifyItemRangeInserted(getChildPosition(child), count);
    }
  }

  /**
   * Remove a previously added child from this item group.
   *
   * @return True if there is a match for the child and it is removed. False if the child could not
   *     be found in our list of child hierarchies.
   */
  public boolean removeChild(ItemHierarchy child) {
    final int childIndex = identityIndexOf(children, child);
    final int childPosition = getChildPosition(childIndex);
    dirty = true;
    if (childIndex != -1) {
      final int childCount = child.getCount();
      children.remove(childIndex);
      child.unregisterObserver(this);
      if (childCount > 0) {
        notifyItemRangeRemoved(childPosition, childCount);
      }
      return true;
    }
    return false;
  }

  /** Remove all children from this hierarchy. */
  public void clear() {
    if (children.isEmpty()) {
      return;
    }

    final int numRemoved = getCount();

    for (ItemHierarchy item : children) {
      item.unregisterObserver(this);
    }
    dirty = true;
    children.clear();
    notifyItemRangeRemoved(0, numRemoved);
  }

  @Override
  public int getCount() {
    updateDataIfNeeded();
    return count;
  }

  @Override
  public IItem getItemAt(int position) {
    int itemIndex = getItemIndex(position);
    ItemHierarchy item = children.get(itemIndex);
    int subpos = position - hierarchyStart.get(itemIndex);
    return item.getItemAt(subpos);
  }

  @Override
  public void onChanged(ItemHierarchy hierarchy) {
    // Need to set dirty, because our children may have gotten more items.
    dirty = true;
    notifyChanged();
  }

  /**
   * @return The "Item Position" of the given child, or -1 if the child is not found. If the given
   *     child is empty, position of the next visible item is returned.
   */
  private int getChildPosition(ItemHierarchy child) {
    // Check the identity of the child rather than using .equals(), because here we want
    // to find the index of the instance itself rather than something that equals to it.
    return getChildPosition(identityIndexOf(children, child));
  }

  private int getChildPosition(int childIndex) {
    updateDataIfNeeded();
    if (childIndex != -1) {
      int childPos = -1;
      int childCount = children.size();
      for (int i = childIndex; childPos < 0 && i < childCount; i++) {
        // Find the position of the first visible child after childIndex. This is required
        // when removing the last item from a nested ItemGroup.
        childPos = hierarchyStart.get(i, -1);
      }
      if (childPos < 0) {
        // If the last item in a group is being removed, there will be no visible item.
        // In that case return the count instead, since that is where the item would have
        // been if the child is not empty.
        childPos = getCount();
      }
      return childPos;
    }
    return -1;
  }

  @Override
  public void onItemRangeChanged(ItemHierarchy itemHierarchy, int positionStart, int itemCount) {
    // No need to set dirty because onItemRangeChanged does not include any structural changes.
    final int childPosition = getChildPosition(itemHierarchy);
    if (childPosition >= 0) {
      notifyItemRangeChanged(childPosition + positionStart, itemCount);
    } else {
      Log.e(TAG, "Unexpected child change " + itemHierarchy);
    }
  }

  @Override
  public void onItemRangeInserted(ItemHierarchy itemHierarchy, int positionStart, int itemCount) {
    dirty = true;
    final int childPosition = getChildPosition(itemHierarchy);
    if (childPosition >= 0) {
      notifyItemRangeInserted(childPosition + positionStart, itemCount);
    } else {
      Log.e(TAG, "Unexpected child insert " + itemHierarchy);
    }
  }

  @Override
  public void onItemRangeMoved(
      ItemHierarchy itemHierarchy, int fromPosition, int toPosition, int itemCount) {
    dirty = true;
    final int childPosition = getChildPosition(itemHierarchy);
    if (childPosition >= 0) {
      notifyItemRangeMoved(childPosition + fromPosition, childPosition + toPosition, itemCount);
    } else {
      Log.e(TAG, "Unexpected child move " + itemHierarchy);
    }
  }

  @Override
  public void onItemRangeRemoved(ItemHierarchy itemHierarchy, int positionStart, int itemCount) {
    dirty = true;
    final int childPosition = getChildPosition(itemHierarchy);
    if (childPosition >= 0) {
      notifyItemRangeRemoved(childPosition + positionStart, itemCount);
    } else {
      Log.e(TAG, "Unexpected child remove " + itemHierarchy);
    }
  }

  @Override
  public ItemHierarchy findItemById(int id) {
    if (id == getId()) {
      return this;
    }
    for (ItemHierarchy child : children) {
      ItemHierarchy childFindItem = child.findItemById(id);
      if (childFindItem != null) {
        return childFindItem;
      }
    }
    return null;
  }

  /** If dirty, this method will recalculate the number of items and hierarchyStart. */
  private void updateDataIfNeeded() {
    if (dirty) {
      count = 0;
      hierarchyStart.clear();
      for (int itemIndex = 0; itemIndex < children.size(); itemIndex++) {
        ItemHierarchy item = children.get(itemIndex);
        if (item.getCount() > 0) {
          hierarchyStart.put(itemIndex, count);
        }
        count += item.getCount();
      }
      dirty = false;
    }
  }

  /**
   * Use binary search to locate the item hierarchy a position is contained in.
   *
   * @return Index of the item hierarchy which is responsible for the item at {@code position}.
   */
  private int getItemIndex(int position) {
    updateDataIfNeeded();
    if (position < 0 || position >= count) {
      throw new IndexOutOfBoundsException("size=" + count + "; index=" + position);
    }
    int result = binarySearch(hierarchyStart, position);
    if (result < 0) {
      throw new IllegalStateException("Cannot have item start index < 0");
    }
    return result;
  }
}