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