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