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