summaryrefslogtreecommitdiffstats
path: root/java/com/android/dialer/app/list/OldSpeedDialFragment.java
blob: 05d017b2869c20629e4bd703c30f61ae24fd7285 (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
/*
 * Copyright (C) 2013 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.dialer.app.list;

import static android.Manifest.permission.READ_CONTACTS;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.Fragment;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Trace;
import android.support.v13.app.FragmentCompat;
import android.support.v4.util.LongSparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.ListView;
import com.android.contacts.common.ContactPhotoManager;
import com.android.contacts.common.ContactTileLoaderFactory;
import com.android.contacts.common.list.ContactTileView;
import com.android.contacts.common.list.OnPhoneNumberPickerActionListener;
import com.android.dialer.app.R;
import com.android.dialer.callintent.CallSpecificAppData;
import com.android.dialer.common.LogUtil;
import com.android.dialer.util.PermissionsUtil;
import com.android.dialer.util.ViewUtil;
import com.android.dialer.widget.EmptyContentView;
import java.util.ArrayList;
import java.util.Arrays;

/** This fragment displays the user's favorite/frequent contacts in a grid. */
public class OldSpeedDialFragment extends Fragment
    implements OnItemClickListener,
        PhoneFavoritesTileAdapter.OnDataSetChangedForAnimationListener,
        EmptyContentView.OnEmptyViewActionButtonClickedListener,
        FragmentCompat.OnRequestPermissionsResultCallback {

  private static final int READ_CONTACTS_PERMISSION_REQUEST_CODE = 1;

  /**
   * By default, the animation code assumes that all items in a list view are of the same height
   * when animating new list items into view (e.g. from the bottom of the screen into view). This
   * can cause incorrect translation offsets when a item that is larger or smaller than other list
   * item is removed from the list. This key is used to provide the actual height of the removed
   * object so that the actual translation appears correct to the user.
   */
  private static final long KEY_REMOVED_ITEM_HEIGHT = Long.MAX_VALUE;

  private static final String TAG = "OldSpeedDialFragment";
  private static final boolean DEBUG = false;
  /** Used with LoaderManager. */
  private static final int LOADER_ID_CONTACT_TILE = 1;

  private final LongSparseArray<Integer> mItemIdTopMap = new LongSparseArray<>();
  private final LongSparseArray<Integer> mItemIdLeftMap = new LongSparseArray<>();
  private final ContactTileView.Listener mContactTileAdapterListener =
      new ContactTileAdapterListener();
  private final LoaderManager.LoaderCallbacks<Cursor> mContactTileLoaderListener =
      new ContactTileLoaderListener();
  private final ScrollListener mScrollListener = new ScrollListener();
  private int mAnimationDuration;
  private OnPhoneNumberPickerActionListener mPhoneNumberPickerActionListener;
  private OnListFragmentScrolledListener mActivityScrollListener;
  private PhoneFavoritesTileAdapter mContactTileAdapter;
  private View mParentView;
  private PhoneFavoriteListView mListView;
  private View mContactTileFrame;
  /** Layout used when there are no favorites. */
  private EmptyContentView mEmptyView;

  @Override
  public void onCreate(Bundle savedState) {
    if (DEBUG) {
      LogUtil.d("OldSpeedDialFragment.onCreate", null);
    }
    Trace.beginSection(TAG + " onCreate");
    super.onCreate(savedState);

    // Construct two base adapters which will become part of PhoneFavoriteMergedAdapter.
    // We don't construct the resultant adapter at this moment since it requires LayoutInflater
    // that will be available on onCreateView().
    mContactTileAdapter =
        new PhoneFavoritesTileAdapter(getActivity(), mContactTileAdapterListener, this);
    mContactTileAdapter.setPhotoLoader(ContactPhotoManager.getInstance(getActivity()));
    mAnimationDuration = getResources().getInteger(R.integer.fade_duration);
    Trace.endSection();
  }

  @Override
  public void onResume() {
    Trace.beginSection(TAG + " onResume");
    super.onResume();
    if (mContactTileAdapter != null) {
      mContactTileAdapter.refreshContactsPreferences();
    }
    if (PermissionsUtil.hasContactsReadPermissions(getActivity())) {
      if (getLoaderManager().getLoader(LOADER_ID_CONTACT_TILE) == null) {
        getLoaderManager().initLoader(LOADER_ID_CONTACT_TILE, null, mContactTileLoaderListener);

      } else {
        getLoaderManager().getLoader(LOADER_ID_CONTACT_TILE).forceLoad();
      }

      mEmptyView.setDescription(R.string.speed_dial_empty);
      mEmptyView.setActionLabel(R.string.speed_dial_empty_add_favorite_action);
    } else {
      mEmptyView.setDescription(R.string.permission_no_speeddial);
      mEmptyView.setActionLabel(R.string.permission_single_turn_on);
    }
    Trace.endSection();
  }

  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Trace.beginSection(TAG + " onCreateView");
    mParentView = inflater.inflate(R.layout.speed_dial_fragment, container, false);

    mListView = (PhoneFavoriteListView) mParentView.findViewById(R.id.contact_tile_list);
    mListView.setOnItemClickListener(this);
    mListView.setVerticalScrollBarEnabled(false);
    mListView.setVerticalScrollbarPosition(View.SCROLLBAR_POSITION_RIGHT);
    mListView.setScrollBarStyle(ListView.SCROLLBARS_OUTSIDE_OVERLAY);
    mListView.getDragDropController().addOnDragDropListener(mContactTileAdapter);

    final ImageView dragShadowOverlay =
        (ImageView) getActivity().findViewById(R.id.contact_tile_drag_shadow_overlay);
    mListView.setDragShadowOverlay(dragShadowOverlay);

    mEmptyView = (EmptyContentView) mParentView.findViewById(R.id.empty_list_view);
    mEmptyView.setImage(R.drawable.empty_speed_dial);
    mEmptyView.setActionClickedListener(this);

    mContactTileFrame = mParentView.findViewById(R.id.contact_tile_frame);

    final LayoutAnimationController controller =
        new LayoutAnimationController(
            AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in));
    controller.setDelay(0);
    mListView.setLayoutAnimation(controller);
    mListView.setAdapter(mContactTileAdapter);

    mListView.setOnScrollListener(mScrollListener);
    mListView.setFastScrollEnabled(false);
    mListView.setFastScrollAlwaysVisible(false);

    //prevent content changes of the list from firing accessibility events.
    mListView.setAccessibilityLiveRegion(View.ACCESSIBILITY_LIVE_REGION_NONE);
    ContentChangedFilter.addToParent(mListView);

    Trace.endSection();
    return mParentView;
  }

  public boolean hasFrequents() {
    if (mContactTileAdapter == null) {
      return false;
    }
    return mContactTileAdapter.getNumFrequents() > 0;
  }

  /* package */ void setEmptyViewVisibility(final boolean visible) {
    final int previousVisibility = mEmptyView.getVisibility();
    final int emptyViewVisibility = visible ? View.VISIBLE : View.GONE;
    final int listViewVisibility = visible ? View.GONE : View.VISIBLE;

    if (previousVisibility != emptyViewVisibility) {
      final FrameLayout.LayoutParams params = (LayoutParams) mContactTileFrame.getLayoutParams();
      params.height = visible ? LayoutParams.WRAP_CONTENT : LayoutParams.MATCH_PARENT;
      mContactTileFrame.setLayoutParams(params);
      mEmptyView.setVisibility(emptyViewVisibility);
      mListView.setVisibility(listViewVisibility);
    }
  }

  @Override
  public void onStart() {
    super.onStart();

    final Activity activity = getActivity();

    try {
      mActivityScrollListener = (OnListFragmentScrolledListener) activity;
    } catch (ClassCastException e) {
      throw new ClassCastException(
          activity.toString() + " must implement OnListFragmentScrolledListener");
    }

    try {
      OnDragDropListener listener = (OnDragDropListener) activity;
      mListView.getDragDropController().addOnDragDropListener(listener);
      ((HostInterface) activity).setDragDropController(mListView.getDragDropController());
    } catch (ClassCastException e) {
      throw new ClassCastException(
          activity.toString() + " must implement OnDragDropListener and HostInterface");
    }

    try {
      mPhoneNumberPickerActionListener = (OnPhoneNumberPickerActionListener) activity;
    } catch (ClassCastException e) {
      throw new ClassCastException(
          activity.toString() + " must implement PhoneFavoritesFragment.listener");
    }

    // Use initLoader() instead of restartLoader() to refraining unnecessary reload.
    // This method call implicitly assures ContactTileLoaderListener's onLoadFinished() will
    // be called, on which we'll check if "all" contacts should be reloaded again or not.
    if (PermissionsUtil.hasContactsReadPermissions(activity)) {
      getLoaderManager().initLoader(LOADER_ID_CONTACT_TILE, null, mContactTileLoaderListener);
    } else {
      setEmptyViewVisibility(true);
    }
  }

  /**
   * {@inheritDoc}
   *
   * <p>This is only effective for elements provided by {@link #mContactTileAdapter}. {@link
   * #mContactTileAdapter} has its own logic for click events.
   */
  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    final int contactTileAdapterCount = mContactTileAdapter.getCount();
    if (position <= contactTileAdapterCount) {
      LogUtil.e(
          "OldSpeedDialFragment.onItemClick",
          "event for unexpected position. The position "
              + position
              + " is before \"all\" section. Ignored.");
    }
  }

  /**
   * Cache the current view offsets into memory. Once a relayout of views in the ListView has
   * happened due to a dataset change, the cached offsets are used to create animations that slide
   * views from their previous positions to their new ones, to give the appearance that the views
   * are sliding into their new positions.
   */
  private void saveOffsets(int removedItemHeight) {
    final int firstVisiblePosition = mListView.getFirstVisiblePosition();
    if (DEBUG) {
      LogUtil.d("OldSpeedDialFragment.saveOffsets", "Child count : " + mListView.getChildCount());
    }
    for (int i = 0; i < mListView.getChildCount(); i++) {
      final View child = mListView.getChildAt(i);
      final int position = firstVisiblePosition + i;
      // Since we are getting the position from mListView and then querying
      // mContactTileAdapter, its very possible that things are out of sync
      // and we might index out of bounds.  Let's make sure that this doesn't happen.
      if (!mContactTileAdapter.isIndexInBound(position)) {
        continue;
      }
      final long itemId = mContactTileAdapter.getItemId(position);
      if (DEBUG) {
        LogUtil.d(
            "OldSpeedDialFragment.saveOffsets",
            "Saving itemId: " + itemId + " for listview child " + i + " Top: " + child.getTop());
      }
      mItemIdTopMap.put(itemId, child.getTop());
      mItemIdLeftMap.put(itemId, child.getLeft());
    }
    mItemIdTopMap.put(KEY_REMOVED_ITEM_HEIGHT, removedItemHeight);
  }

  /*
   * Performs animations for the gridView
   */
  private void animateGridView(final long... idsInPlace) {
    if (mItemIdTopMap.size() == 0) {
      // Don't do animations if the database is being queried for the first time and
      // the previous item offsets have not been cached, or the user hasn't done anything
      // (dragging, swiping etc) that requires an animation.
      return;
    }

    ViewUtil.doOnPreDraw(
        mListView,
        true,
        new Runnable() {
          @Override
          public void run() {

            final int firstVisiblePosition = mListView.getFirstVisiblePosition();
            final AnimatorSet animSet = new AnimatorSet();
            final ArrayList<Animator> animators = new ArrayList<Animator>();
            for (int i = 0; i < mListView.getChildCount(); i++) {
              final View child = mListView.getChildAt(i);
              int position = firstVisiblePosition + i;

              // Since we are getting the position from mListView and then querying
              // mContactTileAdapter, its very possible that things are out of sync
              // and we might index out of bounds.  Let's make sure that this doesn't happen.
              if (!mContactTileAdapter.isIndexInBound(position)) {
                continue;
              }

              final long itemId = mContactTileAdapter.getItemId(position);

              if (containsId(idsInPlace, itemId)) {
                animators.add(ObjectAnimator.ofFloat(child, "alpha", 0.0f, 1.0f));
                break;
              } else {
                Integer startTop = mItemIdTopMap.get(itemId);
                Integer startLeft = mItemIdLeftMap.get(itemId);
                final int top = child.getTop();
                final int left = child.getLeft();
                int deltaX = 0;
                int deltaY = 0;

                if (startLeft != null) {
                  if (startLeft != left) {
                    deltaX = startLeft - left;
                    animators.add(ObjectAnimator.ofFloat(child, "translationX", deltaX, 0.0f));
                  }
                }

                if (startTop != null) {
                  if (startTop != top) {
                    deltaY = startTop - top;
                    animators.add(ObjectAnimator.ofFloat(child, "translationY", deltaY, 0.0f));
                  }
                }

                if (DEBUG) {
                  LogUtil.d(
                      "OldSpeedDialFragment.onPreDraw",
                      "Found itemId: "
                          + itemId
                          + " for listview child "
                          + i
                          + " Top: "
                          + top
                          + " Delta: "
                          + deltaY);
                }
              }
            }

            if (animators.size() > 0) {
              animSet.setDuration(mAnimationDuration).playTogether(animators);
              animSet.start();
            }

            mItemIdTopMap.clear();
            mItemIdLeftMap.clear();
          }
        });
  }

  private boolean containsId(long[] ids, long target) {
    // Linear search on array is fine because this is typically only 0-1 elements long
    for (int i = 0; i < ids.length; i++) {
      if (ids[i] == target) {
        return true;
      }
    }
    return false;
  }

  @Override
  public void onDataSetChangedForAnimation(long... idsInPlace) {
    animateGridView(idsInPlace);
  }

  @Override
  public void cacheOffsetsForDatasetChange() {
    saveOffsets(0);
  }

  @Override
  public void onEmptyViewActionButtonClicked() {
    final Activity activity = getActivity();
    if (activity == null) {
      return;
    }

    String[] deniedPermissions =
        PermissionsUtil.getPermissionsCurrentlyDenied(
            getContext(), PermissionsUtil.allContactsGroupPermissionsUsedInDialer);
    if (deniedPermissions.length > 0) {
      LogUtil.i(
          "OldSpeedDialFragment.onEmptyViewActionButtonClicked",
          "Requesting permissions: " + Arrays.toString(deniedPermissions));
      FragmentCompat.requestPermissions(
          this, deniedPermissions, READ_CONTACTS_PERMISSION_REQUEST_CODE);
    } else {
      // Switch tabs
      ((HostInterface) activity).showAllContactsTab();
    }
  }

  @Override
  public void onRequestPermissionsResult(
      int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == READ_CONTACTS_PERMISSION_REQUEST_CODE) {
      if (grantResults.length == 1 && PackageManager.PERMISSION_GRANTED == grantResults[0]) {
        PermissionsUtil.notifyPermissionGranted(getActivity(), READ_CONTACTS);
      }
    }
  }

  public interface HostInterface {

    void setDragDropController(DragDropController controller);

    void showAllContactsTab();
  }

  class ContactTileLoaderListener implements LoaderManager.LoaderCallbacks<Cursor> {

    @Override
    public CursorLoader onCreateLoader(int id, Bundle args) {
      if (DEBUG) {
        LogUtil.d("ContactTileLoaderListener.onCreateLoader", null);
      }
      return ContactTileLoaderFactory.createStrequentPhoneOnlyLoader(getActivity());
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
      if (DEBUG) {
        LogUtil.d("ContactTileLoaderListener.onLoadFinished", null);
      }
      mContactTileAdapter.setContactCursor(data);
      setEmptyViewVisibility(mContactTileAdapter.getCount() == 0);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
      if (DEBUG) {
        LogUtil.d("ContactTileLoaderListener.onLoaderReset", null);
      }
    }
  }

  private class ContactTileAdapterListener implements ContactTileView.Listener {

    @Override
    public void onContactSelected(
        Uri contactUri, Rect targetRect, CallSpecificAppData callSpecificAppData) {
      if (mPhoneNumberPickerActionListener != null) {
        mPhoneNumberPickerActionListener.onPickDataUri(
            contactUri, false /* isVideoCall */, callSpecificAppData);
      }
    }

    @Override
    public void onCallNumberDirectly(String phoneNumber, CallSpecificAppData callSpecificAppData) {
      if (mPhoneNumberPickerActionListener != null) {
        mPhoneNumberPickerActionListener.onPickPhoneNumber(
            phoneNumber, false /* isVideoCall */, callSpecificAppData);
      }
    }
  }

  private class ScrollListener implements ListView.OnScrollListener {

    @Override
    public void onScroll(
        AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
      if (mActivityScrollListener != null) {
        mActivityScrollListener.onListFragmentScroll(
            firstVisibleItem, visibleItemCount, totalItemCount);
      }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
      mActivityScrollListener.onListFragmentScrollStateChange(scrollState);
    }
  }
}