App ops: add UI for viewing and controlling ops per-app.

Change-Id: Iadd68cbd429af4d431dcd09b9adacd09c5092ae6
diff --git a/res/layout/app_ops_details.xml b/res/layout/app_ops_details.xml
new file mode 100644
index 0000000..d28689d
--- /dev/null
+++ b/res/layout/app_ops_details.xml
@@ -0,0 +1,57 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+/*
+** Copyright 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.
+*/
+-->
+<ScrollView
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:clipToPadding="false"
+    android:scrollbarStyle="@*android:integer/preference_fragment_scrollbarStyle">
+
+    <LinearLayout
+        android:id="@+id/all_details"
+        android:layout_width="match_parent"
+        android:layout_height="match_parent"
+        android:paddingBottom="5dip"
+        android:orientation="vertical">
+
+        <!-- App snippet -->
+        <LinearLayout
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:layout_gravity="center_vertical"
+            android:paddingStart="?android:attr/listPreferredItemPaddingStart"
+            android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
+            android:orientation="vertical">
+
+            <!-- Application snippet label, version and icon -->
+            <include
+                layout="@layout/manage_applications_item"
+                android:id="@+id/app_snippet" />
+
+        </LinearLayout>
+
+        <!-- Operations list -->
+        <LinearLayout
+            android:id="@+id/operations_section"
+            android:layout_width="match_parent"
+            android:layout_height="match_parent"
+            android:orientation="vertical">
+        </LinearLayout>
+    </LinearLayout>
+</ScrollView>
diff --git a/res/layout/app_ops_details_item.xml b/res/layout/app_ops_details_item.xml
new file mode 100644
index 0000000..a0434fc
--- /dev/null
+++ b/res/layout/app_ops_details_item.xml
@@ -0,0 +1,71 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+/*
+** Copyright 2008, 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.
+*/
+-->
+
+<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="wrap_content"
+    android:minHeight="?android:attr/listPreferredItemHeight"
+    android:paddingStart="?android:attr/listPreferredItemPaddingStart"
+    android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
+    android:paddingTop="8dip"
+    android:paddingBottom="8dip"
+    android:columnCount="3">
+
+    <ImageView
+        android:id="@+id/op_icon"
+        android:layout_width="@android:dimen/app_icon_size"
+        android:layout_height="@android:dimen/app_icon_size"
+        android:layout_column="0"
+        android:layout_row="0"
+        android:layout_rowSpan="2"
+        android:layout_marginEnd="8dip"
+        android:scaleType="centerInside"
+        android:contentDescription="@null" />
+
+    <TextView
+        android:id="@+id/op_name"
+        android:layout_column="1"
+        android:layout_row="0"
+        android:layout_gravity="fill_horizontal"
+        android:layout_marginTop="2dip"
+        android:singleLine="true"
+        android:ellipsize="marquee"
+        android:textAppearance="?android:attr/textAppearanceMedium"
+        android:textAlignment="viewStart" />
+
+    <TextView
+        android:id="@+id/op_time"
+        android:layout_column="1"
+        android:layout_row="1"
+        android:layout_gravity="fill_horizontal"
+        android:textAppearance="?android:attr/textAppearanceSmall"
+        android:textAlignment="viewStart" />
+
+    <Switch android:id="@+id/switchWidget"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_marginStart="8dip"
+        android:layout_column="2"
+        android:layout_row="0"
+        android:layout_rowSpan="2"
+        android:padding="8dip"
+        android:focusable="false"
+        android:clickable="true" />
+
+</GridLayout>
diff --git a/res/values/arrays.xml b/res/values/arrays.xml
index a8a371f..797e634 100644
--- a/res/values/arrays.xml
+++ b/res/values/arrays.xml
@@ -572,6 +572,9 @@
         <item>Write contacts</item>
         <item>Read calls</item>
         <item>Write calls</item>
+        <item>Read calendar</item>
+        <item>Write calendar</item>
+        <item>Wi-Fi scan</item>
     </string-array>
     
     <!-- Titles for the list of long press timeout options. -->
diff --git a/res/values/strings.xml b/res/values/strings.xml
index 419cb11..01a5215 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -2705,7 +2705,9 @@
     <string name="app_ops_settings">App ops</string>
     <!-- [CHAR LIMIT=NONE] Time label for an operation that is currently running. -->
     <string name="app_ops_running">Running</string>
-    
+    <!-- [CHAR LIMIT=NONE] Time label for an operation that has never executed. -->
+    <string name="app_ops_never_used">(Never used)</string>
+
     <!-- [CHAR LIMIT=25] Services settings screen, setting option name for the user to go to the screen to view app storage use -->
     <string name="storageuse_settings_title">Storage use</string>
     <!-- Services settings screen, setting option summary for the user to go to the screen to app storage use -->
diff --git a/src/com/android/settings/applications/AppOpsCategory.java b/src/com/android/settings/applications/AppOpsCategory.java
index 1eafbbf..fa164ab 100644
--- a/src/com/android/settings/applications/AppOpsCategory.java
+++ b/src/com/android/settings/applications/AppOpsCategory.java
@@ -28,6 +28,7 @@
 import android.content.res.Configuration;
 import android.content.res.Resources;
 import android.os.Bundle;
+import android.preference.PreferenceActivity;
 import android.util.Log;
 import android.view.LayoutInflater;
 import android.view.View;
@@ -45,9 +46,15 @@
 public class AppOpsCategory extends ListFragment implements
         LoaderManager.LoaderCallbacks<List<AppOpEntry>> {
 
+    private static final int RESULT_APP_DETAILS = 1;
+
+    AppOpsState mState;
+
     // This is the Adapter being used to display the list's data.
     AppListAdapter mAdapter;
 
+    String mCurrentPkgName;
+
     public AppOpsCategory() {
     }
 
@@ -115,9 +122,9 @@
         List<AppOpEntry> mApps;
         PackageIntentReceiver mPackageObserver;
 
-        public AppListLoader(Context context, AppOpsState.OpsTemplate template) {
+        public AppListLoader(Context context, AppOpsState state, AppOpsState.OpsTemplate template) {
             super(context);
-            mState = new AppOpsState(context);
+            mState = state;
             mTemplate = template;
         }
 
@@ -236,13 +243,13 @@
     public static class AppListAdapter extends ArrayAdapter<AppOpEntry> {
         private final Resources mResources;
         private final LayoutInflater mInflater;
-        private final CharSequence[] mOpNames;
+        private final AppOpsState mState;
 
-        public AppListAdapter(Context context) {
+        public AppListAdapter(Context context, AppOpsState state) {
             super(context, android.R.layout.simple_list_item_2);
             mResources = context.getResources();
             mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
-            mOpNames = mResources.getTextArray(R.array.app_ops_names);
+            mState = state;
         }
 
         public void setData(List<AppOpEntry> data) {
@@ -268,13 +275,19 @@
             ((ImageView)view.findViewById(R.id.app_icon)).setImageDrawable(
                     item.getAppEntry().getIcon());
             ((TextView)view.findViewById(R.id.app_name)).setText(item.getAppEntry().getLabel());
-            ((TextView)view.findViewById(R.id.op_name)).setText(item.getLabelText(mOpNames));
+            ((TextView)view.findViewById(R.id.op_name)).setText(item.getLabelText(mState));
             ((TextView)view.findViewById(R.id.op_time)).setText(item.getTimeText(mResources));
 
             return view;
         }
     }
 
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        mState = new AppOpsState(getActivity());
+    }
+
     @Override public void onActivityCreated(Bundle savedInstanceState) {
         super.onActivityCreated(savedInstanceState);
 
@@ -286,7 +299,7 @@
         setHasOptionsMenu(true);
 
         // Create an empty adapter we will use to display the loaded data.
-        mAdapter = new AppListAdapter(getActivity());
+        mAdapter = new AppListAdapter(getActivity(), mState);
         setListAdapter(mAdapter);
 
         // Start out with a progress indicator.
@@ -297,9 +310,23 @@
         getLoaderManager().initLoader(0, null, this);
     }
 
+    // utility method used to start sub activity
+    private void startApplicationDetailsActivity() {
+        // start new fragment to display extended information
+        Bundle args = new Bundle();
+        args.putString(AppOpsDetails.ARG_PACKAGE_NAME, mCurrentPkgName);
+
+        PreferenceActivity pa = (PreferenceActivity)getActivity();
+        pa.startPreferencePanel(AppOpsDetails.class.getName(), args,
+                R.string.app_ops_settings, null, this, RESULT_APP_DETAILS);
+    }
+    
     @Override public void onListItemClick(ListView l, View v, int position, long id) {
-        // Insert desired behavior here.
-        Log.i("LoaderCustom", "Item clicked: " + id);
+        AppOpEntry entry = mAdapter.getItem(position);
+        if (entry != null) {
+            mCurrentPkgName = entry.getAppEntry().getApplicationInfo().packageName;
+            startApplicationDetailsActivity();
+        }
     }
 
     @Override public Loader<List<AppOpEntry>> onCreateLoader(int id, Bundle args) {
@@ -308,7 +335,7 @@
         if (fargs != null) {
             template = (AppOpsState.OpsTemplate)fargs.getParcelable("template");
         }
-        return new AppListLoader(getActivity(), template);
+        return new AppListLoader(getActivity(), mState, template);
     }
 
     @Override public void onLoadFinished(Loader<List<AppOpEntry>> loader, List<AppOpEntry> data) {
diff --git a/src/com/android/settings/applications/AppOpsDetails.java b/src/com/android/settings/applications/AppOpsDetails.java
index 2a071f2..9bc90a7 100644
--- a/src/com/android/settings/applications/AppOpsDetails.java
+++ b/src/com/android/settings/applications/AppOpsDetails.java
@@ -16,8 +16,182 @@
 
 package com.android.settings.applications;
 
+import android.app.Activity;
+import android.app.AppOpsManager;
 import android.app.Fragment;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.PackageManager.NameNotFoundException;
+import android.content.pm.PermissionGroupInfo;
+import android.content.pm.PermissionInfo;
+import android.content.res.Resources;
+import android.os.Bundle;
+import android.preference.PreferenceActivity;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.CompoundButton;
+import android.widget.ImageView;
+import android.widget.LinearLayout;
+import android.widget.Switch;
+import android.widget.TextView;
+
+import com.android.settings.R;
+import com.android.settings.Utils;
+
+import java.util.List;
 
 public class AppOpsDetails extends Fragment {
+    static final String TAG = "AppOpsDetails";
 
+    public static final String ARG_PACKAGE_NAME = "package";
+
+    private AppOpsState mState;
+    private PackageManager mPm;
+    private AppOpsManager mAppOps;
+    private PackageInfo mPackageInfo;
+    private LayoutInflater mInflater;
+    private View mRootView;
+    private TextView mAppVersion;
+    private LinearLayout mOperationsSection;
+
+    // Utility method to set application label and icon.
+    private void setAppLabelAndIcon(PackageInfo pkgInfo) {
+        final View appSnippet = mRootView.findViewById(R.id.app_snippet);
+        appSnippet.setPaddingRelative(0, appSnippet.getPaddingTop(), 0, appSnippet.getPaddingBottom());
+
+        ImageView icon = (ImageView) appSnippet.findViewById(R.id.app_icon);
+        icon.setImageDrawable(mPm.getApplicationIcon(pkgInfo.applicationInfo));
+        // Set application name.
+        TextView label = (TextView) appSnippet.findViewById(R.id.app_name);
+        label.setText(mPm.getApplicationLabel(pkgInfo.applicationInfo));
+        // Version number of application
+        mAppVersion = (TextView) appSnippet.findViewById(R.id.app_size);
+
+        if (pkgInfo.versionName != null) {
+            mAppVersion.setVisibility(View.VISIBLE);
+            mAppVersion.setText(getActivity().getString(R.string.version_text,
+                    String.valueOf(pkgInfo.versionName)));
+        } else {
+            mAppVersion.setVisibility(View.INVISIBLE);
+        }
+    }
+
+    private String retrieveAppEntry() {
+        final Bundle args = getArguments();
+        String packageName = (args != null) ? args.getString(ARG_PACKAGE_NAME) : null;
+        if (packageName == null) {
+            Intent intent = (args == null) ?
+                    getActivity().getIntent() : (Intent) args.getParcelable("intent");
+            if (intent != null) {
+                packageName = intent.getData().getSchemeSpecificPart();
+            }
+        }
+        try {
+            mPackageInfo = mPm.getPackageInfo(packageName,
+                    PackageManager.GET_DISABLED_COMPONENTS |
+                    PackageManager.GET_UNINSTALLED_PACKAGES);
+        } catch (NameNotFoundException e) {
+            Log.e(TAG, "Exception when retrieving package:" + packageName, e);
+            mPackageInfo = null;
+        }
+
+        return packageName;
+    }
+
+    private boolean refreshUi() {
+        if (mPackageInfo == null) {
+            return false;
+        }
+
+        setAppLabelAndIcon(mPackageInfo);
+
+        Resources res = getActivity().getResources();
+
+        mOperationsSection.removeAllViews();
+        String lastPermGroup = "";
+        for (AppOpsState.OpsTemplate tpl : AppOpsState.ALL_TEMPLATES) {
+            List<AppOpsState.AppOpEntry> entries = mState.buildState(tpl,
+                    mPackageInfo.applicationInfo.uid, mPackageInfo.packageName);
+            for (final AppOpsState.AppOpEntry entry : entries) {
+                for (int i=0; i<entry.getNumOpEntry(); i++) {
+                    final AppOpsManager.OpEntry op = entry.getOpEntry(i);
+                    final View view = mInflater.inflate(R.layout.app_ops_details_item,
+                            mOperationsSection, false);
+                    mOperationsSection.addView(view);
+                    String perm = AppOpsManager.opToPermission(op.getOp());
+                    try {
+                        PermissionInfo pi = mPm.getPermissionInfo(perm, 0);
+                        if (pi.group != null && !lastPermGroup.equals(pi.group)) {
+                            lastPermGroup = pi.group;
+                            PermissionGroupInfo pgi = mPm.getPermissionGroupInfo(pi.group, 0);
+                            if (pgi.icon != 0) {
+                                ((ImageView)view.findViewById(R.id.op_icon)).setImageDrawable(
+                                        pgi.loadIcon(mPm));
+                            }
+                        }
+                    } catch (NameNotFoundException e) {
+                    }
+                    ((TextView)view.findViewById(R.id.op_name)).setText(mState.getLabelText(op));
+                    ((TextView)view.findViewById(R.id.op_time)).setText(mState.getTimeText(op));
+                    Switch sw = (Switch)view.findViewById(R.id.switchWidget);
+                    sw.setChecked(op.getMode() == AppOpsManager.MODE_ALLOWED);
+                    sw.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
+                        @Override
+                        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
+                            mAppOps.setMode(op.getOp(), entry.getPackageOps().getUid(),
+                                    entry.getPackageOps().getPackageName(), isChecked
+                                    ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
+                        }
+                    });
+                }
+            }
+        }
+
+        return true;
+    }
+
+    private void setIntentAndFinish(boolean finish, boolean appChanged) {
+        Intent intent = new Intent();
+        intent.putExtra(ManageApplications.APP_CHG, appChanged);
+        PreferenceActivity pa = (PreferenceActivity)getActivity();
+        pa.finishPreferencePanel(this, Activity.RESULT_OK, intent);
+    }
+
+    /** Called when the activity is first created. */
+    @Override
+    public void onCreate(Bundle icicle) {
+        super.onCreate(icicle);
+
+        mState = new AppOpsState(getActivity());
+        mPm = getActivity().getPackageManager();
+        mInflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+        mAppOps = (AppOpsManager)getActivity().getSystemService(Context.APP_OPS_SERVICE);
+
+        retrieveAppEntry();
+
+        setHasOptionsMenu(true);
+    }
+
+    @Override
+    public View onCreateView(
+            LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+        final View view = inflater.inflate(R.layout.app_ops_details, container, false);
+        Utils.prepareCustomPreferencesList(container, view, view, false);
+
+        mRootView = view;
+        mOperationsSection = (LinearLayout)view.findViewById(R.id.operations_section);
+        return view;
+    }
+
+    @Override
+    public void onResume() {
+        super.onResume();
+        if (!refreshUi()) {
+            setIntentAndFinish(true, true);
+        }
+    }
 }
diff --git a/src/com/android/settings/applications/AppOpsState.java b/src/com/android/settings/applications/AppOpsState.java
index 2bd724b..808afa8 100644
--- a/src/com/android/settings/applications/AppOpsState.java
+++ b/src/com/android/settings/applications/AppOpsState.java
@@ -28,6 +28,8 @@
 import android.os.Parcelable;
 import android.text.format.DateUtils;
 
+import android.util.Log;
+import android.util.SparseArray;
 import com.android.settings.R;
 
 import java.io.File;
@@ -39,9 +41,13 @@
 import java.util.List;
 
 public class AppOpsState {
+    static final String TAG = "AppOpsState";
+    static final boolean DEBUG = false;
+
     final Context mContext;
     final AppOpsManager mAppOps;
     final PackageManager mPm;
+    final CharSequence[] mOpNames;
 
     List<AppOpEntry> mApps;
 
@@ -49,23 +55,18 @@
         mContext = context;
         mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
         mPm = context.getPackageManager();
+        mOpNames = context.getResources().getTextArray(R.array.app_ops_names);
     }
 
     public static class OpsTemplate implements Parcelable {
         public final int[] ops;
-        public final String[] perms;
-        public final int[] permOps;
 
-        public OpsTemplate(int[] _ops, String[] _perms, int[] _permOps) {
+        public OpsTemplate(int[] _ops) {
             ops = _ops;
-            perms = _perms;
-            permOps = _permOps;
         }
 
         OpsTemplate(Parcel src) {
             ops = src.createIntArray();
-            perms = src.createStringArray();
-            permOps = src.createIntArray();
         }
 
         @Override
@@ -76,8 +77,6 @@
         @Override
         public void writeToParcel(Parcel dest, int flags) {
             dest.writeIntArray(ops);
-            dest.writeStringArray(perms);
-            dest.writeIntArray(permOps);
         }
 
         public static final Creator<OpsTemplate> CREATOR = new Creator<OpsTemplate>() {
@@ -94,34 +93,27 @@
     public static final OpsTemplate LOCATION_TEMPLATE = new OpsTemplate(
             new int[] { AppOpsManager.OP_COARSE_LOCATION,
                     AppOpsManager.OP_FINE_LOCATION,
-                    AppOpsManager.OP_GPS },
-            new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION,
-                    android.Manifest.permission.ACCESS_FINE_LOCATION },
-            new int[] { AppOpsManager.OP_COARSE_LOCATION,
-                    AppOpsManager.OP_FINE_LOCATION }
+                    AppOpsManager.OP_GPS,
+                    AppOpsManager.OP_WIFI_SCAN }
             );
 
     public static final OpsTemplate PERSONAL_TEMPLATE = new OpsTemplate(
             new int[] { AppOpsManager.OP_READ_CONTACTS,
                     AppOpsManager.OP_WRITE_CONTACTS,
                     AppOpsManager.OP_READ_CALL_LOG,
-                    AppOpsManager.OP_WRITE_CALL_LOG },
-            new String[] { android.Manifest.permission.READ_CONTACTS,
-                            android.Manifest.permission.WRITE_CONTACTS,
-                            android.Manifest.permission.READ_CALL_LOG,
-                            android.Manifest.permission.WRITE_CALL_LOG },
-            new int[] { AppOpsManager.OP_READ_CONTACTS,
-                    AppOpsManager.OP_WRITE_CONTACTS,
-                    AppOpsManager.OP_READ_CALL_LOG,
-                    AppOpsManager.OP_WRITE_CALL_LOG }
+                    AppOpsManager.OP_WRITE_CALL_LOG,
+                    AppOpsManager.OP_READ_CALENDAR,
+                    AppOpsManager.OP_WRITE_CALENDAR }
             );
 
     public static final OpsTemplate DEVICE_TEMPLATE = new OpsTemplate(
-            new int[] { AppOpsManager.OP_VIBRATE },
-            new String[] { android.Manifest.permission.VIBRATE },
             new int[] { AppOpsManager.OP_VIBRATE }
             );
 
+    public static final OpsTemplate[] ALL_TEMPLATES = new OpsTemplate[] {
+            LOCATION_TEMPLATE, PERSONAL_TEMPLATE, DEVICE_TEMPLATE
+    };
+
     /**
      * This class holds the per-item data in our Loader.
      */
@@ -129,6 +121,8 @@
         private final AppOpsState mState;
         private final ApplicationInfo mInfo;
         private final File mApkFile;
+        private final SparseArray<AppOpsManager.OpEntry> mOps
+                = new SparseArray<AppOpsManager.OpEntry>();
         private String mLabel;
         private Drawable mIcon;
         private boolean mMounted;
@@ -139,6 +133,14 @@
             mApkFile = new File(info.sourceDir);
         }
 
+        public void addOp(AppOpsManager.OpEntry op) {
+            mOps.put(op.getOp(), op);
+        }
+
+        public boolean hasOp(int op) {
+            return mOps.indexOfKey(op) >= 0;
+        }
+
         public ApplicationInfo getApplicationInfo() {
             return mInfo;
         }
@@ -200,11 +202,13 @@
 
         public AppOpEntry(AppOpsManager.PackageOps pkg, AppOpsManager.OpEntry op, AppEntry app) {
             mPkgOps = pkg;
-            mOps.add(op);
             mApp = app;
+            mApp.addOp(op);
+            mOps.add(op);
         }
 
         public void addOp(AppOpsManager.OpEntry op) {
+            mApp.addOp(op);
             for (int i=0; i<mOps.size(); i++) {
                 AppOpsManager.OpEntry pos = mOps.get(i);
                 if (pos.isRunning() != op.isRunning()) {
@@ -212,8 +216,9 @@
                         mOps.add(i, op);
                         return;
                     }
+                    continue;
                 }
-                if (pos.getTime() > op.getTime()) {
+                if (pos.getTime() < op.getTime()) {
                     mOps.add(i, op);
                     return;
                 }
@@ -237,16 +242,16 @@
             return mOps.get(pos);
         }
 
-        public CharSequence getLabelText(CharSequence opNames[]) {
+        public CharSequence getLabelText(AppOpsState state) {
             if (getNumOpEntry() == 1) {
-                return opNames[getOpEntry(0).getOp()];
+                return state.mOpNames[getOpEntry(0).getOp()];
             } else {
                 StringBuilder builder = new StringBuilder();
                 for (int i=0; i<getNumOpEntry(); i++) {
                     if (i > 0) {
                         builder.append(", ");
                     }
-                    builder.append(opNames[getOpEntry(i).getOp()]);
+                    builder.append(state.mOpNames[getOpEntry(i).getOp()]);
                 }
                 return builder.toString();
             }
@@ -306,12 +311,16 @@
                 boolean lastExe = last.getTime() != 0;
                 boolean entryExe = opEntry.getTime() != 0;
                 if (lastExe == entryExe) {
+                    if (DEBUG) Log.d(TAG, "Add op " + opEntry.getOp() + " to package "
+                            + pkgOps.getPackageName() + ": append to " + last);
                     last.addOp(opEntry);
                     return;
                 }
             }
         }
         AppOpEntry entry = new AppOpEntry(pkgOps, opEntry, appEntry);
+        if (DEBUG) Log.d(TAG, "Add op " + opEntry.getOp() + " to package "
+                + pkgOps.getPackageName() + ": making new " + entry);
         entries.add(entry);
     }
 
@@ -319,10 +328,42 @@
         return buildState(tpl, 0, null);
     }
 
+    private AppEntry getAppEntry(final Context context, final HashMap<String, AppEntry> appEntries,
+            final String packageName, ApplicationInfo appInfo) {
+        AppEntry appEntry = appEntries.get(packageName);
+        if (appEntry == null) {
+            if (appInfo == null) {
+                try {
+                    appInfo = mPm.getApplicationInfo(packageName,
+                            PackageManager.GET_DISABLED_COMPONENTS
+                            | PackageManager.GET_UNINSTALLED_PACKAGES);
+                } catch (PackageManager.NameNotFoundException e) {
+                    Log.w(TAG, "Unable to find info for package " + packageName);
+                    return null;
+                }
+            }
+            appEntry = new AppEntry(this, appInfo);
+            appEntry.loadLabel(context);
+            appEntries.put(packageName, appEntry);
+        }
+        return appEntry;
+    }
+
     public List<AppOpEntry> buildState(OpsTemplate tpl, int uid, String packageName) {
         final Context context = mContext;
 
         final HashMap<String, AppEntry> appEntries = new HashMap<String, AppEntry>();
+        List<AppOpEntry> entries = new ArrayList<AppOpEntry>();
+
+        ArrayList<String> perms = new ArrayList<String>();
+        ArrayList<Integer> permOps = new ArrayList<Integer>();
+        for (int i=0; i<tpl.ops.length; i++) {
+            String perm = AppOpsManager.opToPermission(tpl.ops[i]);
+            if (!perms.contains(perm)) {
+                perms.add(perm);
+                permOps.add(tpl.ops[i]);
+            }
+        }
 
         List<AppOpsManager.PackageOps> pkgs;
         if (packageName != null) {
@@ -330,68 +371,74 @@
         } else {
             pkgs = mAppOps.getPackagesForOps(tpl.ops);
         }
-        List<AppOpEntry> entries = new ArrayList<AppOpEntry>(pkgs.size());
-        for (int i=0; i<pkgs.size(); i++) {
-            AppOpsManager.PackageOps pkgOps = pkgs.get(i);
-            AppEntry appEntry = appEntries.get(pkgOps.getPackageName());
-            if (appEntry == null) {
-                ApplicationInfo appInfo = null;
-                try {
-                    appInfo = mPm.getApplicationInfo(pkgOps.getPackageName(),
-                            PackageManager.GET_DISABLED_COMPONENTS
-                            | PackageManager.GET_UNINSTALLED_PACKAGES);
-                } catch (PackageManager.NameNotFoundException e) {
+
+        if (pkgs != null) {
+            for (int i=0; i<pkgs.size(); i++) {
+                AppOpsManager.PackageOps pkgOps = pkgs.get(i);
+                AppEntry appEntry = getAppEntry(context, appEntries, pkgOps.getPackageName(), null);
+                if (appEntry == null) {
+                    continue;
                 }
-                appEntry = new AppEntry(this, appInfo);
-                appEntry.loadLabel(context);
-                appEntries.put(pkgOps.getPackageName(), appEntry);
-            }
-            for (int j=0; j<pkgOps.getOps().size(); j++) {
-                AppOpsManager.OpEntry opEntry = pkgOps.getOps().get(j);
-                addOp(entries, pkgOps, appEntry, opEntry);
+                for (int j=0; j<pkgOps.getOps().size(); j++) {
+                    AppOpsManager.OpEntry opEntry = pkgOps.getOps().get(j);
+                    addOp(entries, pkgOps, appEntry, opEntry);
+                }
             }
         }
 
-        if (tpl.perms != null) {
-            List<PackageInfo> apps;
-            if (packageName != null) {
-                apps = new ArrayList<PackageInfo>();
-                try {
-                    PackageInfo pi = mPm.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
-                    apps.add(pi);
-                } catch (NameNotFoundException e) {
-                }
-            } else {
-                apps = mPm.getPackagesHoldingPermissions(tpl.perms, 0);
+        List<PackageInfo> apps;
+        if (packageName != null) {
+            apps = new ArrayList<PackageInfo>();
+            try {
+                PackageInfo pi = mPm.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
+                apps.add(pi);
+            } catch (NameNotFoundException e) {
             }
-            for (int i=0; i<apps.size(); i++) {
-                PackageInfo appInfo = apps.get(i);
-                AppEntry appEntry = appEntries.get(appInfo.packageName);
-                if (appEntry == null) {
-                    appEntry = new AppEntry(this, appInfo.applicationInfo);
-                    appEntry.loadLabel(context);
-                    appEntries.put(appInfo.packageName, appEntry);
-                    List<AppOpsManager.OpEntry> dummyOps
-                            = new ArrayList<AppOpsManager.OpEntry>();
-                    AppOpsManager.PackageOps pkgOps = new AppOpsManager.PackageOps(
-                            appInfo.packageName, appInfo.applicationInfo.uid, dummyOps);
-                    for (int j=0; j<appInfo.requestedPermissions.length; j++) {
-                        if (appInfo.requestedPermissionsFlags != null) {
-                            if ((appInfo.requestedPermissionsFlags[j]
-                                    & PackageInfo.REQUESTED_PERMISSION_GRANTED) == 0) {
-                                break;
-                            }
-                        }
-                        for (int k=0; k<tpl.perms.length; k++) {
-                            if (tpl.perms[k].equals(appInfo.requestedPermissions[j])) {
-                                AppOpsManager.OpEntry opEntry = new AppOpsManager.OpEntry(
-                                        tpl.permOps[k], 0, 0);
-                                dummyOps.add(opEntry);
-                                addOp(entries, pkgOps, appEntry, opEntry);
-                            }
-                        }
+        } else {
+            String[] permsArray = new String[perms.size()];
+            perms.toArray(permsArray);
+            apps = mPm.getPackagesHoldingPermissions(permsArray, 0);
+        }
+        for (int i=0; i<apps.size(); i++) {
+            PackageInfo appInfo = apps.get(i);
+            AppEntry appEntry = getAppEntry(context, appEntries, appInfo.packageName,
+                    appInfo.applicationInfo);
+            if (appEntry == null) {
+                continue;
+            }
+            List<AppOpsManager.OpEntry> dummyOps = null;
+            AppOpsManager.PackageOps pkgOps = null;
+            for (int j=0; j<appInfo.requestedPermissions.length; j++) {
+                if (appInfo.requestedPermissionsFlags != null) {
+                    if ((appInfo.requestedPermissionsFlags[j]
+                            & PackageInfo.REQUESTED_PERMISSION_GRANTED) == 0) {
+                        if (DEBUG) Log.d(TAG, "Pkg " + appInfo.packageName + " perm "
+                                + appInfo.requestedPermissions[j] + " not granted; skipping");
+                        break;
                     }
                 }
+                if (DEBUG) Log.d(TAG, "Pkg " + appInfo.packageName + ": requested perm "
+                        + appInfo.requestedPermissions[j]);
+                for (int k=0; k<perms.size(); k++) {
+                    if (!perms.get(k).equals(appInfo.requestedPermissions[j])) {
+                        continue;
+                    }
+                    if (DEBUG) Log.d(TAG, "Pkg " + appInfo.packageName + " perm " + perms.get(k)
+                            + " has op " + permOps.get(k) + ": " + appEntry.hasOp(permOps.get(k)));
+                    if (appEntry.hasOp(permOps.get(k))) {
+                        continue;
+                    }
+                    if (dummyOps == null) {
+                        dummyOps = new ArrayList<AppOpsManager.OpEntry>();
+                        pkgOps = new AppOpsManager.PackageOps(
+                                appInfo.packageName, appInfo.applicationInfo.uid, dummyOps);
+
+                    }
+                    AppOpsManager.OpEntry opEntry = new AppOpsManager.OpEntry(
+                            permOps.get(k), AppOpsManager.MODE_ALLOWED, 0, 0, 0);
+                    dummyOps.add(opEntry);
+                    addOp(entries, pkgOps, appEntry, opEntry);
+                }
             }
         }
 
@@ -401,4 +448,22 @@
         // Done!
         return entries;
     }
+
+    public CharSequence getLabelText(AppOpsManager.OpEntry op) {
+        return mOpNames[op.getOp()];
+    }
+
+    public CharSequence getTimeText(AppOpsManager.OpEntry op) {
+        if (op.isRunning()) {
+            return mContext.getResources().getText(R.string.app_ops_running);
+        }
+        if (op.getTime() > 0) {
+            return DateUtils.getRelativeTimeSpanString(op.getTime(),
+                    System.currentTimeMillis(),
+                    DateUtils.MINUTE_IN_MILLIS,
+                    DateUtils.FORMAT_ABBREV_RELATIVE);
+        }
+        return mContext.getResources().getText(R.string.app_ops_never_used);
+    }
+
 }
diff --git a/src/com/android/settings/applications/InstalledAppDetails.java b/src/com/android/settings/applications/InstalledAppDetails.java
index 565c585..f3723f8 100644
--- a/src/com/android/settings/applications/InstalledAppDetails.java
+++ b/src/com/android/settings/applications/InstalledAppDetails.java
@@ -537,7 +537,7 @@
         }
     }
 
-    // Utility method to set applicaiton label and icon.
+    // Utility method to set application label and icon.
     private void setAppLabelAndIcon(PackageInfo pkgInfo) {
         final View appSnippet = mRootView.findViewById(R.id.app_snippet);
         appSnippet.setPaddingRelative(0, appSnippet.getPaddingTop(), 0, appSnippet.getPaddingBottom());