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