1/**
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy
6 * 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, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations
14 * under the License.
15 */
16
17package com.android.settings.applications;
18
19import android.app.AppOpsManager;
20import android.content.Context;
21import android.content.pm.ApplicationInfo;
22import android.content.pm.PackageInfo;
23import android.content.pm.PackageManager;
24import android.content.pm.PackageManager.NameNotFoundException;
25import android.content.res.Resources;
26import android.graphics.drawable.Drawable;
27import android.os.Parcel;
28import android.os.Parcelable;
29import android.text.format.DateUtils;
30
31import android.util.Log;
32import android.util.SparseArray;
33import com.android.settings.R;
34
35import java.io.File;
36import java.text.Collator;
37import java.util.ArrayList;
38import java.util.Collections;
39import java.util.Comparator;
40import java.util.HashMap;
41import java.util.List;
42
43public class AppOpsState {
44    static final String TAG = "AppOpsState";
45    static final boolean DEBUG = false;
46
47    final Context mContext;
48    final AppOpsManager mAppOps;
49    final PackageManager mPm;
50    final CharSequence[] mOpSummaries;
51    final CharSequence[] mOpLabels;
52
53    List<AppOpEntry> mApps;
54
55    public AppOpsState(Context context) {
56        mContext = context;
57        mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
58        mPm = context.getPackageManager();
59        mOpSummaries = context.getResources().getTextArray(R.array.app_ops_summaries);
60        mOpLabels = context.getResources().getTextArray(R.array.app_ops_labels);
61    }
62
63    public static class OpsTemplate implements Parcelable {
64        public final int[] ops;
65        public final boolean[] showPerms;
66
67        public OpsTemplate(int[] _ops, boolean[] _showPerms) {
68            ops = _ops;
69            showPerms = _showPerms;
70        }
71
72        OpsTemplate(Parcel src) {
73            ops = src.createIntArray();
74            showPerms = src.createBooleanArray();
75        }
76
77        @Override
78        public int describeContents() {
79            return 0;
80        }
81
82        @Override
83        public void writeToParcel(Parcel dest, int flags) {
84            dest.writeIntArray(ops);
85            dest.writeBooleanArray(showPerms);
86        }
87
88        public static final Creator<OpsTemplate> CREATOR = new Creator<OpsTemplate>() {
89            @Override public OpsTemplate createFromParcel(Parcel source) {
90                return new OpsTemplate(source);
91            }
92
93            @Override public OpsTemplate[] newArray(int size) {
94                return new OpsTemplate[size];
95            }
96        };
97    }
98
99    public static final OpsTemplate LOCATION_TEMPLATE = new OpsTemplate(
100            new int[] { AppOpsManager.OP_COARSE_LOCATION,
101                    AppOpsManager.OP_FINE_LOCATION,
102                    AppOpsManager.OP_GPS,
103                    AppOpsManager.OP_WIFI_SCAN,
104                    AppOpsManager.OP_NEIGHBORING_CELLS },
105            new boolean[] { true,
106                    true,
107                    false,
108                    false,
109                    false }
110            );
111
112    public static final OpsTemplate PERSONAL_TEMPLATE = new OpsTemplate(
113            new int[] { AppOpsManager.OP_READ_CONTACTS,
114                    AppOpsManager.OP_WRITE_CONTACTS,
115                    AppOpsManager.OP_READ_CALL_LOG,
116                    AppOpsManager.OP_WRITE_CALL_LOG,
117                    AppOpsManager.OP_READ_CALENDAR,
118                    AppOpsManager.OP_WRITE_CALENDAR,
119                    AppOpsManager.OP_READ_CLIPBOARD,
120                    AppOpsManager.OP_WRITE_CLIPBOARD },
121            new boolean[] { true,
122                    true,
123                    true,
124                    true,
125                    true,
126                    true,
127                    false,
128                    false }
129            );
130
131    public static final OpsTemplate MESSAGING_TEMPLATE = new OpsTemplate(
132            new int[] { AppOpsManager.OP_READ_SMS,
133                    AppOpsManager.OP_RECEIVE_SMS,
134                    AppOpsManager.OP_RECEIVE_EMERGECY_SMS,
135                    AppOpsManager.OP_RECEIVE_MMS,
136                    AppOpsManager.OP_RECEIVE_WAP_PUSH,
137                    AppOpsManager.OP_WRITE_SMS,
138                    AppOpsManager.OP_SEND_SMS,
139                    AppOpsManager.OP_READ_ICC_SMS,
140                    AppOpsManager.OP_WRITE_ICC_SMS },
141            new boolean[] { true,
142                    true,
143                    true,
144                    true,
145                    true,
146                    true,
147                    true,
148                    true,
149                    true }
150            );
151
152    public static final OpsTemplate DEVICE_TEMPLATE = new OpsTemplate(
153            new int[] { AppOpsManager.OP_VIBRATE,
154                    AppOpsManager.OP_POST_NOTIFICATION,
155                    AppOpsManager.OP_ACCESS_NOTIFICATIONS,
156                    AppOpsManager.OP_CALL_PHONE,
157                    AppOpsManager.OP_WRITE_SETTINGS,
158                    AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
159                    AppOpsManager.OP_CAMERA,
160                    AppOpsManager.OP_RECORD_AUDIO,
161                    AppOpsManager.OP_PLAY_AUDIO },
162            new boolean[] { false,
163                    false,
164                    true,
165                    true,
166                    true,
167                    true,
168                    true,
169                    true,
170                    true }
171            );
172
173    public static final OpsTemplate[] ALL_TEMPLATES = new OpsTemplate[] {
174            LOCATION_TEMPLATE, PERSONAL_TEMPLATE, MESSAGING_TEMPLATE, DEVICE_TEMPLATE
175    };
176
177    /**
178     * This class holds the per-item data in our Loader.
179     */
180    public static class AppEntry {
181        private final AppOpsState mState;
182        private final ApplicationInfo mInfo;
183        private final File mApkFile;
184        private final SparseArray<AppOpsManager.OpEntry> mOps
185                = new SparseArray<AppOpsManager.OpEntry>();
186        private final SparseArray<AppOpEntry> mOpSwitches
187                = new SparseArray<AppOpEntry>();
188        private String mLabel;
189        private Drawable mIcon;
190        private boolean mMounted;
191
192        public AppEntry(AppOpsState state, ApplicationInfo info) {
193            mState = state;
194            mInfo = info;
195            mApkFile = new File(info.sourceDir);
196        }
197
198        public void addOp(AppOpEntry entry, AppOpsManager.OpEntry op) {
199            mOps.put(op.getOp(), op);
200            mOpSwitches.put(AppOpsManager.opToSwitch(op.getOp()), entry);
201        }
202
203        public boolean hasOp(int op) {
204            return mOps.indexOfKey(op) >= 0;
205        }
206
207        public AppOpEntry getOpSwitch(int op) {
208            return mOpSwitches.get(AppOpsManager.opToSwitch(op));
209        }
210
211        public ApplicationInfo getApplicationInfo() {
212            return mInfo;
213        }
214
215        public String getLabel() {
216            return mLabel;
217        }
218
219        public Drawable getIcon() {
220            if (mIcon == null) {
221                if (mApkFile.exists()) {
222                    mIcon = mInfo.loadIcon(mState.mPm);
223                    return mIcon;
224                } else {
225                    mMounted = false;
226                }
227            } else if (!mMounted) {
228                // If the app wasn't mounted but is now mounted, reload
229                // its icon.
230                if (mApkFile.exists()) {
231                    mMounted = true;
232                    mIcon = mInfo.loadIcon(mState.mPm);
233                    return mIcon;
234                }
235            } else {
236                return mIcon;
237            }
238
239            return mState.mContext.getResources().getDrawable(
240                    android.R.drawable.sym_def_app_icon);
241        }
242
243        @Override public String toString() {
244            return mLabel;
245        }
246
247        void loadLabel(Context context) {
248            if (mLabel == null || !mMounted) {
249                if (!mApkFile.exists()) {
250                    mMounted = false;
251                    mLabel = mInfo.packageName;
252                } else {
253                    mMounted = true;
254                    CharSequence label = mInfo.loadLabel(context.getPackageManager());
255                    mLabel = label != null ? label.toString() : mInfo.packageName;
256                }
257            }
258        }
259    }
260
261    /**
262     * This class holds the per-item data in our Loader.
263     */
264    public static class AppOpEntry {
265        private final AppOpsManager.PackageOps mPkgOps;
266        private final ArrayList<AppOpsManager.OpEntry> mOps
267                = new ArrayList<AppOpsManager.OpEntry>();
268        private final ArrayList<AppOpsManager.OpEntry> mSwitchOps
269                = new ArrayList<AppOpsManager.OpEntry>();
270        private final AppEntry mApp;
271        private final int mSwitchOrder;
272
273        public AppOpEntry(AppOpsManager.PackageOps pkg, AppOpsManager.OpEntry op, AppEntry app,
274                int switchOrder) {
275            mPkgOps = pkg;
276            mApp = app;
277            mSwitchOrder = switchOrder;
278            mApp.addOp(this, op);
279            mOps.add(op);
280            mSwitchOps.add(op);
281        }
282
283        private static void addOp(ArrayList<AppOpsManager.OpEntry> list, AppOpsManager.OpEntry op) {
284            for (int i=0; i<list.size(); i++) {
285                AppOpsManager.OpEntry pos = list.get(i);
286                if (pos.isRunning() != op.isRunning()) {
287                    if (op.isRunning()) {
288                        list.add(i, op);
289                        return;
290                    }
291                    continue;
292                }
293                if (pos.getTime() < op.getTime()) {
294                    list.add(i, op);
295                    return;
296                }
297            }
298            list.add(op);
299        }
300
301        public void addOp(AppOpsManager.OpEntry op) {
302            mApp.addOp(this, op);
303            addOp(mOps, op);
304            if (mApp.getOpSwitch(AppOpsManager.opToSwitch(op.getOp())) == null) {
305                addOp(mSwitchOps, op);
306            }
307        }
308
309        public AppEntry getAppEntry() {
310            return mApp;
311        }
312
313        public int getSwitchOrder() {
314            return mSwitchOrder;
315        }
316
317        public AppOpsManager.PackageOps getPackageOps() {
318            return mPkgOps;
319        }
320
321        public int getNumOpEntry() {
322            return mOps.size();
323        }
324
325        public AppOpsManager.OpEntry getOpEntry(int pos) {
326            return mOps.get(pos);
327        }
328
329        private CharSequence getCombinedText(ArrayList<AppOpsManager.OpEntry> ops,
330                CharSequence[] items) {
331            if (ops.size() == 1) {
332                return items[ops.get(0).getOp()];
333            } else {
334                StringBuilder builder = new StringBuilder();
335                for (int i=0; i<ops.size(); i++) {
336                    if (i > 0) {
337                        builder.append(", ");
338                    }
339                    builder.append(items[ops.get(i).getOp()]);
340                }
341                return builder.toString();
342            }
343        }
344
345        public CharSequence getSummaryText(AppOpsState state) {
346            return getCombinedText(mOps, state.mOpSummaries);
347        }
348
349        public CharSequence getSwitchText(AppOpsState state) {
350            if (mSwitchOps.size() > 0) {
351                return getCombinedText(mSwitchOps, state.mOpLabels);
352            } else {
353                return getCombinedText(mOps, state.mOpLabels);
354            }
355        }
356
357        public CharSequence getTimeText(Resources res, boolean showEmptyText) {
358            if (isRunning()) {
359                return res.getText(R.string.app_ops_running);
360            }
361            if (getTime() > 0) {
362                return DateUtils.getRelativeTimeSpanString(getTime(),
363                        System.currentTimeMillis(),
364                        DateUtils.MINUTE_IN_MILLIS,
365                        DateUtils.FORMAT_ABBREV_RELATIVE);
366            }
367            return showEmptyText ? res.getText(R.string.app_ops_never_used) : "";
368        }
369
370        public boolean isRunning() {
371            return mOps.get(0).isRunning();
372        }
373
374        public long getTime() {
375            return mOps.get(0).getTime();
376        }
377
378        @Override public String toString() {
379            return mApp.getLabel();
380        }
381    }
382
383    /**
384     * Perform alphabetical comparison of application entry objects.
385     */
386    public static final Comparator<AppOpEntry> APP_OP_COMPARATOR = new Comparator<AppOpEntry>() {
387        private final Collator sCollator = Collator.getInstance();
388        @Override
389        public int compare(AppOpEntry object1, AppOpEntry object2) {
390            if (object1.getSwitchOrder() != object2.getSwitchOrder()) {
391                return object1.getSwitchOrder() < object2.getSwitchOrder() ? -1 : 1;
392            }
393            if (object1.isRunning() != object2.isRunning()) {
394                // Currently running ops go first.
395                return object1.isRunning() ? -1 : 1;
396            }
397            if (object1.getTime() != object2.getTime()) {
398                // More recent times go first.
399                return object1.getTime() > object2.getTime() ? -1 : 1;
400            }
401            return sCollator.compare(object1.getAppEntry().getLabel(),
402                    object2.getAppEntry().getLabel());
403        }
404    };
405
406    private void addOp(List<AppOpEntry> entries, AppOpsManager.PackageOps pkgOps,
407            AppEntry appEntry, AppOpsManager.OpEntry opEntry, boolean allowMerge, int switchOrder) {
408        if (allowMerge && entries.size() > 0) {
409            AppOpEntry last = entries.get(entries.size()-1);
410            if (last.getAppEntry() == appEntry) {
411                boolean lastExe = last.getTime() != 0;
412                boolean entryExe = opEntry.getTime() != 0;
413                if (lastExe == entryExe) {
414                    if (DEBUG) Log.d(TAG, "Add op " + opEntry.getOp() + " to package "
415                            + pkgOps.getPackageName() + ": append to " + last);
416                    last.addOp(opEntry);
417                    return;
418                }
419            }
420        }
421        AppOpEntry entry = appEntry.getOpSwitch(opEntry.getOp());
422        if (entry != null) {
423            entry.addOp(opEntry);
424            return;
425        }
426        entry = new AppOpEntry(pkgOps, opEntry, appEntry, switchOrder);
427        if (DEBUG) Log.d(TAG, "Add op " + opEntry.getOp() + " to package "
428                + pkgOps.getPackageName() + ": making new " + entry);
429        entries.add(entry);
430    }
431
432    public List<AppOpEntry> buildState(OpsTemplate tpl) {
433        return buildState(tpl, 0, null);
434    }
435
436    private AppEntry getAppEntry(final Context context, final HashMap<String, AppEntry> appEntries,
437            final String packageName, ApplicationInfo appInfo) {
438        AppEntry appEntry = appEntries.get(packageName);
439        if (appEntry == null) {
440            if (appInfo == null) {
441                try {
442                    appInfo = mPm.getApplicationInfo(packageName,
443                            PackageManager.GET_DISABLED_COMPONENTS
444                            | PackageManager.GET_UNINSTALLED_PACKAGES);
445                } catch (PackageManager.NameNotFoundException e) {
446                    Log.w(TAG, "Unable to find info for package " + packageName);
447                    return null;
448                }
449            }
450            appEntry = new AppEntry(this, appInfo);
451            appEntry.loadLabel(context);
452            appEntries.put(packageName, appEntry);
453        }
454        return appEntry;
455    }
456
457    public List<AppOpEntry> buildState(OpsTemplate tpl, int uid, String packageName) {
458        final Context context = mContext;
459
460        final HashMap<String, AppEntry> appEntries = new HashMap<String, AppEntry>();
461        final List<AppOpEntry> entries = new ArrayList<AppOpEntry>();
462
463        final ArrayList<String> perms = new ArrayList<String>();
464        final ArrayList<Integer> permOps = new ArrayList<Integer>();
465        final int[] opToOrder = new int[AppOpsManager._NUM_OP];
466        for (int i=0; i<tpl.ops.length; i++) {
467            if (tpl.showPerms[i]) {
468                String perm = AppOpsManager.opToPermission(tpl.ops[i]);
469                if (perm != null && !perms.contains(perm)) {
470                    perms.add(perm);
471                    permOps.add(tpl.ops[i]);
472                    opToOrder[tpl.ops[i]] = i;
473                }
474            }
475        }
476
477        List<AppOpsManager.PackageOps> pkgs;
478        if (packageName != null) {
479            pkgs = mAppOps.getOpsForPackage(uid, packageName, tpl.ops);
480        } else {
481            pkgs = mAppOps.getPackagesForOps(tpl.ops);
482        }
483
484        if (pkgs != null) {
485            for (int i=0; i<pkgs.size(); i++) {
486                AppOpsManager.PackageOps pkgOps = pkgs.get(i);
487                AppEntry appEntry = getAppEntry(context, appEntries, pkgOps.getPackageName(), null);
488                if (appEntry == null) {
489                    continue;
490                }
491                for (int j=0; j<pkgOps.getOps().size(); j++) {
492                    AppOpsManager.OpEntry opEntry = pkgOps.getOps().get(j);
493                    addOp(entries, pkgOps, appEntry, opEntry, packageName == null,
494                            packageName == null ? 0 : opToOrder[opEntry.getOp()]);
495                }
496            }
497        }
498
499        List<PackageInfo> apps;
500        if (packageName != null) {
501            apps = new ArrayList<PackageInfo>();
502            try {
503                PackageInfo pi = mPm.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
504                apps.add(pi);
505            } catch (NameNotFoundException e) {
506            }
507        } else {
508            String[] permsArray = new String[perms.size()];
509            perms.toArray(permsArray);
510            apps = mPm.getPackagesHoldingPermissions(permsArray, 0);
511        }
512        for (int i=0; i<apps.size(); i++) {
513            PackageInfo appInfo = apps.get(i);
514            AppEntry appEntry = getAppEntry(context, appEntries, appInfo.packageName,
515                    appInfo.applicationInfo);
516            if (appEntry == null) {
517                continue;
518            }
519            List<AppOpsManager.OpEntry> dummyOps = null;
520            AppOpsManager.PackageOps pkgOps = null;
521            if (appInfo.requestedPermissions != null) {
522                for (int j=0; j<appInfo.requestedPermissions.length; j++) {
523                    if (appInfo.requestedPermissionsFlags != null) {
524                        if ((appInfo.requestedPermissionsFlags[j]
525                                & PackageInfo.REQUESTED_PERMISSION_GRANTED) == 0) {
526                            if (DEBUG) Log.d(TAG, "Pkg " + appInfo.packageName + " perm "
527                                    + appInfo.requestedPermissions[j] + " not granted; skipping");
528                            break;
529                        }
530                    }
531                    if (DEBUG) Log.d(TAG, "Pkg " + appInfo.packageName + ": requested perm "
532                            + appInfo.requestedPermissions[j]);
533                    for (int k=0; k<perms.size(); k++) {
534                        if (!perms.get(k).equals(appInfo.requestedPermissions[j])) {
535                            continue;
536                        }
537                        if (DEBUG) Log.d(TAG, "Pkg " + appInfo.packageName + " perm " + perms.get(k)
538                                + " has op " + permOps.get(k) + ": " + appEntry.hasOp(permOps.get(k)));
539                        if (appEntry.hasOp(permOps.get(k))) {
540                            continue;
541                        }
542                        if (dummyOps == null) {
543                            dummyOps = new ArrayList<AppOpsManager.OpEntry>();
544                            pkgOps = new AppOpsManager.PackageOps(
545                                    appInfo.packageName, appInfo.applicationInfo.uid, dummyOps);
546
547                        }
548                        AppOpsManager.OpEntry opEntry = new AppOpsManager.OpEntry(
549                                permOps.get(k), AppOpsManager.MODE_ALLOWED, 0, 0, 0);
550                        dummyOps.add(opEntry);
551                        addOp(entries, pkgOps, appEntry, opEntry, packageName == null,
552                                packageName == null ? 0 : opToOrder[opEntry.getOp()]);
553                    }
554                }
555            }
556        }
557
558        // Sort the list.
559        Collections.sort(entries, APP_OP_COMPARATOR);
560
561        // Done!
562        return entries;
563    }
564}
565