aboutsummaryrefslogtreecommitdiff
path: root/shadows/framework/src/main/java/org/robolectric/shadows/ShadowViewRootImpl.java
blob: 744b1c02e3d887290fbbcec5622fac93f0013a65 (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
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
package org.robolectric.shadows;

import static android.os.Build.VERSION_CODES.Q;
import static android.os.Build.VERSION_CODES.R;
import static android.os.Build.VERSION_CODES.S_V2;
import static org.robolectric.annotation.TextLayoutMode.Mode.REALISTIC;
import static org.robolectric.util.reflector.Reflector.reflector;

import android.content.res.Configuration;
import android.graphics.Rect;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.Looper;
import android.os.RemoteException;
import android.util.MergedConfiguration;
import android.view.Display;
import android.view.HandlerActionQueue;
import android.view.IWindowSession;
import android.view.InsetsState;
import android.view.Surface;
import android.view.SurfaceControl;
import android.view.View;
import android.view.ViewRootImpl;
import android.view.WindowInsets;
import android.view.WindowManager;
import android.window.ClientWindowFrames;
import java.util.ArrayList;
import java.util.Optional;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.RealObject;
import org.robolectric.annotation.Resetter;
import org.robolectric.annotation.TextLayoutMode;
import org.robolectric.config.ConfigurationRegistry;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.util.ReflectionHelpers;
import org.robolectric.util.ReflectionHelpers.ClassParameter;
import org.robolectric.util.reflector.Accessor;
import org.robolectric.util.reflector.Direct;
import org.robolectric.util.reflector.ForType;
import org.robolectric.util.reflector.Static;
import org.robolectric.util.reflector.WithType;

@Implements(value = ViewRootImpl.class, isInAndroidSdk = false)
public class ShadowViewRootImpl {

  private static final int RELAYOUT_RES_IN_TOUCH_MODE = 0x1;

  @RealObject protected ViewRootImpl realObject;

  /**
   * The visibility of the system status bar.
   *
   * <p>The value will be read in the intercepted {@link #getWindowInsets(boolean)} method providing
   * the current state via the returned {@link WindowInsets} instance if it has been set..
   *
   * <p>NOTE: This state does not reflect the current state of system UI visibility flags or the
   * current window insets. Rather it tracks the latest known state provided via {@link
   * #setIsStatusBarVisible(boolean)}.
   */
  private static Optional<Boolean> isStatusBarVisible = Optional.empty();

  /**
   * The visibility of the system navigation bar.
   *
   * <p>The value will be read in the intercepted {@link #getWindowInsets(boolean)} method providing
   * the current state via the returned {@link WindowInsets} instance if it has been set.
   *
   * <p>NOTE: This state does not reflect the current state of system UI visibility flags or the
   * current window insets. Rather it tracks the latest known state provided via {@link
   * #setIsNavigationBarVisible(boolean)}.
   */
  private static Optional<Boolean> isNavigationBarVisible = Optional.empty();

  /** Allows other shadows to set the state of {@link #isStatusBarVisible}. */
  protected static void setIsStatusBarVisible(boolean isStatusBarVisible) {
    ShadowViewRootImpl.isStatusBarVisible = Optional.of(isStatusBarVisible);
  }

  /** Clears the last known state of {@link #isStatusBarVisible}. */
  protected static void clearIsStatusBarVisible() {
    ShadowViewRootImpl.isStatusBarVisible = Optional.empty();
  }

  /** Allows other shadows to set the state of {@link #isNavigationBarVisible}. */
  protected static void setIsNavigationBarVisible(boolean isNavigationBarVisible) {
    ShadowViewRootImpl.isNavigationBarVisible = Optional.of(isNavigationBarVisible);
  }

  /** Clears the last known state of {@link #isNavigationBarVisible}. */
  protected static void clearIsNavigationBarVisible() {
    ShadowViewRootImpl.isNavigationBarVisible = Optional.empty();
  }

  @Implementation(maxSdk = VERSION_CODES.JELLY_BEAN)
  protected static IWindowSession getWindowSession(Looper mainLooper) {
    IWindowSession windowSession = ShadowWindowManagerGlobal.getWindowSession();
    ReflectionHelpers.setStaticField(ViewRootImpl.class, "sWindowSession", windowSession);
    return windowSession;
  }

  @Implementation
  public void playSoundEffect(int effectId) {}

  @Implementation
  protected int relayoutWindow(
      WindowManager.LayoutParams params, int viewVisibility, boolean insetsPending)
      throws RemoteException {
    // TODO(christianw): probably should return WindowManagerGlobal.RELAYOUT_RES_SURFACE_RESIZED?
    int result = 0;
    if (ShadowWindowManagerGlobal.getInTouchMode() && RuntimeEnvironment.getApiLevel() <= S_V2) {
      result |= RELAYOUT_RES_IN_TOUCH_MODE;
    }
    if (RuntimeEnvironment.getApiLevel() >= Q) {
      // Simulate initializing the SurfaceControl member object, which happens during this method.
      SurfaceControl surfaceControl =
          reflector(ViewRootImplReflector.class, realObject).getSurfaceControl();
      ShadowSurfaceControl shadowSurfaceControl = Shadow.extract(surfaceControl);
      shadowSurfaceControl.initializeNativeObject();
    }
    return result;
  }

  public void callDispatchResized() {
    if (RuntimeEnvironment.getApiLevel() > VERSION_CODES.TIRAMISU) {
      Display display = getDisplay();
      Rect frame = new Rect();
      display.getRectSize(frame);

      ClientWindowFrames frames = new ClientWindowFrames();
      // set the final field
      ReflectionHelpers.setField(frames, "frame", frame);

      ReflectionHelpers.callInstanceMethod(
          ViewRootImpl.class,
          realObject,
          "dispatchResized",
          ClassParameter.from(ClientWindowFrames.class, frames),
          ClassParameter.from(boolean.class, true), /* reportDraw */
          ClassParameter.from(
              MergedConfiguration.class, new MergedConfiguration()), /* mergedConfiguration */
          ClassParameter.from(InsetsState.class, new InsetsState()), /* insetsState */
          ClassParameter.from(boolean.class, false), /* forceLayout */
          ClassParameter.from(boolean.class, false), /* alwaysConsumeSystemBars */
          ClassParameter.from(int.class, 0), /* displayId */
          ClassParameter.from(int.class, 0), /* syncSeqId */
          ClassParameter.from(boolean.class, false) /* dragResizing */);
    } else if (RuntimeEnvironment.getApiLevel() > Build.VERSION_CODES.S_V2) {
      Display display = getDisplay();
      Rect frame = new Rect();
      display.getRectSize(frame);

      ClientWindowFrames frames = new ClientWindowFrames();
      // set the final field
      ReflectionHelpers.setField(frames, "frame", frame);

      ReflectionHelpers.callInstanceMethod(
          ViewRootImpl.class,
          realObject,
          "dispatchResized",
          ClassParameter.from(ClientWindowFrames.class, frames),
          ClassParameter.from(boolean.class, true), /* reportDraw */
          ClassParameter.from(
              MergedConfiguration.class, new MergedConfiguration()), /* mergedConfiguration */
          ClassParameter.from(InsetsState.class, new InsetsState()), /* insetsState */
          ClassParameter.from(boolean.class, false), /* forceLayout */
          ClassParameter.from(boolean.class, false), /* alwaysConsumeSystemBars */
          ClassParameter.from(int.class, 0), /* displayId */
          ClassParameter.from(int.class, 0), /* syncSeqId */
          ClassParameter.from(int.class, 0) /* resizeMode */);
    } else if (RuntimeEnvironment.getApiLevel() > Build.VERSION_CODES.R) {
      Display display = getDisplay();
      Rect frame = new Rect();
      display.getRectSize(frame);

      ClientWindowFrames frames = new ClientWindowFrames();
      // set the final field
      ReflectionHelpers.setField(frames, "frame", frame);

      ReflectionHelpers.callInstanceMethod(
          ViewRootImpl.class,
          realObject,
          "dispatchResized",
          ClassParameter.from(ClientWindowFrames.class, frames),
          ClassParameter.from(boolean.class, true), /* reportDraw */
          ClassParameter.from(
              MergedConfiguration.class, new MergedConfiguration()), /* mergedConfiguration */
          ClassParameter.from(boolean.class, false), /* forceLayout */
          ClassParameter.from(boolean.class, false), /* alwaysConsumeSystemBars */
          ClassParameter.from(int.class, 0) /* displayId */);
    } else if (RuntimeEnvironment.getApiLevel() > Build.VERSION_CODES.Q) {
      Display display = getDisplay();
      Rect frame = new Rect();
      display.getRectSize(frame);

      Rect emptyRect = new Rect(0, 0, 0, 0);
      ReflectionHelpers.callInstanceMethod(
          ViewRootImpl.class,
          realObject,
          "dispatchResized",
          ClassParameter.from(Rect.class, frame),
          ClassParameter.from(Rect.class, emptyRect),
          ClassParameter.from(Rect.class, emptyRect),
          ClassParameter.from(Rect.class, emptyRect),
          ClassParameter.from(boolean.class, true),
          ClassParameter.from(MergedConfiguration.class, new MergedConfiguration()),
          ClassParameter.from(Rect.class, frame),
          ClassParameter.from(boolean.class, false),
          ClassParameter.from(boolean.class, false),
          ClassParameter.from(int.class, 0),
          ClassParameter.from(
              android.view.DisplayCutout.ParcelableWrapper.class,
              new android.view.DisplayCutout.ParcelableWrapper()));
    } else {
      Display display = getDisplay();
      Rect frame = new Rect();
      display.getRectSize(frame);
      reflector(ViewRootImplReflector.class, realObject).dispatchResized(frame);
    }
  }

  protected Display getDisplay() {
    return reflector(ViewRootImplReflector.class, realObject).getDisplay();
  }

  @Implementation
  protected void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
    reflector(ViewRootImplReflector.class, realObject).setView(view, attrs, panelParentView);
    if (ConfigurationRegistry.get(TextLayoutMode.Mode.class) == REALISTIC) {
      Rect winFrame = new Rect();
      getDisplay().getRectSize(winFrame);
      reflector(ViewRootImplReflector.class, realObject).setWinFrame(winFrame);
    }
  }

  @Implementation(minSdk = R)
  protected void setView(
      View view, WindowManager.LayoutParams attrs, View panelParentView, int userId) {
    reflector(ViewRootImplReflector.class, realObject)
        .setView(view, attrs, panelParentView, userId);
    if (ConfigurationRegistry.get(TextLayoutMode.Mode.class) == REALISTIC) {
      Rect winFrame = new Rect();
      getDisplay().getRectSize(winFrame);
      reflector(ViewRootImplReflector.class, realObject).setWinFrame(winFrame);
    }
  }

  /**
   * On Android R+ {@link WindowInsets} supports checking visibility of specific inset types.
   *
   * <p>For those SDK levels, override the real {@link WindowInsets} with the tracked system bar
   * visibility status ({@link #isStatusBarVisible}/{@link #isNavigationBarVisible}), if set.
   *
   * <p>NOTE: We use state tracking in place of a longer term solution of implementing the insets
   * calculations and broadcast (via listeners) for now. Once we have insets calculations working we
   * should remove this mechanism.
   */
  @Implementation(minSdk = R)
  protected WindowInsets getWindowInsets(boolean forceConstruct) {
    WindowInsets realInsets =
        reflector(ViewRootImplReflector.class, realObject).getWindowInsets(forceConstruct);

    WindowInsets.Builder overridenInsetsBuilder = new WindowInsets.Builder(realInsets);

    if (isStatusBarVisible.isPresent()) {
      overridenInsetsBuilder =
          overridenInsetsBuilder.setVisible(
              WindowInsets.Type.statusBars(), isStatusBarVisible.get());
    }

    if (isNavigationBarVisible.isPresent()) {
      overridenInsetsBuilder =
          overridenInsetsBuilder.setVisible(
              WindowInsets.Type.navigationBars(), isNavigationBarVisible.get());
    }

    return overridenInsetsBuilder.build();
  }

  @Resetter
  public static void reset() {
    ViewRootImplReflector viewRootImplStatic = reflector(ViewRootImplReflector.class);
    viewRootImplStatic.setRunQueues(new ThreadLocal<>());
    viewRootImplStatic.setFirstDrawHandlers(new ArrayList<>());
    viewRootImplStatic.setFirstDrawComplete(false);
    viewRootImplStatic.setConfigCallbacks(new ArrayList<>());

    clearIsStatusBarVisible();
    clearIsNavigationBarVisible();
  }

  public void callWindowFocusChanged(boolean hasFocus) {
    if (RuntimeEnvironment.getApiLevel() <= S_V2) {
      reflector(ViewRootImplReflector.class, realObject)
          .windowFocusChanged(hasFocus, ShadowWindowManagerGlobal.getInTouchMode());
    } else {
      reflector(ViewRootImplReflector.class, realObject).windowFocusChanged(hasFocus);
    }
  }

  Surface getSurface() {
    return reflector(ViewRootImplReflector.class, realObject).getSurface();
  }

  /** Reflector interface for {@link ViewRootImpl}'s internals. */
  @ForType(ViewRootImpl.class)
  protected interface ViewRootImplReflector {

    @Direct
    void setView(View view, WindowManager.LayoutParams attrs, View panelParentView);

    @Direct
    void setView(View view, WindowManager.LayoutParams attrs, View panelParentView, int userId);

    @Static
    @Accessor("sRunQueues")
    void setRunQueues(ThreadLocal<HandlerActionQueue> threadLocal);

    @Static
    @Accessor("sFirstDrawHandlers")
    void setFirstDrawHandlers(ArrayList<Runnable> handlers);

    @Static
    @Accessor("sFirstDrawComplete")
    void setFirstDrawComplete(boolean isComplete);

    @Static
    @Accessor("sConfigCallbacks")
    void setConfigCallbacks(ArrayList<ViewRootImpl.ConfigChangedCallback> callbacks);

    @Accessor("sNewInsetsMode")
    @Static
    int getNewInsetsMode();

    @Accessor("mWinFrame")
    void setWinFrame(Rect winFrame);

    @Accessor("mDisplay")
    Display getDisplay();

    @Accessor("mSurfaceControl")
    SurfaceControl getSurfaceControl();

    @Accessor("mSurface")
    Surface getSurface();

    @Accessor("mWindowAttributes")
    WindowManager.LayoutParams getWindowAttributes();

    // == KITKAT
    void dispatchResized(
        Rect frame,
        Rect overscanInsets,
        Rect contentInsets,
        Rect visibleInsets,
        boolean reportDraw,
        Configuration newConfig);

    // <= LOLLIPOP_MR1
    void dispatchResized(
        Rect frame,
        Rect overscanInsets,
        Rect contentInsets,
        Rect visibleInsets,
        Rect stableInsets,
        boolean reportDraw,
        Configuration newConfig);

    // <= M
    void dispatchResized(
        Rect frame,
        Rect overscanInsets,
        Rect contentInsets,
        Rect visibleInsets,
        Rect stableInsets,
        Rect outsets,
        boolean reportDraw,
        Configuration newConfig);

    // <= N_MR1
    void dispatchResized(
        Rect frame,
        Rect overscanInsets,
        Rect contentInsets,
        Rect visibleInsets,
        Rect stableInsets,
        Rect outsets,
        boolean reportDraw,
        Configuration newConfig,
        Rect backDropFrame,
        boolean forceLayout,
        boolean alwaysConsumeNavBar);

    // <= O_MR1
    void dispatchResized(
        Rect frame,
        Rect overscanInsets,
        Rect contentInsets,
        Rect visibleInsets,
        Rect stableInsets,
        Rect outsets,
        boolean reportDraw,
        @WithType("android.util.MergedConfiguration") Object mergedConfiguration,
        Rect backDropFrame,
        boolean forceLayout,
        boolean alwaysConsumeNavBar,
        int displayId);

    // >= P
    void dispatchResized(
        Rect frame,
        Rect overscanInsets,
        Rect contentInsets,
        Rect visibleInsets,
        Rect stableInsets,
        Rect outsets,
        boolean reportDraw,
        @WithType("android.util.MergedConfiguration") Object mergedConfiguration,
        Rect backDropFrame,
        boolean forceLayout,
        boolean alwaysConsumeNavBar,
        int displayId,
        @WithType("android.view.DisplayCutout$ParcelableWrapper") Object displayCutout);

    default void dispatchResized(Rect frame) {
      Rect emptyRect = new Rect(0, 0, 0, 0);

      int apiLevel = RuntimeEnvironment.getApiLevel();
      if (apiLevel == Build.VERSION_CODES.KITKAT) {
        dispatchResized(frame, emptyRect, emptyRect, emptyRect, true, null);
      } else if (apiLevel <= Build.VERSION_CODES.LOLLIPOP_MR1) {
        dispatchResized(frame, emptyRect, emptyRect, emptyRect, emptyRect, true, null);
      } else if (apiLevel <= Build.VERSION_CODES.M) {
        dispatchResized(frame, emptyRect, emptyRect, emptyRect, emptyRect, emptyRect, true, null);
      } else if (apiLevel <= Build.VERSION_CODES.N_MR1) {
        dispatchResized(
            frame, emptyRect, emptyRect, emptyRect, emptyRect, emptyRect, true, null, frame, false,
            false);
      } else if (apiLevel <= Build.VERSION_CODES.O_MR1) {
        dispatchResized(
            frame,
            emptyRect,
            emptyRect,
            emptyRect,
            emptyRect,
            emptyRect,
            true,
            new MergedConfiguration(),
            frame,
            false,
            false,
            0);
      } else { // apiLevel >= Build.VERSION_CODES.P
        dispatchResized(
            frame,
            emptyRect,
            emptyRect,
            emptyRect,
            emptyRect,
            emptyRect,
            true,
            new MergedConfiguration(),
            frame,
            false,
            false,
            0,
            new android.view.DisplayCutout.ParcelableWrapper());
      }
    }

    // SDK <= S_V2
    void windowFocusChanged(boolean hasFocus, boolean inTouchMode);

    // SDK >= T
    void windowFocusChanged(boolean hasFocus);

    // SDK >= M
    @Direct
    WindowInsets getWindowInsets(boolean forceConstruct);
  }
}