android.content.ClipDescription

Here are the examples of the java api android.content.ClipDescription taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

46 Examples 7

18 Source : ApiHelperForO.java
with BSD 3-Clause "New" or "Revised" License
from ridi

/**
 * See {@link ClipDescription#getTimestamp()}.
 */
public static long getTimestamp(ClipDescription clipDescription) {
    return clipDescription.getTimestamp();
}

18 Source : InputContentInfo.java
with Apache License 2.0
from lulululbj

/**
 * Constructs {@link InputContentInfo} object with additional link URI.
 *
 * @param contentUri Content URI to be exported from the input method.
 * This cannot be {@code null}.
 * @param description A {@link ClipDescription} object that contains the metadata of
 * {@code contentUri} such as MIME type(s). This object cannot be {@code null}. Also
 * {@link ClipDescription#getLabel()} should be describing the content specified by
 * {@code contentUri} for accessibility reasons.
 * @param linkUri An optional {@code http} or {@code https} URI. The editor author may provide
 * a way to navigate the user to the specified web page if this is not {@code null}.
 * @param throwException {@code true} if this method should throw an
 * {@link InvalidParameterException}.
 * @throws InvalidParameterException if any invalid parameter is specified.
 */
private static boolean validateInternal(@NonNull Uri contentUri, @NonNull ClipDescription description, @Nullable Uri linkUri, boolean throwException) {
    if (contentUri == null) {
        if (throwException) {
            throw new NullPointerException("contentUri");
        }
        return false;
    }
    if (description == null) {
        if (throwException) {
            throw new NullPointerException("description");
        }
        return false;
    }
    final String contentUriScheme = contentUri.getScheme();
    if (!"content".equals(contentUriScheme)) {
        if (throwException) {
            throw new InvalidParameterException("contentUri must have content scheme");
        }
        return false;
    }
    if (linkUri != null) {
        final String scheme = linkUri.getScheme();
        if (scheme == null || (!scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https"))) {
            if (throwException) {
                throw new InvalidParameterException("linkUri must have either http or https scheme");
            }
            return false;
        }
    }
    return true;
}

18 Source : functions.java
with MIT License
from karma9874

public String readFromClipboard() {
    final ClipboardManager[] clipboard = new ClipboardManager[1];
    String result = "";
    activity.runOnUiThread(new Runnable() {

        @Override
        public void run() {
            clipboard[0] = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
        }
    });
    try {
        if (clipboard[0].hasPrimaryClip()) {
            android.content.ClipDescription description = clipboard[0].getPrimaryClipDescription();
            android.content.ClipData data = clipboard[0].getPrimaryClip();
            if (data != null && description != null && description.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN))
                result = String.valueOf(data.gereplacedemAt(0).getText());
            if (result.isEmpty()) {
                result = null;
            }
        }
    } catch (NullPointerException e) {
        result = null;
    }
    return result;
}

18 Source : SingleMimeTypeClipDataHelper.java
with Apache License 2.0
from fly7632785

/**
 * @param descript A description of the incoming clipboard data.
 * @return True if the MIME type is found.
 */
@Override
public boolean isBlockData(ClipDescription descript) {
    String[] mimeTypes = (descript == null) ? null : descript.filterMimeTypes(mMimeType);
    return mimeTypes != null && mimeTypes.length > 0;
}

17 Source : Utils.java
with GNU General Public License v3.0
from stanipintjuk

/**
 * Extract and replacedyze clip label from supplied DragEvent <br>
 * Despite doreplacedentation to the contrary, DragEvent.getClipDescription() will
 * return null in the case of DragEvent.ACTION_DRAG_ENDED!
 */
public static String getClipLabel(DragEvent dragEvent, String loggingTag) {
    int dragAction = dragEvent.getAction();
    // Useful for error diagnosis
    String label = "?";
    ClipDescription cd = dragEvent.getClipDescription();
    if (cd == null) {
        if (dragAction == DragEvent.ACTION_DRAG_ENDED)
            return "ACTION_DRAG_ENDED";
    } else {
        label = cd.getLabel().toString();
    }
    return label;
}

17 Source : MainContentProviderBase.java
with GNU General Public License v2.0
from sovworks

protected String[] getContentMimeType(Location loc, String requestedMime) {
    ClipDescription cd = new ClipDescription(null, new String[] { getContentMimeType(loc) });
    return cd.filterMimeTypes(requestedMime);
}

17 Source : Clipboard.java
with BSD 3-Clause "New" or "Revised" License
from ridi

@TargetApi(Build.VERSION_CODES.O)
private void onPrimaryClipTimestampInvalidated() {
    ClipDescription clipDescription = mClipboardManager.getPrimaryClipDescription();
    if (clipDescription == null)
        return;
    long timestamp = ApiHelperForO.getTimestamp(clipDescription);
    ClipboardJni.get().onPrimaryClipTimestampInvalidated(mNativeClipboard, Clipboard.this, timestamp);
}

17 Source : InputContentInfo.java
with Apache License 2.0
from lulululbj

/**
 * A container object with which input methods can send content files to the target application.
 */
public final clreplaced InputContentInfo implements Parcelable {

    /**
     * The content URI that may or may not have a user ID embedded by
     * {@link ContentProvider#maybeAddUserId(Uri, int)}.  This always preserves the exact value
     * specified to a constructor.  In other words, if it had user ID embedded when it was preplaceded
     * to the constructor, it still has the same user ID no matter if it is valid or not.
     */
    @NonNull
    private final Uri mContentUri;

    /**
     * The user ID to which {@link #mContentUri} belongs to.  If {@link #mContentUri} already
     * embedded the user ID when it was specified then this fields has the same user ID.  Otherwise
     * the user ID is determined based on the process ID when the constructor is called.
     *
     * <p>CAUTION: If you received {@link InputContentInfo} from a different process, there is no
     * guarantee that this value is correct and valid.  Never use this for any security purpose</p>
     */
    @UserIdInt
    private final int mContentUriOwnerUserId;

    @NonNull
    private final ClipDescription mDescription;

    @Nullable
    private final Uri mLinkUri;

    @NonNull
    private IInputContentUriToken mUriToken;

    /**
     * Constructs {@link InputContentInfo} object only with mandatory data.
     *
     * @param contentUri Content URI to be exported from the input method.
     * This cannot be {@code null}.
     * @param description A {@link ClipDescription} object that contains the metadata of
     * {@code contentUri} such as MIME type(s). This object cannot be {@code null}. Also
     * {@link ClipDescription#getLabel()} should be describing the content specified by
     * {@code contentUri} for accessibility reasons.
     */
    public InputContentInfo(@NonNull Uri contentUri, @NonNull ClipDescription description) {
        this(contentUri, description, null);
    }

    /**
     * Constructs {@link InputContentInfo} object with additional link URI.
     *
     * @param contentUri Content URI to be exported from the input method.
     * This cannot be {@code null}.
     * @param description A {@link ClipDescription} object that contains the metadata of
     * {@code contentUri} such as MIME type(s). This object cannot be {@code null}. Also
     * {@link ClipDescription#getLabel()} should be describing the content specified by
     * {@code contentUri} for accessibility reasons.
     * @param linkUri An optional {@code http} or {@code https} URI. The editor author may provide
     * a way to navigate the user to the specified web page if this is not {@code null}.
     * @throws InvalidParameterException if any invalid parameter is specified.
     */
    public InputContentInfo(@NonNull Uri contentUri, @NonNull ClipDescription description, @Nullable Uri linkUri) {
        validateInternal(contentUri, description, linkUri, true);
        mContentUri = contentUri;
        mContentUriOwnerUserId = ContentProvider.getUserIdFromUri(mContentUri, UserHandle.myUserId());
        mDescription = description;
        mLinkUri = linkUri;
    }

    /**
     * @return {@code true} if all the fields are valid.
     * @hide
     */
    public boolean validate() {
        return validateInternal(mContentUri, mDescription, mLinkUri, false);
    }

    /**
     * Constructs {@link InputContentInfo} object with additional link URI.
     *
     * @param contentUri Content URI to be exported from the input method.
     * This cannot be {@code null}.
     * @param description A {@link ClipDescription} object that contains the metadata of
     * {@code contentUri} such as MIME type(s). This object cannot be {@code null}. Also
     * {@link ClipDescription#getLabel()} should be describing the content specified by
     * {@code contentUri} for accessibility reasons.
     * @param linkUri An optional {@code http} or {@code https} URI. The editor author may provide
     * a way to navigate the user to the specified web page if this is not {@code null}.
     * @param throwException {@code true} if this method should throw an
     * {@link InvalidParameterException}.
     * @throws InvalidParameterException if any invalid parameter is specified.
     */
    private static boolean validateInternal(@NonNull Uri contentUri, @NonNull ClipDescription description, @Nullable Uri linkUri, boolean throwException) {
        if (contentUri == null) {
            if (throwException) {
                throw new NullPointerException("contentUri");
            }
            return false;
        }
        if (description == null) {
            if (throwException) {
                throw new NullPointerException("description");
            }
            return false;
        }
        final String contentUriScheme = contentUri.getScheme();
        if (!"content".equals(contentUriScheme)) {
            if (throwException) {
                throw new InvalidParameterException("contentUri must have content scheme");
            }
            return false;
        }
        if (linkUri != null) {
            final String scheme = linkUri.getScheme();
            if (scheme == null || (!scheme.equalsIgnoreCase("http") && !scheme.equalsIgnoreCase("https"))) {
                if (throwException) {
                    throw new InvalidParameterException("linkUri must have either http or https scheme");
                }
                return false;
            }
        }
        return true;
    }

    /**
     * @return Content URI with which the content can be obtained.
     */
    @NonNull
    public Uri getContentUri() {
        // Fix up the content URI when and only when the caller's user ID does not match the owner's
        // user ID.
        if (mContentUriOwnerUserId != UserHandle.myUserId()) {
            return ContentProvider.maybeAddUserId(mContentUri, mContentUriOwnerUserId);
        }
        return mContentUri;
    }

    /**
     * @return {@link ClipDescription} object that contains the metadata of {@code #getContentUri()}
     * such as MIME type(s). {@link ClipDescription#getLabel()} can be used for accessibility
     * purpose.
     */
    @NonNull
    public ClipDescription getDescription() {
        return mDescription;
    }

    /**
     * @return An optional {@code http} or {@code https} URI that is related to this content.
     */
    @Nullable
    public Uri getLinkUri() {
        return mLinkUri;
    }

    void setUriToken(IInputContentUriToken token) {
        if (mUriToken != null) {
            throw new IllegalStateException("URI token is already set");
        }
        mUriToken = token;
    }

    /**
     * Requests a temporary read-only access permission for content URI replacedociated with this object.
     *
     * <p>Does nothing if the temporary permission is already granted.</p>
     */
    public void requestPermission() {
        if (mUriToken == null) {
            return;
        }
        try {
            mUriToken.take();
        } catch (RemoteException e) {
            e.rethrowFromSystemServer();
        }
    }

    /**
     * Releases a temporary read-only access permission for content URI replacedociated with this object.
     *
     * <p>Does nothing if the temporary permission is not granted.</p>
     */
    public void releasePermission() {
        if (mUriToken == null) {
            return;
        }
        try {
            mUriToken.release();
        } catch (RemoteException e) {
            e.rethrowFromSystemServer();
        }
    }

    /**
     * Used to package this object into a {@link Parcel}.
     *
     * @param dest The {@link Parcel} to be written.
     * @param flags The flags used for parceling.
     */
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        Uri.writeToParcel(dest, mContentUri);
        dest.writeInt(mContentUriOwnerUserId);
        mDescription.writeToParcel(dest, flags);
        Uri.writeToParcel(dest, mLinkUri);
        if (mUriToken != null) {
            dest.writeInt(1);
            dest.writeStrongBinder(mUriToken.asBinder());
        } else {
            dest.writeInt(0);
        }
    }

    private InputContentInfo(@NonNull Parcel source) {
        mContentUri = Uri.CREATOR.createFromParcel(source);
        mContentUriOwnerUserId = source.readInt();
        mDescription = ClipDescription.CREATOR.createFromParcel(source);
        mLinkUri = Uri.CREATOR.createFromParcel(source);
        if (source.readInt() == 1) {
            mUriToken = IInputContentUriToken.Stub.asInterface(source.readStrongBinder());
        } else {
            mUriToken = null;
        }
    }

    /**
     * Used to make this clreplaced parcelable.
     */
    public static final Parcelable.Creator<InputContentInfo> CREATOR = new Parcelable.Creator<InputContentInfo>() {

        @Override
        public InputContentInfo createFromParcel(Parcel source) {
            return new InputContentInfo(source);
        }

        @Override
        public InputContentInfo[] newArray(int size) {
            return new InputContentInfo[size];
        }
    };

    /**
     * {@inheritDoc}
     */
    @Override
    public int describeContents() {
        return 0;
    }
}

17 Source : DragEvent.java
with Apache License 2.0
from lulululbj

// TODO: Improve Javadoc
/**
 * Represents an event that is sent out by the system at various times during a drag and drop
 * operation. It is a data structure that contains several important pieces of data about
 * the operation and the underlying data.
 * <p>
 *  View objects that receive a DragEvent call {@link #getAction()}, which returns
 *  an action type that indicates the state of the drag and drop operation. This allows a View
 *  object to react to a change in state by changing its appearance or performing other actions.
 *  For example, a View can react to the {@link #ACTION_DRAG_ENTERED} action type by
 *  by changing one or more colors in its displayed image.
 * </p>
 * <p>
 *  During a drag and drop operation, the system displays an image that the user drags. This image
 *  is called a drag shadow. Several action types reflect the position of the drag shadow relative
 *  to the View receiving the event.
 * </p>
 * <p>
 *  Most methods return valid data only for certain event actions. This is summarized in the
 *  following table. Each possible {@link #getAction()} value is listed in the first column. The
 *  other columns indicate which method or methods return valid data for that getAction() value:
 * </p>
 * <table>
 *  <tr>
 *      <th scope="col">getAction() Value</th>
 *      <th scope="col">getClipDescription()</th>
 *      <th scope="col">getLocalState()</th>
 *      <th scope="col">getX()</th>
 *      <th scope="col">getY()</th>
 *      <th scope="col">getClipData()</th>
 *      <th scope="col">getResult()</th>
 *  </tr>
 *  <tr>
 *      <td>ACTION_DRAG_STARTED</td>
 *      <td style="text-align: center;">X</td>
 *      <td style="text-align: center;">X</td>
 *      <td style="text-align: center;">X</td>
 *      <td style="text-align: center;">X</td>
 *      <td style="text-align: center;"> </td>
 *      <td style="text-align: center;"> </td>
 *  </tr>
 *  <tr>
 *      <td>ACTION_DRAG_ENTERED</td>
 *      <td style="text-align: center;">X</td>
 *      <td style="text-align: center;">X</td>
 *      <td style="text-align: center;"> </td>
 *      <td style="text-align: center;"> </td>
 *      <td style="text-align: center;"> </td>
 *      <td style="text-align: center;"> </td>
 *  </tr>
 *  <tr>
 *      <td>ACTION_DRAG_LOCATION</td>
 *      <td style="text-align: center;">X</td>
 *      <td style="text-align: center;">X</td>
 *      <td style="text-align: center;">X</td>
 *      <td style="text-align: center;">X</td>
 *      <td style="text-align: center;"> </td>
 *      <td style="text-align: center;"> </td>
 *  </tr>
 *  <tr>
 *      <td>ACTION_DRAG_EXITED</td>
 *      <td style="text-align: center;">X</td>
 *      <td style="text-align: center;">X</td>
 *      <td style="text-align: center;"> </td>
 *      <td style="text-align: center;"> </td>
 *      <td style="text-align: center;"> </td>
 *      <td style="text-align: center;"> </td>
 *  </tr>
 *  <tr>
 *      <td>ACTION_DROP</td>
 *      <td style="text-align: center;">X</td>
 *      <td style="text-align: center;">X</td>
 *      <td style="text-align: center;">X</td>
 *      <td style="text-align: center;">X</td>
 *      <td style="text-align: center;">X</td>
 *      <td style="text-align: center;"> </td>
 *  </tr>
 *  <tr>
 *      <td>ACTION_DRAG_ENDED</td>
 *      <td style="text-align: center;"> </td>
 *      <td style="text-align: center;">X</td>
 *      <td style="text-align: center;"> </td>
 *      <td style="text-align: center;"> </td>
 *      <td style="text-align: center;"> </td>
 *      <td style="text-align: center;">X</td>
 *  </tr>
 * </table>
 * <p>
 *  The {@link android.view.DragEvent#getAction()},
 *  {@link android.view.DragEvent#getLocalState()}
 *  {@link android.view.DragEvent#describeContents()},
 *  {@link android.view.DragEvent#writeToParcel(Parcel,int)}, and
 *  {@link android.view.DragEvent#toString()} methods always return valid data.
 * </p>
 *
 * <div clreplaced="special reference">
 * <h3>Developer Guides</h3>
 * <p>For a guide to implementing drag and drop features, read the
 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
 * </div>
 */
public clreplaced DragEvent implements Parcelable {

    private static final boolean TRACK_RECYCLED_LOCATION = false;

    int mAction;

    float mX, mY;

    ClipDescription mClipDescription;

    ClipData mClipData;

    IDragAndDropPermissions mDragAndDropPermissions;

    Object mLocalState;

    boolean mDragResult;

    boolean mEventHandlerWasCalled;

    private DragEvent mNext;

    private RuntimeException mRecycledLocation;

    private boolean mRecycled;

    private static final int MAX_RECYCLED = 10;

    private static final Object gRecyclerLock = new Object();

    private static int gRecyclerUsed = 0;

    private static DragEvent gRecyclerTop = null;

    /**
     * Action constant returned by {@link #getAction()}: Signals the start of a
     * drag and drop operation. The View should return {@code true} from its
     * {@link View#onDragEvent(DragEvent) onDragEvent()} handler method or
     * {@link View.OnDragListener#onDrag(View,DragEvent) OnDragListener.onDrag()} listener
     * if it can accept a drop. The onDragEvent() or onDrag() methods usually inspect the metadata
     * from {@link #getClipDescription()} to determine if they can accept the data contained in
     * this drag. For an operation that doesn't represent data transfer, these methods may
     * perform other actions to determine whether or not the View should accept the data.
     * If the View wants to indicate that it is a valid drop target, it can also react by
     * changing its appearance.
     * <p>
     *  Views added or becoming visible for the first time during a drag operation receive this
     *  event when they are added or becoming visible.
     * </p>
     * <p>
     *  A View only receives further drag events for the drag operation if it returns {@code true}
     *  in response to ACTION_DRAG_STARTED.
     * </p>
     * @see #ACTION_DRAG_ENDED
     * @see #getX()
     * @see #getY()
     */
    public static final int ACTION_DRAG_STARTED = 1;

    /**
     * Action constant returned by {@link #getAction()}: Sent to a View after
     * {@link #ACTION_DRAG_ENTERED} while the drag shadow is still within the View object's bounding
     * box, but not within a descendant view that can accept the data. The {@link #getX()} and
     * {@link #getY()} methods supply
     * the X and Y position of of the drag point within the View object's bounding box.
     * <p>
     * A View receives an {@link #ACTION_DRAG_ENTERED} event before receiving any
     * ACTION_DRAG_LOCATION events.
     * </p>
     * <p>
     * The system stops sending ACTION_DRAG_LOCATION events to a View once the user moves the
     * drag shadow out of the View object's bounding box or into a descendant view that can accept
     * the data. If the user moves the drag shadow back into the View object's bounding box or out
     * of a descendant view that can accept the data, the View receives an ACTION_DRAG_ENTERED again
     * before receiving any more ACTION_DRAG_LOCATION events.
     * </p>
     * @see #ACTION_DRAG_ENTERED
     * @see #getX()
     * @see #getY()
     */
    public static final int ACTION_DRAG_LOCATION = 2;

    /**
     * Action constant returned by {@link #getAction()}: Signals to a View that the user
     * has released the drag shadow, and the drag point is within the bounding box of the View and
     * not within a descendant view that can accept the data.
     * The View should retrieve the data from the DragEvent by calling {@link #getClipData()}.
     * The methods {@link #getX()} and {@link #getY()} return the X and Y position of the drop point
     * within the View object's bounding box.
     * <p>
     * The View should return {@code true} from its {@link View#onDragEvent(DragEvent)}
     * handler or {@link View.OnDragListener#onDrag(View,DragEvent) OnDragListener.onDrag()}
     * listener if it accepted the drop, and {@code false} if it ignored the drop.
     * </p>
     * <p>
     * The View can also react to this action by changing its appearance.
     * </p>
     * @see #getClipData()
     * @see #getX()
     * @see #getY()
     */
    public static final int ACTION_DROP = 3;

    /**
     * Action constant returned by {@link #getAction()}:  Signals to a View that the drag and drop
     * operation has concluded.  A View that changed its appearance during the operation should
     * return to its usual drawing state in response to this event.
     * <p>
     *  All views with listeners that returned boolean <code>true</code> for the ACTION_DRAG_STARTED
     *  event will receive the ACTION_DRAG_ENDED event even if they are not currently visible when
     *  the drag ends. Views removed during the drag operation won't receive the ACTION_DRAG_ENDED
     *  event.
     * </p>
     * <p>
     *  The View object can call {@link #getResult()} to see the result of the operation.
     *  If a View returned {@code true} in response to {@link #ACTION_DROP}, then
     *  getResult() returns {@code true}, otherwise it returns {@code false}.
     * </p>
     * @see #ACTION_DRAG_STARTED
     * @see #getResult()
     */
    public static final int ACTION_DRAG_ENDED = 4;

    /**
     * Action constant returned by {@link #getAction()}: Signals to a View that the drag point has
     * entered the bounding box of the View.
     * <p>
     *  If the View can accept a drop, it can react to ACTION_DRAG_ENTERED
     *  by changing its appearance in a way that tells the user that the View is the current
     *  drop target.
     * </p>
     * The system stops sending ACTION_DRAG_LOCATION events to a View once the user moves the
     * drag shadow out of the View object's bounding box or into a descendant view that can accept
     * the data. If the user moves the drag shadow back into the View object's bounding box or out
     * of a descendant view that can accept the data, the View receives an ACTION_DRAG_ENTERED again
     * before receiving any more ACTION_DRAG_LOCATION events.
     * </p>
     * @see #ACTION_DRAG_ENTERED
     * @see #ACTION_DRAG_LOCATION
     */
    public static final int ACTION_DRAG_ENTERED = 5;

    /**
     * Action constant returned by {@link #getAction()}: Signals that the user has moved the
     * drag shadow out of the bounding box of the View or into a descendant view that can accept
     * the data.
     * The View can react by changing its appearance in a way that tells the user that
     * View is no longer the immediate drop target.
     * <p>
     *  After the system sends an ACTION_DRAG_EXITED event to the View, the View receives no more
     *  ACTION_DRAG_LOCATION events until the user drags the drag shadow back over the View.
     * </p>
     */
    public static final int ACTION_DRAG_EXITED = 6;

    private DragEvent() {
    }

    private void init(int action, float x, float y, ClipDescription description, ClipData data, IDragAndDropPermissions dragAndDropPermissions, Object localState, boolean result) {
        mAction = action;
        mX = x;
        mY = y;
        mClipDescription = description;
        mClipData = data;
        this.mDragAndDropPermissions = dragAndDropPermissions;
        mLocalState = localState;
        mDragResult = result;
    }

    static DragEvent obtain() {
        return DragEvent.obtain(0, 0f, 0f, null, null, null, null, false);
    }

    /**
     * @hide
     */
    public static DragEvent obtain(int action, float x, float y, Object localState, ClipDescription description, ClipData data, IDragAndDropPermissions dragAndDropPermissions, boolean result) {
        final DragEvent ev;
        synchronized (gRecyclerLock) {
            if (gRecyclerTop == null) {
                ev = new DragEvent();
                ev.init(action, x, y, description, data, dragAndDropPermissions, localState, result);
                return ev;
            }
            ev = gRecyclerTop;
            gRecyclerTop = ev.mNext;
            gRecyclerUsed -= 1;
        }
        ev.mRecycledLocation = null;
        ev.mRecycled = false;
        ev.mNext = null;
        ev.init(action, x, y, description, data, dragAndDropPermissions, localState, result);
        return ev;
    }

    /**
     * @hide
     */
    public static DragEvent obtain(DragEvent source) {
        return obtain(source.mAction, source.mX, source.mY, source.mLocalState, source.mClipDescription, source.mClipData, source.mDragAndDropPermissions, source.mDragResult);
    }

    /**
     * Inspect the action value of this event.
     * @return One of the following action constants, in the order in which they usually occur
     * during a drag and drop operation:
     * <ul>
     *  <li>{@link #ACTION_DRAG_STARTED}</li>
     *  <li>{@link #ACTION_DRAG_ENTERED}</li>
     *  <li>{@link #ACTION_DRAG_LOCATION}</li>
     *  <li>{@link #ACTION_DROP}</li>
     *  <li>{@link #ACTION_DRAG_EXITED}</li>
     *  <li>{@link #ACTION_DRAG_ENDED}</li>
     * </ul>
     */
    public int getAction() {
        return mAction;
    }

    /**
     * Gets the X coordinate of the drag point. The value is only valid if the event action is
     * {@link #ACTION_DRAG_STARTED}, {@link #ACTION_DRAG_LOCATION} or {@link #ACTION_DROP}.
     * @return The current drag point's X coordinate
     */
    public float getX() {
        return mX;
    }

    /**
     * Gets the Y coordinate of the drag point. The value is only valid if the event action is
     * {@link #ACTION_DRAG_STARTED}, {@link #ACTION_DRAG_LOCATION} or {@link #ACTION_DROP}.
     * @return The current drag point's Y coordinate
     */
    public float getY() {
        return mY;
    }

    /**
     * Returns the {@link android.content.ClipData} object sent to the system as part of the call
     * to
     * {@link android.view.View#startDragAndDrop(ClipData,View.DragShadowBuilder,Object,int)
     * startDragAndDrop()}.
     * This method only returns valid data if the event action is {@link #ACTION_DROP}.
     * @return The ClipData sent to the system by startDragAndDrop().
     */
    public ClipData getClipData() {
        return mClipData;
    }

    /**
     * Returns the {@link android.content.ClipDescription} object contained in the
     * {@link android.content.ClipData} object sent to the system as part of the call to
     * {@link android.view.View#startDragAndDrop(ClipData,View.DragShadowBuilder,Object,int)
     * startDragAndDrop()}.
     * The drag handler or listener for a View can use the metadata in this object to decide if the
     * View can accept the dragged View object's data.
     * <p>
     * This method returns valid data for all event actions except for {@link #ACTION_DRAG_ENDED}.
     * @return The ClipDescription that was part of the ClipData sent to the system by
     *     startDragAndDrop().
     */
    public ClipDescription getClipDescription() {
        return mClipDescription;
    }

    /**
     * @hide
     */
    public IDragAndDropPermissions getDragAndDropPermissions() {
        return mDragAndDropPermissions;
    }

    /**
     * Returns the local state object sent to the system as part of the call to
     * {@link android.view.View#startDragAndDrop(ClipData,View.DragShadowBuilder,Object,int)
     * startDragAndDrop()}.
     * The object is intended to provide local information about the drag and drop operation. For
     * example, it can indicate whether the drag and drop operation is a copy or a move.
     * <p>
     * The local state is available only to views in the activity which has started the drag
     * operation. In all other activities this method will return null
     * </p>
     * <p>
     *  This method returns valid data for all event actions.
     * </p>
     * @return The local state object sent to the system by startDragAndDrop().
     */
    public Object getLocalState() {
        return mLocalState;
    }

    /**
     * <p>
     * Returns an indication of the result of the drag and drop operation.
     * This method only returns valid data if the action type is {@link #ACTION_DRAG_ENDED}.
     * The return value depends on what happens after the user releases the drag shadow.
     * </p>
     * <p>
     * If the user releases the drag shadow on a View that can accept a drop, the system sends an
     * {@link #ACTION_DROP} event to the View object's drag event listener. If the listener
     * returns {@code true}, then getResult() will return {@code true}.
     * If the listener returns {@code false}, then getResult() returns {@code false}.
     * </p>
     * <p>
     * Notice that getResult() also returns {@code false} if no {@link #ACTION_DROP} is sent. This
     * happens, for example, when the user releases the drag shadow over an area outside of the
     * application. In this case, the system sends out {@link #ACTION_DRAG_ENDED} for the current
     * operation, but never sends out {@link #ACTION_DROP}.
     * </p>
     * @return {@code true} if a drag event listener returned {@code true} in response to
     * {@link #ACTION_DROP}. If the system did not send {@link #ACTION_DROP} before
     * {@link #ACTION_DRAG_ENDED}, or if the listener returned {@code false} in response to
     * {@link #ACTION_DROP}, then {@code false} is returned.
     */
    public boolean getResult() {
        return mDragResult;
    }

    /**
     * Recycle the DragEvent, to be re-used by a later caller.  After calling
     * this function you must never touch the event again.
     *
     * @hide
     */
    public final void recycle() {
        // Ensure recycle is only called once!
        if (TRACK_RECYCLED_LOCATION) {
            if (mRecycledLocation != null) {
                throw new RuntimeException(toString() + " recycled twice!", mRecycledLocation);
            }
            mRecycledLocation = new RuntimeException("Last recycled here");
        } else {
            if (mRecycled) {
                throw new RuntimeException(toString() + " recycled twice!");
            }
            mRecycled = true;
        }
        mClipData = null;
        mClipDescription = null;
        mLocalState = null;
        mEventHandlerWasCalled = false;
        synchronized (gRecyclerLock) {
            if (gRecyclerUsed < MAX_RECYCLED) {
                gRecyclerUsed++;
                mNext = gRecyclerTop;
                gRecyclerTop = this;
            }
        }
    }

    /**
     * Returns a string containing a concise, human-readable representation of this DragEvent
     * object.
     * @return A string representation of the DragEvent object.
     */
    @Override
    public String toString() {
        return "DragEvent{" + Integer.toHexString(System.idenreplacedyHashCode(this)) + " action=" + mAction + " @ (" + mX + ", " + mY + ") desc=" + mClipDescription + " data=" + mClipData + " local=" + mLocalState + " result=" + mDragResult + "}";
    }

    /* Parcelable interface */
    /**
     * Returns information about the {@link android.os.Parcel} representation of this DragEvent
     * object.
     * @return Information about the {@link android.os.Parcel} representation.
     */
    public int describeContents() {
        return 0;
    }

    /**
     * Creates a {@link android.os.Parcel} object from this DragEvent object.
     * @param dest A {@link android.os.Parcel} object in which to put the DragEvent object.
     * @param flags Flags to store in the Parcel.
     */
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(mAction);
        dest.writeFloat(mX);
        dest.writeFloat(mY);
        dest.writeInt(mDragResult ? 1 : 0);
        if (mClipData == null) {
            dest.writeInt(0);
        } else {
            dest.writeInt(1);
            mClipData.writeToParcel(dest, flags);
        }
        if (mClipDescription == null) {
            dest.writeInt(0);
        } else {
            dest.writeInt(1);
            mClipDescription.writeToParcel(dest, flags);
        }
        if (mDragAndDropPermissions == null) {
            dest.writeInt(0);
        } else {
            dest.writeInt(1);
            dest.writeStrongBinder(mDragAndDropPermissions.asBinder());
        }
    }

    /**
     * A container for creating a DragEvent from a Parcel.
     */
    public static final Parcelable.Creator<DragEvent> CREATOR = new Parcelable.Creator<DragEvent>() {

        public DragEvent createFromParcel(Parcel in) {
            DragEvent event = DragEvent.obtain();
            event.mAction = in.readInt();
            event.mX = in.readFloat();
            event.mY = in.readFloat();
            event.mDragResult = (in.readInt() != 0);
            if (in.readInt() != 0) {
                event.mClipData = ClipData.CREATOR.createFromParcel(in);
            }
            if (in.readInt() != 0) {
                event.mClipDescription = ClipDescription.CREATOR.createFromParcel(in);
            }
            if (in.readInt() != 0) {
                event.mDragAndDropPermissions = IDragAndDropPermissions.Stub.asInterface(in.readStrongBinder());
                ;
            }
            return event;
        }

        public DragEvent[] newArray(int size) {
            return new DragEvent[size];
        }
    };
}

17 Source : DragEvent.java
with Apache License 2.0
from lulululbj

/**
 * @hide
 */
public static DragEvent obtain(int action, float x, float y, Object localState, ClipDescription description, ClipData data, IDragAndDropPermissions dragAndDropPermissions, boolean result) {
    final DragEvent ev;
    synchronized (gRecyclerLock) {
        if (gRecyclerTop == null) {
            ev = new DragEvent();
            ev.init(action, x, y, description, data, dragAndDropPermissions, localState, result);
            return ev;
        }
        ev = gRecyclerTop;
        gRecyclerTop = ev.mNext;
        gRecyclerUsed -= 1;
    }
    ev.mRecycledLocation = null;
    ev.mRecycled = false;
    ev.mNext = null;
    ev.init(action, x, y, description, data, dragAndDropPermissions, localState, result);
    return ev;
}

17 Source : DragEvent.java
with Apache License 2.0
from lulululbj

private void init(int action, float x, float y, ClipDescription description, ClipData data, IDragAndDropPermissions dragAndDropPermissions, Object localState, boolean result) {
    mAction = action;
    mX = x;
    mY = y;
    mClipDescription = description;
    mClipData = data;
    this.mDragAndDropPermissions = dragAndDropPermissions;
    mLocalState = localState;
    mDragResult = result;
}

17 Source : ClipboardUtils.java
with Apache License 2.0
from Blankj

/**
 * Return the label for clipboard.
 *
 * @return the label for clipboard
 */
public static CharSequence getLabel() {
    ClipboardManager cm = (ClipboardManager) Utils.getApp().getSystemService(Context.CLIPBOARD_SERVICE);
    // noinspection ConstantConditions
    ClipDescription des = cm.getPrimaryClipDescription();
    if (des == null) {
        return "";
    }
    CharSequence label = des.getLabel();
    if (label == null) {
        return "";
    }
    return label;
}

17 Source : ContentInfoCompat.java
with Apache License 2.0
from androidx

private static ClipData buildClipData(ClipDescription description, List<ClipData.Item> items) {
    ClipData clip = new ClipData(new ClipDescription(description), items.get(0));
    for (int i = 1; i < items.size(); i++) {
        clip.addItem(items.get(i));
    }
    return clip;
}

16 Source : DragState.java
with Apache License 2.0
from lulululbj

/**
 * Drag/drop state
 */
clreplaced DragState {

    private static final long MIN_ANIMATION_DURATION_MS = 195;

    private static final long MAX_ANIMATION_DURATION_MS = 375;

    private static final int DRAG_FLAGS_URI_ACCESS = View.DRAG_FLAG_GLOBAL_URI_READ | View.DRAG_FLAG_GLOBAL_URI_WRITE;

    private static final int DRAG_FLAGS_URI_PERMISSIONS = DRAG_FLAGS_URI_ACCESS | View.DRAG_FLAG_GLOBAL_PERSISTABLE_URI_PERMISSION | View.DRAG_FLAG_GLOBAL_PREFIX_URI_PERMISSION;

    // Property names for animations
    private static final String ANIMATED_PROPERTY_X = "x";

    private static final String ANIMATED_PROPERTY_Y = "y";

    private static final String ANIMATED_PROPERTY_ALPHA = "alpha";

    private static final String ANIMATED_PROPERTY_SCALE = "scale";

    final WindowManagerService mService;

    final DragDropController mDragDropController;

    IBinder mToken;

    /**
     * Do not use the variable from the out of animation thread while mAnimator is not null.
     */
    SurfaceControl mSurfaceControl;

    int mFlags;

    IBinder mLocalWin;

    int mPid;

    int mUid;

    int mSourceUserId;

    boolean mCrossProfileCopyAllowed;

    ClipData mData;

    ClipDescription mDataDescription;

    int mTouchSource;

    boolean mDragResult;

    float mOriginalAlpha;

    float mOriginalX, mOriginalY;

    float mCurrentX, mCurrentY;

    float mThumbOffsetX, mThumbOffsetY;

    InputInterceptor mInputInterceptor;

    WindowState mTargetWindow;

    ArrayList<WindowState> mNotifiedWindows;

    boolean mDragInProgress;

    /**
     * Whether if animation is completed. Needs to be volatile to update from the animation thread
     * without having a WM lock.
     */
    volatile boolean mAnimationCompleted = false;

    DisplayContent mDisplayContent;

    @Nullable
    private ValueAnimator mAnimator;

    private final Interpolator mCubicEaseOutInterpolator = new DecelerateInterpolator(1.5f);

    private Point mDisplaySize = new Point();

    DragState(WindowManagerService service, DragDropController controller, IBinder token, SurfaceControl surface, int flags, IBinder localWin) {
        mService = service;
        mDragDropController = controller;
        mToken = token;
        mSurfaceControl = surface;
        mFlags = flags;
        mLocalWin = localWin;
        mNotifiedWindows = new ArrayList<WindowState>();
    }

    /**
     * After calling this, DragDropController#onDragStateClosedLocked is invoked, which causes
     * DragDropController#mDragState becomes null.
     */
    void closeLocked() {
        // Unregister the input interceptor.
        if (mInputInterceptor != null) {
            if (DEBUG_DRAG)
                Slog.d(TAG_WM, "unregistering drag input channel");
            // Input channel should be disposed on the thread where the input is being handled.
            mDragDropController.sendHandlerMessage(MSG_TEAR_DOWN_DRAG_AND_DROP_INPUT, mInputInterceptor);
            mInputInterceptor = null;
            mService.mInputMonitor.updateInputWindowsLw(true);
        }
        // Send drag end broadcast if drag start has been sent.
        if (mDragInProgress) {
            final int myPid = Process.myPid();
            if (DEBUG_DRAG) {
                Slog.d(TAG_WM, "broadcasting DRAG_ENDED");
            }
            for (WindowState ws : mNotifiedWindows) {
                float x = 0;
                float y = 0;
                if (!mDragResult && (ws.mSession.mPid == mPid)) {
                    // Report unconsumed drop location back to the app that started the drag.
                    x = mCurrentX;
                    y = mCurrentY;
                }
                DragEvent evt = DragEvent.obtain(DragEvent.ACTION_DRAG_ENDED, x, y, null, null, null, null, mDragResult);
                try {
                    ws.mClient.dispatchDragEvent(evt);
                } catch (RemoteException e) {
                    Slog.w(TAG_WM, "Unable to drag-end window " + ws);
                }
                // if the current window is in the same process,
                // the dispatch has already recycled the event
                if (myPid != ws.mSession.mPid) {
                    evt.recycle();
                }
            }
            mNotifiedWindows.clear();
            mDragInProgress = false;
        }
        // Take the cursor back if it has been changed.
        if (isFromSource(InputDevice.SOURCE_MOUSE)) {
            mService.restorePointerIconLocked(mDisplayContent, mCurrentX, mCurrentY);
            mTouchSource = 0;
        }
        // Clear the internal variables.
        if (mSurfaceControl != null) {
            mSurfaceControl.destroy();
            mSurfaceControl = null;
        }
        if (mAnimator != null && !mAnimationCompleted) {
            Slog.wtf(TAG_WM, "Unexpectedly destroying mSurfaceControl while animation is running");
        }
        mFlags = 0;
        mLocalWin = null;
        mToken = null;
        mData = null;
        mThumbOffsetX = mThumbOffsetY = 0;
        mNotifiedWindows = null;
        // Notifies the controller that the drag state is closed.
        mDragDropController.onDragStateClosedLocked(this);
    }

    clreplaced InputInterceptor {

        InputChannel mServerChannel, mClientChannel;

        DragInputEventReceiver mInputEventReceiver;

        InputApplicationHandle mDragApplicationHandle;

        InputWindowHandle mDragWindowHandle;

        InputInterceptor(Display display) {
            InputChannel[] channels = InputChannel.openInputChannelPair("drag");
            mServerChannel = channels[0];
            mClientChannel = channels[1];
            mService.mInputManager.registerInputChannel(mServerChannel, null);
            mInputEventReceiver = new DragInputEventReceiver(mClientChannel, mService.mH.getLooper(), mDragDropController);
            mDragApplicationHandle = new InputApplicationHandle(null);
            mDragApplicationHandle.name = "drag";
            mDragApplicationHandle.dispatchingTimeoutNanos = WindowManagerService.DEFAULT_INPUT_DISPATCHING_TIMEOUT_NANOS;
            mDragWindowHandle = new InputWindowHandle(mDragApplicationHandle, null, null, display.getDisplayId());
            mDragWindowHandle.name = "drag";
            mDragWindowHandle.inputChannel = mServerChannel;
            mDragWindowHandle.layer = getDragLayerLocked();
            mDragWindowHandle.layoutParamsFlags = 0;
            mDragWindowHandle.layoutParamsType = WindowManager.LayoutParams.TYPE_DRAG;
            mDragWindowHandle.dispatchingTimeoutNanos = WindowManagerService.DEFAULT_INPUT_DISPATCHING_TIMEOUT_NANOS;
            mDragWindowHandle.visible = true;
            mDragWindowHandle.canReceiveKeys = false;
            mDragWindowHandle.hasFocus = true;
            mDragWindowHandle.hasWallpaper = false;
            mDragWindowHandle.paused = false;
            mDragWindowHandle.ownerPid = Process.myPid();
            mDragWindowHandle.ownerUid = Process.myUid();
            mDragWindowHandle.inputFeatures = 0;
            mDragWindowHandle.scaleFactor = 1.0f;
            // The drag window cannot receive new touches.
            mDragWindowHandle.touchableRegion.setEmpty();
            // The drag window covers the entire display
            mDragWindowHandle.frameLeft = 0;
            mDragWindowHandle.frameTop = 0;
            mDragWindowHandle.frameRight = mDisplaySize.x;
            mDragWindowHandle.frameBottom = mDisplaySize.y;
            // Pause rotations before a drag.
            if (DEBUG_ORIENTATION) {
                Slog.d(TAG_WM, "Pausing rotation during drag");
            }
            mService.pauseRotationLocked();
        }

        void tearDown() {
            mService.mInputManager.unregisterInputChannel(mServerChannel);
            mInputEventReceiver.dispose();
            mInputEventReceiver = null;
            mClientChannel.dispose();
            mServerChannel.dispose();
            mClientChannel = null;
            mServerChannel = null;
            mDragWindowHandle = null;
            mDragApplicationHandle = null;
            // Resume rotations after a drag.
            if (DEBUG_ORIENTATION) {
                Slog.d(TAG_WM, "Resuming rotation after drag");
            }
            mService.resumeRotationLocked();
        }
    }

    InputChannel getInputChannel() {
        return mInputInterceptor == null ? null : mInputInterceptor.mServerChannel;
    }

    InputWindowHandle getInputWindowHandle() {
        return mInputInterceptor == null ? null : mInputInterceptor.mDragWindowHandle;
    }

    /**
     * @param display The Display that the window being dragged is on.
     */
    void register(Display display) {
        display.getRealSize(mDisplaySize);
        if (DEBUG_DRAG)
            Slog.d(TAG_WM, "registering drag input channel");
        if (mInputInterceptor != null) {
            Slog.e(TAG_WM, "Duplicate register of drag input channel");
        } else {
            mInputInterceptor = new InputInterceptor(display);
            mService.mInputMonitor.updateInputWindowsLw(true);
        }
    }

    int getDragLayerLocked() {
        return mService.mPolicy.getWindowLayerFromTypeLw(WindowManager.LayoutParams.TYPE_DRAG) * WindowManagerService.TYPE_LAYER_MULTIPLIER + WindowManagerService.TYPE_LAYER_OFFSET;
    }

    /* call out to each visible window/session informing it about the drag
     */
    void broadcastDragStartedLocked(final float touchX, final float touchY) {
        mOriginalX = mCurrentX = touchX;
        mOriginalY = mCurrentY = touchY;
        // Cache a base-clreplaced instance of the clip metadata so that parceling
        // works correctly in calling out to the apps.
        mDataDescription = (mData != null) ? mData.getDescription() : null;
        mNotifiedWindows.clear();
        mDragInProgress = true;
        mSourceUserId = UserHandle.getUserId(mUid);
        final UserManagerInternal userManager = LocalServices.getService(UserManagerInternal.clreplaced);
        mCrossProfileCopyAllowed = !userManager.getUserRestriction(mSourceUserId, UserManager.DISALLOW_CROSS_PROFILE_COPY_PASTE);
        if (DEBUG_DRAG) {
            Slog.d(TAG_WM, "broadcasting DRAG_STARTED at (" + touchX + ", " + touchY + ")");
        }
        mDisplayContent.forAllWindows(w -> {
            sendDragStartedLocked(w, touchX, touchY, mDataDescription);
        }, false);
    }

    /* helper - send a ACTION_DRAG_STARTED event, if the
     * designated window is potentially a drop recipient.  There are race situations
     * around DRAG_ENDED broadcast, so we make sure that once we've declared that
     * the drag has ended, we never send out another DRAG_STARTED for this drag action.
     *
     * This method clones the 'event' parameter if it's being delivered to the same
     * process, so it's safe for the caller to call recycle() on the event afterwards.
     */
    private void sendDragStartedLocked(WindowState newWin, float touchX, float touchY, ClipDescription desc) {
        if (mDragInProgress && isValidDropTarget(newWin)) {
            DragEvent event = obtainDragEvent(newWin, DragEvent.ACTION_DRAG_STARTED, touchX, touchY, null, desc, null, null, false);
            try {
                newWin.mClient.dispatchDragEvent(event);
                // track each window that we've notified that the drag is starting
                mNotifiedWindows.add(newWin);
            } catch (RemoteException e) {
                Slog.w(TAG_WM, "Unable to drag-start window " + newWin);
            } finally {
                // if the callee was local, the dispatch has already recycled the event
                if (Process.myPid() != newWin.mSession.mPid) {
                    event.recycle();
                }
            }
        }
    }

    private boolean isValidDropTarget(WindowState targetWin) {
        if (targetWin == null) {
            return false;
        }
        if (!targetWin.isPotentialDragTarget()) {
            return false;
        }
        if ((mFlags & View.DRAG_FLAG_GLOBAL) == 0 || !targetWindowSupportsGlobalDrag(targetWin)) {
            // Drag is limited to the current window.
            if (mLocalWin != targetWin.mClient.asBinder()) {
                return false;
            }
        }
        return mCrossProfileCopyAllowed || mSourceUserId == UserHandle.getUserId(targetWin.getOwningUid());
    }

    private boolean targetWindowSupportsGlobalDrag(WindowState targetWin) {
        // Global drags are limited to system windows, and windows for apps that are targeting N and
        // above.
        return targetWin.mAppToken == null || targetWin.mAppToken.mTargetSdk >= Build.VERSION_CODES.N;
    }

    /* helper - send a ACTION_DRAG_STARTED event only if the window has not
     * previously been notified, i.e. it became visible after the drag operation
     * was begun.  This is a rare case.
     */
    void sendDragStartedIfNeededLocked(WindowState newWin) {
        if (mDragInProgress) {
            // If we have sent the drag-started, we needn't do so again
            if (isWindowNotified(newWin)) {
                return;
            }
            if (DEBUG_DRAG) {
                Slog.d(TAG_WM, "need to send DRAG_STARTED to new window " + newWin);
            }
            sendDragStartedLocked(newWin, mCurrentX, mCurrentY, mDataDescription);
        }
    }

    private boolean isWindowNotified(WindowState newWin) {
        for (WindowState ws : mNotifiedWindows) {
            if (ws == newWin) {
                return true;
            }
        }
        return false;
    }

    void endDragLocked() {
        if (mAnimator != null) {
            return;
        }
        if (!mDragResult) {
            mAnimator = createReturnAnimationLocked();
            // Will call closeLocked() when the animation is done.
            return;
        }
        closeLocked();
    }

    void cancelDragLocked() {
        if (mAnimator != null) {
            return;
        }
        if (!mDragInProgress) {
            // This can happen if an app invokes Session#cancelDragAndDrop before
            // Session#performDrag. Reset the drag state without playing the cancel animation
            // because H.DRAG_START_TIMEOUT may be sent to WindowManagerService, which will cause
            // DragState#reset() while playing the cancel animation.
            closeLocked();
            return;
        }
        mAnimator = createCancelAnimationLocked();
    }

    void notifyMoveLocked(float x, float y) {
        if (mAnimator != null) {
            return;
        }
        mCurrentX = x;
        mCurrentY = y;
        // Move the surface to the given touch
        if (SHOW_LIGHT_TRANSACTIONS)
            Slog.i(TAG_WM, ">>> OPEN TRANSACTION notifyMoveLocked");
        mService.openSurfaceTransaction();
        try {
            mSurfaceControl.setPosition(x - mThumbOffsetX, y - mThumbOffsetY);
            if (SHOW_TRANSACTIONS)
                Slog.i(TAG_WM, "  DRAG " + mSurfaceControl + ": pos=(" + (int) (x - mThumbOffsetX) + "," + (int) (y - mThumbOffsetY) + ")");
        } finally {
            mService.closeSurfaceTransaction("notifyMoveLw");
            if (SHOW_LIGHT_TRANSACTIONS)
                Slog.i(TAG_WM, "<<< CLOSE TRANSACTION notifyMoveLocked");
        }
        notifyLocationLocked(x, y);
    }

    void notifyLocationLocked(float x, float y) {
        // Tell the affected window
        WindowState touchedWin = mDisplayContent.getTouchableWinAtPointLocked(x, y);
        if (touchedWin != null && !isWindowNotified(touchedWin)) {
            // The drag point is over a window which was not notified about a drag start.
            // Pretend it's over empty space.
            touchedWin = null;
        }
        try {
            final int myPid = Process.myPid();
            // have we dragged over a new window?
            if ((touchedWin != mTargetWindow) && (mTargetWindow != null)) {
                if (DEBUG_DRAG) {
                    Slog.d(TAG_WM, "sending DRAG_EXITED to " + mTargetWindow);
                }
                // force DRAG_EXITED_EVENT if appropriate
                DragEvent evt = obtainDragEvent(mTargetWindow, DragEvent.ACTION_DRAG_EXITED, 0, 0, null, null, null, null, false);
                mTargetWindow.mClient.dispatchDragEvent(evt);
                if (myPid != mTargetWindow.mSession.mPid) {
                    evt.recycle();
                }
            }
            if (touchedWin != null) {
                if (false && DEBUG_DRAG) {
                    Slog.d(TAG_WM, "sending DRAG_LOCATION to " + touchedWin);
                }
                DragEvent evt = obtainDragEvent(touchedWin, DragEvent.ACTION_DRAG_LOCATION, x, y, null, null, null, null, false);
                touchedWin.mClient.dispatchDragEvent(evt);
                if (myPid != touchedWin.mSession.mPid) {
                    evt.recycle();
                }
            }
        } catch (RemoteException e) {
            Slog.w(TAG_WM, "can't send drag notification to windows");
        }
        mTargetWindow = touchedWin;
    }

    /**
     * Finds the drop target and tells it about the data. If the drop event is not sent to the
     * target, invokes {@code endDragLocked} immediately.
     */
    void notifyDropLocked(float x, float y) {
        if (mAnimator != null) {
            return;
        }
        mCurrentX = x;
        mCurrentY = y;
        final WindowState touchedWin = mDisplayContent.getTouchableWinAtPointLocked(x, y);
        if (!isWindowNotified(touchedWin)) {
            // "drop" outside a valid window -- no recipient to apply a
            // timeout to, and we can send the drag-ended message immediately.
            mDragResult = false;
            endDragLocked();
            return;
        }
        if (DEBUG_DRAG)
            Slog.d(TAG_WM, "sending DROP to " + touchedWin);
        final int targetUserId = UserHandle.getUserId(touchedWin.getOwningUid());
        final DragAndDropPermissionsHandler dragAndDropPermissions;
        if ((mFlags & View.DRAG_FLAG_GLOBAL) != 0 && (mFlags & DRAG_FLAGS_URI_ACCESS) != 0 && mData != null) {
            dragAndDropPermissions = new DragAndDropPermissionsHandler(mData, mUid, touchedWin.getOwningPackage(), mFlags & DRAG_FLAGS_URI_PERMISSIONS, mSourceUserId, targetUserId);
        } else {
            dragAndDropPermissions = null;
        }
        if (mSourceUserId != targetUserId) {
            if (mData != null) {
                mData.fixUris(mSourceUserId);
            }
        }
        final int myPid = Process.myPid();
        final IBinder token = touchedWin.mClient.asBinder();
        final DragEvent evt = obtainDragEvent(touchedWin, DragEvent.ACTION_DROP, x, y, null, null, mData, dragAndDropPermissions, false);
        try {
            touchedWin.mClient.dispatchDragEvent(evt);
            // 5 second timeout for this window to respond to the drop
            mDragDropController.sendTimeoutMessage(MSG_DRAG_END_TIMEOUT, token);
        } catch (RemoteException e) {
            Slog.w(TAG_WM, "can't send drop notification to win " + touchedWin);
            endDragLocked();
        } finally {
            if (myPid != touchedWin.mSession.mPid) {
                evt.recycle();
            }
        }
        mToken = token;
    }

    /**
     * Returns true if it has sent DRAG_STARTED broadcast out but has not been sent DRAG_END
     * broadcast.
     */
    boolean isInProgress() {
        return mDragInProgress;
    }

    private static DragEvent obtainDragEvent(WindowState win, int action, float x, float y, Object localState, ClipDescription description, ClipData data, IDragAndDropPermissions dragAndDropPermissions, boolean result) {
        final float winX = win.translateToWindowX(x);
        final float winY = win.translateToWindowY(y);
        return DragEvent.obtain(action, winX, winY, localState, description, data, dragAndDropPermissions, result);
    }

    private ValueAnimator createReturnAnimationLocked() {
        final ValueAnimator animator = ValueAnimator.ofPropertyValuesHolder(PropertyValuesHolder.ofFloat(ANIMATED_PROPERTY_X, mCurrentX - mThumbOffsetX, mOriginalX - mThumbOffsetX), PropertyValuesHolder.ofFloat(ANIMATED_PROPERTY_Y, mCurrentY - mThumbOffsetY, mOriginalY - mThumbOffsetY), PropertyValuesHolder.ofFloat(ANIMATED_PROPERTY_SCALE, 1, 1), PropertyValuesHolder.ofFloat(ANIMATED_PROPERTY_ALPHA, mOriginalAlpha, mOriginalAlpha / 2));
        final float translateX = mOriginalX - mCurrentX;
        final float translateY = mOriginalY - mCurrentY;
        // Adjust the duration to the travel distance.
        final double travelDistance = Math.sqrt(translateX * translateX + translateY * translateY);
        final double displayDiagonal = Math.sqrt(mDisplaySize.x * mDisplaySize.x + mDisplaySize.y * mDisplaySize.y);
        final long duration = MIN_ANIMATION_DURATION_MS + (long) (travelDistance / displayDiagonal * (MAX_ANIMATION_DURATION_MS - MIN_ANIMATION_DURATION_MS));
        final AnimationListener listener = new AnimationListener();
        animator.setDuration(duration);
        animator.setInterpolator(mCubicEaseOutInterpolator);
        animator.addListener(listener);
        animator.addUpdateListener(listener);
        mService.mAnimationHandler.post(() -> animator.start());
        return animator;
    }

    private ValueAnimator createCancelAnimationLocked() {
        final ValueAnimator animator = ValueAnimator.ofPropertyValuesHolder(PropertyValuesHolder.ofFloat(ANIMATED_PROPERTY_X, mCurrentX - mThumbOffsetX, mCurrentX), PropertyValuesHolder.ofFloat(ANIMATED_PROPERTY_Y, mCurrentY - mThumbOffsetY, mCurrentY), PropertyValuesHolder.ofFloat(ANIMATED_PROPERTY_SCALE, 1, 0), PropertyValuesHolder.ofFloat(ANIMATED_PROPERTY_ALPHA, mOriginalAlpha, 0));
        final AnimationListener listener = new AnimationListener();
        animator.setDuration(MIN_ANIMATION_DURATION_MS);
        animator.setInterpolator(mCubicEaseOutInterpolator);
        animator.addListener(listener);
        animator.addUpdateListener(listener);
        mService.mAnimationHandler.post(() -> animator.start());
        return animator;
    }

    private boolean isFromSource(int source) {
        return (mTouchSource & source) == source;
    }

    void overridePointerIconLocked(int touchSource) {
        mTouchSource = touchSource;
        if (isFromSource(InputDevice.SOURCE_MOUSE)) {
            InputManager.getInstance().setPointerIconType(PointerIcon.TYPE_GRABBING);
        }
    }

    private clreplaced AnimationListener implements ValueAnimator.AnimatorUpdateListener, Animator.AnimatorListener {

        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            try (final SurfaceControl.Transaction transaction = new SurfaceControl.Transaction()) {
                transaction.setPosition(mSurfaceControl, (float) animation.getAnimatedValue(ANIMATED_PROPERTY_X), (float) animation.getAnimatedValue(ANIMATED_PROPERTY_Y));
                transaction.setAlpha(mSurfaceControl, (float) animation.getAnimatedValue(ANIMATED_PROPERTY_ALPHA));
                transaction.setMatrix(mSurfaceControl, (float) animation.getAnimatedValue(ANIMATED_PROPERTY_SCALE), 0, 0, (float) animation.getAnimatedValue(ANIMATED_PROPERTY_SCALE));
                transaction.apply();
            }
        }

        @Override
        public void onAnimationStart(Animator animator) {
        }

        @Override
        public void onAnimationCancel(Animator animator) {
        }

        @Override
        public void onAnimationRepeat(Animator animator) {
        }

        @Override
        public void onAnimationEnd(Animator animator) {
            mAnimationCompleted = true;
            // Updating mDragState requires the WM lock so continues it on the out of
            // AnimationThread.
            mDragDropController.sendHandlerMessage(MSG_ANIMATION_END, null);
        }
    }
}

16 Source : DragState.java
with Apache License 2.0
from lulululbj

private static DragEvent obtainDragEvent(WindowState win, int action, float x, float y, Object localState, ClipDescription description, ClipData data, IDragAndDropPermissions dragAndDropPermissions, boolean result) {
    final float winX = win.translateToWindowX(x);
    final float winY = win.translateToWindowY(y);
    return DragEvent.obtain(action, winX, winY, localState, description, data, dragAndDropPermissions, result);
}

16 Source : RemoteInputCompatJellybean.java
with GNU General Public License v2.0
from Cloudslab

static Bundle getResultsFromIntent(Intent intent) {
    ClipData clipData = intent.getClipData();
    if (clipData == null) {
        return null;
    }
    ClipDescription clipDescription = clipData.getDescription();
    if (clipDescription.hasMimeType("text/vnd.android.intent") && clipDescription.getLabel().equals("android.remoteinput.results")) {
        return (Bundle) clipData.gereplacedemAt(0).getIntent().getExtras().getParcelable("android.remoteinput.resultsData");
    }
    return null;
}

15 Source : Clipboard.java
with BSD 3-Clause "New" or "Revised" License
from ridi

/**
 * Gets the Uri of top item on the primary clip on the Android clipboard if the mime type is
 * image.
 *
 * @return an Uri if mime type is image type, or null if there is no Uri or no entries on the
 *         primary clip.
 */
@Nullable
public Uri getImageUri() {
    // getPrimaryClip() has been observed to throw unexpected exceptions for some devices (see
    // crbug.com/654802).
    try {
        ClipData clipData = mClipboardManager.getPrimaryClip();
        if (clipData == null || clipData.gereplacedemCount() == 0)
            return null;
        ClipDescription description = clipData.getDescription();
        if (description == null || !description.hasMimeType("image/*")) {
            return null;
        }
        return clipData.gereplacedemAt(0).getUri();
    } catch (Exception e) {
        return null;
    }
}

15 Source : ClipboardManagerUtil.java
with GNU General Public License v3.0
from PowerExplorer

public static boolean hasText() {
    android.text.ClipboardManager clipboardManager = ServiceUtil.getClipboardManager();
    if (APILevel.require(11)) {
        ClipboardManager cm = (ClipboardManager) clipboardManager;
        ClipDescription description = cm.getPrimaryClipDescription();
        ClipData clipData = cm.getPrimaryClip();
        return clipData != null && description != null && (description.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN));
    } else {
        return clipboardManager.hasText();
    }
}

15 Source : RemoteInput.java
with Apache License 2.0
from lulululbj

private static Intent getClipDataIntentFromIntent(Intent intent) {
    ClipData clipData = intent.getClipData();
    if (clipData == null) {
        return null;
    }
    ClipDescription clipDescription = clipData.getDescription();
    if (!clipDescription.hasMimeType(ClipDescription.MIMETYPE_TEXT_INTENT)) {
        return null;
    }
    if (!clipDescription.getLabel().equals(RESULTS_CLIP_LABEL)) {
        return null;
    }
    return clipData.gereplacedemAt(0).getIntent();
}

15 Source : BaseItemDragListener.java
with Apache License 2.0
from Launcher3-dev

protected boolean onDragStart(DragEvent event) {
    ClipDescription desc = event.getClipDescription();
    if (desc == null || !desc.hasMimeType(getMimeType())) {
        Log.e(TAG, "Someone started a dragAndDrop before us.");
        return false;
    }
    Point downPos = new Point((int) event.getX(), (int) event.getY());
    DragOptions options = new DragOptions();
    options.systemDndStartPoint = downPos;
    options.preDragCondition = this;
    // We use drag event position as the screenPos for the preview image. Since mPreviewRect
    // already includes the view position relative to the drag event on the source window,
    // and the absolute position (position relative to the screen) of drag event is same
    // across windows, using drag position here give a good estimate for relative position
    // to source window.
    createDragHelper().startDrag(new Rect(mPreviewRect), mPreviewBitmapWidth, mPreviewViewWidth, downPos, this, options);
    mDragStartTime = SystemClock.uptimeMillis();
    return true;
}

15 Source : DropTargetFragment.java
with Apache License 2.0
from googlearchive

/**
 * DragEvents can contain additional data packaged in a {@link PersistableBundle}.
 * Extract the extras from the event and return the String stored for the
 * {@link #EXTRA_IMAGE_INFO} entry.
 */
private String getExtra(DragEvent event) {
    // The extras are contained in the ClipDescription in the DragEvent.
    ClipDescription clipDescription = event.getClipDescription();
    if (clipDescription != null) {
        PersistableBundle extras = clipDescription.getExtras();
        if (extras != null) {
            return extras.getString(EXTRA_IMAGE_INFO);
        }
    }
    return null;
}

15 Source : RemoteInput.java
with Apache License 2.0
from covidsafewatch

private static Intent getClipDataIntentFromIntent(Intent intent) {
    ClipData clipData = intent.getClipData();
    if (clipData == null) {
        return null;
    }
    ClipDescription description = clipData.getDescription();
    if (description.hasMimeType("text/vnd.android.intent") && description.getLabel().equals(RESULTS_CLIP_LABEL)) {
        return clipData.gereplacedemAt(0).getIntent();
    }
    return null;
}

15 Source : InputConnectionCompat.java
with Apache License 2.0
from androidx

static boolean handlePerformPrivateCommand(@Nullable String action, @NonNull Bundle data, @NonNull OnCommitContentListener onCommitContentListener) {
    if (data == null) {
        return false;
    }
    final boolean interop;
    if (TextUtils.equals(COMMIT_CONTENT_ACTION, action)) {
        interop = false;
    } else if (TextUtils.equals(COMMIT_CONTENT_INTEROP_ACTION, action)) {
        interop = true;
    } else {
        return false;
    }
    ResultReceiver resultReceiver = null;
    boolean result = false;
    try {
        resultReceiver = data.getParcelable(interop ? COMMIT_CONTENT_RESULT_INTEROP_RECEIVER_KEY : COMMIT_CONTENT_RESULT_RECEIVER_KEY);
        final Uri contentUri = data.getParcelable(interop ? COMMIT_CONTENT_CONTENT_URI_INTEROP_KEY : COMMIT_CONTENT_CONTENT_URI_KEY);
        final ClipDescription description = data.getParcelable(interop ? COMMIT_CONTENT_DESCRIPTION_INTEROP_KEY : COMMIT_CONTENT_DESCRIPTION_KEY);
        final Uri linkUri = data.getParcelable(interop ? COMMIT_CONTENT_LINK_URI_INTEROP_KEY : COMMIT_CONTENT_LINK_URI_KEY);
        final int flags = data.getInt(interop ? COMMIT_CONTENT_FLAGS_INTEROP_KEY : COMMIT_CONTENT_FLAGS_KEY);
        final Bundle opts = data.getParcelable(interop ? COMMIT_CONTENT_OPTS_INTEROP_KEY : COMMIT_CONTENT_OPTS_KEY);
        if (contentUri != null && description != null) {
            final InputContentInfoCompat inputContentInfo = new InputContentInfoCompat(contentUri, description, linkUri);
            result = onCommitContentListener.onCommitContent(inputContentInfo, flags, opts);
        }
    } finally {
        if (resultReceiver != null) {
            resultReceiver.send(result ? 1 : 0, null);
        }
    }
    return result;
}

15 Source : InputConnectionCompatTest.java
with Apache License 2.0
from androidx

@RunWith(AndroidJUnit4.clreplaced)
@MediumTest
public clreplaced InputConnectionCompatTest extends BaseInstrumentationTestCase<TestActivity> {

    public InputConnectionCompatTest() {
        super(TestActivity.clreplaced);
    }

    private static final String COMMIT_CONTENT_ACTION = "androidx.core.view.inputmethod.InputConnectionCompat.COMMIT_CONTENT";

    private static final String COMMIT_CONTENT_INTEROP_ACTION = "android.support.v13.view.inputmethod.InputConnectionCompat.COMMIT_CONTENT";

    private static final String COMMIT_CONTENT_CONTENT_URI_KEY = "androidx.core.view.inputmethod.InputConnectionCompat.CONTENT_URI";

    private static final String COMMIT_CONTENT_CONTENT_URI_INTEROP_KEY = "android.support.v13.view.inputmethod.InputConnectionCompat.CONTENT_URI";

    private static final String COMMIT_CONTENT_DESCRIPTION_KEY = "androidx.core.view.inputmethod.InputConnectionCompat.CONTENT_DESCRIPTION";

    private static final String COMMIT_CONTENT_DESCRIPTION_INTEROP_KEY = "android.support.v13.view.inputmethod.InputConnectionCompat.CONTENT_DESCRIPTION";

    private static final String COMMIT_CONTENT_LINK_URI_KEY = "androidx.core.view.inputmethod.InputConnectionCompat.CONTENT_LINK_URI";

    private static final String COMMIT_CONTENT_LINK_URI_INTEROP_KEY = "android.support.v13.view.inputmethod.InputConnectionCompat.CONTENT_LINK_URI";

    private static final String COMMIT_CONTENT_OPTS_KEY = "androidx.core.view.inputmethod.InputConnectionCompat.CONTENT_OPTS";

    private static final String COMMIT_CONTENT_OPTS_INTEROP_KEY = "android.support.v13.view.inputmethod.InputConnectionCompat.CONTENT_OPTS";

    private static final String COMMIT_CONTENT_FLAGS_KEY = "androidx.core.view.inputmethod.InputConnectionCompat.CONTENT_FLAGS";

    private static final String COMMIT_CONTENT_FLAGS_INTEROP_KEY = "android.support.v13.view.inputmethod.InputConnectionCompat.CONTENT_FLAGS";

    private static final String[] TEST_MIME_TYPES = new String[] { "image/gif" };

    private static final ClipDescription TEST_CLIP_DESCRIPTION = new ClipDescription("test", TEST_MIME_TYPES);

    private static final Uri TEST_CONTENT_URI = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT).authority("androidx.core.view.inputmethod.test").appendPath("foobar").build();

    private static final Uri TEST_LINK_URI = Uri.parse("https://example.com");

    private static final InputContentInfoCompat TEST_INPUT_CONTENT_INFO = new InputContentInfoCompat(TEST_CONTENT_URI, TEST_CLIP_DESCRIPTION, TEST_LINK_URI);

    private static final Bundle TEST_BUNDLE = new Bundle();

    private static final int TEST_FLAGS = 0;

    @Test
    @SdkSuppress(minSdkVersion = 25)
    public void commitContentPlatformApi() {
        EditorInfo editorInfo = new EditorInfo();
        EditorInfoCompat.setContentMimeTypes(editorInfo, TEST_MIME_TYPES);
        InputConnection ic = mock(InputConnection.clreplaced);
        doReturn(true).when(ic).commitContent(any(InputContentInfo.clreplaced), anyInt(), any(Bundle.clreplaced));
        InputConnectionCompat.commitContent(ic, editorInfo, TEST_INPUT_CONTENT_INFO, TEST_FLAGS, TEST_BUNDLE);
        verify(ic).commitContent(argThat(new ArgumentMatcher<InputContentInfo>() {

            @Override
            public boolean matches(InputContentInfo info) {
                return Objects.equals(TEST_INPUT_CONTENT_INFO.getContentUri(), info.getContentUri()) && Objects.equals(TEST_INPUT_CONTENT_INFO.getDescription(), info.getDescription()) && Objects.equals(TEST_INPUT_CONTENT_INFO.getLinkUri(), info.getLinkUri());
            }
        }), eq(TEST_FLAGS), eq(TEST_BUNDLE));
    }

    @Test
    @SdkSuppress(maxSdkVersion = 24)
    public void commitContentSupportLib() {
        verifyCommitContentCompat(EditorInfoCompat.Protocol.SupportLib);
    }

    @Test
    @SdkSuppress(maxSdkVersion = 24)
    public void commitContentAndroidX100() {
        verifyCommitContentCompat(EditorInfoCompat.Protocol.AndroidX_1_0_0);
    }

    @Test
    @SdkSuppress(maxSdkVersion = 24)
    public void commitContentAndroidX110() {
        verifyCommitContentCompat(EditorInfoCompat.Protocol.AndroidX_1_1_0);
    }

    private void verifyCommitContentCompat(int protocol) {
        EditorInfo editorInfo = EditorInfoTestUtils.createEditorInfoForTest(TEST_MIME_TYPES, protocol);
        InputConnection ic = mock(InputConnection.clreplaced);
        doReturn(true).when(ic).performPrivateCommand(anyString(), any(Bundle.clreplaced));
        InputContentInfoCompat inputContentInfoCompat = new InputContentInfoCompat(TEST_CONTENT_URI, TEST_CLIP_DESCRIPTION, TEST_LINK_URI);
        InputConnectionCompat.commitContent(ic, editorInfo, inputContentInfoCompat, TEST_FLAGS, TEST_BUNDLE);
        verify(ic).performPrivateCommand(eq(getActionName(protocol)), argThat(getBundleMatcher(protocol)));
    }

    private static String getActionName(int protocol) {
        switch(protocol) {
            case EditorInfoCompat.Protocol.SupportLib:
                // If the target app is based on support-lib version, use legacy action name.
                return COMMIT_CONTENT_INTEROP_ACTION;
            case EditorInfoCompat.Protocol.AndroidX_1_0_0:
            case EditorInfoCompat.Protocol.AndroidX_1_1_0:
                // Otherwise, use new action name.
                return COMMIT_CONTENT_ACTION;
            default:
                throw new UnsupportedOperationException("Unsupported protocol=" + protocol);
        }
    }

    private static ArgumentMatcher<Bundle> getBundleMatcher(int protocol) {
        final String contentUriKey;
        final String descriptionKey;
        final String linkUriKey;
        final String optsKey;
        final String flagsKey;
        switch(protocol) {
            case EditorInfoCompat.Protocol.SupportLib:
                // If the target app is based on support-lib version, use legacy keys.
                contentUriKey = COMMIT_CONTENT_CONTENT_URI_INTEROP_KEY;
                descriptionKey = COMMIT_CONTENT_DESCRIPTION_INTEROP_KEY;
                linkUriKey = COMMIT_CONTENT_LINK_URI_INTEROP_KEY;
                flagsKey = COMMIT_CONTENT_FLAGS_INTEROP_KEY;
                optsKey = COMMIT_CONTENT_OPTS_INTEROP_KEY;
                break;
            case EditorInfoCompat.Protocol.AndroidX_1_0_0:
            case EditorInfoCompat.Protocol.AndroidX_1_1_0:
                // Otherwise, use new keys.
                contentUriKey = COMMIT_CONTENT_CONTENT_URI_KEY;
                descriptionKey = COMMIT_CONTENT_DESCRIPTION_KEY;
                linkUriKey = COMMIT_CONTENT_LINK_URI_KEY;
                flagsKey = COMMIT_CONTENT_FLAGS_KEY;
                optsKey = COMMIT_CONTENT_OPTS_KEY;
                break;
            default:
                throw new UnsupportedOperationException("Unsupported protocol=" + protocol);
        }
        return new ArgumentMatcher<Bundle>() {

            @Override
            public boolean matches(Bundle data) {
                final Uri contentUri = data.getParcelable(contentUriKey);
                final ClipDescription description = data.getParcelable(descriptionKey);
                final Uri linkUri = data.getParcelable(linkUriKey);
                final int flags = data.getInt(flagsKey);
                final Bundle opts = data.getParcelable(optsKey);
                return TEST_CONTENT_URI.equals(contentUri) && TEST_CLIP_DESCRIPTION.equals(description) && TEST_LINK_URI.equals(linkUri) && flags == TEST_FLAGS && opts.equals(TEST_BUNDLE);
            }
        };
    }
}

14 Source : ClipboardManagerUtil.java
with GNU General Public License v3.0
from PowerExplorer

public static CharSequence getText() {
    android.text.ClipboardManager clipboardManager = ServiceUtil.getClipboardManager();
    if (APILevel.require(11)) {
        ClipboardManager cm = (ClipboardManager) clipboardManager;
        ClipDescription description = cm.getPrimaryClipDescription();
        ClipData clipData = cm.getPrimaryClip();
        if (clipData != null && description != null && description.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN))
            return clipData.gereplacedemAt(0).getText();
        else
            return null;
    } else {
        return clipboardManager.getText();
    }
}

14 Source : DragState.java
with Apache License 2.0
from lulululbj

/* helper - send a ACTION_DRAG_STARTED event, if the
     * designated window is potentially a drop recipient.  There are race situations
     * around DRAG_ENDED broadcast, so we make sure that once we've declared that
     * the drag has ended, we never send out another DRAG_STARTED for this drag action.
     *
     * This method clones the 'event' parameter if it's being delivered to the same
     * process, so it's safe for the caller to call recycle() on the event afterwards.
     */
private void sendDragStartedLocked(WindowState newWin, float touchX, float touchY, ClipDescription desc) {
    if (mDragInProgress && isValidDropTarget(newWin)) {
        DragEvent event = obtainDragEvent(newWin, DragEvent.ACTION_DRAG_STARTED, touchX, touchY, null, desc, null, null, false);
        try {
            newWin.mClient.dispatchDragEvent(event);
            // track each window that we've notified that the drag is starting
            mNotifiedWindows.add(newWin);
        } catch (RemoteException e) {
            Slog.w(TAG_WM, "Unable to drag-start window " + newWin);
        } finally {
            // if the callee was local, the dispatch has already recycled the event
            if (Process.myPid() != newWin.mSession.mPid) {
                event.recycle();
            }
        }
    }
}

14 Source : OnDragToTrashListenerTest.java
with Apache License 2.0
from fly7632785

/**
 * Unit tests for {@link OnDragToTrashListener}.
 */
public clreplaced OnDragToTrashListenerTest extends BlocklyTestCase {

    @Mock
    BlocklyController mMockController;

    @Mock
    BlockClipDataHelper mMockClipDataHelper;

    @Mock
    RecyclerView mMockToolbox;

    @Mock
    WorkspaceView mMockWorkspaceView;

    @Mock
    Block mDeletableBlock;

    @Mock
    PendingDrag mMockToolboxDrag;

    @Mock
    PendingDrag mMockWorkspaceDrag;

    @Mock
    DragEvent mBlockDragStartFromToolbox;

    @Mock
    DragEvent mBlockDragStartFromWorkspace;

    @Mock
    DragEvent mBlockDragEntered;

    @Mock
    DragEvent mBlockDragLocation;

    @Mock
    DragEvent mBlockDragExited;

    @Mock
    DragEvent mBlockDrop;

    @Mock
    DragEvent mBlockDragEnded;

    @Mock
    DragEvent mRemoteBlockDragEvent;

    @Mock
    DragEvent mOtherDragEvent;

    @Mock
    Block mUnDeletableBlock;

    @Mock
    PendingDrag mUnDeletableBlockDrag;

    @Mock
    DragEvent mUnDeletableBlockDragEvent;

    /**
     * Test instance.
     */
    OnDragToTrashListener mOnDragToTrashListener;

    ClipDescription mBlockClipDescription = new ClipDescription("block", new String[] {});

    ClipDescription mOtherClipDescription = new ClipDescription("other", new String[] {});

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        Mockito.stub(mMockController.getClipDataHelper()).toReturn(mMockClipDataHelper);
        Mockito.when(mMockToolboxDrag.getDragInitiator()).thenReturn(mMockToolbox);
        Mockito.when(mMockToolboxDrag.getRootDraggedBlock()).thenReturn(mDeletableBlock);
        Mockito.when(mMockWorkspaceDrag.getDragInitiator()).thenReturn(mMockWorkspaceView);
        Mockito.when(mMockWorkspaceDrag.getRootDraggedBlock()).thenReturn(mDeletableBlock);
        Mockito.when(mDeletableBlock.isDeletable()).thenReturn(true);
        Mockito.when(mUnDeletableBlock.isDeletable()).thenReturn(false);
        mockDragEvent(mBlockDragStartFromToolbox, DragEvent.ACTION_DRAG_STARTED, true, mMockToolboxDrag);
        mockDragEvent(mBlockDragStartFromWorkspace, DragEvent.ACTION_DRAG_STARTED, true, mMockWorkspaceDrag);
        mockDragEvent(mBlockDragEntered, DragEvent.ACTION_DRAG_ENTERED, true, mMockWorkspaceDrag);
        mockDragEvent(mBlockDragLocation, DragEvent.ACTION_DRAG_LOCATION, true, mMockWorkspaceDrag);
        mockDragEvent(mBlockDragExited, DragEvent.ACTION_DRAG_EXITED, true, mMockWorkspaceDrag);
        mockDragEvent(mBlockDrop, DragEvent.ACTION_DROP, true, mMockWorkspaceDrag);
        mockDragEvent(mBlockDragEnded, DragEvent.ACTION_DRAG_ENDED, true, // End does not reference the local state.
        null);
        mockDragEvent(mRemoteBlockDragEvent, DragEvent.ACTION_DRAG_STARTED, true, null);
        mockDragEvent(mOtherDragEvent, DragEvent.ACTION_DRAG_STARTED, false, null);
        mockDragEvent(mUnDeletableBlockDragEvent, DragEvent.ACTION_DRAG_STARTED, true, mUnDeletableBlockDrag);
        mOnDragToTrashListener = new OnDragToTrashListener(mMockController);
    }

    @Test
    public void testIsTrashableBlock() {
        replacedertThat(mOnDragToTrashListener.isTrashableBlock(mBlockDragStartFromWorkspace)).isTrue();
        replacedertThat(mOnDragToTrashListener.isTrashableBlock(mBlockDragEntered)).isTrue();
        replacedertThat(mOnDragToTrashListener.isTrashableBlock(mBlockDragLocation)).isTrue();
        replacedertThat(mOnDragToTrashListener.isTrashableBlock(mBlockDragExited)).isTrue();
        replacedertThat(mOnDragToTrashListener.isTrashableBlock(mBlockDrop)).isTrue();
        replacedertWithMessage("DRAG_ENDED does not have local state (reference to the WorkspaceView)").that(mOnDragToTrashListener.isTrashableBlock(mBlockDragEnded)).isFalse();
        replacedertWithMessage("Blocks from other activities (no local state) are not trashable.").that(mOnDragToTrashListener.isTrashableBlock(mRemoteBlockDragEvent)).isFalse();
        replacedertWithMessage("DragEvents that are not recognized blocks are not trashable.").that(mOnDragToTrashListener.isTrashableBlock(mOtherDragEvent)).isFalse();
        replacedertWithMessage("DragEvents that are not recognized blocks are not trashable.").that(mOnDragToTrashListener.isTrashableBlock(mOtherDragEvent)).isFalse();
    }

    @Test
    public void testOnDrag() {
        Mockito.verify(mMockController).getClipDataHelper();
        replacedertThat(mOnDragToTrashListener.onDrag(null, mBlockDragStartFromWorkspace)).isTrue();
        Mockito.verifyNoMoreInteractions(mMockController);
        mOnDragToTrashListener.onDrag(null, mBlockDragEntered);
        Mockito.verifyNoMoreInteractions(mMockController);
        mOnDragToTrashListener.onDrag(null, mBlockDragLocation);
        Mockito.verifyNoMoreInteractions(mMockController);
        mOnDragToTrashListener.onDrag(null, mBlockDragExited);
        Mockito.verifyNoMoreInteractions(mMockController);
        replacedertThat(mOnDragToTrashListener.onDrag(null, mBlockDrop)).isTrue();
        Mockito.verify(mMockController).trashRootBlock(Mockito.any(Block.clreplaced));
        mOnDragToTrashListener.onDrag(null, mBlockDragEnded);
        Mockito.verifyNoMoreInteractions(mMockController);
    }

    @Test
    public void testOnDrag_invalid() {
        replacedertWithMessage("Blocks from other activities (no local state) are not trashable.").that(mOnDragToTrashListener.onDrag(null, mRemoteBlockDragEvent)).isFalse();
        replacedertWithMessage("DragEvents that are not recognized blocks are not trashable.").that(mOnDragToTrashListener.onDrag(null, mOtherDragEvent)).isFalse();
        replacedertWithMessage("DragEvents that are not recognized blocks are not trashable.").that(mOnDragToTrashListener.onDrag(null, mUnDeletableBlockDragEvent)).isFalse();
        Mockito.verify(mMockController, Mockito.never()).trashRootBlock(Mockito.any(Block.clreplaced));
    }

    private void mockDragEvent(DragEvent event, int action, boolean isBlock, PendingDrag pending) {
        ClipDescription clipDescrip = isBlock ? mBlockClipDescription : mOtherClipDescription;
        Mockito.when(event.getAction()).thenReturn(action);
        Mockito.when(event.getClipDescription()).thenReturn(clipDescrip);
        Mockito.when(mMockClipDataHelper.isBlockData(clipDescrip)).thenReturn(isBlock);
        Mockito.when(mMockClipDataHelper.getPendingDrag(event)).thenReturn(pending);
    }
}

14 Source : OnDragToTrashListenerTest.java
with Apache License 2.0
from fly7632785

private void mockDragEvent(DragEvent event, int action, boolean isBlock, PendingDrag pending) {
    ClipDescription clipDescrip = isBlock ? mBlockClipDescription : mOtherClipDescription;
    Mockito.when(event.getAction()).thenReturn(action);
    Mockito.when(event.getClipDescription()).thenReturn(clipDescrip);
    Mockito.when(mMockClipDataHelper.isBlockData(clipDescrip)).thenReturn(isBlock);
    Mockito.when(mMockClipDataHelper.getPendingDrag(event)).thenReturn(pending);
}

14 Source : InputConnectionCompat.java
with Apache License 2.0
from covidsafewatch

public static boolean commitContent(InputConnection inputConnection, EditorInfo editorInfo, InputContentInfoCompat inputContentInfoCompat, int i, Bundle bundle) {
    boolean z;
    ClipDescription description = inputContentInfoCompat.getDescription();
    String[] contentMimeTypes = EditorInfoCompat.getContentMimeTypes(editorInfo);
    int length = contentMimeTypes.length;
    boolean z2 = false;
    int i2 = 0;
    while (true) {
        if (i2 >= length) {
            z = false;
            break;
        } else if (description.hasMimeType(contentMimeTypes[i2])) {
            z = true;
            break;
        } else {
            i2++;
        }
    }
    if (!z) {
        return false;
    }
    if (Build.VERSION.SDK_INT >= 25) {
        return inputConnection.commitContent((InputContentInfo) inputContentInfoCompat.unwrap(), i, bundle);
    }
    int protocol = EditorInfoCompat.getProtocol(editorInfo);
    if (protocol == 2) {
        z2 = true;
    } else if (!(protocol == 3 || protocol == 4)) {
        return false;
    }
    Bundle bundle2 = new Bundle();
    bundle2.putParcelable(z2 ? COMMIT_CONTENT_CONTENT_URI_INTEROP_KEY : COMMIT_CONTENT_CONTENT_URI_KEY, inputContentInfoCompat.getContentUri());
    bundle2.putParcelable(z2 ? COMMIT_CONTENT_DESCRIPTION_INTEROP_KEY : COMMIT_CONTENT_DESCRIPTION_KEY, inputContentInfoCompat.getDescription());
    bundle2.putParcelable(z2 ? COMMIT_CONTENT_LINK_URI_INTEROP_KEY : COMMIT_CONTENT_LINK_URI_KEY, inputContentInfoCompat.getLinkUri());
    bundle2.putInt(z2 ? COMMIT_CONTENT_FLAGS_INTEROP_KEY : COMMIT_CONTENT_FLAGS_KEY, i);
    bundle2.putParcelable(z2 ? COMMIT_CONTENT_OPTS_INTEROP_KEY : COMMIT_CONTENT_OPTS_KEY, bundle);
    return inputConnection.performPrivateCommand(z2 ? COMMIT_CONTENT_INTEROP_ACTION : COMMIT_CONTENT_ACTION, bundle2);
}

14 Source : RemoteInput.java
with Apache License 2.0
from androidx

@RequiresApi(16)
private static Intent getClipDataIntentFromIntent(Intent intent) {
    ClipData clipData = intent.getClipData();
    if (clipData == null) {
        return null;
    }
    ClipDescription clipDescription = clipData.getDescription();
    if (!clipDescription.hasMimeType(ClipDescription.MIMETYPE_TEXT_INTENT)) {
        return null;
    }
    if (!clipDescription.getLabel().toString().contentEquals(RemoteInput.RESULTS_CLIP_LABEL)) {
        return null;
    }
    return clipData.gereplacedemAt(0).getIntent();
}

13 Source : ClipboardUtils.java
with MIT License
from AmniX

public static boolean hasText(Context context) {
    ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        ClipDescription description = cm.getPrimaryClipDescription();
        ClipData clipData = cm.getPrimaryClip();
        return clipData != null && description != null && (description.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN));
    } else {
        // noinspection deprecation
        return cm.hasText();
    }
}

13 Source : ClipboardUtils.java
with MIT License
from AmniX

public static CharSequence getText(Context context) {
    ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        ClipDescription description = cm.getPrimaryClipDescription();
        ClipData clipData = cm.getPrimaryClip();
        if (clipData != null && description != null && description.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
            return clipData.gereplacedemAt(0).getText();
        } else {
            return "";
        }
    } else {
        // noinspection deprecation
        return cm.getText();
    }
}

12 Source : ClipboardUtils.java
with GNU General Public License v3.0
from tianma8023

public static void clearClipboard(Context context) {
    ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
    if (cm == null) {
        XLog.e("Clear failed, clipboard manager is null");
        return;
    }
    if (cm.hasPrimaryClip()) {
        ClipDescription cd = cm.getPrimaryClipDescription();
        if (cd != null) {
            if (cd.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
                cm.setPrimaryClip(ClipData.newPlainText("Copy text", ""));
                XLog.i("Clear clipboard succeed");
            }
        }
    }
}

12 Source : ClipboardUtils.java
with GNU General Public License v3.0
from tianma8023

public static void clearClipboard(Context context) {
    ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
    if (cm == null) {
        return;
    }
    if (cm.hasPrimaryClip()) {
        ClipDescription cd = cm.getPrimaryClipDescription();
        if (cd != null) {
            if (cd.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
                cm.setPrimaryClip(ClipData.newPlainText("Copy text", ""));
            }
        }
    }
}

12 Source : InputConnectionCompat.java
with Apache License 2.0
from androidx

/**
 * Calls commitContent API, in a backwards compatible fashion.
 *
 * @param inputConnection {@link InputConnection} with which commitContent API will be called
 * @param editorInfo {@link EditorInfo} replacedociated with the given {@code inputConnection}
 * @param inputContentInfo content information to be preplaceded to the editor
 * @param flags {@code 0} or {@link #INPUT_CONTENT_GRANT_READ_URI_PERMISSION}
 * @param opts optional bundle data. This can be {@code null}
 * @return {@code true} if this request is accepted by the application, no matter if the request
 * is already handled or still being handled in background
 */
public static boolean commitContent(@NonNull InputConnection inputConnection, @NonNull EditorInfo editorInfo, @NonNull InputContentInfoCompat inputContentInfo, int flags, @Nullable Bundle opts) {
    final ClipDescription description = inputContentInfo.getDescription();
    boolean supported = false;
    for (String mimeType : EditorInfoCompat.getContentMimeTypes(editorInfo)) {
        if (description.hasMimeType(mimeType)) {
            supported = true;
            break;
        }
    }
    if (!supported) {
        return false;
    }
    if (Build.VERSION.SDK_INT >= 25) {
        return inputConnection.commitContent((InputContentInfo) inputContentInfo.unwrap(), flags, opts);
    } else {
        final int protocol = EditorInfoCompat.getProtocol(editorInfo);
        final boolean interop;
        switch(protocol) {
            case EditorInfoCompat.Protocol.AndroidX_1_0_0:
            case EditorInfoCompat.Protocol.AndroidX_1_1_0:
                interop = false;
                break;
            case EditorInfoCompat.Protocol.SupportLib:
                interop = true;
                break;
            default:
                // Must not reach here.
                return false;
        }
        final Bundle params = new Bundle();
        params.putParcelable(interop ? COMMIT_CONTENT_CONTENT_URI_INTEROP_KEY : COMMIT_CONTENT_CONTENT_URI_KEY, inputContentInfo.getContentUri());
        params.putParcelable(interop ? COMMIT_CONTENT_DESCRIPTION_INTEROP_KEY : COMMIT_CONTENT_DESCRIPTION_KEY, inputContentInfo.getDescription());
        params.putParcelable(interop ? COMMIT_CONTENT_LINK_URI_INTEROP_KEY : COMMIT_CONTENT_LINK_URI_KEY, inputContentInfo.getLinkUri());
        params.putInt(interop ? COMMIT_CONTENT_FLAGS_INTEROP_KEY : COMMIT_CONTENT_FLAGS_KEY, flags);
        params.putParcelable(interop ? COMMIT_CONTENT_OPTS_INTEROP_KEY : COMMIT_CONTENT_OPTS_KEY, opts);
        // TODO: Support COMMIT_CONTENT_RESULT_RECEIVER_KEY.
        return inputConnection.performPrivateCommand(interop ? COMMIT_CONTENT_INTEROP_ACTION : COMMIT_CONTENT_ACTION, params);
    }
}

11 Source : DragLayer.java
with GNU General Public License v3.0
from LawnchairLauncher

@TargetApi(Build.VERSION_CODES.N)
private void handleSystemDragStart(DragEvent event) {
    if (!Utilities.ATLEAST_NOUGAT) {
        return;
    }
    if (mLauncher.isWorkspaceLocked()) {
        return;
    }
    ClipDescription description = event.getClipDescription();
    if (!description.hasMimeType(ClipDescription.MIMETYPE_TEXT_INTENT)) {
        return;
    }
    ShortcutInfo info = new ShortcutInfo();
    // Set a dummy intent until we get the final value
    info.intent = new Intent();
    // Since we are not going through the workspace for starting the drag, set drag related
    // information on the workspace before starting the drag.
    ExternalDragPreviewProvider previewProvider = new ExternalDragPreviewProvider(mLauncher, info);
    mLauncher.getWorkspace().prepareDragWithProvider(previewProvider);
    DragOptions options = new DragOptions();
    options.systemDndStartPoint = new Point((int) event.getX(), (int) event.getY());
    int halfPadding = previewProvider.previewPadding / 2;
    mDragController.startDrag(Bitmap.createBitmap(1, 1, Config.ARGB_8888), 0, 0, new AnotherWindowDragSource(mLauncher), info, new Point(-halfPadding, halfPadding), previewProvider.getPreviewBounds(), 1f, options);
}

11 Source : DragDriver.java
with GNU General Public License v3.0
from LawnchairLauncher

private boolean updateInfoFromClipData(ClipData data, ClipDescription desc) {
    if (data == null) {
        return false;
    }
    ArrayList<Intent> intents = new ArrayList<>();
    int itemCount = data.gereplacedemCount();
    for (int i = 0; i < itemCount; i++) {
        Intent intent = data.gereplacedemAt(i).getIntent();
        if (intent == null) {
            continue;
        }
        // Give preference to shortcut intents.
        if (!Intent.ACTION_CREATE_SHORTCUT.equals(intent.getAction())) {
            intents.add(intent);
            continue;
        }
        ShortcutInfo info = InstallShortcutReceiver.fromShortcutIntent(mContext, intent);
        if (info != null) {
            mDragObject.dragInfo = info;
            return true;
        }
        return true;
    }
    // Try creating shortcuts just using the intent and label
    Intent fullIntent = new Intent().putExtra(Intent.EXTRA_SHORTCUT_NAME, desc.getLabel());
    for (Intent intent : intents) {
        fullIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
        ShortcutInfo info = InstallShortcutReceiver.fromShortcutIntent(mContext, fullIntent);
        if (info != null) {
            mDragObject.dragInfo = info;
            return true;
        }
    }
    return false;
}

10 Source : EventForwarder.java
with BSD 3-Clause "New" or "Revised" License
from ridi

/**
 * @see View#onDragEvent(DragEvent)
 * @param event {@link DragEvent} instance.
 * @param containerView A view on which the drag event is taking place.
 */
@TargetApi(Build.VERSION_CODES.N)
public boolean onDragEvent(DragEvent event, View containerView) {
    if (mNativeEventForwarder == 0 || Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
        return false;
    }
    ClipDescription clipDescription = event.getClipDescription();
    // text/* will match text/uri-list, text/html, text/plain.
    String[] mimeTypes = clipDescription == null ? new String[0] : clipDescription.filterMimeTypes("text/*");
    if (event.getAction() == DragEvent.ACTION_DRAG_STARTED) {
        // TODO(hush): support dragging more than just text.
        return mimeTypes != null && mimeTypes.length > 0 && mIsDragDropEnabled;
    }
    StringBuilder content = new StringBuilder("");
    if (event.getAction() == DragEvent.ACTION_DROP) {
        // TODO(hush): obtain dragdrop permissions, when dragging files into Chrome/WebView is
        // supported. Not necessary to do so for now, because only text dragging is supported.
        ClipData clipData = event.getClipData();
        final int itemCount = clipData.gereplacedemCount();
        for (int i = 0; i < itemCount; i++) {
            ClipData.Item item = clipData.gereplacedemAt(i);
            content.append(item.coerceToStyledText(containerView.getContext()));
        }
    }
    int[] locationOnScreen = new int[2];
    containerView.getLocationOnScreen(locationOnScreen);
    // All coordinates are in device pixel. Conversion to DIP happens in the native.
    int x = (int) (event.getX() + mCurrentTouchOffsetX);
    int y = (int) (event.getY() + mCurrentTouchOffsetY);
    int screenX = x + locationOnScreen[0];
    int screenY = y + locationOnScreen[1];
    float scale = getEventSourceScaling();
    EventForwarderJni.get().onDragEvent(mNativeEventForwarder, EventForwarder.this, event.getAction(), (int) (x / scale), (int) (y / scale), (int) (screenX / scale), (int) (screenY / scale), mimeTypes, content.toString());
    return true;
}

10 Source : Clipboard.java
with BSD 3-Clause "New" or "Revised" License
from ridi

public String clipDataToHtmlText(ClipData clipData) {
    ClipDescription description = clipData.getDescription();
    if (description.hasMimeType(ClipDescription.MIMETYPE_TEXT_HTML)) {
        return clipData.gereplacedemAt(0).getHtmlText();
    }
    if (description.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
        CharSequence text = clipData.gereplacedemAt(0).getText();
        if (!(text instanceof Spanned))
            return null;
        Spanned spanned = (Spanned) text;
        if (hreplacedtyleSpan(spanned)) {
            return ApiCompatibilityUtils.toHtml(spanned, Html.TO_HTML_PARAGRAPH_LINES_CONSECUTIVE);
        }
    }
    return null;
}

10 Source : ClipboardService.java
with Apache License 2.0
from lulululbj

void setPrimaryClipInternal(PerUserClipboard clipboard, @Nullable ClipData clip, int callingUid) {
    revokeUris(clipboard);
    clipboard.activePermissionOwners.clear();
    if (clip == null && clipboard.primaryClip == null) {
        return;
    }
    clipboard.primaryClip = clip;
    if (clip != null) {
        clipboard.primaryClipUid = callingUid;
    } else {
        clipboard.primaryClipUid = android.os.Process.NOBODY_UID;
    }
    if (clip != null) {
        final ClipDescription description = clip.getDescription();
        if (description != null) {
            description.setTimestamp(System.currentTimeMillis());
        }
    }
    final long ident = Binder.clearCallingIdenreplacedy();
    final int n = clipboard.primaryClipListeners.beginBroadcast();
    try {
        for (int i = 0; i < n; i++) {
            try {
                ListenerInfo li = (ListenerInfo) clipboard.primaryClipListeners.getBroadcastCookie(i);
                if (clipboardAccessAllowed(AppOpsManager.OP_READ_CLIPBOARD, li.mPackageName, li.mUid)) {
                    clipboard.primaryClipListeners.getBroadcasreplacedem(i).dispatchPrimaryClipChanged();
                }
            } catch (RemoteException e) {
            // The RemoteCallbackList will take care of removing
            // the dead object for us.
            }
        }
    } finally {
        clipboard.primaryClipListeners.finishBroadcast();
        Binder.restoreCallingIdenreplacedy(ident);
    }
}

10 Source : SendingAddressesFragment.java
with Apache License 2.0
from guodroid

private Address getAddressFromPrimaryClip() {
    if (!clipboardManager.hasPrimaryClip())
        return null;
    final ClipData clip = clipboardManager.getPrimaryClip();
    final ClipDescription clipDescription = clip.getDescription();
    if (clipDescription.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
        final CharSequence clipText = clip.gereplacedemAt(0).getText();
        if (clipText == null)
            return null;
        try {
            return Address.fromBase58(Constants.NETWORK_PARAMETERS, clipText.toString().trim());
        } catch (final AddressFormatException x) {
            return null;
        }
    } else if (clipDescription.hasMimeType(ClipDescription.MIMETYPE_TEXT_URILIST)) {
        final Uri clipUri = clip.gereplacedemAt(0).getUri();
        if (clipUri == null)
            return null;
        try {
            return new BitcoinURI(clipUri.toString()).getAddress();
        } catch (final BitcoinURIParseException x) {
            return null;
        }
    } else {
        return null;
    }
}

9 Source : VerifyActivity.java
with GNU General Public License v3.0
from snikket-im

private void pastePinFromClipboard() {
    final ClipDescription description = clipboardManager != null ? clipboardManager.getPrimaryClipDescription() : null;
    if (description != null && description.hasMimeType(MIMETYPE_TEXT_PLAIN)) {
        final ClipData primaryClip = clipboardManager.getPrimaryClip();
        if (primaryClip != null && primaryClip.gereplacedemCount() > 0) {
            final CharSequence clip = primaryClip.gereplacedemAt(0).getText();
            if (PinEntryWrapper.isValidPin(clip) && !clip.toString().equals(this.pasted)) {
                this.pasted = clip.toString();
                pinEntryWrapper.setPin(clip.toString());
                final Snackbar snackbar = Snackbar.make(binding.coordinator, R.string.possible_pin, Snackbar.LENGTH_LONG);
                snackbar.setAction(R.string.undo, v -> pinEntryWrapper.clear());
                snackbar.show();
            }
        }
    }
}

7 Source : PinItemDragListener.java
with GNU General Public License v3.0
from enricocid

private boolean onDragStart(DragEvent event) {
    if (!mRequest.isValid()) {
        return false;
    }
    ClipDescription desc = event.getClipDescription();
    if (desc == null || !desc.hasMimeType(getMimeType())) {
        return false;
    }
    final PendingAddItemInfo item;
    if (mRequest.getRequestType() == PinItemRequestCompat.REQUEST_TYPE_SHORTCUT) {
        item = new PendingAddShortcutInfo(new PinShortcutRequestActivityInfo(mRequest, mLauncher));
    } else {
        // mRequest.getRequestType() == PinItemRequestCompat.REQUEST_TYPE_APPWIDGET
        LauncherAppWidgetProviderInfo providerInfo = LauncherAppWidgetProviderInfo.fromProviderInfo(mLauncher, mRequest.getAppWidgetProviderInfo(mLauncher));
        final PinWidgetFlowHandler flowHandler = new PinWidgetFlowHandler(providerInfo, mRequest);
        item = new PendingAddWidgetInfo(providerInfo) {

            @Override
            public WidgetAddFlowHandler getHandler() {
                return flowHandler;
            }
        };
    }
    View view = new View(mLauncher);
    view.setTag(item);
    Point downPos = new Point((int) event.getX(), (int) event.getY());
    DragOptions options = new DragOptions();
    options.systemDndStartPoint = downPos;
    options.preDragCondition = this;
    // We use drag event position as the screenPos for the preview image. Since mPreviewRect
    // already includes the view position relative to the drag event on the source window,
    // and the absolute position (position relative to the screen) of drag event is same
    // across windows, using drag position here give a good estimate for relative position
    // to source window.
    PendingItemDragHelper dragHelper = new PendingItemDragHelper(view);
    if (mRequest.getRequestType() == PinItemRequestCompat.REQUEST_TYPE_APPWIDGET) {
        dragHelper.setPreview(getPreview(mRequest));
    }
    dragHelper.startDrag(new Rect(mPreviewRect), mPreviewBitmapWidth, mPreviewViewWidth, downPos, this, options);
    mDragStartTime = SystemClock.uptimeMillis();
    return true;
}

6 Source : AddItemActivity.java
with Apache License 2.0
from Launcher3-dev

@Override
public boolean onLongClick(View view) {
    // Find the position of the preview relative to the touch location.
    WidgetImageView img = mWidgetCell.getWidgetView();
    // If the ImageView doesn't have a drawable yet, the widget preview hasn't been loaded and
    // we abort the drag.
    if (img.getBitmap() == null) {
        return false;
    }
    Rect bounds = img.getBitmapBounds();
    bounds.offset(img.getLeft() - (int) mLastTouchPos.x, img.getTop() - (int) mLastTouchPos.y);
    // Start home and preplaced the draw request params
    PinItemDragListener listener = new PinItemDragListener(mRequest, bounds, img.getBitmap().getWidth(), img.getWidth());
    Intent homeIntent = listener.addToIntent(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME).setPackage(getPackageName()).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
    listener.initWhenReady();
    startActivity(homeIntent, ActivityOptions.makeCustomAnimation(this, 0, android.R.anim.fade_out).toBundle());
    mFinishOnPause = true;
    // Start a system drag and drop. We use a transparent bitmap as preview for system drag
    // as the preview is handled internally by launcher.
    ClipDescription description = new ClipDescription("", new String[] { listener.getMimeType() });
    ClipData data = new ClipData(description, new ClipData.Item(""));
    view.startDragAndDrop(data, new DragShadowBuilder(view) {

        @Override
        public void onDrawShadow(Canvas canvas) {
        }

        @Override
        public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
            outShadowSize.set(SHADOW_SIZE, SHADOW_SIZE);
            outShadowTouchPoint.set(SHADOW_SIZE / 2, SHADOW_SIZE / 2);
        }
    }, null, View.DRAG_FLAG_GLOBAL);
    return false;
}

3 Source : AddItemActivity.java
with GNU General Public License v3.0
from enricocid

@Override
public boolean onLongClick(View view) {
    // Find the position of the preview relative to the touch location.
    WidgetImageView img = mWidgetCell.getWidgetView();
    // If the ImageView doesn't have a drawable yet, the widget preview hasn't been loaded and
    // we abort the drag.
    if (img.getBitmap() == null) {
        return false;
    }
    Rect bounds = img.getBitmapBounds();
    bounds.offset(img.getLeft() - (int) mLastTouchPos.x, img.getTop() - (int) mLastTouchPos.y);
    // Start home and preplaced the draw request params
    PinItemDragListener listener = new PinItemDragListener(mRequest, bounds, img.getBitmap().getWidth(), img.getWidth());
    Intent homeIntent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME).setPackage(getPackageName()).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK).putExtra(PinItemDragListener.EXTRA_PIN_ITEM_DRAG_LISTENER, listener);
    if (!PreferencesState.isAllowRotationPrefEnabled(this) && (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE && !isInMultiWindowMode())) {
        // If we are starting the drag in landscape even though home is locked in portrait,
        // restart the home activity to temporarily allow rotation.
        homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    }
    startActivity(homeIntent, ActivityOptions.makeCustomAnimation(this, 0, android.R.anim.fade_out).toBundle());
    // Start a system drag and drop. We use a transparent bitmap as preview for system drag
    // as the preview is handled internally by launcher.
    ClipDescription description = new ClipDescription("", new String[] { listener.getMimeType() });
    ClipData data = new ClipData(description, new ClipData.Item(""));
    view.startDragAndDrop(data, new DragShadowBuilder(view) {

        @Override
        public void onDrawShadow(Canvas canvas) {
        }

        @Override
        public void onProvideShadowMetrics(Point outShadowSize, Point outShadowTouchPoint) {
            outShadowSize.set(SHADOW_SIZE, SHADOW_SIZE);
            outShadowTouchPoint.set(SHADOW_SIZE / 2, SHADOW_SIZE / 2);
        }
    }, null, View.DRAG_FLAG_GLOBAL);
    return false;
}

2 Source : ContentCommitComposeEditText.java
with GNU Affero General Public License v3.0
from threema-ch

@Override
public InputConnection onCreateInputConnection(@NonNull EditorInfo editorInfo) {
    final String[] mimeTypes = new String[] { "image/gif", "image/jpeg", "image/png" };
    final InputConnection ic = super.onCreateInputConnection(editorInfo);
    EditorInfoCompat.setContentMimeTypes(editorInfo, mimeTypes);
    final InputConnectionCompat.OnCommitContentListener callback = (inputContentInfo, flags, opts) -> {
        if (BuildCompat.isAtLeastNMR1() && (flags & InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0) {
            try {
                inputContentInfo.requestPermission();
            } catch (Exception e) {
                // return false if failed
                return false;
            }
        }
        if (messageReceiver != null) {
            final Uri uri = inputContentInfo.getContentUri();
            final ClipDescription description = inputContentInfo.getDescription();
            final String mimeType = description.getMimeType(0);
            if (!isSticker(uri, mimeType)) {
                // go through SendMediaActivity if this item does not qualify as a sticker
                ArrayList<MediaItem> mediaItems = new ArrayList<>();
                mediaItems.add(new MediaItem(uri, mimeType, null));
                MessageReceiver[] messageReceivers = new MessageReceiver[1];
                messageReceivers[0] = messageReceiver;
                Intent intent = IntentDataUtil.addMessageReceiversToIntent(new Intent(getContext(), SendMediaActivity.clreplaced), messageReceivers);
                intent.putExtra(SendMediaActivity.EXTRA_MEDIA_ITEMS, mediaItems);
                intent.putExtra(ThreemaApplication.INTENT_DATA_TEXT, messageReceiver.getDisplayName());
                getContext().startActivity(intent);
            } else {
                String caption = null;
                if (messageService != null) {
                    MediaItem mediaItem = new MediaItem(uri, MimeUtil.isGifFile(mimeType) ? MediaItem.TYPE_GIF : MediaItem.TYPE_IMAGE);
                    mediaItem.setCaption(caption);
                    mediaItem.setMimeType(mimeType);
                    mediaItem.setRenderingType(MimeUtil.MIME_TYPE_IMAGE_JPG.equalsIgnoreCase(mimeType) ? FileData.RENDERING_MEDIA : FileData.RENDERING_STICKER);
                    messageService.sendMediaAsync(Collections.singletonList(mediaItem), Collections.singletonList(messageReceiver));
                }
            }
            return true;
        }
        if (BuildCompat.isAtLeastNMR1()) {
            inputContentInfo.releasePermission();
        }
        return false;
    };
    return InputConnectionCompat.createWrapper(ic, editorInfo, callback);
}