Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 635ddd7d authored by Fabian Kozynski's avatar Fabian Kozynski
Browse files

resolve merge conflicts of 53eec348 to master

Fixes: 197133293
Change-Id: I5f57a0fb7cbdaa96ac7151fca17a616a735d7b88
parents 952613b3 53eec348
Loading
Loading
Loading
Loading
+1 −1
Original line number Diff line number Diff line
@@ -101,6 +101,7 @@ public class SecureSettings {
        Settings.Secure.CAMERA_DOUBLE_TAP_POWER_GESTURE_DISABLED,
        Settings.Secure.SYSTEM_NAVIGATION_KEYS_ENABLED,
        Settings.Secure.QS_TILES,
        Settings.Secure.QS_AUTO_ADDED_TILES,
        Settings.Secure.CONTROLS_ENABLED,
        Settings.Secure.POWER_MENU_LOCKED_SHOW_CONTENT,
        Settings.Secure.DOZE_ENABLED,
@@ -118,7 +119,6 @@ public class SecureSettings {
        Settings.Secure.VR_DISPLAY_MODE,
        Settings.Secure.NOTIFICATION_BADGING,
        Settings.Secure.NOTIFICATION_DISMISS_RTL,
        Settings.Secure.QS_AUTO_ADDED_TILES,
        Settings.Secure.SCREENSAVER_ENABLED,
        Settings.Secure.SCREENSAVER_COMPONENTS,
        Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
+23 −6
Original line number Diff line number Diff line
@@ -72,8 +72,9 @@ public class SettingsHelper {
     * {@hide}
     */
    private static final ArraySet<String> sBroadcastOnRestore;
    private static final ArraySet<String> sBroadcastOnRestoreSystemUI;
    static {
        sBroadcastOnRestore = new ArraySet<String>(4);
        sBroadcastOnRestore = new ArraySet<String>(9);
        sBroadcastOnRestore.add(Settings.Secure.ENABLED_NOTIFICATION_LISTENERS);
        sBroadcastOnRestore.add(Settings.Secure.ENABLED_VR_LISTENERS);
        sBroadcastOnRestore.add(Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
@@ -83,6 +84,9 @@ public class SettingsHelper {
        sBroadcastOnRestore.add(Settings.Secure.DARK_THEME_CUSTOM_END_TIME);
        sBroadcastOnRestore.add(Settings.Secure.ACCESSIBILITY_DISPLAY_MAGNIFICATION_NAVBAR_ENABLED);
        sBroadcastOnRestore.add(Settings.Secure.ACCESSIBILITY_BUTTON_TARGETS);
        sBroadcastOnRestoreSystemUI = new ArraySet<String>(2);
        sBroadcastOnRestoreSystemUI.add(Settings.Secure.QS_TILES);
        sBroadcastOnRestoreSystemUI.add(Settings.Secure.QS_AUTO_ADDED_TILES);
    }

    private interface SettingsLookup {
@@ -133,6 +137,7 @@ public class SettingsHelper {
        // Will we need a post-restore broadcast for this element?
        String oldValue = null;
        boolean sendBroadcast = false;
        boolean sendBroadcastSystemUI = false;
        final SettingsLookup table;

        if (destination.equals(Settings.Secure.CONTENT_URI)) {
@@ -143,10 +148,12 @@ public class SettingsHelper {
            table = sGlobalLookup;
        }

        if (sBroadcastOnRestore.contains(name)) {
        sendBroadcast = sBroadcastOnRestore.contains(name);
        sendBroadcastSystemUI = sBroadcastOnRestoreSystemUI.contains(name);

        if (sendBroadcast || sendBroadcastSystemUI) {
            // TODO: http://b/22388012
            oldValue = table.lookup(cr, name, UserHandle.USER_SYSTEM);
            sendBroadcast = true;
        }

        try {
@@ -193,19 +200,29 @@ public class SettingsHelper {
        } catch (Exception e) {
            // If we fail to apply the setting, by definition nothing happened
            sendBroadcast = false;
            sendBroadcastSystemUI = false;
        } finally {
            // If this was an element of interest, send the "we just restored it"
            // broadcast with the historical value now that the new value has
            // been committed and observers kicked off.
            if (sendBroadcast) {
            if (sendBroadcast || sendBroadcastSystemUI) {
                Intent intent = new Intent(Intent.ACTION_SETTING_RESTORED)
                        .setPackage("android").addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY)
                        .addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY)
                        .putExtra(Intent.EXTRA_SETTING_NAME, name)
                        .putExtra(Intent.EXTRA_SETTING_NEW_VALUE, value)
                        .putExtra(Intent.EXTRA_SETTING_PREVIOUS_VALUE, oldValue)
                        .putExtra(Intent.EXTRA_SETTING_RESTORED_FROM_SDK_INT, restoredFromSdkInt);

                if (sendBroadcast) {
                    intent.setPackage("android");
                    context.sendBroadcastAsUser(intent, UserHandle.SYSTEM, null);
                }
                if (sendBroadcastSystemUI) {
                    intent.setPackage(
                            context.getString(com.android.internal.R.string.config_systemUi));
                    context.sendBroadcastAsUser(intent, UserHandle.SYSTEM, null);
                }
            }
        }
    }

+0 −156
Original line number Diff line number Diff line
/*
 * Copyright (C) 2017 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.systemui.qs;

import static com.android.systemui.statusbar.phone.AutoTileManager.HOTSPOT;
import static com.android.systemui.statusbar.phone.AutoTileManager.INVERSION;
import static com.android.systemui.statusbar.phone.AutoTileManager.NIGHT;
import static com.android.systemui.statusbar.phone.AutoTileManager.SAVER;
import static com.android.systemui.statusbar.phone.AutoTileManager.WORK;

import android.content.Context;
import android.database.ContentObserver;
import android.os.Handler;
import android.os.UserHandle;
import android.provider.Settings.Secure;
import android.text.TextUtils;
import android.util.ArraySet;

import com.android.internal.annotations.VisibleForTesting;
import com.android.systemui.Prefs;
import com.android.systemui.Prefs.Key;
import com.android.systemui.util.UserAwareController;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;

import javax.inject.Inject;

public class AutoAddTracker implements UserAwareController {

    private static final String[][] CONVERT_PREFS = {
            {Key.QS_HOTSPOT_ADDED, HOTSPOT},
            {Key.QS_DATA_SAVER_ADDED, SAVER},
            {Key.QS_INVERT_COLORS_ADDED, INVERSION},
            {Key.QS_WORK_ADDED, WORK},
            {Key.QS_NIGHTDISPLAY_ADDED, NIGHT},
    };

    private final ArraySet<String> mAutoAdded;
    private final Context mContext;
    private int mUserId;

    public AutoAddTracker(Context context, int userId) {
        mContext = context;
        mUserId = userId;
        mAutoAdded = new ArraySet<>(getAdded());
    }

    /**
     * Init method must be called after construction to start listening
     */
    public void initialize() {
        // TODO: remove migration code and shared preferences keys after P release
        if (mUserId == UserHandle.USER_SYSTEM) {
            for (String[] convertPref : CONVERT_PREFS) {
                if (Prefs.getBoolean(mContext, convertPref[0], false)) {
                    setTileAdded(convertPref[1]);
                    Prefs.remove(mContext, convertPref[0]);
                }
            }
        }
        mContext.getContentResolver().registerContentObserver(
                Secure.getUriFor(Secure.QS_AUTO_ADDED_TILES), false, mObserver,
                UserHandle.USER_ALL);
    }

    @Override
    public void changeUser(UserHandle newUser) {
        if (newUser.getIdentifier() == mUserId) {
            return;
        }
        mUserId = newUser.getIdentifier();
        mAutoAdded.clear();
        mAutoAdded.addAll(getAdded());
    }

    @Override
    public int getCurrentUserId() {
        return mUserId;
    }

    public boolean isAdded(String tile) {
        return mAutoAdded.contains(tile);
    }

    public void setTileAdded(String tile) {
        if (mAutoAdded.add(tile)) {
            saveTiles();
        }
    }

    public void setTileRemoved(String tile) {
        if (mAutoAdded.remove(tile)) {
            saveTiles();
        }
    }

    public void destroy() {
        mContext.getContentResolver().unregisterContentObserver(mObserver);
    }

    private void saveTiles() {
        Secure.putStringForUser(mContext.getContentResolver(), Secure.QS_AUTO_ADDED_TILES,
                TextUtils.join(",", mAutoAdded), mUserId);
    }

    private Collection<String> getAdded() {
        String current = Secure.getStringForUser(mContext.getContentResolver(),
                Secure.QS_AUTO_ADDED_TILES, mUserId);
        if (current == null) {
            return Collections.emptyList();
        }
        return Arrays.asList(current.split(","));
    }

    @VisibleForTesting
    protected final ContentObserver mObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange) {
            mAutoAdded.clear();
            mAutoAdded.addAll(getAdded());
        }
    };

    public static class Builder {
        private final Context mContext;
        private int mUserId;

        @Inject
        public Builder(Context context) {
            mContext = context;
        }

        public Builder setUserId(int userId) {
            mUserId = userId;
            return this;
        }

        public AutoAddTracker build() {
            return new AutoAddTracker(mContext, mUserId);
        }
    }
}
+285 −0
Original line number Diff line number Diff line
/*
 * Copyright (C) 2021 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.systemui.qs

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.database.ContentObserver
import android.net.Uri
import android.os.Handler
import android.os.UserHandle
import android.provider.Settings
import android.text.TextUtils
import android.util.ArraySet
import android.util.Log
import androidx.annotation.GuardedBy
import androidx.annotation.VisibleForTesting
import com.android.systemui.Dumpable
import com.android.systemui.broadcast.BroadcastDispatcher
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.dagger.qualifiers.Background
import com.android.systemui.dagger.qualifiers.Main
import com.android.systemui.dump.DumpManager
import com.android.systemui.util.UserAwareController
import com.android.systemui.util.settings.SecureSettings
import java.io.FileDescriptor
import java.io.PrintWriter
import java.util.concurrent.Executor
import javax.inject.Inject

private const val TAG = "AutoAddTracker"

/**
 * Class to track tiles that have been auto-added
 *
 * The list is backed by [Settings.Secure.QS_AUTO_ADDED_TILES].
 *
 * It also handles restore gracefully.
 */
class AutoAddTracker @VisibleForTesting constructor(
    private val secureSettings: SecureSettings,
    private val broadcastDispatcher: BroadcastDispatcher,
    private val qsHost: QSHost,
    private val dumpManager: DumpManager,
    private val mainHandler: Handler?,
    private val backgroundExecutor: Executor,
    private var userId: Int
) : UserAwareController, Dumpable {

    companion object {
        private val FILTER = IntentFilter(Intent.ACTION_SETTING_RESTORED)
    }

    @GuardedBy("autoAdded")
    private val autoAdded = ArraySet<String>()
    private var restoredTiles: Set<String>? = null

    override val currentUserId: Int
        get() = userId

    private val contentObserver = object : ContentObserver(mainHandler) {
        override fun onChange(
            selfChange: Boolean,
            uris: Collection<Uri>,
            flags: Int,
            _userId: Int
        ) {
            if (_userId != userId) {
                // Ignore changes outside of our user. We'll load the correct value on user change
                return
            }
            loadTiles()
        }
    }

    private val restoreReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action != Intent.ACTION_SETTING_RESTORED) return
            processRestoreIntent(intent)
        }
    }

    private fun processRestoreIntent(intent: Intent) {
        when (intent.getStringExtra(Intent.EXTRA_SETTING_NAME)) {
            Settings.Secure.QS_TILES -> {
                restoredTiles = intent.getStringExtra(Intent.EXTRA_SETTING_NEW_VALUE)
                        ?.split(",")
                        ?.toSet()
                        ?: run {
                            Log.w(TAG, "Null restored tiles for user $userId")
                            emptySet()
                        }
            }
            Settings.Secure.QS_AUTO_ADDED_TILES -> {
                restoredTiles?.let { tiles ->
                    val restoredAutoAdded = intent
                            .getStringExtra(Intent.EXTRA_SETTING_NEW_VALUE)
                            ?.split(",")
                            ?: emptyList()
                    val autoAddedBeforeRestore = intent
                            .getStringExtra(Intent.EXTRA_SETTING_PREVIOUS_VALUE)
                            ?.split(",")
                            ?: emptyList()

                    val tilesToRemove = restoredAutoAdded.filter { it !in tiles }
                    if (tilesToRemove.isNotEmpty()) {
                        qsHost.removeTiles(tilesToRemove)
                    }
                    val tiles = synchronized(autoAdded) {
                        autoAdded.clear()
                        autoAdded.addAll(restoredAutoAdded + autoAddedBeforeRestore)
                        getTilesFromListLocked()
                    }
                    saveTiles(tiles)
                } ?: run {
                    Log.w(TAG, "${Settings.Secure.QS_AUTO_ADDED_TILES} restored before " +
                            "${Settings.Secure.QS_TILES} for user $userId")
                }
            }
            else -> {} // Do nothing for other Settings
        }
    }

    /**
     * Init method must be called after construction to start listening
     */
    fun initialize() {
        dumpManager.registerDumpable(TAG, this)
        loadTiles()
        secureSettings.registerContentObserverForUser(
                secureSettings.getUriFor(Settings.Secure.QS_AUTO_ADDED_TILES),
                contentObserver,
                UserHandle.USER_ALL
        )
        registerBroadcastReceiver()
    }

    /**
     * Unregister listeners, receivers and observers
     */
    fun destroy() {
        dumpManager.unregisterDumpable(TAG)
        secureSettings.unregisterContentObserver(contentObserver)
        unregisterBroadcastReceiver()
    }

    private fun registerBroadcastReceiver() {
        broadcastDispatcher.registerReceiver(
                restoreReceiver,
                FILTER,
                backgroundExecutor,
                UserHandle.of(userId)
        )
    }

    private fun unregisterBroadcastReceiver() {
        broadcastDispatcher.unregisterReceiver(restoreReceiver)
    }

    override fun changeUser(newUser: UserHandle) {
        if (newUser.identifier == userId) return
        unregisterBroadcastReceiver()
        userId = newUser.identifier
        restoredTiles = null
        loadTiles()
        registerBroadcastReceiver()
    }

    /**
     * Returns `true` if the tile has been auto-added before
     */
    fun isAdded(tile: String): Boolean {
        return synchronized(autoAdded) {
            tile in autoAdded
        }
    }

    /**
     * Sets a tile as auto-added.
     *
     * From here on, [isAdded] will return true for that tile.
     */
    fun setTileAdded(tile: String) {
        val tiles = synchronized(autoAdded) {
                if (autoAdded.add(tile)) {
                    getTilesFromListLocked()
                } else {
                    null
                }
            }
        tiles?.let { saveTiles(it) }
    }

    /**
     * Removes a tile from the list of auto-added.
     *
     * This allows for this tile to be auto-added again in the future.
     */
    fun setTileRemoved(tile: String) {
        val tiles = synchronized(autoAdded) {
            if (autoAdded.remove(tile)) {
                getTilesFromListLocked()
            } else {
                null
            }
        }
        tiles?.let { saveTiles(it) }
    }

    private fun getTilesFromListLocked(): String {
        return TextUtils.join(",", autoAdded)
    }

    private fun saveTiles(tiles: String) {
        secureSettings.putStringForUser(
                Settings.Secure.QS_AUTO_ADDED_TILES,
                tiles,
                /* tag */ null,
                /* makeDefault */ false,
                userId,
                /* overrideableByRestore */ true
        )
    }

    private fun loadTiles() {
        synchronized(autoAdded) {
            autoAdded.clear()
            autoAdded.addAll(getAdded())
        }
    }

    private fun getAdded(): Collection<String> {
        val current = secureSettings.getStringForUser(Settings.Secure.QS_AUTO_ADDED_TILES, userId)
        return current?.split(",") ?: emptySet()
    }

    override fun dump(fd: FileDescriptor, pw: PrintWriter, args: Array<out String>) {
        pw.println("Current user: $userId")
        pw.println("Added tiles: $autoAdded")
    }

    @SysUISingleton
    class Builder @Inject constructor(
        private val secureSettings: SecureSettings,
        private val broadcastDispatcher: BroadcastDispatcher,
        private val qsHost: QSHost,
        private val dumpManager: DumpManager,
        @Main private val handler: Handler,
        @Background private val executor: Executor
    ) {
        private var userId: Int = 0

        fun setUserId(_userId: Int): Builder {
            userId = _userId
            return this
        }

        fun build(): AutoAddTracker {
            return AutoAddTracker(
                    secureSettings,
                    broadcastDispatcher,
                    qsHost,
                    dumpManager,
                    handler,
                    executor,
                    userId
            )
        }
    }
}
 No newline at end of file
+1 −0
Original line number Diff line number Diff line
@@ -37,6 +37,7 @@ public interface QSHost {
    void removeCallback(Callback callback);
    TileServices getTileServices();
    void removeTile(String tileSpec);
    void removeTiles(Collection<String> specs);
    void unmarkTileAsAutoAdded(String tileSpec);

    int indexOf(String tileSpec);
Loading