PhoneStatusBar.java revision 84920cc56e4cd4e843845d8d542ba47f3ffb4f36
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
595        // XXX: modify when we do something more intelligent with the two content views
596        final RemoteViews oldContentView = (oldNotification.notification.bigContentView != null)
597                ? oldNotification.notification.bigContentView
598                : oldNotification.notification.contentView;
599        final RemoteViews contentView = (notification.notification.bigContentView != null)
600                ? notification.notification.bigContentView
601                : notification.notification.contentView;
602
603        if (DEBUG) {
604            Slog.d(TAG, "old notification: when=" + oldNotification.notification.when
605                    + " ongoing=" + oldNotification.isOngoing()
606                    + " expanded=" + oldEntry.expanded
607                    + " contentView=" + oldContentView
608                    + " rowParent=" + oldEntry.row.getParent());
609            Slog.d(TAG, "new notification: when=" + notification.notification.when
610                    + " ongoing=" + oldNotification.isOngoing()
611                    + " contentView=" + contentView);
612        }
613
614
615        // Can we just reapply the RemoteViews in place?  If when didn't change, the order
616        // didn't change.
617        boolean contentsUnchanged = oldEntry.expanded != null
618                && contentView != null && oldContentView != null
619                && contentView.getPackage() != null
620                && oldContentView.getPackage() != null
621                && oldContentView.getPackage().equals(contentView.getPackage())
622                && oldContentView.getLayoutId() == contentView.getLayoutId();
623        ViewGroup rowParent = (ViewGroup) oldEntry.row.getParent();
624        boolean orderUnchanged = notification.notification.when==oldNotification.notification.when
625                && notification.score == oldNotification.score;
626                // score now encompasses/supersedes isOngoing()
627
628        boolean updateTicker = notification.notification.tickerText != null
629                && !TextUtils.equals(notification.notification.tickerText,
630                        oldEntry.notification.notification.tickerText);
631        boolean isFirstAnyway = rowParent.indexOfChild(oldEntry.row) == 0;
632        if (contentsUnchanged && (orderUnchanged || isFirstAnyway)) {
633            if (DEBUG) Slog.d(TAG, "reusing notification for key: " + key);
634            oldEntry.notification = notification;
635            try {
636                // Reapply the RemoteViews
637                contentView.reapply(mContext, oldEntry.content);
638                // update the contentIntent
639                final PendingIntent contentIntent = notification.notification.contentIntent;
640                if (contentIntent != null) {
641                    final View.OnClickListener listener = new NotificationClicker(contentIntent,
642                            notification.pkg, notification.tag, notification.id);
643                    oldEntry.content.setOnClickListener(listener);
644                } else {
645                    oldEntry.content.setOnClickListener(null);
646                }
647                // Update the icon.
648                final StatusBarIcon ic = new StatusBarIcon(notification.pkg,
649                        notification.notification.icon, notification.notification.iconLevel,
650                        notification.notification.number,
651                        notification.notification.tickerText);
652                if (!oldEntry.icon.set(ic)) {
653                    handleNotificationError(key, notification, "Couldn't update icon: " + ic);
654                    return;
655                }
656            }
657            catch (RuntimeException e) {
658                // It failed to add cleanly.  Log, and remove the view from the panel.
659                Slog.w(TAG, "Couldn't reapply views for package " + contentView.getPackage(), e);
660                removeNotificationViews(key);
661                addNotificationViews(key, notification);
662            }
663        } else {
664            if (SPEW) Slog.d(TAG, "not reusing notification");
665            removeNotificationViews(key);
666            addNotificationViews(key, notification);
667        }
668
669        // Update the veto button accordingly (and as a result, whether this row is
670        // swipe-dismissable)
671        updateNotificationVetoButton(oldEntry.row, notification);
672
673        // Restart the ticker if it's still running
674        if (updateTicker) {
675            mTicker.halt();
676            tick(notification);
677        }
678
679        // Recalculate the position of the sliding windows and the titles.
680        setAreThereNotifications();
681        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
682
683        // See if we need to update the intruder.
684        if (oldNotification == mCurrentlyIntrudingNotification) {
685            if (DEBUG) Slog.d(TAG, "updating the current intruder:" + notification);
686            // XXX: this is a hack for Alarms. The real implementation will need to *update*
687            // the intruder.
688            if (notification.notification.fullScreenIntent == null) { // TODO(dsandler): consistent logic with add()
689                if (DEBUG) Slog.d(TAG, "no longer intrudes!");
690                mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
691            }
692        }
693    }
694
695    public void removeNotification(IBinder key) {
696        StatusBarNotification old = removeNotificationViews(key);
697        if (SPEW) Slog.d(TAG, "removeNotification key=" + key + " old=" + old);
698
699        if (old != null) {
700            // Cancel the ticker if it's still running
701            mTicker.removeEntry(old);
702
703            // Recalculate the position of the sliding windows and the titles.
704            updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
705
706            if (old == mCurrentlyIntrudingNotification) {
707                mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
708            }
709
710            if (CLOSE_PANEL_WHEN_EMPTIED && mNotificationData.size() == 0 && !mAnimating) {
711                animateCollapse();
712            }
713        }
714
715        setAreThereNotifications();
716    }
717
718    @Override
719    protected void onConfigurationChanged(Configuration newConfig) {
720        updateRecentsPanel();
721    }
722
723
724    StatusBarIconView addNotificationViews(IBinder key, StatusBarNotification notification) {
725        if (DEBUG) {
726            Slog.d(TAG, "addNotificationViews(key=" + key + ", notification=" + notification);
727        }
728        // Construct the icon.
729        final StatusBarIconView iconView = new StatusBarIconView(mContext,
730                notification.pkg + "/0x" + Integer.toHexString(notification.id),
731                notification.notification);
732        iconView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
733
734        final StatusBarIcon ic = new StatusBarIcon(notification.pkg,
735                    notification.notification.icon,
736                    notification.notification.iconLevel,
737                    notification.notification.number,
738                    notification.notification.tickerText);
739        if (!iconView.set(ic)) {
740            handleNotificationError(key, notification, "Couldn't create icon: " + ic);
741            return null;
742        }
743        // Construct the expanded view.
744        NotificationData.Entry entry = new NotificationData.Entry(key, notification, iconView);
745        if (!inflateViews(entry, mPile)) {
746            handleNotificationError(key, notification, "Couldn't expand RemoteViews for: "
747                    + notification);
748            return null;
749        }
750
751        // Add the expanded view and icon.
752        int pos = mNotificationData.add(entry);
753        if (DEBUG) {
754            Slog.d(TAG, "addNotificationViews: added at " + pos);
755        }
756        updateNotificationIcons();
757
758        return iconView;
759    }
760
761    private void loadNotificationShade() {
762        int N = mNotificationData.size();
763
764        ArrayList<View> toShow = new ArrayList<View>();
765
766        for (int i=0; i<N; i++) {
767            View row = mNotificationData.get(N-i-1).row;
768            toShow.add(row);
769        }
770
771        ArrayList<View> toRemove = new ArrayList<View>();
772        for (int i=0; i<mPile.getChildCount(); i++) {
773            View child = mPile.getChildAt(i);
774            if (!toShow.contains(child)) {
775                toRemove.add(child);
776            }
777        }
778
779        for (View remove : toRemove) {
780            mPile.removeView(remove);
781        }
782
783        for (int i=0; i<toShow.size(); i++) {
784            View v = toShow.get(i);
785            if (v.getParent() == null) {
786                mPile.addView(v, i);
787            }
788        }
789    }
790
791    private void reloadAllNotificationIcons() {
792        if (mNotificationIcons == null) return;
793        mNotificationIcons.removeAllViews();
794        updateNotificationIcons();
795    }
796
797    private void updateNotificationIcons() {
798        loadNotificationShade();
799
800        final LinearLayout.LayoutParams params
801            = new LinearLayout.LayoutParams(mIconSize + 2*mIconHPadding, mNaturalBarHeight);
802
803        int N = mNotificationData.size();
804
805        if (DEBUG) {
806            Slog.d(TAG, "refreshing icons: " + N + " notifications, mNotificationIcons=" + mNotificationIcons);
807        }
808
809        ArrayList<View> toShow = new ArrayList<View>();
810
811        for (int i=0; i<N; i++) {
812            toShow.add(mNotificationData.get(N-i-1).icon);
813        }
814
815        ArrayList<View> toRemove = new ArrayList<View>();
816        for (int i=0; i<mNotificationIcons.getChildCount(); i++) {
817            View child = mNotificationIcons.getChildAt(i);
818            if (!toShow.contains(child)) {
819                toRemove.add(child);
820            }
821        }
822
823        for (View remove : toRemove) {
824            mNotificationIcons.removeView(remove);
825        }
826
827        for (int i=0; i<toShow.size(); i++) {
828            View v = toShow.get(i);
829            if (v.getParent() == null) {
830                mNotificationIcons.addView(v, i, params);
831            }
832        }
833    }
834
835    private boolean inflateViews(NotificationData.Entry entry, ViewGroup parent) {
836        StatusBarNotification sbn = entry.notification;
837        // XXX: temporary: while testing big notifications, auto-expand all of them
838        final boolean big = (sbn.notification.bigContentView != null);
839        RemoteViews remoteViews = big ? sbn.notification.bigContentView
840                                      : sbn.notification.contentView;
841        if (remoteViews == null) {
842            return false;
843        }
844
845        // create the row view
846        LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(
847                Context.LAYOUT_INFLATER_SERVICE);
848        View row = inflater.inflate(R.layout.status_bar_notification_row, parent, false);
849        ViewGroup.LayoutParams lp = row.getLayoutParams();
850        if (big) {
851            lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
852        } else {
853            lp.height = mContext.getResources().getDimensionPixelSize(R.dimen.notification_height);
854        }
855        row.setLayoutParams(lp);
856        View vetoButton = updateNotificationVetoButton(row, sbn);
857        vetoButton.setContentDescription(mContext.getString(
858                R.string.accessibility_remove_notification));
859
860        // NB: the large icon is now handled entirely by the template
861
862        // bind the click event to the content area
863        ViewGroup content = (ViewGroup)row.findViewById(R.id.content);
864        // XXX: update to allow controls within notification views
865        content.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
866//        content.setOnFocusChangeListener(mFocusChangeListener);
867        PendingIntent contentIntent = sbn.notification.contentIntent;
868        if (contentIntent != null) {
869            final View.OnClickListener listener = new NotificationClicker(contentIntent,
870                    sbn.pkg, sbn.tag, sbn.id);
871            content.setOnClickListener(listener);
872        } else {
873            content.setOnClickListener(null);
874        }
875
876        View expanded = null;
877        Exception exception = null;
878        try {
879            expanded = remoteViews.apply(mContext, content);
880        }
881        catch (RuntimeException e) {
882            exception = e;
883        }
884        if (expanded == null) {
885            final String ident = sbn.pkg + "/0x" + Integer.toHexString(sbn.id);
886            Slog.e(TAG, "couldn't inflate view for notification " + ident, exception);
887            return false;
888        } else {
889            content.addView(expanded);
890            row.setDrawingCacheEnabled(true);
891        }
892
893        applyLegacyRowBackground(sbn, content);
894
895        entry.row = row;
896        entry.content = content;
897        entry.expanded = expanded;
898
899        return true;
900    }
901
902    StatusBarNotification removeNotificationViews(IBinder key) {
903        NotificationData.Entry entry = mNotificationData.remove(key);
904        if (entry == null) {
905            Slog.w(TAG, "removeNotification for unknown key: " + key);
906            return null;
907        }
908        // Remove the expanded view.
909        ViewGroup rowParent = (ViewGroup)entry.row.getParent();
910        if (rowParent != null) rowParent.removeView(entry.row);
911        updateNotificationIcons();
912
913        return entry.notification;
914    }
915
916    private void setAreThereNotifications() {
917        final boolean any = mNotificationData.size() > 0;
918
919        final boolean clearable = any && mNotificationData.hasClearableItems();
920
921        if (DEBUG) {
922            Slog.d(TAG, "setAreThereNotifications: N=" + mNotificationData.size()
923                    + " any=" + any + " clearable=" + clearable);
924        }
925
926        if (mClearButton.isShown()) {
927            if (clearable != (mClearButton.getAlpha() == 1.0f)) {
928                ObjectAnimator.ofFloat(mClearButton, "alpha",
929                        clearable ? 1.0f : 0.0f)
930                    .setDuration(250)
931                    .start();
932            }
933        } else {
934            mClearButton.setAlpha(clearable ? 1.0f : 0.0f);
935        }
936        mClearButton.setEnabled(clearable);
937
938    }
939
940    public void showClock(boolean show) {
941        if (mStatusBarView == null) return;
942        View clock = mStatusBarView.findViewById(R.id.clock);
943        if (clock != null) {
944            clock.setVisibility(show ? View.VISIBLE : View.GONE);
945        }
946    }
947
948    /**
949     * State is one or more of the DISABLE constants from StatusBarManager.
950     */
951    public void disable(int state) {
952        final int old = mDisabled;
953        final int diff = state ^ old;
954        mDisabled = state;
955
956        if (DEBUG) {
957            Slog.d(TAG, String.format("disable: 0x%08x -> 0x%08x (diff: 0x%08x)",
958                old, state, diff));
959        }
960
961        StringBuilder flagdbg = new StringBuilder();
962        flagdbg.append("disable: < ");
963        flagdbg.append(((state & StatusBarManager.DISABLE_EXPAND) != 0) ? "EXPAND" : "expand");
964        flagdbg.append(((diff  & StatusBarManager.DISABLE_EXPAND) != 0) ? "* " : " ");
965        flagdbg.append(((state & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) ? "ICONS" : "icons");
966        flagdbg.append(((diff  & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) ? "* " : " ");
967        flagdbg.append(((state & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) ? "ALERTS" : "alerts");
968        flagdbg.append(((diff  & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) ? "* " : " ");
969        flagdbg.append(((state & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) ? "TICKER" : "ticker");
970        flagdbg.append(((diff  & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) ? "* " : " ");
971        flagdbg.append(((state & StatusBarManager.DISABLE_SYSTEM_INFO) != 0) ? "SYSTEM_INFO" : "system_info");
972        flagdbg.append(((diff  & StatusBarManager.DISABLE_SYSTEM_INFO) != 0) ? "* " : " ");
973        flagdbg.append(((state & StatusBarManager.DISABLE_BACK) != 0) ? "BACK" : "back");
974        flagdbg.append(((diff  & StatusBarManager.DISABLE_BACK) != 0) ? "* " : " ");
975        flagdbg.append(((state & StatusBarManager.DISABLE_HOME) != 0) ? "HOME" : "home");
976        flagdbg.append(((diff  & StatusBarManager.DISABLE_HOME) != 0) ? "* " : " ");
977        flagdbg.append(((state & StatusBarManager.DISABLE_RECENT) != 0) ? "RECENT" : "recent");
978        flagdbg.append(((diff  & StatusBarManager.DISABLE_RECENT) != 0) ? "* " : " ");
979        flagdbg.append(((state & StatusBarManager.DISABLE_CLOCK) != 0) ? "CLOCK" : "clock");
980        flagdbg.append(((diff  & StatusBarManager.DISABLE_CLOCK) != 0) ? "* " : " ");
981        flagdbg.append(">");
982        Slog.d(TAG, flagdbg.toString());
983
984        if ((diff & StatusBarManager.DISABLE_CLOCK) != 0) {
985            boolean show = (state & StatusBarManager.DISABLE_CLOCK) == 0;
986            showClock(show);
987        }
988        if ((diff & StatusBarManager.DISABLE_EXPAND) != 0) {
989            if ((state & StatusBarManager.DISABLE_EXPAND) != 0) {
990                animateCollapse();
991            }
992        }
993
994        if ((diff & (StatusBarManager.DISABLE_HOME
995                        | StatusBarManager.DISABLE_RECENT
996                        | StatusBarManager.DISABLE_BACK)) != 0) {
997            // the nav bar will take care of these
998            if (mNavigationBarView != null) mNavigationBarView.setDisabledFlags(state);
999
1000            if ((state & StatusBarManager.DISABLE_RECENT) != 0) {
1001                // close recents if it's visible
1002                mHandler.removeMessages(MSG_CLOSE_RECENTS_PANEL);
1003                mHandler.sendEmptyMessage(MSG_CLOSE_RECENTS_PANEL);
1004            }
1005        }
1006
1007        if ((diff & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
1008            if ((state & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
1009                if (mTicking) {
1010                    mTicker.halt();
1011                } else {
1012                    setNotificationIconVisibility(false, com.android.internal.R.anim.fade_out);
1013                }
1014            } else {
1015                if (!mExpandedVisible) {
1016                    setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
1017                }
1018            }
1019        } else if ((diff & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
1020            if (mTicking && (state & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
1021                mTicker.halt();
1022            }
1023        }
1024    }
1025
1026    @Override
1027    protected BaseStatusBar.H createHandler() {
1028        return new PhoneStatusBar.H();
1029    }
1030
1031    /**
1032     * All changes to the status bar and notifications funnel through here and are batched.
1033     */
1034    private class H extends BaseStatusBar.H {
1035        public void handleMessage(Message m) {
1036            super.handleMessage(m);
1037            switch (m.what) {
1038                case MSG_ANIMATE:
1039                    doAnimation();
1040                    break;
1041                case MSG_ANIMATE_REVEAL:
1042                    doRevealAnimation();
1043                    break;
1044                case MSG_OPEN_NOTIFICATION_PANEL:
1045                    animateExpand();
1046                    break;
1047                case MSG_CLOSE_NOTIFICATION_PANEL:
1048                    animateCollapse();
1049                    break;
1050                case MSG_SHOW_INTRUDER:
1051                    setIntruderAlertVisibility(true);
1052                    break;
1053                case MSG_HIDE_INTRUDER:
1054                    setIntruderAlertVisibility(false);
1055                    mCurrentlyIntrudingNotification = null;
1056                    break;
1057            }
1058        }
1059    }
1060
1061    View.OnFocusChangeListener mFocusChangeListener = new View.OnFocusChangeListener() {
1062        public void onFocusChange(View v, boolean hasFocus) {
1063            // Because 'v' is a ViewGroup, all its children will be (un)selected
1064            // too, which allows marqueeing to work.
1065            v.setSelected(hasFocus);
1066        }
1067    };
1068
1069    private void makeExpandedVisible() {
1070        if (SPEW) Slog.d(TAG, "Make expanded visible: expanded visible=" + mExpandedVisible);
1071        if (mExpandedVisible) {
1072            return;
1073        }
1074        mExpandedDialog.show(); // XXX HAX
1075        mExpandedVisible = true;
1076        visibilityChanged(true);
1077
1078        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
1079        mExpandedParams.flags &= ~WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
1080        mExpandedParams.flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
1081        if (DEBUG) {
1082            Slog.d(TAG, "makeExpandedVisible: expanded params = " + mExpandedParams);
1083        }
1084        mExpandedDialog.getWindow().setAttributes(mExpandedParams);
1085        mExpandedWindowView.requestFocus(View.FOCUS_FORWARD);
1086        mExpandedWindowView.setVisibility(View.VISIBLE);
1087    }
1088
1089    public void animateExpand() {
1090        if (SPEW) Slog.d(TAG, "Animate expand: expanded=" + mExpanded);
1091        if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
1092            return ;
1093        }
1094        if (mExpanded) {
1095            return;
1096        }
1097
1098        prepareTracking(0, true);
1099        performFling(0, mSelfExpandVelocityPx, true);
1100    }
1101
1102    public void animateCollapse() {
1103        animateCollapse(false);
1104    }
1105
1106    public void animateCollapse(boolean excludeRecents) {
1107        animateCollapse(excludeRecents, 1.0f);
1108    }
1109
1110    public void animateCollapse(boolean excludeRecents, float velocityMultiplier) {
1111        if (SPEW) {
1112            Slog.d(TAG, "animateCollapse(): mExpanded=" + mExpanded
1113                    + " mExpandedVisible=" + mExpandedVisible
1114                    + " mExpanded=" + mExpanded
1115                    + " mAnimating=" + mAnimating
1116                    + " mAnimY=" + mAnimY
1117                    + " mAnimVel=" + mAnimVel);
1118        }
1119
1120        if (!excludeRecents) {
1121            mHandler.removeMessages(MSG_CLOSE_RECENTS_PANEL);
1122            mHandler.sendEmptyMessage(MSG_CLOSE_RECENTS_PANEL);
1123        }
1124
1125        if (!mExpandedVisible) {
1126            return;
1127        }
1128
1129        int y;
1130        if (mAnimating) {
1131            y = (int)mAnimY;
1132        } else {
1133            y = mDisplayMetrics.heightPixels-1;
1134        }
1135        // Let the fling think that we're open so it goes in the right direction
1136        // and doesn't try to re-open the windowshade.
1137        mExpanded = true;
1138        prepareTracking(y, false);
1139        performFling(y, -mSelfCollapseVelocityPx*velocityMultiplier, true);
1140    }
1141
1142    void performExpand() {
1143        if (SPEW) Slog.d(TAG, "performExpand: mExpanded=" + mExpanded);
1144        if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
1145            return ;
1146        }
1147        if (mExpanded) {
1148            return;
1149        }
1150
1151        mExpanded = true;
1152        makeExpandedVisible();
1153        updateExpandedViewPos(EXPANDED_FULL_OPEN);
1154
1155        if (false) postStartTracing();
1156    }
1157
1158    void performCollapse() {
1159        if (SPEW) Slog.d(TAG, "performCollapse: mExpanded=" + mExpanded
1160                + " mExpandedVisible=" + mExpandedVisible);
1161
1162        if (!mExpandedVisible) {
1163            return;
1164        }
1165        mExpandedVisible = false;
1166        visibilityChanged(false);
1167        mExpandedParams.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
1168        mExpandedParams.flags &= ~WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
1169        mExpandedDialog.getWindow().setAttributes(mExpandedParams);
1170        mExpandedDialog.hide(); // XXX HAX
1171        mExpandedWindowView.setVisibility(View.GONE);
1172
1173        if ((mDisabled & StatusBarManager.DISABLE_NOTIFICATION_ICONS) == 0) {
1174            setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
1175        }
1176
1177        if (!mExpanded) {
1178            return;
1179        }
1180        mExpanded = false;
1181        if (mPostCollapseCleanup != null) {
1182            mPostCollapseCleanup.run();
1183            mPostCollapseCleanup = null;
1184        }
1185    }
1186
1187    void doAnimation() {
1188        if (mAnimating) {
1189            if (SPEW) Slog.d(TAG, "doAnimation");
1190            if (SPEW) Slog.d(TAG, "doAnimation before mAnimY=" + mAnimY);
1191            incrementAnim();
1192            if (SPEW) Slog.d(TAG, "doAnimation after  mAnimY=" + mAnimY);
1193            if (mAnimY >= mDisplayMetrics.heightPixels-1) {
1194                if (SPEW) Slog.d(TAG, "Animation completed to expanded state.");
1195                mAnimating = false;
1196                updateExpandedViewPos(EXPANDED_FULL_OPEN);
1197                performExpand();
1198            }
1199            else if (mAnimY < mStatusBarView.getHeight()) {
1200                if (SPEW) Slog.d(TAG, "Animation completed to collapsed state.");
1201                mAnimating = false;
1202                updateExpandedViewPos(0);
1203                performCollapse();
1204            }
1205            else {
1206                updateExpandedViewPos((int)mAnimY);
1207                mCurAnimationTime += ANIM_FRAME_DURATION;
1208                mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE), mCurAnimationTime);
1209            }
1210        }
1211    }
1212
1213    void stopTracking() {
1214        mTracking = false;
1215        mPile.setLayerType(View.LAYER_TYPE_NONE, null);
1216        mVelocityTracker.recycle();
1217        mVelocityTracker = null;
1218    }
1219
1220    void incrementAnim() {
1221        long now = SystemClock.uptimeMillis();
1222        float t = ((float)(now - mAnimLastTime)) / 1000;            // ms -> s
1223        final float y = mAnimY;
1224        final float v = mAnimVel;                                   // px/s
1225        final float a = mAnimAccel;                                 // px/s/s
1226        mAnimY = y + (v*t) + (0.5f*a*t*t);                          // px
1227        mAnimVel = v + (a*t);                                       // px/s
1228        mAnimLastTime = now;                                        // ms
1229        //Slog.d(TAG, "y=" + y + " v=" + v + " a=" + a + " t=" + t + " mAnimY=" + mAnimY
1230        //        + " mAnimAccel=" + mAnimAccel);
1231    }
1232
1233    void doRevealAnimation() {
1234        final int h = mCloseView.getHeight() + mStatusBarView.getHeight();
1235        if (mAnimatingReveal && mAnimating && mAnimY < h) {
1236            incrementAnim();
1237            if (mAnimY >= h) {
1238                mAnimY = h;
1239                updateExpandedViewPos((int)mAnimY);
1240            } else {
1241                updateExpandedViewPos((int)mAnimY);
1242                mCurAnimationTime += ANIM_FRAME_DURATION;
1243                mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE_REVEAL),
1244                        mCurAnimationTime);
1245            }
1246        }
1247    }
1248
1249    void prepareTracking(int y, boolean opening) {
1250        if (CHATTY) {
1251            Slog.d(TAG, "panel: beginning to track the user's touch, y=" + y + " opening=" + opening);
1252        }
1253
1254        // there are some race conditions that cause this to be inaccurate; let's recalculate it any
1255        // time we're about to drag the panel
1256        updateExpandedSize();
1257
1258        mTracking = true;
1259        mPile.setLayerType(View.LAYER_TYPE_HARDWARE, null);
1260        mVelocityTracker = VelocityTracker.obtain();
1261        if (opening) {
1262            mAnimAccel = mExpandAccelPx;
1263            mAnimVel = mFlingExpandMinVelocityPx;
1264            mAnimY = mStatusBarView.getHeight();
1265            updateExpandedViewPos((int)mAnimY);
1266            mAnimating = true;
1267            mAnimatingReveal = true;
1268            mHandler.removeMessages(MSG_ANIMATE);
1269            mHandler.removeMessages(MSG_ANIMATE_REVEAL);
1270            long now = SystemClock.uptimeMillis();
1271            mAnimLastTime = now;
1272            mCurAnimationTime = now + ANIM_FRAME_DURATION;
1273            mAnimating = true;
1274            mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE_REVEAL),
1275                    mCurAnimationTime);
1276            makeExpandedVisible();
1277        } else {
1278            // it's open, close it?
1279            if (mAnimating) {
1280                mAnimating = false;
1281                mHandler.removeMessages(MSG_ANIMATE);
1282            }
1283            updateExpandedViewPos(y + mViewDelta);
1284        }
1285    }
1286
1287    void performFling(int y, float vel, boolean always) {
1288        if (CHATTY) {
1289            Slog.d(TAG, "panel: will fling, y=" + y + " vel=" + vel);
1290        }
1291
1292        mAnimatingReveal = false;
1293
1294        mAnimY = y;
1295        mAnimVel = vel;
1296
1297        //Slog.d(TAG, "starting with mAnimY=" + mAnimY + " mAnimVel=" + mAnimVel);
1298
1299        if (mExpanded) {
1300            if (!always && (
1301                    vel > mFlingCollapseMinVelocityPx
1302                    || (y > (mDisplayMetrics.heightPixels*(1f-mCollapseMinDisplayFraction)) &&
1303                        vel > -mFlingExpandMinVelocityPx))) {
1304                // We are expanded, but they didn't move sufficiently to cause
1305                // us to retract.  Animate back to the expanded position.
1306                mAnimAccel = mExpandAccelPx;
1307                if (vel < 0) {
1308                    mAnimVel = 0;
1309                }
1310            }
1311            else {
1312                // We are expanded and are now going to animate away.
1313                mAnimAccel = -mCollapseAccelPx;
1314                if (vel > 0) {
1315                    mAnimVel = 0;
1316                }
1317            }
1318        } else {
1319            if (always || (
1320                    vel > mFlingExpandMinVelocityPx
1321                    || (y > (mDisplayMetrics.heightPixels*(1f-mExpandMinDisplayFraction)) &&
1322                        vel > -mFlingCollapseMinVelocityPx))) {
1323                // We are collapsed, and they moved enough to allow us to
1324                // expand.  Animate in the notifications.
1325                mAnimAccel = mExpandAccelPx;
1326                if (vel < 0) {
1327                    mAnimVel = 0;
1328                }
1329            }
1330            else {
1331                // We are collapsed, but they didn't move sufficiently to cause
1332                // us to retract.  Animate back to the collapsed position.
1333                mAnimAccel = -mCollapseAccelPx;
1334                if (vel > 0) {
1335                    mAnimVel = 0;
1336                }
1337            }
1338        }
1339        //Slog.d(TAG, "mAnimY=" + mAnimY + " mAnimVel=" + mAnimVel
1340        //        + " mAnimAccel=" + mAnimAccel);
1341
1342        long now = SystemClock.uptimeMillis();
1343        mAnimLastTime = now;
1344        mCurAnimationTime = now + ANIM_FRAME_DURATION;
1345        mAnimating = true;
1346        mHandler.removeMessages(MSG_ANIMATE);
1347        mHandler.removeMessages(MSG_ANIMATE_REVEAL);
1348        mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE), mCurAnimationTime);
1349        stopTracking();
1350    }
1351
1352    boolean interceptTouchEvent(MotionEvent event) {
1353        if (SPEW) {
1354            Slog.d(TAG, "Touch: rawY=" + event.getRawY() + " event=" + event + " mDisabled="
1355                + mDisabled);
1356        } else if (CHATTY) {
1357            if (event.getAction() != MotionEvent.ACTION_MOVE) {
1358                Slog.d(TAG, String.format(
1359                            "panel: %s at (%f, %f) mDisabled=0x%08x",
1360                            MotionEvent.actionToString(event.getAction()),
1361                            event.getRawX(), event.getRawY(), mDisabled));
1362            }
1363        }
1364
1365        if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
1366            return false;
1367        }
1368
1369        final int action = event.getAction();
1370        final int statusBarSize = mStatusBarView.getHeight();
1371        final int hitSize = statusBarSize*2;
1372        final int y = (int)event.getRawY();
1373        if (action == MotionEvent.ACTION_DOWN) {
1374            if (!mExpanded) {
1375                mViewDelta = statusBarSize - y;
1376            } else {
1377//                mCloseView.getLocationOnScreen(mAbsPos)...?
1378//                mViewDelta = mAbsPos[1] + mTrackingView.getHeight() - y;
1379            }
1380            if ((!mExpanded && y < hitSize) ||
1381                    (mExpanded && y > (mDisplayMetrics.heightPixels-hitSize))) {
1382
1383                // We drop events at the edge of the screen to make the windowshade come
1384                // down by accident less, especially when pushing open a device with a keyboard
1385                // that rotates (like g1 and droid)
1386                int x = (int)event.getRawX();
1387                final int edgeBorder = mEdgeBorder;
1388                if (x >= edgeBorder && x < mDisplayMetrics.widthPixels - edgeBorder) {
1389                    prepareTracking(y, !mExpanded);// opening if we're not already fully visible
1390                    trackMovement(event);
1391                }
1392            }
1393        } else if (mTracking) {
1394            trackMovement(event);
1395            final int minY = statusBarSize + mCloseView.getHeight();
1396            if (action == MotionEvent.ACTION_MOVE) {
1397                if (mAnimatingReveal && y < minY) {
1398                    // nothing
1399                } else  {
1400                    mAnimatingReveal = false;
1401                    updateExpandedViewPos(y + mViewDelta);
1402                }
1403            } else if (action == MotionEvent.ACTION_UP
1404                    || action == MotionEvent.ACTION_CANCEL) {
1405                mVelocityTracker.computeCurrentVelocity(1000);
1406
1407                float yVel = mVelocityTracker.getYVelocity();
1408                boolean negative = yVel < 0;
1409
1410                float xVel = mVelocityTracker.getXVelocity();
1411                if (xVel < 0) {
1412                    xVel = -xVel;
1413                }
1414                if (xVel > mFlingGestureMaxXVelocityPx) {
1415                    xVel = mFlingGestureMaxXVelocityPx; // limit how much we care about the x axis
1416                }
1417
1418                float vel = (float)Math.hypot(yVel, xVel);
1419                if (negative) {
1420                    vel = -vel;
1421                }
1422
1423                if (CHATTY) {
1424                    Slog.d(TAG, String.format("gesture: vraw=(%f,%f) vnorm=(%f,%f) vlinear=%f",
1425                        mVelocityTracker.getXVelocity(),
1426                        mVelocityTracker.getYVelocity(),
1427                        xVel, yVel,
1428                        vel));
1429                }
1430
1431                performFling(y + mViewDelta, vel, false);
1432            }
1433
1434        }
1435        return false;
1436    }
1437
1438    private void trackMovement(MotionEvent event) {
1439        // Add movement to velocity tracker using raw screen X and Y coordinates instead
1440        // of window coordinates because the window frame may be moving at the same time.
1441        float deltaX = event.getRawX() - event.getX();
1442        float deltaY = event.getRawY() - event.getY();
1443        event.offsetLocation(deltaX, deltaY);
1444        mVelocityTracker.addMovement(event);
1445        event.offsetLocation(-deltaX, -deltaY);
1446    }
1447
1448    @Override // CommandQueue
1449    public void setNavigationIconHints(int hints) {
1450        if (hints == mNavigationIconHints) return;
1451
1452        mNavigationIconHints = hints;
1453
1454        if (mNavigationBarView != null) {
1455            mNavigationBarView.setNavigationIconHints(hints);
1456        }
1457    }
1458
1459    @Override // CommandQueue
1460    public void setSystemUiVisibility(int vis, int mask) {
1461        final int oldVal = mSystemUiVisibility;
1462        final int newVal = (oldVal&~mask) | (vis&mask);
1463        final int diff = newVal ^ oldVal;
1464
1465        if (diff != 0) {
1466            mSystemUiVisibility = newVal;
1467
1468            if (0 != (diff & View.SYSTEM_UI_FLAG_LOW_PROFILE)) {
1469                final boolean lightsOut = (0 != (vis & View.SYSTEM_UI_FLAG_LOW_PROFILE));
1470                if (lightsOut) {
1471                    animateCollapse();
1472                }
1473                if (mNavigationBarView != null) {
1474                    mNavigationBarView.setLowProfile(lightsOut);
1475                }
1476            }
1477
1478            notifyUiVisibilityChanged();
1479        }
1480    }
1481
1482    public void setLightsOn(boolean on) {
1483        Log.v(TAG, "setLightsOn(" + on + ")");
1484        if (on) {
1485            setSystemUiVisibility(0, View.SYSTEM_UI_FLAG_LOW_PROFILE);
1486        } else {
1487            setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE, View.SYSTEM_UI_FLAG_LOW_PROFILE);
1488        }
1489    }
1490
1491    private void notifyUiVisibilityChanged() {
1492        try {
1493            mWindowManager.statusBarVisibilityChanged(mSystemUiVisibility);
1494        } catch (RemoteException ex) {
1495        }
1496    }
1497
1498    public void topAppWindowChanged(boolean showMenu) {
1499        if (DEBUG) {
1500            Slog.d(TAG, (showMenu?"showing":"hiding") + " the MENU button");
1501        }
1502        if (mNavigationBarView != null) {
1503            mNavigationBarView.setMenuVisibility(showMenu);
1504        }
1505
1506        // See above re: lights-out policy for legacy apps.
1507        if (showMenu) setLightsOn(true);
1508    }
1509
1510    @Override
1511    public void setImeWindowStatus(IBinder token, int vis, int backDisposition) {
1512        boolean altBack = (backDisposition == InputMethodService.BACK_DISPOSITION_WILL_DISMISS)
1513            || ((vis & InputMethodService.IME_VISIBLE) != 0);
1514
1515        mCommandQueue.setNavigationIconHints(
1516                altBack ? (mNavigationIconHints | StatusBarManager.NAVIGATION_HINT_BACK_ALT)
1517                        : (mNavigationIconHints & ~StatusBarManager.NAVIGATION_HINT_BACK_ALT));
1518    }
1519
1520    @Override
1521    public void setHardKeyboardStatus(boolean available, boolean enabled) { }
1522
1523    public NotificationClicker makeClicker(PendingIntent intent, String pkg, String tag, int id) {
1524        return new NotificationClicker(intent, pkg, tag, id);
1525    }
1526
1527    private class NotificationClicker implements View.OnClickListener {
1528        private PendingIntent mIntent;
1529        private String mPkg;
1530        private String mTag;
1531        private int mId;
1532
1533        NotificationClicker(PendingIntent intent, String pkg, String tag, int id) {
1534            mIntent = intent;
1535            mPkg = pkg;
1536            mTag = tag;
1537            mId = id;
1538        }
1539
1540        public void onClick(View v) {
1541            if (DEBUG) {
1542                Slog.v(TAG, "NotificationClicker: intent=" + mIntent
1543                        + " pkg=" + mPkg
1544                        + " tag=" + mTag
1545                        + " id=" + mId);
1546            }
1547            try {
1548                // The intent we are sending is for the application, which
1549                // won't have permission to immediately start an activity after
1550                // the user switches to home.  We know it is safe to do at this
1551                // point, so make sure new activity switches are now allowed.
1552                ActivityManagerNative.getDefault().resumeAppSwitches();
1553                // Also, notifications can be launched from the lock screen,
1554                // so dismiss the lock screen when the activity starts.
1555                ActivityManagerNative.getDefault().dismissKeyguardOnNextActivity();
1556            } catch (RemoteException e) {
1557            }
1558
1559            if (mIntent != null) {
1560                int[] pos = new int[2];
1561                v.getLocationOnScreen(pos);
1562                Intent overlay = new Intent();
1563                overlay.setSourceBounds(
1564                        new Rect(pos[0], pos[1], pos[0]+v.getWidth(), pos[1]+v.getHeight()));
1565                try {
1566                    mIntent.send(mContext, 0, overlay);
1567                } catch (PendingIntent.CanceledException e) {
1568                    // the stack trace isn't very helpful here.  Just log the exception message.
1569                    Slog.w(TAG, "Sending contentIntent failed: " + e);
1570                }
1571
1572                KeyguardManager kgm =
1573                    (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
1574                if (kgm != null) kgm.exitKeyguardSecurely(null);
1575            }
1576
1577            try {
1578                mBarService.onNotificationClick(mPkg, mTag, mId);
1579            } catch (RemoteException ex) {
1580                // system process is dead if we're here.
1581            }
1582
1583            // close the shade if it was open
1584            animateCollapse();
1585
1586            // If this click was on the intruder alert, hide that instead
1587            mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
1588        }
1589    }
1590
1591    private void tick(StatusBarNotification n) {
1592        // Show the ticker if one is requested. Also don't do this
1593        // until status bar window is attached to the window manager,
1594        // because...  well, what's the point otherwise?  And trying to
1595        // run a ticker without being attached will crash!
1596        if (n.notification.tickerText != null && mStatusBarView.getWindowToken() != null) {
1597            if (0 == (mDisabled & (StatusBarManager.DISABLE_NOTIFICATION_ICONS
1598                            | StatusBarManager.DISABLE_NOTIFICATION_TICKER))) {
1599                mTicker.addEntry(n);
1600            }
1601        }
1602    }
1603
1604    /**
1605     * Cancel this notification and tell the StatusBarManagerService / NotificationManagerService
1606     * about the failure.
1607     *
1608     * WARNING: this will call back into us.  Don't hold any locks.
1609     */
1610    void handleNotificationError(IBinder key, StatusBarNotification n, String message) {
1611        removeNotification(key);
1612        try {
1613            mBarService.onNotificationError(n.pkg, n.tag, n.id, n.uid, n.initialPid, message);
1614        } catch (RemoteException ex) {
1615            // The end is nigh.
1616        }
1617    }
1618
1619    private class MyTicker extends Ticker {
1620        MyTicker(Context context, View sb) {
1621            super(context, sb);
1622        }
1623
1624        @Override
1625        public void tickerStarting() {
1626            mTicking = true;
1627            mIcons.setVisibility(View.GONE);
1628            mTickerView.setVisibility(View.VISIBLE);
1629            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_up_in, null));
1630            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.push_up_out, null));
1631        }
1632
1633        @Override
1634        public void tickerDone() {
1635            mIcons.setVisibility(View.VISIBLE);
1636            mTickerView.setVisibility(View.GONE);
1637            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.push_down_in, null));
1638            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_down_out,
1639                        mTickingDoneListener));
1640        }
1641
1642        public void tickerHalting() {
1643            mIcons.setVisibility(View.VISIBLE);
1644            mTickerView.setVisibility(View.GONE);
1645            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.fade_in, null));
1646            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.fade_out,
1647                        mTickingDoneListener));
1648        }
1649    }
1650
1651    Animation.AnimationListener mTickingDoneListener = new Animation.AnimationListener() {;
1652        public void onAnimationEnd(Animation animation) {
1653            mTicking = false;
1654        }
1655        public void onAnimationRepeat(Animation animation) {
1656        }
1657        public void onAnimationStart(Animation animation) {
1658        }
1659    };
1660
1661    private Animation loadAnim(int id, Animation.AnimationListener listener) {
1662        Animation anim = AnimationUtils.loadAnimation(mContext, id);
1663        if (listener != null) {
1664            anim.setAnimationListener(listener);
1665        }
1666        return anim;
1667    }
1668
1669    public static String viewInfo(View v) {
1670        return "[(" + v.getLeft() + "," + v.getTop() + ")(" + v.getRight() + "," + v.getBottom()
1671                + ") " + v.getWidth() + "x" + v.getHeight() + "]";
1672    }
1673
1674    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1675        synchronized (mQueueLock) {
1676            pw.println("Current Status Bar state:");
1677            pw.println("  mExpanded=" + mExpanded
1678                    + ", mExpandedVisible=" + mExpandedVisible);
1679            pw.println("  mTicking=" + mTicking);
1680            pw.println("  mTracking=" + mTracking);
1681            pw.println("  mAnimating=" + mAnimating
1682                    + ", mAnimY=" + mAnimY + ", mAnimVel=" + mAnimVel
1683                    + ", mAnimAccel=" + mAnimAccel);
1684            pw.println("  mCurAnimationTime=" + mCurAnimationTime
1685                    + " mAnimLastTime=" + mAnimLastTime);
1686            pw.println("  mAnimatingReveal=" + mAnimatingReveal
1687                    + " mViewDelta=" + mViewDelta);
1688            pw.println("  mDisplayMetrics=" + mDisplayMetrics);
1689            pw.println("  mExpandedParams: " + mExpandedParams);
1690            pw.println("  mExpandedView: " + viewInfo(mExpandedWindowView));
1691            pw.println("  mExpandedDialog: " + mExpandedDialog);
1692            pw.println("  mPile: " + viewInfo(mPile));
1693            pw.println("  mCloseView: " + viewInfo(mCloseView));
1694            pw.println("  mTickerView: " + viewInfo(mTickerView));
1695            pw.println("  mScrollView: " + viewInfo(mScrollView)
1696                    + " scroll " + mScrollView.getScrollX() + "," + mScrollView.getScrollY());
1697        }
1698
1699        pw.print("  mNavigationBarView=");
1700        if (mNavigationBarView == null) {
1701            pw.println("null");
1702        } else {
1703            mNavigationBarView.dump(fd, pw, args);
1704        }
1705
1706        if (DUMPTRUCK) {
1707            synchronized (mNotificationData) {
1708                int N = mNotificationData.size();
1709                pw.println("  notification icons: " + N);
1710                for (int i=0; i<N; i++) {
1711                    NotificationData.Entry e = mNotificationData.get(i);
1712                    pw.println("    [" + i + "] key=" + e.key + " icon=" + e.icon);
1713                    StatusBarNotification n = e.notification;
1714                    pw.println("         pkg=" + n.pkg + " id=" + n.id + " score=" + n.score);
1715                    pw.println("         notification=" + n.notification);
1716                    pw.println("         tickerText=\"" + n.notification.tickerText + "\"");
1717                }
1718            }
1719
1720            int N = mStatusIcons.getChildCount();
1721            pw.println("  system icons: " + N);
1722            for (int i=0; i<N; i++) {
1723                StatusBarIconView ic = (StatusBarIconView) mStatusIcons.getChildAt(i);
1724                pw.println("    [" + i + "] icon=" + ic);
1725            }
1726
1727            if (false) {
1728                pw.println("see the logcat for a dump of the views we have created.");
1729                // must happen on ui thread
1730                mHandler.post(new Runnable() {
1731                        public void run() {
1732                            mStatusBarView.getLocationOnScreen(mAbsPos);
1733                            Slog.d(TAG, "mStatusBarView: ----- (" + mAbsPos[0] + "," + mAbsPos[1]
1734                                    + ") " + mStatusBarView.getWidth() + "x"
1735                                    + mStatusBarView.getHeight());
1736                            mStatusBarView.debug();
1737
1738                            mExpandedWindowView.getLocationOnScreen(mAbsPos);
1739                            Slog.d(TAG, "mExpandedView: ----- (" + mAbsPos[0] + "," + mAbsPos[1]
1740                                    + ") " + mExpandedWindowView.getWidth() + "x"
1741                                    + mExpandedWindowView.getHeight());
1742                            mExpandedWindowView.debug();
1743                        }
1744                    });
1745            }
1746        }
1747
1748        mNetworkController.dump(fd, pw, args);
1749    }
1750
1751    @Override
1752    public void createAndAddWindows() {
1753        addStatusBarWindow();
1754        addExpandedWindow();
1755    }
1756
1757    private void addStatusBarWindow() {
1758        // Put up the view
1759        final int height = getStatusBarHeight();
1760
1761        final WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
1762                ViewGroup.LayoutParams.MATCH_PARENT,
1763                height,
1764                WindowManager.LayoutParams.TYPE_STATUS_BAR,
1765                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
1766                    | WindowManager.LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING
1767                    | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
1768                // We use a pixel format of RGB565 for the status bar to save memory bandwidth and
1769                // to ensure that the layer can be handled by HWComposer.  On some devices the
1770                // HWComposer is unable to handle SW-rendered RGBX_8888 layers.
1771                PixelFormat.RGB_565);
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        WindowManagerImpl.getDefault().addView(makeStatusBarView(), lp);
1782    }
1783
1784    void addExpandedWindow() {
1785        WindowManager.LayoutParams lp;
1786        int pixelFormat;
1787
1788        /// ---------- Expanded View --------------
1789        pixelFormat = PixelFormat.TRANSLUCENT;
1790
1791        lp = mExpandedDialog.getWindow().getAttributes();
1792        lp.x = 0;
1793        lp.y = 0;
1794        lp.type = WindowManager.LayoutParams.TYPE_STATUS_BAR_SUB_PANEL;
1795        lp.flags = 0
1796                | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
1797                | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
1798                | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
1799                | WindowManager.LayoutParams.FLAG_DITHER
1800                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
1801        if (ActivityManager.isHighEndGfx(mDisplay)) {
1802            lp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
1803        }
1804        lp.format = pixelFormat;
1805        lp.gravity = Gravity.TOP | Gravity.FILL_HORIZONTAL;
1806        lp.setTitle("StatusBarExpanded");
1807        mExpandedParams = lp;
1808        updateExpandedSize();
1809        mExpandedDialog.getWindow().setFormat(pixelFormat);
1810
1811        mExpandedDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
1812        mExpandedDialog.setContentView(mExpandedWindowView,
1813                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1814                                           ViewGroup.LayoutParams.MATCH_PARENT));
1815        mExpandedDialog.getWindow().setBackgroundDrawable(null);
1816        //mExpandedDialog.show();
1817    }
1818
1819    void setNotificationIconVisibility(boolean visible, int anim) {
1820        int old = mNotificationIcons.getVisibility();
1821        int v = visible ? View.VISIBLE : View.INVISIBLE;
1822        if (old != v) {
1823            mNotificationIcons.setVisibility(v);
1824            mNotificationIcons.startAnimation(loadAnim(anim, null));
1825        }
1826    }
1827
1828    void updateExpandedInvisiblePosition() {
1829        mTrackingPosition = -mDisplayMetrics.heightPixels;
1830    }
1831
1832    void updateExpandedViewPos(int expandedPosition) {
1833        if (SPEW) {
1834            Slog.d(TAG, "updateExpandedViewPos before expandedPosition=" + expandedPosition
1835                    //+ " mTrackingParams.y=" + ((mTrackingParams == null) ? "?" : mTrackingParams.y)
1836                    + " mTrackingPosition=" + mTrackingPosition);
1837        }
1838
1839        int panelh = 0;
1840        final int disph = mDisplayMetrics.heightPixels;
1841
1842        // If the expanded view is not visible, make sure they're still off screen.
1843        // Maybe the view was resized.
1844        if (!mExpandedVisible) {
1845            updateExpandedInvisiblePosition();
1846            return;
1847        }
1848
1849        // tracking view...
1850        int pos;
1851        if (expandedPosition == EXPANDED_FULL_OPEN) {
1852            panelh = disph;
1853        }
1854        else if (expandedPosition == EXPANDED_LEAVE_ALONE) {
1855            panelh = mTrackingPosition;
1856        }
1857        else {
1858            if (expandedPosition <= disph) {
1859                panelh = expandedPosition;
1860            } else {
1861                panelh = disph;
1862            }
1863        }
1864
1865        // catch orientation changes and other peculiar cases
1866        if (panelh > disph || (panelh < disph && !mTracking && !mAnimating))
1867            panelh = disph;
1868
1869        mTrackingPosition = panelh;
1870        // XXX: this is all very WIP
1871        //mNotificationPanel.setY(panelh);
1872        final View cropView = mNotificationPanel;
1873        ViewGroup.LayoutParams lp = cropView.getLayoutParams();
1874        lp.height = panelh;
1875        cropView.setLayoutParams(lp);
1876        // woo, special effects
1877        final float frac = (float)panelh / disph;
1878        final int color = ((int)(0xB0 * frac * frac)) << 24;
1879        mExpandedWindowView.setBackgroundColor(color);
1880
1881//        Slog.d(TAG, String.format("updateExpanded: pos=%d frac=%.2f col=0x%08x", pos, frac, color));
1882
1883//        if (mExpandedParams != null) {
1884//            if (mCloseView.getWindowVisibility() == View.VISIBLE) {
1885//                mCloseView.getLocationInWindow(mPositionTmp);
1886//                final int closePos = mPositionTmp[1];
1887//
1888//                mExpandedContents.getLocationInWindow(mPositionTmp);
1889//                final int contentsBottom = mPositionTmp[1] + mExpandedContents.getHeight();
1890//
1891//                mExpandedParams.y = pos + mTrackingView.getHeight()
1892//                        - (mTrackingParams.height-closePos) - contentsBottom;
1893//
1894//                if (SPEW) {
1895//                    Slog.d(PhoneStatusBar.TAG,
1896//                            "pos=" + pos +
1897//                            " trackingHeight=" + mTrackingView.getHeight() +
1898//                            " (trackingParams.height - closePos)=" +
1899//                                (mTrackingParams.height - closePos) +
1900//                            " contentsBottom=" + contentsBottom);
1901//                }
1902//
1903//            } else {
1904//                // If the tracking view is not yet visible, then we can't have
1905//                // a good value of the close view location.  We need to wait for
1906//                // it to be visible to do a layout.
1907//                mExpandedParams.y = -mDisplayMetrics.heightPixels;
1908//            }
1909//            int max = h;
1910//            if (mExpandedParams.y > max) {
1911//                mExpandedParams.y = max;
1912//            }
1913//            int min = mTrackingPosition;
1914//            if (mExpandedParams.y < min) {
1915//                mExpandedParams.y = min;
1916//            }
1917//
1918//            boolean visible = (mTrackingPosition + mTrackingView.getHeight()) > h;
1919//            if (!visible) {
1920//                // if the contents aren't visible, move the expanded view way off screen
1921//                // because the window itself extends below the content view.
1922//                mExpandedParams.y = -disph;
1923//            }
1924//            mExpandedDialog.getWindow().setAttributes(mExpandedParams);
1925//
1926//            // As long as this isn't just a repositioning that's not supposed to affect
1927//            // the user's perception of what's showing, call to say that the visibility
1928//            // has changed. (Otherwise, someone else will call to do that).
1929//            if (expandedPosition != EXPANDED_LEAVE_ALONE) {
1930//                if (SPEW) Slog.d(TAG, "updateExpandedViewPos visibilityChanged(" + visible + ")");
1931//                visibilityChanged(visible);
1932//            }
1933//        }
1934//
1935//        if (SPEW) {
1936//            Slog.d(TAG, "updateExpandedViewPos after  expandedPosition=" + expandedPosition
1937//                    + " mTrackingParams.y=" + mTrackingParams.y
1938//                    + " mTrackingPosition=" + mTrackingPosition
1939//                    + " mExpandedParams.y=" + mExpandedParams.y
1940//                    + " mExpandedParams.height=" + mExpandedParams.height);
1941//        }
1942    }
1943
1944    int getExpandedHeight(int disph) {
1945        if (DEBUG) {
1946            Slog.d(TAG, "getExpandedHeight(" + disph + "): sbView="
1947                    + mStatusBarView.getHeight() + " closeView=" + mCloseView.getHeight());
1948        }
1949        return disph; // - mStatusBarView.getHeight();
1950    }
1951
1952    void updateDisplaySize() {
1953        mDisplay.getMetrics(mDisplayMetrics);
1954        if (DEBUG) {
1955            Slog.d(TAG, "updateDisplaySize: " + mDisplayMetrics);
1956        }
1957        updateExpandedSize();
1958    }
1959
1960    void updateExpandedSize() {
1961        if (DEBUG) {
1962            Slog.d(TAG, "updateExpandedSize()");
1963        }
1964        if (mExpandedDialog != null && mExpandedParams != null && mDisplayMetrics != null) {
1965            mExpandedParams.width = mDisplayMetrics.widthPixels;
1966            mExpandedParams.height = getExpandedHeight(mDisplayMetrics.heightPixels);
1967            if (!mExpandedVisible) {
1968                updateExpandedInvisiblePosition();
1969            } else {
1970                mExpandedDialog.getWindow().setAttributes(mExpandedParams);
1971            }
1972            if (DEBUG) {
1973                Slog.d(TAG, "updateExpandedSize: height=" + mExpandedParams.height + " " +
1974                    (mExpandedVisible ? "VISIBLE":"INVISIBLE"));
1975            }
1976        }
1977    }
1978
1979    /**
1980     * The LEDs are turned o)ff when the notification panel is shown, even just a little bit.
1981     * This was added last-minute and is inconsistent with the way the rest of the notifications
1982     * are handled, because the notification isn't really cancelled.  The lights are just
1983     * turned off.  If any other notifications happen, the lights will turn back on.  Steve says
1984     * this is what he wants. (see bug 1131461)
1985     */
1986    void visibilityChanged(boolean visible) {
1987        if (mPanelSlightlyVisible != visible) {
1988            mPanelSlightlyVisible = visible;
1989            try {
1990                mBarService.onPanelRevealed();
1991            } catch (RemoteException ex) {
1992                // Won't fail unless the world has ended.
1993            }
1994        }
1995    }
1996
1997    void performDisableActions(int net) {
1998        int old = mDisabled;
1999        int diff = net ^ old;
2000        mDisabled = net;
2001
2002        // act accordingly
2003        if ((diff & StatusBarManager.DISABLE_EXPAND) != 0) {
2004            if ((net & StatusBarManager.DISABLE_EXPAND) != 0) {
2005                Slog.d(TAG, "DISABLE_EXPAND: yes");
2006                animateCollapse();
2007            }
2008        }
2009        if ((diff & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
2010            if ((net & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
2011                Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: yes");
2012                if (mTicking) {
2013                    mNotificationIcons.setVisibility(View.INVISIBLE);
2014                    mTicker.halt();
2015                } else {
2016                    setNotificationIconVisibility(false, com.android.internal.R.anim.fade_out);
2017                }
2018            } else {
2019                Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: no");
2020                if (!mExpandedVisible) {
2021                    setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
2022                }
2023            }
2024        } else if ((diff & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
2025            if (mTicking && (net & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
2026                mTicker.halt();
2027            }
2028        }
2029    }
2030
2031    private View.OnClickListener mClearButtonListener = new View.OnClickListener() {
2032        final int mini(int a, int b) {
2033            return (b>a?a:b);
2034        }
2035        public void onClick(View v) {
2036            synchronized (mNotificationData) {
2037                // animate-swipe all dismissable notifications, then animate the shade closed
2038                int numChildren = mPile.getChildCount();
2039
2040                int scrollTop = mScrollView.getScrollY();
2041                int scrollBottom = scrollTop + mScrollView.getHeight();
2042                final ArrayList<View> snapshot = new ArrayList<View>(numChildren);
2043                for (int i=0; i<numChildren; i++) {
2044                    final View child = mPile.getChildAt(i);
2045                    if (mPile.canChildBeDismissed(child) && child.getBottom() > scrollTop &&
2046                            child.getTop() < scrollBottom) {
2047                        snapshot.add(child);
2048                    }
2049                }
2050                final int N = snapshot.size();
2051                new Thread(new Runnable() {
2052                    @Override
2053                    public void run() {
2054                        // Decrease the delay for every row we animate to give the sense of
2055                        // accelerating the swipes
2056                        final int ROW_DELAY_DECREMENT = 10;
2057                        int currentDelay = 140;
2058                        int totalDelay = 0;
2059
2060                        // Set the shade-animating state to avoid doing other work during
2061                        // all of these animations. In particular, avoid layout and
2062                        // redrawing when collapsing the shade.
2063                        mPile.setViewRemoval(false);
2064
2065                        mPostCollapseCleanup = new Runnable() {
2066                            public void run() {
2067                                try {
2068                                    mPile.setViewRemoval(true);
2069                                    mBarService.onClearAllNotifications();
2070                                } catch (Exception ex) { }
2071                            }
2072                        };
2073
2074                        View sampleView = snapshot.get(0);
2075                        int width = sampleView.getWidth();
2076                        final int velocity = (int)(width * 8); // 1000/8 = 125 ms duration
2077                        for (View v : snapshot) {
2078                            final View _v = v;
2079                            mHandler.postDelayed(new Runnable() {
2080                                @Override
2081                                public void run() {
2082                                    mPile.dismissRowAnimated(_v, velocity);
2083                                }
2084                            }, totalDelay);
2085                            currentDelay = Math.max(50, currentDelay - ROW_DELAY_DECREMENT);
2086                            totalDelay += currentDelay;
2087                        }
2088                        // Delay the collapse animation until after all swipe animations have
2089                        // finished. Provide some buffer because there may be some extra delay
2090                        // before actually starting each swipe animation. Ideally, we'd
2091                        // synchronize the end of those animations with the start of the collaps
2092                        // exactly.
2093                        mHandler.postDelayed(new Runnable() {
2094                            public void run() {
2095                                animateCollapse(false);
2096                            }
2097                        }, totalDelay + 225);
2098                    }
2099                }).start();
2100            }
2101        }
2102    };
2103
2104    private View.OnClickListener mSettingsButtonListener = new View.OnClickListener() {
2105        public void onClick(View v) {
2106            try {
2107                // Dismiss the lock screen when Settings starts.
2108                ActivityManagerNative.getDefault().dismissKeyguardOnNextActivity();
2109            } catch (RemoteException e) {
2110            }
2111            v.getContext().startActivity(new Intent(Settings.ACTION_SETTINGS)
2112                    .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
2113            animateCollapse();
2114        }
2115    };
2116
2117    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
2118        public void onReceive(Context context, Intent intent) {
2119            String action = intent.getAction();
2120            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)
2121                    || Intent.ACTION_SCREEN_OFF.equals(action)) {
2122                boolean excludeRecents = false;
2123                if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
2124                    String reason = intent.getStringExtra("reason");
2125                    if (reason != null) {
2126                        excludeRecents = reason.equals("recentapps");
2127                    }
2128                }
2129                animateCollapse(excludeRecents);
2130            }
2131            else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
2132                repositionNavigationBar();
2133                updateResources();
2134            }
2135        }
2136    };
2137
2138    private void setIntruderAlertVisibility(boolean vis) {
2139        if (DEBUG) {
2140            Slog.v(TAG, (vis ? "showing" : "hiding") + " intruder alert window");
2141        }
2142        mIntruderAlertView.setVisibility(vis ? View.VISIBLE : View.GONE);
2143    }
2144
2145    public void dismissIntruder() {
2146        if (mCurrentlyIntrudingNotification == null) return;
2147
2148        try {
2149            mBarService.onNotificationClear(
2150                    mCurrentlyIntrudingNotification.pkg,
2151                    mCurrentlyIntrudingNotification.tag,
2152                    mCurrentlyIntrudingNotification.id);
2153        } catch (android.os.RemoteException ex) {
2154            // oh well
2155        }
2156    }
2157
2158    /**
2159     * Reload some of our resources when the configuration changes.
2160     *
2161     * We don't reload everything when the configuration changes -- we probably
2162     * should, but getting that smooth is tough.  Someday we'll fix that.  In the
2163     * meantime, just update the things that we know change.
2164     */
2165    void updateResources() {
2166        final Context context = mContext;
2167        final Resources res = context.getResources();
2168
2169        if (mClearButton instanceof TextView) {
2170            ((TextView)mClearButton).setText(context.getText(R.string.status_bar_clear_all_button));
2171        }
2172        loadDimens();
2173    }
2174
2175    protected void loadDimens() {
2176        final Resources res = mContext.getResources();
2177
2178        mNaturalBarHeight = res.getDimensionPixelSize(
2179                com.android.internal.R.dimen.status_bar_height);
2180
2181        int newIconSize = res.getDimensionPixelSize(
2182            com.android.internal.R.dimen.status_bar_icon_size);
2183        int newIconHPadding = res.getDimensionPixelSize(
2184            R.dimen.status_bar_icon_padding);
2185
2186        if (newIconHPadding != mIconHPadding || newIconSize != mIconSize) {
2187//            Slog.d(TAG, "size=" + newIconSize + " padding=" + newIconHPadding);
2188            mIconHPadding = newIconHPadding;
2189            mIconSize = newIconSize;
2190            //reloadAllNotificationIcons(); // reload the tray
2191        }
2192
2193        mEdgeBorder = res.getDimensionPixelSize(R.dimen.status_bar_edge_ignore);
2194
2195        mSelfExpandVelocityPx = res.getDimension(R.dimen.self_expand_velocity);
2196        mSelfCollapseVelocityPx = res.getDimension(R.dimen.self_collapse_velocity);
2197        mFlingExpandMinVelocityPx = res.getDimension(R.dimen.fling_expand_min_velocity);
2198        mFlingCollapseMinVelocityPx = res.getDimension(R.dimen.fling_collapse_min_velocity);
2199
2200        mCollapseMinDisplayFraction = res.getFraction(R.dimen.collapse_min_display_fraction, 1, 1);
2201        mExpandMinDisplayFraction = res.getFraction(R.dimen.expand_min_display_fraction, 1, 1);
2202
2203        mExpandAccelPx = res.getDimension(R.dimen.expand_accel);
2204        mCollapseAccelPx = res.getDimension(R.dimen.collapse_accel);
2205
2206        mFlingGestureMaxXVelocityPx = res.getDimension(R.dimen.fling_gesture_max_x_velocity);
2207
2208        if (false) Slog.v(TAG, "updateResources");
2209    }
2210
2211    //
2212    // tracing
2213    //
2214
2215    void postStartTracing() {
2216        mHandler.postDelayed(mStartTracing, 3000);
2217    }
2218
2219    void vibrate() {
2220        android.os.Vibrator vib = (android.os.Vibrator)mContext.getSystemService(
2221                Context.VIBRATOR_SERVICE);
2222        vib.vibrate(250);
2223    }
2224
2225    public int getScoreThreshold() {
2226        return mDisplayMinScore;
2227    }
2228
2229    public void setScoreThreshold(int score) {
2230        // XXX HAX
2231        if (mDisplayMinScore != score) {
2232            this.mDisplayMinScore = score;
2233            applyScoreThreshold();
2234        }
2235    }
2236
2237    private void applyScoreThreshold() {
2238        int N = mNotificationData.size();
2239        for (int i=0; i<N; i++) {
2240            NotificationData.Entry entry = mNotificationData.get(i);
2241            int vis = (entry.notification.score < mDisplayMinScore)
2242                ? View.GONE
2243                : View.VISIBLE;
2244            entry.row.setVisibility(vis);
2245            entry.icon.setVisibility(vis);
2246        }
2247    }
2248
2249    Runnable mStartTracing = new Runnable() {
2250        public void run() {
2251            vibrate();
2252            SystemClock.sleep(250);
2253            Slog.d(TAG, "startTracing");
2254            android.os.Debug.startMethodTracing("/data/statusbar-traces/trace");
2255            mHandler.postDelayed(mStopTracing, 10000);
2256        }
2257    };
2258
2259    Runnable mStopTracing = new Runnable() {
2260        public void run() {
2261            android.os.Debug.stopMethodTracing();
2262            Slog.d(TAG, "stopTracing");
2263            vibrate();
2264        }
2265    };
2266}
2267
2268