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