Beispiel #1
0
  @StressTest
  @UiThreadTest
  public void testRandomTouch() {
    MemoryLogger memoryLogger = new MemoryLogger("testRandomTouch", 100);

    viewManager.setKeyboardLayout(KeyboardLayout.TWELVE_KEYS);

    final int actions = 500;

    final Random random = new Random();
    Rect rect = getViewRect();

    memoryLogger.logMemory("start");
    for (int i = 0; i < actions; i++) {
      final int x = rect.left + random.nextInt(rect.width());
      final int y = rect.top + random.nextInt(rect.height());

      inputView.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, x, y, 0));
      inputView.dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_UP, x, y, 0));

      // updateRequest sends asynchronous message to server. So we need to wait a moment
      // for server processing.
      sleep(200);

      memoryLogger.logMemoryInterval();
    }
    memoryLogger.logMemory("start");
  }
Beispiel #2
0
 /**
  * Simulate touching a specific location and dragging to a new location.
  *
  * <p>This method was copied from {@code TouchUtils.java} in the Android Open Source Project, and
  * modified here.
  *
  * @param fromX X coordinate of the initial touch, in screen coordinates
  * @param toX Xcoordinate of the drag destination, in screen coordinates
  * @param fromY X coordinate of the initial touch, in screen coordinates
  * @param toY Y coordinate of the drag destination, in screen coordinates
  * @param stepCount How many move steps to include in the drag
  */
 public void drag(float fromX, float toX, float fromY, float toY, int stepCount) {
   long downTime = SystemClock.uptimeMillis();
   long eventTime = SystemClock.uptimeMillis();
   float y = fromY;
   float x = fromX;
   float yStep = (toY - fromY) / stepCount;
   float xStep = (toX - fromX) / stepCount;
   MotionEvent event =
       MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, fromX, fromY, 0);
   try {
     inst.sendPointerSync(event);
   } catch (SecurityException ignored) {
   }
   for (int i = 0; i < stepCount; ++i) {
     y += yStep;
     x += xStep;
     eventTime = SystemClock.uptimeMillis();
     event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_MOVE, x, y, 0);
     try {
       inst.sendPointerSync(event);
     } catch (SecurityException ignored) {
     }
   }
   eventTime = SystemClock.uptimeMillis();
   event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_UP, toX, toY, 0);
   try {
     inst.sendPointerSync(event);
   } catch (SecurityException ignored) {
   }
 }
  @Override
  public void click() {
    String tagName = getTagName();
    if (tagName != null && "OPTION".equals(tagName.toUpperCase())) {
      driver.resetPageIsLoading();
      driver.executeAtom(AndroidAtoms.CLICK, this);
      driver.waitForPageToLoad();
    }

    Point center = getCenterCoordinates();
    long downTime = SystemClock.uptimeMillis();
    final List<MotionEvent> events = Lists.newArrayList();

    MotionEvent downEvent =
        MotionEvent.obtain(
            downTime, SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, center.x, center.y, 0);
    events.add(downEvent);
    MotionEvent upEvent =
        MotionEvent.obtain(
            downTime, SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, center.x, center.y, 0);

    events.add(upEvent);

    driver.resetPageIsLoading();
    Activity current = ServerInstrumentation.getInstance().getCurrentActivity();
    EventSender.sendMotion(events, webview, current);

    // If the page started loading we should wait
    // until the page is done loading.
    driver.waitForPageToLoad();
  }
  public void longPress(Coordinates where) {
    long downTime = SystemClock.uptimeMillis();
    long eventTime = SystemClock.uptimeMillis();
    Point point = where.getLocationOnScreen();
    // List<MotionEvent> motionEvents = new ArrayList<MotionEvent>();
    //
    // motionEvents.add(getMotionEvent(downTime, downTime, MotionEvent.ACTION_DOWN, point));
    // motionEvents.add(getMotionEvent(downTime, (downTime + 3000), MotionEvent.ACTION_UP, point));
    // sendMotionEvents(motionEvents);
    Instrumentation inst = instrumentation;

    MotionEvent event = null;
    boolean successfull = false;
    int retry = 0;
    while (!successfull && retry < 10) {
      try {
        if (event == null) {
          event =
              MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, point.x, point.y, 0);
        }
        System.out.println("trying to send pointer");
        inst.sendPointerSync(event);
        successfull = true;
      } catch (SecurityException e) {
        System.out.println("failed: " + retry);
        // activityUtils.hideSoftKeyboard(null, false, true);
        retry++;
      }
    }
    if (!successfull) {
      throw new SelendroidException("Click can not be completed!");
    }
    inst.sendPointerSync(event);
    inst.waitForIdleSync();

    eventTime = SystemClock.uptimeMillis();
    final int touchSlop = ViewConfiguration.get(inst.getTargetContext()).getScaledTouchSlop();
    event =
        MotionEvent.obtain(
            downTime,
            eventTime,
            MotionEvent.ACTION_MOVE,
            point.x + touchSlop / 2,
            point.y + touchSlop / 2,
            0);
    inst.sendPointerSync(event);
    inst.waitForIdleSync();

    try {
      Thread.sleep((long) (ViewConfiguration.getLongPressTimeout() * 1.5f));
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    eventTime = SystemClock.uptimeMillis();
    event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_UP, point.x, point.y, 0);
    inst.sendPointerSync(event);
    inst.waitForIdleSync();
  }
  @Override
  public boolean dispatchTouchEvent(MotionEvent ev) {

    final float x = ev.getX();
    final float y = ev.getY();
    final int action = ev.getAction();

    if (action == MotionEvent.ACTION_DOWN
        && mTouchTarget == null
        && mPinnedSection != null
        && isPinnedViewTouched(mPinnedSection.view, x, y)) { // create touch target

      // user touched pinned view
      mTouchTarget = mPinnedSection.view;
      mTouchPoint.x = x;
      mTouchPoint.y = y;

      // copy down event for eventually be used later
      mDownEvent = MotionEvent.obtain(ev);
    }

    if (mTouchTarget != null) {
      if (isPinnedViewTouched(mTouchTarget, x, y)) { // forward event to pinned view
        mTouchTarget.dispatchTouchEvent(ev);
      }

      if (action == MotionEvent.ACTION_UP) { // perform onClick on pinned view
        super.dispatchTouchEvent(ev);
        performPinnedItemClick();
        clearTouchTarget();

      } else if (action == MotionEvent.ACTION_CANCEL) { // cancel
        clearTouchTarget();

      } else if (action == MotionEvent.ACTION_MOVE) {
        if (Math.abs(y - mTouchPoint.y) > mTouchSlop) {

          // cancel sequence on touch target
          MotionEvent event = MotionEvent.obtain(ev);
          event.setAction(MotionEvent.ACTION_CANCEL);
          mTouchTarget.dispatchTouchEvent(event);
          event.recycle();

          // provide correct sequence to super class for further handling
          super.dispatchTouchEvent(mDownEvent);
          super.dispatchTouchEvent(ev);
          clearTouchTarget();
        }
      }

      return true;
    }

    // call super if this was not our pinned view
    return super.dispatchTouchEvent(ev);
  }
  /**
   * Verify that a recent show pressed state gesture is canceled when double tap occurs.
   *
   * @throws Exception
   */
  @SmallTest
  @Feature({"Gestures"})
  public void testShowPressCancelOnDoubleTap() throws Exception {
    final long downTime = SystemClock.uptimeMillis();
    final long eventTime = SystemClock.uptimeMillis();

    GestureRecordingMotionEventDelegate mockDelegate = new GestureRecordingMotionEventDelegate();
    mGestureHandler =
        new ContentViewGestureHandler(
            getInstrumentation().getTargetContext(),
            mockDelegate,
            new MockZoomManager(getInstrumentation().getTargetContext(), null));
    mLongPressDetector =
        new LongPressDetector(getInstrumentation().getTargetContext(), mGestureHandler);

    MotionEvent event = motionEvent(MotionEvent.ACTION_DOWN, downTime, downTime);

    assertTrue(mGestureHandler.onTouchEvent(event));
    assertFalse("Should not have a pending LONG_PRESS", mLongPressDetector.hasPendingMessage());

    mGestureHandler.sendShowPressedStateGestureForTesting();

    assertEquals(
        "A show pressed state event should have been sent",
        ContentViewGestureHandler.GESTURE_SHOW_PRESSED_STATE,
        mockDelegate.mMostRecentGestureEvent.mType);
    assertEquals(
        "Only flingCancel and showPressedState should have been sent",
        2,
        mockDelegate.mGestureTypeList.size());

    event =
        MotionEvent.obtain(
            downTime, eventTime + 5, MotionEvent.ACTION_UP, FAKE_COORD_X, FAKE_COORD_Y, 0);
    mGestureHandler.onTouchEvent(event);
    assertEquals("The first tap should not do anything", 2, mockDelegate.mGestureTypeList.size());

    event =
        MotionEvent.obtain(
            eventTime + 10, eventTime + 10, MotionEvent.ACTION_DOWN, FAKE_COORD_X, FAKE_COORD_Y, 0);
    assertTrue(mGestureHandler.onTouchEvent(event));
    assertEquals(
        "A double tap should have occurred",
        ContentViewGestureHandler.GESTURE_DOUBLE_TAP,
        mockDelegate.mMostRecentGestureEvent.mType);
    assertTrue(
        "A show press cancel event should have been sent",
        mockDelegate.mGestureTypeList.contains(
            ContentViewGestureHandler.GESTURE_SHOW_PRESS_CANCEL));
    assertEquals(
        "Only flingCancel, showPressedState,"
            + "flingCancel, showPressCancel and doubleTap should have been sent",
        5,
        mockDelegate.mGestureTypeList.size());
  }
  /** step 3 */
  private boolean performMultiPointerUp() {
    if (mTouches == null) {
      return false;
    }

    boolean ret = true;
    MotionEvent event;

    // For each pointer get the last coordinates
    for (int x = 0; x < mTouches.length; x++)
      mPointerCoords[x] = mTouches[x][mTouches[x].length - 1];

    // touch up
    for (int x = 1; x < mTouches.length; x++) {
      event =
          MotionEvent.obtain(
              mDownTime,
              SystemClock.uptimeMillis(),
              getPointerAction(MotionEvent.ACTION_POINTER_UP, x),
              x + 1,
              mProperties,
              mPointerCoords,
              0,
              0,
              1,
              1,
              0,
              0,
              InputDevice.SOURCE_TOUCHSCREEN,
              0);
      ret &= mUiAutomation.injectInputEvent(event, true);
    }

    // first to touch down is last up
    event =
        MotionEvent.obtain(
            mDownTime,
            SystemClock.uptimeMillis(),
            MotionEvent.ACTION_UP,
            1,
            mProperties,
            mPointerCoords,
            0,
            0,
            1,
            1,
            0,
            0,
            InputDevice.SOURCE_TOUCHSCREEN,
            0);
    ret &= mUiAutomation.injectInputEvent(event, true);

    return ret;
  }
  /**
   * Generate a scroll gesture and verify that the resulting scroll motion event has both absolute
   * and relative position information.
   */
  @SmallTest
  @Feature({"Gestures"})
  public void testScrollUpdateCoordinates() {
    final int deltaX = 16;
    final int deltaY = 84;
    final long downTime = SystemClock.uptimeMillis();

    GestureRecordingMotionEventDelegate delegate = new GestureRecordingMotionEventDelegate();
    ContentViewGestureHandler gestureHandler =
        new ContentViewGestureHandler(
            getInstrumentation().getTargetContext(),
            delegate,
            new MockZoomManager(getInstrumentation().getTargetContext(), null));
    MotionEvent event = motionEvent(MotionEvent.ACTION_DOWN, downTime, downTime);
    assertTrue(gestureHandler.onTouchEvent(event));
    assertNotNull(delegate.getMostRecentGestureEvent());

    // Move twice, because the first move gesture is discarded.
    event =
        MotionEvent.obtain(
            downTime,
            downTime + 5,
            MotionEvent.ACTION_MOVE,
            FAKE_COORD_X - deltaX / 2,
            FAKE_COORD_Y - deltaY / 2,
            0);
    assertTrue(gestureHandler.onTouchEvent(event));

    event =
        MotionEvent.obtain(
            downTime,
            downTime + 10,
            MotionEvent.ACTION_MOVE,
            FAKE_COORD_X - deltaX,
            FAKE_COORD_Y - deltaY,
            0);
    assertTrue(gestureHandler.onTouchEvent(event));

    // Make sure the reported gesture event has all the expected data.
    GestureRecordingMotionEventDelegate.GestureEvent gestureEvent =
        delegate.getMostRecentGestureEvent();
    assertNotNull(gestureEvent);
    assertEquals(ContentViewGestureHandler.GESTURE_SCROLL_BY, gestureEvent.getType());
    assertEquals(downTime + 10, gestureEvent.getTimeMs());
    assertEquals(FAKE_COORD_X - deltaX, gestureEvent.getX());
    assertEquals(FAKE_COORD_Y - deltaY, gestureEvent.getY());

    Bundle extraParams = gestureEvent.getExtraParams();
    assertNotNull(extraParams);
    // No horizontal delta because of snapping.
    assertEquals(0, extraParams.getInt(ContentViewGestureHandler.DISTANCE_X));
    assertEquals(deltaY / 2, extraParams.getInt(ContentViewGestureHandler.DISTANCE_Y));
  }
  /**
   * Verify that the first event sent while the page is scrolling will be converted to a
   * touchcancel. The touchcancel event should stay in the pending queue. Acking the touchcancel
   * event will consume all the touch events of the current session.
   */
  @SmallTest
  @Feature({"Gestures"})
  public void testTouchEventsCanceledWhileScrolling() {
    final int deltaY = 84;
    final long downTime = SystemClock.uptimeMillis();

    MockMotionEventDelegate delegate = new MockMotionEventDelegate();
    ContentViewGestureHandler gestureHandler =
        new ContentViewGestureHandler(
            getInstrumentation().getTargetContext(),
            delegate,
            new MockZoomManager(getInstrumentation().getTargetContext(), null));
    gestureHandler.hasTouchEventHandlers(true);
    MotionEvent event = motionEvent(MotionEvent.ACTION_DOWN, downTime, downTime);
    assertTrue(gestureHandler.onTouchEvent(event));
    gestureHandler.confirmTouchEvent(ContentViewGestureHandler.INPUT_EVENT_ACK_STATE_NOT_CONSUMED);

    event =
        MotionEvent.obtain(
            downTime,
            downTime + 5,
            MotionEvent.ACTION_MOVE,
            FAKE_COORD_X,
            FAKE_COORD_Y - deltaY / 2,
            0);
    assertTrue(gestureHandler.onTouchEvent(event));
    gestureHandler.confirmTouchEvent(ContentViewGestureHandler.INPUT_EVENT_ACK_STATE_NOT_CONSUMED);

    // This event will be converted to touchcancel and put into the pending
    // queue.
    event =
        MotionEvent.obtain(
            downTime,
            downTime + 10,
            MotionEvent.ACTION_MOVE,
            FAKE_COORD_X,
            FAKE_COORD_Y - deltaY,
            0);
    assertTrue(gestureHandler.onTouchEvent(event));
    assertEquals(1, gestureHandler.getNumberOfPendingMotionEventsForTesting());
    assertTrue(
        gestureHandler.isEventCancelledForTesting(
            gestureHandler.peekFirstInPendingMotionEventsForTesting()));

    event = motionEvent(MotionEvent.ACTION_POINTER_DOWN, downTime + 15, downTime + 15);
    assertTrue(gestureHandler.onTouchEvent(event));
    assertEquals(2, gestureHandler.getNumberOfPendingMotionEventsForTesting());

    // Acking the touchcancel will drain all the events.
    gestureHandler.confirmTouchEvent(ContentViewGestureHandler.INPUT_EVENT_ACK_STATE_NOT_CONSUMED);
    assertEquals(0, gestureHandler.getNumberOfPendingMotionEventsForTesting());
  }
 public void init(MotionEvent e) {
   if (mInitialEvent != null) {
     mInitialEvent.recycle();
   }
   mInitialEvent = MotionEvent.obtain(e);
   mIsPending = true;
 }
Beispiel #11
0
 private static boolean isTouchEventHandled(final View view, final MotionEvent event) {
   if (view instanceof RightPaneBackgroundView) return false;
   if (!(view instanceof ViewGroup)) return true;
   final MotionEvent ev = MotionEvent.obtain(event);
   final float xf = ev.getX();
   final float yf = ev.getY();
   final float scrolledXFloat = xf + view.getScrollX();
   final float scrolledYFloat = yf + view.getScrollY();
   final Rect frame = new Rect();
   final int scrolledXInt = (int) scrolledXFloat;
   final int scrolledYInt = (int) scrolledYFloat;
   final int count = ((ViewGroup) view).getChildCount();
   for (int i = count - 1; i >= 0; i--) {
     final View child = ((ViewGroup) view).getChildAt(i);
     if (child.isShown() || child.getAnimation() != null) {
       child.getHitRect(frame);
       if (frame.contains(scrolledXInt, scrolledYInt)) {
         // offset the event to the view's coordinate system
         final float xc = scrolledXFloat - child.getLeft();
         final float yc = scrolledYFloat - child.getTop();
         ev.setLocation(xc, yc);
         if (isTouchEventHandled(child, ev)) return true;
       }
     }
   }
   return false;
 }
Beispiel #12
0
  /** Force show keyboard */
  public void showKeyboard() {
    this.requestFocus();

    Context context = getContext();
    if (Activity.class.isInstance(context)) {
      ((Activity) context)
          .getWindow()
          .setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    }

    // mImm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT | InputMethodManager.SHOW_FORCED);
    // mImm.toggleSoftInput(0, 0);

    // Trick used to create a fake touch event on the editText
    MotionEvent event =
        MotionEvent.obtain(
            0,
            SystemClock.uptimeMillis(),
            MotionEvent.ACTION_DOWN | MotionEvent.ACTION_UP,
            this.getMeasuredWidth(),
            0,
            0);
    this.onTouchEvent(event);
    event.recycle();
  }
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    final int action = event.getAction();
    final float x = event.getX();
    final float y = event.getY();

    switch (action) {
      case MotionEvent.ACTION_DOWN:
        if (mCurrentDownEvent != null) {
          mCurrentDownEvent.recycle();
        }
        mCurrentDownEvent = MotionEvent.obtain(event);
        mAlwaysInTapRegion = true;
        showPress(mCurrentDownEvent, true);
        break;
      case MotionEvent.ACTION_MOVE:
        if (mAlwaysInTapRegion) {
          final int deltaX = (int) (x - mCurrentDownEvent.getX());
          final int deltaY = (int) (y - mCurrentDownEvent.getY());
          int distance = (deltaX * deltaX) + (deltaY * deltaY);
          if (distance > mTouchSlopSquare) {
            mAlwaysInTapRegion = false;
            showPress(mCurrentDownEvent, false);
          }
        }
        break;
      case MotionEvent.ACTION_UP:
        showPress(mCurrentDownEvent, false);
        if (mAlwaysInTapRegion) {
          onTap(mCurrentDownEvent);
        }
    }

    return true;
  }
 private static MotionEvent transformEventOld(MotionEvent paramMotionEvent, Matrix paramMatrix) {
   long l1 = paramMotionEvent.getDownTime();
   long l2 = paramMotionEvent.getEventTime();
   int i = paramMotionEvent.getAction();
   int j = paramMotionEvent.getPointerCount();
   int[] arrayOfInt = getPointerIds(paramMotionEvent);
   MotionEvent.PointerCoords[] arrayOfPointerCoords = getPointerCoords(paramMotionEvent);
   int k = paramMotionEvent.getMetaState();
   float f1 = paramMotionEvent.getXPrecision();
   float f2 = paramMotionEvent.getYPrecision();
   int l = paramMotionEvent.getDeviceId();
   int i1 = paramMotionEvent.getEdgeFlags();
   int i2 = paramMotionEvent.getSource();
   int i3 = paramMotionEvent.getFlags();
   float[] arrayOfFloat = new float[2 * arrayOfPointerCoords.length];
   for (int i4 = 0; i4 < j; ++i4) {
     arrayOfFloat[(i4 * 2)] = arrayOfPointerCoords[i4].x;
     arrayOfFloat[(1 + i4 * 2)] = arrayOfPointerCoords[i4].y;
   }
   paramMatrix.mapPoints(arrayOfFloat);
   for (int i5 = 0; i5 < j; ++i5) {
     arrayOfPointerCoords[i5].x = arrayOfFloat[(i5 * 2)];
     arrayOfPointerCoords[i5].y = arrayOfFloat[(1 + i5 * 2)];
     arrayOfPointerCoords[i5].orientation =
         transformAngle(paramMatrix, arrayOfPointerCoords[i5].orientation);
   }
   return MotionEvent.obtain(
       l1, l2, i, j, arrayOfInt, arrayOfPointerCoords, k, f1, f2, l, i1, i2, i3);
 }
  private List<MotionEvent> getMoveEvents(
      long downTime,
      long startingEVentTime,
      Point origin,
      Point destination,
      int steps,
      long timeBetweenEvents) {
    List<MotionEvent> move = new ArrayList<MotionEvent>();
    MotionEvent event = null;

    float xStep = (destination.x - origin.x) / steps;
    float yStep = (destination.y - origin.y) / steps;
    float x = origin.x;
    float y = origin.y;
    long eventTime = startingEVentTime;

    for (int i = 0; i < steps - 1; i++) {
      x += xStep;
      y += yStep;
      eventTime += timeBetweenEvents;
      event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_MOVE, x, y, 0);
      move.add(event);
    }

    eventTime += timeBetweenEvents;
    move.add(getMotionEvent(downTime, eventTime, MotionEvent.ACTION_MOVE, destination));
    return move;
  }
Beispiel #16
0
 @Override
 public boolean onTouchEvent(MotionEvent event) {
   if (event.getAction() == MotionEvent.ACTION_UP) {
     mMotionEvent = MotionEvent.obtain(event);
   }
   return super.onTouchEvent(event);
 }
  @Override
  public boolean onTouchEvent(@NonNull MotionEvent event) {

    if (!isEnabled() || mNestedScrollInProgress) {
      // Fail fast if we're not in a state where a swipe is possible
      return false;
    }
    final int action = MotionEventCompat.getActionMasked(event);
    final int pointerIndex = MotionEventCompat.findPointerIndex(event, mActivePointerId);
    switch (action) {
      case MotionEvent.ACTION_MOVE:
        releaseEvent();
        mLastMoveEvent = MotionEvent.obtain(event);
        return pointerIndex >= 0 && onMoveTouchEvent(event, pointerIndex);
      case MotionEvent.ACTION_UP:
      case MotionEvent.ACTION_CANCEL:
        if (mActivePointerId == INVALID_POINTER_ID) {
          return false;
        }
        touchUp(event);
        mLastEventOffset = -1;
        mFirstTouchDownPointY = -1;
        mActivePointerId = INVALID_POINTER_ID;
        return false;
    }
    return true;
  }
 protected boolean dispatchTouchEvent(MotionEvent event) {
   int x = (int) event.getX();
   int y = (int) event.getY();
   int action = event.getAction();
   if (mMotionTarget != null) {
     if (action == MotionEvent.ACTION_DOWN) {
       MotionEvent cancel = MotionEvent.obtain(event);
       cancel.setAction(MotionEvent.ACTION_CANCEL);
       dispatchTouchEvent(cancel, x, y, mMotionTarget, false);
       mMotionTarget = null;
     } else {
       dispatchTouchEvent(event, x, y, mMotionTarget, false);
       if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
         mMotionTarget = null;
       }
       return true;
     }
   }
   if (action == MotionEvent.ACTION_DOWN) {
     // in the reverse rendering order
     for (int i = getComponentCount() - 1; i >= 0; --i) {
       GLView component = getComponent(i);
       if (component.getVisibility() != GLView.VISIBLE) continue;
       if (dispatchTouchEvent(event, x, y, component, true)) {
         mMotionTarget = component;
         return true;
       }
     }
   }
   return onTouch(event);
 }
  private void setContext(MotionEvent curr) {
    if (mCurrEvent != null) {
      mCurrEvent.recycle();
    }
    mCurrEvent = MotionEvent.obtain(curr);

    mCurrLen = -1;
    mPrevLen = -1;
    mScaleFactor = -1;

    final MotionEvent prev = mPrevEvent;

    final float px0 = prev.getX(0);
    final float py0 = prev.getY(0);
    final float px1 = prev.getX(1);
    final float py1 = prev.getY(1);
    final float cx0 = curr.getX(0);
    final float cy0 = curr.getY(0);
    final float cx1 = curr.getX(1);
    final float cy1 = curr.getY(1);

    final float pvx = px1 - px0;
    final float pvy = py1 - py0;
    final float cvx = cx1 - cx0;
    final float cvy = cy1 - cy0;
    mPrevFingerDiffX = pvx;
    mPrevFingerDiffY = pvy;
    mCurrFingerDiffX = cvx;
    mCurrFingerDiffY = cvy;

    mTimeDelta = curr.getEventTime() - prev.getEventTime();
    mCurrPressure = curr.getPressure(0) + curr.getPressure(1);
    mPrevPressure = prev.getPressure(0) + prev.getPressure(1);
  }
  private void testSceneTouchWorker(
      final Scene pScene,
      final int pSurfaceTouchX,
      final int pSurfaceTouchY,
      final float pExpectedX,
      final float pExpectedY) {
    pScene.setOnSceneTouchListener(
        new IOnSceneTouchListener() {
          @Override
          public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
            final float actualX = pSceneTouchEvent.getX();
            final float actualY = pSceneTouchEvent.getY();
            Assert.assertEquals(pExpectedX, actualX, DELTA);
            Assert.assertEquals(pExpectedY, actualY, DELTA);
            return true;
          }
        });

    final long uptimeMillis = SystemClock.uptimeMillis();

    final boolean result =
        this.mEngine.onTouch(
            null,
            MotionEvent.obtain(
                uptimeMillis,
                uptimeMillis,
                MotionEvent.ACTION_DOWN,
                pSurfaceTouchX,
                pSurfaceTouchY,
                0));

    Assert.assertTrue(result);
  }
  public void onDragOver(DragObject d) {
    final DragView dragView = d.dragView;
    final int scrollOffset = mScrollView.getScrollY();
    final float[] r = getDragViewVisualCenter(d.x, d.y, d.xOffset, d.yOffset, dragView, null);
    r[0] -= getPaddingLeft();
    r[1] -= getPaddingTop();

    final long downTime = SystemClock.uptimeMillis();
    final MotionEvent translatedEv =
        MotionEvent.obtain(downTime, downTime, MotionEvent.ACTION_MOVE, d.x, d.y, 0);

    if (!mAutoScrollHelper.isEnabled()) {
      mAutoScrollHelper.setEnabled(true);
    }

    final boolean handled = mAutoScrollHelper.onTouch(this, translatedEv);
    translatedEv.recycle();

    if (handled) {
      mReorderAlarm.cancelAlarm();
    } else {
      mTargetCell =
          mContent.findNearestArea((int) r[0], (int) r[1] + scrollOffset, 1, 1, mTargetCell);
      if (isLayoutRtl()) {
        mTargetCell[0] = mContent.getCountX() - mTargetCell[0] - 1;
      }
      if (mTargetCell[0] != mPreviousTargetCell[0] || mTargetCell[1] != mPreviousTargetCell[1]) {
        mReorderAlarm.cancelAlarm();
        mReorderAlarm.setOnAlarmListener(mReorderAlarmListener);
        mReorderAlarm.setAlarm(REORDER_DELAY);
        mPreviousTargetCell[0] = mTargetCell[0];
        mPreviousTargetCell[1] = mTargetCell[1];
      }
    }
  }
Beispiel #22
0
  private void init(
      int viewTag, long timestampMs, TouchEventType touchEventType, MotionEvent motionEventToCopy) {
    super.init(viewTag, timestampMs);

    short coalescingKey = 0;
    int action = (motionEventToCopy.getAction() & MotionEvent.ACTION_MASK);
    switch (action) {
      case MotionEvent.ACTION_DOWN:
        TouchEventCoalescingKeyHelper.addCoalescingKey(motionEventToCopy.getDownTime());
        break;
      case MotionEvent.ACTION_UP:
        TouchEventCoalescingKeyHelper.removeCoalescingKey(motionEventToCopy.getDownTime());
        break;
      case MotionEvent.ACTION_POINTER_DOWN:
      case MotionEvent.ACTION_POINTER_UP:
        TouchEventCoalescingKeyHelper.incrementCoalescingKey(motionEventToCopy.getDownTime());
        break;
      case MotionEvent.ACTION_MOVE:
        coalescingKey =
            TouchEventCoalescingKeyHelper.getCoalescingKey(motionEventToCopy.getDownTime());
        break;
      case MotionEvent.ACTION_CANCEL:
        TouchEventCoalescingKeyHelper.removeCoalescingKey(motionEventToCopy.getDownTime());
        break;
      default:
        throw new RuntimeException("Unhandled MotionEvent action: " + action);
    }
    mTouchEventType = touchEventType;
    mMotionEvent = MotionEvent.obtain(motionEventToCopy);
    mCoalescingKey = coalescingKey;
  }
  private boolean processTouch(MotionEvent event) {
    // Checking if that event was already processed
    // (by onInterceptTouchEvent prior to onTouchEvent)
    long eventTime = event.getEventTime();
    int action = event.getActionMasked();

    if (lastTouchEventTime == eventTime && lastTouchEventAction == action) {
      return lastTouchEventResult;
    }

    lastTouchEventTime = eventTime;
    lastTouchEventAction = action;

    if (getCount() > 0) {
      // Fixing event's Y position due to performed translation
      MotionEvent eventCopy = MotionEvent.obtain(event);
      eventCopy.offsetLocation(0, getTranslationY());
      lastTouchEventResult = gestureDetector.onTouchEvent(eventCopy);
      eventCopy.recycle();
    } else {
      lastTouchEventResult = false;
    }

    if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
      onUpOrCancel();
    }

    return lastTouchEventResult;
  }
  @Override
  protected void handleInProgressEvent(int actionCode, MotionEvent event) {
    switch (actionCode) {
      case MotionEvent.ACTION_UP:
      case MotionEvent.ACTION_CANCEL:
        mListener.onMoveEnd(this);
        resetState();
        break;

      case MotionEvent.ACTION_MOVE:
        updateStateByEvent(event);

        // Only accept the event if our relative pressure is within
        // a certain limit. This can help filter shaky data as a
        // finger is lifted.
        if (mCurrPressure / mPrevPressure > PRESSURE_THRESHOLD) {
          final boolean updatePrevious = mListener.onMove(this);
          if (updatePrevious) {
            mPrevEvent.recycle();
            mPrevEvent = MotionEvent.obtain(event);
          }
        }
        break;
    }
  }
  public void testRun() {
    getInstrumentation().addMonitor(LoginActivity.class.getName(), null, true);
    solo.waitForActivity(LoginActivity.class.getSimpleName(), 200000);
    sleep(10000);

    MotionEvent newTouch;
    while (true) {
      newTouch =
          MotionEvent.obtain(
              SystemClock.uptimeMillis(),
              SystemClock.uptimeMillis(),
              MotionEvent.ACTION_DOWN,
              755,
              1055,
              0);
      getInstrumentation().sendPointerSync(newTouch);
      newTouch =
          MotionEvent.obtain(
              SystemClock.uptimeMillis(),
              SystemClock.uptimeMillis(),
              MotionEvent.ACTION_UP,
              755,
              1055,
              0);
      getInstrumentation().sendPointerSync(newTouch);
      sleep(10000);
      newTouch =
          MotionEvent.obtain(
              SystemClock.uptimeMillis(),
              SystemClock.uptimeMillis(),
              MotionEvent.ACTION_DOWN,
              96,
              156,
              0);
      getInstrumentation().sendPointerSync(newTouch);
      newTouch =
          MotionEvent.obtain(
              SystemClock.uptimeMillis(),
              SystemClock.uptimeMillis(),
              MotionEvent.ACTION_UP,
              96,
              156,
              0);
      getInstrumentation().sendPointerSync(newTouch);
      sleep(10000);
    }
  }
 public boolean dispatchTouchEvent(MotionEvent paramMotionEvent)
 {
   float f1 = paramMotionEvent.getRawX();
   float f2 = paramMotionEvent.getRawY();
   if ((this.f == null) && (this.a != null) && (this.a.getVisibility() == 0) && (this.b != null))
   {
     this.b.getLocationOnScreen(this.g);
     if ((f1 >= this.g[0]) && (f1 < this.g[0] + this.b.getWidth()) && (f2 >= this.g[1]) && (f2 < this.g[1] + this.b.getHeight())) {
       this.f = this.a;
     }
   }
   if ((this.f == null) && (this.a != null) && (this.a.getVisibility() == 0))
   {
     if ((this.d == null) || (this.d.getVisibility() != 0)) {
       break label269;
     }
     this.d.getLocationOnScreen(this.g);
     if (f2 >= this.g[1]) {
       this.f = this.a;
     }
     if (f2 >= this.g[1]) {
       this.f = this.a;
     }
   }
   int i = paramMotionEvent.getAction();
   if (this.f != null)
   {
     localView = this.f;
     if (paramMotionEvent.getAction() == 3)
     {
       localView.dispatchTouchEvent(paramMotionEvent);
       if ((i == 3) || (i == 1)) {
         this.f = null;
       }
     }
   }
   label269:
   while (this.e == null) {
     for (;;)
     {
       View localView;
       return true;
       if ((this.c != null) && (this.c.getVisibility() == 0))
       {
         this.c.getLocationOnScreen(this.g);
         break;
       }
       this.g[0] = 2147483647;
       this.g[1] = 2147483647;
       break;
       MotionEvent localMotionEvent = MotionEvent.obtain(paramMotionEvent);
       localMotionEvent.offsetLocation(getScrollX() - localView.getLeft(), getScrollY() - localView.getTop());
       localView.dispatchTouchEvent(localMotionEvent);
       localMotionEvent.recycle();
     }
   }
   this.e.a(i);
   return true;
 }
  /**
   * Emulates a tap event positioned at the center of the selected view. No-op if no view is
   * selected.
   */
  private void tapSelectedView() {
    if (mSelectedView == null) {
      return;
    }

    final float centerX = mSelectedRect.exactCenterX();
    final float centerY = mSelectedRect.exactCenterY();
    final long currTime = SystemClock.uptimeMillis();

    MotionEvent down =
        MotionEvent.obtain(currTime, currTime, MotionEvent.ACTION_DOWN, centerX, centerY, 0);
    MotionEvent up =
        MotionEvent.obtain(currTime, currTime, MotionEvent.ACTION_UP, centerX, centerY, 0);

    super.dispatchTouchEvent(down);
    super.dispatchTouchEvent(up);
  }
 /** 按下 */
 public void touchDown(int x, int y, int duration) {
   mTouchDownTime = SystemClock.uptimeMillis();
   MotionEvent event =
       MotionEvent.obtain(
           mTouchDownTime, mTouchDownTime + duration, MotionEvent.ACTION_DOWN, x, y, 0);
   event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
   mUiAutomation.injectInputEvent(event, true);
 }
    //  Executes one touch event
    private void executeTouchEvent(
        int eventCode, int xcoord, int ycoord, long timeEventStarted, long timeDepressStarted) {
      MotionEvent me =
          MotionEvent.obtain(timeDepressStarted, timeEventStarted, eventCode, xcoord, ycoord, 0);

      InputManager.getInstance()
          .injectInputEvent(me, InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH);
    }
  /**
   * Verify that the timer of LONG_PRESS will be cancelled when scrolling begins so LONG_PRESS and
   * LONG_TAP won't be triggered.
   *
   * @throws Exception
   */
  @SmallTest
  @Feature({"Gestures"})
  public void testLongPressAndTapCancelWhenScrollBegins() throws Exception {
    final long downTime = SystemClock.uptimeMillis();
    final long eventTime = SystemClock.uptimeMillis();

    GestureRecordingMotionEventDelegate mockDelegate = new GestureRecordingMotionEventDelegate();
    mGestureHandler =
        new ContentViewGestureHandler(
            getInstrumentation().getTargetContext(),
            mockDelegate,
            new MockZoomManager(getInstrumentation().getTargetContext(), null));
    mLongPressDetector = mGestureHandler.getLongPressDetector();

    MotionEvent event = motionEvent(MotionEvent.ACTION_DOWN, downTime, downTime);
    assertTrue(mGestureHandler.onTouchEvent(event));
    assertNotNull(mockDelegate.getMostRecentGestureEvent());
    assertTrue("Should have a pending LONG_PRESS", mLongPressDetector.hasPendingMessage());
    event =
        MotionEvent.obtain(
            downTime,
            eventTime + 5,
            MotionEvent.ACTION_MOVE,
            FAKE_COORD_X * 5,
            FAKE_COORD_Y * 5,
            0);
    assertTrue(mGestureHandler.onTouchEvent(event));
    event =
        MotionEvent.obtain(
            downTime,
            eventTime + 10,
            MotionEvent.ACTION_MOVE,
            FAKE_COORD_X * 10,
            FAKE_COORD_Y * 10,
            0);
    assertTrue(mGestureHandler.onTouchEvent(event));
    assertTrue("Should not have a pending LONG_PRESS", !mLongPressDetector.hasPendingMessage());

    // No LONG_TAP because LONG_PRESS timer is cancelled.
    assertFalse(
        "No LONG_PRESS should be sent",
        mockDelegate.mGestureTypeList.contains(ContentViewGestureHandler.GESTURE_LONG_PRESS));
    assertFalse(
        "No LONG_TAP should be sent",
        mockDelegate.mGestureTypeList.contains(ContentViewGestureHandler.GESTURE_LONG_TAP));
  }