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