1/*
2 * Copyright (C) 2016 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 com.android.dialer.shortcuts;
18
19import android.Manifest;
20import android.annotation.TargetApi;
21import android.content.Context;
22import android.content.pm.PackageManager;
23import android.content.pm.ShortcutInfo;
24import android.content.pm.ShortcutManager;
25import android.os.Build.VERSION_CODES;
26import android.support.annotation.NonNull;
27import android.support.annotation.WorkerThread;
28import android.support.v4.content.ContextCompat;
29import android.util.ArrayMap;
30import com.android.contacts.common.list.ContactEntry;
31import com.android.dialer.common.Assert;
32import com.android.dialer.common.LogUtil;
33import java.util.ArrayList;
34import java.util.List;
35import java.util.Map;
36import java.util.Map.Entry;
37
38/**
39 * Handles refreshing of dialer dynamic shortcuts.
40 *
41 * <p>Dynamic shortcuts are the list of shortcuts which is accessible by tapping and holding the
42 * dialer launcher icon from the app drawer or a home screen.
43 *
44 * <p>Dynamic shortcuts are refreshed whenever the dialtacts activity detects changes to favorites
45 * tiles. This class compares the newly updated favorites tiles to the existing list of (previously
46 * published) dynamic shortcuts to compute a delta, which consists of lists of shortcuts which need
47 * to be updated, added, or deleted.
48 *
49 * <p>Dynamic shortcuts should mirror (in order) the contacts displayed in the "tiled favorites" tab
50 * of the dialer application. When selecting a dynamic shortcut, the behavior should be the same as
51 * if the user had tapped on the contact from the tiled favorites tab. Specifically, if the user has
52 * more than one phone number, a number picker should be displayed, and otherwise the contact should
53 * be called directly.
54 *
55 * <p>Note that an icon change by itself does not trigger a shortcut update, because it is not
56 * possible to detect an icon update and we don't want to constantly force update icons, because
57 * that is an expensive operation which requires storage I/O.
58 *
59 * <p>However, the job scheduler uses {@link #updateIcons()} to makes sure icons are forcefully
60 * updated periodically (about once a day).
61 *
62 */
63@TargetApi(VERSION_CODES.N_MR1) // Shortcuts introduced in N MR1
64final class DynamicShortcuts {
65
66  private static final int MAX_DYNAMIC_SHORTCUTS = 3;
67
68  private static class Delta {
69
70    final Map<String, DialerShortcut> shortcutsToUpdateById = new ArrayMap<>();
71    final List<String> shortcutIdsToRemove = new ArrayList<>();
72    final Map<String, DialerShortcut> shortcutsToAddById = new ArrayMap<>();
73  }
74
75  private final Context context;
76  private final ShortcutInfoFactory shortcutInfoFactory;
77
78  DynamicShortcuts(@NonNull Context context, IconFactory iconFactory) {
79    this.context = context;
80    this.shortcutInfoFactory = new ShortcutInfoFactory(context, iconFactory);
81  }
82
83  /**
84   * Performs a "complete refresh" of dynamic shortcuts. This is done by comparing the provided
85   * contact information with the existing dynamic shortcuts in order to compute a delta which
86   * contains shortcuts which should be added, updated, or removed.
87   *
88   * <p>If the delta is non-empty, it is applied by making appropriate calls to the {@link
89   * ShortcutManager} system service.
90   *
91   * <p>This is a slow blocking call which performs file I/O and should not be performed on the main
92   * thread.
93   */
94  @WorkerThread
95  public void refresh(List<ContactEntry> contacts) {
96    Assert.isWorkerThread();
97    LogUtil.enterBlock("DynamicShortcuts.refresh");
98
99    ShortcutManager shortcutManager = getShortcutManager(context);
100
101    if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS)
102        != PackageManager.PERMISSION_GRANTED) {
103      LogUtil.i("DynamicShortcuts.refresh", "no contact permissions");
104      shortcutManager.removeAllDynamicShortcuts();
105      return;
106    }
107
108    // Fill the available shortcuts with dynamic shortcuts up to a maximum of 3 dynamic shortcuts.
109    int numDynamicShortcutsToCreate =
110        Math.min(
111            MAX_DYNAMIC_SHORTCUTS,
112            shortcutManager.getMaxShortcutCountPerActivity()
113                - shortcutManager.getManifestShortcuts().size());
114
115    Map<String, DialerShortcut> newDynamicShortcutsById =
116        new ArrayMap<>(numDynamicShortcutsToCreate);
117    int rank = 0;
118    for (ContactEntry entry : contacts) {
119      if (newDynamicShortcutsById.size() >= numDynamicShortcutsToCreate) {
120        break;
121      }
122
123      DialerShortcut shortcut =
124          DialerShortcut.builder()
125              .setContactId(entry.id)
126              .setLookupKey(entry.lookupKey)
127              .setDisplayName(entry.getPreferredDisplayName())
128              .setRank(rank++)
129              .build();
130      newDynamicShortcutsById.put(shortcut.getShortcutId(), shortcut);
131    }
132
133    List<ShortcutInfo> oldDynamicShortcuts = new ArrayList<>(shortcutManager.getDynamicShortcuts());
134    Delta delta = computeDelta(oldDynamicShortcuts, newDynamicShortcutsById);
135    applyDelta(delta);
136  }
137
138  /**
139   * Forces an update of all dynamic shortcut icons. This should only be done from job scheduler as
140   * updating icons requires storage I/O.
141   */
142  @WorkerThread
143  void updateIcons() {
144    Assert.isWorkerThread();
145    LogUtil.enterBlock("DynamicShortcuts.updateIcons");
146
147    if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS)
148        != PackageManager.PERMISSION_GRANTED) {
149      LogUtil.i("DynamicShortcuts.updateIcons", "no contact permissions");
150      return;
151    }
152
153    ShortcutManager shortcutManager = getShortcutManager(context);
154
155    int maxDynamicShortcutsToCreate =
156        shortcutManager.getMaxShortcutCountPerActivity()
157            - shortcutManager.getManifestShortcuts().size();
158    int count = 0;
159
160    List<ShortcutInfo> newShortcuts = new ArrayList<>();
161    for (ShortcutInfo oldInfo : shortcutManager.getDynamicShortcuts()) {
162      newShortcuts.add(shortcutInfoFactory.withUpdatedIcon(oldInfo));
163      if (++count >= maxDynamicShortcutsToCreate) {
164        break;
165      }
166    }
167    LogUtil.i("DynamicShortcuts.updateIcons", "updating %d shortcut icons", newShortcuts.size());
168    shortcutManager.setDynamicShortcuts(newShortcuts);
169  }
170
171  @NonNull
172  private Delta computeDelta(
173      @NonNull List<ShortcutInfo> oldDynamicShortcuts,
174      @NonNull Map<String, DialerShortcut> newDynamicShortcutsById) {
175    Delta delta = new Delta();
176    if (oldDynamicShortcuts.isEmpty()) {
177      delta.shortcutsToAddById.putAll(newDynamicShortcutsById);
178      return delta;
179    }
180
181    for (ShortcutInfo oldInfo : oldDynamicShortcuts) {
182      // Check to see if the new shortcut list contains the existing shortcut.
183      DialerShortcut newShortcut = newDynamicShortcutsById.get(oldInfo.getId());
184      if (newShortcut != null) {
185        if (newShortcut.needsUpdate(oldInfo)) {
186          LogUtil.i("DynamicShortcuts.computeDelta", "contact updated");
187          delta.shortcutsToUpdateById.put(oldInfo.getId(), newShortcut);
188        } // else the shortcut hasn't changed, nothing to do to it
189      } else {
190        // The old shortcut is not in the new shortcut list, remove it.
191        LogUtil.i("DynamicShortcuts.computeDelta", "contact removed");
192        delta.shortcutIdsToRemove.add(oldInfo.getId());
193      }
194    }
195
196    // Add any new shortcuts that were not in the old shortcuts.
197    for (Entry<String, DialerShortcut> entry : newDynamicShortcutsById.entrySet()) {
198      String newId = entry.getKey();
199      DialerShortcut newShortcut = entry.getValue();
200      if (!containsShortcut(oldDynamicShortcuts, newId)) {
201        // The new shortcut was not found in the old shortcut list, so add it.
202        LogUtil.i("DynamicShortcuts.computeDelta", "contact added");
203        delta.shortcutsToAddById.put(newId, newShortcut);
204      }
205    }
206    return delta;
207  }
208
209  private void applyDelta(@NonNull Delta delta) {
210    ShortcutManager shortcutManager = getShortcutManager(context);
211    // Must perform remove before performing add to avoid adding more than supported by system.
212    if (!delta.shortcutIdsToRemove.isEmpty()) {
213      shortcutManager.removeDynamicShortcuts(delta.shortcutIdsToRemove);
214    }
215    if (!delta.shortcutsToUpdateById.isEmpty()) {
216      // Note: This may update pinned shortcuts as well. Pinned shortcuts which are also dynamic
217      // are not updated by the pinned shortcut logic. The reason that they are updated here
218      // instead of in the pinned shortcut logic is because setRank is required and only available
219      // here.
220      shortcutManager.updateShortcuts(
221          shortcutInfoFactory.buildShortcutInfos(delta.shortcutsToUpdateById));
222    }
223    if (!delta.shortcutsToAddById.isEmpty()) {
224      shortcutManager.addDynamicShortcuts(
225          shortcutInfoFactory.buildShortcutInfos(delta.shortcutsToAddById));
226    }
227  }
228
229  private boolean containsShortcut(
230      @NonNull List<ShortcutInfo> shortcutInfos, @NonNull String shortcutId) {
231    for (ShortcutInfo oldInfo : shortcutInfos) {
232      if (oldInfo.getId().equals(shortcutId)) {
233        return true;
234      }
235    }
236    return false;
237  }
238
239  private static ShortcutManager getShortcutManager(Context context) {
240    //noinspection WrongConstant
241    return (ShortcutManager) context.getSystemService(Context.SHORTCUT_SERVICE);
242  }
243}
244