Quick setting tile to toggle work mode for managed profiles

Status bar will also show a different badge icon when managed profile
is in quiet mode i.e. work mode is off. The tile is invisible for now
until the full feature lands.

Bug: 22541941
Change-Id: I53f33ea346cd9215ecee2ca42de137af61e4c8a2
diff --git a/packages/SystemUI/src/com/android/systemui/qs/tiles/WorkModeTile.java b/packages/SystemUI/src/com/android/systemui/qs/tiles/WorkModeTile.java
new file mode 100644
index 0000000..7605f3b8
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/qs/tiles/WorkModeTile.java
@@ -0,0 +1,216 @@
+/*
+ * Copyright (C) 2015 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.tiles;
+
+import android.app.ActivityManager;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.pm.UserInfo;
+import android.os.IUserManager;
+import android.os.RemoteException;
+import android.os.ServiceManager;
+import android.os.UserHandle;
+import android.os.UserManager;
+import android.util.ArraySet;
+import android.util.Log;
+
+import com.android.internal.logging.MetricsLogger;
+import com.android.systemui.R;
+import com.android.systemui.qs.QSTile;
+
+import java.util.LinkedList;
+import java.util.List;
+
+/** Quick settings tile: Work profile on/off */
+public class WorkModeTile extends QSTile<QSTile.BooleanState> {
+    private final AnimationIcon mEnable =
+            new AnimationIcon(R.drawable.ic_signal_workmode_enable_animation);
+    private final AnimationIcon mDisable =
+            new AnimationIcon(R.drawable.ic_signal_workmode_disable_animation);
+
+    private boolean mListening;
+
+    private UserManager mUserManager;
+    private List<UserInfo> mProfiles;
+
+    public WorkModeTile(Host host) {
+        super(host);
+        mUserManager = UserManager.get(mContext);
+        mProfiles = new LinkedList<UserInfo>();
+    }
+
+    @Override
+    protected BooleanState newTileState() {
+        return new BooleanState();
+    }
+
+    @Override
+    public void handleClick() {
+        MetricsLogger.action(mContext, getMetricsCategory(), !mState.value);
+        setWorkModeEnabled(!mState.value);
+    }
+
+    private void reloadManagedProfiles(int userHandle) {
+        synchronized (mProfiles) {
+            mProfiles.clear();
+
+            if (userHandle == UserHandle.USER_CURRENT) {
+                userHandle = ActivityManager.getCurrentUser();
+            }
+            for (UserInfo ui : mUserManager.getEnabledProfiles(userHandle)) {
+                if (ui.isManagedProfile()) {
+                    mProfiles.add(ui);
+                }
+            }
+        }
+    }
+
+    private boolean hasActiveProfile() {
+        synchronized (mProfiles) {
+            return mProfiles.size() > 0;
+        }
+    }
+
+    private boolean isWorkModeEnabled() {
+        synchronized (mProfiles) {
+            for (UserInfo ui : mProfiles) {
+                if (ui.isQuietModeEnabled()) {
+                    return false;
+                }
+            }
+            return true;
+        }
+    }
+
+    private void refreshQuietModeState(boolean backgroundRefresh) {
+        if (backgroundRefresh) {
+            refreshState(isWorkModeEnabled() ? UserBoolean.BACKGROUND_TRUE
+                    : UserBoolean.BACKGROUND_FALSE);
+        } else {
+            refreshState(isWorkModeEnabled() ? UserBoolean.USER_TRUE : UserBoolean.USER_FALSE);
+        }
+    }
+
+    @Override
+    protected void handleUpdateState(BooleanState state, Object arg) {
+        if (!hasActiveProfile()) {
+            state.visible = false;
+            state.value = false;
+            return;
+        }
+
+        final boolean userInitialized;
+        if (arg instanceof UserBoolean) {
+            state.value = ((UserBoolean) arg).value;
+            userInitialized = ((UserBoolean) arg).userInitiated;
+        } else {
+            state.value = isWorkModeEnabled();
+            userInitialized = false;
+        }
+
+        state.visible = true;
+        final AnimationIcon icon;
+        state.label = mContext.getString(R.string.quick_settings_work_mode_label);
+        if (state.value) {
+            icon = mEnable;
+            state.contentDescription =  mContext.getString(
+                    R.string.accessibility_quick_settings_work_mode_on);
+        } else {
+            icon = mDisable;
+            state.contentDescription =  mContext.getString(
+                    R.string.accessibility_quick_settings_work_mode_off);
+        }
+        icon.setAllowAnimation(userInitialized);
+        state.icon = icon;
+    }
+
+    @Override
+    public int getMetricsCategory() {
+        return MetricsLogger.QS_WORKMODE;
+    }
+
+    @Override
+    protected String composeChangeAnnouncement() {
+        if (mState.value) {
+            return mContext.getString(R.string.accessibility_quick_settings_work_mode_changed_on);
+        } else {
+            return mContext.getString(R.string.accessibility_quick_settings_work_mode_changed_off);
+        }
+    }
+
+    @Override
+    public void setListening(boolean listening) {
+        if (mListening == listening) {
+            return;
+        }
+        mListening = listening;
+        if (listening) {
+            reloadManagedProfiles(UserHandle.USER_CURRENT);
+
+            final IntentFilter filter = new IntentFilter();
+            filter.addAction(Intent.ACTION_USER_SWITCHED);
+            filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
+            filter.addAction(Intent.ACTION_MANAGED_PROFILE_REMOVED);
+            filter.addAction(Intent.ACTION_MANAGED_PROFILE_AVAILABILITY_CHANGED);
+            mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, null);
+        } else {
+            mContext.unregisterReceiver(mReceiver);
+        }
+    }
+
+    private void setWorkModeEnabled(boolean enabled) {
+        synchronized (mProfiles) {
+            for (UserInfo ui : mProfiles) {
+                mUserManager.setQuietModeEnabled(ui.id, !enabled);
+            }
+        }
+    }
+
+    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
+        @Override
+        public void onReceive(Context context, Intent intent) {
+            final String action = intent.getAction();
+            final int targetUser;
+            final boolean isBackgroundRefresh;
+            switch (action) {
+                case Intent.ACTION_USER_SWITCHED:
+                    targetUser = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
+                            UserHandle.USER_CURRENT);
+                    isBackgroundRefresh = true;
+                    break;
+                case Intent.ACTION_MANAGED_PROFILE_ADDED:
+                case Intent.ACTION_MANAGED_PROFILE_REMOVED:
+                    targetUser = UserHandle.USER_CURRENT;
+                    isBackgroundRefresh = true;
+                    break;
+                case Intent.ACTION_MANAGED_PROFILE_AVAILABILITY_CHANGED:
+                    targetUser = UserHandle.USER_CURRENT;
+                    isBackgroundRefresh = false;
+                    break;
+               default:
+                   targetUser = UserHandle.USER_NULL;
+                   isBackgroundRefresh = false;
+            }
+            if (targetUser != UserHandle.USER_NULL) {
+                reloadManagedProfiles(targetUser);
+                refreshQuietModeState(isBackgroundRefresh);
+            }
+        }
+    };
+}
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java
index 83edc96..5177f0e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/PhoneStatusBarPolicy.java
@@ -16,6 +16,7 @@
 
 package com.android.systemui.statusbar.phone;
 
+import android.app.ActivityManager;
 import android.app.ActivityManagerNative;
 import android.app.AlarmManager;
 import android.app.AlarmManager.AlarmClockInfo;
@@ -72,6 +73,7 @@
     private final HotspotController mHotspot;
     private final AlarmManager mAlarmManager;
     private final UserInfoController mUserInfoController;
+    private final UserManager mUserManager;
 
     // Assume it's all good unless we hear otherwise.  We don't always seem
     // to get broadcasts that it *is* there.
@@ -84,7 +86,8 @@
     private int mZen;
 
     private boolean mManagedProfileFocused = false;
-    private boolean mManagedProfileIconVisible = true;
+    private boolean mManagedProfileIconVisible = false;
+    private boolean mManagedProfileInQuietMode = false;
 
     private boolean mKeyguardVisible = true;
     private BluetoothController mBluetooth;
@@ -106,6 +109,10 @@
             else if (action.equals(TelecomManager.ACTION_CURRENT_TTY_MODE_CHANGED)) {
                 updateTTY(intent);
             }
+            else if (action.equals(Intent.ACTION_MANAGED_PROFILE_AVAILABILITY_CHANGED)) {
+                updateQuietState();
+                updateManagedProfile();
+            }
         }
     };
 
@@ -127,6 +134,7 @@
         mService = (StatusBarManager) context.getSystemService(Context.STATUS_BAR_SERVICE);
         mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
         mUserInfoController = userInfoController;
+        mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
 
         // listen for broadcasts
         IntentFilter filter = new IntentFilter();
@@ -135,6 +143,7 @@
         filter.addAction(AudioManager.INTERNAL_RINGER_MODE_CHANGED_ACTION);
         filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED);
         filter.addAction(TelecomManager.ACTION_CURRENT_TTY_MODE_CHANGED);
+        filter.addAction(Intent.ACTION_MANAGED_PROFILE_AVAILABILITY_CHANGED);
         mContext.registerReceiver(mIntentReceiver, filter, null, mHandler);
 
         // listen for user / profile change.
@@ -178,7 +187,7 @@
         // managed profile
         mService.setIcon(SLOT_MANAGED_PROFILE, R.drawable.stat_sys_managed_profile_status, 0,
                 mContext.getString(R.string.accessibility_managed_profile));
-        mService.setIconVisibility(SLOT_MANAGED_PROFILE, false);
+        mService.setIconVisibility(SLOT_MANAGED_PROFILE, mManagedProfileIconVisible);
     }
 
     public void setZenMode(int zen) {
@@ -349,8 +358,18 @@
         }
     }
 
+    private void updateQuietState() {
+        mManagedProfileInQuietMode = false;
+        int currentUserId = ActivityManager.getCurrentUser();
+        for (UserInfo ui : mUserManager.getEnabledProfiles(currentUserId)) {
+            if (ui.isManagedProfile() && ui.isQuietModeEnabled()) {
+                mManagedProfileInQuietMode = true;
+                return;
+            }
+        }
+    }
+
     private void profileChanged(int userId) {
-        UserManager userManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
         UserInfo user = null;
         if (userId == UserHandle.USER_CURRENT) {
             try {
@@ -359,7 +378,7 @@
                 // Ignore
             }
         } else {
-            user = userManager.getUserInfo(userId);
+            user = mUserManager.getUserInfo(userId);
         }
 
         mManagedProfileFocused = user != null && user.isManagedProfile();
@@ -371,7 +390,18 @@
         if (DEBUG) Log.v(TAG, "updateManagedProfile: mManagedProfileFocused: "
                 + mManagedProfileFocused
                 + " mKeyguardVisible: " + mKeyguardVisible);
-        boolean showIcon = mManagedProfileFocused && !mKeyguardVisible;
+        final boolean showIcon;
+        if (mManagedProfileFocused && !mKeyguardVisible) {
+            showIcon = true;
+            mService.setIcon(SLOT_MANAGED_PROFILE, R.drawable.stat_sys_managed_profile_status, 0,
+                    mContext.getString(R.string.accessibility_managed_profile));
+        } else if (mManagedProfileInQuietMode) {
+            showIcon = true;
+            mService.setIcon(SLOT_MANAGED_PROFILE, R.drawable.stat_sys_managed_profile_status_off, 0,
+                    mContext.getString(R.string.accessibility_managed_profile));
+        } else {
+            showIcon = false;
+        }
         if (mManagedProfileIconVisible != showIcon) {
             mService.setIconVisibility(SLOT_MANAGED_PROFILE, showIcon);
             mManagedProfileIconVisible = showIcon;
@@ -395,6 +425,8 @@
                 public void onUserSwitchComplete(int newUserId) throws RemoteException {
                     updateAlarm();
                     profileChanged(newUserId);
+                    updateQuietState();
+                    updateManagedProfile();
                 }
 
                 @Override
@@ -430,5 +462,6 @@
         if (mCurrentUserSetup == userSetup) return;
         mCurrentUserSetup = userSetup;
         updateAlarm();
+        updateQuietState();
     }
 }
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QSTileHost.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QSTileHost.java
index f7ff8aa..327b81e 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QSTileHost.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QSTileHost.java
@@ -54,6 +54,7 @@
 import com.android.systemui.qs.tiles.RotationLockTile;
 import com.android.systemui.qs.tiles.UserTile;
 import com.android.systemui.qs.tiles.WifiTile;
+import com.android.systemui.qs.tiles.WorkModeTile;
 import com.android.systemui.statusbar.policy.BatteryController;
 import com.android.systemui.statusbar.policy.BluetoothController;
 import com.android.systemui.statusbar.policy.CastController;
@@ -338,6 +339,7 @@
         else if (tileSpec.equals("inversion")) return new ColorInversionTile(this);
         else if (tileSpec.equals("cell")) return new CellularTile(this);
         else if (tileSpec.equals("airplane")) return new AirplaneModeTile(this);
+        else if (tileSpec.equals("work")) return new WorkModeTile(this);
         else if (tileSpec.equals("dnd")) return new DndTile(this);
         else if (tileSpec.equals("rotation")) return new RotationLockTile(this);
         else if (tileSpec.equals("flashlight")) return new FlashlightTile(this);