PhoneStatusBar.java revision 69314e72941c86734c12476d1e61459811159b74
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                if (mNavigationBarView != null) {
1509                    mNavigationBarView.setLowProfile(lightsOut);
1510                }
1511            }
1512
1513            notifyUiVisibilityChanged();
1514        }
1515    }
1516
1517    public void setLightsOn(boolean on) {
1518        Log.v(TAG, "setLightsOn(" + on + ")");
1519        if (on) {
1520            setSystemUiVisibility(mSystemUiVisibility & ~View.SYSTEM_UI_FLAG_LOW_PROFILE);
1521        } else {
1522            setSystemUiVisibility(mSystemUiVisibility | View.SYSTEM_UI_FLAG_LOW_PROFILE);
1523        }
1524    }
1525
1526    private void notifyUiVisibilityChanged() {
1527        try {
1528            mWindowManager.statusBarVisibilityChanged(mSystemUiVisibility);
1529        } catch (RemoteException ex) {
1530        }
1531    }
1532
1533    public void topAppWindowChanged(boolean showMenu) {
1534        if (DEBUG) {
1535            Slog.d(TAG, (showMenu?"showing":"hiding") + " the MENU button");
1536        }
1537        if (mNavigationBarView != null) {
1538            mNavigationBarView.getMenuButton().setVisibility(showMenu
1539                ? View.VISIBLE : View.INVISIBLE);
1540        }
1541
1542        // See above re: lights-out policy for legacy apps.
1543        if (showMenu) setLightsOn(true);
1544    }
1545
1546    // Not supported
1547    public void setImeWindowStatus(IBinder token, int vis, int backDisposition) { }
1548    @Override
1549    public void setHardKeyboardStatus(boolean available, boolean enabled) { }
1550
1551    public NotificationClicker makeClicker(PendingIntent intent, String pkg, String tag, int id) {
1552        return new NotificationClicker(intent, pkg, tag, id);
1553    }
1554
1555    private class NotificationClicker implements View.OnClickListener {
1556        private PendingIntent mIntent;
1557        private String mPkg;
1558        private String mTag;
1559        private int mId;
1560
1561        NotificationClicker(PendingIntent intent, String pkg, String tag, int id) {
1562            mIntent = intent;
1563            mPkg = pkg;
1564            mTag = tag;
1565            mId = id;
1566        }
1567
1568        public void onClick(View v) {
1569            try {
1570                // The intent we are sending is for the application, which
1571                // won't have permission to immediately start an activity after
1572                // the user switches to home.  We know it is safe to do at this
1573                // point, so make sure new activity switches are now allowed.
1574                ActivityManagerNative.getDefault().resumeAppSwitches();
1575            } catch (RemoteException e) {
1576            }
1577
1578            if (mIntent != null) {
1579                int[] pos = new int[2];
1580                v.getLocationOnScreen(pos);
1581                Intent overlay = new Intent();
1582                overlay.setSourceBounds(
1583                        new Rect(pos[0], pos[1], pos[0]+v.getWidth(), pos[1]+v.getHeight()));
1584                try {
1585                    mIntent.send(mContext, 0, overlay);
1586                } catch (PendingIntent.CanceledException e) {
1587                    // the stack trace isn't very helpful here.  Just log the exception message.
1588                    Slog.w(TAG, "Sending contentIntent failed: " + e);
1589                }
1590            }
1591
1592            try {
1593                mBarService.onNotificationClick(mPkg, mTag, mId);
1594            } catch (RemoteException ex) {
1595                // system process is dead if we're here.
1596            }
1597
1598            // close the shade if it was open
1599            animateCollapse();
1600
1601            // If this click was on the intruder alert, hide that instead
1602            mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
1603        }
1604    }
1605
1606    private void tick(StatusBarNotification n) {
1607        // Show the ticker if one is requested. Also don't do this
1608        // until status bar window is attached to the window manager,
1609        // because...  well, what's the point otherwise?  And trying to
1610        // run a ticker without being attached will crash!
1611        if (n.notification.tickerText != null && mStatusBarView.getWindowToken() != null) {
1612            if (0 == (mDisabled & (StatusBarManager.DISABLE_NOTIFICATION_ICONS
1613                            | StatusBarManager.DISABLE_NOTIFICATION_TICKER))) {
1614                mTicker.addEntry(n);
1615            }
1616        }
1617    }
1618
1619    /**
1620     * Cancel this notification and tell the StatusBarManagerService / NotificationManagerService
1621     * about the failure.
1622     *
1623     * WARNING: this will call back into us.  Don't hold any locks.
1624     */
1625    void handleNotificationError(IBinder key, StatusBarNotification n, String message) {
1626        removeNotification(key);
1627        try {
1628            mBarService.onNotificationError(n.pkg, n.tag, n.id, n.uid, n.initialPid, message);
1629        } catch (RemoteException ex) {
1630            // The end is nigh.
1631        }
1632    }
1633
1634    private class MyTicker extends Ticker {
1635        MyTicker(Context context, View sb) {
1636            super(context, sb);
1637        }
1638
1639        @Override
1640        public void tickerStarting() {
1641            mTicking = true;
1642            mIcons.setVisibility(View.GONE);
1643            mTickerView.setVisibility(View.VISIBLE);
1644            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_up_in, null));
1645            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.push_up_out, null));
1646        }
1647
1648        @Override
1649        public void tickerDone() {
1650            mIcons.setVisibility(View.VISIBLE);
1651            mTickerView.setVisibility(View.GONE);
1652            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.push_down_in, null));
1653            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_down_out,
1654                        mTickingDoneListener));
1655        }
1656
1657        public void tickerHalting() {
1658            mIcons.setVisibility(View.VISIBLE);
1659            mTickerView.setVisibility(View.GONE);
1660            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.fade_in, null));
1661            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.fade_out,
1662                        mTickingDoneListener));
1663        }
1664    }
1665
1666    Animation.AnimationListener mTickingDoneListener = new Animation.AnimationListener() {;
1667        public void onAnimationEnd(Animation animation) {
1668            mTicking = false;
1669        }
1670        public void onAnimationRepeat(Animation animation) {
1671        }
1672        public void onAnimationStart(Animation animation) {
1673        }
1674    };
1675
1676    private Animation loadAnim(int id, Animation.AnimationListener listener) {
1677        Animation anim = AnimationUtils.loadAnimation(mContext, id);
1678        if (listener != null) {
1679            anim.setAnimationListener(listener);
1680        }
1681        return anim;
1682    }
1683
1684    public String viewInfo(View v) {
1685        return "(" + v.getLeft() + "," + v.getTop() + ")(" + v.getRight() + "," + v.getBottom()
1686                + " " + v.getWidth() + "x" + v.getHeight() + ")";
1687    }
1688
1689    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1690        synchronized (mQueueLock) {
1691            pw.println("Current Status Bar state:");
1692            pw.println("  mExpanded=" + mExpanded
1693                    + ", mExpandedVisible=" + mExpandedVisible);
1694            pw.println("  mTicking=" + mTicking);
1695            pw.println("  mTracking=" + mTracking);
1696            pw.println("  mAnimating=" + mAnimating
1697                    + ", mAnimY=" + mAnimY + ", mAnimVel=" + mAnimVel
1698                    + ", mAnimAccel=" + mAnimAccel);
1699            pw.println("  mCurAnimationTime=" + mCurAnimationTime
1700                    + " mAnimLastTime=" + mAnimLastTime);
1701            pw.println("  mAnimatingReveal=" + mAnimatingReveal
1702                    + " mViewDelta=" + mViewDelta);
1703            pw.println("  mDisplayMetrics=" + mDisplayMetrics);
1704            pw.println("  mExpandedParams: " + mExpandedParams);
1705            pw.println("  mExpandedView: " + viewInfo(mExpandedView));
1706            pw.println("  mExpandedDialog: " + mExpandedDialog);
1707            pw.println("  mTrackingParams: " + mTrackingParams);
1708            pw.println("  mTrackingView: " + viewInfo(mTrackingView));
1709            pw.println("  mPile: " + viewInfo(mPile));
1710            pw.println("  mNoNotificationsTitle: " + viewInfo(mNoNotificationsTitle));
1711            pw.println("  mCloseView: " + viewInfo(mCloseView));
1712            pw.println("  mTickerView: " + viewInfo(mTickerView));
1713            pw.println("  mScrollView: " + viewInfo(mScrollView)
1714                    + " scroll " + mScrollView.getScrollX() + "," + mScrollView.getScrollY());
1715        }
1716
1717        if (DUMPTRUCK) {
1718            synchronized (mNotificationData) {
1719                int N = mNotificationData.size();
1720                pw.println("  notification icons: " + N);
1721                for (int i=0; i<N; i++) {
1722                    NotificationData.Entry e = mNotificationData.get(i);
1723                    pw.println("    [" + i + "] key=" + e.key + " icon=" + e.icon);
1724                    StatusBarNotification n = e.notification;
1725                    pw.println("         pkg=" + n.pkg + " id=" + n.id + " priority=" + n.priority);
1726                    pw.println("         notification=" + n.notification);
1727                    pw.println("         tickerText=\"" + n.notification.tickerText + "\"");
1728                }
1729            }
1730
1731            int N = mStatusIcons.getChildCount();
1732            pw.println("  system icons: " + N);
1733            for (int i=0; i<N; i++) {
1734                StatusBarIconView ic = (StatusBarIconView) mStatusIcons.getChildAt(i);
1735                pw.println("    [" + i + "] icon=" + ic);
1736            }
1737
1738            pw.println("see the logcat for a dump of the views we have created.");
1739            // must happen on ui thread
1740            mHandler.post(new Runnable() {
1741                    public void run() {
1742                        mStatusBarView.getLocationOnScreen(mAbsPos);
1743                        Slog.d(TAG, "mStatusBarView: ----- (" + mAbsPos[0] + "," + mAbsPos[1]
1744                                + ") " + mStatusBarView.getWidth() + "x"
1745                                + mStatusBarView.getHeight());
1746                        mStatusBarView.debug();
1747
1748                        mExpandedView.getLocationOnScreen(mAbsPos);
1749                        Slog.d(TAG, "mExpandedView: ----- (" + mAbsPos[0] + "," + mAbsPos[1]
1750                                + ") " + mExpandedView.getWidth() + "x"
1751                                + mExpandedView.getHeight());
1752                        mExpandedView.debug();
1753
1754                        mTrackingView.getLocationOnScreen(mAbsPos);
1755                        Slog.d(TAG, "mTrackingView: ----- (" + mAbsPos[0] + "," + mAbsPos[1]
1756                                + ") " + mTrackingView.getWidth() + "x"
1757                                + mTrackingView.getHeight());
1758                        mTrackingView.debug();
1759                    }
1760                });
1761        }
1762    }
1763
1764    void onBarViewAttached() {
1765        WindowManager.LayoutParams lp;
1766        int pixelFormat;
1767        Drawable bg;
1768
1769        /// ---------- Tracking View --------------
1770        pixelFormat = PixelFormat.RGBX_8888;
1771        bg = mTrackingView.getBackground();
1772        if (bg != null) {
1773            pixelFormat = bg.getOpacity();
1774        }
1775
1776        lp = new WindowManager.LayoutParams(
1777                ViewGroup.LayoutParams.MATCH_PARENT,
1778                ViewGroup.LayoutParams.MATCH_PARENT,
1779                WindowManager.LayoutParams.TYPE_STATUS_BAR_SUB_PANEL,
1780                0
1781                | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
1782                | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
1783                | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
1784                pixelFormat);
1785//        lp.token = mStatusBarView.getWindowToken();
1786        lp.gravity = Gravity.TOP | Gravity.FILL_HORIZONTAL;
1787        lp.setTitle("TrackingView");
1788        lp.y = mTrackingPosition;
1789        mTrackingParams = lp;
1790
1791        WindowManagerImpl.getDefault().addView(mTrackingView, lp);
1792    }
1793
1794    void onTrackingViewAttached() {
1795        WindowManager.LayoutParams lp;
1796        int pixelFormat;
1797
1798        /// ---------- Expanded View --------------
1799        pixelFormat = PixelFormat.TRANSLUCENT;
1800
1801        lp = mExpandedDialog.getWindow().getAttributes();
1802        lp.x = 0;
1803        mTrackingPosition = lp.y = mDisplayMetrics.heightPixels; // sufficiently large negative
1804        lp.type = WindowManager.LayoutParams.TYPE_STATUS_BAR_SUB_PANEL;
1805        lp.flags = 0
1806                | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
1807                | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
1808                | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
1809                | WindowManager.LayoutParams.FLAG_DITHER
1810                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
1811        lp.format = pixelFormat;
1812        lp.gravity = Gravity.TOP | Gravity.FILL_HORIZONTAL;
1813        lp.setTitle("StatusBarExpanded");
1814        mExpandedParams = lp;
1815        updateExpandedSize();
1816        mExpandedDialog.getWindow().setFormat(pixelFormat);
1817
1818        mExpandedDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
1819        mExpandedDialog.setContentView(mExpandedView,
1820                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1821                                           ViewGroup.LayoutParams.MATCH_PARENT));
1822        mExpandedDialog.getWindow().setBackgroundDrawable(null);
1823        mExpandedDialog.show();
1824    }
1825
1826    void setNotificationIconVisibility(boolean visible, int anim) {
1827        int old = mNotificationIcons.getVisibility();
1828        int v = visible ? View.VISIBLE : View.INVISIBLE;
1829        if (old != v) {
1830            mNotificationIcons.setVisibility(v);
1831            mNotificationIcons.startAnimation(loadAnim(anim, null));
1832        }
1833    }
1834
1835    void updateExpandedInvisiblePosition() {
1836        if (mTrackingView != null) {
1837            mTrackingPosition = -mDisplayMetrics.heightPixels;
1838            if (mTrackingParams != null) {
1839                mTrackingParams.y = mTrackingPosition;
1840                WindowManagerImpl.getDefault().updateViewLayout(mTrackingView, mTrackingParams);
1841            }
1842        }
1843        if (mExpandedParams != null) {
1844            mExpandedParams.y = -mDisplayMetrics.heightPixels;
1845            mExpandedDialog.getWindow().setAttributes(mExpandedParams);
1846        }
1847    }
1848
1849    void updateExpandedViewPos(int expandedPosition) {
1850        if (SPEW) {
1851            Slog.d(TAG, "updateExpandedViewPos before expandedPosition=" + expandedPosition
1852                    + " mTrackingParams.y=" + ((mTrackingParams == null) ? "?" : mTrackingParams.y)
1853                    + " mTrackingPosition=" + mTrackingPosition);
1854        }
1855
1856        int h = mStatusBarView.getHeight();
1857        int disph = mDisplayMetrics.heightPixels;
1858
1859        // If the expanded view is not visible, make sure they're still off screen.
1860        // Maybe the view was resized.
1861        if (!mExpandedVisible) {
1862            updateExpandedInvisiblePosition();
1863            return;
1864        }
1865
1866        // tracking view...
1867        int pos;
1868        if (expandedPosition == EXPANDED_FULL_OPEN) {
1869            pos = h;
1870        }
1871        else if (expandedPosition == EXPANDED_LEAVE_ALONE) {
1872            pos = mTrackingPosition;
1873        }
1874        else {
1875            if (expandedPosition <= disph) {
1876                pos = expandedPosition;
1877            } else {
1878                pos = disph;
1879            }
1880            pos -= disph-h;
1881        }
1882        mTrackingPosition = mTrackingParams.y = pos;
1883        mTrackingParams.height = disph-h;
1884        WindowManagerImpl.getDefault().updateViewLayout(mTrackingView, mTrackingParams);
1885
1886        if (mExpandedParams != null) {
1887            if (mCloseView.getWindowVisibility() == View.VISIBLE) {
1888                mCloseView.getLocationInWindow(mPositionTmp);
1889                final int closePos = mPositionTmp[1];
1890
1891                mExpandedContents.getLocationInWindow(mPositionTmp);
1892                final int contentsBottom = mPositionTmp[1] + mExpandedContents.getHeight();
1893
1894                mExpandedParams.y = pos + mTrackingView.getHeight()
1895                        - (mTrackingParams.height-closePos) - contentsBottom;
1896
1897                if (SPEW) {
1898                    Slog.d(PhoneStatusBar.TAG,
1899                            "pos=" + pos +
1900                            " trackingHeight=" + mTrackingView.getHeight() +
1901                            " (trackingParams.height - closePos)=" +
1902                                (mTrackingParams.height - closePos) +
1903                            " contentsBottom=" + contentsBottom);
1904                }
1905
1906            } else {
1907                // If the tracking view is not yet visible, then we can't have
1908                // a good value of the close view location.  We need to wait for
1909                // it to be visible to do a layout.
1910                mExpandedParams.y = -mDisplayMetrics.heightPixels;
1911            }
1912            int max = h;
1913            if (mExpandedParams.y > max) {
1914                mExpandedParams.y = max;
1915            }
1916            int min = mTrackingPosition;
1917            if (mExpandedParams.y < min) {
1918                mExpandedParams.y = min;
1919            }
1920
1921            boolean visible = (mTrackingPosition + mTrackingView.getHeight()) > h;
1922            if (!visible) {
1923                // if the contents aren't visible, move the expanded view way off screen
1924                // because the window itself extends below the content view.
1925                mExpandedParams.y = -disph;
1926            }
1927            mExpandedDialog.getWindow().setAttributes(mExpandedParams);
1928
1929            // As long as this isn't just a repositioning that's not supposed to affect
1930            // the user's perception of what's showing, call to say that the visibility
1931            // has changed. (Otherwise, someone else will call to do that).
1932            if (expandedPosition != EXPANDED_LEAVE_ALONE) {
1933                if (SPEW) Slog.d(TAG, "updateExpandedViewPos visibilityChanged(" + visible + ")");
1934                visibilityChanged(visible);
1935            }
1936        }
1937
1938        if (SPEW) {
1939            Slog.d(TAG, "updateExpandedViewPos after  expandedPosition=" + expandedPosition
1940                    + " mTrackingParams.y=" + mTrackingParams.y
1941                    + " mTrackingPosition=" + mTrackingPosition
1942                    + " mExpandedParams.y=" + mExpandedParams.y
1943                    + " mExpandedParams.height=" + mExpandedParams.height);
1944        }
1945    }
1946
1947    int getExpandedHeight(int disph) {
1948        if (DEBUG) {
1949            Slog.d(TAG, "getExpandedHeight(" + disph + "): sbView="
1950                    + mStatusBarView.getHeight() + " closeView=" + mCloseView.getHeight());
1951        }
1952        return disph - mStatusBarView.getHeight() - mCloseView.getHeight();
1953    }
1954
1955    void updateDisplaySize() {
1956        mDisplay.getMetrics(mDisplayMetrics);
1957        if (DEBUG) {
1958            Slog.d(TAG, "updateDisplaySize: " + mDisplayMetrics);
1959        }
1960        updateExpandedSize();
1961    }
1962
1963    void updateExpandedSize() {
1964        if (DEBUG) {
1965            Slog.d(TAG, "updateExpandedSize()");
1966        }
1967        if (mExpandedDialog != null && mExpandedParams != null && mDisplayMetrics != null) {
1968            mExpandedParams.width = mDisplayMetrics.widthPixels;
1969            mExpandedParams.height = getExpandedHeight(mDisplayMetrics.heightPixels);
1970            if (!mExpandedVisible) {
1971                updateExpandedInvisiblePosition();
1972            } else {
1973                mExpandedDialog.getWindow().setAttributes(mExpandedParams);
1974            }
1975            if (DEBUG) {
1976                Slog.d(TAG, "updateExpandedSize: height=" + mExpandedParams.height + " " +
1977                    (mExpandedVisible ? "VISIBLE":"INVISIBLE"));
1978            }
1979        }
1980    }
1981
1982    // The user is not allowed to get stuck without navigation UI. Upon the slightest user
1983    // interaction we bring the navigation back.
1984    public void userActivity() {
1985        if (mNavigationBarView != null) {
1986            mNavigationBarView.setHidden(false);
1987        }
1988    }
1989
1990    public void toggleRecentApps() {
1991        int msg = (mRecentsPanel.getVisibility() == View.GONE)
1992                ? MSG_OPEN_RECENTS_PANEL : MSG_CLOSE_RECENTS_PANEL;
1993        mHandler.removeMessages(msg);
1994        mHandler.sendEmptyMessage(msg);
1995    }
1996
1997    /**
1998     * The LEDs are turned o)ff when the notification panel is shown, even just a little bit.
1999     * This was added last-minute and is inconsistent with the way the rest of the notifications
2000     * are handled, because the notification isn't really cancelled.  The lights are just
2001     * turned off.  If any other notifications happen, the lights will turn back on.  Steve says
2002     * this is what he wants. (see bug 1131461)
2003     */
2004    void visibilityChanged(boolean visible) {
2005        if (mPanelSlightlyVisible != visible) {
2006            mPanelSlightlyVisible = visible;
2007            try {
2008                mBarService.onPanelRevealed();
2009            } catch (RemoteException ex) {
2010                // Won't fail unless the world has ended.
2011            }
2012        }
2013    }
2014
2015    void performDisableActions(int net) {
2016        int old = mDisabled;
2017        int diff = net ^ old;
2018        mDisabled = net;
2019
2020        // act accordingly
2021        if ((diff & StatusBarManager.DISABLE_EXPAND) != 0) {
2022            if ((net & StatusBarManager.DISABLE_EXPAND) != 0) {
2023                Slog.d(TAG, "DISABLE_EXPAND: yes");
2024                animateCollapse();
2025            }
2026        }
2027        if ((diff & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
2028            if ((net & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
2029                Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: yes");
2030                if (mTicking) {
2031                    mNotificationIcons.setVisibility(View.INVISIBLE);
2032                    mTicker.halt();
2033                } else {
2034                    setNotificationIconVisibility(false, com.android.internal.R.anim.fade_out);
2035                }
2036            } else {
2037                Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: no");
2038                if (!mExpandedVisible) {
2039                    setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
2040                }
2041            }
2042        } else if ((diff & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
2043            if (mTicking && (net & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
2044                mTicker.halt();
2045            }
2046        }
2047    }
2048
2049    private View.OnClickListener mClearButtonListener = new View.OnClickListener() {
2050        public void onClick(View v) {
2051            try {
2052                mBarService.onClearAllNotifications();
2053            } catch (RemoteException ex) {
2054                // system process is dead if we're here.
2055            }
2056            animateCollapse();
2057        }
2058    };
2059
2060    private View.OnClickListener mSettingsButtonListener = new View.OnClickListener() {
2061        public void onClick(View v) {
2062            v.getContext().startActivity(new Intent(Settings.ACTION_SETTINGS)
2063                    .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
2064            animateCollapse();
2065        }
2066    };
2067
2068    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
2069        public void onReceive(Context context, Intent intent) {
2070            String action = intent.getAction();
2071            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)
2072                    || Intent.ACTION_SCREEN_OFF.equals(action)) {
2073                boolean excludeRecents = false;
2074                if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
2075                    String reason = intent.getStringExtra("reason");
2076                    if (reason != null) {
2077                        excludeRecents = reason.equals("recentapps");
2078                    }
2079                }
2080                animateCollapse(excludeRecents);
2081            }
2082            else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
2083                repositionNavigationBar();
2084                updateResources();
2085            }
2086        }
2087    };
2088
2089    private void setIntruderAlertVisibility(boolean vis) {
2090        mIntruderAlertView.setVisibility(vis ? View.VISIBLE : View.GONE);
2091    }
2092
2093    /**
2094     * Reload some of our resources when the configuration changes.
2095     *
2096     * We don't reload everything when the configuration changes -- we probably
2097     * should, but getting that smooth is tough.  Someday we'll fix that.  In the
2098     * meantime, just update the things that we know change.
2099     */
2100    void updateResources() {
2101        final Context context = mContext;
2102        final Resources res = context.getResources();
2103
2104        if (mClearButton instanceof TextView) {
2105            ((TextView)mClearButton).setText(context.getText(R.string.status_bar_clear_all_button));
2106        }
2107        mNoNotificationsTitle.setText(context.getText(R.string.status_bar_no_notifications_title));
2108
2109        loadDimens();
2110    }
2111
2112    protected void loadDimens() {
2113        final Resources res = mContext.getResources();
2114
2115        mNaturalBarHeight = res.getDimensionPixelSize(
2116                com.android.internal.R.dimen.status_bar_height);
2117
2118        int newIconSize = res.getDimensionPixelSize(
2119            com.android.internal.R.dimen.status_bar_icon_size);
2120        int newIconHPadding = res.getDimensionPixelSize(
2121            R.dimen.status_bar_icon_padding);
2122
2123        if (newIconHPadding != mIconHPadding || newIconSize != mIconSize) {
2124//            Slog.d(TAG, "size=" + newIconSize + " padding=" + newIconHPadding);
2125            mIconHPadding = newIconHPadding;
2126            mIconSize = newIconSize;
2127            //reloadAllNotificationIcons(); // reload the tray
2128        }
2129
2130        mEdgeBorder = res.getDimensionPixelSize(R.dimen.status_bar_edge_ignore);
2131
2132        if (false) Slog.v(TAG, "updateResources");
2133    }
2134
2135    //
2136    // tracing
2137    //
2138
2139    void postStartTracing() {
2140        mHandler.postDelayed(mStartTracing, 3000);
2141    }
2142
2143    void vibrate() {
2144        android.os.Vibrator vib = (android.os.Vibrator)mContext.getSystemService(
2145                Context.VIBRATOR_SERVICE);
2146        vib.vibrate(250);
2147    }
2148
2149    Runnable mStartTracing = new Runnable() {
2150        public void run() {
2151            vibrate();
2152            SystemClock.sleep(250);
2153            Slog.d(TAG, "startTracing");
2154            android.os.Debug.startMethodTracing("/data/statusbar-traces/trace");
2155            mHandler.postDelayed(mStopTracing, 10000);
2156        }
2157    };
2158
2159    Runnable mStopTracing = new Runnable() {
2160        public void run() {
2161            android.os.Debug.stopMethodTracing();
2162            Slog.d(TAG, "stopTracing");
2163            vibrate();
2164        }
2165    };
2166
2167    public class TouchOutsideListener implements View.OnTouchListener {
2168        private int mMsg;
2169        private RecentsPanelView mPanel;
2170
2171        public TouchOutsideListener(int msg, RecentsPanelView panel) {
2172            mMsg = msg;
2173            mPanel = panel;
2174        }
2175
2176        public boolean onTouch(View v, MotionEvent ev) {
2177            final int action = ev.getAction();
2178            if (action == MotionEvent.ACTION_OUTSIDE
2179                || (action == MotionEvent.ACTION_DOWN
2180                    && !mPanel.isInContentArea((int)ev.getX(), (int)ev.getY()))) {
2181                mHandler.removeMessages(mMsg);
2182                mHandler.sendEmptyMessage(mMsg);
2183                return true;
2184            }
2185            return false;
2186        }
2187    }
2188}
2189
2190