summaryrefslogtreecommitdiffstats
path: root/src/com/android/mail/ui/AnimatedAdapter.java
blob: 9b9803fee79f51589989f309abda7b278fd4dab2 (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
/*
 * Copyright (C) 2012 Google Inc.
 * Licensed to 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.mail.ui;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleCursorAdapter;

import com.android.mail.R;
import com.android.mail.browse.ConversationCursor;
import com.android.mail.browse.ConversationItemView;
import com.android.mail.browse.SwipeableConversationItemView;
import com.android.mail.providers.Account;
import com.android.mail.providers.Conversation;
import com.android.mail.providers.Folder;
import com.android.mail.providers.Settings;
import com.android.mail.providers.UIProvider;
import com.android.mail.utils.LogTag;
import com.android.mail.utils.LogUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;

public class AnimatedAdapter extends SimpleCursorAdapter implements
        android.animation.Animator.AnimatorListener, Settings.ChangeListener {
    private static final String LAST_DELETING_ITEMS = "last_deleting_items";
    private static final String LEAVE_BEHIND_ITEM = "leave_behind_item";
    private final static int TYPE_VIEW_CONVERSATION = 0;
    private final static int TYPE_VIEW_DELETING = 1;
    private final static int TYPE_VIEW_UNDOING = 2;
    private final static int TYPE_VIEW_FOOTER = 3;
    private final static int TYPE_VIEW_LEAVEBEHIND = 4;
    private HashSet<Integer> mDeletingItems = new HashSet<Integer>();
    private HashSet<Integer> mUndoingItems = new HashSet<Integer>();
    private HashSet<Integer> mSwipeUndoingItems = new HashSet<Integer>();
    private Account mSelectedAccount;
    private Context mContext;
    private ConversationSelectionSet mBatchConversations;
    /**
     * The next action to perform. Do not read or write this. All accesses should
     * be in {@link #performAndSetNextAction(DestructiveAction)} which commits the
     * previous action, if any.
     */
    private DestructiveAction mPendingDestruction;
    /**
     * A destructive action that refreshes the list and performs no other action.
     */
    private final DestructiveAction mRefreshAction = new DestructiveAction() {
        @Override
        public void performAction() {
            notifyDataSetChanged();
        }
    };

    private ArrayList<Integer> mLastDeletingItems = new ArrayList<Integer>();
    private ViewMode mViewMode;
    private View mFooter;
    private boolean mShowFooter;
    private Folder mFolder;
    private final SwipeableListView mListView;
    private Settings mCachedSettings;
    private boolean mSwipeEnabled;
    private LeaveBehindItem mFadeLeaveBehindItem;
    private LeaveBehindItem mLeaveBehindItem;

    /**
     * Used only for debugging.
     */
    private static final String LOG_TAG = LogTag.getLogTag();

    public AnimatedAdapter(Context context, int textViewResourceId, ConversationCursor cursor,
            ConversationSelectionSet batch, Account account, Settings settings, ViewMode viewMode,
            SwipeableListView listView) {
        super(context, textViewResourceId, cursor, UIProvider.CONVERSATION_PROJECTION, null, 0);
        mContext = context;
        mBatchConversations = batch;
        mSelectedAccount = account;
        mViewMode = viewMode;
        mShowFooter = false;
        mListView = listView;
        mCachedSettings = settings;
        mSwipeEnabled = account.supportsCapability(UIProvider.AccountCapabilities.UNDO);
    }

    @Override
    public int getCount() {
        final int count = super.getCount();
        return mShowFooter ? count + 1 : count;
    }

    public void setUndo(boolean undo) {
        if (undo && !mLastDeletingItems.isEmpty()) {
            mUndoingItems.addAll(mLastDeletingItems);
            mLastDeletingItems.clear();
            // Start animation
            notifyDataSetChanged();
            performAndSetNextAction(mRefreshAction);
        }
    }

    public void setSwipeUndo(boolean undo) {
        if (undo && !mLastDeletingItems.isEmpty()) {
            mSwipeUndoingItems.addAll(mLastDeletingItems);
            mLastDeletingItems.clear();
            // Start animation
            notifyDataSetChanged();
            performAndSetNextAction(mRefreshAction);
        }
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        SwipeableConversationItemView view = new SwipeableConversationItemView(context,
                mSelectedAccount.name);
        return view;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        if (! (view instanceof SwipeableConversationItemView)) {
            return;
        }
        ((SwipeableConversationItemView) view).bind(cursor, mViewMode, mBatchConversations, mFolder,
                mCachedSettings != null ? mCachedSettings.hideCheckboxes : false,
                        mSwipeEnabled, this);
    }

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

    @Override
    public int getViewTypeCount() {
        // TYPE_VIEW_CONVERSATION, TYPE_VIEW_DELETING, TYPE_VIEW_UNDOING, and
        // TYPE_VIEW_FOOTER, TYPE_VIEW_LEAVEBEHIND.
        return 5;
    }

    @Override
    public int getItemViewType(int position) {
        // Try to recycle views.
        if (isPositionDeleting(position)) {
            return TYPE_VIEW_DELETING;
        }
        if (isPositionUndoingType(position)) {
            return TYPE_VIEW_UNDOING;
        }
        if (mShowFooter && position == super.getCount()) {
            return TYPE_VIEW_FOOTER;
        }
        if (isPositionTypeLeaveBehind(position)) {
            return TYPE_VIEW_LEAVEBEHIND;
        }
        return TYPE_VIEW_CONVERSATION;
    }

    /**
     * Deletes the selected conversations from the conversation list view. These conversations
     * <b>must</b> have their {@link Conversation#position} set to the position of these
     * conversations among the list. . This will only remove the
     * element from the list. The job of deleting the actual element is left to the the listener.
     * This listener will be called when the animations are complete and is required to
     * delete the conversation.
     * @param conversations
     * @param listener
     */
    public void delete(Collection<Conversation> conversations, DestructiveAction listener) {
        // Animate out the positions.
        // Call when all the animations are complete.
        final ArrayList<Integer> positions = new ArrayList<Integer>();
        for (Conversation c : conversations) {
            positions.add(c.position);
        }
        delete(positions, listener);
    }

    /**
     * Deletes a conversation with the list positions given here. This will only remove the
     * element from the list. The job of deleting the actual elements is left to the the listener.
     * This listener will be called when the animations are complete and is required to
     * delete the conversations.
     * @param deletedRows the position in the list view to be deleted.
     * @param action the destructive action that modifies the database.
     */
    public void delete(ArrayList<Integer> deletedRows, DestructiveAction action) {
        // Clear out any remaining items and add the new ones
        mLastDeletingItems.clear();

        final int startPosition = mListView.getFirstVisiblePosition();
        final int endPosition = mListView.getLastVisiblePosition();

        // Only animate visible items
        for (int deletedRow: deletedRows) {
            if (deletedRow >= startPosition && deletedRow <= endPosition) {
                mLastDeletingItems.add(deletedRow);
                mDeletingItems.add(deletedRow);
            }
        }

        if (mDeletingItems.isEmpty()) {
            // If we have no deleted items on screen, skip the animation
            action.performAction();
        } else {
            performAndSetNextAction(action);
        }

        // TODO(viki): Rather than notifying for a full data set change,
        // perhaps we can mark
        // only the affected conversations?
        notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (mShowFooter && position == super.getCount()) {
            return mFooter;
        }
        if (isPositionUndoing(position)) {
            return getUndoingView(position, convertView, parent,
                    false /* don't show swipe background */);
        } if (isPositionUndoingSwipe(position)) {
            return getUndoingView(position, convertView, parent,
                    true /* show swipe background */);
        } else if (isPositionDeleting(position)) {
            return getDeletingView(position, convertView, parent);
        }
        if (hasFadeLeaveBehinds()) {
            Conversation conv = new Conversation((ConversationCursor) getItem(position));
            if(isPositionFadeLeaveBehind(conv)) {
                LeaveBehindItem fade  = getFadeLeaveBehindItem(position, conv);
                fade.startAnimation(mViewMode, this);
                return fade;
            }
        }
        if (hasLeaveBehinds()) {
            Conversation conv = new Conversation((ConversationCursor) getItem(position));
            if(isPositionLeaveBehind(conv)) {
                return getLeaveBehindItem(conv);
            }
        }
        // TODO: do this in the swipe helper?
        // If this view gets recycled, we need to reset things set by the
        // animation.
        if (convertView != null) {
            if (convertView.getAlpha() < 1) {
                convertView.setAlpha(1);
            }
            if (convertView.getTranslationX() != 0) {
                convertView.setTranslationX(0);
            }
            if (convertView instanceof SwipeableConversationItemView) {
                ((SwipeableConversationItemView)convertView).reset();
            }
        }
        return super.getView(position, convertView, parent);
    }

    private boolean hasLeaveBehinds() {
        return mLeaveBehindItem != null;
    }

    private boolean hasFadeLeaveBehinds() {
        return mFadeLeaveBehindItem != null;
    }

    public LeaveBehindItem setupLeaveBehind(Conversation target, ToastBarOperation undoOp,
            int deletedRow) {
        fadeOutLeaveBehindItems();
        LeaveBehindItem leaveBehind = (LeaveBehindItem) LayoutInflater.from(mContext).inflate(
                R.layout.swipe_leavebehind, null);
        leaveBehind.bindOperations(deletedRow, mSelectedAccount, this, undoOp, target);
        mLeaveBehindItem = leaveBehind;
        mLastDeletingItems.add(deletedRow);
        return leaveBehind;
    }

    public void fadeOutLeaveBehindItems() {
        // Remove any previously existing leave behind item.
        final int startPosition = mListView.getFirstVisiblePosition();
        final int endPosition = mListView.getLastVisiblePosition();

        if (hasLeaveBehinds()) {
            // If the item is visible, fade it out. Otherwise, just remove
            // it.
            Conversation conv = mLeaveBehindItem.getData();
            if (conv.position >= startPosition && conv.position <= endPosition) {
                mFadeLeaveBehindItem = mLeaveBehindItem;
            }
            clearLeaveBehind(conv.id);
        }
        if (!mLastDeletingItems.isEmpty()) {
            mLastDeletingItems.clear();
        }
        notifyDataSetChanged();
    }

    public void commitLeaveBehindItems() {
        // Remove any previously existing leave behinds.
        if (hasLeaveBehinds()) {
            mLeaveBehindItem.commit();
        }
        if (hasFadeLeaveBehinds()) {
            mFadeLeaveBehindItem.commit();
        }

        if (!mLastDeletingItems.isEmpty()) {
            mLastDeletingItems.clear();
        }
        notifyDataSetChanged();
    }

    private LeaveBehindItem getLeaveBehindItem(Conversation target) {
        return mLeaveBehindItem;
    }

    private LeaveBehindItem getFadeLeaveBehindItem(int position, Conversation target) {
        return mFadeLeaveBehindItem;
    }

    @Override
    public long getItemId(int position) {
        if (mShowFooter && position == super.getCount()) {
            return -1;
        }
        return super.getItemId(position);
    }

    /**
     * Get an animating view. This happens when a list item is in the process of being removed
     * from the list (items being deleted).
     * @param position the position of the view inside the list
     * @param convertView if null, a recycled view that we can reuse
     * @param parent the parent view
     * @return the view to show when animating an operation.
     */
    private View getDeletingView(int position, View convertView, ViewGroup parent) {
        // We are getting the wrong view, and we need to gracefully carry on.
        if (convertView != null && !(convertView instanceof AnimatingItemView)) {
            LogUtils.d(LOG_TAG, "AnimatedAdapter.getAnimatingView received the wrong view!");
            convertView = null;
        }
        Conversation conversation = new Conversation((ConversationCursor) getItem(position));
        conversation.position = position;
        // Destroying a conversation just shows a blank shrinking item.
        final AnimatingItemView view = new AnimatingItemView(mContext);
        view.setData(conversation);
        view.startAnimation(mViewMode, this);
        return view;
    }

    private View getUndoingView(int position, View convertView, ViewGroup parent,
            boolean swipe) {
        Conversation conversation = new Conversation((ConversationCursor) getItem(position));
        conversation.position = position;
        // The undo animation consists of fading in the conversation that
        // had been destroyed.
        final SwipeableConversationItemView convView = (SwipeableConversationItemView) super
                .getView(position, null, parent);
        convView.bind(conversation, mViewMode, mBatchConversations, mFolder,
                mCachedSettings != null ? mCachedSettings.hideCheckboxes : false, mSwipeEnabled,
                this);
        convView.startUndoAnimation(mListView.getSwipeActionText(), mViewMode, this, swipe);
        return convView;
    }

    @Override
    public Object getItem(int position) {
        if (mShowFooter && position == super.getCount()) {
            return mFooter;
        }
        return super.getItem(position);
    }

    private boolean isPositionDeleting(int position) {
        return mDeletingItems.contains(position);
    }

    private boolean isPositionUndoing(int position) {
        return mUndoingItems.contains(position);
    }

    private boolean isPositionUndoingSwipe(int position) {
        return mSwipeUndoingItems.contains(position);
    }

    private boolean isPositionUndoingType(int position) {
        return isPositionUndoing(position) || isPositionUndoingSwipe(position);
    }

    private boolean isPositionLeaveBehind(Conversation conv) {
        return hasLeaveBehinds()
                && mLeaveBehindItem.getConversationId() == conv.id
                && conv.isMostlyDead();
    }

    private boolean isPositionFadeLeaveBehind(Conversation conv) {
        return hasFadeLeaveBehinds()
                && mFadeLeaveBehindItem.getConversationId() == conv.id
                && conv.isMostlyDead();
    }

    private boolean isPositionTypeLeaveBehind(int position) {
        if (hasLeaveBehinds()) {
            Object item = getItem(position);
            if (item instanceof ConversationCursor) {
                Conversation conv = new Conversation((ConversationCursor) item);
                return isPositionLeaveBehind(conv) || isPositionFadeLeaveBehind(conv);
            }
        }
        return false;
    }

    @Override
    public void onAnimationStart(Animator animation) {
        if (!mUndoingItems.isEmpty()) {
            mDeletingItems.clear();
            mLastDeletingItems.clear();
        } else {
            mUndoingItems.clear();
        }
    }

    /**
     * Performs the pending destruction, if any and assigns the next pending action.
     * @param next The next action that is to be performed, possibly null (if no next action is
     * needed).
     */
    private final void performAndSetNextAction(DestructiveAction next) {
        if (mPendingDestruction != null) {
            mPendingDestruction.performAction();
        }
        mPendingDestruction = next;
    }

    @Override
    public void onAnimationEnd(Animator animation) {
        if (hasFadeLeaveBehinds()) {
            Object obj = ((ObjectAnimator) animation).getTarget();
            if (obj instanceof LeaveBehindItem) {
                LeaveBehindItem objItem = (LeaveBehindItem)obj;
                clearLeaveBehind(objItem.getConversationId());
                objItem.commit();
            }
        } else if (hasUndoingItems()) {
            // See if we have received all the animations we expected; if
            // so, call the listener and reset it.
            final int position = ((ConversationItemView) ((ObjectAnimator) animation).getTarget())
                    .getPosition();
            if (isPositionUndoingSwipe(position)) {
                mSwipeUndoingItems.remove(position);
                if (mSwipeUndoingItems.isEmpty()) {
                    performAndSetNextAction(null);
                }
            } else if (isPositionUndoing(position)) {
                mUndoingItems.remove(position);
                if (mUndoingItems.isEmpty()) {
                    performAndSetNextAction(null);
                }
            }
        } else if (!mDeletingItems.isEmpty()) {
            // See if we have received all the animations we expected; if
            // so, call the listener and reset it.
            final AnimatingItemView target = ((AnimatingItemView) ((ObjectAnimator) animation)
                    .getTarget());
            final int position = target.getData().position;
            mDeletingItems.remove(position);
            if (mDeletingItems.isEmpty()) {
                performAndSetNextAction(null);
            }
        }
        // The view types have changed, since the animating views are gone.
        notifyDataSetChanged();
    }

    private boolean hasUndoingItems() {
        return !mUndoingItems.isEmpty() || !mSwipeUndoingItems.isEmpty();
    }

    @Override
    public boolean areAllItemsEnabled() {
        // The animating positions are not enabled.
        return false;
    }

    @Override
    public boolean isEnabled(int position) {
        return !isPositionDeleting(position) && !isPositionUndoing(position);
    }

    @Override
    public void onAnimationCancel(Animator animation) {
        onAnimationEnd(animation);
    }

    @Override
    public void onAnimationRepeat(Animator animation) {
    }

    public void showFooter() {
        if (!mShowFooter) {
            mShowFooter = true;
            notifyDataSetChanged();
        }
    }

    public void hideFooter() {
        if (mShowFooter) {
            mShowFooter = false;
            notifyDataSetChanged();
        }
    }

    public void addFooter(View footerView) {
        mFooter = footerView;
    }

    public void setFolder(Folder folder) {
        mFolder = folder;
    }

    public void clearLeaveBehind(long itemId) {
        if (hasLeaveBehinds() && mLeaveBehindItem.getConversationId() == itemId) {
            mLeaveBehindItem = null;
        } else if (hasFadeLeaveBehinds() && mFadeLeaveBehindItem.getConversationId() == itemId) {
            mFadeLeaveBehindItem = null;
        } else {
            LogUtils.d(LOG_TAG, "Trying to clear a non-existant leave behind");
        }
    }

    /**
     * @param updatedSettings
     */
    @Override
    public void onSettingsChanged(Settings updatedSettings) {
        mCachedSettings = updatedSettings;
    }

    public void onSaveInstanceState(Bundle outState) {
        int[] lastDeleting = new int[mLastDeletingItems.size()];
        for (int i = 0; i < lastDeleting.length; i++) {
            lastDeleting[i] = mLastDeletingItems.get(i);
        }
        outState.putIntArray(LAST_DELETING_ITEMS, lastDeleting);
        if (hasLeaveBehinds()) {
            outState.putParcelable(LEAVE_BEHIND_ITEM, mLeaveBehindItem.getLeaveBehindData());
        }
    }

    public void onRestoreInstanceState(Bundle outState) {
        if (outState.containsKey(LAST_DELETING_ITEMS)) {
            final int[] lastDeleting = outState.getIntArray(LAST_DELETING_ITEMS);
            for (int i = 0; i < lastDeleting.length;i++) {
                mLastDeletingItems.add(lastDeleting[i]);
            }
        }
        if (outState.containsKey(LEAVE_BEHIND_ITEM)) {
            LeaveBehindItem.LeaveBehindData left = outState.getParcelable(LEAVE_BEHIND_ITEM);
            LeaveBehindItem item = setupLeaveBehind(left.data, left.op, left.data.position);
            mLeaveBehindItem = item;
        }
    }
}