1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy 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,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.internal.policy.impl;
18
19import com.android.internal.app.AlertController;
20import com.android.internal.app.AlertController.AlertParams;
21import com.android.internal.telephony.TelephonyIntents;
22import com.android.internal.telephony.TelephonyProperties;
23import com.android.internal.R;
24
25import android.app.ActivityManagerNative;
26import android.app.AlertDialog;
27import android.app.Dialog;
28import android.content.BroadcastReceiver;
29import android.content.Context;
30import android.content.DialogInterface;
31import android.content.Intent;
32import android.content.IntentFilter;
33import android.content.pm.UserInfo;
34import android.database.ContentObserver;
35import android.graphics.drawable.Drawable;
36import android.media.AudioManager;
37import android.net.ConnectivityManager;
38import android.os.Bundle;
39import android.os.Handler;
40import android.os.Message;
41import android.os.RemoteException;
42import android.os.ServiceManager;
43import android.os.SystemClock;
44import android.os.SystemProperties;
45import android.os.UserHandle;
46import android.os.UserManager;
47import android.os.Vibrator;
48import android.provider.Settings;
49import android.service.dreams.DreamService;
50import android.service.dreams.IDreamManager;
51import android.telephony.PhoneStateListener;
52import android.telephony.ServiceState;
53import android.telephony.TelephonyManager;
54import android.util.Log;
55import android.util.TypedValue;
56import android.view.InputDevice;
57import android.view.KeyEvent;
58import android.view.LayoutInflater;
59import android.view.MotionEvent;
60import android.view.View;
61import android.view.ViewConfiguration;
62import android.view.ViewGroup;
63import android.view.WindowManager;
64import android.view.WindowManagerPolicy.WindowManagerFuncs;
65import android.widget.AdapterView;
66import android.widget.BaseAdapter;
67import android.widget.ImageView;
68import android.widget.ImageView.ScaleType;
69import android.widget.ListView;
70import android.widget.TextView;
71
72import java.util.ArrayList;
73import java.util.List;
74
75/**
76 * Helper to show the global actions dialog.  Each item is an {@link Action} that
77 * may show depending on whether the keyguard is showing, and whether the device
78 * is provisioned.
79 */
80class GlobalActions implements DialogInterface.OnDismissListener, DialogInterface.OnClickListener  {
81
82    private static final String TAG = "GlobalActions";
83
84    private static final boolean SHOW_SILENT_TOGGLE = true;
85
86    private final Context mContext;
87    private final WindowManagerFuncs mWindowManagerFuncs;
88    private final AudioManager mAudioManager;
89    private final IDreamManager mDreamManager;
90
91    private ArrayList<Action> mItems;
92    private GlobalActionsDialog mDialog;
93
94    private Action mSilentModeAction;
95    private ToggleAction mAirplaneModeOn;
96
97    private MyAdapter mAdapter;
98
99    private boolean mKeyguardShowing = false;
100    private boolean mDeviceProvisioned = false;
101    private ToggleAction.State mAirplaneState = ToggleAction.State.Off;
102    private boolean mIsWaitingForEcmExit = false;
103    private boolean mHasTelephony;
104    private boolean mHasVibrator;
105    private final boolean mShowSilentToggle;
106
107    /**
108     * @param context everything needs a context :(
109     */
110    public GlobalActions(Context context, WindowManagerFuncs windowManagerFuncs) {
111        mContext = context;
112        mWindowManagerFuncs = windowManagerFuncs;
113        mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
114        mDreamManager = IDreamManager.Stub.asInterface(
115                ServiceManager.getService(DreamService.DREAM_SERVICE));
116
117        // receive broadcasts
118        IntentFilter filter = new IntentFilter();
119        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
120        filter.addAction(Intent.ACTION_SCREEN_OFF);
121        filter.addAction(TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED);
122        context.registerReceiver(mBroadcastReceiver, filter);
123
124        // get notified of phone state changes
125        TelephonyManager telephonyManager =
126                (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
127        telephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_SERVICE_STATE);
128        ConnectivityManager cm = (ConnectivityManager)
129                context.getSystemService(Context.CONNECTIVITY_SERVICE);
130        mHasTelephony = cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE);
131        mContext.getContentResolver().registerContentObserver(
132                Settings.Global.getUriFor(Settings.Global.AIRPLANE_MODE_ON), true,
133                mAirplaneModeObserver);
134        Vibrator vibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
135        mHasVibrator = vibrator != null && vibrator.hasVibrator();
136
137        mShowSilentToggle = SHOW_SILENT_TOGGLE && !mContext.getResources().getBoolean(
138                com.android.internal.R.bool.config_useFixedVolume);
139    }
140
141    /**
142     * Show the global actions dialog (creating if necessary)
143     * @param keyguardShowing True if keyguard is showing
144     */
145    public void showDialog(boolean keyguardShowing, boolean isDeviceProvisioned) {
146        mKeyguardShowing = keyguardShowing;
147        mDeviceProvisioned = isDeviceProvisioned;
148        if (mDialog != null) {
149            mDialog.dismiss();
150            mDialog = null;
151            // Show delayed, so that the dismiss of the previous dialog completes
152            mHandler.sendEmptyMessage(MESSAGE_SHOW);
153        } else {
154            handleShow();
155        }
156    }
157
158    private void awakenIfNecessary() {
159        if (mDreamManager != null) {
160            try {
161                if (mDreamManager.isDreaming()) {
162                    mDreamManager.awaken();
163                }
164            } catch (RemoteException e) {
165                // we tried
166            }
167        }
168    }
169
170    private void handleShow() {
171        awakenIfNecessary();
172        mDialog = createDialog();
173        prepareDialog();
174
175        WindowManager.LayoutParams attrs = mDialog.getWindow().getAttributes();
176        attrs.setTitle("GlobalActions");
177        mDialog.getWindow().setAttributes(attrs);
178        mDialog.show();
179        mDialog.getWindow().getDecorView().setSystemUiVisibility(View.STATUS_BAR_DISABLE_EXPAND);
180    }
181
182    /**
183     * Create the global actions dialog.
184     * @return A new dialog.
185     */
186    private GlobalActionsDialog createDialog() {
187        // Simple toggle style if there's no vibrator, otherwise use a tri-state
188        if (!mHasVibrator) {
189            mSilentModeAction = new SilentModeToggleAction();
190        } else {
191            mSilentModeAction = new SilentModeTriStateAction(mContext, mAudioManager, mHandler);
192        }
193        mAirplaneModeOn = new ToggleAction(
194                R.drawable.ic_lock_airplane_mode,
195                R.drawable.ic_lock_airplane_mode_off,
196                R.string.global_actions_toggle_airplane_mode,
197                R.string.global_actions_airplane_mode_on_status,
198                R.string.global_actions_airplane_mode_off_status) {
199
200            void onToggle(boolean on) {
201                if (mHasTelephony && Boolean.parseBoolean(
202                        SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE))) {
203                    mIsWaitingForEcmExit = true;
204                    // Launch ECM exit dialog
205                    Intent ecmDialogIntent =
206                            new Intent(TelephonyIntents.ACTION_SHOW_NOTICE_ECM_BLOCK_OTHERS, null);
207                    ecmDialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
208                    mContext.startActivity(ecmDialogIntent);
209                } else {
210                    changeAirplaneModeSystemSetting(on);
211                }
212            }
213
214            @Override
215            protected void changeStateFromPress(boolean buttonOn) {
216                if (!mHasTelephony) return;
217
218                // In ECM mode airplane state cannot be changed
219                if (!(Boolean.parseBoolean(
220                        SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE)))) {
221                    mState = buttonOn ? State.TurningOn : State.TurningOff;
222                    mAirplaneState = mState;
223                }
224            }
225
226            public boolean showDuringKeyguard() {
227                return true;
228            }
229
230            public boolean showBeforeProvisioning() {
231                return false;
232            }
233        };
234        onAirplaneModeChanged();
235
236        mItems = new ArrayList<Action>();
237
238        // first: power off
239        mItems.add(
240            new SinglePressAction(
241                    com.android.internal.R.drawable.ic_lock_power_off,
242                    R.string.global_action_power_off) {
243
244                public void onPress() {
245                    // shutdown by making sure radio and power are handled accordingly.
246                    mWindowManagerFuncs.shutdown(true);
247                }
248
249                public boolean onLongPress() {
250                    mWindowManagerFuncs.rebootSafeMode(true);
251                    return true;
252                }
253
254                public boolean showDuringKeyguard() {
255                    return true;
256                }
257
258                public boolean showBeforeProvisioning() {
259                    return true;
260                }
261            });
262
263        // next: airplane mode
264        mItems.add(mAirplaneModeOn);
265
266        // next: bug report, if enabled
267        if (Settings.Global.getInt(mContext.getContentResolver(),
268                Settings.Global.BUGREPORT_IN_POWER_MENU, 0) != 0) {
269            mItems.add(
270                new SinglePressAction(com.android.internal.R.drawable.stat_sys_adb,
271                        R.string.global_action_bug_report) {
272
273                    public void onPress() {
274                        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
275                        builder.setTitle(com.android.internal.R.string.bugreport_title);
276                        builder.setMessage(com.android.internal.R.string.bugreport_message);
277                        builder.setNegativeButton(com.android.internal.R.string.cancel, null);
278                        builder.setPositiveButton(com.android.internal.R.string.report,
279                                new DialogInterface.OnClickListener() {
280                                    @Override
281                                    public void onClick(DialogInterface dialog, int which) {
282                                        // Add a little delay before executing, to give the
283                                        // dialog a chance to go away before it takes a
284                                        // screenshot.
285                                        mHandler.postDelayed(new Runnable() {
286                                            @Override public void run() {
287                                                try {
288                                                    ActivityManagerNative.getDefault()
289                                                            .requestBugReport();
290                                                } catch (RemoteException e) {
291                                                }
292                                            }
293                                        }, 500);
294                                    }
295                                });
296                        AlertDialog dialog = builder.create();
297                        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
298                        dialog.show();
299                    }
300
301                    public boolean onLongPress() {
302                        return false;
303                    }
304
305                    public boolean showDuringKeyguard() {
306                        return true;
307                    }
308
309                    public boolean showBeforeProvisioning() {
310                        return false;
311                    }
312                });
313        }
314
315        // last: silent mode
316        if (mShowSilentToggle) {
317            mItems.add(mSilentModeAction);
318        }
319
320        // one more thing: optionally add a list of users to switch to
321        if (SystemProperties.getBoolean("fw.power_user_switcher", false)) {
322            addUsersToMenu(mItems);
323        }
324
325        mAdapter = new MyAdapter();
326
327        AlertParams params = new AlertParams(mContext);
328        params.mAdapter = mAdapter;
329        params.mOnClickListener = this;
330        params.mForceInverseBackground = true;
331
332        GlobalActionsDialog dialog = new GlobalActionsDialog(mContext, params);
333        dialog.setCanceledOnTouchOutside(false); // Handled by the custom class.
334
335        dialog.getListView().setItemsCanFocus(true);
336        dialog.getListView().setLongClickable(true);
337        dialog.getListView().setOnItemLongClickListener(
338                new AdapterView.OnItemLongClickListener() {
339                    @Override
340                    public boolean onItemLongClick(AdapterView<?> parent, View view, int position,
341                            long id) {
342                        return mAdapter.getItem(position).onLongPress();
343                    }
344        });
345        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
346
347        dialog.setOnDismissListener(this);
348
349        return dialog;
350    }
351
352    private void addUsersToMenu(ArrayList<Action> items) {
353        List<UserInfo> users = ((UserManager) mContext.getSystemService(Context.USER_SERVICE))
354                .getUsers();
355        if (users.size() > 1) {
356            UserInfo currentUser;
357            try {
358                currentUser = ActivityManagerNative.getDefault().getCurrentUser();
359            } catch (RemoteException re) {
360                currentUser = null;
361            }
362            for (final UserInfo user : users) {
363                boolean isCurrentUser = currentUser == null
364                        ? user.id == 0 : (currentUser.id == user.id);
365                Drawable icon = user.iconPath != null ? Drawable.createFromPath(user.iconPath)
366                        : null;
367                SinglePressAction switchToUser = new SinglePressAction(
368                        com.android.internal.R.drawable.ic_menu_cc, icon,
369                        (user.name != null ? user.name : "Primary")
370                        + (isCurrentUser ? " \u2714" : "")) {
371                    public void onPress() {
372                        try {
373                            ActivityManagerNative.getDefault().switchUser(user.id);
374                        } catch (RemoteException re) {
375                            Log.e(TAG, "Couldn't switch user " + re);
376                        }
377                    }
378
379                    public boolean showDuringKeyguard() {
380                        return true;
381                    }
382
383                    public boolean showBeforeProvisioning() {
384                        return false;
385                    }
386                };
387                items.add(switchToUser);
388            }
389        }
390    }
391
392    private void prepareDialog() {
393        refreshSilentMode();
394        mAirplaneModeOn.updateState(mAirplaneState);
395        mAdapter.notifyDataSetChanged();
396        mDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
397        if (mShowSilentToggle) {
398            IntentFilter filter = new IntentFilter(AudioManager.RINGER_MODE_CHANGED_ACTION);
399            mContext.registerReceiver(mRingerModeReceiver, filter);
400        }
401    }
402
403    private void refreshSilentMode() {
404        if (!mHasVibrator) {
405            final boolean silentModeOn =
406                    mAudioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL;
407            ((ToggleAction)mSilentModeAction).updateState(
408                    silentModeOn ? ToggleAction.State.On : ToggleAction.State.Off);
409        }
410    }
411
412    /** {@inheritDoc} */
413    public void onDismiss(DialogInterface dialog) {
414        if (mShowSilentToggle) {
415            try {
416                mContext.unregisterReceiver(mRingerModeReceiver);
417            } catch (IllegalArgumentException ie) {
418                // ignore this
419                Log.w(TAG, ie);
420            }
421        }
422    }
423
424    /** {@inheritDoc} */
425    public void onClick(DialogInterface dialog, int which) {
426        if (!(mAdapter.getItem(which) instanceof SilentModeTriStateAction)) {
427            dialog.dismiss();
428        }
429        mAdapter.getItem(which).onPress();
430    }
431
432    /**
433     * The adapter used for the list within the global actions dialog, taking
434     * into account whether the keyguard is showing via
435     * {@link GlobalActions#mKeyguardShowing} and whether the device is provisioned
436     * via {@link GlobalActions#mDeviceProvisioned}.
437     */
438    private class MyAdapter extends BaseAdapter {
439
440        public int getCount() {
441            int count = 0;
442
443            for (int i = 0; i < mItems.size(); i++) {
444                final Action action = mItems.get(i);
445
446                if (mKeyguardShowing && !action.showDuringKeyguard()) {
447                    continue;
448                }
449                if (!mDeviceProvisioned && !action.showBeforeProvisioning()) {
450                    continue;
451                }
452                count++;
453            }
454            return count;
455        }
456
457        @Override
458        public boolean isEnabled(int position) {
459            return getItem(position).isEnabled();
460        }
461
462        @Override
463        public boolean areAllItemsEnabled() {
464            return false;
465        }
466
467        public Action getItem(int position) {
468
469            int filteredPos = 0;
470            for (int i = 0; i < mItems.size(); i++) {
471                final Action action = mItems.get(i);
472                if (mKeyguardShowing && !action.showDuringKeyguard()) {
473                    continue;
474                }
475                if (!mDeviceProvisioned && !action.showBeforeProvisioning()) {
476                    continue;
477                }
478                if (filteredPos == position) {
479                    return action;
480                }
481                filteredPos++;
482            }
483
484            throw new IllegalArgumentException("position " + position
485                    + " out of range of showable actions"
486                    + ", filtered count=" + getCount()
487                    + ", keyguardshowing=" + mKeyguardShowing
488                    + ", provisioned=" + mDeviceProvisioned);
489        }
490
491
492        public long getItemId(int position) {
493            return position;
494        }
495
496        public View getView(int position, View convertView, ViewGroup parent) {
497            Action action = getItem(position);
498            return action.create(mContext, convertView, parent, LayoutInflater.from(mContext));
499        }
500    }
501
502    // note: the scheme below made more sense when we were planning on having
503    // 8 different things in the global actions dialog.  seems overkill with
504    // only 3 items now, but may as well keep this flexible approach so it will
505    // be easy should someone decide at the last minute to include something
506    // else, such as 'enable wifi', or 'enable bluetooth'
507
508    /**
509     * What each item in the global actions dialog must be able to support.
510     */
511    private interface Action {
512        View create(Context context, View convertView, ViewGroup parent, LayoutInflater inflater);
513
514        void onPress();
515
516        public boolean onLongPress();
517
518        /**
519         * @return whether this action should appear in the dialog when the keygaurd
520         *    is showing.
521         */
522        boolean showDuringKeyguard();
523
524        /**
525         * @return whether this action should appear in the dialog before the
526         *   device is provisioned.
527         */
528        boolean showBeforeProvisioning();
529
530        boolean isEnabled();
531    }
532
533    /**
534     * A single press action maintains no state, just responds to a press
535     * and takes an action.
536     */
537    private static abstract class SinglePressAction implements Action {
538        private final int mIconResId;
539        private final Drawable mIcon;
540        private final int mMessageResId;
541        private final CharSequence mMessage;
542
543        protected SinglePressAction(int iconResId, int messageResId) {
544            mIconResId = iconResId;
545            mMessageResId = messageResId;
546            mMessage = null;
547            mIcon = null;
548        }
549
550        protected SinglePressAction(int iconResId, Drawable icon, CharSequence message) {
551            mIconResId = iconResId;
552            mMessageResId = 0;
553            mMessage = message;
554            mIcon = icon;
555        }
556
557        protected SinglePressAction(int iconResId, CharSequence message) {
558            mIconResId = iconResId;
559            mMessageResId = 0;
560            mMessage = message;
561            mIcon = null;
562        }
563
564        public boolean isEnabled() {
565            return true;
566        }
567
568        abstract public void onPress();
569
570        public boolean onLongPress() {
571            return false;
572        }
573
574        public View create(
575                Context context, View convertView, ViewGroup parent, LayoutInflater inflater) {
576            View v = inflater.inflate(R.layout.global_actions_item, parent, false);
577
578            ImageView icon = (ImageView) v.findViewById(R.id.icon);
579            TextView messageView = (TextView) v.findViewById(R.id.message);
580
581            v.findViewById(R.id.status).setVisibility(View.GONE);
582            if (mIcon != null) {
583                icon.setImageDrawable(mIcon);
584                icon.setScaleType(ScaleType.CENTER_CROP);
585            } else if (mIconResId != 0) {
586                icon.setImageDrawable(context.getResources().getDrawable(mIconResId));
587            }
588            if (mMessage != null) {
589                messageView.setText(mMessage);
590            } else {
591                messageView.setText(mMessageResId);
592            }
593
594            return v;
595        }
596    }
597
598    /**
599     * A toggle action knows whether it is on or off, and displays an icon
600     * and status message accordingly.
601     */
602    private static abstract class ToggleAction implements Action {
603
604        enum State {
605            Off(false),
606            TurningOn(true),
607            TurningOff(true),
608            On(false);
609
610            private final boolean inTransition;
611
612            State(boolean intermediate) {
613                inTransition = intermediate;
614            }
615
616            public boolean inTransition() {
617                return inTransition;
618            }
619        }
620
621        protected State mState = State.Off;
622
623        // prefs
624        protected int mEnabledIconResId;
625        protected int mDisabledIconResid;
626        protected int mMessageResId;
627        protected int mEnabledStatusMessageResId;
628        protected int mDisabledStatusMessageResId;
629
630        /**
631         * @param enabledIconResId The icon for when this action is on.
632         * @param disabledIconResid The icon for when this action is off.
633         * @param essage The general information message, e.g 'Silent Mode'
634         * @param enabledStatusMessageResId The on status message, e.g 'sound disabled'
635         * @param disabledStatusMessageResId The off status message, e.g. 'sound enabled'
636         */
637        public ToggleAction(int enabledIconResId,
638                int disabledIconResid,
639                int message,
640                int enabledStatusMessageResId,
641                int disabledStatusMessageResId) {
642            mEnabledIconResId = enabledIconResId;
643            mDisabledIconResid = disabledIconResid;
644            mMessageResId = message;
645            mEnabledStatusMessageResId = enabledStatusMessageResId;
646            mDisabledStatusMessageResId = disabledStatusMessageResId;
647        }
648
649        /**
650         * Override to make changes to resource IDs just before creating the
651         * View.
652         */
653        void willCreate() {
654
655        }
656
657        public View create(Context context, View convertView, ViewGroup parent,
658                LayoutInflater inflater) {
659            willCreate();
660
661            View v = inflater.inflate(R
662                            .layout.global_actions_item, parent, false);
663
664            ImageView icon = (ImageView) v.findViewById(R.id.icon);
665            TextView messageView = (TextView) v.findViewById(R.id.message);
666            TextView statusView = (TextView) v.findViewById(R.id.status);
667            final boolean enabled = isEnabled();
668
669            if (messageView != null) {
670                messageView.setText(mMessageResId);
671                messageView.setEnabled(enabled);
672            }
673
674            boolean on = ((mState == State.On) || (mState == State.TurningOn));
675            if (icon != null) {
676                icon.setImageDrawable(context.getResources().getDrawable(
677                        (on ? mEnabledIconResId : mDisabledIconResid)));
678                icon.setEnabled(enabled);
679            }
680
681            if (statusView != null) {
682                statusView.setText(on ? mEnabledStatusMessageResId : mDisabledStatusMessageResId);
683                statusView.setVisibility(View.VISIBLE);
684                statusView.setEnabled(enabled);
685            }
686            v.setEnabled(enabled);
687
688            return v;
689        }
690
691        public final void onPress() {
692            if (mState.inTransition()) {
693                Log.w(TAG, "shouldn't be able to toggle when in transition");
694                return;
695            }
696
697            final boolean nowOn = !(mState == State.On);
698            onToggle(nowOn);
699            changeStateFromPress(nowOn);
700        }
701
702        public boolean onLongPress() {
703            return false;
704        }
705
706        public boolean isEnabled() {
707            return !mState.inTransition();
708        }
709
710        /**
711         * Implementations may override this if their state can be in on of the intermediate
712         * states until some notification is received (e.g airplane mode is 'turning off' until
713         * we know the wireless connections are back online
714         * @param buttonOn Whether the button was turned on or off
715         */
716        protected void changeStateFromPress(boolean buttonOn) {
717            mState = buttonOn ? State.On : State.Off;
718        }
719
720        abstract void onToggle(boolean on);
721
722        public void updateState(State state) {
723            mState = state;
724        }
725    }
726
727    private class SilentModeToggleAction extends ToggleAction {
728        public SilentModeToggleAction() {
729            super(R.drawable.ic_audio_vol_mute,
730                    R.drawable.ic_audio_vol,
731                    R.string.global_action_toggle_silent_mode,
732                    R.string.global_action_silent_mode_on_status,
733                    R.string.global_action_silent_mode_off_status);
734        }
735
736        void onToggle(boolean on) {
737            if (on) {
738                mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
739            } else {
740                mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
741            }
742        }
743
744        public boolean showDuringKeyguard() {
745            return true;
746        }
747
748        public boolean showBeforeProvisioning() {
749            return false;
750        }
751    }
752
753    private static class SilentModeTriStateAction implements Action, View.OnClickListener {
754
755        private final int[] ITEM_IDS = { R.id.option1, R.id.option2, R.id.option3 };
756
757        private final AudioManager mAudioManager;
758        private final Handler mHandler;
759        private final Context mContext;
760
761        SilentModeTriStateAction(Context context, AudioManager audioManager, Handler handler) {
762            mAudioManager = audioManager;
763            mHandler = handler;
764            mContext = context;
765        }
766
767        private int ringerModeToIndex(int ringerMode) {
768            // They just happen to coincide
769            return ringerMode;
770        }
771
772        private int indexToRingerMode(int index) {
773            // They just happen to coincide
774            return index;
775        }
776
777        public View create(Context context, View convertView, ViewGroup parent,
778                LayoutInflater inflater) {
779            View v = inflater.inflate(R.layout.global_actions_silent_mode, parent, false);
780
781            int selectedIndex = ringerModeToIndex(mAudioManager.getRingerMode());
782            for (int i = 0; i < 3; i++) {
783                View itemView = v.findViewById(ITEM_IDS[i]);
784                itemView.setSelected(selectedIndex == i);
785                // Set up click handler
786                itemView.setTag(i);
787                itemView.setOnClickListener(this);
788            }
789            return v;
790        }
791
792        public void onPress() {
793        }
794
795        public boolean onLongPress() {
796            return false;
797        }
798
799        public boolean showDuringKeyguard() {
800            return true;
801        }
802
803        public boolean showBeforeProvisioning() {
804            return false;
805        }
806
807        public boolean isEnabled() {
808            return true;
809        }
810
811        void willCreate() {
812        }
813
814        public void onClick(View v) {
815            if (!(v.getTag() instanceof Integer)) return;
816
817            int index = (Integer) v.getTag();
818            mAudioManager.setRingerMode(indexToRingerMode(index));
819            mHandler.sendEmptyMessageDelayed(MESSAGE_DISMISS, DIALOG_DISMISS_DELAY);
820        }
821    }
822
823    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
824        public void onReceive(Context context, Intent intent) {
825            String action = intent.getAction();
826            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)
827                    || Intent.ACTION_SCREEN_OFF.equals(action)) {
828                String reason = intent.getStringExtra(PhoneWindowManager.SYSTEM_DIALOG_REASON_KEY);
829                if (!PhoneWindowManager.SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS.equals(reason)) {
830                    mHandler.sendEmptyMessage(MESSAGE_DISMISS);
831                }
832            } else if (TelephonyIntents.ACTION_EMERGENCY_CALLBACK_MODE_CHANGED.equals(action)) {
833                // Airplane mode can be changed after ECM exits if airplane toggle button
834                // is pressed during ECM mode
835                if (!(intent.getBooleanExtra("PHONE_IN_ECM_STATE", false)) &&
836                        mIsWaitingForEcmExit) {
837                    mIsWaitingForEcmExit = false;
838                    changeAirplaneModeSystemSetting(true);
839                }
840            }
841        }
842    };
843
844    PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
845        @Override
846        public void onServiceStateChanged(ServiceState serviceState) {
847            if (!mHasTelephony) return;
848            final boolean inAirplaneMode = serviceState.getState() == ServiceState.STATE_POWER_OFF;
849            mAirplaneState = inAirplaneMode ? ToggleAction.State.On : ToggleAction.State.Off;
850            mAirplaneModeOn.updateState(mAirplaneState);
851            mAdapter.notifyDataSetChanged();
852        }
853    };
854
855    private BroadcastReceiver mRingerModeReceiver = new BroadcastReceiver() {
856        @Override
857        public void onReceive(Context context, Intent intent) {
858            if (intent.getAction().equals(AudioManager.RINGER_MODE_CHANGED_ACTION)) {
859                mHandler.sendEmptyMessage(MESSAGE_REFRESH);
860            }
861        }
862    };
863
864    private ContentObserver mAirplaneModeObserver = new ContentObserver(new Handler()) {
865        @Override
866        public void onChange(boolean selfChange) {
867            onAirplaneModeChanged();
868        }
869    };
870
871    private static final int MESSAGE_DISMISS = 0;
872    private static final int MESSAGE_REFRESH = 1;
873    private static final int MESSAGE_SHOW = 2;
874    private static final int DIALOG_DISMISS_DELAY = 300; // ms
875
876    private Handler mHandler = new Handler() {
877        public void handleMessage(Message msg) {
878            switch (msg.what) {
879            case MESSAGE_DISMISS:
880                if (mDialog != null) {
881                    mDialog.dismiss();
882                }
883                break;
884            case MESSAGE_REFRESH:
885                refreshSilentMode();
886                mAdapter.notifyDataSetChanged();
887                break;
888            case MESSAGE_SHOW:
889                handleShow();
890                break;
891            }
892        }
893    };
894
895    private void onAirplaneModeChanged() {
896        // Let the service state callbacks handle the state.
897        if (mHasTelephony) return;
898
899        boolean airplaneModeOn = Settings.Global.getInt(
900                mContext.getContentResolver(),
901                Settings.Global.AIRPLANE_MODE_ON,
902                0) == 1;
903        mAirplaneState = airplaneModeOn ? ToggleAction.State.On : ToggleAction.State.Off;
904        mAirplaneModeOn.updateState(mAirplaneState);
905    }
906
907    /**
908     * Change the airplane mode system setting
909     */
910    private void changeAirplaneModeSystemSetting(boolean on) {
911        Settings.Global.putInt(
912                mContext.getContentResolver(),
913                Settings.Global.AIRPLANE_MODE_ON,
914                on ? 1 : 0);
915        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
916        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
917        intent.putExtra("state", on);
918        mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
919        if (!mHasTelephony) {
920            mAirplaneState = on ? ToggleAction.State.On : ToggleAction.State.Off;
921        }
922    }
923
924    private static final class GlobalActionsDialog extends Dialog implements DialogInterface {
925        private final Context mContext;
926        private final int mWindowTouchSlop;
927        private final AlertController mAlert;
928
929        private EnableAccessibilityController mEnableAccessibilityController;
930
931        private boolean mIntercepted;
932        private boolean mCancelOnUp;
933
934        public GlobalActionsDialog(Context context, AlertParams params) {
935            super(context, getDialogTheme(context));
936            mContext = context;
937            mAlert = new AlertController(mContext, this, getWindow());
938            mWindowTouchSlop = ViewConfiguration.get(context).getScaledWindowTouchSlop();
939            params.apply(mAlert);
940        }
941
942        private static int getDialogTheme(Context context) {
943            TypedValue outValue = new TypedValue();
944            context.getTheme().resolveAttribute(com.android.internal.R.attr.alertDialogTheme,
945                    outValue, true);
946            return outValue.resourceId;
947        }
948
949        @Override
950        protected void onStart() {
951            // If global accessibility gesture can be performed, we will take care
952            // of dismissing the dialog on touch outside. This is because the dialog
953            // is dismissed on the first down while the global gesture is a long press
954            // with two fingers anywhere on the screen.
955            if (EnableAccessibilityController.canEnableAccessibilityViaGesture(mContext)) {
956                mEnableAccessibilityController = new EnableAccessibilityController(mContext);
957                super.setCanceledOnTouchOutside(false);
958            } else {
959                mEnableAccessibilityController = null;
960                super.setCanceledOnTouchOutside(true);
961            }
962            super.onStart();
963        }
964
965        @Override
966        protected void onStop() {
967            if (mEnableAccessibilityController != null) {
968                mEnableAccessibilityController.onDestroy();
969            }
970            super.onStop();
971        }
972
973        @Override
974        public boolean dispatchTouchEvent(MotionEvent event) {
975            if (mEnableAccessibilityController != null) {
976                final int action = event.getActionMasked();
977                if (action == MotionEvent.ACTION_DOWN) {
978                    View decor = getWindow().getDecorView();
979                    final int eventX = (int) event.getX();
980                    final int eventY = (int) event.getY();
981                    if (eventX < -mWindowTouchSlop
982                            || eventY < -mWindowTouchSlop
983                            || eventX >= decor.getWidth() + mWindowTouchSlop
984                            || eventY >= decor.getHeight() + mWindowTouchSlop) {
985                        mCancelOnUp = true;
986                    }
987                }
988                try {
989                    if (!mIntercepted) {
990                        mIntercepted = mEnableAccessibilityController.onInterceptTouchEvent(event);
991                        if (mIntercepted) {
992                            final long now = SystemClock.uptimeMillis();
993                            event = MotionEvent.obtain(now, now,
994                                    MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
995                            event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
996                            mCancelOnUp = true;
997                        }
998                    } else {
999                        return mEnableAccessibilityController.onTouchEvent(event);
1000                    }
1001                } finally {
1002                    if (action == MotionEvent.ACTION_UP) {
1003                        if (mCancelOnUp) {
1004                            cancel();
1005                        }
1006                        mCancelOnUp = false;
1007                        mIntercepted = false;
1008                    }
1009                }
1010            }
1011            return super.dispatchTouchEvent(event);
1012        }
1013
1014        public ListView getListView() {
1015            return mAlert.getListView();
1016        }
1017
1018        @Override
1019        protected void onCreate(Bundle savedInstanceState) {
1020            super.onCreate(savedInstanceState);
1021            mAlert.installContent();
1022        }
1023
1024        @Override
1025        public boolean onKeyDown(int keyCode, KeyEvent event) {
1026            if (mAlert.onKeyDown(keyCode, event)) {
1027                return true;
1028            }
1029            return super.onKeyDown(keyCode, event);
1030        }
1031
1032        @Override
1033        public boolean onKeyUp(int keyCode, KeyEvent event) {
1034            if (mAlert.onKeyUp(keyCode, event)) {
1035                return true;
1036            }
1037            return super.onKeyUp(keyCode, event);
1038        }
1039    }
1040}
1041