PhoneStatusBar.java revision f59a90c24788d6d67a492aa5a9d8efbf350bbd7e
1/*
2 * Copyright (C) 2010 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.systemui.statusbar.phone;
18
19import android.animation.Animator;
20import android.animation.AnimatorListenerAdapter;
21import android.animation.AnimatorSet;
22import android.animation.ObjectAnimator;
23import android.app.ActivityManager;
24import android.app.ActivityManagerNative;
25import android.app.Notification;
26import android.app.PendingIntent;
27import android.app.StatusBarManager;
28import android.content.BroadcastReceiver;
29import android.content.Context;
30import android.content.Intent;
31import android.content.IntentFilter;
32import android.content.res.Resources;
33import android.graphics.Canvas;
34import android.graphics.ColorFilter;
35import android.graphics.PixelFormat;
36import android.graphics.PorterDuff;
37import android.graphics.Rect;
38import android.graphics.drawable.Drawable;
39import android.graphics.drawable.NinePatchDrawable;
40import android.inputmethodservice.InputMethodService;
41import android.os.IBinder;
42import android.os.Message;
43import android.os.RemoteException;
44import android.os.ServiceManager;
45import android.os.SystemClock;
46import android.os.UserHandle;
47import android.provider.Settings;
48import android.service.dreams.Dream;
49import android.service.dreams.IDreamManager;
50import android.util.DisplayMetrics;
51import android.util.Log;
52import android.util.Slog;
53import android.view.Display;
54import android.view.Gravity;
55import android.view.MotionEvent;
56import android.view.VelocityTracker;
57import android.view.View;
58import android.view.ViewGroup;
59import android.view.ViewGroup.LayoutParams;
60import android.view.WindowManager;
61import android.view.animation.AccelerateInterpolator;
62import android.view.animation.Animation;
63import android.view.animation.AnimationUtils;
64import android.view.animation.DecelerateInterpolator;
65import android.widget.FrameLayout;
66import android.widget.ImageView;
67import android.widget.LinearLayout;
68import android.widget.ScrollView;
69import android.widget.TextView;
70
71import com.android.internal.statusbar.StatusBarIcon;
72import com.android.internal.statusbar.StatusBarNotification;
73import com.android.systemui.R;
74import com.android.systemui.statusbar.BaseStatusBar;
75import com.android.systemui.statusbar.CommandQueue;
76import com.android.systemui.statusbar.GestureRecorder;
77import com.android.systemui.statusbar.NotificationData;
78import com.android.systemui.statusbar.NotificationData.Entry;
79import com.android.systemui.statusbar.SignalClusterView;
80import com.android.systemui.statusbar.StatusBarIconView;
81import com.android.systemui.statusbar.policy.BatteryController;
82import com.android.systemui.statusbar.policy.BluetoothController;
83import com.android.systemui.statusbar.policy.DateView;
84import com.android.systemui.statusbar.policy.IntruderAlertView;
85import com.android.systemui.statusbar.policy.LocationController;
86import com.android.systemui.statusbar.policy.NetworkController;
87import com.android.systemui.statusbar.policy.NotificationRowLayout;
88import com.android.systemui.statusbar.policy.OnSizeChangedListener;
89
90import java.io.FileDescriptor;
91import java.io.PrintWriter;
92import java.util.ArrayList;
93
94public class PhoneStatusBar extends BaseStatusBar {
95    static final String TAG = "PhoneStatusBar";
96    public static final boolean DEBUG = BaseStatusBar.DEBUG;
97    public static final boolean SPEW = DEBUG;
98    public static final boolean DUMPTRUCK = true; // extra dumpsys info
99
100    // additional instrumentation for testing purposes; intended to be left on during development
101    public static final boolean CHATTY = DEBUG;
102
103    public static final String ACTION_STATUSBAR_START
104            = "com.android.internal.policy.statusbar.START";
105
106    private static final int MSG_OPEN_NOTIFICATION_PANEL = 1000;
107    private static final int MSG_CLOSE_PANELS = 1001;
108    private static final int MSG_OPEN_SETTINGS_PANEL = 1002;
109    // 1020-1030 reserved for BaseStatusBar
110
111    // will likely move to a resource or other tunable param at some point
112    private static final int INTRUDER_ALERT_DECAY_MS = 0; // disabled, was 10000;
113
114    private static final boolean CLOSE_PANEL_WHEN_EMPTIED = true;
115
116    private static final int NOTIFICATION_PRIORITY_MULTIPLIER = 10; // see NotificationManagerService
117    private static final int HIDE_ICONS_BELOW_SCORE = Notification.PRIORITY_LOW * NOTIFICATION_PRIORITY_MULTIPLIER;
118
119    // fling gesture tuning parameters, scaled to display density
120    private float mSelfExpandVelocityPx; // classic value: 2000px/s
121    private float mSelfCollapseVelocityPx; // classic value: 2000px/s (will be negated to collapse "up")
122    private float mFlingExpandMinVelocityPx; // classic value: 200px/s
123    private float mFlingCollapseMinVelocityPx; // classic value: 200px/s
124    private float mCollapseMinDisplayFraction; // classic value: 0.08 (25px/min(320px,480px) on G1)
125    private float mExpandMinDisplayFraction; // classic value: 0.5 (drag open halfway to expand)
126    private float mFlingGestureMaxXVelocityPx; // classic value: 150px/s
127
128    private float mExpandAccelPx; // classic value: 2000px/s/s
129    private float mCollapseAccelPx; // classic value: 2000px/s/s (will be negated to collapse "up")
130
131    private float mFlingGestureMaxOutputVelocityPx; // how fast can it really go? (should be a little
132                                                    // faster than mSelfCollapseVelocityPx)
133
134    PhoneStatusBarPolicy mIconPolicy;
135
136    // These are no longer handled by the policy, because we need custom strategies for them
137    BluetoothController mBluetoothController;
138    BatteryController mBatteryController;
139    LocationController mLocationController;
140    NetworkController mNetworkController;
141
142    int mNaturalBarHeight = -1;
143    int mIconSize = -1;
144    int mIconHPadding = -1;
145    Display mDisplay;
146
147    IDreamManager mDreamManager;
148
149    StatusBarWindowView mStatusBarWindow;
150    PhoneStatusBarView mStatusBarView;
151
152    int mPixelFormat;
153    Object mQueueLock = new Object();
154
155    // viewgroup containing the normal contents of the statusbar
156    LinearLayout mStatusBarContents;
157
158    // right-hand icons
159    LinearLayout mSystemIconArea;
160
161    // left-hand icons
162    LinearLayout mStatusIcons;
163    // the icons themselves
164    IconMerger mNotificationIcons;
165    // [+>
166    View mMoreIcon;
167
168    // expanded notifications
169    PanelView mNotificationPanel; // the sliding/resizing panel within the notification window
170    ScrollView mScrollView;
171    View mExpandedContents;
172    final Rect mNotificationPanelBackgroundPadding = new Rect();
173    int mNotificationPanelGravity;
174    int mNotificationPanelMarginBottomPx, mNotificationPanelMarginPx;
175    int mNotificationPanelMinHeight;
176    boolean mNotificationPanelIsFullScreenWidth;
177    TextView mNotificationPanelDebugText;
178
179    // settings
180    SettingsPanelView mSettingsPanel;
181    int mSettingsPanelGravity;
182
183    // top bar
184    View mClearButton;
185    View mSettingsButton;
186
187    // carrier/wifi label
188    private TextView mCarrierLabel;
189    private boolean mCarrierLabelVisible = false;
190    private int mCarrierLabelHeight;
191    private TextView mEmergencyCallLabel;
192    private int mNotificationHeaderHeight;
193
194    private boolean mShowCarrierInPanel = false;
195
196    // position
197    int[] mPositionTmp = new int[2];
198    boolean mExpandedVisible;
199
200    // the date view
201    DateView mDateView;
202
203    // for immersive activities
204    private IntruderAlertView mIntruderAlertView;
205
206    // on-screen navigation buttons
207    private NavigationBarView mNavigationBarView = null;
208
209    // the tracker view
210    int mTrackingPosition; // the position of the top of the tracking view.
211
212    // ticker
213    private Ticker mTicker;
214    private View mTickerView;
215    private boolean mTicking;
216
217    // Tracking finger for opening/closing.
218    int mEdgeBorder; // corresponds to R.dimen.status_bar_edge_ignore
219    boolean mTracking;
220    VelocityTracker mVelocityTracker;
221
222    boolean mAnimating;
223    boolean mClosing; // only valid when mAnimating; indicates the initial acceleration
224    float mAnimY;
225    float mAnimVel;
226    float mAnimAccel;
227    long mAnimLastTimeNanos;
228    boolean mAnimatingReveal = false;
229    int mViewDelta;
230    float mFlingVelocity;
231    int mFlingY;
232    int[] mAbsPos = new int[2];
233    Runnable mPostCollapseCleanup = null;
234
235    private Animator mLightsOutAnimation;
236    private Animator mLightsOnAnimation;
237
238    // for disabling the status bar
239    int mDisabled = 0;
240
241    // tracking calls to View.setSystemUiVisibility()
242    int mSystemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE;
243
244    DisplayMetrics mDisplayMetrics = new DisplayMetrics();
245
246    // XXX: gesture research
247    private GestureRecorder mGestureRec = new GestureRecorder("/sdcard/statusbar_gestures.dat");
248
249    private int mNavigationIconHints = 0;
250    private final Animator.AnimatorListener mMakeIconsInvisible = new AnimatorListenerAdapter() {
251        @Override
252        public void onAnimationEnd(Animator animation) {
253            // double-check to avoid races
254            if (mStatusBarContents.getAlpha() == 0) {
255                Slog.d(TAG, "makeIconsInvisible");
256                mStatusBarContents.setVisibility(View.INVISIBLE);
257            }
258        }
259    };
260
261    @Override
262    public void start() {
263        mDisplay = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE))
264                .getDefaultDisplay();
265
266        mDreamManager = IDreamManager.Stub.asInterface(
267                ServiceManager.checkService(Dream.DREAM_SERVICE));
268
269        super.start(); // calls createAndAddWindows()
270
271        addNavigationBar();
272
273        if (ENABLE_INTRUDERS) addIntruderView();
274
275        // Lastly, call to the icon policy to install/update all the icons.
276        mIconPolicy = new PhoneStatusBarPolicy(mContext);
277    }
278
279    // ================================================================================
280    // Constructing the view
281    // ================================================================================
282    protected PhoneStatusBarView makeStatusBarView() {
283        final Context context = mContext;
284
285        Resources res = context.getResources();
286
287        updateDisplaySize(); // populates mDisplayMetrics
288        loadDimens();
289
290        mIconSize = res.getDimensionPixelSize(com.android.internal.R.dimen.status_bar_icon_size);
291
292        mStatusBarWindow = (StatusBarWindowView) View.inflate(context,
293                R.layout.super_status_bar, null);
294        mStatusBarWindow.mService = this;
295        mStatusBarWindow.setOnTouchListener(new View.OnTouchListener() {
296            @Override
297            public boolean onTouch(View v, MotionEvent event) {
298                if (event.getAction() == MotionEvent.ACTION_DOWN) {
299                    if (mExpandedVisible && !mAnimating) {
300                        animateCollapsePanels();
301                    }
302                }
303                return mStatusBarWindow.onTouchEvent(event);
304            }});
305
306        mStatusBarView = (PhoneStatusBarView) mStatusBarWindow.findViewById(R.id.status_bar);
307        mStatusBarView.setBar(this);
308
309        PanelHolder holder = (PanelHolder) mStatusBarWindow.findViewById(R.id.panel_holder);
310        mStatusBarView.setPanelHolder(holder);
311
312        mNotificationPanel = (PanelView) mStatusBarWindow.findViewById(R.id.notification_panel);
313        mNotificationPanelIsFullScreenWidth =
314            (mNotificationPanel.getLayoutParams().width == ViewGroup.LayoutParams.MATCH_PARENT);
315        mNotificationPanel.setSystemUiVisibility(
316                  View.STATUS_BAR_DISABLE_NOTIFICATION_TICKER | View.STATUS_BAR_DISABLE_NOTIFICATION_ICONS);
317
318        if (!ActivityManager.isHighEndGfx()) {
319            mStatusBarWindow.setBackground(null);
320            mNotificationPanel.setBackground(new FastColorDrawable(context.getResources().getColor(
321                    R.color.notification_panel_solid_background)));
322        }
323        if (ENABLE_INTRUDERS) {
324            mIntruderAlertView = (IntruderAlertView) View.inflate(context, R.layout.intruder_alert, null);
325            mIntruderAlertView.setVisibility(View.GONE);
326            mIntruderAlertView.setBar(this);
327        }
328        if (MULTIUSER_DEBUG) {
329            mNotificationPanelDebugText = (TextView) mNotificationPanel.findViewById(R.id.header_debug_info);
330            mNotificationPanelDebugText.setVisibility(View.VISIBLE);
331        }
332
333        updateShowSearchHoldoff();
334
335        try {
336            boolean showNav = mWindowManagerService.hasNavigationBar();
337            if (DEBUG) Slog.v(TAG, "hasNavigationBar=" + showNav);
338            if (showNav) {
339                mNavigationBarView =
340                    (NavigationBarView) View.inflate(context, R.layout.navigation_bar, null);
341
342                mNavigationBarView.setDisabledFlags(mDisabled);
343                mNavigationBarView.setBar(this);
344            }
345        } catch (RemoteException ex) {
346            // no window manager? good luck with that
347        }
348
349        // figure out which pixel-format to use for the status bar.
350        mPixelFormat = PixelFormat.OPAQUE;
351
352        mSystemIconArea = (LinearLayout) mStatusBarView.findViewById(R.id.system_icon_area);
353        mStatusIcons = (LinearLayout)mStatusBarView.findViewById(R.id.statusIcons);
354        mNotificationIcons = (IconMerger)mStatusBarView.findViewById(R.id.notificationIcons);
355        mNotificationIcons.setOverflowIndicator(mMoreIcon);
356        mStatusBarContents = (LinearLayout)mStatusBarView.findViewById(R.id.status_bar_contents);
357        mTickerView = mStatusBarView.findViewById(R.id.ticker);
358
359        mPile = (NotificationRowLayout)mStatusBarWindow.findViewById(R.id.latestItems);
360        mPile.setLayoutTransitionsEnabled(false);
361        mPile.setLongPressListener(getNotificationLongClicker());
362        mExpandedContents = mPile; // was: expanded.findViewById(R.id.notificationLinearLayout);
363
364        mClearButton = mStatusBarWindow.findViewById(R.id.clear_all_button);
365        mClearButton.setOnClickListener(mClearButtonListener);
366        mClearButton.setAlpha(0f);
367        mClearButton.setVisibility(View.INVISIBLE);
368        mClearButton.setEnabled(false);
369        mDateView = (DateView)mStatusBarWindow.findViewById(R.id.date);
370        mSettingsButton = mStatusBarWindow.findViewById(R.id.settings_button);
371        if (mSettingsButton != null) {
372            mSettingsButton.setOnClickListener(mSettingsButtonListener);
373        }
374
375        mScrollView = (ScrollView)mStatusBarWindow.findViewById(R.id.scroll);
376        mScrollView.setVerticalScrollBarEnabled(false); // less drawing during pulldowns
377
378        mTicker = new MyTicker(context, mStatusBarView);
379
380        TickerView tickerView = (TickerView)mStatusBarView.findViewById(R.id.tickerText);
381        tickerView.mTicker = mTicker;
382
383        mEdgeBorder = res.getDimensionPixelSize(R.dimen.status_bar_edge_ignore);
384
385        // set the inital view visibility
386        setAreThereNotifications();
387
388        // Other icons
389        mLocationController = new LocationController(mContext); // will post a notification
390        mBatteryController = new BatteryController(mContext);
391        mBatteryController.addIconView((ImageView)mStatusBarView.findViewById(R.id.battery));
392        mNetworkController = new NetworkController(mContext);
393        mBluetoothController = new BluetoothController(mContext);
394        final SignalClusterView signalCluster =
395                (SignalClusterView)mStatusBarView.findViewById(R.id.signal_cluster);
396
397
398        mNetworkController.addSignalCluster(signalCluster);
399        signalCluster.setNetworkController(mNetworkController);
400
401        mEmergencyCallLabel = (TextView)mStatusBarWindow.findViewById(R.id.emergency_calls_only);
402        if (mEmergencyCallLabel != null) {
403            mNetworkController.addEmergencyLabelView(mEmergencyCallLabel);
404            mEmergencyCallLabel.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
405                @Override
406                public void onLayoutChange(View v, int left, int top, int right, int bottom,
407                        int oldLeft, int oldTop, int oldRight, int oldBottom) {
408                    updateCarrierLabelVisibility(false);
409                }});
410        }
411
412        mCarrierLabel = (TextView)mStatusBarWindow.findViewById(R.id.carrier_label);
413        mShowCarrierInPanel = (mCarrierLabel != null);
414        Slog.v(TAG, "carrierlabel=" + mCarrierLabel + " show=" + mShowCarrierInPanel);
415        if (mShowCarrierInPanel) {
416            mCarrierLabel.setVisibility(mCarrierLabelVisible ? View.VISIBLE : View.INVISIBLE);
417
418            // for mobile devices, we always show mobile connection info here (SPN/PLMN)
419            // for other devices, we show whatever network is connected
420            if (mNetworkController.hasMobileDataFeature()) {
421                mNetworkController.addMobileLabelView(mCarrierLabel);
422            } else {
423                mNetworkController.addCombinedLabelView(mCarrierLabel);
424            }
425
426            // set up the dynamic hide/show of the label
427            mPile.setOnSizeChangedListener(new OnSizeChangedListener() {
428                @Override
429                public void onSizeChanged(View view, int w, int h, int oldw, int oldh) {
430                    updateCarrierLabelVisibility(false);
431                }
432            });
433        }
434
435        // Quick Settings (WIP)
436        mSettingsPanel = (SettingsPanelView) mStatusBarWindow.findViewById(R.id.settings_panel);
437        mSettingsPanel.setBar(mStatusBarView);
438        mSettingsPanel.setService(this);
439        mSettingsPanel.setup(mNetworkController, mBluetoothController, mBatteryController,
440                mLocationController);
441        mSettingsPanel.setSystemUiVisibility(
442                View.STATUS_BAR_DISABLE_NOTIFICATION_TICKER | View.STATUS_BAR_DISABLE_SYSTEM_INFO);
443
444        if (!ActivityManager.isHighEndGfx()) {
445            mSettingsPanel.setBackground(new FastColorDrawable(context.getResources().getColor(
446                    R.color.notification_panel_solid_background)));
447        }
448
449//        final ImageView wimaxRSSI =
450//                (ImageView)sb.findViewById(R.id.wimax_signal);
451//        if (wimaxRSSI != null) {
452//            mNetworkController.addWimaxIconView(wimaxRSSI);
453//        }
454
455        // receive broadcasts
456        IntentFilter filter = new IntentFilter();
457        filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
458        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
459        filter.addAction(Intent.ACTION_SCREEN_OFF);
460        filter.addAction(Intent.ACTION_SCREEN_ON);
461        context.registerReceiver(mBroadcastReceiver, filter);
462
463        return mStatusBarView;
464    }
465
466    @Override
467    protected View getStatusBarView() {
468        return mStatusBarView;
469    }
470
471    @Override
472    protected WindowManager.LayoutParams getRecentsLayoutParams(LayoutParams layoutParams) {
473        boolean opaque = false;
474        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
475                layoutParams.width,
476                layoutParams.height,
477                WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL,
478                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
479                | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
480                | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
481                (opaque ? PixelFormat.OPAQUE : PixelFormat.TRANSLUCENT));
482        if (ActivityManager.isHighEndGfx()) {
483            lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
484        } else {
485            lp.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
486            lp.dimAmount = 0.75f;
487        }
488        lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
489        lp.setTitle("RecentsPanel");
490        lp.windowAnimations = com.android.internal.R.style.Animation_RecentApplications;
491        lp.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED
492        | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
493        return lp;
494    }
495
496    @Override
497    protected WindowManager.LayoutParams getSearchLayoutParams(LayoutParams layoutParams) {
498        boolean opaque = false;
499        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
500                LayoutParams.MATCH_PARENT,
501                LayoutParams.MATCH_PARENT,
502                WindowManager.LayoutParams.TYPE_NAVIGATION_BAR_PANEL,
503                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
504                | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
505                | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
506                (opaque ? PixelFormat.OPAQUE : PixelFormat.TRANSLUCENT));
507        if (ActivityManager.isHighEndGfx()) {
508            lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
509        }
510        lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
511        lp.setTitle("SearchPanel");
512        // TODO: Define custom animation for Search panel
513        lp.windowAnimations = com.android.internal.R.style.Animation_RecentApplications;
514        lp.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED
515        | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
516        return lp;
517    }
518
519    @Override
520    protected void updateSearchPanel() {
521        super.updateSearchPanel();
522        mSearchPanelView.setStatusBarView(mNavigationBarView);
523        mNavigationBarView.setDelegateView(mSearchPanelView);
524    }
525
526    @Override
527    public void showSearchPanel() {
528        super.showSearchPanel();
529        WindowManager.LayoutParams lp =
530            (android.view.WindowManager.LayoutParams) mNavigationBarView.getLayoutParams();
531        lp.flags &= ~WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
532        mWindowManager.updateViewLayout(mNavigationBarView, lp);
533    }
534
535    @Override
536    public void hideSearchPanel() {
537        super.hideSearchPanel();
538        WindowManager.LayoutParams lp =
539            (android.view.WindowManager.LayoutParams) mNavigationBarView.getLayoutParams();
540        lp.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
541        mWindowManager.updateViewLayout(mNavigationBarView, lp);
542    }
543
544    protected int getStatusBarGravity() {
545        return Gravity.TOP | Gravity.FILL_HORIZONTAL;
546    }
547
548    public int getStatusBarHeight() {
549        if (mNaturalBarHeight < 0) {
550            final Resources res = mContext.getResources();
551            mNaturalBarHeight =
552                    res.getDimensionPixelSize(com.android.internal.R.dimen.status_bar_height);
553        }
554        return mNaturalBarHeight;
555    }
556
557    private View.OnClickListener mRecentsClickListener = new View.OnClickListener() {
558        public void onClick(View v) {
559            toggleRecentApps();
560        }
561    };
562
563    private int mShowSearchHoldoff = 0;
564    private Runnable mShowSearchPanel = new Runnable() {
565        public void run() {
566            showSearchPanel();
567            awakenDreams();
568        }
569    };
570
571    View.OnTouchListener mHomeSearchActionListener = new View.OnTouchListener() {
572        public boolean onTouch(View v, MotionEvent event) {
573            switch(event.getAction()) {
574            case MotionEvent.ACTION_DOWN:
575                if (!shouldDisableNavbarGestures() && !inKeyguardRestrictedInputMode()) {
576                    mHandler.removeCallbacks(mShowSearchPanel);
577                    mHandler.postDelayed(mShowSearchPanel, mShowSearchHoldoff);
578                }
579            break;
580
581            case MotionEvent.ACTION_UP:
582            case MotionEvent.ACTION_CANCEL:
583                mHandler.removeCallbacks(mShowSearchPanel);
584                awakenDreams();
585            break;
586        }
587        return false;
588        }
589    };
590
591    private void awakenDreams() {
592        if (mDreamManager != null) {
593            try {
594                mDreamManager.awaken();
595            } catch (RemoteException e) {
596                // fine, stay asleep then
597            }
598        }
599    }
600
601    private void prepareNavigationBarView() {
602        mNavigationBarView.reorient();
603
604        mNavigationBarView.getRecentsButton().setOnClickListener(mRecentsClickListener);
605        mNavigationBarView.getRecentsButton().setOnTouchListener(getRecentTasksLoader());
606        mNavigationBarView.getHomeButton().setOnTouchListener(mHomeSearchActionListener);
607        updateSearchPanel();
608    }
609
610    // For small-screen devices (read: phones) that lack hardware navigation buttons
611    private void addNavigationBar() {
612        if (DEBUG) Slog.v(TAG, "addNavigationBar: about to add " + mNavigationBarView);
613        if (mNavigationBarView == null) return;
614
615        prepareNavigationBarView();
616
617        mWindowManager.addView(mNavigationBarView, getNavigationBarLayoutParams());
618    }
619
620    private void repositionNavigationBar() {
621        if (mNavigationBarView == null) return;
622
623        prepareNavigationBarView();
624
625        mWindowManager.updateViewLayout(mNavigationBarView, getNavigationBarLayoutParams());
626    }
627
628    private WindowManager.LayoutParams getNavigationBarLayoutParams() {
629        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
630                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,
631                WindowManager.LayoutParams.TYPE_NAVIGATION_BAR,
632                    0
633                    | WindowManager.LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING
634                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
635                    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
636                    | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
637                    | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
638                PixelFormat.OPAQUE);
639        // this will allow the navbar to run in an overlay on devices that support this
640        if (ActivityManager.isHighEndGfx()) {
641            lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
642        }
643
644        lp.setTitle("NavigationBar");
645        lp.windowAnimations = 0;
646        return lp;
647    }
648
649    private void addIntruderView() {
650        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
651                ViewGroup.LayoutParams.MATCH_PARENT,
652                ViewGroup.LayoutParams.WRAP_CONTENT,
653                WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL, // above the status bar!
654                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
655                    | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
656                    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
657                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
658                    | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
659                    | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
660                PixelFormat.TRANSLUCENT);
661        lp.gravity = Gravity.TOP | Gravity.FILL_HORIZONTAL;
662        //lp.y += height * 1.5; // FIXME
663        lp.setTitle("IntruderAlert");
664        lp.packageName = mContext.getPackageName();
665        lp.windowAnimations = R.style.Animation_StatusBar_IntruderAlert;
666
667        mWindowManager.addView(mIntruderAlertView, lp);
668    }
669
670    public void addIcon(String slot, int index, int viewIndex, StatusBarIcon icon) {
671        if (SPEW) Slog.d(TAG, "addIcon slot=" + slot + " index=" + index + " viewIndex=" + viewIndex
672                + " icon=" + icon);
673        StatusBarIconView view = new StatusBarIconView(mContext, slot, null);
674        view.set(icon);
675        mStatusIcons.addView(view, viewIndex, new LinearLayout.LayoutParams(mIconSize, mIconSize));
676    }
677
678    public void updateIcon(String slot, int index, int viewIndex,
679            StatusBarIcon old, StatusBarIcon icon) {
680        if (SPEW) Slog.d(TAG, "updateIcon slot=" + slot + " index=" + index + " viewIndex=" + viewIndex
681                + " old=" + old + " icon=" + icon);
682        StatusBarIconView view = (StatusBarIconView)mStatusIcons.getChildAt(viewIndex);
683        view.set(icon);
684    }
685
686    public void removeIcon(String slot, int index, int viewIndex) {
687        if (SPEW) Slog.d(TAG, "removeIcon slot=" + slot + " index=" + index + " viewIndex=" + viewIndex);
688        mStatusIcons.removeViewAt(viewIndex);
689    }
690
691    public void addNotification(IBinder key, StatusBarNotification notification) {
692        /* if (DEBUG) */ Slog.d(TAG, "addNotification score=" + notification.score);
693        StatusBarIconView iconView = addNotificationViews(key, notification);
694        if (iconView == null) return;
695
696        boolean immersive = false;
697        try {
698            immersive = ActivityManagerNative.getDefault().isTopActivityImmersive();
699            if (DEBUG) {
700                Slog.d(TAG, "Top activity is " + (immersive?"immersive":"not immersive"));
701            }
702        } catch (RemoteException ex) {
703        }
704
705        /*
706         * DISABLED due to missing API
707        if (ENABLE_INTRUDERS && (
708                   // TODO(dsandler): Only if the screen is on
709                notification.notification.intruderView != null)) {
710            Slog.d(TAG, "Presenting high-priority notification");
711            // special new transient ticker mode
712            // 1. Populate mIntruderAlertView
713
714            if (notification.notification.intruderView == null) {
715                Slog.e(TAG, notification.notification.toString() + " wanted to intrude but intruderView was null");
716                return;
717            }
718
719            // bind the click event to the content area
720            PendingIntent contentIntent = notification.notification.contentIntent;
721            final View.OnClickListener listener = (contentIntent != null)
722                    ? new NotificationClicker(contentIntent,
723                            notification.pkg, notification.tag, notification.id)
724                    : null;
725
726            mIntruderAlertView.applyIntruderContent(notification.notification.intruderView, listener);
727
728            mCurrentlyIntrudingNotification = notification;
729
730            // 2. Animate mIntruderAlertView in
731            mHandler.sendEmptyMessage(MSG_SHOW_INTRUDER);
732
733            // 3. Set alarm to age the notification off (TODO)
734            mHandler.removeMessages(MSG_HIDE_INTRUDER);
735            if (INTRUDER_ALERT_DECAY_MS > 0) {
736                mHandler.sendEmptyMessageDelayed(MSG_HIDE_INTRUDER, INTRUDER_ALERT_DECAY_MS);
737            }
738        } else
739         */
740
741        if (notification.notification.fullScreenIntent != null) {
742            // Stop screensaver if the notification has a full-screen intent.
743            // (like an incoming phone call)
744            awakenDreams();
745
746            // not immersive & a full-screen alert should be shown
747            Slog.d(TAG, "Notification has fullScreenIntent; sending fullScreenIntent");
748            try {
749                notification.notification.fullScreenIntent.send();
750            } catch (PendingIntent.CanceledException e) {
751            }
752        } else {
753            // usual case: status bar visible & not immersive
754
755            // show the ticker if there isn't an intruder too
756            if (mCurrentlyIntrudingNotification == null) {
757                tick(null, notification, true);
758            }
759        }
760
761        // Recalculate the position of the sliding windows and the titles.
762        setAreThereNotifications();
763        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
764    }
765
766    public void removeNotification(IBinder key) {
767        StatusBarNotification old = removeNotificationViews(key);
768        if (SPEW) Slog.d(TAG, "removeNotification key=" + key + " old=" + old);
769
770        if (old != null) {
771            // Cancel the ticker if it's still running
772            mTicker.removeEntry(old);
773
774            // Recalculate the position of the sliding windows and the titles.
775            updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
776
777            if (ENABLE_INTRUDERS && old == mCurrentlyIntrudingNotification) {
778                mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
779            }
780
781            if (CLOSE_PANEL_WHEN_EMPTIED && mNotificationData.size() == 0 && !mAnimating) {
782                animateCollapsePanels();
783            }
784        }
785
786        setAreThereNotifications();
787    }
788
789    private void updateShowSearchHoldoff() {
790        mShowSearchHoldoff = mContext.getResources().getInteger(
791            R.integer.config_show_search_delay);
792    }
793
794    private void loadNotificationShade() {
795        if (mPile == null) return;
796
797        int N = mNotificationData.size();
798
799        ArrayList<View> toShow = new ArrayList<View>();
800
801        final boolean provisioned = isDeviceProvisioned();
802        // If the device hasn't been through Setup, we only show system notifications
803        for (int i=0; i<N; i++) {
804            Entry ent = mNotificationData.get(N-i-1);
805            if (!(provisioned || showNotificationEvenIfUnprovisioned(ent.notification))) continue;
806            if (!notificationIsForCurrentUser(ent.notification)) continue;
807            toShow.add(ent.row);
808        }
809
810        ArrayList<View> toRemove = new ArrayList<View>();
811        for (int i=0; i<mPile.getChildCount(); i++) {
812            View child = mPile.getChildAt(i);
813            if (!toShow.contains(child)) {
814                toRemove.add(child);
815            }
816        }
817
818        for (View remove : toRemove) {
819            mPile.removeView(remove);
820        }
821
822        for (int i=0; i<toShow.size(); i++) {
823            View v = toShow.get(i);
824            if (v.getParent() == null) {
825                mPile.addView(v, i);
826            }
827        }
828
829        if (mSettingsButton != null) {
830            mSettingsButton.setEnabled(isDeviceProvisioned());
831        }
832    }
833
834    @Override
835    protected void updateNotificationIcons() {
836        if (mNotificationIcons == null) return;
837
838        loadNotificationShade();
839
840        final LinearLayout.LayoutParams params
841            = new LinearLayout.LayoutParams(mIconSize + 2*mIconHPadding, mNaturalBarHeight);
842
843        int N = mNotificationData.size();
844
845        if (DEBUG) {
846            Slog.d(TAG, "refreshing icons: " + N + " notifications, mNotificationIcons=" + mNotificationIcons);
847        }
848
849        ArrayList<View> toShow = new ArrayList<View>();
850
851        final boolean provisioned = isDeviceProvisioned();
852        // If the device hasn't been through Setup, we only show system notifications
853        for (int i=0; i<N; i++) {
854            Entry ent = mNotificationData.get(N-i-1);
855            if (!((provisioned && ent.notification.score >= HIDE_ICONS_BELOW_SCORE)
856                    || showNotificationEvenIfUnprovisioned(ent.notification))) continue;
857            if (!notificationIsForCurrentUser(ent.notification)) continue;
858            toShow.add(ent.icon);
859        }
860
861        ArrayList<View> toRemove = new ArrayList<View>();
862        for (int i=0; i<mNotificationIcons.getChildCount(); i++) {
863            View child = mNotificationIcons.getChildAt(i);
864            if (!toShow.contains(child)) {
865                toRemove.add(child);
866            }
867        }
868
869        for (View remove : toRemove) {
870            mNotificationIcons.removeView(remove);
871        }
872
873        for (int i=0; i<toShow.size(); i++) {
874            View v = toShow.get(i);
875            if (v.getParent() == null) {
876                mNotificationIcons.addView(v, i, params);
877            }
878        }
879    }
880
881    protected void updateCarrierLabelVisibility(boolean force) {
882        if (!mShowCarrierInPanel) return;
883        // The idea here is to only show the carrier label when there is enough room to see it,
884        // i.e. when there aren't enough notifications to fill the panel.
885        if (DEBUG) {
886            Slog.d(TAG, String.format("pileh=%d scrollh=%d carrierh=%d",
887                    mPile.getHeight(), mScrollView.getHeight(), mCarrierLabelHeight));
888        }
889
890        final boolean emergencyCallsShownElsewhere = mEmergencyCallLabel != null;
891        final boolean makeVisible =
892            !(emergencyCallsShownElsewhere && mNetworkController.isEmergencyOnly())
893            && mPile.getHeight() < (mNotificationPanel.getHeight() - mCarrierLabelHeight - mNotificationHeaderHeight);
894
895        if (force || mCarrierLabelVisible != makeVisible) {
896            mCarrierLabelVisible = makeVisible;
897            if (DEBUG) {
898                Slog.d(TAG, "making carrier label " + (makeVisible?"visible":"invisible"));
899            }
900            mCarrierLabel.animate().cancel();
901            if (makeVisible) {
902                mCarrierLabel.setVisibility(View.VISIBLE);
903            }
904            mCarrierLabel.animate()
905                .alpha(makeVisible ? 1f : 0f)
906                //.setStartDelay(makeVisible ? 500 : 0)
907                //.setDuration(makeVisible ? 750 : 100)
908                .setDuration(150)
909                .setListener(makeVisible ? null : new AnimatorListenerAdapter() {
910                    @Override
911                    public void onAnimationEnd(Animator animation) {
912                        if (!mCarrierLabelVisible) { // race
913                            mCarrierLabel.setVisibility(View.INVISIBLE);
914                            mCarrierLabel.setAlpha(0f);
915                        }
916                    }
917                })
918                .start();
919        }
920    }
921
922    @Override
923    protected void setAreThereNotifications() {
924        final boolean any = mNotificationData.size() > 0;
925
926        final boolean clearable = any && mNotificationData.hasClearableItems();
927
928        if (DEBUG) {
929            Slog.d(TAG, "setAreThereNotifications: N=" + mNotificationData.size()
930                    + " any=" + any + " clearable=" + clearable);
931        }
932
933        if (mClearButton.isShown()) {
934            if (clearable != (mClearButton.getAlpha() == 1.0f)) {
935                ObjectAnimator clearAnimation = ObjectAnimator.ofFloat(
936                        mClearButton, "alpha", clearable ? 1.0f : 0.0f).setDuration(250);
937                clearAnimation.addListener(new AnimatorListenerAdapter() {
938                    @Override
939                    public void onAnimationEnd(Animator animation) {
940                        if (mClearButton.getAlpha() <= 0.0f) {
941                            mClearButton.setVisibility(View.INVISIBLE);
942                        }
943                    }
944
945                    @Override
946                    public void onAnimationStart(Animator animation) {
947                        if (mClearButton.getAlpha() <= 0.0f) {
948                            mClearButton.setVisibility(View.VISIBLE);
949                        }
950                    }
951                });
952                clearAnimation.start();
953            }
954        } else {
955            mClearButton.setAlpha(clearable ? 1.0f : 0.0f);
956            mClearButton.setVisibility(clearable ? View.VISIBLE : View.INVISIBLE);
957        }
958        mClearButton.setEnabled(clearable);
959
960        final View nlo = mStatusBarView.findViewById(R.id.notification_lights_out);
961        final boolean showDot = (any&&!areLightsOn());
962        if (showDot != (nlo.getAlpha() == 1.0f)) {
963            if (showDot) {
964                nlo.setAlpha(0f);
965                nlo.setVisibility(View.VISIBLE);
966            }
967            nlo.animate()
968                .alpha(showDot?1:0)
969                .setDuration(showDot?750:250)
970                .setInterpolator(new AccelerateInterpolator(2.0f))
971                .setListener(showDot ? null : new AnimatorListenerAdapter() {
972                    @Override
973                    public void onAnimationEnd(Animator _a) {
974                        nlo.setVisibility(View.GONE);
975                    }
976                })
977                .start();
978        }
979
980        updateCarrierLabelVisibility(false);
981    }
982
983    public void showClock(boolean show) {
984        if (mStatusBarView == null) return;
985        View clock = mStatusBarView.findViewById(R.id.clock);
986        if (clock != null) {
987            clock.setVisibility(show ? View.VISIBLE : View.GONE);
988        }
989    }
990
991    /**
992     * State is one or more of the DISABLE constants from StatusBarManager.
993     */
994    public void disable(int state) {
995        final int old = mDisabled;
996        final int diff = state ^ old;
997        mDisabled = state;
998
999        if (DEBUG) {
1000            Slog.d(TAG, String.format("disable: 0x%08x -> 0x%08x (diff: 0x%08x)",
1001                old, state, diff));
1002        }
1003
1004        StringBuilder flagdbg = new StringBuilder();
1005        flagdbg.append("disable: < ");
1006        flagdbg.append(((state & StatusBarManager.DISABLE_EXPAND) != 0) ? "EXPAND" : "expand");
1007        flagdbg.append(((diff  & StatusBarManager.DISABLE_EXPAND) != 0) ? "* " : " ");
1008        flagdbg.append(((state & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) ? "ICONS" : "icons");
1009        flagdbg.append(((diff  & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) ? "* " : " ");
1010        flagdbg.append(((state & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) ? "ALERTS" : "alerts");
1011        flagdbg.append(((diff  & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) ? "* " : " ");
1012        flagdbg.append(((state & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) ? "TICKER" : "ticker");
1013        flagdbg.append(((diff  & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) ? "* " : " ");
1014        flagdbg.append(((state & StatusBarManager.DISABLE_SYSTEM_INFO) != 0) ? "SYSTEM_INFO" : "system_info");
1015        flagdbg.append(((diff  & StatusBarManager.DISABLE_SYSTEM_INFO) != 0) ? "* " : " ");
1016        flagdbg.append(((state & StatusBarManager.DISABLE_BACK) != 0) ? "BACK" : "back");
1017        flagdbg.append(((diff  & StatusBarManager.DISABLE_BACK) != 0) ? "* " : " ");
1018        flagdbg.append(((state & StatusBarManager.DISABLE_HOME) != 0) ? "HOME" : "home");
1019        flagdbg.append(((diff  & StatusBarManager.DISABLE_HOME) != 0) ? "* " : " ");
1020        flagdbg.append(((state & StatusBarManager.DISABLE_RECENT) != 0) ? "RECENT" : "recent");
1021        flagdbg.append(((diff  & StatusBarManager.DISABLE_RECENT) != 0) ? "* " : " ");
1022        flagdbg.append(((state & StatusBarManager.DISABLE_CLOCK) != 0) ? "CLOCK" : "clock");
1023        flagdbg.append(((diff  & StatusBarManager.DISABLE_CLOCK) != 0) ? "* " : " ");
1024        flagdbg.append(">");
1025        Slog.d(TAG, flagdbg.toString());
1026
1027        if ((diff & StatusBarManager.DISABLE_SYSTEM_INFO) != 0) {
1028            mSystemIconArea.animate().cancel();
1029            if ((state & StatusBarManager.DISABLE_SYSTEM_INFO) != 0) {
1030                mSystemIconArea.animate()
1031                    .alpha(0f)
1032                    .translationY(mNaturalBarHeight*0.5f)
1033                    .setDuration(175)
1034                    .setInterpolator(new DecelerateInterpolator(1.5f))
1035                    .setListener(mMakeIconsInvisible)
1036                    .start();
1037            } else {
1038                mSystemIconArea.setVisibility(View.VISIBLE);
1039                mSystemIconArea.animate()
1040                    .alpha(1f)
1041                    .translationY(0)
1042                    .setStartDelay(0)
1043                    .setInterpolator(new DecelerateInterpolator(1.5f))
1044                    .setDuration(175)
1045                    .start();
1046            }
1047        }
1048
1049        if ((diff & StatusBarManager.DISABLE_CLOCK) != 0) {
1050            boolean show = (state & StatusBarManager.DISABLE_CLOCK) == 0;
1051            showClock(show);
1052        }
1053        if ((diff & StatusBarManager.DISABLE_EXPAND) != 0) {
1054            if ((state & StatusBarManager.DISABLE_EXPAND) != 0) {
1055                animateCollapsePanels();
1056            }
1057        }
1058
1059        if ((diff & (StatusBarManager.DISABLE_HOME
1060                        | StatusBarManager.DISABLE_RECENT
1061                        | StatusBarManager.DISABLE_BACK)) != 0) {
1062            // the nav bar will take care of these
1063            if (mNavigationBarView != null) mNavigationBarView.setDisabledFlags(state);
1064
1065            if ((state & StatusBarManager.DISABLE_RECENT) != 0) {
1066                // close recents if it's visible
1067                mHandler.removeMessages(MSG_CLOSE_RECENTS_PANEL);
1068                mHandler.sendEmptyMessage(MSG_CLOSE_RECENTS_PANEL);
1069            }
1070        }
1071
1072        if ((diff & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
1073            if ((state & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
1074                if (mTicking) {
1075                    haltTicker();
1076                }
1077
1078                mNotificationIcons.animate()
1079                    .alpha(0f)
1080                    .translationY(mNaturalBarHeight*0.5f)
1081                    .setDuration(175)
1082                    .setInterpolator(new DecelerateInterpolator(1.5f))
1083                    .setListener(mMakeIconsInvisible)
1084                    .start();
1085            } else {
1086                mNotificationIcons.setVisibility(View.VISIBLE);
1087                mNotificationIcons.animate()
1088                    .alpha(1f)
1089                    .translationY(0)
1090                    .setStartDelay(0)
1091                    .setInterpolator(new DecelerateInterpolator(1.5f))
1092                    .setDuration(175)
1093                    .start();
1094            }
1095        } else if ((diff & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
1096            if (mTicking && (state & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
1097                haltTicker();
1098            }
1099        }
1100    }
1101
1102    @Override
1103    protected BaseStatusBar.H createHandler() {
1104        return new PhoneStatusBar.H();
1105    }
1106
1107    /**
1108     * All changes to the status bar and notifications funnel through here and are batched.
1109     */
1110    private class H extends BaseStatusBar.H {
1111        public void handleMessage(Message m) {
1112            super.handleMessage(m);
1113            switch (m.what) {
1114                case MSG_OPEN_NOTIFICATION_PANEL:
1115                    animateExpandNotificationsPanel();
1116                    break;
1117                case MSG_OPEN_SETTINGS_PANEL:
1118                    animateExpandSettingsPanel();
1119                    break;
1120                case MSG_CLOSE_PANELS:
1121                    animateCollapsePanels();
1122                    break;
1123                case MSG_SHOW_INTRUDER:
1124                    setIntruderAlertVisibility(true);
1125                    break;
1126                case MSG_HIDE_INTRUDER:
1127                    setIntruderAlertVisibility(false);
1128                    mCurrentlyIntrudingNotification = null;
1129                    break;
1130            }
1131        }
1132    }
1133
1134    View.OnFocusChangeListener mFocusChangeListener = new View.OnFocusChangeListener() {
1135        public void onFocusChange(View v, boolean hasFocus) {
1136            // Because 'v' is a ViewGroup, all its children will be (un)selected
1137            // too, which allows marqueeing to work.
1138            v.setSelected(hasFocus);
1139        }
1140    };
1141
1142    void makeExpandedVisible(boolean revealAfterDraw) {
1143        if (SPEW) Slog.d(TAG, "Make expanded visible: expanded visible=" + mExpandedVisible);
1144        if (mExpandedVisible) {
1145            return;
1146        }
1147
1148        mExpandedVisible = true;
1149        mPile.setLayoutTransitionsEnabled(true);
1150        if (mNavigationBarView != null)
1151            mNavigationBarView.setSlippery(true);
1152
1153        updateCarrierLabelVisibility(true);
1154
1155        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
1156
1157        // Expand the window to encompass the full screen in anticipation of the drag.
1158        // This is only possible to do atomically because the status bar is at the top of the screen!
1159        WindowManager.LayoutParams lp = (WindowManager.LayoutParams) mStatusBarWindow.getLayoutParams();
1160        lp.flags &= ~WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
1161        lp.flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
1162        lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
1163        mWindowManager.updateViewLayout(mStatusBarWindow, lp);
1164
1165        // Updating the window layout will force an expensive traversal/redraw.
1166        // Kick off the reveal animation after this is complete to avoid animation latency.
1167        if (revealAfterDraw) {
1168//            mHandler.post(mStartRevealAnimation);
1169        }
1170
1171        visibilityChanged(true);
1172    }
1173
1174    public void animateCollapsePanels() {
1175        animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
1176    }
1177
1178    public void animateCollapsePanels(int flags) {
1179        if (SPEW) {
1180            Slog.d(TAG, "animateCollapse():"
1181                    + " mExpandedVisible=" + mExpandedVisible
1182                    + " mAnimating=" + mAnimating
1183                    + " mAnimatingReveal=" + mAnimatingReveal
1184                    + " mAnimY=" + mAnimY
1185                    + " mAnimVel=" + mAnimVel
1186                    + " flags=" + flags);
1187        }
1188
1189        if ((flags & CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL) == 0) {
1190            mHandler.removeMessages(MSG_CLOSE_RECENTS_PANEL);
1191            mHandler.sendEmptyMessage(MSG_CLOSE_RECENTS_PANEL);
1192        }
1193
1194        if ((flags & CommandQueue.FLAG_EXCLUDE_SEARCH_PANEL) == 0) {
1195            mHandler.removeMessages(MSG_CLOSE_SEARCH_PANEL);
1196            mHandler.sendEmptyMessage(MSG_CLOSE_SEARCH_PANEL);
1197        }
1198
1199        mStatusBarView.collapseAllPanels(true);
1200    }
1201
1202    @Override
1203    public void animateExpandNotificationsPanel() {
1204        if (SPEW) Slog.d(TAG, "animateExpand: mExpandedVisible=" + mExpandedVisible);
1205        if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
1206            return ;
1207        }
1208
1209        mNotificationPanel.expand();
1210
1211        if (false) postStartTracing();
1212    }
1213
1214    @Override
1215    public void animateExpandSettingsPanel() {
1216        if (SPEW) Slog.d(TAG, "animateExpand: mExpandedVisible=" + mExpandedVisible);
1217        if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
1218            return;
1219        }
1220
1221        mSettingsPanel.expand();
1222
1223        if (false) postStartTracing();
1224    }
1225
1226    public void animateCollapseQuickSettings() {
1227        mStatusBarView.collapseAllPanels(true);
1228    }
1229
1230    void makeExpandedInvisible() {
1231        if (SPEW) Slog.d(TAG, "makeExpandedInvisible: mExpandedVisible=" + mExpandedVisible
1232                + " mExpandedVisible=" + mExpandedVisible);
1233
1234        if (!mExpandedVisible) {
1235            return;
1236        }
1237
1238        // Ensure the panel is fully collapsed (just in case; bug 6765842)
1239 // @@@        mStatusBarView.collapseAllPanels(/*animate=*/ false);
1240
1241        mExpandedVisible = false;
1242        mPile.setLayoutTransitionsEnabled(false);
1243        if (mNavigationBarView != null)
1244            mNavigationBarView.setSlippery(false);
1245        visibilityChanged(false);
1246
1247        // Shrink the window to the size of the status bar only
1248        WindowManager.LayoutParams lp = (WindowManager.LayoutParams) mStatusBarWindow.getLayoutParams();
1249        lp.height = getStatusBarHeight();
1250        lp.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
1251        lp.flags &= ~WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
1252        mWindowManager.updateViewLayout(mStatusBarWindow, lp);
1253
1254        if ((mDisabled & StatusBarManager.DISABLE_NOTIFICATION_ICONS) == 0) {
1255            setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
1256        }
1257
1258        // Close any "App info" popups that might have snuck on-screen
1259        dismissPopups();
1260
1261        if (mPostCollapseCleanup != null) {
1262            mPostCollapseCleanup.run();
1263            mPostCollapseCleanup = null;
1264        }
1265    }
1266
1267    /**
1268     * Enables or disables layers on the children of the notifications pile.
1269     *
1270     * When layers are enabled, this method attempts to enable layers for the minimal
1271     * number of children. Only children visible when the notification area is fully
1272     * expanded will receive a layer. The technique used in this method might cause
1273     * more children than necessary to get a layer (at most one extra child with the
1274     * current UI.)
1275     *
1276     * @param layerType {@link View#LAYER_TYPE_NONE} or {@link View#LAYER_TYPE_HARDWARE}
1277     */
1278    private void setPileLayers(int layerType) {
1279        final int count = mPile.getChildCount();
1280
1281        switch (layerType) {
1282            case View.LAYER_TYPE_NONE:
1283                for (int i = 0; i < count; i++) {
1284                    mPile.getChildAt(i).setLayerType(layerType, null);
1285                }
1286                break;
1287            case View.LAYER_TYPE_HARDWARE:
1288                final int[] location = new int[2];
1289                mNotificationPanel.getLocationInWindow(location);
1290
1291                final int left = location[0];
1292                final int top = location[1];
1293                final int right = left + mNotificationPanel.getWidth();
1294                final int bottom = top + getExpandedViewMaxHeight();
1295
1296                final Rect childBounds = new Rect();
1297
1298                for (int i = 0; i < count; i++) {
1299                    final View view = mPile.getChildAt(i);
1300                    view.getLocationInWindow(location);
1301
1302                    childBounds.set(location[0], location[1],
1303                            location[0] + view.getWidth(), location[1] + view.getHeight());
1304
1305                    if (childBounds.intersects(left, top, right, bottom)) {
1306                        view.setLayerType(layerType, null);
1307                    }
1308                }
1309
1310                break;
1311        }
1312    }
1313
1314    boolean interceptTouchEvent(MotionEvent event) {
1315        if (SPEW) {
1316            Slog.d(TAG, "Touch: rawY=" + event.getRawY() + " event=" + event + " mDisabled="
1317                + mDisabled + " mTracking=" + mTracking);
1318        } else if (CHATTY) {
1319            if (event.getAction() != MotionEvent.ACTION_MOVE) {
1320                Slog.d(TAG, String.format(
1321                            "panel: %s at (%f, %f) mDisabled=0x%08x",
1322                            MotionEvent.actionToString(event.getAction()),
1323                            event.getRawX(), event.getRawY(), mDisabled));
1324            }
1325        }
1326
1327        mGestureRec.add(event);
1328
1329        return false;
1330    }
1331
1332    public GestureRecorder getGestureRecorder() {
1333        return mGestureRec;
1334    }
1335
1336    @Override // CommandQueue
1337    public void setNavigationIconHints(int hints) {
1338        if (hints == mNavigationIconHints) return;
1339
1340        mNavigationIconHints = hints;
1341
1342        if (mNavigationBarView != null) {
1343            mNavigationBarView.setNavigationIconHints(hints);
1344        }
1345    }
1346
1347    @Override // CommandQueue
1348    public void setSystemUiVisibility(int vis, int mask) {
1349        final int oldVal = mSystemUiVisibility;
1350        final int newVal = (oldVal&~mask) | (vis&mask);
1351        final int diff = newVal ^ oldVal;
1352
1353        if (diff != 0) {
1354            mSystemUiVisibility = newVal;
1355
1356            if (0 != (diff & View.SYSTEM_UI_FLAG_LOW_PROFILE)) {
1357                final boolean lightsOut = (0 != (vis & View.SYSTEM_UI_FLAG_LOW_PROFILE));
1358                if (lightsOut) {
1359                    animateCollapsePanels();
1360                    if (mTicking) {
1361                        haltTicker();
1362                    }
1363                }
1364
1365                if (mNavigationBarView != null) {
1366                    mNavigationBarView.setLowProfile(lightsOut);
1367                }
1368
1369                setStatusBarLowProfile(lightsOut);
1370            }
1371
1372            notifyUiVisibilityChanged();
1373        }
1374    }
1375
1376    private void setStatusBarLowProfile(boolean lightsOut) {
1377        if (mLightsOutAnimation == null) {
1378            mLightsOutAnimation = ObjectAnimator.ofFloat(mStatusBarContents, View.ALPHA, 0);
1379            mLightsOutAnimation.setDuration(750);
1380
1381            mLightsOnAnimation = new AnimatorSet();
1382            mLightsOnAnimation = ObjectAnimator.ofFloat(mStatusBarContents, View.ALPHA, 1);
1383            mLightsOnAnimation.setDuration(250);
1384        }
1385
1386        mLightsOutAnimation.cancel();
1387        mLightsOnAnimation.cancel();
1388
1389        final Animator a = lightsOut ? mLightsOutAnimation : mLightsOnAnimation;
1390        a.start();
1391
1392        setAreThereNotifications();
1393    }
1394
1395    private boolean areLightsOn() {
1396        return 0 == (mSystemUiVisibility & View.SYSTEM_UI_FLAG_LOW_PROFILE);
1397    }
1398
1399    public void setLightsOn(boolean on) {
1400        Log.v(TAG, "setLightsOn(" + on + ")");
1401        if (on) {
1402            setSystemUiVisibility(0, View.SYSTEM_UI_FLAG_LOW_PROFILE);
1403        } else {
1404            setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE, View.SYSTEM_UI_FLAG_LOW_PROFILE);
1405        }
1406    }
1407
1408    private void notifyUiVisibilityChanged() {
1409        try {
1410            mWindowManagerService.statusBarVisibilityChanged(mSystemUiVisibility);
1411        } catch (RemoteException ex) {
1412        }
1413    }
1414
1415    public void topAppWindowChanged(boolean showMenu) {
1416        if (DEBUG) {
1417            Slog.d(TAG, (showMenu?"showing":"hiding") + " the MENU button");
1418        }
1419        if (mNavigationBarView != null) {
1420            mNavigationBarView.setMenuVisibility(showMenu);
1421        }
1422
1423        // See above re: lights-out policy for legacy apps.
1424        if (showMenu) setLightsOn(true);
1425    }
1426
1427    @Override
1428    public void setImeWindowStatus(IBinder token, int vis, int backDisposition) {
1429        boolean altBack = (backDisposition == InputMethodService.BACK_DISPOSITION_WILL_DISMISS)
1430            || ((vis & InputMethodService.IME_VISIBLE) != 0);
1431
1432        mCommandQueue.setNavigationIconHints(
1433                altBack ? (mNavigationIconHints | StatusBarManager.NAVIGATION_HINT_BACK_ALT)
1434                        : (mNavigationIconHints & ~StatusBarManager.NAVIGATION_HINT_BACK_ALT));
1435        mSettingsPanel.setImeWindowStatus(vis > 0);
1436    }
1437
1438    @Override
1439    public void setHardKeyboardStatus(boolean available, boolean enabled) {}
1440
1441    @Override
1442    protected void tick(IBinder key, StatusBarNotification n, boolean firstTime) {
1443        // no ticking in lights-out mode
1444        if (!areLightsOn()) return;
1445
1446        // no ticking in Setup
1447        if (!isDeviceProvisioned()) return;
1448
1449        // not for you
1450        if (!notificationIsForCurrentUser(n)) return;
1451
1452        // Show the ticker if one is requested. Also don't do this
1453        // until status bar window is attached to the window manager,
1454        // because...  well, what's the point otherwise?  And trying to
1455        // run a ticker without being attached will crash!
1456        if (n.notification.tickerText != null && mStatusBarWindow.getWindowToken() != null) {
1457            if (0 == (mDisabled & (StatusBarManager.DISABLE_NOTIFICATION_ICONS
1458                            | StatusBarManager.DISABLE_NOTIFICATION_TICKER))) {
1459                mTicker.addEntry(n);
1460            }
1461        }
1462    }
1463
1464    private class MyTicker extends Ticker {
1465        MyTicker(Context context, View sb) {
1466            super(context, sb);
1467        }
1468
1469        @Override
1470        public void tickerStarting() {
1471            mTicking = true;
1472            mStatusBarContents.setVisibility(View.GONE);
1473            mTickerView.setVisibility(View.VISIBLE);
1474            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_up_in, null));
1475            mStatusBarContents.startAnimation(loadAnim(com.android.internal.R.anim.push_up_out, null));
1476        }
1477
1478        @Override
1479        public void tickerDone() {
1480            mStatusBarContents.setVisibility(View.VISIBLE);
1481            mTickerView.setVisibility(View.GONE);
1482            mStatusBarContents.startAnimation(loadAnim(com.android.internal.R.anim.push_down_in, null));
1483            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_down_out,
1484                        mTickingDoneListener));
1485        }
1486
1487        public void tickerHalting() {
1488            mStatusBarContents.setVisibility(View.VISIBLE);
1489            mTickerView.setVisibility(View.GONE);
1490            mStatusBarContents.startAnimation(loadAnim(com.android.internal.R.anim.fade_in, null));
1491            // we do not animate the ticker away at this point, just get rid of it (b/6992707)
1492        }
1493    }
1494
1495    Animation.AnimationListener mTickingDoneListener = new Animation.AnimationListener() {;
1496        public void onAnimationEnd(Animation animation) {
1497            mTicking = false;
1498        }
1499        public void onAnimationRepeat(Animation animation) {
1500        }
1501        public void onAnimationStart(Animation animation) {
1502        }
1503    };
1504
1505    private Animation loadAnim(int id, Animation.AnimationListener listener) {
1506        Animation anim = AnimationUtils.loadAnimation(mContext, id);
1507        if (listener != null) {
1508            anim.setAnimationListener(listener);
1509        }
1510        return anim;
1511    }
1512
1513    public static String viewInfo(View v) {
1514        return "[(" + v.getLeft() + "," + v.getTop() + ")(" + v.getRight() + "," + v.getBottom()
1515                + ") " + v.getWidth() + "x" + v.getHeight() + "]";
1516    }
1517
1518    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1519        synchronized (mQueueLock) {
1520            pw.println("Current Status Bar state:");
1521            pw.println("  mExpandedVisible=" + mExpandedVisible
1522                    + ", mTrackingPosition=" + mTrackingPosition);
1523            pw.println("  mTicking=" + mTicking);
1524            pw.println("  mTracking=" + mTracking);
1525            pw.println("  mNotificationPanel=" +
1526                    ((mNotificationPanel == null)
1527                            ? "null"
1528                            : (mNotificationPanel + " params=" + mNotificationPanel.getLayoutParams().debug(""))));
1529            pw.println("  mAnimating=" + mAnimating
1530                    + ", mAnimY=" + mAnimY + ", mAnimVel=" + mAnimVel
1531                    + ", mAnimAccel=" + mAnimAccel);
1532            pw.println("  mAnimLastTimeNanos=" + mAnimLastTimeNanos);
1533            pw.println("  mAnimatingReveal=" + mAnimatingReveal
1534                    + " mViewDelta=" + mViewDelta);
1535            pw.println("  mDisplayMetrics=" + mDisplayMetrics);
1536            pw.println("  mPile: " + viewInfo(mPile));
1537            pw.println("  mTickerView: " + viewInfo(mTickerView));
1538            pw.println("  mScrollView: " + viewInfo(mScrollView)
1539                    + " scroll " + mScrollView.getScrollX() + "," + mScrollView.getScrollY());
1540        }
1541
1542        pw.print("  mNavigationBarView=");
1543        if (mNavigationBarView == null) {
1544            pw.println("null");
1545        } else {
1546            mNavigationBarView.dump(fd, pw, args);
1547        }
1548
1549        if (DUMPTRUCK) {
1550            synchronized (mNotificationData) {
1551                int N = mNotificationData.size();
1552                pw.println("  notification icons: " + N);
1553                for (int i=0; i<N; i++) {
1554                    NotificationData.Entry e = mNotificationData.get(i);
1555                    pw.println("    [" + i + "] key=" + e.key + " icon=" + e.icon);
1556                    StatusBarNotification n = e.notification;
1557                    pw.println("         pkg=" + n.pkg + " id=" + n.id + " score=" + n.score);
1558                    pw.println("         notification=" + n.notification);
1559                    pw.println("         tickerText=\"" + n.notification.tickerText + "\"");
1560                }
1561            }
1562
1563            int N = mStatusIcons.getChildCount();
1564            pw.println("  system icons: " + N);
1565            for (int i=0; i<N; i++) {
1566                StatusBarIconView ic = (StatusBarIconView) mStatusIcons.getChildAt(i);
1567                pw.println("    [" + i + "] icon=" + ic);
1568            }
1569
1570            if (false) {
1571                pw.println("see the logcat for a dump of the views we have created.");
1572                // must happen on ui thread
1573                mHandler.post(new Runnable() {
1574                        public void run() {
1575                            mStatusBarView.getLocationOnScreen(mAbsPos);
1576                            Slog.d(TAG, "mStatusBarView: ----- (" + mAbsPos[0] + "," + mAbsPos[1]
1577                                    + ") " + mStatusBarView.getWidth() + "x"
1578                                    + getStatusBarHeight());
1579                            mStatusBarView.debug();
1580                        }
1581                    });
1582            }
1583        }
1584
1585        pw.print("  status bar gestures: ");
1586        mGestureRec.dump(fd, pw, args);
1587
1588        mNetworkController.dump(fd, pw, args);
1589    }
1590
1591    @Override
1592    public void createAndAddWindows() {
1593        addStatusBarWindow();
1594    }
1595
1596    private void addStatusBarWindow() {
1597        // Put up the view
1598        final int height = getStatusBarHeight();
1599
1600        // Now that the status bar window encompasses the sliding panel and its
1601        // translucent backdrop, the entire thing is made TRANSLUCENT and is
1602        // hardware-accelerated.
1603        final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
1604                ViewGroup.LayoutParams.MATCH_PARENT,
1605                height,
1606                WindowManager.LayoutParams.TYPE_STATUS_BAR,
1607                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
1608                    | WindowManager.LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING
1609                    | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
1610                PixelFormat.TRANSLUCENT);
1611
1612        lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
1613
1614        lp.gravity = getStatusBarGravity();
1615        lp.setTitle("StatusBar");
1616        lp.packageName = mContext.getPackageName();
1617
1618        makeStatusBarView();
1619        mWindowManager.addView(mStatusBarWindow, lp);
1620    }
1621
1622    void setNotificationIconVisibility(boolean visible, int anim) {
1623        int old = mNotificationIcons.getVisibility();
1624        int v = visible ? View.VISIBLE : View.INVISIBLE;
1625        if (old != v) {
1626            mNotificationIcons.setVisibility(v);
1627            mNotificationIcons.startAnimation(loadAnim(anim, null));
1628        }
1629    }
1630
1631    void updateExpandedInvisiblePosition() {
1632        mTrackingPosition = -mDisplayMetrics.heightPixels;
1633    }
1634
1635    static final float saturate(float a) {
1636        return a < 0f ? 0f : (a > 1f ? 1f : a);
1637    }
1638
1639    @Override
1640    protected int getExpandedViewMaxHeight() {
1641        return mDisplayMetrics.heightPixels - mNotificationPanelMarginBottomPx;
1642    }
1643
1644    @Override
1645    public void updateExpandedViewPos(int thingy) {
1646        // TODO
1647        if (DEBUG) Slog.v(TAG, "updateExpandedViewPos");
1648        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mNotificationPanel.getLayoutParams();
1649        lp.gravity = mNotificationPanelGravity;
1650        lp.leftMargin = mNotificationPanelMarginPx;
1651        mNotificationPanel.setLayoutParams(lp);
1652        lp = (FrameLayout.LayoutParams) mSettingsPanel.getLayoutParams();
1653        lp.gravity = mSettingsPanelGravity;
1654        lp.rightMargin = mNotificationPanelMarginPx;
1655        mSettingsPanel.setLayoutParams(lp);
1656
1657        updateCarrierLabelVisibility(false);
1658    }
1659
1660    // called by makeStatusbar and also by PhoneStatusBarView
1661    void updateDisplaySize() {
1662        mDisplay.getMetrics(mDisplayMetrics);
1663        mGestureRec.tag("display",
1664                String.format("%dx%d", mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels));
1665    }
1666
1667    private View.OnClickListener mClearButtonListener = new View.OnClickListener() {
1668        public void onClick(View v) {
1669            synchronized (mNotificationData) {
1670                // animate-swipe all dismissable notifications, then animate the shade closed
1671                int numChildren = mPile.getChildCount();
1672
1673                int scrollTop = mScrollView.getScrollY();
1674                int scrollBottom = scrollTop + mScrollView.getHeight();
1675                final ArrayList<View> snapshot = new ArrayList<View>(numChildren);
1676                for (int i=0; i<numChildren; i++) {
1677                    final View child = mPile.getChildAt(i);
1678                    if (mPile.canChildBeDismissed(child) && child.getBottom() > scrollTop &&
1679                            child.getTop() < scrollBottom) {
1680                        snapshot.add(child);
1681                    }
1682                }
1683                if (snapshot.isEmpty()) {
1684                    animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
1685                    return;
1686                }
1687                new Thread(new Runnable() {
1688                    @Override
1689                    public void run() {
1690                        // Decrease the delay for every row we animate to give the sense of
1691                        // accelerating the swipes
1692                        final int ROW_DELAY_DECREMENT = 10;
1693                        int currentDelay = 140;
1694                        int totalDelay = 0;
1695
1696                        // Set the shade-animating state to avoid doing other work during
1697                        // all of these animations. In particular, avoid layout and
1698                        // redrawing when collapsing the shade.
1699                        mPile.setViewRemoval(false);
1700
1701                        mPostCollapseCleanup = new Runnable() {
1702                            @Override
1703                            public void run() {
1704                                if (DEBUG) {
1705                                    Slog.v(TAG, "running post-collapse cleanup");
1706                                }
1707                                try {
1708                                    mPile.setViewRemoval(true);
1709                                    mBarService.onClearAllNotifications();
1710                                } catch (Exception ex) { }
1711                            }
1712                        };
1713
1714                        View sampleView = snapshot.get(0);
1715                        int width = sampleView.getWidth();
1716                        final int velocity = width * 8; // 1000/8 = 125 ms duration
1717                        for (final View _v : snapshot) {
1718                            mHandler.postDelayed(new Runnable() {
1719                                @Override
1720                                public void run() {
1721                                    mPile.dismissRowAnimated(_v, velocity);
1722                                }
1723                            }, totalDelay);
1724                            currentDelay = Math.max(50, currentDelay - ROW_DELAY_DECREMENT);
1725                            totalDelay += currentDelay;
1726                        }
1727                        // Delay the collapse animation until after all swipe animations have
1728                        // finished. Provide some buffer because there may be some extra delay
1729                        // before actually starting each swipe animation. Ideally, we'd
1730                        // synchronize the end of those animations with the start of the collaps
1731                        // exactly.
1732                        mHandler.postDelayed(new Runnable() {
1733                            @Override
1734                            public void run() {
1735                                animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
1736                            }
1737                        }, totalDelay + 225);
1738                    }
1739                }).start();
1740            }
1741        }
1742    };
1743
1744    private View.OnClickListener mSettingsButtonListener = new View.OnClickListener() {
1745        public void onClick(View v) {
1746            // We take this as a good indicator that Setup is running and we shouldn't
1747            // allow you to go somewhere else
1748            if (!isDeviceProvisioned()) return;
1749            try {
1750                // Dismiss the lock screen when Settings starts.
1751                ActivityManagerNative.getDefault().dismissKeyguardOnNextActivity();
1752            } catch (RemoteException e) {
1753            }
1754            v.getContext().startActivityAsUser(new Intent(Settings.ACTION_SETTINGS)
1755                    .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
1756                    new UserHandle(UserHandle.USER_CURRENT));
1757            animateCollapsePanels();
1758        }
1759    };
1760
1761    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1762        public void onReceive(Context context, Intent intent) {
1763            Slog.v(TAG, "onReceive: " + intent);
1764            String action = intent.getAction();
1765            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
1766                int flags = CommandQueue.FLAG_EXCLUDE_NONE;
1767                if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
1768                    String reason = intent.getStringExtra("reason");
1769                    if (reason != null && reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
1770                        flags |= CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL;
1771                    }
1772                }
1773                animateCollapsePanels(flags);
1774            }
1775            else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
1776                // no waiting!
1777                makeExpandedInvisible();
1778            }
1779            else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1780                if (DEBUG) {
1781                    Slog.v(TAG, "configuration changed: " + mContext.getResources().getConfiguration());
1782                }
1783                updateResources();
1784                repositionNavigationBar();
1785                updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
1786                updateShowSearchHoldoff();
1787            }
1788            else if (Intent.ACTION_SCREEN_ON.equals(action)) {
1789                // work around problem where mDisplay.getRotation() is not stable while screen is off (bug 7086018)
1790                repositionNavigationBar();
1791            }
1792        }
1793    };
1794
1795    @Override
1796    public void userSwitched(int newUserId) {
1797        if (MULTIUSER_DEBUG) mNotificationPanelDebugText.setText("USER " + newUserId);
1798        animateCollapsePanels();
1799        updateNotificationIcons();
1800    }
1801
1802    private void setIntruderAlertVisibility(boolean vis) {
1803        if (!ENABLE_INTRUDERS) return;
1804        if (DEBUG) {
1805            Slog.v(TAG, (vis ? "showing" : "hiding") + " intruder alert window");
1806        }
1807        mIntruderAlertView.setVisibility(vis ? View.VISIBLE : View.GONE);
1808    }
1809
1810    public void dismissIntruder() {
1811        if (mCurrentlyIntrudingNotification == null) return;
1812
1813        try {
1814            mBarService.onNotificationClear(
1815                    mCurrentlyIntrudingNotification.pkg,
1816                    mCurrentlyIntrudingNotification.tag,
1817                    mCurrentlyIntrudingNotification.id);
1818        } catch (android.os.RemoteException ex) {
1819            // oh well
1820        }
1821    }
1822
1823    /**
1824     * Reload some of our resources when the configuration changes.
1825     *
1826     * We don't reload everything when the configuration changes -- we probably
1827     * should, but getting that smooth is tough.  Someday we'll fix that.  In the
1828     * meantime, just update the things that we know change.
1829     */
1830    void updateResources() {
1831        final Context context = mContext;
1832        final Resources res = context.getResources();
1833
1834        if (mClearButton instanceof TextView) {
1835            ((TextView)mClearButton).setText(context.getText(R.string.status_bar_clear_all_button));
1836        }
1837
1838        // Update the QuickSettings container
1839        mSettingsPanel.updateResources();
1840
1841        loadDimens();
1842    }
1843
1844    protected void loadDimens() {
1845        final Resources res = mContext.getResources();
1846
1847        mNaturalBarHeight = res.getDimensionPixelSize(
1848                com.android.internal.R.dimen.status_bar_height);
1849
1850        int newIconSize = res.getDimensionPixelSize(
1851            com.android.internal.R.dimen.status_bar_icon_size);
1852        int newIconHPadding = res.getDimensionPixelSize(
1853            R.dimen.status_bar_icon_padding);
1854
1855        if (newIconHPadding != mIconHPadding || newIconSize != mIconSize) {
1856//            Slog.d(TAG, "size=" + newIconSize + " padding=" + newIconHPadding);
1857            mIconHPadding = newIconHPadding;
1858            mIconSize = newIconSize;
1859            //reloadAllNotificationIcons(); // reload the tray
1860        }
1861
1862        mEdgeBorder = res.getDimensionPixelSize(R.dimen.status_bar_edge_ignore);
1863
1864        mSelfExpandVelocityPx = res.getDimension(R.dimen.self_expand_velocity);
1865        mSelfCollapseVelocityPx = res.getDimension(R.dimen.self_collapse_velocity);
1866        mFlingExpandMinVelocityPx = res.getDimension(R.dimen.fling_expand_min_velocity);
1867        mFlingCollapseMinVelocityPx = res.getDimension(R.dimen.fling_collapse_min_velocity);
1868
1869        mCollapseMinDisplayFraction = res.getFraction(R.dimen.collapse_min_display_fraction, 1, 1);
1870        mExpandMinDisplayFraction = res.getFraction(R.dimen.expand_min_display_fraction, 1, 1);
1871
1872        mExpandAccelPx = res.getDimension(R.dimen.expand_accel);
1873        mCollapseAccelPx = res.getDimension(R.dimen.collapse_accel);
1874
1875        mFlingGestureMaxXVelocityPx = res.getDimension(R.dimen.fling_gesture_max_x_velocity);
1876
1877        mFlingGestureMaxOutputVelocityPx = res.getDimension(R.dimen.fling_gesture_max_output_velocity);
1878
1879        mNotificationPanelMarginBottomPx
1880            = (int) res.getDimension(R.dimen.notification_panel_margin_bottom);
1881        mNotificationPanelMarginPx
1882            = (int) res.getDimension(R.dimen.notification_panel_margin_left);
1883        mNotificationPanelGravity = res.getInteger(R.integer.notification_panel_layout_gravity);
1884        if (mNotificationPanelGravity <= 0) {
1885            mNotificationPanelGravity = Gravity.LEFT | Gravity.TOP;
1886        }
1887        mSettingsPanelGravity = res.getInteger(R.integer.settings_panel_layout_gravity);
1888        if (mSettingsPanelGravity <= 0) {
1889            mSettingsPanelGravity = Gravity.RIGHT | Gravity.TOP;
1890        }
1891        getNinePatchPadding(res.getDrawable(R.drawable.notification_panel_bg), mNotificationPanelBackgroundPadding);
1892        final int notificationPanelDecorationHeight =
1893              res.getDimensionPixelSize(R.dimen.notification_panel_padding_top)
1894            + res.getDimensionPixelSize(R.dimen.notification_panel_header_height)
1895            + mNotificationPanelBackgroundPadding.top
1896            + mNotificationPanelBackgroundPadding.bottom;
1897        mNotificationPanelMinHeight =
1898              notificationPanelDecorationHeight
1899            + res.getDimensionPixelSize(R.dimen.close_handle_underlap);
1900
1901        mCarrierLabelHeight = res.getDimensionPixelSize(R.dimen.carrier_label_height);
1902        mNotificationHeaderHeight = res.getDimensionPixelSize(R.dimen.notification_panel_header_height);
1903
1904        if (false) Slog.v(TAG, "updateResources");
1905    }
1906
1907    private static void getNinePatchPadding(Drawable d, Rect outPadding) {
1908        if (d instanceof NinePatchDrawable) {
1909            NinePatchDrawable ninePatch = (NinePatchDrawable) d;
1910            ninePatch.getPadding(outPadding);
1911        }
1912    }
1913
1914    //
1915    // tracing
1916    //
1917
1918    void postStartTracing() {
1919        mHandler.postDelayed(mStartTracing, 3000);
1920    }
1921
1922    void vibrate() {
1923        android.os.Vibrator vib = (android.os.Vibrator)mContext.getSystemService(
1924                Context.VIBRATOR_SERVICE);
1925        vib.vibrate(250);
1926    }
1927
1928    Runnable mStartTracing = new Runnable() {
1929        public void run() {
1930            vibrate();
1931            SystemClock.sleep(250);
1932            Slog.d(TAG, "startTracing");
1933            android.os.Debug.startMethodTracing("/data/statusbar-traces/trace");
1934            mHandler.postDelayed(mStopTracing, 10000);
1935        }
1936    };
1937
1938    Runnable mStopTracing = new Runnable() {
1939        public void run() {
1940            android.os.Debug.stopMethodTracing();
1941            Slog.d(TAG, "stopTracing");
1942            vibrate();
1943        }
1944    };
1945
1946    @Override
1947    protected void haltTicker() {
1948        mTicker.halt();
1949    }
1950
1951    @Override
1952    protected boolean shouldDisableNavbarGestures() {
1953        return mExpandedVisible || (mDisabled & StatusBarManager.DISABLE_HOME) != 0;
1954    }
1955
1956    private static class FastColorDrawable extends Drawable {
1957        private final int mColor;
1958
1959        public FastColorDrawable(int color) {
1960            mColor = 0xff000000 | color;
1961        }
1962
1963        @Override
1964        public void draw(Canvas canvas) {
1965            canvas.drawColor(mColor, PorterDuff.Mode.SRC);
1966        }
1967
1968        @Override
1969        public void setAlpha(int alpha) {
1970        }
1971
1972        @Override
1973        public void setColorFilter(ColorFilter cf) {
1974        }
1975
1976        @Override
1977        public int getOpacity() {
1978            return PixelFormat.OPAQUE;
1979        }
1980
1981        @Override
1982        public void setBounds(int left, int top, int right, int bottom) {
1983        }
1984
1985        @Override
1986        public void setBounds(Rect bounds) {
1987        }
1988    }
1989}
1990