aboutsummaryrefslogtreecommitdiff
path: root/shadows/framework/src/main/java/org/robolectric/shadows/ShadowView.java
blob: 848502e602cb4238c0dc4bd19dadf0f100318686 (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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
package org.robolectric.shadows;

import static android.os.Build.VERSION_CODES.KITKAT;
import static android.os.Build.VERSION_CODES.KITKAT_WATCH;
import static android.os.Build.VERSION_CODES.N;
import static android.os.Build.VERSION_CODES.O;
import static android.os.Build.VERSION_CODES.Q;
import static android.os.Build.VERSION_CODES.R;
import static org.robolectric.shadows.ShadowLooper.shadowMainLooper;
import static org.robolectric.util.ReflectionHelpers.getField;
import static org.robolectric.util.reflector.Reflector.reflector;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Looper;
import android.os.RemoteException;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Choreographer;
import android.view.IWindowFocusObserver;
import android.view.IWindowId;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewParent;
import android.view.WindowId;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import com.google.common.annotations.Beta;
import com.google.common.collect.ImmutableList;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.GraphicsMode;
import org.robolectric.annotation.GraphicsMode.Mode;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.LooperMode;
import org.robolectric.annotation.RealObject;
import org.robolectric.annotation.ReflectorObject;
import org.robolectric.annotation.Resetter;
import org.robolectric.config.ConfigurationRegistry;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.shadows.ShadowViewRootImpl.ViewRootImplReflector;
import org.robolectric.util.TimeUtils;
import org.robolectric.util.reflector.Accessor;
import org.robolectric.util.reflector.Direct;
import org.robolectric.util.reflector.ForType;

@Implements(View.class)
@SuppressLint("NewApi")
public class ShadowView {

  @RealObject protected View realView;
  @ReflectorObject protected _View_ viewReflector;
  private static final List<View.OnClickListener> globalClickListeners =
      new CopyOnWriteArrayList<>();
  private static final List<View.OnLongClickListener> globalLongClickListeners =
      new CopyOnWriteArrayList<>();
  private View.OnClickListener onClickListener;
  private View.OnLongClickListener onLongClickListener;
  private View.OnFocusChangeListener onFocusChangeListener;
  private View.OnSystemUiVisibilityChangeListener onSystemUiVisibilityChangeListener;
  private final HashSet<View.OnAttachStateChangeListener> onAttachStateChangeListeners =
      new HashSet<>();
  private final HashSet<View.OnLayoutChangeListener> onLayoutChangeListeners = new HashSet<>();
  private boolean wasInvalidated;
  private View.OnTouchListener onTouchListener;
  protected AttributeSet attributeSet;
  public Point scrollToCoordinates = new Point();
  private boolean didRequestLayout;
  private MotionEvent lastTouchEvent;
  private int hapticFeedbackPerformed = -1;
  private boolean onLayoutWasCalled;
  private View.OnCreateContextMenuListener onCreateContextMenuListener;
  private Rect globalVisibleRect;
  private int layerType;
  private final ArrayList<Animation> animations = new ArrayList<>();
  private AnimationRunner animationRunner;

  /**
   * Calls {@code performClick()} on a {@code View} after ensuring that it and its ancestors are
   * visible and that it is enabled.
   *
   * @param view the view to click on
   * @return true if {@code View.OnClickListener}s were found and fired, false otherwise.
   * @throws RuntimeException if the preconditions are not met.
   * @deprecated Please use Espresso for view interactions
   */
  @Deprecated
  public static boolean clickOn(View view) {
    ShadowView shadowView = Shadow.extract(view);
    return shadowView.checkedPerformClick();
  }

  /**
   * Returns a textual representation of the appearance of the object.
   *
   * @param view the view to visualize
   * @return Textual representation of the appearance of the object.
   */
  public static String visualize(View view) {
    Canvas canvas = new Canvas();
    view.draw(canvas);
    if (!useRealGraphics()) {
      ShadowCanvas shadowCanvas = Shadow.extract(canvas);
      return shadowCanvas.getDescription();
    } else {
      return "";
    }
  }

  /**
   * Emits an xml-like representation of the view to System.out.
   *
   * @param view the view to dump.
   * @deprecated - Please use {@link androidx.test.espresso.util.HumanReadables#describe(View)}
   */
  @SuppressWarnings("UnusedDeclaration")
  @Deprecated
  public static void dump(View view) {
    ShadowView shadowView = Shadow.extract(view);
    shadowView.dump();
  }

  /**
   * Returns the text contained within this view.
   *
   * @param view the view to scan for text
   * @return Text contained within this view.
   */
  @SuppressWarnings("UnusedDeclaration")
  public static String innerText(View view) {
    ShadowView shadowView = Shadow.extract(view);
    return shadowView.innerText();
  }

  static int[] getLocationInSurfaceCompat(View view) {
    int[] locationInSurface = new int[2];
    if (RuntimeEnvironment.getApiLevel() >= Build.VERSION_CODES.Q) {
      view.getLocationInSurface(locationInSurface);
    } else {
      view.getLocationInWindow(locationInSurface);
      Rect surfaceInsets =
          reflector(ViewRootImplReflector.class, view.getViewRootImpl())
              .getWindowAttributes()
              .surfaceInsets;
      locationInSurface[0] += surfaceInsets.left;
      locationInSurface[1] += surfaceInsets.top;
    }
    return locationInSurface;
  }

  // Only override up to kitkat, while this version exists after kitkat it just calls through to the
  // __constructor__(Context, AttributeSet, int, int) variant below.
  @Implementation(maxSdk = KITKAT)
  protected void __constructor__(Context context, AttributeSet attributeSet, int defStyle) {
    this.attributeSet = attributeSet;
    reflector(_View_.class, realView).__constructor__(context, attributeSet, defStyle);
  }

  /* Note: maxSdk is R because capturing `attributeSet` is not needed any more after R. */
  @Implementation(minSdk = KITKAT_WATCH, maxSdk = R)
  protected void __constructor__(
      Context context, AttributeSet attributeSet, int defStyleAttr, int defStyleRes) {
    this.attributeSet = attributeSet;
    reflector(_View_.class, realView)
        .__constructor__(context, attributeSet, defStyleAttr, defStyleRes);
  }

  @Implementation
  protected void setLayerType(int layerType, Paint paint) {
    this.layerType = layerType;
    reflector(_View_.class, realView).setLayerType(layerType, paint);
  }

  @Implementation
  protected void setOnFocusChangeListener(View.OnFocusChangeListener l) {
    onFocusChangeListener = l;
    reflector(_View_.class, realView).setOnFocusChangeListener(l);
  }

  @Implementation
  protected void setOnClickListener(View.OnClickListener onClickListener) {
    this.onClickListener = onClickListener;
    reflector(_View_.class, realView).setOnClickListener(onClickListener);
  }

  @Implementation
  protected void setOnLongClickListener(View.OnLongClickListener onLongClickListener) {
    this.onLongClickListener = onLongClickListener;
    reflector(_View_.class, realView).setOnLongClickListener(onLongClickListener);
  }

  @Implementation
  protected void setOnSystemUiVisibilityChangeListener(
      View.OnSystemUiVisibilityChangeListener onSystemUiVisibilityChangeListener) {
    this.onSystemUiVisibilityChangeListener = onSystemUiVisibilityChangeListener;
    reflector(_View_.class, realView)
        .setOnSystemUiVisibilityChangeListener(onSystemUiVisibilityChangeListener);
  }

  @Implementation
  protected void setOnCreateContextMenuListener(
      View.OnCreateContextMenuListener onCreateContextMenuListener) {
    this.onCreateContextMenuListener = onCreateContextMenuListener;
    reflector(_View_.class, realView).setOnCreateContextMenuListener(onCreateContextMenuListener);
  }

  @Implementation
  protected void addOnAttachStateChangeListener(
      View.OnAttachStateChangeListener onAttachStateChangeListener) {
    onAttachStateChangeListeners.add(onAttachStateChangeListener);
    reflector(_View_.class, realView).addOnAttachStateChangeListener(onAttachStateChangeListener);
  }

  @Implementation
  protected void removeOnAttachStateChangeListener(
      View.OnAttachStateChangeListener onAttachStateChangeListener) {
    onAttachStateChangeListeners.remove(onAttachStateChangeListener);
    reflector(_View_.class, realView)
        .removeOnAttachStateChangeListener(onAttachStateChangeListener);
  }

  @Implementation
  protected void addOnLayoutChangeListener(View.OnLayoutChangeListener onLayoutChangeListener) {
    onLayoutChangeListeners.add(onLayoutChangeListener);
    reflector(_View_.class, realView).addOnLayoutChangeListener(onLayoutChangeListener);
  }

  @Implementation
  protected void removeOnLayoutChangeListener(View.OnLayoutChangeListener onLayoutChangeListener) {
    onLayoutChangeListeners.remove(onLayoutChangeListener);
    reflector(_View_.class, realView).removeOnLayoutChangeListener(onLayoutChangeListener);
  }

  @Implementation
  protected void draw(Canvas canvas) {
    Drawable background = realView.getBackground();
    if (background != null && !useRealGraphics()) {
      Object shadowCanvas = Shadow.extract(canvas);
      // Check that Canvas is not a Mockito mock
      if (shadowCanvas instanceof ShadowCanvas) {
        ((ShadowCanvas) shadowCanvas).appendDescription("background:");
      }
    }
    reflector(_View_.class, realView).draw(canvas);
  }

  @Implementation
  protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    onLayoutWasCalled = true;
    reflector(_View_.class, realView).onLayout(changed, left, top, right, bottom);
  }

  public boolean onLayoutWasCalled() {
    return onLayoutWasCalled;
  }

  @Implementation
  protected void requestLayout() {
    didRequestLayout = true;
    reflector(_View_.class, realView).requestLayout();
  }

  @Implementation
  protected boolean performClick() {
    for (View.OnClickListener listener : globalClickListeners) {
      listener.onClick(realView);
    }
    return reflector(_View_.class, realView).performClick();
  }

  /**
   * Registers an {@link View.OnClickListener} to the {@link ShadowView}.
   *
   * @param listener The {@link View.OnClickListener} to be registered.
   */
  public static void addGlobalPerformClickListener(View.OnClickListener listener) {
    ShadowView.globalClickListeners.add(listener);
  }

  /**
   * Removes an {@link View.OnClickListener} from the {@link ShadowView}.
   *
   * @param listener The {@link View.OnClickListener} to be removed.
   */
  public static void removeGlobalPerformClickListener(View.OnClickListener listener) {
    ShadowView.globalClickListeners.remove(listener);
  }

  @Implementation
  protected boolean performLongClick() {
    for (View.OnLongClickListener listener : globalLongClickListeners) {
      listener.onLongClick(realView);
    }
    return reflector(_View_.class, realView).performLongClick();
  }

  /**
   * Registers an {@link View.OnLongClickListener} to the {@link ShadowView}.
   *
   * @param listener The {@link View.OnLongClickListener} to be registered.
   */
  public static void addGlobalPerformLongClickListener(View.OnLongClickListener listener) {
    ShadowView.globalLongClickListeners.add(listener);
  }

  /**
   * Removes an {@link View.OnLongClickListener} from the {@link ShadowView}.
   *
   * @param listener The {@link View.OnLongClickListener} to be removed.
   */
  public static void removeGlobalPerformLongClickListener(View.OnLongClickListener listener) {
    ShadowView.globalLongClickListeners.remove(listener);
  }

  @Resetter
  public static void reset() {
    ShadowView.globalClickListeners.clear();
    ShadowView.globalLongClickListeners.clear();
  }

  public boolean didRequestLayout() {
    return didRequestLayout;
  }

  public void setDidRequestLayout(boolean didRequestLayout) {
    this.didRequestLayout = didRequestLayout;
  }

  public void setViewFocus(boolean hasFocus) {
    if (onFocusChangeListener != null) {
      onFocusChangeListener.onFocusChange(realView, hasFocus);
    }
  }

  @Implementation
  protected void invalidate() {
    wasInvalidated = true;
    reflector(_View_.class, realView).invalidate();
  }

  @Implementation
  protected boolean onTouchEvent(MotionEvent event) {
    lastTouchEvent = event;
    return reflector(_View_.class, realView).onTouchEvent(event);
  }

  @Implementation
  protected void setOnTouchListener(View.OnTouchListener onTouchListener) {
    this.onTouchListener = onTouchListener;
    reflector(_View_.class, realView).setOnTouchListener(onTouchListener);
  }

  public MotionEvent getLastTouchEvent() {
    return lastTouchEvent;
  }

  /**
   * Returns a string representation of this {@code View}. Unless overridden, it will be an empty
   * string.
   *
   * <p>Robolectric extension.
   *
   * @return String representation of this view.
   */
  public String innerText() {
    return "";
  }

  /**
   * Dumps the status of this {@code View} to {@code System.out}
   *
   * @deprecated - Please use {@link androidx.test.espresso.util.HumanReadables#describe(View)}
   */
  @Deprecated
  public void dump() {
    dump(System.out, 0);
  }

  /**
   * Dumps the status of this {@code View} to {@code System.out} at the given indentation level
   *
   * @param out Output stream.
   * @param indent Indentation level.
   * @deprecated - Please use {@link androidx.test.espresso.util.HumanReadables#describe(View)}
   */
  @Deprecated
  public void dump(PrintStream out, int indent) {
    dumpFirstPart(out, indent);
    out.println("/>");
  }

  @Deprecated
  protected void dumpFirstPart(PrintStream out, int indent) {
    dumpIndent(out, indent);

    out.print("<" + realView.getClass().getSimpleName());
    dumpAttributes(out);
  }

  @Deprecated
  protected void dumpAttributes(PrintStream out) {
    if (realView.getId() > 0) {
      dumpAttribute(
          out, "id", realView.getContext().getResources().getResourceName(realView.getId()));
    }

    switch (realView.getVisibility()) {
      case View.VISIBLE:
        break;
      case View.INVISIBLE:
        dumpAttribute(out, "visibility", "INVISIBLE");
        break;
      case View.GONE:
        dumpAttribute(out, "visibility", "GONE");
        break;
    }
  }

  @Deprecated
  protected void dumpAttribute(PrintStream out, String name, String value) {
    out.print(" " + name + "=\"" + (value == null ? null : TextUtils.htmlEncode(value)) + "\"");
  }

  @Deprecated
  protected void dumpIndent(PrintStream out, int indent) {
    for (int i = 0; i < indent; i++) out.print(" ");
  }

  /**
   * @return whether or not {@link #invalidate()} has been called
   */
  public boolean wasInvalidated() {
    return wasInvalidated;
  }

  /** Clears the wasInvalidated flag */
  public void clearWasInvalidated() {
    wasInvalidated = false;
  }

  /**
   * Utility method for clicking on views exposing testing scenarios that are not possible when
   * using the actual app.
   *
   * <p>If running with LooperMode PAUSED will also idle the main Looper.
   *
   * @throws RuntimeException if the view is disabled or if the view or any of its parents are not
   *     visible.
   * @return Return value of the underlying click operation.
   * @deprecated - Please use Espresso for View interactions.
   */
  @Deprecated
  public boolean checkedPerformClick() {
    if (!realView.isShown()) {
      throw new RuntimeException("View is not visible and cannot be clicked");
    }
    if (!realView.isEnabled()) {
      throw new RuntimeException("View is not enabled and cannot be clicked");
    }
    boolean res = realView.performClick();
    shadowMainLooper().idleIfPaused();
    return res;
  }

  /**
   * @return Touch listener, if set.
   */
  public View.OnTouchListener getOnTouchListener() {
    return onTouchListener;
  }

  /**
   * @return Returns click listener, if set.
   */
  public View.OnClickListener getOnClickListener() {
    return onClickListener;
  }

  /**
   * @return Returns long click listener, if set.
   */
  @Implementation(minSdk = R)
  public View.OnLongClickListener getOnLongClickListener() {
    if (RuntimeEnvironment.getApiLevel() >= R) {
      return reflector(_View_.class, realView).getOnLongClickListener();
    } else {
      return onLongClickListener;
    }
  }

  /**
   * @return Returns system ui visibility change listener.
   */
  public View.OnSystemUiVisibilityChangeListener getOnSystemUiVisibilityChangeListener() {
    return onSystemUiVisibilityChangeListener;
  }

  /**
   * @return Returns create ContextMenu listener, if set.
   */
  public View.OnCreateContextMenuListener getOnCreateContextMenuListener() {
    return onCreateContextMenuListener;
  }

  /**
   * @return Returns the attached listeners, or the empty set if none are present.
   */
  public Set<View.OnAttachStateChangeListener> getOnAttachStateChangeListeners() {
    return onAttachStateChangeListeners;
  }

  /**
   * @return Returns the layout change listeners, or the empty set if none are present.
   */
  public Set<View.OnLayoutChangeListener> getOnLayoutChangeListeners() {
    return onLayoutChangeListeners;
  }

  @Implementation
  protected boolean post(Runnable action) {
    if (ShadowLooper.looperMode() == LooperMode.Mode.LEGACY) {
      ShadowApplication.getInstance().getForegroundThreadScheduler().post(action);
      return true;
    } else {
      return reflector(_View_.class, realView).post(action);
    }
  }

  @Implementation
  protected boolean postDelayed(Runnable action, long delayMills) {
    if (ShadowLooper.looperMode() == LooperMode.Mode.LEGACY) {
      ShadowApplication.getInstance()
          .getForegroundThreadScheduler()
          .postDelayed(action, delayMills);
      return true;
    } else {
      return reflector(_View_.class, realView).postDelayed(action, delayMills);
    }
  }

  @Implementation
  protected void postInvalidateDelayed(long delayMilliseconds) {
    if (ShadowLooper.looperMode() == LooperMode.Mode.LEGACY) {
      ShadowApplication.getInstance()
          .getForegroundThreadScheduler()
          .postDelayed(
              new Runnable() {
                @Override
                public void run() {
                  realView.invalidate();
                }
              },
              delayMilliseconds);
    } else {
      reflector(_View_.class, realView).postInvalidateDelayed(delayMilliseconds);
    }
  }

  @Implementation
  protected boolean removeCallbacks(Runnable callback) {
    if (ShadowLooper.looperMode() == LooperMode.Mode.LEGACY) {
      ShadowLegacyLooper shadowLooper = Shadow.extract(Looper.getMainLooper());
      shadowLooper.getScheduler().remove(callback);
      return true;
    } else {
      return reflector(_View_.class, realView).removeCallbacks(callback);
    }
  }

  @Implementation
  protected void scrollTo(int x, int y) {
    if (useRealScrolling()) {
      reflector(_View_.class, realView).scrollTo(x, y);
    } else {
      reflector(_View_.class, realView)
          .onScrollChanged(x, y, scrollToCoordinates.x, scrollToCoordinates.y);
      scrollToCoordinates = new Point(x, y);
      reflector(_View_.class, realView).setMemberScrollX(x);
      reflector(_View_.class, realView).setMemberScrollY(y);
    }
  }

  @Implementation
  protected void scrollBy(int x, int y) {
    if (useRealScrolling()) {
      reflector(_View_.class, realView).scrollBy(x, y);
    } else {
      scrollTo(getScrollX() + x, getScrollY() + y);
    }
  }

  @Implementation
  protected int getScrollX() {
    if (useRealScrolling()) {
      return reflector(_View_.class, realView).getScrollX();
    } else {
      return scrollToCoordinates != null ? scrollToCoordinates.x : 0;
    }
  }

  @Implementation
  protected int getScrollY() {
    if (useRealScrolling()) {
      return reflector(_View_.class, realView).getScrollY();
    } else {
      return scrollToCoordinates != null ? scrollToCoordinates.y : 0;
    }
  }

  @Implementation
  protected void setScrollX(int scrollX) {
    if (useRealScrolling()) {
      reflector(_View_.class, realView).setScrollX(scrollX);
    } else {
      scrollTo(scrollX, scrollToCoordinates.y);
    }
  }

  @Implementation
  protected void setScrollY(int scrollY) {
    if (useRealScrolling()) {
      reflector(_View_.class, realView).setScrollY(scrollY);
    } else {
      scrollTo(scrollToCoordinates.x, scrollY);
    }
  }

  @Implementation
  protected void getLocationOnScreen(int[] outLocation) {
    reflector(_View_.class, realView).getLocationOnScreen(outLocation);
    int[] windowLocation = getWindowLocation();
    outLocation[0] += windowLocation[0];
    outLocation[1] += windowLocation[1];
  }

  @Implementation(minSdk = O)
  protected void mapRectFromViewToScreenCoords(RectF rect, boolean clipToParent) {
    reflector(_View_.class, realView).mapRectFromViewToScreenCoords(rect, clipToParent);
    int[] windowLocation = getWindowLocation();
    rect.offset(windowLocation[0], windowLocation[1]);
  }

  // TODO(paulsowden): Should configure the correct frame on the ViewRootImpl instead and remove
  //  this.
  private int[] getWindowLocation() {
    int[] location = new int[2];
    LayoutParams rootParams = realView.getRootView().getLayoutParams();
    if (rootParams instanceof WindowManager.LayoutParams) {
      location[0] = ((WindowManager.LayoutParams) rootParams).x;
      location[1] = ((WindowManager.LayoutParams) rootParams).y;
    }
    return location;
  }

  @Implementation
  protected int getLayerType() {
    return this.layerType;
  }

  /** Returns a list of all animations that have been set on this view. */
  public ImmutableList<Animation> getAnimations() {
    return ImmutableList.copyOf(animations);
  }

  /** Resets the list returned by {@link #getAnimations()} to an empty list. */
  public void clearAnimations() {
    animations.clear();
  }

  @Implementation
  protected void setAnimation(final Animation animation) {
    reflector(_View_.class, realView).setAnimation(animation);

    if (animation != null) {
      animations.add(animation);
      if (animationRunner != null) {
        animationRunner.cancel();
      }
      animationRunner = new AnimationRunner(animation);
      animationRunner.start();
    }
  }

  @Implementation
  protected void clearAnimation() {
    reflector(_View_.class, realView).clearAnimation();

    if (animationRunner != null) {
      animationRunner.cancel();
      animationRunner = null;
    }
  }

  @Implementation
  protected boolean initialAwakenScrollBars() {
    // Temporarily allow disabling initial awaken of scroll bars to aid in migration of tests to
    // default to window's being marked visible, this will be removed once migration is complete.
    if (Boolean.getBoolean("robolectric.disableInitialAwakenScrollBars")) {
      return false;
    } else {
      return viewReflector.initialAwakenScrollBars();
    }
  }

  private class AnimationRunner implements Runnable {
    private final Animation animation;
    private final Transformation transformation = new Transformation();
    private long startTime;
    private long elapsedTime;
    private boolean canceled;

    AnimationRunner(Animation animation) {
      this.animation = animation;
    }

    private void start() {
      startTime = animation.getStartTime();
      long startOffset = animation.getStartOffset();
      long startDelay =
          startTime == Animation.START_ON_FIRST_FRAME
              ? startOffset
              : (startTime + startOffset) - SystemClock.uptimeMillis();
      Choreographer.getInstance()
          .postCallbackDelayed(Choreographer.CALLBACK_ANIMATION, this, null, startDelay);
    }

    private boolean step() {
      long animationTime =
          animation.getStartTime() == Animation.START_ON_FIRST_FRAME
              ? SystemClock.uptimeMillis()
              : (animation.getStartTime() + animation.getStartOffset() + elapsedTime);
      // Note in real android the parent is non-nullable, retain legacy robolectric behavior which
      // allows detached views to animate.
      if (!animation.isInitialized() && realView.getParent() != null) {
        View parent = (View) realView.getParent();
        animation.initialize(
            realView.getWidth(), realView.getHeight(), parent.getWidth(), parent.getHeight());
      }
      boolean next = animation.getTransformation(animationTime, transformation);
      // Note in real view implementation it doesn't check the animation equality before clearing,
      // but in the real implementation the animation listeners are posted so it doesn't race with
      // chained animations.
      if (realView.getAnimation() == animation && !next) {
        if (!animation.getFillAfter()) {
          realView.clearAnimation();
        }
      }
      // We can't handle infinitely repeating animations in the current scheduling model, so abort
      // after one iteration.
      return next
          && (animation.getRepeatCount() != Animation.INFINITE
              || elapsedTime < animation.getDuration());
    }

    @Override
    public void run() {
      // Abort if start time has been messed with, as this simulation is only designed to handle
      // standard situations.
      if (!canceled && animation.getStartTime() == startTime && step()) {
        // Start time updates for repeating animations and if START_ON_FIRST_FRAME.
        startTime = animation.getStartTime();
        elapsedTime +=
            ShadowLooper.looperMode().equals(LooperMode.Mode.LEGACY)
                ? ShadowChoreographer.getFrameInterval() / TimeUtils.NANOS_PER_MS
                : ShadowChoreographer.getFrameDelay().toMillis();
        Choreographer.getInstance().postCallback(Choreographer.CALLBACK_ANIMATION, this, null);
      } else if (animationRunner == this) {
        animationRunner = null;
      }
    }

    public void cancel() {
      this.canceled = true;
      Choreographer.getInstance()
          .removeCallbacks(Choreographer.CALLBACK_ANIMATION, animationRunner, null);
    }
  }

  @Implementation
  protected boolean isAttachedToWindow() {
    return getAttachInfo() != null;
  }

  private Object getAttachInfo() {
    return reflector(_View_.class, realView).getAttachInfo();
  }

  /** Reflector interface for {@link View}'s internals. */
  @ForType(View.class)
  private interface _View_ {

    @Direct
    void draw(Canvas canvas);

    @Direct
    void onLayout(boolean changed, int left, int top, int right, int bottom);

    void assignParent(ViewParent viewParent);

    @Direct
    void setOnFocusChangeListener(View.OnFocusChangeListener l);

    @Direct
    void setLayerType(int layerType, Paint paint);

    @Direct
    void setOnClickListener(View.OnClickListener onClickListener);

    @Direct
    void setOnLongClickListener(View.OnLongClickListener onLongClickListener);

    @Direct
    View.OnLongClickListener getOnLongClickListener();

    @Direct
    void setOnSystemUiVisibilityChangeListener(
        View.OnSystemUiVisibilityChangeListener onSystemUiVisibilityChangeListener);

    @Direct
    void setOnCreateContextMenuListener(
        View.OnCreateContextMenuListener onCreateContextMenuListener);

    @Direct
    void addOnAttachStateChangeListener(
        View.OnAttachStateChangeListener onAttachStateChangeListener);

    @Direct
    void removeOnAttachStateChangeListener(
        View.OnAttachStateChangeListener onAttachStateChangeListener);

    @Direct
    void addOnLayoutChangeListener(View.OnLayoutChangeListener onLayoutChangeListener);

    @Direct
    void removeOnLayoutChangeListener(View.OnLayoutChangeListener onLayoutChangeListener);

    @Direct
    void requestLayout();

    @Direct
    boolean performClick();

    @Direct
    boolean performLongClick();

    @Direct
    void invalidate();

    @Direct
    boolean onTouchEvent(MotionEvent event);

    @Direct
    void setOnTouchListener(View.OnTouchListener onTouchListener);

    @Direct
    boolean post(Runnable action);

    @Direct
    boolean postDelayed(Runnable action, long delayMills);

    @Direct
    void postInvalidateDelayed(long delayMilliseconds);

    @Direct
    boolean removeCallbacks(Runnable callback);

    @Direct
    void setAnimation(final Animation animation);

    @Direct
    void clearAnimation();

    @Direct
    boolean getGlobalVisibleRect(Rect rect, Point globalOffset);

    @Direct
    WindowId getWindowId();

    @Accessor("mAttachInfo")
    Object getAttachInfo();

    void onAttachedToWindow();

    void onDetachedFromWindow();

    void onScrollChanged(int l, int t, int oldl, int oldt);

    @Direct
    void getLocationOnScreen(int[] outLocation);

    @Direct
    void mapRectFromViewToScreenCoords(RectF rect, boolean clipToParent);

    @Direct
    int getSourceLayoutResId();

    @Direct
    boolean initialAwakenScrollBars();

    @Accessor("mScrollX")
    void setMemberScrollX(int value);

    @Accessor("mScrollY")
    void setMemberScrollY(int value);

    @Direct
    void scrollTo(int x, int y);

    @Direct
    void scrollBy(int x, int y);

    @Direct
    int getScrollX();

    @Direct
    int getScrollY();

    @Direct
    void setScrollX(int value);

    @Direct
    void setScrollY(int value);

    @Direct
    void __constructor__(Context context, AttributeSet attributeSet, int defStyle);

    @Direct
    void __constructor__(
        Context context, AttributeSet attributeSet, int defStyleAttr, int defStyleRes);
  }

  public void callOnAttachedToWindow() {
    reflector(_View_.class, realView).onAttachedToWindow();
  }

  public void callOnDetachedFromWindow() {
    reflector(_View_.class, realView).onDetachedFromWindow();
  }

  @Implementation
  protected WindowId getWindowId() {
    return WindowIdHelper.getWindowId(this);
  }

  @Implementation
  protected boolean performHapticFeedback(int hapticFeedbackType) {
    hapticFeedbackPerformed = hapticFeedbackType;
    return true;
  }

  @Implementation
  protected boolean getGlobalVisibleRect(Rect rect, Point globalOffset) {
    if (globalVisibleRect == null) {
      return reflector(_View_.class, realView).getGlobalVisibleRect(rect, globalOffset);
    }

    if (!globalVisibleRect.isEmpty()) {
      rect.set(globalVisibleRect);
      if (globalOffset != null) {
        rect.offset(-globalOffset.x, -globalOffset.y);
      }
      return true;
    }
    rect.setEmpty();
    return false;
  }

  public void setGlobalVisibleRect(Rect rect) {
    if (rect != null) {
      globalVisibleRect = new Rect();
      globalVisibleRect.set(rect);
    } else {
      globalVisibleRect = null;
    }
  }

  public int lastHapticFeedbackPerformed() {
    return hapticFeedbackPerformed;
  }

  public void setMyParent(ViewParent viewParent) {
    reflector(_View_.class, realView).assignParent(viewParent);
  }

  @Implementation
  protected void getWindowVisibleDisplayFrame(Rect outRect) {
    // TODO: figure out how to simulate this logic instead
    // if (mAttachInfo != null) {
    //   mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);

    ShadowDisplay.getDefaultDisplay().getRectSize(outRect);
  }

  @Implementation(minSdk = N)
  protected void getWindowDisplayFrame(Rect outRect) {
    // TODO: figure out how to simulate this logic instead
    // if (mAttachInfo != null) {
    //   mAttachInfo.mSession.getDisplayFrame(mAttachInfo.mWindow, outRect);

    ShadowDisplay.getDefaultDisplay().getRectSize(outRect);
  }

  /**
   * Returns the layout resource id this view was inflated from. Backwards compatible version of
   * {@link View#getSourceLayoutResId()}, passes through to the underlying implementation on API
   * levels where it is supported.
   */
  @Implementation(minSdk = Q)
  public int getSourceLayoutResId() {
    if (RuntimeEnvironment.getApiLevel() >= Q) {
      return reflector(_View_.class, realView).getSourceLayoutResId();
    } else {
      return ShadowResources.getAttributeSetSourceResId(attributeSet);
    }
  }

  public static class WindowIdHelper {
    public static WindowId getWindowId(ShadowView shadowView) {
      if (shadowView.isAttachedToWindow()) {
        Object attachInfo = shadowView.getAttachInfo();
        if (getField(attachInfo, "mWindowId") == null) {
          IWindowId iWindowId = new MyIWindowIdStub();
          reflector(_AttachInfo_.class, attachInfo).setWindowId(new WindowId(iWindowId));
          reflector(_AttachInfo_.class, attachInfo).setIWindowId(iWindowId);
        }
      }

      return reflector(_View_.class, shadowView.realView).getWindowId();
    }

    private static class MyIWindowIdStub extends IWindowId.Stub {
      @Override
      public void registerFocusObserver(IWindowFocusObserver iWindowFocusObserver)
          throws RemoteException {}

      @Override
      public void unregisterFocusObserver(IWindowFocusObserver iWindowFocusObserver)
          throws RemoteException {}

      @Override
      public boolean isFocused() throws RemoteException {
        return true;
      }
    }
  }

  /** Reflector interface for android.view.View.AttachInfo's internals. */
  @ForType(className = "android.view.View$AttachInfo")
  interface _AttachInfo_ {

    @Accessor("mIWindowId")
    void setIWindowId(IWindowId iWindowId);

    @Accessor("mWindowId")
    void setWindowId(WindowId windowId);
  }

  /**
   * Internal API to determine if native graphics is enabled.
   *
   * <p>This is currently public because it has to be accessed from multiple packages, but it is not
   * recommended to depend on this API.
   */
  @Beta
  public static boolean useRealGraphics() {
    GraphicsMode.Mode graphicsMode = ConfigurationRegistry.get(GraphicsMode.Mode.class);
    return graphicsMode == Mode.NATIVE && RuntimeEnvironment.getApiLevel() >= O;
  }

  /**
   * Currently the default View scrolling implementation is broken and low-fidelity. For instance,
   * even if a View has no children, Robolectric will still happily set the scroll position of a
   * View. Long-term we want to eliminate this broken behavior, but in the mean time the real
   * scrolling behavior is enabled when native graphics are enabled, or when a system property is
   * set.
   */
  static boolean useRealScrolling() {
    return useRealGraphics()
        || Boolean.parseBoolean(System.getProperty("robolectric.useRealScrolling", "true"));
  }
}