PhoneStatusBar.java revision fc753d2dfa6f1bfafce59e1a2049e640b1629a83
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.Dialog;
26import android.app.KeyguardManager;
27import android.app.Notification;
28import android.app.PendingIntent;
29import android.app.StatusBarManager;
30import android.content.BroadcastReceiver;
31import android.content.Context;
32import android.content.Intent;
33import android.content.IntentFilter;
34import android.content.res.Configuration;
35import android.content.res.Resources;
36import android.graphics.PixelFormat;
37import android.graphics.Rect;
38import android.inputmethodservice.InputMethodService;
39import android.os.IBinder;
40import android.os.Message;
41import android.os.RemoteException;
42import android.os.ServiceManager;
43import android.os.SystemClock;
44import android.provider.Settings;
45import android.text.TextUtils;
46import android.util.DisplayMetrics;
47import android.util.Log;
48import android.util.Slog;
49import android.util.TypedValue;
50import android.view.Choreographer;
51import android.view.Display;
52import android.view.Gravity;
53import android.view.IWindowManager;
54import android.view.KeyEvent;
55import android.view.MotionEvent;
56import android.view.VelocityTracker;
57import android.view.View;
58import android.view.ViewGroup;
59import android.view.ViewGroup.LayoutParams;
60import android.view.Window;
61import android.view.WindowManager;
62import android.view.WindowManagerImpl;
63import android.view.animation.AccelerateInterpolator;
64import android.view.animation.Animation;
65import android.view.animation.AnimationUtils;
66import android.widget.CompoundButton;
67import android.widget.FrameLayout;
68import android.widget.ImageView;
69import android.widget.LinearLayout;
70import android.widget.RemoteViews;
71import android.widget.ScrollView;
72import android.widget.TextView;
73
74import com.android.internal.statusbar.StatusBarIcon;
75import com.android.internal.statusbar.StatusBarNotification;
76import com.android.systemui.R;
77import com.android.systemui.recent.RecentTasksLoader;
78import com.android.systemui.statusbar.BaseStatusBar;
79import com.android.systemui.statusbar.NotificationData;
80import com.android.systemui.statusbar.NotificationData.Entry;
81import com.android.systemui.statusbar.RotationToggle;
82import com.android.systemui.statusbar.SignalClusterView;
83import com.android.systemui.statusbar.StatusBarIconView;
84import com.android.systemui.statusbar.policy.AutoRotateController;
85import com.android.systemui.statusbar.policy.BatteryController;
86import com.android.systemui.statusbar.policy.DateView;
87import com.android.systemui.statusbar.policy.IntruderAlertView;
88import com.android.systemui.statusbar.policy.LocationController;
89import com.android.systemui.statusbar.policy.NetworkController;
90import com.android.systemui.statusbar.policy.NotificationRowLayout;
91
92import java.io.FileDescriptor;
93import java.io.PrintWriter;
94import java.util.ArrayList;
95
96public class PhoneStatusBar extends BaseStatusBar {
97    static final String TAG = "PhoneStatusBar";
98    public static final boolean DEBUG = false;
99    public static final boolean SPEW = DEBUG;
100    public static final boolean DUMPTRUCK = true; // extra dumpsys info
101
102    // additional instrumentation for testing purposes; intended to be left on during development
103    public static final boolean CHATTY = DEBUG;
104
105    public static final String ACTION_STATUSBAR_START
106            = "com.android.internal.policy.statusbar.START";
107
108    private static final boolean ENABLE_INTRUDERS = false;
109    private static final boolean DIM_BEHIND_EXPANDED_PANEL = false;
110
111    static final int EXPANDED_LEAVE_ALONE = -10000;
112    static final int EXPANDED_FULL_OPEN = -10001;
113
114    private static final int MSG_OPEN_NOTIFICATION_PANEL = 1000;
115    private static final int MSG_CLOSE_NOTIFICATION_PANEL = 1001;
116    private static final int MSG_SHOW_INTRUDER = 1002;
117    private static final int MSG_HIDE_INTRUDER = 1003;
118    // 1020-1030 reserved for BaseStatusBar
119
120    // will likely move to a resource or other tunable param at some point
121    private static final int INTRUDER_ALERT_DECAY_MS = 0; // disabled, was 10000;
122
123    private static final boolean CLOSE_PANEL_WHEN_EMPTIED = true;
124
125    private static final int NOTIFICATION_PRIORITY_MULTIPLIER = 10; // see NotificationManagerService
126    private static final int HIDE_ICONS_BELOW_SCORE = Notification.PRIORITY_LOW * NOTIFICATION_PRIORITY_MULTIPLIER;
127
128    // fling gesture tuning parameters, scaled to display density
129    private float mSelfExpandVelocityPx; // classic value: 2000px/s
130    private float mSelfCollapseVelocityPx; // classic value: 2000px/s (will be negated to collapse "up")
131    private float mFlingExpandMinVelocityPx; // classic value: 200px/s
132    private float mFlingCollapseMinVelocityPx; // classic value: 200px/s
133    private float mCollapseMinDisplayFraction; // classic value: 0.08 (25px/min(320px,480px) on G1)
134    private float mExpandMinDisplayFraction; // classic value: 0.5 (drag open halfway to expand)
135    private float mFlingGestureMaxXVelocityPx; // classic value: 150px/s
136
137    private float mExpandAccelPx; // classic value: 2000px/s/s
138    private float mCollapseAccelPx; // classic value: 2000px/s/s (will be negated to collapse "up")
139
140    PhoneStatusBarPolicy mIconPolicy;
141
142    // These are no longer handled by the policy, because we need custom strategies for them
143    BatteryController mBatteryController;
144    LocationController mLocationController;
145    NetworkController mNetworkController;
146
147    int mNaturalBarHeight = -1;
148    int mIconSize = -1;
149    int mIconHPadding = -1;
150    Display mDisplay;
151
152    IWindowManager mWindowManager;
153
154    StatusBarWindowView mStatusBarWindow;
155    PhoneStatusBarView mStatusBarView;
156
157    int mPixelFormat;
158    Object mQueueLock = new Object();
159
160    // icons
161    LinearLayout mIcons;
162    IconMerger mNotificationIcons;
163    View mMoreIcon;
164    LinearLayout mStatusIcons;
165
166    // expanded notifications
167    View mNotificationPanel; // the sliding/resizing panel within the notification window
168    ScrollView mScrollView;
169    View mExpandedContents;
170    int mNotificationPanelMarginBottomPx, mNotificationPanelMarginLeftPx;
171    int mNotificationPanelGravity;
172
173    // top bar
174    View mClearButton;
175    View mSettingsButton;
176    RotationToggle mRotationButton;
177
178    // drag bar
179    CloseDragHandle mCloseView;
180    private int mCloseViewHeight;
181
182    // all notifications
183    NotificationData mNotificationData = new NotificationData();
184    NotificationRowLayout mPile;
185
186    // position
187    int[] mPositionTmp = new int[2];
188    boolean mExpanded;
189    boolean mExpandedVisible;
190
191    // the date view
192    DateView mDateView;
193
194    // for immersive activities
195    private IntruderAlertView mIntruderAlertView;
196
197    // on-screen navigation buttons
198    private NavigationBarView mNavigationBarView = null;
199
200    // the tracker view
201    int mTrackingPosition; // the position of the top of the tracking view.
202    private boolean mPanelSlightlyVisible;
203
204    // ticker
205    private Ticker mTicker;
206    private View mTickerView;
207    private boolean mTicking;
208
209    // Tracking finger for opening/closing.
210    int mEdgeBorder; // corresponds to R.dimen.status_bar_edge_ignore
211    boolean mTracking;
212    VelocityTracker mVelocityTracker;
213
214    Choreographer mChoreographer;
215    boolean mAnimating;
216    boolean mClosing; // only valid when mAnimating; indicates the initial acceleration
217    float mAnimY;
218    float mAnimVel;
219    float mAnimAccel;
220    long mAnimLastTimeNanos;
221    boolean mAnimatingReveal = false;
222    int mViewDelta;
223    int[] mAbsPos = new int[2];
224    Runnable mPostCollapseCleanup = null;
225
226    private AnimatorSet mLightsOutAnimation;
227    private AnimatorSet mLightsOnAnimation;
228
229    // for disabling the status bar
230    int mDisabled = 0;
231
232    // tracking calls to View.setSystemUiVisibility()
233    int mSystemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE;
234
235    DisplayMetrics mDisplayMetrics = new DisplayMetrics();
236
237    private int mNavigationIconHints = 0;
238
239    private class ExpandedDialog extends Dialog {
240        ExpandedDialog(Context context) {
241            super(context, com.android.internal.R.style.Theme_Translucent_NoTitleBar);
242        }
243
244        @Override
245        public boolean dispatchKeyEvent(KeyEvent event) {
246            boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
247            switch (event.getKeyCode()) {
248            case KeyEvent.KEYCODE_BACK:
249                if (!down) {
250                    animateCollapse();
251                }
252                return true;
253            }
254            return super.dispatchKeyEvent(event);
255        }
256    }
257
258    @Override
259    public void start() {
260        mDisplay = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE))
261                .getDefaultDisplay();
262
263        mWindowManager = IWindowManager.Stub.asInterface(
264                ServiceManager.getService(Context.WINDOW_SERVICE));
265
266        super.start(); // calls createAndAddWindows()
267
268        addNavigationBar();
269
270        if (ENABLE_INTRUDERS) addIntruderView();
271
272        // Lastly, call to the icon policy to install/update all the icons.
273        mIconPolicy = new PhoneStatusBarPolicy(mContext);
274    }
275
276    // ================================================================================
277    // Constructing the view
278    // ================================================================================
279    protected PhoneStatusBarView makeStatusBarView() {
280        final Context context = mContext;
281
282        Resources res = context.getResources();
283
284        updateDisplaySize(); // populates mDisplayMetrics
285        loadDimens();
286
287        mIconSize = res.getDimensionPixelSize(com.android.internal.R.dimen.status_bar_icon_size);
288
289        mStatusBarWindow = (StatusBarWindowView) View.inflate(context,
290                R.layout.super_status_bar, null);
291        if (DEBUG) {
292            mStatusBarWindow.setBackgroundColor(0x6000FF80);
293        }
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 (mExpanded && !mAnimating) {
300                        animateCollapse();
301                    }
302                }
303                return true;
304            }});
305
306        mStatusBarView = (PhoneStatusBarView) mStatusBarWindow.findViewById(R.id.status_bar);
307        mNotificationPanel = mStatusBarWindow.findViewById(R.id.notification_panel);
308        // don't allow clicks on the panel to pass through to the background where they will cause the panel to close
309        mNotificationPanel.setOnTouchListener(new View.OnTouchListener() {
310            @Override
311            public boolean onTouch(View v, MotionEvent event) {
312                return true;
313            }
314        });
315
316        if (!ActivityManager.isHighEndGfx(mDisplay)) {
317            mStatusBarWindow.setBackground(null);
318            mNotificationPanel.setBackgroundColor(context.getResources().getColor(
319                    R.color.notification_panel_solid_background));
320        }
321
322        if (ENABLE_INTRUDERS) {
323            mIntruderAlertView = (IntruderAlertView) View.inflate(context, R.layout.intruder_alert, null);
324            mIntruderAlertView.setVisibility(View.GONE);
325            mIntruderAlertView.setBar(this);
326        }
327
328        mStatusBarView.mService = this;
329
330        mChoreographer = Choreographer.getInstance();
331
332        try {
333            boolean showNav = mWindowManager.hasNavigationBar();
334            if (DEBUG) Slog.v(TAG, "hasNavigationBar=" + showNav);
335            if (showNav) {
336                mNavigationBarView =
337                    (NavigationBarView) View.inflate(context, R.layout.navigation_bar, null);
338
339                mNavigationBarView.setDisabledFlags(mDisabled);
340                mNavigationBarView.setBar(this);
341            }
342        } catch (RemoteException ex) {
343            // no window manager? good luck with that
344        }
345
346        // figure out which pixel-format to use for the status bar.
347        mPixelFormat = PixelFormat.OPAQUE;
348        mStatusIcons = (LinearLayout)mStatusBarView.findViewById(R.id.statusIcons);
349        mNotificationIcons = (IconMerger)mStatusBarView.findViewById(R.id.notificationIcons);
350        mMoreIcon = mStatusBarView.findViewById(R.id.moreIcon);
351        mNotificationIcons.setOverflowIndicator(mMoreIcon);
352        mIcons = (LinearLayout)mStatusBarView.findViewById(R.id.icons);
353        mTickerView = mStatusBarView.findViewById(R.id.ticker);
354
355        mPile = (NotificationRowLayout)mStatusBarWindow.findViewById(R.id.latestItems);
356        mPile.setLongPressListener(getNotificationLongClicker());
357        mExpandedContents = mPile; // was: expanded.findViewById(R.id.notificationLinearLayout);
358
359        mClearButton = mStatusBarWindow.findViewById(R.id.clear_all_button);
360        mClearButton.setOnClickListener(mClearButtonListener);
361        mClearButton.setAlpha(0f);
362        mClearButton.setEnabled(false);
363        mDateView = (DateView)mStatusBarWindow.findViewById(R.id.date);
364        mSettingsButton = mStatusBarWindow.findViewById(R.id.settings_button);
365        mSettingsButton.setOnClickListener(mSettingsButtonListener);
366        mRotationButton = (RotationToggle) mStatusBarWindow.findViewById(R.id.rotation_lock_button);
367
368        mScrollView = (ScrollView)mStatusBarWindow.findViewById(R.id.scroll);
369        mScrollView.setVerticalScrollBarEnabled(false); // less drawing during pulldowns
370
371        mTicker = new MyTicker(context, mStatusBarView);
372
373        TickerView tickerView = (TickerView)mStatusBarView.findViewById(R.id.tickerText);
374        tickerView.mTicker = mTicker;
375
376        mCloseView = (CloseDragHandle)mStatusBarWindow.findViewById(R.id.close);
377        mCloseView.mService = this;
378        mCloseViewHeight = res.getDimensionPixelSize(R.dimen.close_handle_height);
379
380        mEdgeBorder = res.getDimensionPixelSize(R.dimen.status_bar_edge_ignore);
381
382        // set the inital view visibility
383        setAreThereNotifications();
384
385        // Other icons
386        mLocationController = new LocationController(mContext); // will post a notification
387        mBatteryController = new BatteryController(mContext);
388        mBatteryController.addIconView((ImageView)mStatusBarView.findViewById(R.id.battery));
389        mNetworkController = new NetworkController(mContext);
390        final SignalClusterView signalCluster =
391                (SignalClusterView)mStatusBarView.findViewById(R.id.signal_cluster);
392        mNetworkController.addSignalCluster(signalCluster);
393        signalCluster.setNetworkController(mNetworkController);
394//        final ImageView wimaxRSSI =
395//                (ImageView)sb.findViewById(R.id.wimax_signal);
396//        if (wimaxRSSI != null) {
397//            mNetworkController.addWimaxIconView(wimaxRSSI);
398//        }
399        // Recents Panel
400        mRecentTasksLoader = new RecentTasksLoader(context);
401        updateRecentsPanel();
402
403        // receive broadcasts
404        IntentFilter filter = new IntentFilter();
405        filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
406        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
407        filter.addAction(Intent.ACTION_SCREEN_OFF);
408        context.registerReceiver(mBroadcastReceiver, filter);
409
410        return mStatusBarView;
411    }
412
413    @Override
414    protected WindowManager.LayoutParams getRecentsLayoutParams(LayoutParams layoutParams) {
415        boolean opaque = false;
416        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
417                layoutParams.width,
418                layoutParams.height,
419                WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL,
420                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
421                | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
422                | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
423                (opaque ? PixelFormat.OPAQUE : PixelFormat.TRANSLUCENT));
424        if (ActivityManager.isHighEndGfx(mDisplay)) {
425            lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
426        } else {
427            lp.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
428            lp.dimAmount = 0.7f;
429        }
430        lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
431        lp.setTitle("RecentsPanel");
432        lp.windowAnimations = com.android.internal.R.style.Animation_RecentApplications;
433        lp.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED
434        | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
435        return lp;
436    }
437
438    @Override
439    protected WindowManager.LayoutParams getSearchLayoutParams(LayoutParams layoutParams) {
440        boolean opaque = false;
441        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
442                LayoutParams.MATCH_PARENT,
443                LayoutParams.MATCH_PARENT,
444                WindowManager.LayoutParams.TYPE_NAVIGATION_BAR_PANEL,
445                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
446                | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
447                | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
448                (opaque ? PixelFormat.OPAQUE : PixelFormat.TRANSLUCENT));
449        if (ActivityManager.isHighEndGfx(mDisplay)) {
450            lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
451        } else {
452            lp.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
453            lp.dimAmount = 0.7f;
454        }
455        lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
456        lp.setTitle("SearchPanel");
457        // TODO: Define custom animation for Search panel
458        lp.windowAnimations = com.android.internal.R.style.Animation_RecentApplications;
459        lp.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED
460        | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING;
461        return lp;
462    }
463
464    protected void updateRecentsPanel() {
465        super.updateRecentsPanel(R.layout.status_bar_recent_panel);
466        // Make .03 alpha the minimum so you always see the item a bit-- slightly below
467        // .03, the item disappears entirely (as if alpha = 0) and that discontinuity looks
468        // a bit jarring
469        mRecentsPanel.setMinSwipeAlpha(0.03f);
470    }
471
472    @Override
473    protected void updateSearchPanel() {
474        super.updateSearchPanel();
475        mSearchPanelView.setStatusBarView(mNavigationBarView);
476        mNavigationBarView.setDelegateView(mSearchPanelView);
477    }
478
479    @Override
480    public void showSearchPanel() {
481        super.showSearchPanel();
482        WindowManager.LayoutParams lp =
483            (android.view.WindowManager.LayoutParams) mNavigationBarView.getLayoutParams();
484        lp.flags &= ~WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
485        lp.flags &= ~WindowManager.LayoutParams.FLAG_SLIPPERY;
486        WindowManagerImpl.getDefault().updateViewLayout(mNavigationBarView, lp);
487    }
488
489    @Override
490    public void hideSearchPanel() {
491        super.hideSearchPanel();
492        WindowManager.LayoutParams lp =
493            (android.view.WindowManager.LayoutParams) mNavigationBarView.getLayoutParams();
494        lp.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
495        lp.flags |= WindowManager.LayoutParams.FLAG_SLIPPERY;
496        WindowManagerImpl.getDefault().updateViewLayout(mNavigationBarView, lp);
497    }
498
499    protected int getStatusBarGravity() {
500        return Gravity.TOP | Gravity.FILL_HORIZONTAL;
501    }
502
503    public int getStatusBarHeight() {
504        if (mNaturalBarHeight < 0) {
505            final Resources res = mContext.getResources();
506            mNaturalBarHeight =
507                    res.getDimensionPixelSize(com.android.internal.R.dimen.status_bar_height);
508        }
509        return mNaturalBarHeight;
510    }
511
512    private int getCloseViewHeight() {
513        return mCloseViewHeight;
514    }
515
516    private View.OnClickListener mRecentsClickListener = new View.OnClickListener() {
517        public void onClick(View v) {
518            toggleRecentApps();
519        }
520    };
521    private StatusBarNotification mCurrentlyIntrudingNotification;
522    View.OnTouchListener mHomeSearchActionListener = new View.OnTouchListener() {
523        public boolean onTouch(View v, MotionEvent event) {
524            switch(event.getAction()) {
525                case MotionEvent.ACTION_DOWN:
526                    Slog.d(TAG, "showing search panel");
527                    showSearchPanel();
528                break;
529
530                case MotionEvent.ACTION_UP:
531                    Slog.d(TAG, "hiding search panel");
532                    hideSearchPanel();
533                break;
534            }
535            return false;
536        }
537    };
538
539    private void prepareNavigationBarView() {
540        mNavigationBarView.reorient();
541
542        mNavigationBarView.getRecentsButton().setOnClickListener(mRecentsClickListener);
543        mNavigationBarView.getRecentsButton().setOnTouchListener(mRecentsPanel);
544        updateSearchPanel();
545//        mNavigationBarView.getHomeButton().setOnTouchListener(mHomeSearchActionListener);
546    }
547
548    // For small-screen devices (read: phones) that lack hardware navigation buttons
549    private void addNavigationBar() {
550        if (DEBUG) Slog.v(TAG, "addNavigationBar: about to add " + mNavigationBarView);
551        if (mNavigationBarView == null) return;
552
553        prepareNavigationBarView();
554
555        WindowManagerImpl.getDefault().addView(
556                mNavigationBarView, getNavigationBarLayoutParams());
557    }
558
559    private void repositionNavigationBar() {
560        if (mNavigationBarView == null) return;
561
562        prepareNavigationBarView();
563
564        WindowManagerImpl.getDefault().updateViewLayout(
565                mNavigationBarView, getNavigationBarLayoutParams());
566    }
567
568    private WindowManager.LayoutParams getNavigationBarLayoutParams() {
569        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
570                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,
571                WindowManager.LayoutParams.TYPE_NAVIGATION_BAR,
572                    0
573                    | WindowManager.LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING
574                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
575                    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
576                    | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH
577                    | WindowManager.LayoutParams.FLAG_SLIPPERY,
578                PixelFormat.OPAQUE);
579        // this will allow the navbar to run in an overlay on devices that support this
580        if (ActivityManager.isHighEndGfx(mDisplay)) {
581            lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
582        }
583
584        lp.setTitle("NavigationBar");
585        lp.windowAnimations = 0;
586
587        return lp;
588    }
589
590    private void addIntruderView() {
591        final int height = getStatusBarHeight();
592
593        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
594                ViewGroup.LayoutParams.MATCH_PARENT,
595                ViewGroup.LayoutParams.WRAP_CONTENT,
596                WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL, // above the status bar!
597                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
598                    | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
599                    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
600                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
601                    | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
602                    | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
603                PixelFormat.TRANSLUCENT);
604        lp.gravity = Gravity.TOP | Gravity.FILL_HORIZONTAL;
605        //lp.y += height * 1.5; // FIXME
606        lp.setTitle("IntruderAlert");
607        lp.packageName = mContext.getPackageName();
608        lp.windowAnimations = R.style.Animation_StatusBar_IntruderAlert;
609
610        WindowManagerImpl.getDefault().addView(mIntruderAlertView, lp);
611    }
612
613    public void addIcon(String slot, int index, int viewIndex, StatusBarIcon icon) {
614        if (SPEW) Slog.d(TAG, "addIcon slot=" + slot + " index=" + index + " viewIndex=" + viewIndex
615                + " icon=" + icon);
616        StatusBarIconView view = new StatusBarIconView(mContext, slot, null);
617        view.set(icon);
618        mStatusIcons.addView(view, viewIndex, new LinearLayout.LayoutParams(mIconSize, mIconSize));
619    }
620
621    public void updateIcon(String slot, int index, int viewIndex,
622            StatusBarIcon old, StatusBarIcon icon) {
623        if (SPEW) Slog.d(TAG, "updateIcon slot=" + slot + " index=" + index + " viewIndex=" + viewIndex
624                + " old=" + old + " icon=" + icon);
625        StatusBarIconView view = (StatusBarIconView)mStatusIcons.getChildAt(viewIndex);
626        view.set(icon);
627    }
628
629    public void removeIcon(String slot, int index, int viewIndex) {
630        if (SPEW) Slog.d(TAG, "removeIcon slot=" + slot + " index=" + index + " viewIndex=" + viewIndex);
631        mStatusIcons.removeViewAt(viewIndex);
632    }
633
634    public void addNotification(IBinder key, StatusBarNotification notification) {
635        /* if (DEBUG) */ Slog.d(TAG, "addNotification score=" + notification.score);
636        StatusBarIconView iconView = addNotificationViews(key, notification);
637        if (iconView == null) return;
638
639        boolean immersive = false;
640        try {
641            immersive = ActivityManagerNative.getDefault().isTopActivityImmersive();
642            if (DEBUG) {
643                Slog.d(TAG, "Top activity is " + (immersive?"immersive":"not immersive"));
644            }
645        } catch (RemoteException ex) {
646        }
647
648        /*
649         * DISABLED due to missing API
650        if (ENABLE_INTRUDERS && (
651                   // TODO(dsandler): Only if the screen is on
652                notification.notification.intruderView != null)) {
653            Slog.d(TAG, "Presenting high-priority notification");
654            // special new transient ticker mode
655            // 1. Populate mIntruderAlertView
656
657            if (notification.notification.intruderView == null) {
658                Slog.e(TAG, notification.notification.toString() + " wanted to intrude but intruderView was null");
659                return;
660            }
661
662            // bind the click event to the content area
663            PendingIntent contentIntent = notification.notification.contentIntent;
664            final View.OnClickListener listener = (contentIntent != null)
665                    ? new NotificationClicker(contentIntent,
666                            notification.pkg, notification.tag, notification.id)
667                    : null;
668
669            mIntruderAlertView.applyIntruderContent(notification.notification.intruderView, listener);
670
671            mCurrentlyIntrudingNotification = notification;
672
673            // 2. Animate mIntruderAlertView in
674            mHandler.sendEmptyMessage(MSG_SHOW_INTRUDER);
675
676            // 3. Set alarm to age the notification off (TODO)
677            mHandler.removeMessages(MSG_HIDE_INTRUDER);
678            if (INTRUDER_ALERT_DECAY_MS > 0) {
679                mHandler.sendEmptyMessageDelayed(MSG_HIDE_INTRUDER, INTRUDER_ALERT_DECAY_MS);
680            }
681        } else
682         */
683
684        if (notification.notification.fullScreenIntent != null) {
685            // not immersive & a full-screen alert should be shown
686            Slog.d(TAG, "Notification has fullScreenIntent; sending fullScreenIntent");
687            try {
688                notification.notification.fullScreenIntent.send();
689            } catch (PendingIntent.CanceledException e) {
690            }
691        } else {
692            // usual case: status bar visible & not immersive
693
694            // show the ticker if there isn't an intruder too
695            if (mCurrentlyIntrudingNotification == null) {
696                tick(notification);
697            }
698        }
699
700        // Recalculate the position of the sliding windows and the titles.
701        setAreThereNotifications();
702        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
703    }
704
705    public void updateNotification(IBinder key, StatusBarNotification notification) {
706        if (DEBUG) Slog.d(TAG, "updateNotification(" + key + " -> " + notification + ")");
707
708        final NotificationData.Entry oldEntry = mNotificationData.findByKey(key);
709        if (oldEntry == null) {
710            Slog.w(TAG, "updateNotification for unknown key: " + key);
711            return;
712        }
713
714        final StatusBarNotification oldNotification = oldEntry.notification;
715
716        // XXX: modify when we do something more intelligent with the two content views
717        final RemoteViews oldContentView = (oldNotification.notification.bigContentView != null)
718                ? oldNotification.notification.bigContentView
719                : oldNotification.notification.contentView;
720        final RemoteViews contentView = (notification.notification.bigContentView != null)
721                ? notification.notification.bigContentView
722                : notification.notification.contentView;
723
724        if (DEBUG) {
725            Slog.d(TAG, "old notification: when=" + oldNotification.notification.when
726                    + " ongoing=" + oldNotification.isOngoing()
727                    + " expanded=" + oldEntry.expanded
728                    + " contentView=" + oldContentView
729                    + " rowParent=" + oldEntry.row.getParent());
730            Slog.d(TAG, "new notification: when=" + notification.notification.when
731                    + " ongoing=" + oldNotification.isOngoing()
732                    + " contentView=" + contentView);
733        }
734
735
736        // Can we just reapply the RemoteViews in place?  If when didn't change, the order
737        // didn't change.
738        boolean contentsUnchanged = oldEntry.expanded != null
739                && contentView != null && oldContentView != null
740                && contentView.getPackage() != null
741                && oldContentView.getPackage() != null
742                && oldContentView.getPackage().equals(contentView.getPackage())
743                && oldContentView.getLayoutId() == contentView.getLayoutId();
744        ViewGroup rowParent = (ViewGroup) oldEntry.row.getParent();
745        boolean orderUnchanged = notification.notification.when==oldNotification.notification.when
746                && notification.score == oldNotification.score;
747                // score now encompasses/supersedes isOngoing()
748
749        boolean updateTicker = notification.notification.tickerText != null
750                && !TextUtils.equals(notification.notification.tickerText,
751                        oldEntry.notification.notification.tickerText);
752        boolean isFirstAnyway = rowParent.indexOfChild(oldEntry.row) == 0;
753        if (contentsUnchanged && (orderUnchanged || isFirstAnyway)) {
754            if (DEBUG) Slog.d(TAG, "reusing notification for key: " + key);
755            oldEntry.notification = notification;
756            try {
757                // Reapply the RemoteViews
758                contentView.reapply(mContext, oldEntry.content);
759                // update the contentIntent
760                final PendingIntent contentIntent = notification.notification.contentIntent;
761                if (contentIntent != null) {
762                    final View.OnClickListener listener = new NotificationClicker(contentIntent,
763                            notification.pkg, notification.tag, notification.id);
764                    oldEntry.content.setOnClickListener(listener);
765                } else {
766                    oldEntry.content.setOnClickListener(null);
767                }
768                // Update the icon.
769                final StatusBarIcon ic = new StatusBarIcon(notification.pkg,
770                        notification.notification.icon, notification.notification.iconLevel,
771                        notification.notification.number,
772                        notification.notification.tickerText);
773                if (!oldEntry.icon.set(ic)) {
774                    handleNotificationError(key, notification, "Couldn't update icon: " + ic);
775                    return;
776                }
777            }
778            catch (RuntimeException e) {
779                // It failed to add cleanly.  Log, and remove the view from the panel.
780                Slog.w(TAG, "Couldn't reapply views for package " + contentView.getPackage(), e);
781                removeNotificationViews(key);
782                addNotificationViews(key, notification);
783            }
784        } else {
785            if (SPEW) Slog.d(TAG, "not reusing notification");
786            removeNotificationViews(key);
787            addNotificationViews(key, notification);
788        }
789
790        // Update the veto button accordingly (and as a result, whether this row is
791        // swipe-dismissable)
792        updateNotificationVetoButton(oldEntry.row, notification);
793
794        // Restart the ticker if it's still running
795        if (updateTicker) {
796            mTicker.halt();
797            tick(notification);
798        }
799
800        // Recalculate the position of the sliding windows and the titles.
801        setAreThereNotifications();
802        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
803
804        // See if we need to update the intruder.
805        if (ENABLE_INTRUDERS && oldNotification == mCurrentlyIntrudingNotification) {
806            if (DEBUG) Slog.d(TAG, "updating the current intruder:" + notification);
807            // XXX: this is a hack for Alarms. The real implementation will need to *update*
808            // the intruder.
809            if (notification.notification.fullScreenIntent == null) { // TODO(dsandler): consistent logic with add()
810                if (DEBUG) Slog.d(TAG, "no longer intrudes!");
811                mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
812            }
813        }
814    }
815
816    public void removeNotification(IBinder key) {
817        StatusBarNotification old = removeNotificationViews(key);
818        if (SPEW) Slog.d(TAG, "removeNotification key=" + key + " old=" + old);
819
820        if (old != null) {
821            // Cancel the ticker if it's still running
822            mTicker.removeEntry(old);
823
824            // Recalculate the position of the sliding windows and the titles.
825            updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
826
827            if (ENABLE_INTRUDERS && old == mCurrentlyIntrudingNotification) {
828                mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
829            }
830
831            if (CLOSE_PANEL_WHEN_EMPTIED && mNotificationData.size() == 0 && !mAnimating) {
832                animateCollapse();
833            }
834        }
835
836        setAreThereNotifications();
837    }
838
839    @Override
840    protected void onConfigurationChanged(Configuration newConfig) {
841        updateRecentsPanel();
842    }
843
844
845    StatusBarIconView addNotificationViews(IBinder key, StatusBarNotification notification) {
846        if (DEBUG) {
847            Slog.d(TAG, "addNotificationViews(key=" + key + ", notification=" + notification);
848        }
849        // Construct the icon.
850        final StatusBarIconView iconView = new StatusBarIconView(mContext,
851                notification.pkg + "/0x" + Integer.toHexString(notification.id),
852                notification.notification);
853        iconView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
854
855        final StatusBarIcon ic = new StatusBarIcon(notification.pkg,
856                    notification.notification.icon,
857                    notification.notification.iconLevel,
858                    notification.notification.number,
859                    notification.notification.tickerText);
860        if (!iconView.set(ic)) {
861            handleNotificationError(key, notification, "Couldn't create icon: " + ic);
862            return null;
863        }
864        // Construct the expanded view.
865        NotificationData.Entry entry = new NotificationData.Entry(key, notification, iconView);
866        if (!inflateViews(entry, mPile)) {
867            handleNotificationError(key, notification, "Couldn't expand RemoteViews for: "
868                    + notification);
869            return null;
870        }
871
872        // Add the expanded view and icon.
873        int pos = mNotificationData.add(entry);
874        if (DEBUG) {
875            Slog.d(TAG, "addNotificationViews: added at " + pos);
876        }
877        updateNotificationIcons();
878
879        return iconView;
880    }
881
882    private void loadNotificationShade() {
883        int N = mNotificationData.size();
884
885        ArrayList<View> toShow = new ArrayList<View>();
886
887        for (int i=0; i<N; i++) {
888            View row = mNotificationData.get(N-i-1).row;
889            toShow.add(row);
890        }
891
892        ArrayList<View> toRemove = new ArrayList<View>();
893        for (int i=0; i<mPile.getChildCount(); i++) {
894            View child = mPile.getChildAt(i);
895            if (!toShow.contains(child)) {
896                toRemove.add(child);
897            }
898        }
899
900        for (View remove : toRemove) {
901            mPile.removeView(remove);
902        }
903
904        for (int i=0; i<toShow.size(); i++) {
905            View v = toShow.get(i);
906            if (v.getParent() == null) {
907                mPile.addView(v, i);
908            }
909        }
910    }
911
912    private void reloadAllNotificationIcons() {
913        if (mNotificationIcons == null) return;
914        mNotificationIcons.removeAllViews();
915        updateNotificationIcons();
916    }
917
918    private void updateNotificationIcons() {
919        loadNotificationShade();
920
921        final LinearLayout.LayoutParams params
922            = new LinearLayout.LayoutParams(mIconSize + 2*mIconHPadding, mNaturalBarHeight);
923
924        int N = mNotificationData.size();
925
926        if (DEBUG) {
927            Slog.d(TAG, "refreshing icons: " + N + " notifications, mNotificationIcons=" + mNotificationIcons);
928        }
929
930        ArrayList<View> toShow = new ArrayList<View>();
931
932        for (int i=0; i<N; i++) {
933            Entry ent = mNotificationData.get(N-i-1);
934            if (ent.notification.score >= HIDE_ICONS_BELOW_SCORE) {
935                toShow.add(ent.icon);
936            }
937        }
938
939        ArrayList<View> toRemove = new ArrayList<View>();
940        for (int i=0; i<mNotificationIcons.getChildCount(); i++) {
941            View child = mNotificationIcons.getChildAt(i);
942            if (!toShow.contains(child)) {
943                toRemove.add(child);
944            }
945        }
946
947        for (View remove : toRemove) {
948            mNotificationIcons.removeView(remove);
949        }
950
951        for (int i=0; i<toShow.size(); i++) {
952            View v = toShow.get(i);
953            if (v.getParent() == null) {
954                mNotificationIcons.addView(v, i, params);
955            }
956        }
957    }
958
959    StatusBarNotification removeNotificationViews(IBinder key) {
960        NotificationData.Entry entry = mNotificationData.remove(key);
961        if (entry == null) {
962            Slog.w(TAG, "removeNotification for unknown key: " + key);
963            return null;
964        }
965        // Remove the expanded view.
966        ViewGroup rowParent = (ViewGroup)entry.row.getParent();
967        if (rowParent != null) rowParent.removeView(entry.row);
968        updateNotificationIcons();
969
970        return entry.notification;
971    }
972
973    private void setAreThereNotifications() {
974        final boolean any = mNotificationData.size() > 0;
975
976        final boolean clearable = any && mNotificationData.hasClearableItems();
977
978        if (DEBUG) {
979            Slog.d(TAG, "setAreThereNotifications: N=" + mNotificationData.size()
980                    + " any=" + any + " clearable=" + clearable);
981        }
982
983        if (mClearButton.isShown()) {
984            if (clearable != (mClearButton.getAlpha() == 1.0f)) {
985                ObjectAnimator.ofFloat(mClearButton, "alpha",
986                        clearable ? 1.0f : 0.0f)
987                    .setDuration(250)
988                    .start();
989            }
990        } else {
991            mClearButton.setAlpha(clearable ? 1.0f : 0.0f);
992        }
993        mClearButton.setEnabled(clearable);
994
995        final View nlo = mStatusBarView.findViewById(R.id.notification_lights_out);
996        final boolean showDot = (any&&!areLightsOn());
997        if (showDot != (nlo.getAlpha() == 1.0f)) {
998            if (showDot) {
999                nlo.setAlpha(0f);
1000                nlo.setVisibility(View.VISIBLE);
1001            }
1002            nlo.animate()
1003                .alpha(showDot?1:0)
1004                .setDuration(showDot?750:250)
1005                .setInterpolator(new AccelerateInterpolator(2.0f))
1006                .setListener(showDot ? null : new AnimatorListenerAdapter() {
1007                    @Override
1008                    public void onAnimationEnd(Animator _a) {
1009                        nlo.setVisibility(View.GONE);
1010                    }
1011                })
1012                .start();
1013        }
1014    }
1015
1016    public void showClock(boolean show) {
1017        if (mStatusBarView == null) return;
1018        View clock = mStatusBarView.findViewById(R.id.clock);
1019        if (clock != null) {
1020            clock.setVisibility(show ? View.VISIBLE : View.GONE);
1021        }
1022    }
1023
1024    /**
1025     * State is one or more of the DISABLE constants from StatusBarManager.
1026     */
1027    public void disable(int state) {
1028        final int old = mDisabled;
1029        final int diff = state ^ old;
1030        mDisabled = state;
1031
1032        if (DEBUG) {
1033            Slog.d(TAG, String.format("disable: 0x%08x -> 0x%08x (diff: 0x%08x)",
1034                old, state, diff));
1035        }
1036
1037        StringBuilder flagdbg = new StringBuilder();
1038        flagdbg.append("disable: < ");
1039        flagdbg.append(((state & StatusBarManager.DISABLE_EXPAND) != 0) ? "EXPAND" : "expand");
1040        flagdbg.append(((diff  & StatusBarManager.DISABLE_EXPAND) != 0) ? "* " : " ");
1041        flagdbg.append(((state & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) ? "ICONS" : "icons");
1042        flagdbg.append(((diff  & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) ? "* " : " ");
1043        flagdbg.append(((state & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) ? "ALERTS" : "alerts");
1044        flagdbg.append(((diff  & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) ? "* " : " ");
1045        flagdbg.append(((state & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) ? "TICKER" : "ticker");
1046        flagdbg.append(((diff  & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) ? "* " : " ");
1047        flagdbg.append(((state & StatusBarManager.DISABLE_SYSTEM_INFO) != 0) ? "SYSTEM_INFO" : "system_info");
1048        flagdbg.append(((diff  & StatusBarManager.DISABLE_SYSTEM_INFO) != 0) ? "* " : " ");
1049        flagdbg.append(((state & StatusBarManager.DISABLE_BACK) != 0) ? "BACK" : "back");
1050        flagdbg.append(((diff  & StatusBarManager.DISABLE_BACK) != 0) ? "* " : " ");
1051        flagdbg.append(((state & StatusBarManager.DISABLE_HOME) != 0) ? "HOME" : "home");
1052        flagdbg.append(((diff  & StatusBarManager.DISABLE_HOME) != 0) ? "* " : " ");
1053        flagdbg.append(((state & StatusBarManager.DISABLE_RECENT) != 0) ? "RECENT" : "recent");
1054        flagdbg.append(((diff  & StatusBarManager.DISABLE_RECENT) != 0) ? "* " : " ");
1055        flagdbg.append(((state & StatusBarManager.DISABLE_CLOCK) != 0) ? "CLOCK" : "clock");
1056        flagdbg.append(((diff  & StatusBarManager.DISABLE_CLOCK) != 0) ? "* " : " ");
1057        flagdbg.append(">");
1058        Slog.d(TAG, flagdbg.toString());
1059
1060        if ((diff & StatusBarManager.DISABLE_CLOCK) != 0) {
1061            boolean show = (state & StatusBarManager.DISABLE_CLOCK) == 0;
1062            showClock(show);
1063        }
1064        if ((diff & StatusBarManager.DISABLE_EXPAND) != 0) {
1065            if ((state & StatusBarManager.DISABLE_EXPAND) != 0) {
1066                animateCollapse();
1067            }
1068        }
1069
1070        if ((diff & (StatusBarManager.DISABLE_HOME
1071                        | StatusBarManager.DISABLE_RECENT
1072                        | StatusBarManager.DISABLE_BACK)) != 0) {
1073            // the nav bar will take care of these
1074            if (mNavigationBarView != null) mNavigationBarView.setDisabledFlags(state);
1075
1076            if ((state & StatusBarManager.DISABLE_RECENT) != 0) {
1077                // close recents if it's visible
1078                mHandler.removeMessages(MSG_CLOSE_RECENTS_PANEL);
1079                mHandler.sendEmptyMessage(MSG_CLOSE_RECENTS_PANEL);
1080            }
1081        }
1082
1083        if ((diff & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
1084            if ((state & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
1085                if (mTicking) {
1086                    mTicker.halt();
1087                } else {
1088                    setNotificationIconVisibility(false, com.android.internal.R.anim.fade_out);
1089                }
1090            } else {
1091                if (!mExpandedVisible) {
1092                    setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
1093                }
1094            }
1095        } else if ((diff & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
1096            if (mTicking && (state & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
1097                mTicker.halt();
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                    animateExpand();
1116                    break;
1117                case MSG_CLOSE_NOTIFICATION_PANEL:
1118                    animateCollapse();
1119                    break;
1120                case MSG_SHOW_INTRUDER:
1121                    setIntruderAlertVisibility(true);
1122                    break;
1123                case MSG_HIDE_INTRUDER:
1124                    setIntruderAlertVisibility(false);
1125                    mCurrentlyIntrudingNotification = null;
1126                    break;
1127            }
1128        }
1129    }
1130
1131    final Runnable mAnimationCallback = new Runnable() {
1132        @Override
1133        public void run() {
1134            doAnimation(mChoreographer.getFrameTimeNanos());
1135        }
1136    };
1137
1138    final Runnable mRevealAnimationCallback = new Runnable() {
1139        @Override
1140        public void run() {
1141            doRevealAnimation(mChoreographer.getFrameTimeNanos());
1142        }
1143    };
1144
1145    View.OnFocusChangeListener mFocusChangeListener = new View.OnFocusChangeListener() {
1146        public void onFocusChange(View v, boolean hasFocus) {
1147            // Because 'v' is a ViewGroup, all its children will be (un)selected
1148            // too, which allows marqueeing to work.
1149            v.setSelected(hasFocus);
1150        }
1151    };
1152
1153    private void makeExpandedVisible() {
1154        if (SPEW) Slog.d(TAG, "Make expanded visible: expanded visible=" + mExpandedVisible);
1155        if (mExpandedVisible) {
1156            return;
1157        }
1158
1159        mExpandedVisible = true;
1160
1161        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
1162
1163        // Expand the window to encompass the full screen in anticipation of the drag.
1164        // This is only possible to do atomically because the status bar is at the top of the screen!
1165        WindowManager.LayoutParams lp = (WindowManager.LayoutParams) mStatusBarWindow.getLayoutParams();
1166        lp.flags &= (~WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
1167        lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
1168        final WindowManager wm = WindowManagerImpl.getDefault();
1169        wm.updateViewLayout(mStatusBarWindow, lp);
1170
1171        mStatusBarWindow.requestFocus(View.FOCUS_FORWARD);
1172
1173        visibilityChanged(true);
1174    }
1175
1176    public void animateExpand() {
1177        if (SPEW) Slog.d(TAG, "Animate expand: expanded=" + mExpanded);
1178        if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
1179            return ;
1180        }
1181        if (mExpanded) {
1182            return;
1183        }
1184
1185        prepareTracking(0, true);
1186        performFling(0, mSelfExpandVelocityPx, true);
1187    }
1188
1189    public void animateCollapse() {
1190        animateCollapse(false);
1191    }
1192
1193    public void animateCollapse(boolean excludeRecents) {
1194        animateCollapse(excludeRecents, 1.0f);
1195    }
1196
1197    public void animateCollapse(boolean excludeRecents, float velocityMultiplier) {
1198        if (SPEW) {
1199            Slog.d(TAG, "animateCollapse(): mExpanded=" + mExpanded
1200                    + " mExpandedVisible=" + mExpandedVisible
1201                    + " mExpanded=" + mExpanded
1202                    + " mAnimating=" + mAnimating
1203                    + " mAnimY=" + mAnimY
1204                    + " mAnimVel=" + mAnimVel);
1205        }
1206
1207        if (!excludeRecents) {
1208            mHandler.removeMessages(MSG_CLOSE_RECENTS_PANEL);
1209            mHandler.sendEmptyMessage(MSG_CLOSE_RECENTS_PANEL);
1210        }
1211
1212        if (!mExpandedVisible) {
1213            return;
1214        }
1215
1216        int y;
1217        if (mAnimating) {
1218            y = (int)mAnimY;
1219        } else {
1220            y = getExpandedViewMaxHeight()-1;
1221        }
1222        // Let the fling think that we're open so it goes in the right direction
1223        // and doesn't try to re-open the windowshade.
1224        mExpanded = true;
1225        prepareTracking(y, false);
1226        performFling(y, -mSelfCollapseVelocityPx*velocityMultiplier, true);
1227    }
1228
1229    void performExpand() {
1230        if (SPEW) Slog.d(TAG, "performExpand: mExpanded=" + mExpanded);
1231        if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
1232            return ;
1233        }
1234        if (mExpanded) {
1235            return;
1236        }
1237
1238        mExpanded = true;
1239        makeExpandedVisible();
1240        updateExpandedViewPos(EXPANDED_FULL_OPEN);
1241
1242        if (false) postStartTracing();
1243    }
1244
1245    void performCollapse() {
1246        if (SPEW) Slog.d(TAG, "performCollapse: mExpanded=" + mExpanded
1247                + " mExpandedVisible=" + mExpandedVisible);
1248
1249        if (!mExpandedVisible) {
1250            return;
1251        }
1252        mExpandedVisible = false;
1253        visibilityChanged(false);
1254        //mNotificationPanel.setVisibility(View.GONE);
1255
1256        // Shrink the window to the size of the status bar only
1257        WindowManager.LayoutParams lp = (WindowManager.LayoutParams) mStatusBarWindow.getLayoutParams();
1258        lp.height = getStatusBarHeight();
1259        lp.flags |= (WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
1260        final WindowManager wm = WindowManagerImpl.getDefault();
1261        wm.updateViewLayout(mStatusBarWindow, lp);
1262
1263        if ((mDisabled & StatusBarManager.DISABLE_NOTIFICATION_ICONS) == 0) {
1264            setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
1265        }
1266
1267        if (!mExpanded) {
1268            return;
1269        }
1270        mExpanded = false;
1271
1272        // Close any "App info" popups that might have snuck on-screen
1273        dismissPopups();
1274
1275        if (mPostCollapseCleanup != null) {
1276            mPostCollapseCleanup.run();
1277            mPostCollapseCleanup = null;
1278        }
1279    }
1280
1281    void resetLastAnimTime() {
1282        mAnimLastTimeNanos = System.nanoTime();
1283        if (SPEW) {
1284            Throwable t = new Throwable();
1285            t.fillInStackTrace();
1286            Slog.d(TAG, "resetting last anim time=" + mAnimLastTimeNanos, t);
1287        }
1288    }
1289
1290    void doAnimation(long frameTimeNanos) {
1291        if (mAnimating) {
1292            if (SPEW) Slog.d(TAG, "doAnimation dt=" + (frameTimeNanos - mAnimLastTimeNanos));
1293            if (SPEW) Slog.d(TAG, "doAnimation before mAnimY=" + mAnimY);
1294            incrementAnim(frameTimeNanos);
1295            if (SPEW) {
1296                Slog.d(TAG, "doAnimation after  mAnimY=" + mAnimY);
1297                Slog.d(TAG, "doAnimation expandedViewMax=" + getExpandedViewMaxHeight());
1298            }
1299
1300            if (mAnimY >= getExpandedViewMaxHeight()-1 && !mClosing) {
1301                if (SPEW) Slog.d(TAG, "Animation completed to expanded state.");
1302                mAnimating = false;
1303                updateExpandedViewPos(EXPANDED_FULL_OPEN);
1304                performExpand();
1305                return;
1306            }
1307
1308            if (mAnimY == 0 && mAnimAccel == 0 && mClosing) {
1309                if (SPEW) Slog.d(TAG, "Animation completed to collapsed state.");
1310                mAnimating = false;
1311                performCollapse();
1312                return;
1313            }
1314
1315            if (mAnimY < getStatusBarHeight() && mClosing) {
1316                // Draw one more frame with the bar positioned at the top of the screen
1317                // before ending the animation so that the user sees the bar in
1318                // its final position.  The call to performCollapse() causes a window
1319                // relayout which takes time and might cause the animation to skip
1320                // on the very last frame before the bar disappears if we did it now.
1321                mAnimY = 0;
1322                mAnimAccel = 0;
1323                mAnimVel = 0;
1324            }
1325
1326            updateExpandedViewPos((int)mAnimY);
1327            mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION,
1328                    mAnimationCallback, null);
1329        }
1330    }
1331
1332    void stopTracking() {
1333        mTracking = false;
1334        mPile.setLayerType(View.LAYER_TYPE_NONE, null);
1335        mVelocityTracker.recycle();
1336        mVelocityTracker = null;
1337        mCloseView.setPressed(false);
1338    }
1339
1340    void incrementAnim(long frameTimeNanos) {
1341        final long deltaNanos = Math.max(frameTimeNanos - mAnimLastTimeNanos, 0);
1342        final float t = deltaNanos * 0.000000001f;                  // ns -> s
1343        final float y = mAnimY;
1344        final float v = mAnimVel;                                   // px/s
1345        final float a = mAnimAccel;                                 // px/s/s
1346        mAnimY = y + (v*t) + (0.5f*a*t*t);                          // px
1347        mAnimVel = v + (a*t);                                       // px/s
1348        mAnimLastTimeNanos = frameTimeNanos;                        // ns
1349        //Slog.d(TAG, "y=" + y + " v=" + v + " a=" + a + " t=" + t + " mAnimY=" + mAnimY
1350        //        + " mAnimAccel=" + mAnimAccel);
1351    }
1352
1353    void doRevealAnimation(long frameTimeNanos) {
1354        if (SPEW) {
1355            Slog.d(TAG, "doRevealAnimation: dt=" + (frameTimeNanos - mAnimLastTimeNanos));
1356        }
1357        final int h = getCloseViewHeight() + getStatusBarHeight();
1358        if (mAnimatingReveal && mAnimating && mAnimY < h) {
1359            incrementAnim(frameTimeNanos);
1360            if (mAnimY >= h) {
1361                mAnimY = h;
1362                updateExpandedViewPos((int)mAnimY);
1363            } else {
1364                updateExpandedViewPos((int)mAnimY);
1365                mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION,
1366                        mRevealAnimationCallback, null);
1367            }
1368        }
1369    }
1370
1371    void prepareTracking(int y, boolean opening) {
1372        if (CHATTY) {
1373            Slog.d(TAG, "panel: beginning to track the user's touch, y=" + y + " opening=" + opening);
1374        }
1375
1376        mCloseView.setPressed(true);
1377
1378        mTracking = true;
1379        mPile.setLayerType(View.LAYER_TYPE_HARDWARE, null);
1380        mVelocityTracker = VelocityTracker.obtain();
1381        if (opening) {
1382            mAnimAccel = mExpandAccelPx;
1383            mAnimVel = mFlingExpandMinVelocityPx;
1384            mAnimY = getStatusBarHeight();
1385            updateExpandedViewPos((int)mAnimY);
1386            mAnimating = true;
1387            mAnimatingReveal = true;
1388            resetLastAnimTime();
1389            mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION,
1390                    mAnimationCallback, null);
1391            mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION,
1392                    mRevealAnimationCallback, null);
1393            mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION,
1394                    mRevealAnimationCallback, null);
1395            makeExpandedVisible();
1396        } else {
1397            // it's open, close it?
1398            if (mAnimating) {
1399                mAnimating = false;
1400                mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION,
1401                        mAnimationCallback, null);
1402            }
1403            updateExpandedViewPos(y + mViewDelta);
1404        }
1405    }
1406
1407    void performFling(int y, float vel, boolean always) {
1408        if (CHATTY) {
1409            Slog.d(TAG, "panel: will fling, y=" + y + " vel=" + vel);
1410        }
1411
1412        mAnimatingReveal = false;
1413
1414        mAnimY = y;
1415        mAnimVel = vel;
1416
1417        //Slog.d(TAG, "starting with mAnimY=" + mAnimY + " mAnimVel=" + mAnimVel);
1418
1419        if (mExpanded) {
1420            if (!always && (
1421                    vel > mFlingCollapseMinVelocityPx
1422                    || (y > (getExpandedViewMaxHeight()*(1f-mCollapseMinDisplayFraction)) &&
1423                        vel > -mFlingExpandMinVelocityPx))) {
1424                // We are expanded, but they didn't move sufficiently to cause
1425                // us to retract.  Animate back to the expanded position.
1426                mAnimAccel = mExpandAccelPx;
1427                if (vel < 0) {
1428                    mAnimVel = 0;
1429                }
1430            }
1431            else {
1432                // We are expanded and are now going to animate away.
1433                mAnimAccel = -mCollapseAccelPx;
1434                if (vel > 0) {
1435                    mAnimVel = 0;
1436                }
1437            }
1438        } else {
1439            if (always || (
1440                    vel > mFlingExpandMinVelocityPx
1441                    || (y > (getExpandedViewMaxHeight()*(1f-mExpandMinDisplayFraction)) &&
1442                        vel > -mFlingCollapseMinVelocityPx))) {
1443                // We are collapsed, and they moved enough to allow us to
1444                // expand.  Animate in the notifications.
1445                mAnimAccel = mExpandAccelPx;
1446                if (vel < 0) {
1447                    mAnimVel = 0;
1448                }
1449            }
1450            else {
1451                // We are collapsed, but they didn't move sufficiently to cause
1452                // us to retract.  Animate back to the collapsed position.
1453                mAnimAccel = -mCollapseAccelPx;
1454                if (vel > 0) {
1455                    mAnimVel = 0;
1456                }
1457            }
1458        }
1459        //Slog.d(TAG, "mAnimY=" + mAnimY + " mAnimVel=" + mAnimVel
1460        //        + " mAnimAccel=" + mAnimAccel);
1461
1462        resetLastAnimTime();
1463        mAnimating = true;
1464        mClosing = mAnimAccel < 0;
1465
1466        mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION,
1467                mAnimationCallback, null);
1468        mChoreographer.removeCallbacks(Choreographer.CALLBACK_ANIMATION,
1469                mRevealAnimationCallback, null);
1470        mChoreographer.postCallback(Choreographer.CALLBACK_ANIMATION,
1471                mAnimationCallback, null);
1472        stopTracking();
1473    }
1474
1475    boolean interceptTouchEvent(MotionEvent event) {
1476        if (SPEW) {
1477            Slog.d(TAG, "Touch: rawY=" + event.getRawY() + " event=" + event + " mDisabled="
1478                + mDisabled);
1479        } else if (CHATTY) {
1480            if (event.getAction() != MotionEvent.ACTION_MOVE) {
1481                Slog.d(TAG, String.format(
1482                            "panel: %s at (%f, %f) mDisabled=0x%08x",
1483                            MotionEvent.actionToString(event.getAction()),
1484                            event.getRawX(), event.getRawY(), mDisabled));
1485            }
1486        }
1487
1488        if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
1489            return false;
1490        }
1491
1492        final int action = event.getAction();
1493        final int statusBarSize = getStatusBarHeight();
1494        final int hitSize = statusBarSize*2;
1495        final int y = (int)event.getRawY();
1496        if (action == MotionEvent.ACTION_DOWN) {
1497            if (!areLightsOn()) {
1498                setLightsOn(true);
1499            }
1500
1501            if (!mExpanded) {
1502                mViewDelta = statusBarSize - y;
1503            } else {
1504                mCloseView.getLocationOnScreen(mAbsPos);
1505                mViewDelta = mAbsPos[1] + statusBarSize + getCloseViewHeight() - y; // XXX: not closeViewHeight, but paddingBottom from the 9patch
1506            }
1507            if ((!mExpanded && y < hitSize) ||
1508                    // @@ add taps outside the panel if it's not full-screen
1509                    (mExpanded && y > (getExpandedViewMaxHeight()-hitSize))) {
1510
1511                // We drop events at the edge of the screen to make the windowshade come
1512                // down by accident less, especially when pushing open a device with a keyboard
1513                // that rotates (like g1 and droid)
1514                int x = (int)event.getRawX();
1515                final int edgeBorder = mEdgeBorder;
1516                if (x >= edgeBorder && x < mDisplayMetrics.widthPixels - edgeBorder) {
1517                    prepareTracking(y, !mExpanded);// opening if we're not already fully visible
1518                    trackMovement(event);
1519                }
1520            }
1521        } else if (mTracking) {
1522            trackMovement(event);
1523            final int minY = statusBarSize + getCloseViewHeight();
1524            if (action == MotionEvent.ACTION_MOVE) {
1525                if (mAnimatingReveal && (y + mViewDelta) < minY) {
1526                    // nothing
1527                } else  {
1528                    mAnimatingReveal = false;
1529                    updateExpandedViewPos(y + mViewDelta);
1530                }
1531            } else if (action == MotionEvent.ACTION_UP
1532                    || action == MotionEvent.ACTION_CANCEL) {
1533                mVelocityTracker.computeCurrentVelocity(1000);
1534
1535                float yVel = mVelocityTracker.getYVelocity();
1536                boolean negative = yVel < 0;
1537
1538                float xVel = mVelocityTracker.getXVelocity();
1539                if (xVel < 0) {
1540                    xVel = -xVel;
1541                }
1542                if (xVel > mFlingGestureMaxXVelocityPx) {
1543                    xVel = mFlingGestureMaxXVelocityPx; // limit how much we care about the x axis
1544                }
1545
1546                float vel = (float)Math.hypot(yVel, xVel);
1547                if (negative) {
1548                    vel = -vel;
1549                }
1550
1551                if (CHATTY) {
1552                    Slog.d(TAG, String.format("gesture: vraw=(%f,%f) vnorm=(%f,%f) vlinear=%f",
1553                        mVelocityTracker.getXVelocity(),
1554                        mVelocityTracker.getYVelocity(),
1555                        xVel, yVel,
1556                        vel));
1557                }
1558
1559                performFling(y + mViewDelta, vel, false);
1560            }
1561
1562        }
1563        return false;
1564    }
1565
1566    private void trackMovement(MotionEvent event) {
1567        // Add movement to velocity tracker using raw screen X and Y coordinates instead
1568        // of window coordinates because the window frame may be moving at the same time.
1569        float deltaX = event.getRawX() - event.getX();
1570        float deltaY = event.getRawY() - event.getY();
1571        event.offsetLocation(deltaX, deltaY);
1572        mVelocityTracker.addMovement(event);
1573        event.offsetLocation(-deltaX, -deltaY);
1574    }
1575
1576    @Override // CommandQueue
1577    public void setNavigationIconHints(int hints) {
1578        if (hints == mNavigationIconHints) return;
1579
1580        mNavigationIconHints = hints;
1581
1582        if (mNavigationBarView != null) {
1583            mNavigationBarView.setNavigationIconHints(hints);
1584        }
1585    }
1586
1587    @Override // CommandQueue
1588    public void setSystemUiVisibility(int vis, int mask) {
1589        final int oldVal = mSystemUiVisibility;
1590        final int newVal = (oldVal&~mask) | (vis&mask);
1591        final int diff = newVal ^ oldVal;
1592
1593        if (diff != 0) {
1594            mSystemUiVisibility = newVal;
1595
1596            if (0 != (diff & View.SYSTEM_UI_FLAG_LOW_PROFILE)) {
1597                final boolean lightsOut = (0 != (vis & View.SYSTEM_UI_FLAG_LOW_PROFILE));
1598                if (lightsOut) {
1599                    animateCollapse();
1600                    if (mTicking) {
1601                        mTicker.halt();
1602                    }
1603                }
1604
1605                if (mNavigationBarView != null) {
1606                    mNavigationBarView.setLowProfile(lightsOut);
1607                }
1608
1609                setStatusBarLowProfile(lightsOut);
1610            }
1611
1612            notifyUiVisibilityChanged();
1613        }
1614    }
1615
1616    private void setStatusBarLowProfile(boolean lightsOut) {
1617        if (mLightsOutAnimation == null) {
1618            final View notifications = mStatusBarView.findViewById(R.id.notification_icon_area);
1619            final View systemIcons = mStatusBarView.findViewById(R.id.statusIcons);
1620            final View signal = mStatusBarView.findViewById(R.id.signal_cluster);
1621            final View battery = mStatusBarView.findViewById(R.id.battery);
1622            final View clock = mStatusBarView.findViewById(R.id.clock);
1623
1624            mLightsOutAnimation = new AnimatorSet();
1625            mLightsOutAnimation.playTogether(
1626                    ObjectAnimator.ofFloat(notifications, View.ALPHA, 0),
1627                    ObjectAnimator.ofFloat(systemIcons, View.ALPHA, 0),
1628                    ObjectAnimator.ofFloat(signal, View.ALPHA, 0),
1629                    ObjectAnimator.ofFloat(battery, View.ALPHA, 0.5f),
1630                    ObjectAnimator.ofFloat(clock, View.ALPHA, 0.5f)
1631                );
1632            mLightsOutAnimation.setDuration(750);
1633
1634            mLightsOnAnimation = new AnimatorSet();
1635            mLightsOnAnimation.playTogether(
1636                    ObjectAnimator.ofFloat(notifications, View.ALPHA, 1),
1637                    ObjectAnimator.ofFloat(systemIcons, View.ALPHA, 1),
1638                    ObjectAnimator.ofFloat(signal, View.ALPHA, 1),
1639                    ObjectAnimator.ofFloat(battery, View.ALPHA, 1),
1640                    ObjectAnimator.ofFloat(clock, View.ALPHA, 1)
1641                );
1642            mLightsOnAnimation.setDuration(250);
1643        }
1644
1645        mLightsOutAnimation.cancel();
1646        mLightsOnAnimation.cancel();
1647
1648        final Animator a = lightsOut ? mLightsOutAnimation : mLightsOnAnimation;
1649        a.start();
1650
1651        setAreThereNotifications();
1652    }
1653
1654    private boolean areLightsOn() {
1655        return 0 == (mSystemUiVisibility & View.SYSTEM_UI_FLAG_LOW_PROFILE);
1656    }
1657
1658    public void setLightsOn(boolean on) {
1659        Log.v(TAG, "setLightsOn(" + on + ")");
1660        if (on) {
1661            setSystemUiVisibility(0, View.SYSTEM_UI_FLAG_LOW_PROFILE);
1662        } else {
1663            setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE, View.SYSTEM_UI_FLAG_LOW_PROFILE);
1664        }
1665    }
1666
1667    private void notifyUiVisibilityChanged() {
1668        try {
1669            mWindowManager.statusBarVisibilityChanged(mSystemUiVisibility);
1670        } catch (RemoteException ex) {
1671        }
1672    }
1673
1674    public void topAppWindowChanged(boolean showMenu) {
1675        if (DEBUG) {
1676            Slog.d(TAG, (showMenu?"showing":"hiding") + " the MENU button");
1677        }
1678        if (mNavigationBarView != null) {
1679            mNavigationBarView.setMenuVisibility(showMenu);
1680        }
1681
1682        // See above re: lights-out policy for legacy apps.
1683        if (showMenu) setLightsOn(true);
1684    }
1685
1686    @Override
1687    public void setImeWindowStatus(IBinder token, int vis, int backDisposition) {
1688        boolean altBack = (backDisposition == InputMethodService.BACK_DISPOSITION_WILL_DISMISS)
1689            || ((vis & InputMethodService.IME_VISIBLE) != 0);
1690
1691        mCommandQueue.setNavigationIconHints(
1692                altBack ? (mNavigationIconHints | StatusBarManager.NAVIGATION_HINT_BACK_ALT)
1693                        : (mNavigationIconHints & ~StatusBarManager.NAVIGATION_HINT_BACK_ALT));
1694    }
1695
1696    @Override
1697    public void setHardKeyboardStatus(boolean available, boolean enabled) { }
1698
1699    private class NotificationClicker implements View.OnClickListener {
1700        private PendingIntent mIntent;
1701        private String mPkg;
1702        private String mTag;
1703        private int mId;
1704
1705        NotificationClicker(PendingIntent intent, String pkg, String tag, int id) {
1706            mIntent = intent;
1707            mPkg = pkg;
1708            mTag = tag;
1709            mId = id;
1710        }
1711
1712        public void onClick(View v) {
1713            try {
1714                // The intent we are sending is for the application, which
1715                // won't have permission to immediately start an activity after
1716                // the user switches to home.  We know it is safe to do at this
1717                // point, so make sure new activity switches are now allowed.
1718                ActivityManagerNative.getDefault().resumeAppSwitches();
1719                // Also, notifications can be launched from the lock screen,
1720                // so dismiss the lock screen when the activity starts.
1721                ActivityManagerNative.getDefault().dismissKeyguardOnNextActivity();
1722            } catch (RemoteException e) {
1723            }
1724
1725            if (mIntent != null) {
1726                int[] pos = new int[2];
1727                v.getLocationOnScreen(pos);
1728                Intent overlay = new Intent();
1729                overlay.setSourceBounds(
1730                        new Rect(pos[0], pos[1], pos[0]+v.getWidth(), pos[1]+v.getHeight()));
1731                try {
1732                    mIntent.send(mContext, 0, overlay);
1733                } catch (PendingIntent.CanceledException e) {
1734                    // the stack trace isn't very helpful here.  Just log the exception message.
1735                    Slog.w(TAG, "Sending contentIntent failed: " + e);
1736                }
1737
1738                KeyguardManager kgm =
1739                    (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
1740                if (kgm != null) kgm.exitKeyguardSecurely(null);
1741            }
1742
1743            try {
1744                mBarService.onNotificationClick(mPkg, mTag, mId);
1745            } catch (RemoteException ex) {
1746                // system process is dead if we're here.
1747            }
1748
1749            // close the shade if it was open
1750            animateCollapse();
1751
1752            // If this click was on the intruder alert, hide that instead
1753            mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
1754        }
1755    }
1756
1757    private void tick(StatusBarNotification n) {
1758        // no ticking in lights-out mode
1759        if (!areLightsOn()) return;
1760
1761        // Show the ticker if one is requested. Also don't do this
1762        // until status bar window is attached to the window manager,
1763        // because...  well, what's the point otherwise?  And trying to
1764        // run a ticker without being attached will crash!
1765        if (n.notification.tickerText != null && mStatusBarWindow.getWindowToken() != null) {
1766            if (0 == (mDisabled & (StatusBarManager.DISABLE_NOTIFICATION_ICONS
1767                            | StatusBarManager.DISABLE_NOTIFICATION_TICKER))) {
1768                mTicker.addEntry(n);
1769            }
1770        }
1771    }
1772
1773    /**
1774     * Cancel this notification and tell the StatusBarManagerService / NotificationManagerService
1775     * about the failure.
1776     *
1777     * WARNING: this will call back into us.  Don't hold any locks.
1778     */
1779    void handleNotificationError(IBinder key, StatusBarNotification n, String message) {
1780        removeNotification(key);
1781        try {
1782            mBarService.onNotificationError(n.pkg, n.tag, n.id, n.uid, n.initialPid, message);
1783        } catch (RemoteException ex) {
1784            // The end is nigh.
1785        }
1786    }
1787
1788    private class MyTicker extends Ticker {
1789        MyTicker(Context context, View sb) {
1790            super(context, sb);
1791        }
1792
1793        @Override
1794        public void tickerStarting() {
1795            mTicking = true;
1796            mIcons.setVisibility(View.GONE);
1797            mTickerView.setVisibility(View.VISIBLE);
1798            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_up_in, null));
1799            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.push_up_out, null));
1800        }
1801
1802        @Override
1803        public void tickerDone() {
1804            mIcons.setVisibility(View.VISIBLE);
1805            mTickerView.setVisibility(View.GONE);
1806            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.push_down_in, null));
1807            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_down_out,
1808                        mTickingDoneListener));
1809        }
1810
1811        public void tickerHalting() {
1812            mIcons.setVisibility(View.VISIBLE);
1813            mTickerView.setVisibility(View.GONE);
1814            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.fade_in, null));
1815            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.fade_out,
1816                        mTickingDoneListener));
1817        }
1818    }
1819
1820    Animation.AnimationListener mTickingDoneListener = new Animation.AnimationListener() {;
1821        public void onAnimationEnd(Animation animation) {
1822            mTicking = false;
1823        }
1824        public void onAnimationRepeat(Animation animation) {
1825        }
1826        public void onAnimationStart(Animation animation) {
1827        }
1828    };
1829
1830    private Animation loadAnim(int id, Animation.AnimationListener listener) {
1831        Animation anim = AnimationUtils.loadAnimation(mContext, id);
1832        if (listener != null) {
1833            anim.setAnimationListener(listener);
1834        }
1835        return anim;
1836    }
1837
1838    public static String viewInfo(View v) {
1839        return "[(" + v.getLeft() + "," + v.getTop() + ")(" + v.getRight() + "," + v.getBottom()
1840                + ") " + v.getWidth() + "x" + v.getHeight() + "]";
1841    }
1842
1843    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1844        synchronized (mQueueLock) {
1845            pw.println("Current Status Bar state:");
1846            pw.println("  mExpanded=" + mExpanded
1847                    + ", mExpandedVisible=" + mExpandedVisible);
1848            pw.println("  mTicking=" + mTicking);
1849            pw.println("  mTracking=" + mTracking);
1850            pw.println("  mAnimating=" + mAnimating
1851                    + ", mAnimY=" + mAnimY + ", mAnimVel=" + mAnimVel
1852                    + ", mAnimAccel=" + mAnimAccel);
1853            pw.println("  mAnimLastTimeNanos=" + mAnimLastTimeNanos);
1854            pw.println("  mAnimatingReveal=" + mAnimatingReveal
1855                    + " mViewDelta=" + mViewDelta);
1856            pw.println("  mDisplayMetrics=" + mDisplayMetrics);
1857            pw.println("  mPile: " + viewInfo(mPile));
1858            pw.println("  mCloseView: " + viewInfo(mCloseView));
1859            pw.println("  mTickerView: " + viewInfo(mTickerView));
1860            pw.println("  mScrollView: " + viewInfo(mScrollView)
1861                    + " scroll " + mScrollView.getScrollX() + "," + mScrollView.getScrollY());
1862        }
1863
1864        pw.print("  mNavigationBarView=");
1865        if (mNavigationBarView == null) {
1866            pw.println("null");
1867        } else {
1868            mNavigationBarView.dump(fd, pw, args);
1869        }
1870
1871        if (DUMPTRUCK) {
1872            synchronized (mNotificationData) {
1873                int N = mNotificationData.size();
1874                pw.println("  notification icons: " + N);
1875                for (int i=0; i<N; i++) {
1876                    NotificationData.Entry e = mNotificationData.get(i);
1877                    pw.println("    [" + i + "] key=" + e.key + " icon=" + e.icon);
1878                    StatusBarNotification n = e.notification;
1879                    pw.println("         pkg=" + n.pkg + " id=" + n.id + " score=" + n.score);
1880                    pw.println("         notification=" + n.notification);
1881                    pw.println("         tickerText=\"" + n.notification.tickerText + "\"");
1882                }
1883            }
1884
1885            int N = mStatusIcons.getChildCount();
1886            pw.println("  system icons: " + N);
1887            for (int i=0; i<N; i++) {
1888                StatusBarIconView ic = (StatusBarIconView) mStatusIcons.getChildAt(i);
1889                pw.println("    [" + i + "] icon=" + ic);
1890            }
1891
1892            if (false) {
1893                pw.println("see the logcat for a dump of the views we have created.");
1894                // must happen on ui thread
1895                mHandler.post(new Runnable() {
1896                        public void run() {
1897                            mStatusBarView.getLocationOnScreen(mAbsPos);
1898                            Slog.d(TAG, "mStatusBarView: ----- (" + mAbsPos[0] + "," + mAbsPos[1]
1899                                    + ") " + mStatusBarView.getWidth() + "x"
1900                                    + getStatusBarHeight());
1901                            mStatusBarView.debug();
1902                        }
1903                    });
1904            }
1905        }
1906
1907        mNetworkController.dump(fd, pw, args);
1908    }
1909
1910    @Override
1911    public void createAndAddWindows() {
1912        addStatusBarWindow();
1913    }
1914
1915    private void addStatusBarWindow() {
1916        // Put up the view
1917        final int height = getStatusBarHeight();
1918
1919        // Now that the status bar window encompasses the sliding panel and its
1920        // translucent backdrop, the entire thing is made TRANSLUCENT and is
1921        // hardware-accelerated.
1922        final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
1923                ViewGroup.LayoutParams.MATCH_PARENT,
1924                height,
1925                WindowManager.LayoutParams.TYPE_STATUS_BAR,
1926                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
1927                    | WindowManager.LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING
1928                    | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
1929                PixelFormat.TRANSLUCENT);
1930
1931        if (ActivityManager.isHighEndGfx(mDisplay)) {
1932            lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
1933        }
1934
1935        lp.gravity = getStatusBarGravity();
1936        lp.setTitle("StatusBar");
1937        lp.packageName = mContext.getPackageName();
1938
1939        makeStatusBarView();
1940        WindowManagerImpl.getDefault().addView(mStatusBarWindow, lp);
1941    }
1942
1943    void setNotificationIconVisibility(boolean visible, int anim) {
1944        int old = mNotificationIcons.getVisibility();
1945        int v = visible ? View.VISIBLE : View.INVISIBLE;
1946        if (old != v) {
1947            mNotificationIcons.setVisibility(v);
1948            mNotificationIcons.startAnimation(loadAnim(anim, null));
1949        }
1950    }
1951
1952    void updateExpandedInvisiblePosition() {
1953        mTrackingPosition = -mDisplayMetrics.heightPixels;
1954    }
1955
1956    static final float saturate(float a) {
1957        return a < 0f ? 0f : (a > 1f ? 1f : a);
1958    }
1959
1960    int getExpandedViewMaxHeight() {
1961        return mDisplayMetrics.heightPixels - mNotificationPanelMarginBottomPx;
1962    }
1963
1964    void updateExpandedViewPos(int expandedPosition) {
1965        if (SPEW) {
1966            Slog.d(TAG, "updateExpandedViewPos before expandedPosition=" + expandedPosition
1967                    //+ " mTrackingParams.y=" + ((mTrackingParams == null) ? "?" : mTrackingParams.y)
1968                    + " mTrackingPosition=" + mTrackingPosition
1969                    + " gravity=" + mNotificationPanelGravity);
1970        }
1971
1972        int panelh = 0;
1973        final boolean portrait = mDisplayMetrics.heightPixels > mDisplayMetrics.widthPixels;
1974
1975        final int disph = getExpandedViewMaxHeight();
1976
1977        // If the expanded view is not visible, make sure they're still off screen.
1978        // Maybe the view was resized.
1979        if (!mExpandedVisible) {
1980            updateExpandedInvisiblePosition();
1981            return;
1982        }
1983
1984        // tracking view...
1985        int pos;
1986        if (expandedPosition == EXPANDED_FULL_OPEN) {
1987            panelh = disph;
1988        }
1989        else if (expandedPosition == EXPANDED_LEAVE_ALONE) {
1990            panelh = mTrackingPosition;
1991        }
1992        else {
1993            if (expandedPosition <= disph) {
1994                panelh = expandedPosition;
1995            } else {
1996                panelh = disph;
1997            }
1998        }
1999
2000        // catch orientation changes and other peculiar cases
2001        if (panelh > disph || (panelh < disph && !mTracking && !mAnimating)) {
2002            panelh = disph;
2003        } else if (panelh < 0) {
2004            panelh = 0;
2005        }
2006
2007        mTrackingPosition = panelh;
2008
2009        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mNotificationPanel.getLayoutParams();
2010        lp.height = panelh;
2011        lp.gravity = mNotificationPanelGravity;
2012        lp.leftMargin = mNotificationPanelMarginLeftPx;
2013        if (SPEW) {
2014            Slog.v(TAG, "updated cropView height=" + panelh + " grav=" + lp.gravity);
2015        }
2016        mNotificationPanel.setLayoutParams(lp);
2017
2018        if (DIM_BEHIND_EXPANDED_PANEL && ActivityManager.isHighEndGfx(mDisplay)) {
2019            // woo, special effects
2020            final int barh = getCloseViewHeight() + getStatusBarHeight();
2021            final float frac = saturate((float)(panelh - barh) / (disph - barh));
2022            final int color = ((int)(0xB0 * Math.sin(frac * 1.57f))) << 24;
2023            mStatusBarWindow.setBackgroundColor(color);
2024        }
2025    }
2026
2027    void updateDisplaySize() {
2028        mDisplay.getMetrics(mDisplayMetrics);
2029    }
2030
2031    void performDisableActions(int net) {
2032        int old = mDisabled;
2033        int diff = net ^ old;
2034        mDisabled = net;
2035
2036        // act accordingly
2037        if ((diff & StatusBarManager.DISABLE_EXPAND) != 0) {
2038            if ((net & StatusBarManager.DISABLE_EXPAND) != 0) {
2039                Slog.d(TAG, "DISABLE_EXPAND: yes");
2040                animateCollapse();
2041            }
2042        }
2043        if ((diff & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
2044            if ((net & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
2045                Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: yes");
2046                if (mTicking) {
2047                    mNotificationIcons.setVisibility(View.INVISIBLE);
2048                    mTicker.halt();
2049                } else {
2050                    setNotificationIconVisibility(false, com.android.internal.R.anim.fade_out);
2051                }
2052            } else {
2053                Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: no");
2054                if (!mExpandedVisible) {
2055                    setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
2056                }
2057            }
2058        } else if ((diff & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
2059            if (mTicking && (net & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
2060                mTicker.halt();
2061            }
2062        }
2063    }
2064
2065    private View.OnClickListener mClearButtonListener = new View.OnClickListener() {
2066        final int mini(int a, int b) {
2067            return (b>a?a:b);
2068        }
2069        public void onClick(View v) {
2070            synchronized (mNotificationData) {
2071                // animate-swipe all dismissable notifications, then animate the shade closed
2072                int numChildren = mPile.getChildCount();
2073
2074                int scrollTop = mScrollView.getScrollY();
2075                int scrollBottom = scrollTop + mScrollView.getHeight();
2076                final ArrayList<View> snapshot = new ArrayList<View>(numChildren);
2077                for (int i=0; i<numChildren; i++) {
2078                    final View child = mPile.getChildAt(i);
2079                    if (mPile.canChildBeDismissed(child) && child.getBottom() > scrollTop &&
2080                            child.getTop() < scrollBottom) {
2081                        snapshot.add(child);
2082                    }
2083                }
2084                if (snapshot.isEmpty()) {
2085                    animateCollapse(false);
2086                    return;
2087                }
2088                new Thread(new Runnable() {
2089                    @Override
2090                    public void run() {
2091                        // Decrease the delay for every row we animate to give the sense of
2092                        // accelerating the swipes
2093                        final int ROW_DELAY_DECREMENT = 10;
2094                        int currentDelay = 140;
2095                        int totalDelay = 0;
2096
2097                        // Set the shade-animating state to avoid doing other work during
2098                        // all of these animations. In particular, avoid layout and
2099                        // redrawing when collapsing the shade.
2100                        mPile.setViewRemoval(false);
2101
2102                        mPostCollapseCleanup = new Runnable() {
2103                            @Override
2104                            public void run() {
2105                                try {
2106                                    mPile.setViewRemoval(true);
2107                                    mBarService.onClearAllNotifications();
2108                                } catch (Exception ex) { }
2109                            }
2110                        };
2111
2112                        View sampleView = snapshot.get(0);
2113                        int width = sampleView.getWidth();
2114                        final int velocity = width * 8; // 1000/8 = 125 ms duration
2115                        for (final View _v : snapshot) {
2116                            mHandler.postDelayed(new Runnable() {
2117                                @Override
2118                                public void run() {
2119                                    mPile.dismissRowAnimated(_v, velocity);
2120                                }
2121                            }, totalDelay);
2122                            currentDelay = Math.max(50, currentDelay - ROW_DELAY_DECREMENT);
2123                            totalDelay += currentDelay;
2124                        }
2125                        // Delay the collapse animation until after all swipe animations have
2126                        // finished. Provide some buffer because there may be some extra delay
2127                        // before actually starting each swipe animation. Ideally, we'd
2128                        // synchronize the end of those animations with the start of the collaps
2129                        // exactly.
2130                        mHandler.postDelayed(new Runnable() {
2131                            @Override
2132                            public void run() {
2133                                animateCollapse(false);
2134                            }
2135                        }, totalDelay + 225);
2136                    }
2137                }).start();
2138            }
2139        }
2140    };
2141
2142    private View.OnClickListener mSettingsButtonListener = new View.OnClickListener() {
2143        public void onClick(View v) {
2144            try {
2145                // Dismiss the lock screen when Settings starts.
2146                ActivityManagerNative.getDefault().dismissKeyguardOnNextActivity();
2147            } catch (RemoteException e) {
2148            }
2149            v.getContext().startActivity(new Intent(Settings.ACTION_SETTINGS)
2150                    .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
2151            animateCollapse();
2152        }
2153    };
2154
2155    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
2156        public void onReceive(Context context, Intent intent) {
2157            String action = intent.getAction();
2158            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)
2159                    || Intent.ACTION_SCREEN_OFF.equals(action)) {
2160                boolean excludeRecents = false;
2161                if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
2162                    String reason = intent.getStringExtra("reason");
2163                    if (reason != null) {
2164                        excludeRecents = reason.equals("recentapps");
2165                    }
2166                }
2167                animateCollapse(excludeRecents);
2168            }
2169            else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
2170                updateResources();
2171                repositionNavigationBar();
2172                updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
2173            }
2174        }
2175    };
2176
2177    private void setIntruderAlertVisibility(boolean vis) {
2178        if (!ENABLE_INTRUDERS) return;
2179        if (DEBUG) {
2180            Slog.v(TAG, (vis ? "showing" : "hiding") + " intruder alert window");
2181        }
2182        mIntruderAlertView.setVisibility(vis ? View.VISIBLE : View.GONE);
2183    }
2184
2185    public void dismissIntruder() {
2186        if (mCurrentlyIntrudingNotification == null) return;
2187
2188        try {
2189            mBarService.onNotificationClear(
2190                    mCurrentlyIntrudingNotification.pkg,
2191                    mCurrentlyIntrudingNotification.tag,
2192                    mCurrentlyIntrudingNotification.id);
2193        } catch (android.os.RemoteException ex) {
2194            // oh well
2195        }
2196    }
2197
2198    /**
2199     * Reload some of our resources when the configuration changes.
2200     *
2201     * We don't reload everything when the configuration changes -- we probably
2202     * should, but getting that smooth is tough.  Someday we'll fix that.  In the
2203     * meantime, just update the things that we know change.
2204     */
2205    void updateResources() {
2206        final Context context = mContext;
2207        final Resources res = context.getResources();
2208
2209        if (mClearButton instanceof TextView) {
2210            ((TextView)mClearButton).setText(context.getText(R.string.status_bar_clear_all_button));
2211        }
2212        loadDimens();
2213    }
2214
2215    protected void loadDimens() {
2216        final Resources res = mContext.getResources();
2217
2218        mNaturalBarHeight = res.getDimensionPixelSize(
2219                com.android.internal.R.dimen.status_bar_height);
2220
2221        int newIconSize = res.getDimensionPixelSize(
2222            com.android.internal.R.dimen.status_bar_icon_size);
2223        int newIconHPadding = res.getDimensionPixelSize(
2224            R.dimen.status_bar_icon_padding);
2225
2226        if (newIconHPadding != mIconHPadding || newIconSize != mIconSize) {
2227//            Slog.d(TAG, "size=" + newIconSize + " padding=" + newIconHPadding);
2228            mIconHPadding = newIconHPadding;
2229            mIconSize = newIconSize;
2230            //reloadAllNotificationIcons(); // reload the tray
2231        }
2232
2233        mEdgeBorder = res.getDimensionPixelSize(R.dimen.status_bar_edge_ignore);
2234
2235        mSelfExpandVelocityPx = res.getDimension(R.dimen.self_expand_velocity);
2236        mSelfCollapseVelocityPx = res.getDimension(R.dimen.self_collapse_velocity);
2237        mFlingExpandMinVelocityPx = res.getDimension(R.dimen.fling_expand_min_velocity);
2238        mFlingCollapseMinVelocityPx = res.getDimension(R.dimen.fling_collapse_min_velocity);
2239
2240        mCollapseMinDisplayFraction = res.getFraction(R.dimen.collapse_min_display_fraction, 1, 1);
2241        mExpandMinDisplayFraction = res.getFraction(R.dimen.expand_min_display_fraction, 1, 1);
2242
2243        mExpandAccelPx = res.getDimension(R.dimen.expand_accel);
2244        mCollapseAccelPx = res.getDimension(R.dimen.collapse_accel);
2245
2246        mFlingGestureMaxXVelocityPx = res.getDimension(R.dimen.fling_gesture_max_x_velocity);
2247
2248        mNotificationPanelMarginBottomPx
2249            = (int) res.getDimension(R.dimen.notification_panel_margin_bottom);
2250        mNotificationPanelMarginLeftPx
2251            = (int) res.getDimension(R.dimen.notification_panel_margin_left);
2252        mNotificationPanelGravity = res.getInteger(R.integer.notification_panel_layout_gravity);
2253        if (mNotificationPanelGravity <= 0) {
2254            mNotificationPanelGravity = Gravity.CENTER_VERTICAL | Gravity.TOP;
2255        }
2256
2257        if (false) Slog.v(TAG, "updateResources");
2258    }
2259
2260    //
2261    // tracing
2262    //
2263
2264    void postStartTracing() {
2265        mHandler.postDelayed(mStartTracing, 3000);
2266    }
2267
2268    void vibrate() {
2269        android.os.Vibrator vib = (android.os.Vibrator)mContext.getSystemService(
2270                Context.VIBRATOR_SERVICE);
2271        vib.vibrate(250);
2272    }
2273
2274    Runnable mStartTracing = new Runnable() {
2275        public void run() {
2276            vibrate();
2277            SystemClock.sleep(250);
2278            Slog.d(TAG, "startTracing");
2279            android.os.Debug.startMethodTracing("/data/statusbar-traces/trace");
2280            mHandler.postDelayed(mStopTracing, 10000);
2281        }
2282    };
2283
2284    Runnable mStopTracing = new Runnable() {
2285        public void run() {
2286            android.os.Debug.stopMethodTracing();
2287            Slog.d(TAG, "stopTracing");
2288            vibrate();
2289        }
2290    };
2291}
2292
2293