summaryrefslogtreecommitdiffstats
path: root/src/com/android/dreams/phototable/PhotoTable.java
blob: 4cf278ce4c8cf3bf01b5cd08fc520a8154e08779 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.dreams.phototable;

import android.service.dreams.DreamService;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PointF;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewPropertyAnimator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import java.util.LinkedList;
import java.util.Random;

/**
 * A surface where photos sit.
 */
public class PhotoTable extends FrameLayout {
    private static final String TAG = "PhotoTable";
    private static final boolean DEBUG = false;

    class Launcher implements Runnable {
        @Override
        public void run() {
            PhotoTable.this.scheduleNext(mDropPeriod);
            PhotoTable.this.launch();
        }
    }

    class FocusReaper implements Runnable {
        @Override
        public void run() {
            PhotoTable.this.clearFocus();
        }
    }

    private static final int MAX_SELECTION_TIME = 10000;
    private static final int MAX_FOCUS_TIME = 5000;
    private static final float EDGE_SWIPE_GUTTER = 0.05f;
    private static final float EDGE_SWIPE_THRESHOLD = 0.25f;
    private static Random sRNG = new Random();

    private final Launcher mLauncher;
    private final FocusReaper mFocusReaper;
    private final LinkedList<View> mOnTable;
    private final int mDropPeriod;
    private final int mFastDropPeriod;
    private final int mNowDropDelay;
    private final float mImageRatio;
    private final float mTableRatio;
    private final float mImageRotationLimit;
    private final float mThrowRotation;
    private final float mThrowSpeed;
    private final boolean mTapToExit;
    private final int mTableCapacity;
    private final int mRedealCount;
    private final int mInset;
    private final PhotoSourcePlexor mPhotoSource;
    private final Resources mResources;
    private final Interpolator mThrowInterpolator;
    private final Interpolator mDropInterpolator;
    final private EdgeSwipeDetector mEdgeSwipeDetector;
    final private DragGestureDetector mDragGestureDetector;
    private DreamService mDream;
    private PhotoLaunchTask mPhotoLaunchTask;
    private boolean mStarted;
    private boolean mIsLandscape;
    private int mLongSide;
    private int mShortSide;
    private int mWidth;
    private int mHeight;
    private View mSelected;
    private long mSelectedTime;
    private View mFocused;
    private long mFocusedTime;
    private int mHighlightColor;

    public PhotoTable(Context context, AttributeSet as) {
        super(context, as);
        mResources = getResources();
        mInset = mResources.getDimensionPixelSize(R.dimen.photo_inset);
        mDropPeriod = mResources.getInteger(R.integer.table_drop_period);
        mFastDropPeriod = mResources.getInteger(R.integer.fast_drop);
        mNowDropDelay = mResources.getInteger(R.integer.now_drop);
        mImageRatio = mResources.getInteger(R.integer.image_ratio) / 1000000f;
        mTableRatio = mResources.getInteger(R.integer.table_ratio) / 1000000f;
        mImageRotationLimit = (float) mResources.getInteger(R.integer.max_image_rotation);
        mThrowSpeed = mResources.getDimension(R.dimen.image_throw_speed);
        mThrowRotation = (float) mResources.getInteger(R.integer.image_throw_rotatioan);
        mTableCapacity = mResources.getInteger(R.integer.table_capacity);
        mRedealCount = mResources.getInteger(R.integer.redeal_count);
        mTapToExit = mResources.getBoolean(R.bool.enable_tap_to_exit);
        mHighlightColor = mResources.getColor(R.color.highlight_color);
        mThrowInterpolator = new SoftLandingInterpolator(
                mResources.getInteger(R.integer.soft_landing_time) / 1000000f,
                mResources.getInteger(R.integer.soft_landing_distance) / 1000000f);
        mDropInterpolator = new DecelerateInterpolator(
                (float) mResources.getInteger(R.integer.drop_deceleration_exponent));
        mOnTable = new LinkedList<View>();
        mPhotoSource = new PhotoSourcePlexor(getContext(),
                getContext().getSharedPreferences(PhotoTableDreamSettings.PREFS_NAME, 0));
        mLauncher = new Launcher();
        mFocusReaper = new FocusReaper();
        mEdgeSwipeDetector = new EdgeSwipeDetector(context, this);
        mDragGestureDetector = new DragGestureDetector(context, this);
        mStarted = false;
    }


    public void setDream(DreamService dream) {
        mDream = dream;
    }

    public boolean hasSelection() {
        return mSelected != null;
    }

    public View getSelected() {
        return mSelected;
    }

    public void clearSelection() {
        if (hasSelection()) {
            dropOnTable(getSelected());
        }
        mSelected = null;
    }

    public void setSelection(View selected) {
        assert(selected != null);
        clearSelection();
        mSelected = selected;
        mSelectedTime = System.currentTimeMillis();
        moveToTopOfPile(selected);
        pickUp(selected);
    }

    public boolean hasFocus() {
        return mFocused != null;
    }

    public View getFocused() {
        return mFocused;
    }

    public void clearFocus() {
        if (hasFocus()) {
            setHighlight(getFocused(), false);
        }
        mFocused = null;
    }

    public void setFocus(View focus) {
        assert(focus != null);
        clearFocus();
        mFocused = focus;
        mFocusedTime = System.currentTimeMillis();
        moveToTopOfPile(focus);
        setHighlight(focus, true);
        scheduleFocusReaper(MAX_FOCUS_TIME);
    }

    static float lerp(float a, float b, float f) {
        return (b-a)*f + a;
    }

    static float randfrange(float a, float b) {
        return lerp(a, b, sRNG.nextFloat());
    }

    static PointF randFromCurve(float t, PointF[] v) {
        PointF p = new PointF();
        if (v.length == 4 && t >= 0f && t <= 1f) {
            float a = (float) Math.pow(1f-t, 3f);
            float b = (float) Math.pow(1f-t, 2f) * t;
            float c = (1f-t) * (float) Math.pow(t, 2f);
            float d = (float) Math.pow(t, 3f);

            p.x = a * v[0].x + 3 * b * v[1].x + 3 * c * v[2].x + d * v[3].x;
            p.y = a * v[0].y + 3 * b * v[1].y + 3 * c * v[2].y + d * v[3].y;
        }
        return p;
    }

    private static PointF randInCenter(float i, float j, int width, int height) {
        log("randInCenter (" + i + ", " + j + ", " + width + ", " + height + ")");
        PointF p = new PointF();
        p.x = 0.5f * width + 0.15f * width * i;
        p.y = 0.5f * height + 0.15f * height * j;
        log("randInCenter returning " + p.x + "," + p.y);
        return p;
    }

    private static PointF randMultiDrop(int n, float i, float j, int width, int height) {
        log("randMultiDrop (" + n + "," + i + ", " + j + ", " + width + ", " + height + ")");
        final float[] cx = {0.3f, 0.3f, 0.5f, 0.7f, 0.7f};
        final float[] cy = {0.3f, 0.7f, 0.5f, 0.3f, 0.7f};
        n = Math.abs(n);
        float x = cx[n % cx.length];
        float y = cy[n % cx.length];
        PointF p = new PointF();
        p.x = x * width + 0.05f * width * i;
        p.y = y * height + 0.05f * height * j;
        log("randInCenter returning " + p.x + "," + p.y);
        return p;
    }

    private double cross(double[] a, double[] b) {
        return a[0] * b[1] - a[1] * b[0];
    }

    private double dot(double[] a, double[] b) {
        return a[0] * b[0] + a[1] * b[1];
    }

    private double norm(double[] a) {
        return Math.hypot(a[0], a[1]);
    }

    private double[] getCenter(View photo) {
        float width = (float) ((Integer) photo.getTag(R.id.photo_width)).intValue();
        float height = (float) ((Integer) photo.getTag(R.id.photo_height)).intValue();
        double[] center = { photo.getX() + width / 2f,
                            - (photo.getY() + height / 2f) };
        return center;
    }

    public View moveFocus(View focus, float direction) {
        return moveFocus(focus, direction, 90f);
    }

    public View moveFocus(View focus, float direction, float angle) {
        if (focus == null) {
            setFocus(mOnTable.getLast());
        } else {
            final double alpha = Math.toRadians(direction);
            final double beta = Math.toRadians(Math.min(angle, 180f) / 2f);
            final double[] left = { Math.sin(alpha - beta),
                                    Math.cos(alpha - beta) };
            final double[] right = { Math.sin(alpha + beta),
                                     Math.cos(alpha + beta) };
            final double[] a = getCenter(focus);
            View bestFocus = null;
            double bestDistance = Double.MAX_VALUE;
            for (View candidate: mOnTable) {
                if (candidate != focus) {
                    final double[] b = getCenter(candidate);
                    final double[] delta = { b[0] - a[0],
                                             b[1] - a[1] };
                    if (cross(delta, left) > 0.0 && cross(delta, right) < 0.0) {
                        final double distance = norm(delta);
                        if (bestDistance > distance) {
                            bestDistance = distance;
                            bestFocus = candidate;
                        }
                    }
                }
            }
            if (bestFocus == null) {
                if (angle < 180f) {
                    return moveFocus(focus, direction, 180f);
                }
            } else {
                setFocus(bestFocus);
            }
        }
        return getFocused();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        final View focus = getFocused();
        boolean consumed = true;

        if (hasSelection()) {
            switch (keyCode) {
            case KeyEvent.KEYCODE_ENTER:
            case KeyEvent.KEYCODE_DPAD_CENTER:
            case KeyEvent.KEYCODE_ESCAPE:
                setFocus(getSelected());
                clearSelection();
                break;
            default:
                log("dropped unexpected: " + keyCode);
                consumed = false;
                break;
            }
        } else {
            switch (keyCode) {
            case KeyEvent.KEYCODE_ENTER:
            case KeyEvent.KEYCODE_DPAD_CENTER:
                if (hasFocus()) {
                    setSelection(getFocused());
                    clearFocus();
                } else {
                    setFocus(mOnTable.getLast());
                }
                break;

            case KeyEvent.KEYCODE_DEL:
            case KeyEvent.KEYCODE_X:
                if (hasFocus()) {
                    fling(getFocused());
                }
                break;

            case KeyEvent.KEYCODE_DPAD_UP:
            case KeyEvent.KEYCODE_K:
                moveFocus(focus, 0f);
                break;

            case KeyEvent.KEYCODE_DPAD_RIGHT:
            case KeyEvent.KEYCODE_L:
                moveFocus(focus, 90f);
                break;

            case KeyEvent.KEYCODE_DPAD_DOWN:
            case KeyEvent.KEYCODE_J:
                moveFocus(focus, 180f);
                break;

            case KeyEvent.KEYCODE_DPAD_LEFT:
            case KeyEvent.KEYCODE_H:
                moveFocus(focus, 270f);
                break;

            default:
                log("dropped unexpected: " + keyCode);
                consumed = false;
                break;
            }
        }

        return consumed;
    }

    @Override
    public boolean onGenericMotionEvent(MotionEvent event) {
        return mEdgeSwipeDetector.onTouchEvent(event) || mDragGestureDetector.onTouchEvent(event);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
            if (hasSelection()) {
                clearSelection();
            } else  {
                if (mTapToExit && mDream != null) {
                    mDream.finish();
                }
            }
            return true;
        }
        return false;
    }

    @Override
    public void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        log("onLayout (" + left + ", " + top + ", " + right + ", " + bottom + ")");

        mHeight = bottom - top;
        mWidth = right - left;

        mLongSide = (int) (mImageRatio * Math.max(mWidth, mHeight));
        mShortSide = (int) (mImageRatio * Math.min(mWidth, mHeight));

        boolean isLandscape = mWidth > mHeight;
        if (mIsLandscape != isLandscape) {
            for (View photo: mOnTable) {
                if (photo == getSelected()) {
                    pickUp(photo);
                } else {
                    dropOnTable(photo);
                }
            }
            mIsLandscape = isLandscape;
        }
        start();
    }

    @Override
    public boolean isOpaque() {
        return true;
    }

    private class PhotoLaunchTask extends AsyncTask<Void, Void, View> {
        private final BitmapFactory.Options mOptions;

        public PhotoLaunchTask () {
            mOptions = new BitmapFactory.Options();
            mOptions.inTempStorage = new byte[32768];
        }

        @Override
        public View doInBackground(Void... unused) {
            log("load a new photo");
            final PhotoTable table = PhotoTable.this;

            LayoutInflater inflater = (LayoutInflater) table.getContext()
                   .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View photo = inflater.inflate(R.layout.photo, null);
            ImageView image = (ImageView) photo;
            Drawable[] layers = new Drawable[2];
            Bitmap decodedPhoto = table.mPhotoSource.next(mOptions,
                    table.mLongSide, table.mShortSide);
            int photoWidth = mOptions.outWidth;
            int photoHeight = mOptions.outHeight;
            if (decodedPhoto == null || mOptions.outWidth <= 0 || mOptions.outHeight <= 0) {
                photo = null;
            } else {
                decodedPhoto.setHasMipMap(true);
                layers[0] = new BitmapDrawable(table.mResources, decodedPhoto);
                layers[1] = table.mResources.getDrawable(R.drawable.frame);
                LayerDrawable layerList = new LayerDrawable(layers);
                layerList.setLayerInset(0, table.mInset, table.mInset,
                                        table.mInset, table.mInset);
                image.setImageDrawable(layerList);

                photo.setTag(R.id.photo_width, new Integer(photoWidth));
                photo.setTag(R.id.photo_height, new Integer(photoHeight));

                photo.setOnTouchListener(new PhotoTouchListener(table.getContext(),
                                                                table));
            }

            return photo;
        }

        @Override
        public void onPostExecute(View photo) {
            if (photo != null) {
                final PhotoTable table = PhotoTable.this;

                table.addView(photo, new LayoutParams(LayoutParams.WRAP_CONTENT,
                                                       LayoutParams.WRAP_CONTENT));
                if (table.hasSelection()) {
                    table.moveToTopOfPile(table.getSelected());
                }
                int width = ((Integer) photo.getTag(R.id.photo_width)).intValue();
                int height = ((Integer) photo.getTag(R.id.photo_height)).intValue();

                log("drop it");
                table.throwOnTable(photo);

                if (mOnTable.size() > mTableCapacity) {
                    int targetSize = Math.max(0, mOnTable.size() - mRedealCount);
                    while (mOnTable.size() > targetSize) {
                        fadeAway(mOnTable.poll(), false);
                    }
                }

                if(table.mOnTable.size() < table.mTableCapacity) {
                    table.scheduleNext(table.mFastDropPeriod);
                }
            }
        }
    };

    public void launch() {
        log("launching");
        setSystemUiVisibility(View.STATUS_BAR_HIDDEN);
        if (hasSelection() &&
                (System.currentTimeMillis() - mSelectedTime) > MAX_SELECTION_TIME) {
            clearSelection();
        } else {
            log("inflate it");
            if (mPhotoLaunchTask == null ||
                mPhotoLaunchTask.getStatus() == AsyncTask.Status.FINISHED) {
                mPhotoLaunchTask = new PhotoLaunchTask();
                mPhotoLaunchTask.execute();
            }
        }
    }
    public void fadeAway(final View photo, final boolean replace) {
        // fade out of view
        mOnTable.remove(photo);
        if (photo == getFocused()) {
            clearFocus();
        }
        photo.animate().cancel();
        photo.animate()
                .withLayer()
                .alpha(0f)
                .setDuration(1000)
                .withEndAction(new Runnable() {
                        @Override
                        public void run() {
                            removeView(photo);
                            recycle(photo);
                            if (replace) {
                                scheduleNext(mNowDropDelay);
                            }
                        }
                    });
    }

    public void moveToTopOfPile(View photo) {
        // make this photo the last to be removed.
        bringChildToFront(photo);
        invalidate();
        mOnTable.remove(photo);
        mOnTable.offer(photo);
    }

    private void throwOnTable(final View photo) {
        mOnTable.offer(photo);
        log("start offscreen");
        int width = ((Integer) photo.getTag(R.id.photo_width));
        int height = ((Integer) photo.getTag(R.id.photo_height));
        photo.setRotation(mThrowRotation);
        photo.setX(-mLongSide);
        photo.setY(-mLongSide);

        dropOnTable(photo, mThrowInterpolator);
    }

    public void move(final View photo, float dx, float dy, boolean drop) {
        if (photo != null) {
            final float x = photo.getX() + dx;
            final float y = photo.getY() + dy;
            photo.setX(x);
            photo.setY(y);
            Log.d(TAG, "[" + photo.getX() + ", " + photo.getY() + "] + (" + dx + "," + dy + ")");
            if (drop && photoOffTable(photo)) {
                fadeAway(photo, true);
            }
        }
    }

    public void fling(final View photo) {
        final float[] o = { mWidth + mLongSide / 2f,
                            mHeight + mLongSide / 2f };
        final float[] a = { photo.getX(), photo.getY() };
        final float[] b = { o[0], a[1] + o[0] - a[0] };
        final float[] c = { a[0] + o[1] - a[1], o[1] };
        float[] delta = { 0f, 0f };
        if (Math.hypot(b[0] - a[0], b[1] - a[1]) < Math.hypot(c[0] - a[0], c[1] - a[1])) {
            delta[0] = b[0] - a[0];
            delta[1] = b[1] - a[1];
        } else {
            delta[0] = c[0] - a[0];
            delta[1] = c[1] - a[1];
        }

        final float dist = (float) Math.hypot(delta[0], delta[1]);
        final int duration = (int) (1000f * dist / mThrowSpeed);
        fling(photo, delta[0], delta[1], duration, true);
    }

    public void fling(final View photo, float dx, float dy, int duration, boolean spin) {
        if (photo == getFocused()) {
            if (moveFocus(photo, 0f) == null) {
                moveFocus(photo, 180f);
            }
        }
        ViewPropertyAnimator animator = photo.animate()
                .xBy(dx)
                .yBy(dy)
                .setDuration(duration)
                .setInterpolator(new DecelerateInterpolator(2f));

        if (spin) {
            animator.rotation(mThrowRotation);
        }

        if (photoOffTable(photo, (int) dx, (int) dy)) {
            log("fling away");
            animator.withEndAction(new Runnable() {
                    @Override
                    public void run() {
                        fadeAway(photo, true);
                    }
                });
        }
    }
    public boolean photoOffTable(final View photo) {
        return photoOffTable(photo, 0, 0);
    }

    public boolean photoOffTable(final View photo, final int dx, final int dy) {
        Rect hit = new Rect();
        photo.getHitRect(hit);
        hit.offset(dx, dy);
        return (hit.bottom < 0f || hit.top > getHeight() ||
                hit.right < 0f || hit.left > getWidth());
    }

    public void dropOnTable(final View photo) {
        dropOnTable(photo, mDropInterpolator);
    }

    public void dropOnTable(final View photo, final Interpolator interpolator) {
        float angle = randfrange(-mImageRotationLimit, mImageRotationLimit);
        PointF p = randMultiDrop(sRNG.nextInt(),
                                 (float) sRNG.nextGaussian(), (float) sRNG.nextGaussian(),
                                 mWidth, mHeight);
        float x = p.x;
        float y = p.y;

        log("drop it at " + x + ", " + y);

        float x0 = photo.getX();
        float y0 = photo.getY();
        float width = (float) ((Integer) photo.getTag(R.id.photo_width)).intValue();
        float height = (float) ((Integer) photo.getTag(R.id.photo_height)).intValue();

        x -= mLongSide / 2f;
        y -= mShortSide / 2f;
        log("fixed offset is " + x + ", " + y);

        float dx = x - x0;
        float dy = y - y0;

        float dist = (float) Math.hypot(dx, dy);
        int duration = (int) (1000f * dist / mThrowSpeed);
        duration = Math.max(duration, 1000);

        log("animate it");
        // toss onto table
        photo.animate()
                .scaleX(mTableRatio / mImageRatio)
                .scaleY(mTableRatio / mImageRatio)
                .rotation(angle)
                .x(x)
                .y(y)
                .setDuration(duration)
                .setInterpolator(interpolator);
    }

    /** wrap all orientations to the interval [-180, 180). */
    private float wrapAngle(float angle) {
        float result = angle + 180;
        result = ((result % 360) + 360) % 360; // catch negative numbers
        result -= 180;
        return result;
    }

    private void pickUp(final View photo) {
        float photoWidth = photo.getWidth();
        float photoHeight = photo.getHeight();

        float scale = Math.min(getHeight() / photoHeight, getWidth() / photoWidth);

        log("target it");
        float x = (getWidth() - photoWidth) / 2f;
        float y = (getHeight() - photoHeight) / 2f;

        float x0 = photo.getX();
        float y0 = photo.getY();
        float dx = x - x0;
        float dy = y - y0;

        float dist = (float) (Math.sqrt(dx * dx + dy * dy));
        int duration = (int) (1000f * dist / 600f);
        duration = Math.max(duration, 500);

        photo.setRotation(wrapAngle(photo.getRotation()));

        log("animate it");
        // toss onto table
        photo.animate()
                .rotation(0f)
                .scaleX(scale)
                .scaleY(scale)
                .x(x)
                .y(y)
                .setDuration(duration)
                .setInterpolator(new DecelerateInterpolator(2f))
                .withEndAction(new Runnable() {
                        @Override
                            public void run() {
                            log("endtimes: " + photo.getX());
                        }
                    });
    }

    private void recycle(View photo) {
        ImageView image = (ImageView) photo;
        LayerDrawable layers = (LayerDrawable) image.getDrawable();
        BitmapDrawable bitmap = (BitmapDrawable) layers.getDrawable(0);
        bitmap.getBitmap().recycle();
    }

    public void setHighlight(View photo, boolean highlighted) {
        ImageView image = (ImageView) photo;
        LayerDrawable layers = (LayerDrawable) image.getDrawable();
        if (highlighted) {
            layers.getDrawable(1).setColorFilter(mHighlightColor, PorterDuff.Mode.SRC_IN);
        } else {
            layers.getDrawable(1).clearColorFilter();
        }
    }

    public void start() {
        if (!mStarted) {
            log("kick it");
            mStarted = true;
            scheduleNext(mDropPeriod);
            launch();
        }
    }

    public void refreshFocus() {
        scheduleFocusReaper(MAX_FOCUS_TIME);
    }

    public void scheduleFocusReaper(int delay) {
        removeCallbacks(mFocusReaper);
        postDelayed(mFocusReaper, delay);
    }

    public void scheduleNext(int delay) {
        removeCallbacks(mLauncher);
        postDelayed(mLauncher, delay);
    }

    private static void log(String message) {
        if (DEBUG) {
            Log.i(TAG, message);
        }
    }
}