aboutsummaryrefslogtreecommitdiff
path: root/shadows/framework/src/main/java/org/robolectric/shadows/ShadowMotionEvent.java
blob: 371cb6d9eefabebaa9ed725e523ac02fc88a1d54 (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
package org.robolectric.shadows;

import static android.os.Build.VERSION_CODES.KITKAT_WATCH;
import static android.os.Build.VERSION_CODES.LOLLIPOP;
import static android.os.Build.VERSION_CODES.M;
import static android.os.Build.VERSION_CODES.P;
import static android.os.Build.VERSION_CODES.UPSIDE_DOWN_CAKE;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static org.robolectric.shadows.NativeAndroidInput.AMOTION_EVENT_AXIS_ORIENTATION;
import static org.robolectric.shadows.NativeAndroidInput.AMOTION_EVENT_AXIS_PRESSURE;
import static org.robolectric.shadows.NativeAndroidInput.AMOTION_EVENT_AXIS_SIZE;
import static org.robolectric.shadows.NativeAndroidInput.AMOTION_EVENT_AXIS_TOOL_MAJOR;
import static org.robolectric.shadows.NativeAndroidInput.AMOTION_EVENT_AXIS_TOOL_MINOR;
import static org.robolectric.shadows.NativeAndroidInput.AMOTION_EVENT_AXIS_TOUCH_MAJOR;
import static org.robolectric.shadows.NativeAndroidInput.AMOTION_EVENT_AXIS_TOUCH_MINOR;
import static org.robolectric.shadows.NativeAndroidInput.AMOTION_EVENT_AXIS_X;
import static org.robolectric.shadows.NativeAndroidInput.AMOTION_EVENT_AXIS_Y;

import android.graphics.Matrix;
import android.os.Parcel;
import android.view.MotionEvent;
import android.view.MotionEvent.PointerCoords;
import android.view.MotionEvent.PointerProperties;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.HiddenApi;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.InDevelopment;
import org.robolectric.annotation.RealObject;
import org.robolectric.annotation.Resetter;
import org.robolectric.res.android.NativeObjRegistry;
import org.robolectric.util.ReflectionHelpers;
import org.robolectric.versioning.AndroidVersions.V;

/**
 * Shadow of MotionEvent.
 *
 * <p>The Android framework stores motion events in a pool of native objects. All motion event data
 * is stored natively, and accessed via a series of static native methods following the pattern
 * nativeGetXXXX(mNativePtr, ...)
 *
 * <p>This shadow mirrors this design, but has java equivalents of each native object. Most of the
 * contents of this class were transliterated from oreo-mr1 (SDK 27)
 * frameworks/base/core/jni/android_view_MotionEvent.cpp
 *
 * @see <a
 *     href="https://android.googlesource.com/platform/frameworks/base/+/oreo-mr1-release/core/jni/android_view_MotionEvent.cpp">core/jni/android_view_MotionEvent.cpp</a>
 *     <p>Tests should not reference this class directly. MotionEvents should be created via one of
 *     the MotionEvent.obtain methods or via MotionEventBuilder.
 */
@SuppressWarnings({"UnusedDeclaration"})
@Implements(value = MotionEvent.class)
public class ShadowMotionEvent extends ShadowInputEvent {

  private static NativeObjRegistry<NativeInput.MotionEvent> nativeMotionEventRegistry =
      new NativeObjRegistry<>(NativeInput.MotionEvent.class);

  private static final int HISTORY_CURRENT = -0x80000000;

  @RealObject private MotionEvent realMotionEvent;

  @Resetter
  public static void reset() {
    // rely on MotionEvent finalizer to clear native object instead of calling
    // nativeMotionEventRegistry.clear();
    ReflectionHelpers.setStaticField(MotionEvent.class, "gRecyclerTop", null);
    ReflectionHelpers.setStaticField(MotionEvent.class, "gSharedTempPointerCoords", null);
    ReflectionHelpers.setStaticField(MotionEvent.class, "gSharedTempPointerProperties", null);
    ReflectionHelpers.setStaticField(MotionEvent.class, "gRecyclerUsed", 0);
    ReflectionHelpers.setStaticField(MotionEvent.class, "gSharedTempPointerIndexMap", null);
  }

  private static void validatePointerCount(int pointerCount) {
    checkState(pointerCount >= 1, "pointerCount must be at least 1");
  }

  private static void validatePointerPropertiesArray(
      PointerProperties[] pointerPropertiesObjArray, int pointerCount) {
    checkNotNull(pointerPropertiesObjArray, "pointerProperties array must not be null");
    checkState(
        pointerPropertiesObjArray.length >= pointerCount,
        "pointerProperties array must be large enough to hold all pointers");
  }

  private static void validatePointerCoordsObjArray(
      PointerCoords[] pointerCoordsObjArray, int pointerCount) {
    checkNotNull(pointerCoordsObjArray, "pointerCoords array must not be null");
    checkState(
        pointerCoordsObjArray.length >= pointerCount,
        "pointerCoords array must be large enough to hold all pointers");
  }

  private static void validatePointerIndex(int pointerIndex, int pointerCount) {
    checkState(pointerIndex >= 0 && pointerIndex < pointerCount, "pointerIndex out of range");
  }

  private static void validateHistoryPos(int historyPos, int historySize) {
    checkState(historyPos >= 0 && historyPos < historySize, "historyPos out of range");
  }

  private static void validatePointerCoords(PointerCoords pointerCoordsObj) {
    checkNotNull(pointerCoordsObj, "pointerCoords must not be null");
  }

  private static void validatePointerProperties(PointerProperties pointerPropertiesObj) {
    checkNotNull(pointerPropertiesObj, "pointerProperties must not be null");
  }

  private static NativeInput.PointerCoords pointerCoordsToNative(
      PointerCoords pointerCoordsObj, float xOffset, float yOffset) {
    NativeInput.PointerCoords outRawPointerCoords = new NativeInput.PointerCoords();
    outRawPointerCoords.clear();
    outRawPointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, pointerCoordsObj.x - xOffset);
    outRawPointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, pointerCoordsObj.y - yOffset);
    outRawPointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pointerCoordsObj.pressure);
    outRawPointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SIZE, pointerCoordsObj.size);
    outRawPointerCoords.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, pointerCoordsObj.touchMajor);
    outRawPointerCoords.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, pointerCoordsObj.touchMinor);
    outRawPointerCoords.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, pointerCoordsObj.toolMajor);
    outRawPointerCoords.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, pointerCoordsObj.toolMinor);
    outRawPointerCoords.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, pointerCoordsObj.orientation);
    long packedAxisBits = ReflectionHelpers.getField(pointerCoordsObj, "mPackedAxisBits");
    NativeBitSet64 bits = new NativeBitSet64(packedAxisBits);
    if (!bits.isEmpty()) {
      float[] valuesArray = ReflectionHelpers.getField(pointerCoordsObj, "mPackedAxisValues");
      if (valuesArray != null) {
        int index = 0;
        do {
          int axis = bits.clearFirstMarkedBit();
          outRawPointerCoords.setAxisValue(axis, valuesArray[index++]);
        } while (!bits.isEmpty());
      }
    }
    return outRawPointerCoords;
  }

  private static float[] obtainPackedAxisValuesArray(
      int minSize, PointerCoords outPointerCoordsObj) {
    float[] outValuesArray = ReflectionHelpers.getField(outPointerCoordsObj, "mPackedAxisValues");
    if (outValuesArray != null) {
      int size = outValuesArray.length;
      if (minSize <= size) {
        return outValuesArray;
      }
    }
    int size = 8;
    while (size < minSize) {
      size *= 2;
    }
    outValuesArray = new float[size];
    ReflectionHelpers.setField(outPointerCoordsObj, "mPackedAxisValues", outValuesArray);
    return outValuesArray;
  }

  private static void pointerCoordsFromNative(
      NativeInput.PointerCoords rawPointerCoords,
      float xOffset,
      float yOffset,
      PointerCoords outPointerCoordsObj) {
    outPointerCoordsObj.x = rawPointerCoords.getAxisValue(AMOTION_EVENT_AXIS_X) + xOffset;
    outPointerCoordsObj.y = rawPointerCoords.getAxisValue(AMOTION_EVENT_AXIS_Y) + yOffset;
    outPointerCoordsObj.pressure = rawPointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
    outPointerCoordsObj.size = rawPointerCoords.getAxisValue(AMOTION_EVENT_AXIS_SIZE);
    outPointerCoordsObj.touchMajor = rawPointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR);
    outPointerCoordsObj.touchMinor = rawPointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR);
    outPointerCoordsObj.toolMajor = rawPointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR);
    outPointerCoordsObj.toolMinor = rawPointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR);
    outPointerCoordsObj.orientation = rawPointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION);
    long outBits = 0;
    NativeBitSet64 bits = new NativeBitSet64(rawPointerCoords.getBits());
    bits.clearBit(AMOTION_EVENT_AXIS_X);
    bits.clearBit(AMOTION_EVENT_AXIS_Y);
    bits.clearBit(AMOTION_EVENT_AXIS_PRESSURE);
    bits.clearBit(AMOTION_EVENT_AXIS_SIZE);
    bits.clearBit(AMOTION_EVENT_AXIS_TOUCH_MAJOR);
    bits.clearBit(AMOTION_EVENT_AXIS_TOUCH_MINOR);
    bits.clearBit(AMOTION_EVENT_AXIS_TOOL_MAJOR);
    bits.clearBit(AMOTION_EVENT_AXIS_TOOL_MINOR);
    bits.clearBit(AMOTION_EVENT_AXIS_ORIENTATION);
    if (!bits.isEmpty()) {
      int packedAxesCount = bits.count();
      float[] outValuesArray = obtainPackedAxisValuesArray(packedAxesCount, outPointerCoordsObj);
      float[] outValues = outValuesArray;
      int index = 0;
      do {
        int axis = bits.clearFirstMarkedBit();
        outBits |= NativeBitSet64.valueForBit(axis);
        outValues[index++] = rawPointerCoords.getAxisValue(axis);
      } while (!bits.isEmpty());
    }
    ReflectionHelpers.setField(outPointerCoordsObj, "mPackedAxisBits", outBits);
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static int nativeInitialize(
      int nativePtr,
      int deviceId,
      int source,
      int action,
      int flags,
      int edgeFlags,
      int metaState,
      int buttonState,
      float xOffset,
      float yOffset,
      float xPrecision,
      float yPrecision,
      long downTimeNanos,
      long eventTimeNanos,
      int pointerCount,
      PointerProperties[] pointerIds,
      PointerCoords[] pointerCoords) {
    return (int)
        nativeInitialize(
            (long) nativePtr,
            deviceId,
            source,
            action,
            flags,
            edgeFlags,
            metaState,
            buttonState,
            xOffset,
            yOffset,
            xPrecision,
            yPrecision,
            downTimeNanos,
            eventTimeNanos,
            pointerCount,
            pointerIds,
            pointerCoords);
  }

  @Implementation(minSdk = LOLLIPOP, maxSdk = P)
  @HiddenApi
  protected static long nativeInitialize(
      long nativePtr,
      int deviceId,
      int source,
      int action,
      int flags,
      int edgeFlags,
      int metaState,
      int buttonState,
      float xOffset,
      float yOffset,
      float xPrecision,
      float yPrecision,
      long downTimeNanos,
      long eventTimeNanos,
      int pointerCount,
      PointerProperties[] pointerPropertiesObjArray,
      PointerCoords[] pointerCoordsObjArray) {

    validatePointerCount(pointerCount);
    validatePointerPropertiesArray(pointerPropertiesObjArray, pointerCount);
    validatePointerCoordsObjArray(pointerCoordsObjArray, pointerCount);

    NativeInput.MotionEvent event;
    if (nativePtr > 0) {
      event = nativeMotionEventRegistry.getNativeObject(nativePtr);
    } else {
      event = new NativeInput.MotionEvent();
      nativePtr = nativeMotionEventRegistry.register(event);
    }

    NativeInput.PointerCoords[] rawPointerCoords = new NativeInput.PointerCoords[pointerCount];
    for (int i = 0; i < pointerCount; i++) {
      PointerCoords pointerCoordsObj = pointerCoordsObjArray[i];
      checkNotNull(pointerCoordsObj);
      rawPointerCoords[i] = pointerCoordsToNative(pointerCoordsObj, xOffset, yOffset);
    }

    event.initialize(
        deviceId,
        source,
        action,
        0,
        flags,
        edgeFlags,
        metaState,
        buttonState,
        xOffset,
        yOffset,
        xPrecision,
        yPrecision,
        downTimeNanos,
        eventTimeNanos,
        pointerCount,
        pointerPropertiesObjArray,
        rawPointerCoords);
    return nativePtr;
  }

  // TODO(brettchabot): properly handle displayId
  @Implementation(minSdk = android.os.Build.VERSION_CODES.Q)
  @HiddenApi
  protected static long nativeInitialize(
      long nativePtr,
      int deviceId,
      int source,
      int displayId,
      int action,
      int flags,
      int edgeFlags,
      int metaState,
      int buttonState,
      int classification,
      float xOffset,
      float yOffset,
      float xPrecision,
      float yPrecision,
      long downTimeNanos,
      long eventTimeNanos,
      int pointerCount,
      PointerProperties[] pointerIds,
      PointerCoords[] pointerCoords) {
    return nativeInitialize(
        nativePtr,
        deviceId,
        source,
        action,
        flags,
        edgeFlags,
        metaState,
        buttonState,
        xOffset,
        yOffset,
        xPrecision,
        yPrecision,
        downTimeNanos,
        eventTimeNanos,
        pointerCount,
        pointerIds,
        pointerCoords);
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static void nativeDispose(int nativePtr) {
    nativeDispose((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static void nativeDispose(long nativePtr) {
    nativeMotionEventRegistry.unregister(nativePtr);
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static void nativeAddBatch(
      int nativePtr, long eventTimeNanos, PointerCoords[] pointerCoordsObjArray, int metaState) {
    nativeAddBatch((long) nativePtr, eventTimeNanos, pointerCoordsObjArray, metaState);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static void nativeAddBatch(
      long nativePtr, long eventTimeNanos, PointerCoords[] pointerCoordsObjArray, int metaState) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    int pointerCount = event.getPointerCount();
    validatePointerCoordsObjArray(pointerCoordsObjArray, pointerCount);
    NativeInput.PointerCoords[] rawPointerCoords = new NativeInput.PointerCoords[pointerCount];
    for (int i = 0; i < pointerCount; i++) {
      PointerCoords pointerCoordsObj = pointerCoordsObjArray[i];
      checkNotNull(pointerCoordsObj);
      rawPointerCoords[i] =
          pointerCoordsToNative(pointerCoordsObj, event.getXOffset(), event.getYOffset());
    }
    event.addSample(eventTimeNanos, rawPointerCoords);
    event.setMetaState(event.getMetaState() | metaState);
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static void nativeGetPointerCoords(
      int nativePtr, int pointerIndex, int historyPos, PointerCoords outPointerCoordsObj) {
    nativeGetPointerCoords((long) nativePtr, pointerIndex, historyPos, outPointerCoordsObj);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static void nativeGetPointerCoords(
      long nativePtr, int pointerIndex, int historyPos, PointerCoords outPointerCoordsObj) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    int pointerCount = event.getPointerCount();
    validatePointerIndex(pointerIndex, pointerCount);
    validatePointerCoords(outPointerCoordsObj);

    NativeInput.PointerCoords rawPointerCoords;
    if (historyPos == HISTORY_CURRENT) {
      rawPointerCoords = event.getRawPointerCoords(pointerIndex);
    } else {
      int historySize = event.getHistorySize();
      validateHistoryPos(historyPos, historySize);
      rawPointerCoords = event.getHistoricalRawPointerCoords(pointerIndex, historyPos);
    }
    pointerCoordsFromNative(
        rawPointerCoords, event.getXOffset(), event.getYOffset(), outPointerCoordsObj);
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static void nativeGetPointerProperties(
      int nativePtr, int pointerIndex, PointerProperties outPointerPropertiesObj) {
    nativeGetPointerProperties((long) nativePtr, pointerIndex, outPointerPropertiesObj);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static void nativeGetPointerProperties(
      long nativePtr, int pointerIndex, PointerProperties outPointerPropertiesObj) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    int pointerCount = event.getPointerCount();
    validatePointerIndex(pointerIndex, pointerCount);
    validatePointerProperties(outPointerPropertiesObj);

    PointerProperties pointerProperties = event.getPointerProperties(pointerIndex);
    // pointerPropertiesFromNative(env, pointerProperties, outPointerPropertiesObj);
    outPointerPropertiesObj.copyFrom(pointerProperties);
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static int nativeReadFromParcel(int nativePtr, Parcel parcelObj) {
    return (int) nativeReadFromParcel((long) nativePtr, parcelObj);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static long nativeReadFromParcel(long nativePtr, Parcel parcelObj) {
    NativeInput.MotionEvent event;
    if (nativePtr == 0) {
      event = new NativeInput.MotionEvent();
      nativePtr = nativeMotionEventRegistry.register(event);
    } else {
      event = nativeMotionEventRegistry.getNativeObject(nativePtr);
    }
    boolean status = event.readFromParcel(parcelObj);
    if (!status) {
      if (nativePtr > 0) {
        nativeMotionEventRegistry.unregister(nativePtr);
      }
      throw new RuntimeException("Failed to read MotionEvent parcel.");
    }
    return nativePtr;
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static void nativeWriteToParcel(int nativePtr, Parcel parcel) {
    nativeWriteToParcel((long) nativePtr, parcel);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static void nativeWriteToParcel(long nativePtr, Parcel parcel) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    if (!event.writeToParcel(parcel)) {
      throw new RuntimeException("Failed to write MotionEvent parcel.");
    }
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static String nativeAxisToString(int axis) {
    // The native code just mirrors the AXIS_* constants defined in MotionEvent.java.
    // Look up the field value by reflection to future proof this method
    for (Field field : MotionEvent.class.getDeclaredFields()) {
      int modifiers = field.getModifiers();
      try {
        if (Modifier.isStatic(modifiers)
            && Modifier.isPublic(modifiers)
            && field.getName().startsWith("AXIS_")
            && field.getInt(null) == axis) {
          // return the field name stripping off the "AXIS_" prefix
          return field.getName().substring(5);
        }
      } catch (IllegalAccessException e) {
        // ignore
      }
    }
    return null;
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static int nativeAxisFromString(String label) {
    // The native code just mirrors the AXIS_* constants defined in MotionEvent.java. Look up
    // the field value by reflection
    try {
      Field constantField = MotionEvent.class.getDeclaredField("AXIS_" + label);
      return constantField.getInt(null);
    } catch (NoSuchFieldException | IllegalAccessException e) {
      return 0;
    }
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static int nativeGetPointerId(int nativePtr, int pointerIndex) {
    return nativeGetPointerId((long) nativePtr, pointerIndex);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static int nativeGetPointerId(long nativePtr, int pointerIndex) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    int pointerCount = event.getPointerCount();
    validatePointerIndex(pointerIndex, pointerCount);
    return event.getPointerId(pointerIndex);
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static int nativeGetToolType(int nativePtr, int pointerIndex) {
    return nativeGetToolType((long) nativePtr, pointerIndex);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static int nativeGetToolType(long nativePtr, int pointerIndex) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    int pointerCount = event.getPointerCount();
    validatePointerIndex(pointerIndex, pointerCount);
    return event.getToolType(pointerIndex);
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static long nativeGetEventTimeNanos(int nativePtr, int historyPos) {
    return nativeGetEventTimeNanos((long) nativePtr, historyPos);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static long nativeGetEventTimeNanos(long nativePtr, int historyPos) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    if (historyPos == HISTORY_CURRENT) {
      return event.getEventTime();
    } else {
      int historySize = event.getHistorySize();
      validateHistoryPos(historyPos, historySize);
      return event.getHistoricalEventTime(historyPos);
    }
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static float nativeGetRawAxisValue(
      int nativePtr, int axis, int pointerIndex, int historyPos) {
    return nativeGetRawAxisValue((long) nativePtr, axis, pointerIndex, historyPos);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static float nativeGetRawAxisValue(
      long nativePtr, int axis, int pointerIndex, int historyPos) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    int pointerCount = event.getPointerCount();
    validatePointerIndex(pointerIndex, pointerCount);

    if (historyPos == HISTORY_CURRENT) {
      return event.getRawAxisValue(axis, pointerIndex);
    } else {
      int historySize = event.getHistorySize();
      validateHistoryPos(historyPos, historySize);
      return event.getHistoricalRawAxisValue(axis, pointerIndex, historyPos);
    }
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static float nativeGetAxisValue(
      int nativePtr, int axis, int pointerIndex, int historyPos) {
    return nativeGetAxisValue((long) nativePtr, axis, pointerIndex, historyPos);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static float nativeGetAxisValue(
      long nativePtr, int axis, int pointerIndex, int historyPos) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    int pointerCount = event.getPointerCount();
    validatePointerIndex(pointerIndex, pointerCount);

    if (historyPos == HISTORY_CURRENT) {
      return event.getAxisValue(axis, pointerIndex);
    } else {
      int historySize = event.getHistorySize();
      validateHistoryPos(historyPos, historySize);
      return event.getHistoricalAxisValue(axis, pointerIndex, historyPos);
    }
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static int nativeCopy(int destNativePtr, int sourceNativePtr, boolean keepHistory) {
    return (int) nativeCopy((long) destNativePtr, (long) sourceNativePtr, keepHistory);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static long nativeCopy(long destNativePtr, long sourceNativePtr, boolean keepHistory) {
    NativeInput.MotionEvent destEvent = nativeMotionEventRegistry.peekNativeObject(destNativePtr);
    if (destEvent == null) {
      destEvent = new NativeInput.MotionEvent();
      destNativePtr = nativeMotionEventRegistry.register(destEvent);
    }
    NativeInput.MotionEvent sourceEvent = getNativeMotionEvent(sourceNativePtr);
    destEvent.copyFrom(sourceEvent, keepHistory);
    return destNativePtr;
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static int nativeGetDeviceId(int nativePtr) {
    return nativeGetDeviceId((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static int nativeGetDeviceId(long nativePtr) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    return event.getDeviceId();
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static int nativeGetSource(int nativePtr) {
    return nativeGetSource((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static int nativeGetSource(long nativePtr) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    return event.getSource();
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static int nativeSetSource(int nativePtr, int source) {
    nativeSetSource((long) nativePtr, source);
    return 0;
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  @SuppressWarnings("robolectric.ShadowReturnTypeMismatch")
  protected static void nativeSetSource(long nativePtr, int source) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    event.setSource(source);
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static int nativeGetAction(int nativePtr) {
    return nativeGetAction((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static int nativeGetAction(long nativePtr) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    return event.getAction();
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static void nativeSetAction(int nativePtr, int action) {
    nativeSetAction((long) nativePtr, action);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static void nativeSetAction(long nativePtr, int action) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    event.setAction(action);
  }

  @Implementation(minSdk = M)
  @HiddenApi
  protected static int nativeGetActionButton(long nativePtr) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    return event.getActionButton();
  }

  @Implementation(minSdk = M)
  @HiddenApi
  protected static void nativeSetActionButton(long nativePtr, int button) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    event.setActionButton(button);
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static boolean nativeIsTouchEvent(int nativePtr) {
    return nativeIsTouchEvent((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static boolean nativeIsTouchEvent(long nativePtr) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    return event.isTouchEvent();
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static int nativeGetFlags(int nativePtr) {
    return nativeGetFlags((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static int nativeGetFlags(long nativePtr) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    return event.getFlags();
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static void nativeSetFlags(int nativePtr, int flags) {
    nativeSetFlags((long) nativePtr, flags);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static void nativeSetFlags(long nativePtr, int flags) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    event.setFlags(flags);
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static int nativeGetEdgeFlags(int nativePtr) {
    return nativeGetEdgeFlags((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static int nativeGetEdgeFlags(long nativePtr) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    return event.getEdgeFlags();
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static void nativeSetEdgeFlags(int nativePtr, int edgeFlags) {
    nativeSetEdgeFlags((long) nativePtr, edgeFlags);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static void nativeSetEdgeFlags(long nativePtr, int edgeFlags) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    event.setEdgeFlags(edgeFlags);
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static int nativeGetMetaState(int nativePtr) {
    return nativeGetMetaState((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static int nativeGetMetaState(long nativePtr) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    return event.getMetaState();
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static int nativeGetButtonState(int nativePtr) {
    return nativeGetButtonState((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static int nativeGetButtonState(long nativePtr) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    return event.getButtonState();
  }

  @Implementation(minSdk = M)
  @HiddenApi
  protected static void nativeSetButtonState(long nativePtr, int buttonState) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    event.setButtonState(buttonState);
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static void nativeOffsetLocation(int nativePtr, float deltaX, float deltaY) {
    nativeOffsetLocation((long) nativePtr, deltaX, deltaY);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static void nativeOffsetLocation(long nativePtr, float deltaX, float deltaY) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    event.offsetLocation(deltaX, deltaY);
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static float nativeGetXOffset(int nativePtr) {
    return nativeGetXOffset((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP, maxSdk = UPSIDE_DOWN_CAKE)
  @HiddenApi
  @InDevelopment
  protected static float nativeGetXOffset(long nativePtr) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    return event.getXOffset();
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static float nativeGetYOffset(int nativePtr) {
    return nativeGetYOffset((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP, maxSdk = UPSIDE_DOWN_CAKE)
  @HiddenApi
  @InDevelopment
  protected static float nativeGetYOffset(long nativePtr) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    return event.getYOffset();
  }

  @Implementation(minSdk = V.SDK_INT)
  protected final MotionEvent split(int idBits) {
    NativeInput.MotionEvent event = getNativeMotionEvent();
    return event.nativeSplit(idBits);
  }

  @Implementation(minSdk = V.SDK_INT)
  @HiddenApi
  protected static float nativeGetRawXOffset(long nativePtr) {
    return getNativeMotionEvent(nativePtr).getXOffset();
  }

  @Implementation(minSdk = V.SDK_INT)
  @HiddenApi
  protected static float nativeGetRawYOffset(long nativePtr) {
    return getNativeMotionEvent(nativePtr).getYOffset();
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static float nativeGetXPrecision(int nativePtr) {
    return nativeGetXPrecision((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static float nativeGetXPrecision(long nativePtr) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    return event.getXPrecision();
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static float nativeGetYPrecision(int nativePtr) {
    return nativeGetYPrecision((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static float nativeGetYPrecision(long nativePtr) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    return event.getYPrecision();
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static long nativeGetDownTimeNanos(int nativePtr) {
    return nativeGetDownTimeNanos((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static long nativeGetDownTimeNanos(long nativePtr) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    return event.getDownTime();
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static void nativeSetDownTimeNanos(int nativePtr, long downTimeNanos) {
    nativeSetDownTimeNanos((long) nativePtr, downTimeNanos);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static void nativeSetDownTimeNanos(long nativePtr, long downTimeNanos) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    event.setDownTime(downTimeNanos);
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static int nativeGetPointerCount(int nativePtr) {
    return nativeGetPointerCount((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static int nativeGetPointerCount(long nativePtr) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    return event.getPointerCount();
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static int nativeFindPointerIndex(int nativePtr, int pointerId) {
    return nativeFindPointerIndex((long) nativePtr, pointerId);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static int nativeFindPointerIndex(long nativePtr, int pointerId) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    return event.findPointerIndex(pointerId);
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static int nativeGetHistorySize(int nativePtr) {
    return nativeGetHistorySize((long) nativePtr);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static int nativeGetHistorySize(long nativePtr) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    return event.getHistorySize();
  }

  @Implementation(maxSdk = KITKAT_WATCH)
  @HiddenApi
  protected static void nativeScale(int nativePtr, float scale) {
    nativeScale((long) nativePtr, scale);
  }

  @Implementation(minSdk = LOLLIPOP)
  @HiddenApi
  protected static void nativeScale(long nativePtr, float scale) {
    NativeInput.MotionEvent event = getNativeMotionEvent(nativePtr);
    event.scale(scale);
  }

  protected static NativeInput.MotionEvent getNativeMotionEvent(long nativePtr) {
    // check that MotionEvent was initialized properly. This can occur if MotionEvent was mocked
    checkState(
        nativePtr > 0,
        "MotionEvent has not been initialized. "
            + "Ensure MotionEvent.obtain was used to create it, instead of creating it directly "
            + "or via a Mocking framework");

    return nativeMotionEventRegistry.getNativeObject(nativePtr);
  }

  @Implementation
  protected void transform(Matrix matrix) {
    checkNotNull(matrix);
    NativeInput.MotionEvent event = getNativeMotionEvent();

    float[] m = new float[9];
    matrix.getValues(m);
    event.transform(m);
  }

  protected NativeInput.MotionEvent getNativeMotionEvent() {
    long nativePtr;
    if (RuntimeEnvironment.getApiLevel() <= KITKAT_WATCH) {
      Integer nativePtrInt = ReflectionHelpers.getField(realMotionEvent, "mNativePtr");
      nativePtr = nativePtrInt.longValue();
    } else {
      nativePtr = ReflectionHelpers.getField(realMotionEvent, "mNativePtr");
    }
    return nativeMotionEventRegistry.getNativeObject(nativePtr);
  }

  // Testing API methods

  /**
   * @deprecated use {@link MotionEvent#obtain} or {@link
   *     androidx.test.core.view.MotionEventBuilder} to create a MotionEvent with desired data.
   */
  @Deprecated
  public MotionEvent setPointer2(float pointer1X, float pointer1Y) {
    NativeInput.MotionEvent event = getNativeMotionEvent();
    List<NativeInput.PointerCoords> pointerCoords = event.getSamplePointerCoords();
    List<PointerProperties> pointerProperties = event.getPointerProperties();
    ensureTwoPointers(pointerCoords, pointerProperties);

    pointerCoords.get(1).setAxisValue(AMOTION_EVENT_AXIS_X, pointer1X);
    pointerCoords.get(1).setAxisValue(AMOTION_EVENT_AXIS_Y, pointer1Y);
    return realMotionEvent;
  }

  private static void ensureTwoPointers(
      List<NativeInput.PointerCoords> pointerCoords, List<PointerProperties> pointerProperties) {
    if (pointerCoords.size() < 2) {
      pointerCoords.add(new NativeInput.PointerCoords());
    }
    if (pointerProperties.size() < 2) {
      pointerProperties.add(new PointerProperties());
    }
  }

  /**
   * @deprecated use {@link MotionEvent#obtain} or {@link
   *     androidx.test.core.view.MotionEventBuilder#setPointerAction(int, int)} to create a
   *     MotionEvent with desired data.
   */
  @Deprecated
  public void setPointerIndex(int pointerIndex) {
    NativeInput.MotionEvent event = getNativeMotionEvent();
    // pointer index is stored in upper two bytes of action
    event.setAction(
        event.getAction() | ((pointerIndex & 0xff) << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
  }

  /**
   * @deprecated use {@link MotionEvent#obtain} or {@link MotionEventBuilder} to create a
   *     MotionEvent with desired data
   */
  @Deprecated
  public void setPointerIds(int index0PointerId, int index1PointerId) {
    NativeInput.MotionEvent event = getNativeMotionEvent();
    List<NativeInput.PointerCoords> pointerCoords = event.getSamplePointerCoords();
    List<PointerProperties> pointerProperties = event.getPointerProperties();
    ensureTwoPointers(pointerCoords, pointerProperties);

    pointerProperties.get(0).id = index0PointerId;
    pointerProperties.get(1).id = index1PointerId;
  }
}