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