summaryrefslogtreecommitdiff
path: root/quickstep/src/com/android/launcher3/model/WellbeingModel.java
blob: e489cb3a71094904c205d16e0a34c3dbf852d89b (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
/*
 * Copyright (C) 2018 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.launcher3.model;

import static android.content.ContentResolver.SCHEME_CONTENT;

import static com.android.launcher3.Utilities.newContentObserver;

import android.annotation.TargetApi;
import android.app.RemoteAction;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.LauncherApps;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.DeadObjectException;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.os.UserHandle;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Log;

import androidx.annotation.MainThread;
import androidx.annotation.Nullable;
import androidx.annotation.WorkerThread;

import com.android.launcher3.BaseDraggingActivity;
import com.android.launcher3.InvariantDeviceProfile;
import com.android.launcher3.LauncherProvider;
import com.android.launcher3.LauncherSettings;
import com.android.launcher3.R;
import com.android.launcher3.config.FeatureFlags;
import com.android.launcher3.model.data.ItemInfo;
import com.android.launcher3.popup.RemoteActionShortcut;
import com.android.launcher3.popup.SystemShortcut;
import com.android.launcher3.util.BgObjectWithLooper;
import com.android.launcher3.util.MainThreadInitializedObject;
import com.android.launcher3.util.PackageManagerHelper;
import com.android.launcher3.util.Preconditions;
import com.android.launcher3.util.SimpleBroadcastReceiver;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Data model for digital wellbeing status of apps.
 */
@TargetApi(Build.VERSION_CODES.Q)
public final class WellbeingModel extends BgObjectWithLooper {
    private static final String TAG = "WellbeingModel";
    private static final int[] RETRY_TIMES_MS = {5000, 15000, 30000};
    private static final boolean DEBUG = false;

    private static final int UNKNOWN_MINIMAL_DEVICE_STATE = 0;
    private static final int IN_MINIMAL_DEVICE = 2;

    // Welbeing contract
    private static final String PATH_ACTIONS = "actions";
    private static final String PATH_MINIMAL_DEVICE = "minimal_device";
    private static final String METHOD_GET_MINIMAL_DEVICE_CONFIG = "get_minimal_device_config";
    private static final String METHOD_GET_ACTIONS = "get_actions";
    private static final String EXTRA_ACTIONS = "actions";
    private static final String EXTRA_ACTION = "action";
    private static final String EXTRA_MAX_NUM_ACTIONS_SHOWN = "max_num_actions_shown";
    private static final String EXTRA_PACKAGES = "packages";
    private static final String EXTRA_SUCCESS = "success";
    private static final String EXTRA_MINIMAL_DEVICE_STATE = "minimal_device_state";
    private static final String DB_NAME_MINIMAL_DEVICE = "minimal.db";

    public static final MainThreadInitializedObject<WellbeingModel> INSTANCE =
            new MainThreadInitializedObject<>(WellbeingModel::new);

    private final Context mContext;
    private final String mWellbeingProviderPkg;

    private Handler mWorkerHandler;
    private ContentObserver mContentObserver;

    private final Object mModelLock = new Object();
    // Maps the action Id to the corresponding RemoteAction
    private final Map<String, RemoteAction> mActionIdMap = new ArrayMap<>();
    private final Map<String, String> mPackageToActionId = new HashMap<>();

    private boolean mIsInTest;

    private WellbeingModel(final Context context) {
        mContext = context;
        mWellbeingProviderPkg = mContext.getString(R.string.wellbeing_provider_pkg);
        initializeInBackground("WellbeingHandler");
    }

    @Override
    protected void onInitialized(Looper looper) {
        mWorkerHandler = new Handler(looper);
        mContentObserver = newContentObserver(mWorkerHandler, this::onWellbeingUriChanged);
        if (!TextUtils.isEmpty(mWellbeingProviderPkg)) {
            mContext.registerReceiver(
                    new SimpleBroadcastReceiver(t -> restartObserver()),
                    PackageManagerHelper.getPackageFilter(mWellbeingProviderPkg,
                            Intent.ACTION_PACKAGE_ADDED, Intent.ACTION_PACKAGE_CHANGED,
                            Intent.ACTION_PACKAGE_REMOVED, Intent.ACTION_PACKAGE_DATA_CLEARED,
                            Intent.ACTION_PACKAGE_RESTARTED),
                    null, mWorkerHandler);

            IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
            filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
            filter.addDataScheme("package");
            mContext.registerReceiver(new SimpleBroadcastReceiver(this::onAppPackageChanged),
                    filter, null, mWorkerHandler);

            restartObserver();
        }
    }

    @WorkerThread
    private void onWellbeingUriChanged(Uri uri) {
        Preconditions.assertNonUiThread();
        if (DEBUG || mIsInTest) {
            Log.d(TAG, "ContentObserver.onChange() called with: uri = [" + uri + "]");
        }
        if (uri.getPath().contains(PATH_ACTIONS)) {
            // Wellbeing reports that app actions have changed.
            updateAllPackages();
        } else if (uri.getPath().contains(PATH_MINIMAL_DEVICE)) {
            // Wellbeing reports that minimal device state or config is changed.
            if (!FeatureFlags.ENABLE_MINIMAL_DEVICE.get()) {
                return;
            }

            // Temporary bug fix for b/169771796. Wellbeing provides the layout configuration when
            // minimal device is enabled. We always want to reload the configuration from Wellbeing
            // since the layout configuration might have changed.
            mContext.deleteDatabase(DB_NAME_MINIMAL_DEVICE);

            final Bundle extras = new Bundle();
            String dbFile;
            if (isInMinimalDeviceMode()) {
                dbFile = DB_NAME_MINIMAL_DEVICE;
                extras.putString(LauncherProvider.KEY_LAYOUT_PROVIDER_AUTHORITY,
                        mWellbeingProviderPkg + ".api");
            } else {
                dbFile = InvariantDeviceProfile.INSTANCE.get(mContext).dbFile;
            }
            LauncherSettings.Settings.call(mContext.getContentResolver(),
                    LauncherSettings.Settings.METHOD_SWITCH_DATABASE,
                    dbFile, extras);
        }
    }

    public void setInTest(boolean inTest) {
        mIsInTest = inTest;
    }

    @WorkerThread
    private void restartObserver() {
        final ContentResolver resolver = mContext.getContentResolver();
        resolver.unregisterContentObserver(mContentObserver);
        Uri actionsUri = apiBuilder().path(PATH_ACTIONS).build();
        Uri minimalDeviceUri = apiBuilder().path(PATH_MINIMAL_DEVICE).build();
        try {
            resolver.registerContentObserver(
                    actionsUri, true /* notifyForDescendants */, mContentObserver);
            resolver.registerContentObserver(
                    minimalDeviceUri, true /* notifyForDescendants */, mContentObserver);
        } catch (Exception e) {
            Log.e(TAG, "Failed to register content observer for " + actionsUri + ": " + e);
            if (mIsInTest) throw new RuntimeException(e);
        }
        updateAllPackages();
    }

    @MainThread
    private SystemShortcut getShortcutForApp(String packageName, int userId,
            BaseDraggingActivity activity, ItemInfo info) {
        Preconditions.assertUIThread();
        // Work profile apps are not recognized by digital wellbeing.
        if (userId != UserHandle.myUserId()) {
            if (DEBUG || mIsInTest) {
                Log.d(TAG, "getShortcutForApp [" + packageName + "]: not current user");
            }
            return null;
        }

        synchronized (mModelLock) {
            String actionId = mPackageToActionId.get(packageName);
            final RemoteAction action = actionId != null ? mActionIdMap.get(actionId) : null;
            if (action == null) {
                if (DEBUG || mIsInTest) {
                    Log.d(TAG, "getShortcutForApp [" + packageName + "]: no action");
                }
                return null;
            }
            if (DEBUG || mIsInTest) {
                Log.d(TAG,
                        "getShortcutForApp [" + packageName + "]: action: '" + action.getTitle()
                                + "'");
            }
            return new RemoteActionShortcut(action, activity, info);
        }
    }

    private Uri.Builder apiBuilder() {
        return new Uri.Builder()
                .scheme(SCHEME_CONTENT)
                .authority(mWellbeingProviderPkg + ".api");
    }

    @WorkerThread
    private boolean isInMinimalDeviceMode() {
        if (!FeatureFlags.ENABLE_MINIMAL_DEVICE.get()) {
            return false;
        }
        if (DEBUG || mIsInTest) {
            Log.d(TAG, "isInMinimalDeviceMode() called");
        }
        Preconditions.assertNonUiThread();

        final Uri contentUri = apiBuilder().build();
        try (ContentProviderClient client = mContext.getContentResolver()
                .acquireUnstableContentProviderClient(contentUri)) {
            final Bundle remoteBundle = client == null ? null : client.call(
                    METHOD_GET_MINIMAL_DEVICE_CONFIG, null /* args */, null /* extras */);
            return remoteBundle != null
                    && remoteBundle.getInt(EXTRA_MINIMAL_DEVICE_STATE,
                    UNKNOWN_MINIMAL_DEVICE_STATE) == IN_MINIMAL_DEVICE;
        } catch (Exception e) {
            Log.e(TAG, "Failed to retrieve data from " + contentUri + ": " + e);
            if (mIsInTest) throw new RuntimeException(e);
        }
        if (DEBUG || mIsInTest) Log.i(TAG, "isInMinimalDeviceMode(): finished");
        return false;
    }

    @WorkerThread
    private boolean updateActions(String[] packageNames) {
        if (packageNames.length == 0) {
            return true;
        }
        if (DEBUG || mIsInTest) {
            Log.d(TAG, "retrieveActions() called with: packageNames = [" + String.join(", ",
                    packageNames) + "]");
        }
        Preconditions.assertNonUiThread();

        Uri contentUri = apiBuilder().build();
        final Bundle remoteActionBundle;
        try (ContentProviderClient client = mContext.getContentResolver()
                .acquireUnstableContentProviderClient(contentUri)) {
            if (client == null) {
                if (DEBUG || mIsInTest) Log.i(TAG, "retrieveActions(): null provider");
                return false;
            }

            // Prepare wellbeing call parameters.
            final Bundle params = new Bundle();
            params.putStringArray(EXTRA_PACKAGES, packageNames);
            params.putInt(EXTRA_MAX_NUM_ACTIONS_SHOWN, 1);
            // Perform wellbeing call .
            remoteActionBundle = client.call(METHOD_GET_ACTIONS, null, params);
            if (!remoteActionBundle.getBoolean(EXTRA_SUCCESS, true)) return false;

            synchronized (mModelLock) {
                // Remove the entries for requested packages, and then update the fist with what we
                // got from service
                Arrays.stream(packageNames).forEach(mPackageToActionId::remove);

                // The result consists of sub-bundles, each one is per a remote action. Each
                // sub-bundle has a RemoteAction and a list of packages to which the action applies.
                for (String actionId :
                        remoteActionBundle.getStringArray(EXTRA_ACTIONS)) {
                    final Bundle actionBundle = remoteActionBundle.getBundle(actionId);
                    mActionIdMap.put(actionId,
                            actionBundle.getParcelable(EXTRA_ACTION));

                    final String[] packagesForAction =
                            actionBundle.getStringArray(EXTRA_PACKAGES);
                    if (DEBUG || mIsInTest) {
                        Log.d(TAG, "....actionId: " + actionId + ", packages: " + String.join(", ",
                                packagesForAction));
                    }
                    for (String packageName : packagesForAction) {
                        mPackageToActionId.put(packageName, actionId);
                    }
                }
            }
        } catch (DeadObjectException e) {
            Log.i(TAG, "retrieveActions(): DeadObjectException");
            return false;
        } catch (Exception e) {
            Log.e(TAG, "Failed to retrieve data from " + contentUri + ": " + e);
            if (mIsInTest) throw new RuntimeException(e);
            return true;
        }
        if (DEBUG || mIsInTest) Log.i(TAG, "retrieveActions(): finished");
        return true;
    }

    @WorkerThread
    private void updateActionsWithRetry(int retryCount, @Nullable String packageName) {
        if (DEBUG || mIsInTest) {
            Log.i(TAG,
                    "updateActionsWithRetry(); retryCount: " + retryCount + ", package: "
                            + packageName);
        }
        String[] packageNames = TextUtils.isEmpty(packageName)
                ? mContext.getSystemService(LauncherApps.class)
                .getActivityList(null, Process.myUserHandle()).stream()
                .map(li -> li.getApplicationInfo().packageName).distinct()
                .toArray(String[]::new)
                : new String[]{packageName};

        mWorkerHandler.removeCallbacksAndMessages(packageName);
        if (updateActions(packageNames)) {
            return;
        }
        if (retryCount >= RETRY_TIMES_MS.length) {
            // To many retries, skip
            return;
        }
        mWorkerHandler.postDelayed(
                () -> {
                    if (DEBUG || mIsInTest) Log.i(TAG, "Retrying; attempt " + (retryCount + 1));
                    updateActionsWithRetry(retryCount + 1, packageName);
                },
                packageName, RETRY_TIMES_MS[retryCount]);
    }

    @WorkerThread
    private void updateAllPackages() {
        if (DEBUG || mIsInTest) Log.i(TAG, "updateAllPackages");
        updateActionsWithRetry(0, null);
    }

    @WorkerThread
    private void onAppPackageChanged(Intent intent) {
        if (DEBUG || mIsInTest) Log.d(TAG, "Changes in apps: intent = [" + intent + "]");
        Preconditions.assertNonUiThread();

        final String packageName = intent.getData().getSchemeSpecificPart();
        if (packageName == null || packageName.length() == 0) {
            // they sent us a bad intent
            return;
        }
        final String action = intent.getAction();
        if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
            mWorkerHandler.removeCallbacksAndMessages(packageName);
            synchronized (mModelLock) {
                mPackageToActionId.remove(packageName);
            }
        } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
            updateActionsWithRetry(0, packageName);
        }
    }

    /**
     * Shortcut factory for generating wellbeing action
     */
    public static final SystemShortcut.Factory<BaseDraggingActivity> SHORTCUT_FACTORY =
            (activity, info) -> (info.getTargetComponent() == null) ? null : INSTANCE.get(activity)
                    .getShortcutForApp(
                            info.getTargetComponent().getPackageName(), info.user.getIdentifier(),
                            activity, info);
}