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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
|
/*
* Copyright (C) 2020 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 android.view;
import android.annotation.AnyThread;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.UiThread;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Log;
import com.android.internal.annotations.VisibleForTesting;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
/**
* Queries additional state from a list of {@link ScrollCaptureTarget targets} via asynchronous
* callbacks, then aggregates and reduces the target list to a single target, or null if no target
* is suitable.
* <p>
* The rules for selection are (in order):
* <ul>
* <li>prefer getScrollBounds(): non-empty
* <li>prefer View.getScrollCaptureHint == SCROLL_CAPTURE_HINT_INCLUDE
* <li>prefer descendants before parents
* <li>prefer larger area for getScrollBounds() (clipped to view bounds)
* </ul>
*
* <p>
* All calls to {@link ScrollCaptureCallback#onScrollCaptureSearch} are made on the main thread,
* with results are queued and consumed to the main thread as well.
*
* @see #start(Handler, long, Consumer)
*
* @hide
*/
@UiThread
public class ScrollCaptureTargetResolver {
private static final String TAG = "ScrollCaptureTargetRes";
private static final boolean DEBUG = true;
private final Object mLock = new Object();
private final Queue<ScrollCaptureTarget> mTargets;
private Handler mHandler;
private long mTimeLimitMillis;
private Consumer<ScrollCaptureTarget> mWhenComplete;
private int mPendingBoundsRequests;
private long mDeadlineMillis;
private ScrollCaptureTarget mResult;
private boolean mFinished;
private boolean mStarted;
private static int area(Rect r) {
return r.width() * r.height();
}
private static boolean nullOrEmpty(Rect r) {
return r == null || r.isEmpty();
}
/**
* Binary operator which selects the best {@link ScrollCaptureTarget}.
*/
private static ScrollCaptureTarget chooseTarget(ScrollCaptureTarget a, ScrollCaptureTarget b) {
Log.d(TAG, "chooseTarget: " + a + " or " + b);
// Nothing plus nothing is still nothing.
if (a == null && b == null) {
Log.d(TAG, "chooseTarget: (both null) return " + null);
return null;
}
// Prefer non-null.
if (a == null || b == null) {
ScrollCaptureTarget c = (a == null) ? b : a;
Log.d(TAG, "chooseTarget: (other is null) return " + c);
return c;
}
boolean emptyScrollBoundsA = nullOrEmpty(a.getScrollBounds());
boolean emptyScrollBoundsB = nullOrEmpty(b.getScrollBounds());
if (emptyScrollBoundsA || emptyScrollBoundsB) {
if (emptyScrollBoundsA && emptyScrollBoundsB) {
// Both have an empty or null scrollBounds
Log.d(TAG, "chooseTarget: (both have empty or null bounds) return " + null);
return null;
}
// Prefer the one with a non-empty scroll bounds
if (emptyScrollBoundsA) {
Log.d(TAG, "chooseTarget: (a has empty or null bounds) return " + b);
return b;
}
Log.d(TAG, "chooseTarget: (b has empty or null bounds) return " + a);
return a;
}
final View viewA = a.getContainingView();
final View viewB = b.getContainingView();
// Prefer any view with scrollCaptureHint="INCLUDE", over one without
// This is an escape hatch for the next rule (descendants first)
boolean hintIncludeA = hasIncludeHint(viewA);
boolean hintIncludeB = hasIncludeHint(viewB);
if (hintIncludeA != hintIncludeB) {
ScrollCaptureTarget c = (hintIncludeA) ? a : b;
Log.d(TAG, "chooseTarget: (has hint=INCLUDE) return " + c);
return c;
}
// If the views are relatives, prefer the descendant. This allows implementations to
// leverage nested scrolling APIs by interacting with the innermost scrollable view (as
// would happen with touch input).
if (isDescendant(viewA, viewB)) {
Log.d(TAG, "chooseTarget: (b is descendant of a) return " + b);
return b;
}
if (isDescendant(viewB, viewA)) {
Log.d(TAG, "chooseTarget: (a is descendant of b) return " + a);
return a;
}
// finally, prefer one with larger scroll bounds
int scrollAreaA = area(a.getScrollBounds());
int scrollAreaB = area(b.getScrollBounds());
ScrollCaptureTarget c = (scrollAreaA >= scrollAreaB) ? a : b;
Log.d(TAG, "chooseTarget: return " + c);
return c;
}
/**
* Creates an instance to query and filter {@code target}.
*
* @param targets a list of {@link ScrollCaptureTarget} as collected by {@link
* View#dispatchScrollCaptureSearch}.
* @param uiHandler the UI thread handler for the view tree
* @see #start(long, Consumer)
*/
public ScrollCaptureTargetResolver(Queue<ScrollCaptureTarget> targets) {
mTargets = targets;
}
void checkThread() {
if (mHandler.getLooper() != Looper.myLooper()) {
throw new IllegalStateException("Called from wrong thread! ("
+ Thread.currentThread().getName() + ")");
}
}
/**
* Blocks until a result is returned (after completion or timeout).
* <p>
* For testing only. Normal usage should receive a callback after calling {@link #start}.
*/
@VisibleForTesting
public ScrollCaptureTarget waitForResult() throws InterruptedException {
synchronized (mLock) {
while (!mFinished) {
mLock.wait();
}
}
return mResult;
}
private void supplyResult(ScrollCaptureTarget target) {
checkThread();
if (mFinished) {
return;
}
mResult = chooseTarget(mResult, target);
boolean finish = mPendingBoundsRequests == 0
|| SystemClock.elapsedRealtime() >= mDeadlineMillis;
if (finish) {
System.err.println("We think we're done, or timed out");
mPendingBoundsRequests = 0;
mWhenComplete.accept(mResult);
synchronized (mLock) {
mFinished = true;
mLock.notify();
}
mWhenComplete = null;
}
}
/**
* Asks all targets for {@link ScrollCaptureCallback#onScrollCaptureSearch(Consumer)
* scrollBounds}, and selects the primary target according to the {@link
* #chooseTarget} function.
*
* @param timeLimitMillis the amount of time to wait for all responses before delivering the top
* result
* @param resultConsumer the consumer to receive the primary target
*/
@AnyThread
public void start(Handler uiHandler, long timeLimitMillis,
Consumer<ScrollCaptureTarget> resultConsumer) {
synchronized (mLock) {
if (mStarted) {
throw new IllegalStateException("already started!");
}
if (timeLimitMillis < 0) {
throw new IllegalArgumentException("Time limit must be positive");
}
mHandler = uiHandler;
mTimeLimitMillis = timeLimitMillis;
mWhenComplete = resultConsumer;
if (mTargets.isEmpty()) {
mHandler.post(() -> supplyResult(null));
return;
}
mStarted = true;
uiHandler.post(() -> run(timeLimitMillis, resultConsumer));
}
}
private void run(long timeLimitMillis, Consumer<ScrollCaptureTarget> resultConsumer) {
checkThread();
mPendingBoundsRequests = mTargets.size();
for (ScrollCaptureTarget target : mTargets) {
queryTarget(target);
}
mDeadlineMillis = SystemClock.elapsedRealtime() + mTimeLimitMillis;
mHandler.postAtTime(mTimeoutRunnable, mDeadlineMillis);
}
private final Runnable mTimeoutRunnable = new Runnable() {
@Override
public void run() {
checkThread();
supplyResult(null);
}
};
/**
* Adds a target to the list and requests {@link ScrollCaptureCallback#onScrollCaptureSearch}
* scrollBounds} from it. Results are returned by a call to {@link #onScrollBoundsProvided}.
*
* @param target the target to add
*/
@UiThread
private void queryTarget(@NonNull ScrollCaptureTarget target) {
checkThread();
final ScrollCaptureCallback callback = target.getCallback();
// from the UI thread, request scroll bounds
callback.onScrollCaptureSearch(
// allow only one callback to onReady.accept():
new SingletonConsumer<Rect>(
// Queue and consume on the UI thread
((scrollBounds) -> mHandler.post(
() -> onScrollBoundsProvided(target, scrollBounds)))));
}
@UiThread
private void onScrollBoundsProvided(ScrollCaptureTarget target, @Nullable Rect scrollBounds) {
checkThread();
if (mFinished) {
return;
}
// Record progress.
mPendingBoundsRequests--;
// Remove the timeout.
mHandler.removeCallbacks(mTimeoutRunnable);
boolean doneOrTimedOut = mPendingBoundsRequests == 0
|| SystemClock.elapsedRealtime() >= mDeadlineMillis;
final View containingView = target.getContainingView();
if (!nullOrEmpty(scrollBounds) && containingView.isAggregatedVisible()) {
target.updatePositionInWindow();
target.setScrollBounds(scrollBounds);
supplyResult(target);
}
System.err.println("mPendingBoundsRequests: " + mPendingBoundsRequests);
System.err.println("mDeadlineMillis: " + mDeadlineMillis);
System.err.println("SystemClock.elapsedRealtime(): " + SystemClock.elapsedRealtime());
if (!mFinished) {
// Reschedule the timeout.
System.err.println(
"We think we're NOT done yet and will check back at " + mDeadlineMillis);
mHandler.postAtTime(mTimeoutRunnable, mDeadlineMillis);
}
}
private static boolean hasIncludeHint(View view) {
return (view.getScrollCaptureHint() & View.SCROLL_CAPTURE_HINT_INCLUDE) != 0;
}
/**
* Determines if {@code otherView} is a descendant of {@code view}.
*
* @param view a view
* @param otherView another view
* @return true if {@code view} is an ancestor of {@code otherView}
*/
private static boolean isDescendant(@NonNull View view, @NonNull View otherView) {
if (view == otherView) {
return false;
}
ViewParent otherParent = otherView.getParent();
while (otherParent != view && otherParent != null) {
otherParent = otherParent.getParent();
}
return otherParent == view;
}
private static int findRelation(@NonNull View a, @NonNull View b) {
if (a == b) {
return 0;
}
ViewParent parentA = a.getParent();
ViewParent parentB = b.getParent();
while (parentA != null || parentB != null) {
if (parentA == parentB) {
return 0;
}
if (parentA == b) {
return 1; // A is descendant of B
}
if (parentB == a) {
return -1; // B is descendant of A
}
if (parentA != null) {
parentA = parentA.getParent();
}
if (parentB != null) {
parentB = parentB.getParent();
}
}
return 0;
}
/**
* A safe wrapper for a consumer callbacks intended to accept a single value. It ensures
* that the receiver of the consumer does not retain a reference to {@code target} after use nor
* cause race conditions by invoking {@link Consumer#accept accept} more than once.
*
* @param target the target consumer
*/
static class SingletonConsumer<T> implements Consumer<T> {
final AtomicReference<Consumer<T>> mAtomicRef;
SingletonConsumer(Consumer<T> target) {
mAtomicRef = new AtomicReference<>(target);
}
@Override
public void accept(T t) {
final Consumer<T> consumer = mAtomicRef.getAndSet(null);
if (consumer != null) {
consumer.accept(t);
}
}
}
}
|