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