PhoneStatusBar.java revision 1d4d30aebd2c22627131819cabfe95f97def2c83
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.app.Service;
20import android.app.ActivityManagerNative;
21import android.app.Dialog;
22import android.app.Notification;
23import android.app.PendingIntent;
24import android.app.Service;
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.graphics.PixelFormat;
32import android.graphics.Rect;
33import android.graphics.drawable.Drawable;
34import android.net.Uri;
35import android.os.IBinder;
36import android.os.RemoteException;
37import android.os.Handler;
38import android.os.Message;
39import android.os.ServiceManager;
40import android.os.SystemClock;
41import android.text.TextUtils;
42import android.util.Slog;
43import android.util.Log;
44import android.view.Display;
45import android.view.Gravity;
46import android.view.IWindowManager;
47import android.view.KeyEvent;
48import android.view.LayoutInflater;
49import android.view.MotionEvent;
50import android.view.Surface;
51import android.view.VelocityTracker;
52import android.view.View;
53import android.view.ViewGroup;
54import android.view.Window;
55import android.view.WindowManager;
56import android.view.WindowManagerImpl;
57import android.view.animation.Animation;
58import android.view.animation.AnimationUtils;
59import android.widget.ImageView;
60import android.widget.LinearLayout;
61import android.widget.RemoteViews;
62import android.widget.ScrollView;
63import android.widget.TextView;
64import android.widget.FrameLayout;
65
66import java.io.FileDescriptor;
67import java.io.PrintWriter;
68import java.util.ArrayList;
69import java.util.HashMap;
70import java.util.Set;
71
72import com.android.internal.statusbar.StatusBarIcon;
73import com.android.internal.statusbar.StatusBarIconList;
74import com.android.internal.statusbar.StatusBarNotification;
75
76import com.android.systemui.R;
77import com.android.systemui.statusbar.NotificationData;
78import com.android.systemui.statusbar.StatusBar;
79import com.android.systemui.statusbar.StatusBarIconView;
80import com.android.systemui.statusbar.policy.DateView;
81
82
83public class PhoneStatusBar extends StatusBar {
84    static final String TAG = "PhoneStatusBar";
85    static final boolean SPEW = false;
86
87    public static final String ACTION_STATUSBAR_START
88            = "com.android.internal.policy.statusbar.START";
89
90    static final int EXPANDED_LEAVE_ALONE = -10000;
91    static final int EXPANDED_FULL_OPEN = -10001;
92
93    private static final int MSG_ANIMATE = 1000;
94    private static final int MSG_ANIMATE_REVEAL = 1001;
95    private static final int MSG_SHOW_INTRUDER = 1002;
96    private static final int MSG_HIDE_INTRUDER = 1003;
97
98    // will likely move to a resource or other tunable param at some point
99    private static final int INTRUDER_ALERT_DECAY_MS = 10000;
100
101    PhoneStatusBarPolicy mIconPolicy;
102
103    int mIconSize;
104    Display mDisplay;
105
106    IWindowManager mWindowManager;
107
108    PhoneStatusBarView mStatusBarView;
109    int mPixelFormat;
110    H mHandler = new H();
111    Object mQueueLock = new Object();
112
113    // icons
114    LinearLayout mIcons;
115    IconMerger mNotificationIcons;
116    LinearLayout mStatusIcons;
117
118    // expanded notifications
119    Dialog mExpandedDialog;
120    ExpandedView mExpandedView;
121    WindowManager.LayoutParams mExpandedParams;
122    ScrollView mScrollView;
123    View mNotificationLinearLayout;
124    View mExpandedContents;
125    // top bar
126    TextView mNoNotificationsTitle;
127    TextView mClearButton;
128    // drag bar
129    CloseDragHandle mCloseView;
130    // ongoing
131    NotificationData mOngoing = new NotificationData();
132    TextView mOngoingTitle;
133    LinearLayout mOngoingItems;
134    // latest
135    NotificationData mLatest = new NotificationData();
136    TextView mLatestTitle;
137    LinearLayout mLatestItems;
138    // position
139    int[] mPositionTmp = new int[2];
140    boolean mExpanded;
141    boolean mExpandedVisible;
142
143    // the date view
144    DateView mDateView;
145
146    // for immersive activities
147    private View mIntruderAlertView;
148
149    // on-screen navigation buttons
150    private NavigationBarView mNavigationBarView;
151
152    // the tracker view
153    TrackingView mTrackingView;
154    WindowManager.LayoutParams mTrackingParams;
155    int mTrackingPosition; // the position of the top of the tracking view.
156    private boolean mPanelSlightlyVisible;
157
158    // ticker
159    private Ticker mTicker;
160    private View mTickerView;
161    private boolean mTicking;
162
163    // Tracking finger for opening/closing.
164    int mEdgeBorder; // corresponds to R.dimen.status_bar_edge_ignore
165    boolean mTracking;
166    VelocityTracker mVelocityTracker;
167
168    static final int ANIM_FRAME_DURATION = (1000/60);
169
170    boolean mAnimating;
171    long mCurAnimationTime;
172    float mDisplayHeight;
173    float mAnimY;
174    float mAnimVel;
175    float mAnimAccel;
176    long mAnimLastTime;
177    boolean mAnimatingReveal = false;
178    int mViewDelta;
179    int[] mAbsPos = new int[2];
180
181    // for disabling the status bar
182    int mDisabled = 0;
183
184    private class ExpandedDialog extends Dialog {
185        ExpandedDialog(Context context) {
186            super(context, com.android.internal.R.style.Theme_Light_NoTitleBar);
187        }
188
189        @Override
190        public boolean dispatchKeyEvent(KeyEvent event) {
191            boolean down = event.getAction() == KeyEvent.ACTION_DOWN;
192            switch (event.getKeyCode()) {
193            case KeyEvent.KEYCODE_BACK:
194                if (!down) {
195                    animateCollapse();
196                }
197                return true;
198            }
199            return super.dispatchKeyEvent(event);
200        }
201    }
202
203    @Override
204    public void start() {
205        mDisplay = ((WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE))
206                .getDefaultDisplay();
207
208        mWindowManager = IWindowManager.Stub.asInterface(
209                ServiceManager.getService(Context.WINDOW_SERVICE));
210
211        super.start();
212
213        addNavigationBar();
214
215        //addIntruderView();
216
217        // Lastly, call to the icon policy to install/update all the icons.
218        mIconPolicy = new PhoneStatusBarPolicy(mContext);
219    }
220
221    // ================================================================================
222    // Constructing the view
223    // ================================================================================
224    protected View makeStatusBarView() {
225        final Context context = mContext;
226
227        Resources res = context.getResources();
228
229        mIconSize = res.getDimensionPixelSize(com.android.internal.R.dimen.status_bar_icon_size);
230
231        ExpandedView expanded = (ExpandedView)View.inflate(context,
232                R.layout.status_bar_expanded, null);
233        expanded.mService = this;
234
235        mIntruderAlertView = View.inflate(context, R.layout.intruder_alert, null);
236        mIntruderAlertView.setVisibility(View.GONE);
237        mIntruderAlertView.setClickable(true);
238
239        mNavigationBarView =
240            (NavigationBarView) View.inflate(context, R.layout.navigation_bar, null);
241
242        PhoneStatusBarView sb = (PhoneStatusBarView)View.inflate(context,
243                R.layout.status_bar, null);
244        sb.mService = this;
245
246        // figure out which pixel-format to use for the status bar.
247        mPixelFormat = PixelFormat.TRANSLUCENT;
248        Drawable bg = sb.getBackground();
249        if (bg != null) {
250            mPixelFormat = bg.getOpacity();
251        }
252
253        mStatusBarView = sb;
254        mStatusIcons = (LinearLayout)sb.findViewById(R.id.statusIcons);
255        mNotificationIcons = (IconMerger)sb.findViewById(R.id.notificationIcons);
256        mIcons = (LinearLayout)sb.findViewById(R.id.icons);
257        mTickerView = sb.findViewById(R.id.ticker);
258        mDateView = (DateView)sb.findViewById(R.id.date);
259
260        mExpandedDialog = new ExpandedDialog(context);
261        mExpandedView = expanded;
262        mExpandedContents = expanded.findViewById(R.id.notificationLinearLayout);
263        mOngoingTitle = (TextView)expanded.findViewById(R.id.ongoingTitle);
264        mOngoingItems = (LinearLayout)expanded.findViewById(R.id.ongoingItems);
265        mLatestTitle = (TextView)expanded.findViewById(R.id.latestTitle);
266        mLatestItems = (LinearLayout)expanded.findViewById(R.id.latestItems);
267        mNoNotificationsTitle = (TextView)expanded.findViewById(R.id.noNotificationsTitle);
268        mClearButton = (TextView)expanded.findViewById(R.id.clear_all_button);
269        mClearButton.setOnClickListener(mClearButtonListener);
270        mScrollView = (ScrollView)expanded.findViewById(R.id.scroll);
271        mNotificationLinearLayout = expanded.findViewById(R.id.notificationLinearLayout);
272
273        mOngoingTitle.setVisibility(View.GONE);
274        mLatestTitle.setVisibility(View.GONE);
275
276        mTicker = new MyTicker(context, sb);
277
278        TickerView tickerView = (TickerView)sb.findViewById(R.id.tickerText);
279        tickerView.mTicker = mTicker;
280
281        mTrackingView = (TrackingView)View.inflate(context, R.layout.status_bar_tracking, null);
282        mTrackingView.mService = this;
283        mCloseView = (CloseDragHandle)mTrackingView.findViewById(R.id.close);
284        mCloseView.mService = this;
285
286        mEdgeBorder = res.getDimensionPixelSize(R.dimen.status_bar_edge_ignore);
287
288        // set the inital view visibility
289        setAreThereNotifications();
290        mDateView.setVisibility(View.INVISIBLE);
291
292        // receive broadcasts
293        IntentFilter filter = new IntentFilter();
294        filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
295        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
296        filter.addAction(Intent.ACTION_SCREEN_OFF);
297        context.registerReceiver(mBroadcastReceiver, filter);
298
299        return sb;
300    }
301
302    protected int getStatusBarGravity() {
303        return Gravity.TOP | Gravity.FILL_HORIZONTAL;
304    }
305
306    public int getStatusBarHeight() {
307        final Resources res = mContext.getResources();
308        return res.getDimensionPixelSize(com.android.internal.R.dimen.status_bar_height);
309    }
310
311    // For small-screen devices (read: phones) that lack hardware navigation buttons
312    private void addNavigationBar() {
313        mNavigationBarView.reorient();
314        WindowManagerImpl.getDefault().addView(
315                mNavigationBarView, getNavigationBarLayoutParams());
316    }
317
318    private void repositionNavigationBar() {
319        mNavigationBarView.reorient();
320        WindowManagerImpl.getDefault().updateViewLayout(
321                mNavigationBarView, getNavigationBarLayoutParams());
322    }
323
324    private WindowManager.LayoutParams getNavigationBarLayoutParams() {
325        final int rotation = mDisplay.getRotation();
326        final boolean sideways =
327            (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270);
328
329        final Resources res = mContext.getResources();
330        final int size = res.getDimensionPixelSize(R.dimen.navigation_bar_size);
331
332        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
333                sideways ? size : ViewGroup.LayoutParams.MATCH_PARENT,
334                sideways ? ViewGroup.LayoutParams.MATCH_PARENT : size,
335                WindowManager.LayoutParams.TYPE_NAVIGATION_BAR,
336                    0
337                    | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
338                    | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
339                    | WindowManager.LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING
340                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
341                    | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
342                PixelFormat.TRANSLUCENT);
343
344        lp.setTitle("NavigationBar");
345        switch (rotation) {
346            case Surface.ROTATION_90:
347                // device has been turned 90deg counter-clockwise
348                lp.gravity = Gravity.RIGHT | Gravity.FILL_VERTICAL;
349                break;
350            case Surface.ROTATION_270:
351                // device has been turned 90deg clockwise
352                lp.gravity = Gravity.LEFT | Gravity.FILL_VERTICAL;
353                break;
354            default:
355                lp.gravity = Gravity.BOTTOM | Gravity.FILL_HORIZONTAL;
356                break;
357        }
358        lp.windowAnimations = 0;
359
360        return lp;
361    }
362
363    private void addIntruderView() {
364        final int height = getStatusBarHeight();
365
366        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
367                ViewGroup.LayoutParams.MATCH_PARENT,
368                ViewGroup.LayoutParams.WRAP_CONTENT,
369                WindowManager.LayoutParams.TYPE_STATUS_BAR_SUB_PANEL,
370                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
371                    | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
372                    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
373                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
374                    | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
375                    | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH,
376                PixelFormat.TRANSLUCENT);
377        lp.gravity = Gravity.TOP | Gravity.FILL_HORIZONTAL;
378        lp.y += height * 1.5; // FIXME
379        lp.setTitle("IntruderAlert");
380        lp.windowAnimations = com.android.internal.R.style.Animation_StatusBar_IntruderAlert;
381
382        WindowManagerImpl.getDefault().addView(mIntruderAlertView, lp);
383    }
384
385    public void addIcon(String slot, int index, int viewIndex, StatusBarIcon icon) {
386        if (SPEW) Slog.d(TAG, "addIcon slot=" + slot + " index=" + index + " viewIndex=" + viewIndex
387                + " icon=" + icon);
388        StatusBarIconView view = new StatusBarIconView(mContext, slot);
389        view.set(icon);
390        mStatusIcons.addView(view, viewIndex, new LinearLayout.LayoutParams(mIconSize, mIconSize));
391    }
392
393    public void updateIcon(String slot, int index, int viewIndex,
394            StatusBarIcon old, StatusBarIcon icon) {
395        if (SPEW) Slog.d(TAG, "updateIcon slot=" + slot + " index=" + index + " viewIndex=" + viewIndex
396                + " old=" + old + " icon=" + icon);
397        StatusBarIconView view = (StatusBarIconView)mStatusIcons.getChildAt(viewIndex);
398        view.set(icon);
399    }
400
401    public void removeIcon(String slot, int index, int viewIndex) {
402        if (SPEW) Slog.d(TAG, "removeIcon slot=" + slot + " index=" + index + " viewIndex=" + viewIndex);
403        mStatusIcons.removeViewAt(viewIndex);
404    }
405
406    public void addNotification(IBinder key, StatusBarNotification notification) {
407        StatusBarIconView iconView = addNotificationViews(key, notification);
408        if (iconView == null) return;
409
410        boolean immersive = false;
411        try {
412            immersive = ActivityManagerNative.getDefault().isTopActivityImmersive();
413            Slog.d(TAG, "Top activity is " + (immersive?"immersive":"not immersive"));
414        } catch (RemoteException ex) {
415        }
416        if (immersive) {
417            if ((notification.notification.flags & Notification.FLAG_HIGH_PRIORITY) != 0) {
418                Slog.d(TAG, "Presenting high-priority notification in immersive activity");
419                // special new transient ticker mode
420                // 1. Populate mIntruderAlertView
421
422                ImageView alertIcon = (ImageView) mIntruderAlertView.findViewById(R.id.alertIcon);
423                TextView alertText = (TextView) mIntruderAlertView.findViewById(R.id.alertText);
424                alertIcon.setImageDrawable(StatusBarIconView.getIcon(
425                    alertIcon.getContext(),
426                    iconView.getStatusBarIcon()));
427                alertText.setText(notification.notification.tickerText);
428
429                View button = mIntruderAlertView.findViewById(R.id.intruder_alert_content);
430                button.setOnClickListener(
431                    new Launcher(notification.notification.contentIntent,
432                        notification.pkg, notification.tag, notification.id));
433
434                // 2. Animate mIntruderAlertView in
435                mHandler.sendEmptyMessage(MSG_SHOW_INTRUDER);
436
437                // 3. Set alarm to age the notification off (TODO)
438                mHandler.removeMessages(MSG_HIDE_INTRUDER);
439                mHandler.sendEmptyMessageDelayed(MSG_HIDE_INTRUDER, INTRUDER_ALERT_DECAY_MS);
440            }
441        } else if (notification.notification.fullScreenIntent != null) {
442            // not immersive & a full-screen alert should be shown
443            Slog.d(TAG, "Notification has fullScreenIntent and activity is not immersive;"
444                    + " sending fullScreenIntent");
445            try {
446                notification.notification.fullScreenIntent.send();
447            } catch (PendingIntent.CanceledException e) {
448            }
449        } else {
450            // usual case: status bar visible & not immersive
451
452            // show the ticker
453            tick(notification);
454        }
455
456        // Recalculate the position of the sliding windows and the titles.
457        setAreThereNotifications();
458        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
459    }
460
461    public void updateNotification(IBinder key, StatusBarNotification notification) {
462        Slog.d(TAG, "updateNotification key=" + key + " notification=" + notification);
463
464        NotificationData oldList;
465        NotificationData.Entry oldEntry = mOngoing.findByKey(key);
466        if (oldEntry != null) {
467            oldList = mOngoing;
468        } else {
469            oldEntry = mLatest.findByKey(key);
470            if (oldEntry == null) {
471                Slog.w(TAG, "updateNotification for unknown key: " + key);
472                return;
473            }
474            oldList = mLatest;
475        }
476        final StatusBarNotification oldNotification = oldEntry.notification;
477        final RemoteViews oldContentView = oldNotification.notification.contentView;
478
479        final RemoteViews contentView = notification.notification.contentView;
480
481        if (false) {
482            Slog.d(TAG, "old notification: when=" + oldNotification.notification.when
483                    + " ongoing=" + oldNotification.isOngoing()
484                    + " expanded=" + oldEntry.expanded
485                    + " contentView=" + oldContentView);
486            Slog.d(TAG, "new notification: when=" + notification.notification.when
487                    + " ongoing=" + oldNotification.isOngoing()
488                    + " contentView=" + contentView);
489        }
490
491        // Can we just reapply the RemoteViews in place?  If when didn't change, the order
492        // didn't change.
493        if (notification.notification.when == oldNotification.notification.when
494                && notification.isOngoing() == oldNotification.isOngoing()
495                && oldEntry.expanded != null
496                && contentView != null && oldContentView != null
497                && contentView.getPackage() != null
498                && oldContentView.getPackage() != null
499                && oldContentView.getPackage().equals(contentView.getPackage())
500                && oldContentView.getLayoutId() == contentView.getLayoutId()) {
501            if (SPEW) Slog.d(TAG, "reusing notification");
502            oldEntry.notification = notification;
503            try {
504                // Reapply the RemoteViews
505                contentView.reapply(mContext, oldEntry.content);
506                // update the contentIntent
507                final PendingIntent contentIntent = notification.notification.contentIntent;
508                if (contentIntent != null) {
509                    oldEntry.content.setOnClickListener(new Launcher(contentIntent,
510                                notification.pkg, notification.tag, notification.id));
511                } else {
512                    oldEntry.content.setOnClickListener(null);
513                }
514                // Update the icon.
515                final StatusBarIcon ic = new StatusBarIcon(notification.pkg,
516                        notification.notification.icon, notification.notification.iconLevel,
517                        notification.notification.number);
518                if (!oldEntry.icon.set(ic)) {
519                    handleNotificationError(key, notification, "Couldn't update icon: " + ic);
520                    return;
521                }
522            }
523            catch (RuntimeException e) {
524                // It failed to add cleanly.  Log, and remove the view from the panel.
525                Slog.w(TAG, "Couldn't reapply views for package " + contentView.getPackage(), e);
526                removeNotificationViews(key);
527                addNotificationViews(key, notification);
528            }
529        } else {
530            if (SPEW) Slog.d(TAG, "not reusing notification");
531            removeNotificationViews(key);
532            addNotificationViews(key, notification);
533        }
534
535        // Restart the ticker if it's still running
536        if (notification.notification.tickerText != null
537                && !TextUtils.equals(notification.notification.tickerText,
538                    oldEntry.notification.notification.tickerText)) {
539            tick(notification);
540        }
541
542        // Recalculate the position of the sliding windows and the titles.
543        setAreThereNotifications();
544        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
545    }
546
547    public void removeNotification(IBinder key) {
548        if (SPEW) Slog.d(TAG, "removeNotification key=" + key);
549        StatusBarNotification old = removeNotificationViews(key);
550
551        if (old != null) {
552            // Cancel the ticker if it's still running
553            mTicker.removeEntry(old);
554
555            // Recalculate the position of the sliding windows and the titles.
556            setAreThereNotifications();
557            updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
558        }
559    }
560
561    private int chooseIconIndex(boolean isOngoing, int viewIndex) {
562        final int latestSize = mLatest.size();
563        if (isOngoing) {
564            return latestSize + (mOngoing.size() - viewIndex);
565        } else {
566            return latestSize - viewIndex;
567        }
568    }
569
570    View[] makeNotificationView(StatusBarNotification notification, ViewGroup parent) {
571        Notification n = notification.notification;
572        RemoteViews remoteViews = n.contentView;
573        if (remoteViews == null) {
574            return null;
575        }
576
577        // create the row view
578        LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(
579                Context.LAYOUT_INFLATER_SERVICE);
580        View row = inflater.inflate(R.layout.status_bar_notification_row, parent, false);
581
582        // wire up the veto button
583        View vetoButton = row.findViewById(R.id.veto);
584        if (notification.isClearable()) {
585            final String _pkg = notification.pkg;
586            final String _tag = notification.tag;
587            final int _id = notification.id;
588            vetoButton.setOnClickListener(new View.OnClickListener() {
589                    public void onClick(View v) {
590                        try {
591                            mBarService.onNotificationClear(_pkg, _tag, _id);
592                        } catch (RemoteException ex) {
593                            // system process is dead if we're here.
594                        }
595                    }
596                });
597        } else {
598            if ((notification.notification.flags & Notification.FLAG_ONGOING_EVENT) == 0) {
599                vetoButton.setVisibility(View.INVISIBLE);
600            } else {
601                vetoButton.setVisibility(View.GONE);
602            }
603        }
604
605        // the large icon
606        ImageView largeIcon = (ImageView)row.findViewById(R.id.large_icon);
607        if (notification.notification.largeIcon != null) {
608            largeIcon.setImageBitmap(notification.notification.largeIcon);
609        } else {
610            largeIcon.getLayoutParams().width = 0;
611            largeIcon.setVisibility(View.INVISIBLE);
612        }
613
614        // bind the click event to the content area
615        ViewGroup content = (ViewGroup)row.findViewById(R.id.content);
616        content.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
617        content.setOnFocusChangeListener(mFocusChangeListener);
618        PendingIntent contentIntent = n.contentIntent;
619        if (contentIntent != null) {
620            content.setOnClickListener(new Launcher(contentIntent, notification.pkg,
621                        notification.tag, notification.id));
622        } else {
623            content.setOnClickListener(null);
624        }
625
626        View expanded = null;
627        Exception exception = null;
628        try {
629            expanded = remoteViews.apply(mContext, content);
630        }
631        catch (RuntimeException e) {
632            exception = e;
633        }
634        if (expanded == null) {
635            String ident = notification.pkg + "/0x" + Integer.toHexString(notification.id);
636            Slog.e(TAG, "couldn't inflate view for notification " + ident, exception);
637            return null;
638        } else {
639            content.addView(expanded);
640            row.setDrawingCacheEnabled(true);
641        }
642
643        return new View[] { row, content, expanded };
644    }
645
646    StatusBarIconView addNotificationViews(IBinder key, StatusBarNotification notification) {
647        NotificationData list;
648        ViewGroup parent;
649        final boolean isOngoing = notification.isOngoing();
650        if (isOngoing) {
651            list = mOngoing;
652            parent = mOngoingItems;
653        } else {
654            list = mLatest;
655            parent = mLatestItems;
656        }
657        // Construct the expanded view.
658        final View[] views = makeNotificationView(notification, parent);
659        if (views == null) {
660            handleNotificationError(key, notification, "Couldn't expand RemoteViews for: "
661                    + notification);
662            return null;
663        }
664        final View row = views[0];
665        final View content = views[1];
666        final View expanded = views[2];
667        // Construct the icon.
668        final StatusBarIconView iconView = new StatusBarIconView(mContext,
669                notification.pkg + "/0x" + Integer.toHexString(notification.id));
670        final StatusBarIcon ic = new StatusBarIcon(notification.pkg, notification.notification.icon,
671                    notification.notification.iconLevel, notification.notification.number);
672        if (!iconView.set(ic)) {
673            handleNotificationError(key, notification, "Coulding create icon: " + ic);
674            return null;
675        }
676        // Add the expanded view.
677        final int viewIndex = list.add(key, notification, row, content, expanded, iconView);
678        parent.addView(row, viewIndex);
679        // Add the icon.
680        final int iconIndex = chooseIconIndex(isOngoing, viewIndex);
681        mNotificationIcons.addView(iconView, iconIndex);
682        return iconView;
683    }
684
685    StatusBarNotification removeNotificationViews(IBinder key) {
686        NotificationData.Entry entry = mOngoing.remove(key);
687        if (entry == null) {
688            entry = mLatest.remove(key);
689            if (entry == null) {
690                Slog.w(TAG, "removeNotification for unknown key: " + key);
691                return null;
692            }
693        }
694        // Remove the expanded view.
695        ((ViewGroup)entry.row.getParent()).removeView(entry.row);
696        // Remove the icon.
697        ((ViewGroup)entry.icon.getParent()).removeView(entry.icon);
698
699        return entry.notification;
700    }
701
702    private void setAreThereNotifications() {
703        boolean ongoing = mOngoing.hasVisibleItems();
704        boolean latest = mLatest.hasVisibleItems();
705
706        // (no ongoing notifications are clearable)
707        if (mLatest.hasClearableItems()) {
708            mClearButton.setVisibility(View.VISIBLE);
709        } else {
710            mClearButton.setVisibility(View.INVISIBLE);
711        }
712
713        mOngoingTitle.setVisibility(ongoing ? View.VISIBLE : View.GONE);
714        mLatestTitle.setVisibility(latest ? View.VISIBLE : View.GONE);
715
716        if (ongoing || latest) {
717            mNoNotificationsTitle.setVisibility(View.GONE);
718        } else {
719            mNoNotificationsTitle.setVisibility(View.VISIBLE);
720        }
721    }
722
723
724    /**
725     * State is one or more of the DISABLE constants from StatusBarManager.
726     */
727    public void disable(int state) {
728        final int old = mDisabled;
729        final int diff = state ^ old;
730        mDisabled = state;
731
732        if ((diff & StatusBarManager.DISABLE_EXPAND) != 0) {
733            if ((state & StatusBarManager.DISABLE_EXPAND) != 0) {
734                Slog.d(TAG, "DISABLE_EXPAND: yes");
735                animateCollapse();
736            }
737        }
738        if ((diff & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
739            if ((state & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
740                Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: yes");
741                if (mTicking) {
742                    mTicker.halt();
743                } else {
744                    setNotificationIconVisibility(false, com.android.internal.R.anim.fade_out);
745                }
746            } else {
747                Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: no");
748                if (!mExpandedVisible) {
749                    setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
750                }
751            }
752        } else if ((diff & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
753            if (mTicking && (state & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
754                Slog.d(TAG, "DISABLE_NOTIFICATION_TICKER: yes");
755                mTicker.halt();
756            }
757        }
758    }
759
760    /**
761     * All changes to the status bar and notifications funnel through here and are batched.
762     */
763    private class H extends Handler {
764        public void handleMessage(Message m) {
765            switch (m.what) {
766                case MSG_ANIMATE:
767                    doAnimation();
768                    break;
769                case MSG_ANIMATE_REVEAL:
770                    doRevealAnimation();
771                    break;
772                case MSG_SHOW_INTRUDER:
773                    setIntruderAlertVisibility(true);
774                    break;
775                case MSG_HIDE_INTRUDER:
776                    setIntruderAlertVisibility(false);
777                    break;
778            }
779        }
780    }
781
782    View.OnFocusChangeListener mFocusChangeListener = new View.OnFocusChangeListener() {
783        public void onFocusChange(View v, boolean hasFocus) {
784            // Because 'v' is a ViewGroup, all its children will be (un)selected
785            // too, which allows marqueeing to work.
786            v.setSelected(hasFocus);
787        }
788    };
789
790    private void makeExpandedVisible() {
791        if (SPEW) Slog.d(TAG, "Make expanded visible: expanded visible=" + mExpandedVisible);
792        if (mExpandedVisible) {
793            return;
794        }
795        mExpandedVisible = true;
796        visibilityChanged(true);
797
798        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
799        mExpandedParams.flags &= ~WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
800        mExpandedParams.flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
801        mExpandedDialog.getWindow().setAttributes(mExpandedParams);
802        mExpandedView.requestFocus(View.FOCUS_FORWARD);
803        mTrackingView.setVisibility(View.VISIBLE);
804
805        if (!mTicking) {
806            setDateViewVisibility(true, com.android.internal.R.anim.fade_in);
807        }
808    }
809
810    public void animateExpand() {
811        if (SPEW) Slog.d(TAG, "Animate expand: expanded=" + mExpanded);
812        if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
813            return ;
814        }
815        if (mExpanded) {
816            return;
817        }
818
819        prepareTracking(0, true);
820        performFling(0, 2000.0f, true);
821    }
822
823    public void animateCollapse() {
824        if (SPEW) {
825            Slog.d(TAG, "animateCollapse(): mExpanded=" + mExpanded
826                    + " mExpandedVisible=" + mExpandedVisible
827                    + " mExpanded=" + mExpanded
828                    + " mAnimating=" + mAnimating
829                    + " mAnimY=" + mAnimY
830                    + " mAnimVel=" + mAnimVel);
831        }
832
833        if (!mExpandedVisible) {
834            return;
835        }
836
837        int y;
838        if (mAnimating) {
839            y = (int)mAnimY;
840        } else {
841            y = mDisplay.getHeight()-1;
842        }
843        // Let the fling think that we're open so it goes in the right direction
844        // and doesn't try to re-open the windowshade.
845        mExpanded = true;
846        prepareTracking(y, false);
847        performFling(y, -2000.0f, true);
848    }
849
850    void performExpand() {
851        if (SPEW) Slog.d(TAG, "performExpand: mExpanded=" + mExpanded);
852        if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
853            return ;
854        }
855        if (mExpanded) {
856            return;
857        }
858
859        mExpanded = true;
860        makeExpandedVisible();
861        updateExpandedViewPos(EXPANDED_FULL_OPEN);
862
863        if (false) postStartTracing();
864    }
865
866    void performCollapse() {
867        if (SPEW) Slog.d(TAG, "performCollapse: mExpanded=" + mExpanded
868                + " mExpandedVisible=" + mExpandedVisible);
869
870        if (!mExpandedVisible) {
871            return;
872        }
873        mExpandedVisible = false;
874        visibilityChanged(false);
875        mExpandedParams.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
876        mExpandedParams.flags &= ~WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
877        mExpandedDialog.getWindow().setAttributes(mExpandedParams);
878        mTrackingView.setVisibility(View.GONE);
879
880        if ((mDisabled & StatusBarManager.DISABLE_NOTIFICATION_ICONS) == 0) {
881            setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
882        }
883        setDateViewVisibility(false, com.android.internal.R.anim.fade_out);
884
885        if (!mExpanded) {
886            return;
887        }
888        mExpanded = false;
889    }
890
891    void doAnimation() {
892        if (mAnimating) {
893            if (SPEW) Slog.d(TAG, "doAnimation");
894            if (SPEW) Slog.d(TAG, "doAnimation before mAnimY=" + mAnimY);
895            incrementAnim();
896            if (SPEW) Slog.d(TAG, "doAnimation after  mAnimY=" + mAnimY);
897            if (mAnimY >= mDisplay.getHeight()-1) {
898                if (SPEW) Slog.d(TAG, "Animation completed to expanded state.");
899                mAnimating = false;
900                updateExpandedViewPos(EXPANDED_FULL_OPEN);
901                performExpand();
902            }
903            else if (mAnimY < mStatusBarView.getHeight()) {
904                if (SPEW) Slog.d(TAG, "Animation completed to collapsed state.");
905                mAnimating = false;
906                updateExpandedViewPos(0);
907                performCollapse();
908            }
909            else {
910                updateExpandedViewPos((int)mAnimY);
911                mCurAnimationTime += ANIM_FRAME_DURATION;
912                mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE), mCurAnimationTime);
913            }
914        }
915    }
916
917    void stopTracking() {
918        mTracking = false;
919        mVelocityTracker.recycle();
920        mVelocityTracker = null;
921    }
922
923    void incrementAnim() {
924        long now = SystemClock.uptimeMillis();
925        float t = ((float)(now - mAnimLastTime)) / 1000;            // ms -> s
926        final float y = mAnimY;
927        final float v = mAnimVel;                                   // px/s
928        final float a = mAnimAccel;                                 // px/s/s
929        mAnimY = y + (v*t) + (0.5f*a*t*t);                          // px
930        mAnimVel = v + (a*t);                                       // px/s
931        mAnimLastTime = now;                                        // ms
932        //Slog.d(TAG, "y=" + y + " v=" + v + " a=" + a + " t=" + t + " mAnimY=" + mAnimY
933        //        + " mAnimAccel=" + mAnimAccel);
934    }
935
936    void doRevealAnimation() {
937        final int h = mCloseView.getHeight() + mStatusBarView.getHeight();
938        if (mAnimatingReveal && mAnimating && mAnimY < h) {
939            incrementAnim();
940            if (mAnimY >= h) {
941                mAnimY = h;
942                updateExpandedViewPos((int)mAnimY);
943            } else {
944                updateExpandedViewPos((int)mAnimY);
945                mCurAnimationTime += ANIM_FRAME_DURATION;
946                mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE_REVEAL),
947                        mCurAnimationTime);
948            }
949        }
950    }
951
952    void prepareTracking(int y, boolean opening) {
953        mTracking = true;
954        mVelocityTracker = VelocityTracker.obtain();
955        if (opening) {
956            mAnimAccel = 2000.0f;
957            mAnimVel = 200;
958            mAnimY = mStatusBarView.getHeight();
959            updateExpandedViewPos((int)mAnimY);
960            mAnimating = true;
961            mAnimatingReveal = true;
962            mHandler.removeMessages(MSG_ANIMATE);
963            mHandler.removeMessages(MSG_ANIMATE_REVEAL);
964            long now = SystemClock.uptimeMillis();
965            mAnimLastTime = now;
966            mCurAnimationTime = now + ANIM_FRAME_DURATION;
967            mAnimating = true;
968            mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE_REVEAL),
969                    mCurAnimationTime);
970            makeExpandedVisible();
971        } else {
972            // it's open, close it?
973            if (mAnimating) {
974                mAnimating = false;
975                mHandler.removeMessages(MSG_ANIMATE);
976            }
977            updateExpandedViewPos(y + mViewDelta);
978        }
979    }
980
981    void performFling(int y, float vel, boolean always) {
982        mAnimatingReveal = false;
983        mDisplayHeight = mDisplay.getHeight();
984
985        mAnimY = y;
986        mAnimVel = vel;
987
988        //Slog.d(TAG, "starting with mAnimY=" + mAnimY + " mAnimVel=" + mAnimVel);
989
990        if (mExpanded) {
991            if (!always && (
992                    vel > 200.0f
993                    || (y > (mDisplayHeight-25) && vel > -200.0f))) {
994                // We are expanded, but they didn't move sufficiently to cause
995                // us to retract.  Animate back to the expanded position.
996                mAnimAccel = 2000.0f;
997                if (vel < 0) {
998                    mAnimVel = 0;
999                }
1000            }
1001            else {
1002                // We are expanded and are now going to animate away.
1003                mAnimAccel = -2000.0f;
1004                if (vel > 0) {
1005                    mAnimVel = 0;
1006                }
1007            }
1008        } else {
1009            if (always || (
1010                    vel > 200.0f
1011                    || (y > (mDisplayHeight/2) && vel > -200.0f))) {
1012                // We are collapsed, and they moved enough to allow us to
1013                // expand.  Animate in the notifications.
1014                mAnimAccel = 2000.0f;
1015                if (vel < 0) {
1016                    mAnimVel = 0;
1017                }
1018            }
1019            else {
1020                // We are collapsed, but they didn't move sufficiently to cause
1021                // us to retract.  Animate back to the collapsed position.
1022                mAnimAccel = -2000.0f;
1023                if (vel > 0) {
1024                    mAnimVel = 0;
1025                }
1026            }
1027        }
1028        //Slog.d(TAG, "mAnimY=" + mAnimY + " mAnimVel=" + mAnimVel
1029        //        + " mAnimAccel=" + mAnimAccel);
1030
1031        long now = SystemClock.uptimeMillis();
1032        mAnimLastTime = now;
1033        mCurAnimationTime = now + ANIM_FRAME_DURATION;
1034        mAnimating = true;
1035        mHandler.removeMessages(MSG_ANIMATE);
1036        mHandler.removeMessages(MSG_ANIMATE_REVEAL);
1037        mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE), mCurAnimationTime);
1038        stopTracking();
1039    }
1040
1041    boolean interceptTouchEvent(MotionEvent event) {
1042        if (SPEW) {
1043            Slog.d(TAG, "Touch: rawY=" + event.getRawY() + " event=" + event + " mDisabled="
1044                + mDisabled);
1045        }
1046
1047        if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
1048            return false;
1049        }
1050
1051        final int statusBarSize = mStatusBarView.getHeight();
1052        final int hitSize = statusBarSize*2;
1053        if (event.getAction() == MotionEvent.ACTION_DOWN) {
1054            final int y = (int)event.getRawY();
1055
1056            if (!mExpanded) {
1057                mViewDelta = statusBarSize - y;
1058            } else {
1059                mTrackingView.getLocationOnScreen(mAbsPos);
1060                mViewDelta = mAbsPos[1] + mTrackingView.getHeight() - y;
1061            }
1062            if ((!mExpanded && y < hitSize) ||
1063                    (mExpanded && y > (mDisplay.getHeight()-hitSize))) {
1064
1065                // We drop events at the edge of the screen to make the windowshade come
1066                // down by accident less, especially when pushing open a device with a keyboard
1067                // that rotates (like g1 and droid)
1068                int x = (int)event.getRawX();
1069                final int edgeBorder = mEdgeBorder;
1070                if (x >= edgeBorder && x < mDisplay.getWidth() - edgeBorder) {
1071                    prepareTracking(y, !mExpanded);// opening if we're not already fully visible
1072                    mVelocityTracker.addMovement(event);
1073                }
1074            }
1075        } else if (mTracking) {
1076            mVelocityTracker.addMovement(event);
1077            final int minY = statusBarSize + mCloseView.getHeight();
1078            if (event.getAction() == MotionEvent.ACTION_MOVE) {
1079                int y = (int)event.getRawY();
1080                if (mAnimatingReveal && y < minY) {
1081                    // nothing
1082                } else  {
1083                    mAnimatingReveal = false;
1084                    updateExpandedViewPos(y + mViewDelta);
1085                }
1086            } else if (event.getAction() == MotionEvent.ACTION_UP) {
1087                mVelocityTracker.computeCurrentVelocity(1000);
1088
1089                float yVel = mVelocityTracker.getYVelocity();
1090                boolean negative = yVel < 0;
1091
1092                float xVel = mVelocityTracker.getXVelocity();
1093                if (xVel < 0) {
1094                    xVel = -xVel;
1095                }
1096                if (xVel > 150.0f) {
1097                    xVel = 150.0f; // limit how much we care about the x axis
1098                }
1099
1100                float vel = (float)Math.hypot(yVel, xVel);
1101                if (negative) {
1102                    vel = -vel;
1103                }
1104
1105                performFling((int)event.getRawY(), vel, false);
1106            }
1107
1108        }
1109        return false;
1110    }
1111
1112    public void setLightsOn(boolean on) {
1113        Log.v(TAG, "lights " + (on ? "on" : "off"));
1114        if (!on) {
1115            // All we do for "lights out" mode on a phone is hide the status bar,
1116            // which the window manager does.  But we do need to hide the windowshade
1117            // on our own.
1118            animateCollapse();
1119        }
1120        notifyLightsChanged(on);
1121    }
1122
1123    private void notifyLightsChanged(boolean shown) {
1124        try {
1125            Slog.d(TAG, "lights " + (shown?"on":"out"));
1126            mWindowManager.statusBarVisibilityChanged(
1127                    shown ? View.STATUS_BAR_VISIBLE : View.STATUS_BAR_HIDDEN);
1128        } catch (RemoteException ex) {
1129        }
1130    }
1131
1132    // Not supported
1133    public void setMenuKeyVisible(boolean visible) { }
1134    public void setImeWindowStatus(IBinder token, int vis, int backDisposition) { }
1135    @Override
1136    public void setHardKeyboardStatus(boolean available, boolean enabled) { }
1137
1138    private class Launcher implements View.OnClickListener {
1139        private PendingIntent mIntent;
1140        private String mPkg;
1141        private String mTag;
1142        private int mId;
1143
1144        Launcher(PendingIntent intent, String pkg, String tag, int id) {
1145            mIntent = intent;
1146            mPkg = pkg;
1147            mTag = tag;
1148            mId = id;
1149        }
1150
1151        public void onClick(View v) {
1152            try {
1153                // The intent we are sending is for the application, which
1154                // won't have permission to immediately start an activity after
1155                // the user switches to home.  We know it is safe to do at this
1156                // point, so make sure new activity switches are now allowed.
1157                ActivityManagerNative.getDefault().resumeAppSwitches();
1158            } catch (RemoteException e) {
1159            }
1160
1161            if (mIntent != null) {
1162                int[] pos = new int[2];
1163                v.getLocationOnScreen(pos);
1164                Intent overlay = new Intent();
1165                overlay.setSourceBounds(
1166                        new Rect(pos[0], pos[1], pos[0]+v.getWidth(), pos[1]+v.getHeight()));
1167                try {
1168                    mIntent.send(mContext, 0, overlay);
1169                } catch (PendingIntent.CanceledException e) {
1170                    // the stack trace isn't very helpful here.  Just log the exception message.
1171                    Slog.w(TAG, "Sending contentIntent failed: " + e);
1172                }
1173            }
1174
1175            try {
1176                mBarService.onNotificationClick(mPkg, mTag, mId);
1177            } catch (RemoteException ex) {
1178                // system process is dead if we're here.
1179            }
1180
1181            // close the shade if it was open
1182            animateCollapse();
1183
1184            // If this click was on the intruder alert, hide that instead
1185            mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
1186        }
1187    }
1188
1189    private void tick(StatusBarNotification n) {
1190        // Show the ticker if one is requested. Also don't do this
1191        // until status bar window is attached to the window manager,
1192        // because...  well, what's the point otherwise?  And trying to
1193        // run a ticker without being attached will crash!
1194        if (n.notification.tickerText != null && mStatusBarView.getWindowToken() != null) {
1195            if (0 == (mDisabled & (StatusBarManager.DISABLE_NOTIFICATION_ICONS
1196                            | StatusBarManager.DISABLE_NOTIFICATION_TICKER))) {
1197                mTicker.addEntry(n);
1198            }
1199        }
1200    }
1201
1202    /**
1203     * Cancel this notification and tell the StatusBarManagerService / NotificationManagerService
1204     * about the failure.
1205     *
1206     * WARNING: this will call back into us.  Don't hold any locks.
1207     */
1208    void handleNotificationError(IBinder key, StatusBarNotification n, String message) {
1209        removeNotification(key);
1210        try {
1211            mBarService.onNotificationError(n.pkg, n.tag, n.id, n.uid, n.initialPid, message);
1212        } catch (RemoteException ex) {
1213            // The end is nigh.
1214        }
1215    }
1216
1217    private class MyTicker extends Ticker {
1218        MyTicker(Context context, View sb) {
1219            super(context, sb);
1220        }
1221
1222        @Override
1223        public void tickerStarting() {
1224            mTicking = true;
1225            mIcons.setVisibility(View.GONE);
1226            mTickerView.setVisibility(View.VISIBLE);
1227            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_up_in, null));
1228            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.push_up_out, null));
1229            if (mExpandedVisible) {
1230                setDateViewVisibility(false, com.android.internal.R.anim.push_up_out);
1231            }
1232        }
1233
1234        @Override
1235        public void tickerDone() {
1236            mIcons.setVisibility(View.VISIBLE);
1237            mTickerView.setVisibility(View.GONE);
1238            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.push_down_in, null));
1239            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_down_out,
1240                        mTickingDoneListener));
1241            if (mExpandedVisible) {
1242                setDateViewVisibility(true, com.android.internal.R.anim.push_down_in);
1243            }
1244        }
1245
1246        public void tickerHalting() {
1247            mIcons.setVisibility(View.VISIBLE);
1248            mTickerView.setVisibility(View.GONE);
1249            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.fade_in, null));
1250            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.fade_out,
1251                        mTickingDoneListener));
1252            if (mExpandedVisible) {
1253                setDateViewVisibility(true, com.android.internal.R.anim.fade_in);
1254            }
1255        }
1256    }
1257
1258    Animation.AnimationListener mTickingDoneListener = new Animation.AnimationListener() {;
1259        public void onAnimationEnd(Animation animation) {
1260            mTicking = false;
1261        }
1262        public void onAnimationRepeat(Animation animation) {
1263        }
1264        public void onAnimationStart(Animation animation) {
1265        }
1266    };
1267
1268    private Animation loadAnim(int id, Animation.AnimationListener listener) {
1269        Animation anim = AnimationUtils.loadAnimation(mContext, id);
1270        if (listener != null) {
1271            anim.setAnimationListener(listener);
1272        }
1273        return anim;
1274    }
1275
1276    public String viewInfo(View v) {
1277        return "(" + v.getLeft() + "," + v.getTop() + ")(" + v.getRight() + "," + v.getBottom()
1278                + " " + v.getWidth() + "x" + v.getHeight() + ")";
1279    }
1280
1281    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1282        synchronized (mQueueLock) {
1283            pw.println("Current Status Bar state:");
1284            pw.println("  mExpanded=" + mExpanded
1285                    + ", mExpandedVisible=" + mExpandedVisible);
1286            pw.println("  mTicking=" + mTicking);
1287            pw.println("  mTracking=" + mTracking);
1288            pw.println("  mAnimating=" + mAnimating
1289                    + ", mAnimY=" + mAnimY + ", mAnimVel=" + mAnimVel
1290                    + ", mAnimAccel=" + mAnimAccel);
1291            pw.println("  mCurAnimationTime=" + mCurAnimationTime
1292                    + " mAnimLastTime=" + mAnimLastTime);
1293            pw.println("  mDisplayHeight=" + mDisplayHeight
1294                    + " mAnimatingReveal=" + mAnimatingReveal
1295                    + " mViewDelta=" + mViewDelta);
1296            pw.println("  mDisplayHeight=" + mDisplayHeight);
1297            pw.println("  mExpandedParams: " + mExpandedParams);
1298            pw.println("  mExpandedView: " + viewInfo(mExpandedView));
1299            pw.println("  mExpandedDialog: " + mExpandedDialog);
1300            pw.println("  mTrackingParams: " + mTrackingParams);
1301            pw.println("  mTrackingView: " + viewInfo(mTrackingView));
1302            pw.println("  mOngoingTitle: " + viewInfo(mOngoingTitle));
1303            pw.println("  mOngoingItems: " + viewInfo(mOngoingItems));
1304            pw.println("  mLatestTitle: " + viewInfo(mLatestTitle));
1305            pw.println("  mLatestItems: " + viewInfo(mLatestItems));
1306            pw.println("  mNoNotificationsTitle: " + viewInfo(mNoNotificationsTitle));
1307            pw.println("  mCloseView: " + viewInfo(mCloseView));
1308            pw.println("  mTickerView: " + viewInfo(mTickerView));
1309            pw.println("  mScrollView: " + viewInfo(mScrollView)
1310                    + " scroll " + mScrollView.getScrollX() + "," + mScrollView.getScrollY());
1311            pw.println("mNotificationLinearLayout: " + viewInfo(mNotificationLinearLayout));
1312        }
1313        /*
1314        synchronized (mNotificationData) {
1315            int N = mNotificationData.ongoingCount();
1316            pw.println("  ongoingCount.size=" + N);
1317            for (int i=0; i<N; i++) {
1318                StatusBarNotification n = mNotificationData.getOngoing(i);
1319                pw.println("    [" + i + "] key=" + n.key + " view=" + n.view);
1320                pw.println("           data=" + n.data);
1321            }
1322            N = mNotificationData.latestCount();
1323            pw.println("  ongoingCount.size=" + N);
1324            for (int i=0; i<N; i++) {
1325                StatusBarNotification n = mNotificationData.getLatest(i);
1326                pw.println("    [" + i + "] key=" + n.key + " view=" + n.view);
1327                pw.println("           data=" + n.data);
1328            }
1329        }
1330        */
1331
1332        if (false) {
1333            pw.println("see the logcat for a dump of the views we have created.");
1334            // must happen on ui thread
1335            mHandler.post(new Runnable() {
1336                    public void run() {
1337                        mStatusBarView.getLocationOnScreen(mAbsPos);
1338                        Slog.d(TAG, "mStatusBarView: ----- (" + mAbsPos[0] + "," + mAbsPos[1]
1339                                + ") " + mStatusBarView.getWidth() + "x"
1340                                + mStatusBarView.getHeight());
1341                        mStatusBarView.debug();
1342
1343                        mExpandedView.getLocationOnScreen(mAbsPos);
1344                        Slog.d(TAG, "mExpandedView: ----- (" + mAbsPos[0] + "," + mAbsPos[1]
1345                                + ") " + mExpandedView.getWidth() + "x"
1346                                + mExpandedView.getHeight());
1347                        mExpandedView.debug();
1348
1349                        mTrackingView.getLocationOnScreen(mAbsPos);
1350                        Slog.d(TAG, "mTrackingView: ----- (" + mAbsPos[0] + "," + mAbsPos[1]
1351                                + ") " + mTrackingView.getWidth() + "x"
1352                                + mTrackingView.getHeight());
1353                        mTrackingView.debug();
1354                    }
1355                });
1356        }
1357    }
1358
1359    void onBarViewAttached() {
1360        WindowManager.LayoutParams lp;
1361        int pixelFormat;
1362        Drawable bg;
1363
1364        /// ---------- Tracking View --------------
1365        pixelFormat = PixelFormat.RGBX_8888;
1366        bg = mTrackingView.getBackground();
1367        if (bg != null) {
1368            pixelFormat = bg.getOpacity();
1369        }
1370
1371        lp = new WindowManager.LayoutParams(
1372                ViewGroup.LayoutParams.MATCH_PARENT,
1373                ViewGroup.LayoutParams.MATCH_PARENT,
1374                WindowManager.LayoutParams.TYPE_STATUS_BAR_SUB_PANEL,
1375                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
1376                | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
1377                | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
1378                pixelFormat);
1379//        lp.token = mStatusBarView.getWindowToken();
1380        lp.gravity = Gravity.TOP | Gravity.FILL_HORIZONTAL;
1381        lp.setTitle("TrackingView");
1382        lp.y = mTrackingPosition;
1383        mTrackingParams = lp;
1384
1385        WindowManagerImpl.getDefault().addView(mTrackingView, lp);
1386    }
1387
1388    void onTrackingViewAttached() {
1389        WindowManager.LayoutParams lp;
1390        int pixelFormat;
1391        Drawable bg;
1392
1393        /// ---------- Expanded View --------------
1394        pixelFormat = PixelFormat.TRANSLUCENT;
1395
1396        final int disph = mDisplay.getHeight();
1397        lp = mExpandedDialog.getWindow().getAttributes();
1398        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
1399        lp.height = getExpandedHeight();
1400        lp.x = 0;
1401        mTrackingPosition = lp.y = -disph; // sufficiently large negative
1402        lp.type = WindowManager.LayoutParams.TYPE_STATUS_BAR_SUB_PANEL;
1403        lp.flags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
1404                | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
1405                | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
1406                | WindowManager.LayoutParams.FLAG_DITHER
1407                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
1408        lp.format = pixelFormat;
1409        lp.gravity = Gravity.TOP | Gravity.FILL_HORIZONTAL;
1410        lp.setTitle("StatusBarExpanded");
1411        mExpandedDialog.getWindow().setAttributes(lp);
1412        mExpandedDialog.getWindow().setFormat(pixelFormat);
1413        mExpandedParams = lp;
1414
1415        mExpandedDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
1416        mExpandedDialog.setContentView(mExpandedView,
1417                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1418                                           ViewGroup.LayoutParams.MATCH_PARENT));
1419        mExpandedDialog.getWindow().setBackgroundDrawable(null);
1420        mExpandedDialog.show();
1421        FrameLayout hack = (FrameLayout)mExpandedView.getParent();
1422    }
1423
1424    void setDateViewVisibility(boolean visible, int anim) {
1425        mDateView.setVisibility(visible ? View.VISIBLE : View.INVISIBLE);
1426        mDateView.startAnimation(loadAnim(anim, null));
1427    }
1428
1429    void setNotificationIconVisibility(boolean visible, int anim) {
1430        int old = mNotificationIcons.getVisibility();
1431        int v = visible ? View.VISIBLE : View.INVISIBLE;
1432        if (old != v) {
1433            mNotificationIcons.setVisibility(v);
1434            mNotificationIcons.startAnimation(loadAnim(anim, null));
1435        }
1436    }
1437
1438    void updateExpandedViewPos(int expandedPosition) {
1439        if (SPEW) {
1440            Slog.d(TAG, "updateExpandedViewPos before expandedPosition=" + expandedPosition
1441                    + " mTrackingParams.y=" + mTrackingParams.y
1442                    + " mTrackingPosition=" + mTrackingPosition);
1443        }
1444
1445        int h = mStatusBarView.getHeight();
1446        int disph = mDisplay.getHeight();
1447
1448        // If the expanded view is not visible, make sure they're still off screen.
1449        // Maybe the view was resized.
1450        if (!mExpandedVisible) {
1451            if (mTrackingView != null) {
1452                mTrackingPosition = -disph;
1453                if (mTrackingParams != null) {
1454                    mTrackingParams.y = mTrackingPosition;
1455                    WindowManagerImpl.getDefault().updateViewLayout(mTrackingView, mTrackingParams);
1456                }
1457            }
1458            if (mExpandedParams != null) {
1459                mExpandedParams.y = -disph;
1460                mExpandedDialog.getWindow().setAttributes(mExpandedParams);
1461            }
1462            return;
1463        }
1464
1465        // tracking view...
1466        int pos;
1467        if (expandedPosition == EXPANDED_FULL_OPEN) {
1468            pos = h;
1469        }
1470        else if (expandedPosition == EXPANDED_LEAVE_ALONE) {
1471            pos = mTrackingPosition;
1472        }
1473        else {
1474            if (expandedPosition <= disph) {
1475                pos = expandedPosition;
1476            } else {
1477                pos = disph;
1478            }
1479            pos -= disph-h;
1480        }
1481        mTrackingPosition = mTrackingParams.y = pos;
1482        mTrackingParams.height = disph-h;
1483        WindowManagerImpl.getDefault().updateViewLayout(mTrackingView, mTrackingParams);
1484
1485        if (mExpandedParams != null) {
1486            mCloseView.getLocationInWindow(mPositionTmp);
1487            final int closePos = mPositionTmp[1];
1488
1489            mExpandedContents.getLocationInWindow(mPositionTmp);
1490            final int contentsBottom = mPositionTmp[1] + mExpandedContents.getHeight();
1491
1492            mExpandedParams.y = pos + mTrackingView.getHeight()
1493                    - (mTrackingParams.height-closePos) - contentsBottom;
1494            int max = h;
1495            if (mExpandedParams.y > max) {
1496                mExpandedParams.y = max;
1497            }
1498            int min = mTrackingPosition;
1499            if (mExpandedParams.y < min) {
1500                mExpandedParams.y = min;
1501            }
1502
1503            boolean visible = (mTrackingPosition + mTrackingView.getHeight()) > h;
1504            if (!visible) {
1505                // if the contents aren't visible, move the expanded view way off screen
1506                // because the window itself extends below the content view.
1507                mExpandedParams.y = -disph;
1508            }
1509            mExpandedDialog.getWindow().setAttributes(mExpandedParams);
1510
1511            // As long as this isn't just a repositioning that's not supposed to affect
1512            // the user's perception of what's showing, call to say that the visibility
1513            // has changed. (Otherwise, someone else will call to do that).
1514            if (expandedPosition != EXPANDED_LEAVE_ALONE) {
1515                if (SPEW) Slog.d(TAG, "updateExpandedViewPos visibilityChanged(" + visible + ")");
1516                visibilityChanged(visible);
1517            }
1518        }
1519
1520        if (SPEW) {
1521            Slog.d(TAG, "updateExpandedViewPos after  expandedPosition=" + expandedPosition
1522                    + " mTrackingParams.y=" + mTrackingParams.y
1523                    + " mTrackingPosition=" + mTrackingPosition
1524                    + " mExpandedParams.y=" + mExpandedParams.y
1525                    + " mExpandedParams.height=" + mExpandedParams.height);
1526        }
1527    }
1528
1529    int getExpandedHeight() {
1530        return mDisplay.getHeight() - mStatusBarView.getHeight() - mCloseView.getHeight();
1531    }
1532
1533    void updateExpandedHeight() {
1534        if (mExpandedView != null) {
1535            mExpandedParams.height = getExpandedHeight();
1536            mExpandedDialog.getWindow().setAttributes(mExpandedParams);
1537        }
1538    }
1539
1540    public void userActivity() {
1541        try {
1542            mBarService.setSystemUiVisibility(View.STATUS_BAR_VISIBLE);
1543        } catch (RemoteException ex) { }
1544    }
1545
1546    /**
1547     * The LEDs are turned o)ff when the notification panel is shown, even just a little bit.
1548     * This was added last-minute and is inconsistent with the way the rest of the notifications
1549     * are handled, because the notification isn't really cancelled.  The lights are just
1550     * turned off.  If any other notifications happen, the lights will turn back on.  Steve says
1551     * this is what he wants. (see bug 1131461)
1552     */
1553    void visibilityChanged(boolean visible) {
1554        if (mPanelSlightlyVisible != visible) {
1555            mPanelSlightlyVisible = visible;
1556            try {
1557                mBarService.onPanelRevealed();
1558            } catch (RemoteException ex) {
1559                // Won't fail unless the world has ended.
1560            }
1561        }
1562    }
1563
1564    void performDisableActions(int net) {
1565        int old = mDisabled;
1566        int diff = net ^ old;
1567        mDisabled = net;
1568
1569        // act accordingly
1570        if ((diff & StatusBarManager.DISABLE_EXPAND) != 0) {
1571            if ((net & StatusBarManager.DISABLE_EXPAND) != 0) {
1572                Slog.d(TAG, "DISABLE_EXPAND: yes");
1573                animateCollapse();
1574            }
1575        }
1576        if ((diff & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
1577            if ((net & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
1578                Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: yes");
1579                if (mTicking) {
1580                    mNotificationIcons.setVisibility(View.INVISIBLE);
1581                    mTicker.halt();
1582                } else {
1583                    setNotificationIconVisibility(false, com.android.internal.R.anim.fade_out);
1584                }
1585            } else {
1586                Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: no");
1587                if (!mExpandedVisible) {
1588                    setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
1589                }
1590            }
1591        } else if ((diff & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
1592            if (mTicking && (net & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
1593                mTicker.halt();
1594            }
1595        }
1596    }
1597
1598    private View.OnClickListener mClearButtonListener = new View.OnClickListener() {
1599        public void onClick(View v) {
1600            try {
1601                mBarService.onClearAllNotifications();
1602            } catch (RemoteException ex) {
1603                // system process is dead if we're here.
1604            }
1605            animateCollapse();
1606        }
1607    };
1608
1609    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1610        public void onReceive(Context context, Intent intent) {
1611            String action = intent.getAction();
1612            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)
1613                    || Intent.ACTION_SCREEN_OFF.equals(action)) {
1614                animateCollapse();
1615            }
1616            else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1617                repositionNavigationBar();
1618                updateResources();
1619            }
1620        }
1621    };
1622
1623    private void setIntruderAlertVisibility(boolean vis) {
1624        mIntruderAlertView.setVisibility(vis ? View.VISIBLE : View.GONE);
1625    }
1626
1627    /**
1628     * Reload some of our resources when the configuration changes.
1629     *
1630     * We don't reload everything when the configuration changes -- we probably
1631     * should, but getting that smooth is tough.  Someday we'll fix that.  In the
1632     * meantime, just update the things that we know change.
1633     */
1634    void updateResources() {
1635        final Context context = mContext;
1636        final Resources res = context.getResources();
1637
1638        mClearButton.setText(context.getText(R.string.status_bar_clear_all_button));
1639        mOngoingTitle.setText(context.getText(R.string.status_bar_ongoing_events_title));
1640        mLatestTitle.setText(context.getText(R.string.status_bar_latest_events_title));
1641        mNoNotificationsTitle.setText(context.getText(R.string.status_bar_no_notifications_title));
1642
1643        mEdgeBorder = res.getDimensionPixelSize(R.dimen.status_bar_edge_ignore);
1644
1645        if (false) Slog.v(TAG, "updateResources");
1646    }
1647
1648    //
1649    // tracing
1650    //
1651
1652    void postStartTracing() {
1653        mHandler.postDelayed(mStartTracing, 3000);
1654    }
1655
1656    void vibrate() {
1657        android.os.Vibrator vib = (android.os.Vibrator)mContext.getSystemService(
1658                Context.VIBRATOR_SERVICE);
1659        vib.vibrate(250);
1660    }
1661
1662    Runnable mStartTracing = new Runnable() {
1663        public void run() {
1664            vibrate();
1665            SystemClock.sleep(250);
1666            Slog.d(TAG, "startTracing");
1667            android.os.Debug.startMethodTracing("/data/statusbar-traces/trace");
1668            mHandler.postDelayed(mStopTracing, 10000);
1669        }
1670    };
1671
1672    Runnable mStopTracing = new Runnable() {
1673        public void run() {
1674            android.os.Debug.stopMethodTracing();
1675            Slog.d(TAG, "stopTracing");
1676            vibrate();
1677        }
1678    };
1679}
1680
1681