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