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