PhoneStatusBar.java revision b48e74b10c3ef14d6c30381d8893abaddd50f2b2
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        // wire up the veto button
515        View vetoButton = row.findViewById(R.id.veto);
516        if (notification.isClearable()) {
517            final String _pkg = notification.pkg;
518            final String _tag = notification.tag;
519            final int _id = notification.id;
520            vetoButton.setOnClickListener(new View.OnClickListener() {
521                    public void onClick(View v) {
522                        try {
523                            mBarService.onNotificationClear(_pkg, _tag, _id);
524                        } catch (RemoteException ex) {
525                            // system process is dead if we're here.
526                        }
527                    }
528                });
529        } else {
530            if ((notification.notification.flags & Notification.FLAG_ONGOING_EVENT) == 0) {
531                vetoButton.setVisibility(View.INVISIBLE);
532            } else {
533                vetoButton.setVisibility(View.GONE);
534            }
535        }
536
537        // the large icon
538        ImageView largeIcon = (ImageView)row.findViewById(R.id.large_icon);
539        if (notification.notification.largeIcon != null) {
540            largeIcon.setImageBitmap(notification.notification.largeIcon);
541        } else {
542            largeIcon.getLayoutParams().width = 0;
543            largeIcon.setVisibility(View.INVISIBLE);
544        }
545
546        // bind the click event to the content area
547        ViewGroup content = (ViewGroup)row.findViewById(R.id.content);
548        content.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
549        content.setOnFocusChangeListener(mFocusChangeListener);
550        PendingIntent contentIntent = n.contentIntent;
551        if (contentIntent != null) {
552            content.setOnClickListener(new Launcher(contentIntent, notification.pkg,
553                        notification.tag, notification.id));
554        } else {
555            content.setOnClickListener(null);
556        }
557
558        View expanded = null;
559        Exception exception = null;
560        try {
561            expanded = remoteViews.apply(mContext, content);
562        }
563        catch (RuntimeException e) {
564            exception = e;
565        }
566        if (expanded == null) {
567            String ident = notification.pkg + "/0x" + Integer.toHexString(notification.id);
568            Slog.e(TAG, "couldn't inflate view for notification " + ident, exception);
569            return null;
570        } else {
571            content.addView(expanded);
572            row.setDrawingCacheEnabled(true);
573        }
574
575        return new View[] { row, content, expanded };
576    }
577
578    StatusBarIconView addNotificationViews(IBinder key, StatusBarNotification notification) {
579        NotificationData list;
580        ViewGroup parent;
581        final boolean isOngoing = notification.isOngoing();
582        if (isOngoing) {
583            list = mOngoing;
584            parent = mOngoingItems;
585        } else {
586            list = mLatest;
587            parent = mLatestItems;
588        }
589        // Construct the expanded view.
590        final View[] views = makeNotificationView(notification, parent);
591        if (views == null) {
592            handleNotificationError(key, notification, "Couldn't expand RemoteViews for: "
593                    + notification);
594            return null;
595        }
596        final View row = views[0];
597        final View content = views[1];
598        final View expanded = views[2];
599        // Construct the icon.
600        final StatusBarIconView iconView = new StatusBarIconView(mContext,
601                notification.pkg + "/0x" + Integer.toHexString(notification.id));
602        final StatusBarIcon ic = new StatusBarIcon(notification.pkg, notification.notification.icon,
603                    notification.notification.iconLevel, notification.notification.number);
604        if (!iconView.set(ic)) {
605            handleNotificationError(key, notification, "Coulding create icon: " + ic);
606            return null;
607        }
608        // Add the expanded view.
609        final int viewIndex = list.add(key, notification, row, content, expanded, iconView);
610        parent.addView(row, viewIndex);
611        // Add the icon.
612        final int iconIndex = chooseIconIndex(isOngoing, viewIndex);
613        mNotificationIcons.addView(iconView, iconIndex);
614        return iconView;
615    }
616
617    StatusBarNotification removeNotificationViews(IBinder key) {
618        NotificationData.Entry entry = mOngoing.remove(key);
619        if (entry == null) {
620            entry = mLatest.remove(key);
621            if (entry == null) {
622                Slog.w(TAG, "removeNotification for unknown key: " + key);
623                return null;
624            }
625        }
626        // Remove the expanded view.
627        ((ViewGroup)entry.row.getParent()).removeView(entry.row);
628        // Remove the icon.
629        ((ViewGroup)entry.icon.getParent()).removeView(entry.icon);
630
631        return entry.notification;
632    }
633
634    private void setAreThereNotifications() {
635        boolean ongoing = mOngoing.hasVisibleItems();
636        boolean latest = mLatest.hasVisibleItems();
637
638        // (no ongoing notifications are clearable)
639        if (mLatest.hasClearableItems()) {
640            mClearButton.setVisibility(View.VISIBLE);
641        } else {
642            mClearButton.setVisibility(View.INVISIBLE);
643        }
644
645        mOngoingTitle.setVisibility(ongoing ? View.VISIBLE : View.GONE);
646        mLatestTitle.setVisibility(latest ? View.VISIBLE : View.GONE);
647
648        if (ongoing || latest) {
649            mNoNotificationsTitle.setVisibility(View.GONE);
650        } else {
651            mNoNotificationsTitle.setVisibility(View.VISIBLE);
652        }
653    }
654
655
656    /**
657     * State is one or more of the DISABLE constants from StatusBarManager.
658     */
659    public void disable(int state) {
660        final int old = mDisabled;
661        final int diff = state ^ old;
662        mDisabled = state;
663
664        if ((diff & StatusBarManager.DISABLE_EXPAND) != 0) {
665            if ((state & StatusBarManager.DISABLE_EXPAND) != 0) {
666                Slog.d(TAG, "DISABLE_EXPAND: yes");
667                animateCollapse();
668            }
669        }
670        if ((diff & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
671            if ((state & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
672                Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: yes");
673                if (mTicking) {
674                    mTicker.halt();
675                } else {
676                    setNotificationIconVisibility(false, com.android.internal.R.anim.fade_out);
677                }
678            } else {
679                Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: no");
680                if (!mExpandedVisible) {
681                    setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
682                }
683            }
684        } else if ((diff & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
685            if (mTicking && (state & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
686                Slog.d(TAG, "DISABLE_NOTIFICATION_TICKER: yes");
687                mTicker.halt();
688            }
689        }
690    }
691
692    /**
693     * All changes to the status bar and notifications funnel through here and are batched.
694     */
695    private class H extends Handler {
696        public void handleMessage(Message m) {
697            switch (m.what) {
698                case MSG_ANIMATE:
699                    doAnimation();
700                    break;
701                case MSG_ANIMATE_REVEAL:
702                    doRevealAnimation();
703                    break;
704                case MSG_SHOW_INTRUDER:
705                    setIntruderAlertVisibility(true);
706                    break;
707                case MSG_HIDE_INTRUDER:
708                    setIntruderAlertVisibility(false);
709                    break;
710            }
711        }
712    }
713
714    View.OnFocusChangeListener mFocusChangeListener = new View.OnFocusChangeListener() {
715        public void onFocusChange(View v, boolean hasFocus) {
716            // Because 'v' is a ViewGroup, all its children will be (un)selected
717            // too, which allows marqueeing to work.
718            v.setSelected(hasFocus);
719        }
720    };
721
722    private void makeExpandedVisible() {
723        if (SPEW) Slog.d(TAG, "Make expanded visible: expanded visible=" + mExpandedVisible);
724        if (mExpandedVisible) {
725            return;
726        }
727        mExpandedVisible = true;
728        visibilityChanged(true);
729
730        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
731        mExpandedParams.flags &= ~WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
732        mExpandedParams.flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
733        mExpandedDialog.getWindow().setAttributes(mExpandedParams);
734        mExpandedView.requestFocus(View.FOCUS_FORWARD);
735        mTrackingView.setVisibility(View.VISIBLE);
736
737        if (!mTicking) {
738            setDateViewVisibility(true, com.android.internal.R.anim.fade_in);
739        }
740    }
741
742    public void animateExpand() {
743        if (SPEW) Slog.d(TAG, "Animate expand: expanded=" + mExpanded);
744        if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
745            return ;
746        }
747        if (mExpanded) {
748            return;
749        }
750
751        prepareTracking(0, true);
752        performFling(0, 2000.0f, true);
753    }
754
755    public void animateCollapse() {
756        if (SPEW) {
757            Slog.d(TAG, "animateCollapse(): mExpanded=" + mExpanded
758                    + " mExpandedVisible=" + mExpandedVisible
759                    + " mExpanded=" + mExpanded
760                    + " mAnimating=" + mAnimating
761                    + " mAnimY=" + mAnimY
762                    + " mAnimVel=" + mAnimVel);
763        }
764
765        if (!mExpandedVisible) {
766            return;
767        }
768
769        int y;
770        if (mAnimating) {
771            y = (int)mAnimY;
772        } else {
773            y = mDisplay.getHeight()-1;
774        }
775        // Let the fling think that we're open so it goes in the right direction
776        // and doesn't try to re-open the windowshade.
777        mExpanded = true;
778        prepareTracking(y, false);
779        performFling(y, -2000.0f, true);
780    }
781
782    void performExpand() {
783        if (SPEW) Slog.d(TAG, "performExpand: mExpanded=" + mExpanded);
784        if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
785            return ;
786        }
787        if (mExpanded) {
788            return;
789        }
790
791        mExpanded = true;
792        makeExpandedVisible();
793        updateExpandedViewPos(EXPANDED_FULL_OPEN);
794
795        if (false) postStartTracing();
796    }
797
798    void performCollapse() {
799        if (SPEW) Slog.d(TAG, "performCollapse: mExpanded=" + mExpanded
800                + " mExpandedVisible=" + mExpandedVisible);
801
802        if (!mExpandedVisible) {
803            return;
804        }
805        mExpandedVisible = false;
806        visibilityChanged(false);
807        mExpandedParams.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
808        mExpandedParams.flags &= ~WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
809        mExpandedDialog.getWindow().setAttributes(mExpandedParams);
810        mTrackingView.setVisibility(View.GONE);
811
812        if ((mDisabled & StatusBarManager.DISABLE_NOTIFICATION_ICONS) == 0) {
813            setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
814        }
815        setDateViewVisibility(false, com.android.internal.R.anim.fade_out);
816
817        if (!mExpanded) {
818            return;
819        }
820        mExpanded = false;
821    }
822
823    void doAnimation() {
824        if (mAnimating) {
825            if (SPEW) Slog.d(TAG, "doAnimation");
826            if (SPEW) Slog.d(TAG, "doAnimation before mAnimY=" + mAnimY);
827            incrementAnim();
828            if (SPEW) Slog.d(TAG, "doAnimation after  mAnimY=" + mAnimY);
829            if (mAnimY >= mDisplay.getHeight()-1) {
830                if (SPEW) Slog.d(TAG, "Animation completed to expanded state.");
831                mAnimating = false;
832                updateExpandedViewPos(EXPANDED_FULL_OPEN);
833                performExpand();
834            }
835            else if (mAnimY < mStatusBarView.getHeight()) {
836                if (SPEW) Slog.d(TAG, "Animation completed to collapsed state.");
837                mAnimating = false;
838                updateExpandedViewPos(0);
839                performCollapse();
840            }
841            else {
842                updateExpandedViewPos((int)mAnimY);
843                mCurAnimationTime += ANIM_FRAME_DURATION;
844                mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE), mCurAnimationTime);
845            }
846        }
847    }
848
849    void stopTracking() {
850        mTracking = false;
851        mVelocityTracker.recycle();
852        mVelocityTracker = null;
853    }
854
855    void incrementAnim() {
856        long now = SystemClock.uptimeMillis();
857        float t = ((float)(now - mAnimLastTime)) / 1000;            // ms -> s
858        final float y = mAnimY;
859        final float v = mAnimVel;                                   // px/s
860        final float a = mAnimAccel;                                 // px/s/s
861        mAnimY = y + (v*t) + (0.5f*a*t*t);                          // px
862        mAnimVel = v + (a*t);                                       // px/s
863        mAnimLastTime = now;                                        // ms
864        //Slog.d(TAG, "y=" + y + " v=" + v + " a=" + a + " t=" + t + " mAnimY=" + mAnimY
865        //        + " mAnimAccel=" + mAnimAccel);
866    }
867
868    void doRevealAnimation() {
869        final int h = mCloseView.getHeight() + mStatusBarView.getHeight();
870        if (mAnimatingReveal && mAnimating && mAnimY < h) {
871            incrementAnim();
872            if (mAnimY >= h) {
873                mAnimY = h;
874                updateExpandedViewPos((int)mAnimY);
875            } else {
876                updateExpandedViewPos((int)mAnimY);
877                mCurAnimationTime += ANIM_FRAME_DURATION;
878                mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE_REVEAL),
879                        mCurAnimationTime);
880            }
881        }
882    }
883
884    void prepareTracking(int y, boolean opening) {
885        mTracking = true;
886        mVelocityTracker = VelocityTracker.obtain();
887        if (opening) {
888            mAnimAccel = 2000.0f;
889            mAnimVel = 200;
890            mAnimY = mStatusBarView.getHeight();
891            updateExpandedViewPos((int)mAnimY);
892            mAnimating = true;
893            mAnimatingReveal = true;
894            mHandler.removeMessages(MSG_ANIMATE);
895            mHandler.removeMessages(MSG_ANIMATE_REVEAL);
896            long now = SystemClock.uptimeMillis();
897            mAnimLastTime = now;
898            mCurAnimationTime = now + ANIM_FRAME_DURATION;
899            mAnimating = true;
900            mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE_REVEAL),
901                    mCurAnimationTime);
902            makeExpandedVisible();
903        } else {
904            // it's open, close it?
905            if (mAnimating) {
906                mAnimating = false;
907                mHandler.removeMessages(MSG_ANIMATE);
908            }
909            updateExpandedViewPos(y + mViewDelta);
910        }
911    }
912
913    void performFling(int y, float vel, boolean always) {
914        mAnimatingReveal = false;
915        mDisplayHeight = mDisplay.getHeight();
916
917        mAnimY = y;
918        mAnimVel = vel;
919
920        //Slog.d(TAG, "starting with mAnimY=" + mAnimY + " mAnimVel=" + mAnimVel);
921
922        if (mExpanded) {
923            if (!always && (
924                    vel > 200.0f
925                    || (y > (mDisplayHeight-25) && vel > -200.0f))) {
926                // We are expanded, but they didn't move sufficiently to cause
927                // us to retract.  Animate back to the expanded position.
928                mAnimAccel = 2000.0f;
929                if (vel < 0) {
930                    mAnimVel = 0;
931                }
932            }
933            else {
934                // We are expanded and are now going to animate away.
935                mAnimAccel = -2000.0f;
936                if (vel > 0) {
937                    mAnimVel = 0;
938                }
939            }
940        } else {
941            if (always || (
942                    vel > 200.0f
943                    || (y > (mDisplayHeight/2) && vel > -200.0f))) {
944                // We are collapsed, and they moved enough to allow us to
945                // expand.  Animate in the notifications.
946                mAnimAccel = 2000.0f;
947                if (vel < 0) {
948                    mAnimVel = 0;
949                }
950            }
951            else {
952                // We are collapsed, but they didn't move sufficiently to cause
953                // us to retract.  Animate back to the collapsed position.
954                mAnimAccel = -2000.0f;
955                if (vel > 0) {
956                    mAnimVel = 0;
957                }
958            }
959        }
960        //Slog.d(TAG, "mAnimY=" + mAnimY + " mAnimVel=" + mAnimVel
961        //        + " mAnimAccel=" + mAnimAccel);
962
963        long now = SystemClock.uptimeMillis();
964        mAnimLastTime = now;
965        mCurAnimationTime = now + ANIM_FRAME_DURATION;
966        mAnimating = true;
967        mHandler.removeMessages(MSG_ANIMATE);
968        mHandler.removeMessages(MSG_ANIMATE_REVEAL);
969        mHandler.sendMessageAtTime(mHandler.obtainMessage(MSG_ANIMATE), mCurAnimationTime);
970        stopTracking();
971    }
972
973    boolean interceptTouchEvent(MotionEvent event) {
974        if (SPEW) {
975            Slog.d(TAG, "Touch: rawY=" + event.getRawY() + " event=" + event + " mDisabled="
976                + mDisabled);
977        }
978
979        if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
980            return false;
981        }
982
983        final int statusBarSize = mStatusBarView.getHeight();
984        final int hitSize = statusBarSize*2;
985        if (event.getAction() == MotionEvent.ACTION_DOWN) {
986            final int y = (int)event.getRawY();
987
988            if (!mExpanded) {
989                mViewDelta = statusBarSize - y;
990            } else {
991                mTrackingView.getLocationOnScreen(mAbsPos);
992                mViewDelta = mAbsPos[1] + mTrackingView.getHeight() - y;
993            }
994            if ((!mExpanded && y < hitSize) ||
995                    (mExpanded && y > (mDisplay.getHeight()-hitSize))) {
996
997                // We drop events at the edge of the screen to make the windowshade come
998                // down by accident less, especially when pushing open a device with a keyboard
999                // that rotates (like g1 and droid)
1000                int x = (int)event.getRawX();
1001                final int edgeBorder = mEdgeBorder;
1002                if (x >= edgeBorder && x < mDisplay.getWidth() - edgeBorder) {
1003                    prepareTracking(y, !mExpanded);// opening if we're not already fully visible
1004                    mVelocityTracker.addMovement(event);
1005                }
1006            }
1007        } else if (mTracking) {
1008            mVelocityTracker.addMovement(event);
1009            final int minY = statusBarSize + mCloseView.getHeight();
1010            if (event.getAction() == MotionEvent.ACTION_MOVE) {
1011                int y = (int)event.getRawY();
1012                if (mAnimatingReveal && y < minY) {
1013                    // nothing
1014                } else  {
1015                    mAnimatingReveal = false;
1016                    updateExpandedViewPos(y + mViewDelta);
1017                }
1018            } else if (event.getAction() == MotionEvent.ACTION_UP) {
1019                mVelocityTracker.computeCurrentVelocity(1000);
1020
1021                float yVel = mVelocityTracker.getYVelocity();
1022                boolean negative = yVel < 0;
1023
1024                float xVel = mVelocityTracker.getXVelocity();
1025                if (xVel < 0) {
1026                    xVel = -xVel;
1027                }
1028                if (xVel > 150.0f) {
1029                    xVel = 150.0f; // limit how much we care about the x axis
1030                }
1031
1032                float vel = (float)Math.hypot(yVel, xVel);
1033                if (negative) {
1034                    vel = -vel;
1035                }
1036
1037                performFling((int)event.getRawY(), vel, false);
1038            }
1039
1040        }
1041        return false;
1042    }
1043
1044    public void setLightsOn(boolean on) {
1045        if (!on) {
1046            // All we do for "lights out" mode on a phone is hide the status bar,
1047            // which the window manager does.  But we do need to hide the windowshade
1048            // on our own.
1049            animateCollapse();
1050        }
1051    }
1052
1053    // Not supported
1054    public void setMenuKeyVisible(boolean visible) { }
1055    public void setImeWindowStatus(IBinder token, int vis, int backDisposition) { }
1056    @Override
1057    public void setHardKeyboardStatus(boolean available, boolean enabled) { }
1058
1059    private class Launcher implements View.OnClickListener {
1060        private PendingIntent mIntent;
1061        private String mPkg;
1062        private String mTag;
1063        private int mId;
1064
1065        Launcher(PendingIntent intent, String pkg, String tag, int id) {
1066            mIntent = intent;
1067            mPkg = pkg;
1068            mTag = tag;
1069            mId = id;
1070        }
1071
1072        public void onClick(View v) {
1073            try {
1074                // The intent we are sending is for the application, which
1075                // won't have permission to immediately start an activity after
1076                // the user switches to home.  We know it is safe to do at this
1077                // point, so make sure new activity switches are now allowed.
1078                ActivityManagerNative.getDefault().resumeAppSwitches();
1079            } catch (RemoteException e) {
1080            }
1081
1082            if (mIntent != null) {
1083                int[] pos = new int[2];
1084                v.getLocationOnScreen(pos);
1085                Intent overlay = new Intent();
1086                overlay.setSourceBounds(
1087                        new Rect(pos[0], pos[1], pos[0]+v.getWidth(), pos[1]+v.getHeight()));
1088                try {
1089                    mIntent.send(mContext, 0, overlay);
1090                } catch (PendingIntent.CanceledException e) {
1091                    // the stack trace isn't very helpful here.  Just log the exception message.
1092                    Slog.w(TAG, "Sending contentIntent failed: " + e);
1093                }
1094            }
1095
1096            try {
1097                mBarService.onNotificationClick(mPkg, mTag, mId);
1098            } catch (RemoteException ex) {
1099                // system process is dead if we're here.
1100            }
1101
1102            // close the shade if it was open
1103            animateCollapse();
1104
1105            // If this click was on the intruder alert, hide that instead
1106            mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
1107        }
1108    }
1109
1110    private void tick(StatusBarNotification n) {
1111        // Show the ticker if one is requested. Also don't do this
1112        // until status bar window is attached to the window manager,
1113        // because...  well, what's the point otherwise?  And trying to
1114        // run a ticker without being attached will crash!
1115        if (n.notification.tickerText != null && mStatusBarView.getWindowToken() != null) {
1116            if (0 == (mDisabled & (StatusBarManager.DISABLE_NOTIFICATION_ICONS
1117                            | StatusBarManager.DISABLE_NOTIFICATION_TICKER))) {
1118                mTicker.addEntry(n);
1119            }
1120        }
1121    }
1122
1123    /**
1124     * Cancel this notification and tell the StatusBarManagerService / NotificationManagerService
1125     * about the failure.
1126     *
1127     * WARNING: this will call back into us.  Don't hold any locks.
1128     */
1129    void handleNotificationError(IBinder key, StatusBarNotification n, String message) {
1130        removeNotification(key);
1131        try {
1132            mBarService.onNotificationError(n.pkg, n.tag, n.id, n.uid, n.initialPid, message);
1133        } catch (RemoteException ex) {
1134            // The end is nigh.
1135        }
1136    }
1137
1138    private class MyTicker extends Ticker {
1139        MyTicker(Context context, View sb) {
1140            super(context, sb);
1141        }
1142
1143        @Override
1144        public void tickerStarting() {
1145            mTicking = true;
1146            mIcons.setVisibility(View.GONE);
1147            mTickerView.setVisibility(View.VISIBLE);
1148            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_up_in, null));
1149            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.push_up_out, null));
1150            if (mExpandedVisible) {
1151                setDateViewVisibility(false, com.android.internal.R.anim.push_up_out);
1152            }
1153        }
1154
1155        @Override
1156        public void tickerDone() {
1157            mIcons.setVisibility(View.VISIBLE);
1158            mTickerView.setVisibility(View.GONE);
1159            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.push_down_in, null));
1160            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_down_out,
1161                        mTickingDoneListener));
1162            if (mExpandedVisible) {
1163                setDateViewVisibility(true, com.android.internal.R.anim.push_down_in);
1164            }
1165        }
1166
1167        public void tickerHalting() {
1168            mIcons.setVisibility(View.VISIBLE);
1169            mTickerView.setVisibility(View.GONE);
1170            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.fade_in, null));
1171            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.fade_out,
1172                        mTickingDoneListener));
1173            if (mExpandedVisible) {
1174                setDateViewVisibility(true, com.android.internal.R.anim.fade_in);
1175            }
1176        }
1177    }
1178
1179    Animation.AnimationListener mTickingDoneListener = new Animation.AnimationListener() {;
1180        public void onAnimationEnd(Animation animation) {
1181            mTicking = false;
1182        }
1183        public void onAnimationRepeat(Animation animation) {
1184        }
1185        public void onAnimationStart(Animation animation) {
1186        }
1187    };
1188
1189    private Animation loadAnim(int id, Animation.AnimationListener listener) {
1190        Animation anim = AnimationUtils.loadAnimation(mContext, id);
1191        if (listener != null) {
1192            anim.setAnimationListener(listener);
1193        }
1194        return anim;
1195    }
1196
1197    public String viewInfo(View v) {
1198        return "(" + v.getLeft() + "," + v.getTop() + ")(" + v.getRight() + "," + v.getBottom()
1199                + " " + v.getWidth() + "x" + v.getHeight() + ")";
1200    }
1201
1202    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1203        synchronized (mQueueLock) {
1204            pw.println("Current Status Bar state:");
1205            pw.println("  mExpanded=" + mExpanded
1206                    + ", mExpandedVisible=" + mExpandedVisible);
1207            pw.println("  mTicking=" + mTicking);
1208            pw.println("  mTracking=" + mTracking);
1209            pw.println("  mAnimating=" + mAnimating
1210                    + ", mAnimY=" + mAnimY + ", mAnimVel=" + mAnimVel
1211                    + ", mAnimAccel=" + mAnimAccel);
1212            pw.println("  mCurAnimationTime=" + mCurAnimationTime
1213                    + " mAnimLastTime=" + mAnimLastTime);
1214            pw.println("  mDisplayHeight=" + mDisplayHeight
1215                    + " mAnimatingReveal=" + mAnimatingReveal
1216                    + " mViewDelta=" + mViewDelta);
1217            pw.println("  mDisplayHeight=" + mDisplayHeight);
1218            pw.println("  mExpandedParams: " + mExpandedParams);
1219            pw.println("  mExpandedView: " + viewInfo(mExpandedView));
1220            pw.println("  mExpandedDialog: " + mExpandedDialog);
1221            pw.println("  mTrackingParams: " + mTrackingParams);
1222            pw.println("  mTrackingView: " + viewInfo(mTrackingView));
1223            pw.println("  mOngoingTitle: " + viewInfo(mOngoingTitle));
1224            pw.println("  mOngoingItems: " + viewInfo(mOngoingItems));
1225            pw.println("  mLatestTitle: " + viewInfo(mLatestTitle));
1226            pw.println("  mLatestItems: " + viewInfo(mLatestItems));
1227            pw.println("  mNoNotificationsTitle: " + viewInfo(mNoNotificationsTitle));
1228            pw.println("  mCloseView: " + viewInfo(mCloseView));
1229            pw.println("  mTickerView: " + viewInfo(mTickerView));
1230            pw.println("  mScrollView: " + viewInfo(mScrollView)
1231                    + " scroll " + mScrollView.getScrollX() + "," + mScrollView.getScrollY());
1232            pw.println("mNotificationLinearLayout: " + viewInfo(mNotificationLinearLayout));
1233        }
1234        /*
1235        synchronized (mNotificationData) {
1236            int N = mNotificationData.ongoingCount();
1237            pw.println("  ongoingCount.size=" + N);
1238            for (int i=0; i<N; i++) {
1239                StatusBarNotification n = mNotificationData.getOngoing(i);
1240                pw.println("    [" + i + "] key=" + n.key + " view=" + n.view);
1241                pw.println("           data=" + n.data);
1242            }
1243            N = mNotificationData.latestCount();
1244            pw.println("  ongoingCount.size=" + N);
1245            for (int i=0; i<N; i++) {
1246                StatusBarNotification n = mNotificationData.getLatest(i);
1247                pw.println("    [" + i + "] key=" + n.key + " view=" + n.view);
1248                pw.println("           data=" + n.data);
1249            }
1250        }
1251        */
1252
1253        if (false) {
1254            pw.println("see the logcat for a dump of the views we have created.");
1255            // must happen on ui thread
1256            mHandler.post(new Runnable() {
1257                    public void run() {
1258                        mStatusBarView.getLocationOnScreen(mAbsPos);
1259                        Slog.d(TAG, "mStatusBarView: ----- (" + mAbsPos[0] + "," + mAbsPos[1]
1260                                + ") " + mStatusBarView.getWidth() + "x"
1261                                + mStatusBarView.getHeight());
1262                        mStatusBarView.debug();
1263
1264                        mExpandedView.getLocationOnScreen(mAbsPos);
1265                        Slog.d(TAG, "mExpandedView: ----- (" + mAbsPos[0] + "," + mAbsPos[1]
1266                                + ") " + mExpandedView.getWidth() + "x"
1267                                + mExpandedView.getHeight());
1268                        mExpandedView.debug();
1269
1270                        mTrackingView.getLocationOnScreen(mAbsPos);
1271                        Slog.d(TAG, "mTrackingView: ----- (" + mAbsPos[0] + "," + mAbsPos[1]
1272                                + ") " + mTrackingView.getWidth() + "x"
1273                                + mTrackingView.getHeight());
1274                        mTrackingView.debug();
1275                    }
1276                });
1277        }
1278    }
1279
1280    void onBarViewAttached() {
1281        WindowManager.LayoutParams lp;
1282        int pixelFormat;
1283        Drawable bg;
1284
1285        /// ---------- Tracking View --------------
1286        pixelFormat = PixelFormat.RGBX_8888;
1287        bg = mTrackingView.getBackground();
1288        if (bg != null) {
1289            pixelFormat = bg.getOpacity();
1290        }
1291
1292        lp = new WindowManager.LayoutParams(
1293                ViewGroup.LayoutParams.MATCH_PARENT,
1294                ViewGroup.LayoutParams.MATCH_PARENT,
1295                WindowManager.LayoutParams.TYPE_STATUS_BAR_SUB_PANEL,
1296                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
1297                | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
1298                | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
1299                pixelFormat);
1300//        lp.token = mStatusBarView.getWindowToken();
1301        lp.gravity = Gravity.TOP | Gravity.FILL_HORIZONTAL;
1302        lp.setTitle("TrackingView");
1303        lp.y = mTrackingPosition;
1304        mTrackingParams = lp;
1305
1306        WindowManagerImpl.getDefault().addView(mTrackingView, lp);
1307    }
1308
1309    void onTrackingViewAttached() {
1310        WindowManager.LayoutParams lp;
1311        int pixelFormat;
1312        Drawable bg;
1313
1314        /// ---------- Expanded View --------------
1315        pixelFormat = PixelFormat.TRANSLUCENT;
1316
1317        final int disph = mDisplay.getHeight();
1318        lp = mExpandedDialog.getWindow().getAttributes();
1319        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
1320        lp.height = getExpandedHeight();
1321        lp.x = 0;
1322        mTrackingPosition = lp.y = -disph; // sufficiently large negative
1323        lp.type = WindowManager.LayoutParams.TYPE_STATUS_BAR_SUB_PANEL;
1324        lp.flags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
1325                | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
1326                | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
1327                | WindowManager.LayoutParams.FLAG_DITHER
1328                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
1329        lp.format = pixelFormat;
1330        lp.gravity = Gravity.TOP | Gravity.FILL_HORIZONTAL;
1331        lp.setTitle("StatusBarExpanded");
1332        mExpandedDialog.getWindow().setAttributes(lp);
1333        mExpandedDialog.getWindow().setFormat(pixelFormat);
1334        mExpandedParams = lp;
1335
1336        mExpandedDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
1337        mExpandedDialog.setContentView(mExpandedView,
1338                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1339                                           ViewGroup.LayoutParams.MATCH_PARENT));
1340        mExpandedDialog.getWindow().setBackgroundDrawable(null);
1341        mExpandedDialog.show();
1342        FrameLayout hack = (FrameLayout)mExpandedView.getParent();
1343    }
1344
1345    void setDateViewVisibility(boolean visible, int anim) {
1346        mDateView.setVisibility(visible ? View.VISIBLE : View.INVISIBLE);
1347        mDateView.startAnimation(loadAnim(anim, null));
1348    }
1349
1350    void setNotificationIconVisibility(boolean visible, int anim) {
1351        int old = mNotificationIcons.getVisibility();
1352        int v = visible ? View.VISIBLE : View.INVISIBLE;
1353        if (old != v) {
1354            mNotificationIcons.setVisibility(v);
1355            mNotificationIcons.startAnimation(loadAnim(anim, null));
1356        }
1357    }
1358
1359    void updateExpandedViewPos(int expandedPosition) {
1360        if (SPEW) {
1361            Slog.d(TAG, "updateExpandedViewPos before expandedPosition=" + expandedPosition
1362                    + " mTrackingParams.y=" + mTrackingParams.y
1363                    + " mTrackingPosition=" + mTrackingPosition);
1364        }
1365
1366        int h = mStatusBarView.getHeight();
1367        int disph = mDisplay.getHeight();
1368
1369        // If the expanded view is not visible, make sure they're still off screen.
1370        // Maybe the view was resized.
1371        if (!mExpandedVisible) {
1372            if (mTrackingView != null) {
1373                mTrackingPosition = -disph;
1374                if (mTrackingParams != null) {
1375                    mTrackingParams.y = mTrackingPosition;
1376                    WindowManagerImpl.getDefault().updateViewLayout(mTrackingView, mTrackingParams);
1377                }
1378            }
1379            if (mExpandedParams != null) {
1380                mExpandedParams.y = -disph;
1381                mExpandedDialog.getWindow().setAttributes(mExpandedParams);
1382            }
1383            return;
1384        }
1385
1386        // tracking view...
1387        int pos;
1388        if (expandedPosition == EXPANDED_FULL_OPEN) {
1389            pos = h;
1390        }
1391        else if (expandedPosition == EXPANDED_LEAVE_ALONE) {
1392            pos = mTrackingPosition;
1393        }
1394        else {
1395            if (expandedPosition <= disph) {
1396                pos = expandedPosition;
1397            } else {
1398                pos = disph;
1399            }
1400            pos -= disph-h;
1401        }
1402        mTrackingPosition = mTrackingParams.y = pos;
1403        mTrackingParams.height = disph-h;
1404        WindowManagerImpl.getDefault().updateViewLayout(mTrackingView, mTrackingParams);
1405
1406        if (mExpandedParams != null) {
1407            mCloseView.getLocationInWindow(mPositionTmp);
1408            final int closePos = mPositionTmp[1];
1409
1410            mExpandedContents.getLocationInWindow(mPositionTmp);
1411            final int contentsBottom = mPositionTmp[1] + mExpandedContents.getHeight();
1412
1413            mExpandedParams.y = pos + mTrackingView.getHeight()
1414                    - (mTrackingParams.height-closePos) - contentsBottom;
1415            int max = h;
1416            if (mExpandedParams.y > max) {
1417                mExpandedParams.y = max;
1418            }
1419            int min = mTrackingPosition;
1420            if (mExpandedParams.y < min) {
1421                mExpandedParams.y = min;
1422            }
1423
1424            boolean visible = (mTrackingPosition + mTrackingView.getHeight()) > h;
1425            if (!visible) {
1426                // if the contents aren't visible, move the expanded view way off screen
1427                // because the window itself extends below the content view.
1428                mExpandedParams.y = -disph;
1429            }
1430            mExpandedDialog.getWindow().setAttributes(mExpandedParams);
1431
1432            // As long as this isn't just a repositioning that's not supposed to affect
1433            // the user's perception of what's showing, call to say that the visibility
1434            // has changed. (Otherwise, someone else will call to do that).
1435            if (expandedPosition != EXPANDED_LEAVE_ALONE) {
1436                if (SPEW) Slog.d(TAG, "updateExpandedViewPos visibilityChanged(" + visible + ")");
1437                visibilityChanged(visible);
1438            }
1439        }
1440
1441        if (SPEW) {
1442            Slog.d(TAG, "updateExpandedViewPos after  expandedPosition=" + expandedPosition
1443                    + " mTrackingParams.y=" + mTrackingParams.y
1444                    + " mTrackingPosition=" + mTrackingPosition
1445                    + " mExpandedParams.y=" + mExpandedParams.y
1446                    + " mExpandedParams.height=" + mExpandedParams.height);
1447        }
1448    }
1449
1450    int getExpandedHeight() {
1451        return mDisplay.getHeight() - mStatusBarView.getHeight() - mCloseView.getHeight();
1452    }
1453
1454    void updateExpandedHeight() {
1455        if (mExpandedView != null) {
1456            mExpandedParams.height = getExpandedHeight();
1457            mExpandedDialog.getWindow().setAttributes(mExpandedParams);
1458        }
1459    }
1460
1461    /**
1462     * The LEDs are turned o)ff when the notification panel is shown, even just a little bit.
1463     * This was added last-minute and is inconsistent with the way the rest of the notifications
1464     * are handled, because the notification isn't really cancelled.  The lights are just
1465     * turned off.  If any other notifications happen, the lights will turn back on.  Steve says
1466     * this is what he wants. (see bug 1131461)
1467     */
1468    void visibilityChanged(boolean visible) {
1469        if (mPanelSlightlyVisible != visible) {
1470            mPanelSlightlyVisible = visible;
1471            try {
1472                mBarService.onPanelRevealed();
1473            } catch (RemoteException ex) {
1474                // Won't fail unless the world has ended.
1475            }
1476        }
1477    }
1478
1479    void performDisableActions(int net) {
1480        int old = mDisabled;
1481        int diff = net ^ old;
1482        mDisabled = net;
1483
1484        // act accordingly
1485        if ((diff & StatusBarManager.DISABLE_EXPAND) != 0) {
1486            if ((net & StatusBarManager.DISABLE_EXPAND) != 0) {
1487                Slog.d(TAG, "DISABLE_EXPAND: yes");
1488                animateCollapse();
1489            }
1490        }
1491        if ((diff & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
1492            if ((net & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
1493                Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: yes");
1494                if (mTicking) {
1495                    mNotificationIcons.setVisibility(View.INVISIBLE);
1496                    mTicker.halt();
1497                } else {
1498                    setNotificationIconVisibility(false, com.android.internal.R.anim.fade_out);
1499                }
1500            } else {
1501                Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: no");
1502                if (!mExpandedVisible) {
1503                    setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
1504                }
1505            }
1506        } else if ((diff & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
1507            if (mTicking && (net & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
1508                mTicker.halt();
1509            }
1510        }
1511    }
1512
1513    private View.OnClickListener mClearButtonListener = new View.OnClickListener() {
1514        public void onClick(View v) {
1515            try {
1516                mBarService.onClearAllNotifications();
1517            } catch (RemoteException ex) {
1518                // system process is dead if we're here.
1519            }
1520            animateCollapse();
1521        }
1522    };
1523
1524    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1525        public void onReceive(Context context, Intent intent) {
1526            String action = intent.getAction();
1527            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)
1528                    || Intent.ACTION_SCREEN_OFF.equals(action)) {
1529                animateCollapse();
1530            }
1531            else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1532                updateResources();
1533            }
1534        }
1535    };
1536
1537    private void setIntruderAlertVisibility(boolean vis) {
1538        mIntruderAlertView.setVisibility(vis ? View.VISIBLE : View.GONE);
1539    }
1540
1541    /**
1542     * Reload some of our resources when the configuration changes.
1543     *
1544     * We don't reload everything when the configuration changes -- we probably
1545     * should, but getting that smooth is tough.  Someday we'll fix that.  In the
1546     * meantime, just update the things that we know change.
1547     */
1548    void updateResources() {
1549        final Context context = mContext;
1550        final Resources res = context.getResources();
1551
1552        mClearButton.setText(context.getText(R.string.status_bar_clear_all_button));
1553        mOngoingTitle.setText(context.getText(R.string.status_bar_ongoing_events_title));
1554        mLatestTitle.setText(context.getText(R.string.status_bar_latest_events_title));
1555        mNoNotificationsTitle.setText(context.getText(R.string.status_bar_no_notifications_title));
1556
1557        mEdgeBorder = res.getDimensionPixelSize(R.dimen.status_bar_edge_ignore);
1558
1559        if (false) Slog.v(TAG, "updateResources");
1560    }
1561
1562    //
1563    // tracing
1564    //
1565
1566    void postStartTracing() {
1567        mHandler.postDelayed(mStartTracing, 3000);
1568    }
1569
1570    void vibrate() {
1571        android.os.Vibrator vib = (android.os.Vibrator)mContext.getSystemService(
1572                Context.VIBRATOR_SERVICE);
1573        vib.vibrate(250);
1574    }
1575
1576    Runnable mStartTracing = new Runnable() {
1577        public void run() {
1578            vibrate();
1579            SystemClock.sleep(250);
1580            Slog.d(TAG, "startTracing");
1581            android.os.Debug.startMethodTracing("/data/statusbar-traces/trace");
1582            mHandler.postDelayed(mStopTracing, 10000);
1583        }
1584    };
1585
1586    Runnable mStopTracing = new Runnable() {
1587        public void run() {
1588            android.os.Debug.stopMethodTracing();
1589            Slog.d(TAG, "stopTracing");
1590            vibrate();
1591        }
1592    };
1593}
1594
1595