1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.content.ClipData;
20import android.content.ClipDescription;
21import android.os.Parcel;
22import android.os.Parcelable;
23
24import com.android.internal.view.IDragAndDropPermissions;
25
26//TODO: Improve Javadoc
27/**
28 * Represents an event that is sent out by the system at various times during a drag and drop
29 * operation. It is a complex data structure that contains several important pieces of data about
30 * the operation and the underlying data.
31 * <p>
32 *  View objects that receive a DragEvent call {@link #getAction()}, which returns
33 *  an action type that indicates the state of the drag and drop operation. This allows a View
34 *  object to react to a change in state by changing its appearance or performing other actions.
35 *  For example, a View can react to the {@link #ACTION_DRAG_ENTERED} action type by
36 *  by changing one or more colors in its displayed image.
37 * </p>
38 * <p>
39 *  During a drag and drop operation, the system displays an image that the user drags. This image
40 *  is called a drag shadow. Several action types reflect the position of the drag shadow relative
41 *  to the View receiving the event.
42 * </p>
43 * <p>
44 *  Most methods return valid data only for certain event actions. This is summarized in the
45 *  following table. Each possible {@link #getAction()} value is listed in the first column. The
46 *  other columns indicate which method or methods return valid data for that getAction() value:
47 * </p>
48 * <table>
49 *  <tr>
50 *      <th scope="col">getAction() Value</th>
51 *      <th scope="col">getClipDescription()</th>
52 *      <th scope="col">getLocalState()</th>
53 *      <th scope="col">getX()</th>
54 *      <th scope="col">getY()</th>
55 *      <th scope="col">getClipData()</th>
56 *      <th scope="col">getResult()</th>
57 *  </tr>
58 *  <tr>
59 *      <td>ACTION_DRAG_STARTED</td>
60 *      <td style="text-align: center;">X</td>
61 *      <td style="text-align: center;">X</td>
62 *      <td style="text-align: center;">X</td>
63 *      <td style="text-align: center;">X</td>
64 *      <td style="text-align: center;">&nbsp;</td>
65 *      <td style="text-align: center;">&nbsp;</td>
66 *  </tr>
67 *  <tr>
68 *      <td>ACTION_DRAG_ENTERED</td>
69 *      <td style="text-align: center;">X</td>
70 *      <td style="text-align: center;">X</td>
71 *      <td style="text-align: center;">&nbsp;</td>
72 *      <td style="text-align: center;">&nbsp;</td>
73 *      <td style="text-align: center;">&nbsp;</td>
74 *      <td style="text-align: center;">&nbsp;</td>
75 *  </tr>
76 *  <tr>
77 *      <td>ACTION_DRAG_LOCATION</td>
78 *      <td style="text-align: center;">X</td>
79 *      <td style="text-align: center;">X</td>
80 *      <td style="text-align: center;">X</td>
81 *      <td style="text-align: center;">X</td>
82 *      <td style="text-align: center;">&nbsp;</td>
83 *      <td style="text-align: center;">&nbsp;</td>
84 *  </tr>
85 *  <tr>
86 *      <td>ACTION_DRAG_EXITED</td>
87 *      <td style="text-align: center;">X</td>
88 *      <td style="text-align: center;">X</td>
89 *      <td style="text-align: center;">&nbsp;</td>
90 *      <td style="text-align: center;">&nbsp;</td>
91 *      <td style="text-align: center;">&nbsp;</td>
92 *      <td style="text-align: center;">&nbsp;</td>
93 *  </tr>
94 *  <tr>
95 *      <td>ACTION_DROP</td>
96 *      <td style="text-align: center;">X</td>
97 *      <td style="text-align: center;">X</td>
98 *      <td style="text-align: center;">X</td>
99 *      <td style="text-align: center;">X</td>
100 *      <td style="text-align: center;">X</td>
101 *      <td style="text-align: center;">&nbsp;</td>
102 *  </tr>
103 *  <tr>
104 *      <td>ACTION_DRAG_ENDED</td>
105 *      <td style="text-align: center;">&nbsp;</td>
106 *      <td style="text-align: center;">&nbsp;</td>
107 *      <td style="text-align: center;">&nbsp;</td>
108 *      <td style="text-align: center;">&nbsp;</td>
109 *      <td style="text-align: center;">&nbsp;</td>
110 *      <td style="text-align: center;">X</td>
111 *  </tr>
112 * </table>
113 * <p>
114 *  The {@link android.view.DragEvent#getAction()},
115 *  {@link android.view.DragEvent#describeContents()},
116 *  {@link android.view.DragEvent#writeToParcel(Parcel,int)}, and
117 *  {@link android.view.DragEvent#toString()} methods always return valid data.
118 * </p>
119 *
120 * <div class="special reference">
121 * <h3>Developer Guides</h3>
122 * <p>For a guide to implementing drag and drop features, read the
123 * <a href="{@docRoot}guide/topics/ui/drag-drop.html">Drag and Drop</a> developer guide.</p>
124 * </div>
125 */
126public class DragEvent implements Parcelable {
127    private static final boolean TRACK_RECYCLED_LOCATION = false;
128
129    int mAction;
130    float mX, mY;
131    ClipDescription mClipDescription;
132    ClipData mClipData;
133    IDragAndDropPermissions mDragAndDropPermissions;
134
135    Object mLocalState;
136    boolean mDragResult;
137    boolean mEventHandlerWasCalled;
138
139    private DragEvent mNext;
140    private RuntimeException mRecycledLocation;
141    private boolean mRecycled;
142
143    private static final int MAX_RECYCLED = 10;
144    private static final Object gRecyclerLock = new Object();
145    private static int gRecyclerUsed = 0;
146    private static DragEvent gRecyclerTop = null;
147
148    /**
149     * Action constant returned by {@link #getAction()}: Signals the start of a
150     * drag and drop operation. The View should return {@code true} from its
151     * {@link View#onDragEvent(DragEvent) onDragEvent()} handler method or
152     * {@link View.OnDragListener#onDrag(View,DragEvent) OnDragListener.onDrag()} listener
153     * if it can accept a drop. The onDragEvent() or onDrag() methods usually inspect the metadata
154     * from {@link #getClipDescription()} to determine if they can accept the data contained in
155     * this drag. For an operation that doesn't represent data transfer, these methods may
156     * perform other actions to determine whether or not the View should accept the data.
157     * If the View wants to indicate that it is a valid drop target, it can also react by
158     * changing its appearance.
159     * <p>
160     *  Views added or becoming visible for the first time during a drag operation receive this
161     *  event when they are added or becoming visible.
162     * </p>
163     * <p>
164     *  A View only receives further drag events if it returns {@code true} in response to
165     *  ACTION_DRAG_STARTED.
166     * </p>
167     * @see #ACTION_DRAG_ENDED
168     * @see #getX()
169     * @see #getY()
170     */
171    public static final int ACTION_DRAG_STARTED = 1;
172
173    /**
174     * Action constant returned by {@link #getAction()}: Sent to a View after
175     * {@link #ACTION_DRAG_ENTERED} if the drag shadow is still within the View object's bounding
176     * box. The {@link #getX()} and {@link #getY()} methods supply
177     * the X and Y position of of the drag point within the View object's bounding box.
178     * <p>
179     * A View receives an {@link #ACTION_DRAG_ENTERED} event before receiving any
180     * ACTION_DRAG_LOCATION events.
181     * </p>
182     * <p>
183     * The system stops sending ACTION_DRAG_LOCATION events to a View once the user moves the
184     * drag shadow out of the View object's bounding box or into a descendant view that can accept
185     * the data. If the user moves the drag shadow back into the View object's bounding box or out
186     * of a descendant view that can accept the data, the View receives an ACTION_DRAG_ENTERED again
187     * before receiving any more ACTION_DRAG_LOCATION events.
188     * </p>
189     * @see #ACTION_DRAG_ENTERED
190     * @see #getX()
191     * @see #getY()
192     */
193    public static final int ACTION_DRAG_LOCATION = 2;
194
195    /**
196     * Action constant returned by {@link #getAction()}: Signals to a View that the user
197     * has released the drag shadow, and the drag point is within the bounding box of the View and
198     * not within a descendant view that can accept the data.
199     * The View should retrieve the data from the DragEvent by calling {@link #getClipData()}.
200     * The methods {@link #getX()} and {@link #getY()} return the X and Y position of the drop point
201     * within the View object's bounding box.
202     * <p>
203     * The View should return {@code true} from its {@link View#onDragEvent(DragEvent)}
204     * handler or {@link View.OnDragListener#onDrag(View,DragEvent) OnDragListener.onDrag()}
205     * listener if it accepted the drop, and {@code false} if it ignored the drop.
206     * </p>
207     * <p>
208     * The View can also react to this action by changing its appearance.
209     * </p>
210     * @see #getClipData()
211     * @see #getX()
212     * @see #getY()
213     */
214    public static final int ACTION_DROP = 3;
215
216    /**
217     * Action constant returned by {@link #getAction()}:  Signals to a View that the drag and drop
218     * operation has concluded.  A View that changed its appearance during the operation should
219     * return to its usual drawing state in response to this event.
220     * <p>
221     *  All views with listeners that returned boolean <code>true</code> for the ACTION_DRAG_STARTED
222     *  event will receive the ACTION_DRAG_ENDED event even if they are not currently visible when
223     *  the drag ends. Views removed during the drag operation won't receive the ACTION_DRAG_ENDED
224     *  event.
225     * </p>
226     * <p>
227     *  The View object can call {@link #getResult()} to see the result of the operation.
228     *  If a View returned {@code true} in response to {@link #ACTION_DROP}, then
229     *  getResult() returns {@code true}, otherwise it returns {@code false}.
230     * </p>
231     * @see #ACTION_DRAG_STARTED
232     * @see #getResult()
233     */
234    public static final int ACTION_DRAG_ENDED = 4;
235
236    /**
237     * Action constant returned by {@link #getAction()}: Signals to a View that the drag point has
238     * entered the bounding box of the View.
239     * <p>
240     *  If the View can accept a drop, it can react to ACTION_DRAG_ENTERED
241     *  by changing its appearance in a way that tells the user that the View is the current
242     *  drop target.
243     * </p>
244     * The system stops sending ACTION_DRAG_LOCATION events to a View once the user moves the
245     * drag shadow out of the View object's bounding box or into a descendant view that can accept
246     * the data. If the user moves the drag shadow back into the View object's bounding box or out
247     * of a descendant view that can accept the data, the View receives an ACTION_DRAG_ENTERED again
248     * before receiving any more ACTION_DRAG_LOCATION events.
249     * </p>
250     * @see #ACTION_DRAG_ENTERED
251     * @see #ACTION_DRAG_LOCATION
252     */
253    public static final int ACTION_DRAG_ENTERED = 5;
254
255    /**
256     * Action constant returned by {@link #getAction()}: Signals that the user has moved the
257     * drag shadow out of the bounding box of the View or into a descendant view that can accept
258     * the data.
259     * The View can react by changing its appearance in a way that tells the user that
260     * View is no longer the immediate drop target.
261     * <p>
262     *  After the system sends an ACTION_DRAG_EXITED event to the View, the View receives no more
263     *  ACTION_DRAG_LOCATION events until the user drags the drag shadow back over the View.
264     * </p>
265     *
266     */
267     public static final int ACTION_DRAG_EXITED = 6;
268
269    private DragEvent() {
270    }
271
272    private void init(int action, float x, float y, ClipDescription description, ClipData data,
273            IDragAndDropPermissions dragAndDropPermissions, Object localState, boolean result) {
274        mAction = action;
275        mX = x;
276        mY = y;
277        mClipDescription = description;
278        mClipData = data;
279        this.mDragAndDropPermissions = dragAndDropPermissions;
280        mLocalState = localState;
281        mDragResult = result;
282    }
283
284    static DragEvent obtain() {
285        return DragEvent.obtain(0, 0f, 0f, null, null, null, null, false);
286    }
287
288    /** @hide */
289    public static DragEvent obtain(int action, float x, float y, Object localState,
290            ClipDescription description, ClipData data,
291            IDragAndDropPermissions dragAndDropPermissions, boolean result) {
292        final DragEvent ev;
293        synchronized (gRecyclerLock) {
294            if (gRecyclerTop == null) {
295                ev = new DragEvent();
296                ev.init(action, x, y, description, data, dragAndDropPermissions, localState,
297                        result);
298                return ev;
299            }
300            ev = gRecyclerTop;
301            gRecyclerTop = ev.mNext;
302            gRecyclerUsed -= 1;
303        }
304        ev.mRecycledLocation = null;
305        ev.mRecycled = false;
306        ev.mNext = null;
307
308        ev.init(action, x, y, description, data, dragAndDropPermissions, localState, result);
309
310        return ev;
311    }
312
313    /** @hide */
314    public static DragEvent obtain(DragEvent source) {
315        return obtain(source.mAction, source.mX, source.mY, source.mLocalState,
316                source.mClipDescription, source.mClipData, source.mDragAndDropPermissions,
317                source.mDragResult);
318    }
319
320    /**
321     * Inspect the action value of this event.
322     * @return One of the following action constants, in the order in which they usually occur
323     * during a drag and drop operation:
324     * <ul>
325     *  <li>{@link #ACTION_DRAG_STARTED}</li>
326     *  <li>{@link #ACTION_DRAG_ENTERED}</li>
327     *  <li>{@link #ACTION_DRAG_LOCATION}</li>
328     *  <li>{@link #ACTION_DROP}</li>
329     *  <li>{@link #ACTION_DRAG_EXITED}</li>
330     *  <li>{@link #ACTION_DRAG_ENDED}</li>
331     * </ul>
332     */
333    public int getAction() {
334        return mAction;
335    }
336
337    /**
338     * Gets the X coordinate of the drag point. The value is only valid if the event action is
339     * {@link #ACTION_DRAG_STARTED}, {@link #ACTION_DRAG_LOCATION} or {@link #ACTION_DROP}.
340     * @return The current drag point's X coordinate
341     */
342    public float getX() {
343        return mX;
344    }
345
346    /**
347     * Gets the Y coordinate of the drag point. The value is only valid if the event action is
348     * {@link #ACTION_DRAG_STARTED}, {@link #ACTION_DRAG_LOCATION} or {@link #ACTION_DROP}.
349     * @return The current drag point's Y coordinate
350     */
351    public float getY() {
352        return mY;
353    }
354
355    /**
356     * Returns the {@link android.content.ClipData} object sent to the system as part of the call
357     * to
358     * {@link android.view.View#startDrag(ClipData,View.DragShadowBuilder,Object,int) startDrag()}.
359     * This method only returns valid data if the event action is {@link #ACTION_DROP}.
360     * @return The ClipData sent to the system by startDrag().
361     */
362    public ClipData getClipData() {
363        return mClipData;
364    }
365
366    /**
367     * Returns the {@link android.content.ClipDescription} object contained in the
368     * {@link android.content.ClipData} object sent to the system as part of the call to
369     * {@link android.view.View#startDrag(ClipData,View.DragShadowBuilder,Object,int) startDrag()}.
370     * The drag handler or listener for a View can use the metadata in this object to decide if the
371     * View can accept the dragged View object's data.
372     * <p>
373     * This method returns valid data for all event actions except for {@link #ACTION_DRAG_ENDED}.
374     * @return The ClipDescription that was part of the ClipData sent to the system by startDrag().
375     */
376    public ClipDescription getClipDescription() {
377        return mClipDescription;
378    }
379
380    /** @hide */
381    public IDragAndDropPermissions getDragAndDropPermissions() {
382        return mDragAndDropPermissions;
383    }
384
385    /**
386     * Returns the local state object sent to the system as part of the call to
387     * {@link android.view.View#startDrag(ClipData,View.DragShadowBuilder,Object,int) startDrag()}.
388     * The object is intended to provide local information about the drag and drop operation. For
389     * example, it can indicate whether the drag and drop operation is a copy or a move.
390     * <p>
391     * The local state is available only to views in the activity which has started the drag
392     * operation. In all other activities this method will return null
393     * </p>
394     * <p>
395     *  This method returns valid data for all event actions except for {@link #ACTION_DRAG_ENDED}.
396     * </p>
397     * @return The local state object sent to the system by startDrag().
398     */
399    public Object getLocalState() {
400        return mLocalState;
401    }
402
403    /**
404     * <p>
405     * Returns an indication of the result of the drag and drop operation.
406     * This method only returns valid data if the action type is {@link #ACTION_DRAG_ENDED}.
407     * The return value depends on what happens after the user releases the drag shadow.
408     * </p>
409     * <p>
410     * If the user releases the drag shadow on a View that can accept a drop, the system sends an
411     * {@link #ACTION_DROP} event to the View object's drag event listener. If the listener
412     * returns {@code true}, then getResult() will return {@code true}.
413     * If the listener returns {@code false}, then getResult() returns {@code false}.
414     * </p>
415     * <p>
416     * Notice that getResult() also returns {@code false} if no {@link #ACTION_DROP} is sent. This
417     * happens, for example, when the user releases the drag shadow over an area outside of the
418     * application. In this case, the system sends out {@link #ACTION_DRAG_ENDED} for the current
419     * operation, but never sends out {@link #ACTION_DROP}.
420     * </p>
421     * @return {@code true} if a drag event listener returned {@code true} in response to
422     * {@link #ACTION_DROP}. If the system did not send {@link #ACTION_DROP} before
423     * {@link #ACTION_DRAG_ENDED}, or if the listener returned {@code false} in response to
424     * {@link #ACTION_DROP}, then {@code false} is returned.
425     */
426    public boolean getResult() {
427        return mDragResult;
428    }
429
430    /**
431     * Recycle the DragEvent, to be re-used by a later caller.  After calling
432     * this function you must never touch the event again.
433     *
434     * @hide
435     */
436    public final void recycle() {
437        // Ensure recycle is only called once!
438        if (TRACK_RECYCLED_LOCATION) {
439            if (mRecycledLocation != null) {
440                throw new RuntimeException(toString() + " recycled twice!", mRecycledLocation);
441            }
442            mRecycledLocation = new RuntimeException("Last recycled here");
443        } else {
444            if (mRecycled) {
445                throw new RuntimeException(toString() + " recycled twice!");
446            }
447            mRecycled = true;
448        }
449
450        mClipData = null;
451        mClipDescription = null;
452        mLocalState = null;
453        mEventHandlerWasCalled = false;
454
455        synchronized (gRecyclerLock) {
456            if (gRecyclerUsed < MAX_RECYCLED) {
457                gRecyclerUsed++;
458                mNext = gRecyclerTop;
459                gRecyclerTop = this;
460            }
461        }
462    }
463
464    /**
465     * Returns a string containing a concise, human-readable representation of this DragEvent
466     * object.
467     * @return A string representation of the DragEvent object.
468     */
469    @Override
470    public String toString() {
471        return "DragEvent{" + Integer.toHexString(System.identityHashCode(this))
472        + " action=" + mAction + " @ (" + mX + ", " + mY + ") desc=" + mClipDescription
473        + " data=" + mClipData + " local=" + mLocalState + " result=" + mDragResult
474        + "}";
475    }
476
477    /* Parcelable interface */
478
479    /**
480     * Returns information about the {@link android.os.Parcel} representation of this DragEvent
481     * object.
482     * @return Information about the {@link android.os.Parcel} representation.
483     */
484    public int describeContents() {
485        return 0;
486    }
487
488    /**
489     * Creates a {@link android.os.Parcel} object from this DragEvent object.
490     * @param dest A {@link android.os.Parcel} object in which to put the DragEvent object.
491     * @param flags Flags to store in the Parcel.
492     */
493    public void writeToParcel(Parcel dest, int flags) {
494        dest.writeInt(mAction);
495        dest.writeFloat(mX);
496        dest.writeFloat(mY);
497        dest.writeInt(mDragResult ? 1 : 0);
498        if (mClipData == null) {
499            dest.writeInt(0);
500        } else {
501            dest.writeInt(1);
502            mClipData.writeToParcel(dest, flags);
503        }
504        if (mClipDescription == null) {
505            dest.writeInt(0);
506        } else {
507            dest.writeInt(1);
508            mClipDescription.writeToParcel(dest, flags);
509        }
510        if (mDragAndDropPermissions == null) {
511            dest.writeInt(0);
512        } else {
513            dest.writeInt(1);
514            dest.writeStrongBinder(mDragAndDropPermissions.asBinder());
515        }
516    }
517
518    /**
519     * A container for creating a DragEvent from a Parcel.
520     */
521    public static final Parcelable.Creator<DragEvent> CREATOR =
522        new Parcelable.Creator<DragEvent>() {
523        public DragEvent createFromParcel(Parcel in) {
524            DragEvent event = DragEvent.obtain();
525            event.mAction = in.readInt();
526            event.mX = in.readFloat();
527            event.mY = in.readFloat();
528            event.mDragResult = (in.readInt() != 0);
529            if (in.readInt() != 0) {
530                event.mClipData = ClipData.CREATOR.createFromParcel(in);
531            }
532            if (in.readInt() != 0) {
533                event.mClipDescription = ClipDescription.CREATOR.createFromParcel(in);
534            }
535            if (in.readInt() != 0) {
536                event.mDragAndDropPermissions =
537                        IDragAndDropPermissions.Stub.asInterface(in.readStrongBinder());;
538            }
539            return event;
540        }
541
542        public DragEvent[] newArray(int size) {
543            return new DragEvent[size];
544        }
545    };
546}
547