PhoneStatusBar.java revision 7d04932ef5c001769ccef244f551b75773f1666b
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 topAppWindowChanged(boolean visible) { }
1023    public void setImeWindowStatus(IBinder token, int vis, int backDisposition) { }
1024    @Override
1025    public void setHardKeyboardStatus(boolean available, boolean enabled) { }
1026
1027    private class Launcher implements View.OnClickListener {
1028        private PendingIntent mIntent;
1029        private String mPkg;
1030        private String mTag;
1031        private int mId;
1032
1033        Launcher(PendingIntent intent, String pkg, String tag, int id) {
1034            mIntent = intent;
1035            mPkg = pkg;
1036            mTag = tag;
1037            mId = id;
1038        }
1039
1040        public void onClick(View v) {
1041            try {
1042                // The intent we are sending is for the application, which
1043                // won't have permission to immediately start an activity after
1044                // the user switches to home.  We know it is safe to do at this
1045                // point, so make sure new activity switches are now allowed.
1046                ActivityManagerNative.getDefault().resumeAppSwitches();
1047            } catch (RemoteException e) {
1048            }
1049
1050            if (mIntent != null) {
1051                int[] pos = new int[2];
1052                v.getLocationOnScreen(pos);
1053                Intent overlay = new Intent();
1054                overlay.setSourceBounds(
1055                        new Rect(pos[0], pos[1], pos[0]+v.getWidth(), pos[1]+v.getHeight()));
1056                try {
1057                    mIntent.send(mContext, 0, overlay);
1058                } catch (PendingIntent.CanceledException e) {
1059                    // the stack trace isn't very helpful here.  Just log the exception message.
1060                    Slog.w(TAG, "Sending contentIntent failed: " + e);
1061                }
1062            }
1063
1064            try {
1065                mBarService.onNotificationClick(mPkg, mTag, mId);
1066            } catch (RemoteException ex) {
1067                // system process is dead if we're here.
1068            }
1069
1070            // close the shade if it was open
1071            animateCollapse();
1072
1073            // If this click was on the intruder alert, hide that instead
1074            mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
1075        }
1076    }
1077
1078    private void tick(StatusBarNotification n) {
1079        // Show the ticker if one is requested. Also don't do this
1080        // until status bar window is attached to the window manager,
1081        // because...  well, what's the point otherwise?  And trying to
1082        // run a ticker without being attached will crash!
1083        if (n.notification.tickerText != null && mStatusBarView.getWindowToken() != null) {
1084            if (0 == (mDisabled & (StatusBarManager.DISABLE_NOTIFICATION_ICONS
1085                            | StatusBarManager.DISABLE_NOTIFICATION_TICKER))) {
1086                mTicker.addEntry(n);
1087            }
1088        }
1089    }
1090
1091    /**
1092     * Cancel this notification and tell the StatusBarManagerService / NotificationManagerService
1093     * about the failure.
1094     *
1095     * WARNING: this will call back into us.  Don't hold any locks.
1096     */
1097    void handleNotificationError(IBinder key, StatusBarNotification n, String message) {
1098        removeNotification(key);
1099        try {
1100            mBarService.onNotificationError(n.pkg, n.tag, n.id, n.uid, n.initialPid, message);
1101        } catch (RemoteException ex) {
1102            // The end is nigh.
1103        }
1104    }
1105
1106    private class MyTicker extends Ticker {
1107        MyTicker(Context context, View sb) {
1108            super(context, sb);
1109        }
1110
1111        @Override
1112        public void tickerStarting() {
1113            mTicking = true;
1114            mIcons.setVisibility(View.GONE);
1115            mTickerView.setVisibility(View.VISIBLE);
1116            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_up_in, null));
1117            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.push_up_out, null));
1118            if (mExpandedVisible) {
1119                setDateViewVisibility(false, com.android.internal.R.anim.push_up_out);
1120            }
1121        }
1122
1123        @Override
1124        public void tickerDone() {
1125            mIcons.setVisibility(View.VISIBLE);
1126            mTickerView.setVisibility(View.GONE);
1127            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.push_down_in, null));
1128            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.push_down_out,
1129                        mTickingDoneListener));
1130            if (mExpandedVisible) {
1131                setDateViewVisibility(true, com.android.internal.R.anim.push_down_in);
1132            }
1133        }
1134
1135        public void tickerHalting() {
1136            mIcons.setVisibility(View.VISIBLE);
1137            mTickerView.setVisibility(View.GONE);
1138            mIcons.startAnimation(loadAnim(com.android.internal.R.anim.fade_in, null));
1139            mTickerView.startAnimation(loadAnim(com.android.internal.R.anim.fade_out,
1140                        mTickingDoneListener));
1141            if (mExpandedVisible) {
1142                setDateViewVisibility(true, com.android.internal.R.anim.fade_in);
1143            }
1144        }
1145    }
1146
1147    Animation.AnimationListener mTickingDoneListener = new Animation.AnimationListener() {;
1148        public void onAnimationEnd(Animation animation) {
1149            mTicking = false;
1150        }
1151        public void onAnimationRepeat(Animation animation) {
1152        }
1153        public void onAnimationStart(Animation animation) {
1154        }
1155    };
1156
1157    private Animation loadAnim(int id, Animation.AnimationListener listener) {
1158        Animation anim = AnimationUtils.loadAnimation(mContext, id);
1159        if (listener != null) {
1160            anim.setAnimationListener(listener);
1161        }
1162        return anim;
1163    }
1164
1165    public String viewInfo(View v) {
1166        return "(" + v.getLeft() + "," + v.getTop() + ")(" + v.getRight() + "," + v.getBottom()
1167                + " " + v.getWidth() + "x" + v.getHeight() + ")";
1168    }
1169
1170    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1171        synchronized (mQueueLock) {
1172            pw.println("Current Status Bar state:");
1173            pw.println("  mExpanded=" + mExpanded
1174                    + ", mExpandedVisible=" + mExpandedVisible);
1175            pw.println("  mTicking=" + mTicking);
1176            pw.println("  mTracking=" + mTracking);
1177            pw.println("  mAnimating=" + mAnimating
1178                    + ", mAnimY=" + mAnimY + ", mAnimVel=" + mAnimVel
1179                    + ", mAnimAccel=" + mAnimAccel);
1180            pw.println("  mCurAnimationTime=" + mCurAnimationTime
1181                    + " mAnimLastTime=" + mAnimLastTime);
1182            pw.println("  mDisplayHeight=" + mDisplayHeight
1183                    + " mAnimatingReveal=" + mAnimatingReveal
1184                    + " mViewDelta=" + mViewDelta);
1185            pw.println("  mDisplayHeight=" + mDisplayHeight);
1186            pw.println("  mExpandedParams: " + mExpandedParams);
1187            pw.println("  mExpandedView: " + viewInfo(mExpandedView));
1188            pw.println("  mExpandedDialog: " + mExpandedDialog);
1189            pw.println("  mTrackingParams: " + mTrackingParams);
1190            pw.println("  mTrackingView: " + viewInfo(mTrackingView));
1191            pw.println("  mOngoingTitle: " + viewInfo(mOngoingTitle));
1192            pw.println("  mOngoingItems: " + viewInfo(mOngoingItems));
1193            pw.println("  mLatestTitle: " + viewInfo(mLatestTitle));
1194            pw.println("  mLatestItems: " + viewInfo(mLatestItems));
1195            pw.println("  mNoNotificationsTitle: " + viewInfo(mNoNotificationsTitle));
1196            pw.println("  mCloseView: " + viewInfo(mCloseView));
1197            pw.println("  mTickerView: " + viewInfo(mTickerView));
1198            pw.println("  mScrollView: " + viewInfo(mScrollView)
1199                    + " scroll " + mScrollView.getScrollX() + "," + mScrollView.getScrollY());
1200            pw.println("mNotificationLinearLayout: " + viewInfo(mNotificationLinearLayout));
1201        }
1202        /*
1203        synchronized (mNotificationData) {
1204            int N = mNotificationData.ongoingCount();
1205            pw.println("  ongoingCount.size=" + N);
1206            for (int i=0; i<N; i++) {
1207                StatusBarNotification n = mNotificationData.getOngoing(i);
1208                pw.println("    [" + i + "] key=" + n.key + " view=" + n.view);
1209                pw.println("           data=" + n.data);
1210            }
1211            N = mNotificationData.latestCount();
1212            pw.println("  ongoingCount.size=" + N);
1213            for (int i=0; i<N; i++) {
1214                StatusBarNotification n = mNotificationData.getLatest(i);
1215                pw.println("    [" + i + "] key=" + n.key + " view=" + n.view);
1216                pw.println("           data=" + n.data);
1217            }
1218        }
1219        */
1220
1221        if (false) {
1222            pw.println("see the logcat for a dump of the views we have created.");
1223            // must happen on ui thread
1224            mHandler.post(new Runnable() {
1225                    public void run() {
1226                        mStatusBarView.getLocationOnScreen(mAbsPos);
1227                        Slog.d(TAG, "mStatusBarView: ----- (" + mAbsPos[0] + "," + mAbsPos[1]
1228                                + ") " + mStatusBarView.getWidth() + "x"
1229                                + mStatusBarView.getHeight());
1230                        mStatusBarView.debug();
1231
1232                        mExpandedView.getLocationOnScreen(mAbsPos);
1233                        Slog.d(TAG, "mExpandedView: ----- (" + mAbsPos[0] + "," + mAbsPos[1]
1234                                + ") " + mExpandedView.getWidth() + "x"
1235                                + mExpandedView.getHeight());
1236                        mExpandedView.debug();
1237
1238                        mTrackingView.getLocationOnScreen(mAbsPos);
1239                        Slog.d(TAG, "mTrackingView: ----- (" + mAbsPos[0] + "," + mAbsPos[1]
1240                                + ") " + mTrackingView.getWidth() + "x"
1241                                + mTrackingView.getHeight());
1242                        mTrackingView.debug();
1243                    }
1244                });
1245        }
1246    }
1247
1248    void onBarViewAttached() {
1249        WindowManager.LayoutParams lp;
1250        int pixelFormat;
1251        Drawable bg;
1252
1253        /// ---------- Tracking View --------------
1254        pixelFormat = PixelFormat.RGBX_8888;
1255        bg = mTrackingView.getBackground();
1256        if (bg != null) {
1257            pixelFormat = bg.getOpacity();
1258        }
1259
1260        lp = new WindowManager.LayoutParams(
1261                ViewGroup.LayoutParams.MATCH_PARENT,
1262                ViewGroup.LayoutParams.MATCH_PARENT,
1263                WindowManager.LayoutParams.TYPE_STATUS_BAR_SUB_PANEL,
1264                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
1265                | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
1266                | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
1267                pixelFormat);
1268//        lp.token = mStatusBarView.getWindowToken();
1269        lp.gravity = Gravity.TOP | Gravity.FILL_HORIZONTAL;
1270        lp.setTitle("TrackingView");
1271        lp.y = mTrackingPosition;
1272        mTrackingParams = lp;
1273
1274        WindowManagerImpl.getDefault().addView(mTrackingView, lp);
1275    }
1276
1277    void onTrackingViewAttached() {
1278        WindowManager.LayoutParams lp;
1279        int pixelFormat;
1280        Drawable bg;
1281
1282        /// ---------- Expanded View --------------
1283        pixelFormat = PixelFormat.TRANSLUCENT;
1284
1285        final int disph = mDisplay.getHeight();
1286        lp = mExpandedDialog.getWindow().getAttributes();
1287        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
1288        lp.height = getExpandedHeight();
1289        lp.x = 0;
1290        mTrackingPosition = lp.y = -disph; // sufficiently large negative
1291        lp.type = WindowManager.LayoutParams.TYPE_STATUS_BAR_SUB_PANEL;
1292        lp.flags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
1293                | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
1294                | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
1295                | WindowManager.LayoutParams.FLAG_DITHER
1296                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
1297        lp.format = pixelFormat;
1298        lp.gravity = Gravity.TOP | Gravity.FILL_HORIZONTAL;
1299        lp.setTitle("StatusBarExpanded");
1300        mExpandedDialog.getWindow().setAttributes(lp);
1301        mExpandedDialog.getWindow().setFormat(pixelFormat);
1302        mExpandedParams = lp;
1303
1304        mExpandedDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
1305        mExpandedDialog.setContentView(mExpandedView,
1306                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1307                                           ViewGroup.LayoutParams.MATCH_PARENT));
1308        mExpandedDialog.getWindow().setBackgroundDrawable(null);
1309        mExpandedDialog.show();
1310        FrameLayout hack = (FrameLayout)mExpandedView.getParent();
1311    }
1312
1313    void setDateViewVisibility(boolean visible, int anim) {
1314        mDateView.setVisibility(visible ? View.VISIBLE : View.INVISIBLE);
1315        mDateView.startAnimation(loadAnim(anim, null));
1316    }
1317
1318    void setNotificationIconVisibility(boolean visible, int anim) {
1319        int old = mNotificationIcons.getVisibility();
1320        int v = visible ? View.VISIBLE : View.INVISIBLE;
1321        if (old != v) {
1322            mNotificationIcons.setVisibility(v);
1323            mNotificationIcons.startAnimation(loadAnim(anim, null));
1324        }
1325    }
1326
1327    void updateExpandedViewPos(int expandedPosition) {
1328        if (SPEW) {
1329            Slog.d(TAG, "updateExpandedViewPos before expandedPosition=" + expandedPosition
1330                    + " mTrackingParams.y=" + mTrackingParams.y
1331                    + " mTrackingPosition=" + mTrackingPosition);
1332        }
1333
1334        int h = mStatusBarView.getHeight();
1335        int disph = mDisplay.getHeight();
1336
1337        // If the expanded view is not visible, make sure they're still off screen.
1338        // Maybe the view was resized.
1339        if (!mExpandedVisible) {
1340            if (mTrackingView != null) {
1341                mTrackingPosition = -disph;
1342                if (mTrackingParams != null) {
1343                    mTrackingParams.y = mTrackingPosition;
1344                    WindowManagerImpl.getDefault().updateViewLayout(mTrackingView, mTrackingParams);
1345                }
1346            }
1347            if (mExpandedParams != null) {
1348                mExpandedParams.y = -disph;
1349                mExpandedDialog.getWindow().setAttributes(mExpandedParams);
1350            }
1351            return;
1352        }
1353
1354        // tracking view...
1355        int pos;
1356        if (expandedPosition == EXPANDED_FULL_OPEN) {
1357            pos = h;
1358        }
1359        else if (expandedPosition == EXPANDED_LEAVE_ALONE) {
1360            pos = mTrackingPosition;
1361        }
1362        else {
1363            if (expandedPosition <= disph) {
1364                pos = expandedPosition;
1365            } else {
1366                pos = disph;
1367            }
1368            pos -= disph-h;
1369        }
1370        mTrackingPosition = mTrackingParams.y = pos;
1371        mTrackingParams.height = disph-h;
1372        WindowManagerImpl.getDefault().updateViewLayout(mTrackingView, mTrackingParams);
1373
1374        if (mExpandedParams != null) {
1375            mCloseView.getLocationInWindow(mPositionTmp);
1376            final int closePos = mPositionTmp[1];
1377
1378            mExpandedContents.getLocationInWindow(mPositionTmp);
1379            final int contentsBottom = mPositionTmp[1] + mExpandedContents.getHeight();
1380
1381            mExpandedParams.y = pos + mTrackingView.getHeight()
1382                    - (mTrackingParams.height-closePos) - contentsBottom;
1383            int max = h;
1384            if (mExpandedParams.y > max) {
1385                mExpandedParams.y = max;
1386            }
1387            int min = mTrackingPosition;
1388            if (mExpandedParams.y < min) {
1389                mExpandedParams.y = min;
1390            }
1391
1392            boolean visible = (mTrackingPosition + mTrackingView.getHeight()) > h;
1393            if (!visible) {
1394                // if the contents aren't visible, move the expanded view way off screen
1395                // because the window itself extends below the content view.
1396                mExpandedParams.y = -disph;
1397            }
1398            mExpandedDialog.getWindow().setAttributes(mExpandedParams);
1399
1400            // As long as this isn't just a repositioning that's not supposed to affect
1401            // the user's perception of what's showing, call to say that the visibility
1402            // has changed. (Otherwise, someone else will call to do that).
1403            if (expandedPosition != EXPANDED_LEAVE_ALONE) {
1404                if (SPEW) Slog.d(TAG, "updateExpandedViewPos visibilityChanged(" + visible + ")");
1405                visibilityChanged(visible);
1406            }
1407        }
1408
1409        if (SPEW) {
1410            Slog.d(TAG, "updateExpandedViewPos after  expandedPosition=" + expandedPosition
1411                    + " mTrackingParams.y=" + mTrackingParams.y
1412                    + " mTrackingPosition=" + mTrackingPosition
1413                    + " mExpandedParams.y=" + mExpandedParams.y
1414                    + " mExpandedParams.height=" + mExpandedParams.height);
1415        }
1416    }
1417
1418    int getExpandedHeight() {
1419        return mDisplay.getHeight() - mStatusBarView.getHeight() - mCloseView.getHeight();
1420    }
1421
1422    void updateExpandedHeight() {
1423        if (mExpandedView != null) {
1424            mExpandedParams.height = getExpandedHeight();
1425            mExpandedDialog.getWindow().setAttributes(mExpandedParams);
1426        }
1427    }
1428
1429    /**
1430     * The LEDs are turned o)ff when the notification panel is shown, even just a little bit.
1431     * This was added last-minute and is inconsistent with the way the rest of the notifications
1432     * are handled, because the notification isn't really cancelled.  The lights are just
1433     * turned off.  If any other notifications happen, the lights will turn back on.  Steve says
1434     * this is what he wants. (see bug 1131461)
1435     */
1436    void visibilityChanged(boolean visible) {
1437        if (mPanelSlightlyVisible != visible) {
1438            mPanelSlightlyVisible = visible;
1439            try {
1440                mBarService.onPanelRevealed();
1441            } catch (RemoteException ex) {
1442                // Won't fail unless the world has ended.
1443            }
1444        }
1445    }
1446
1447    void performDisableActions(int net) {
1448        int old = mDisabled;
1449        int diff = net ^ old;
1450        mDisabled = net;
1451
1452        // act accordingly
1453        if ((diff & StatusBarManager.DISABLE_EXPAND) != 0) {
1454            if ((net & StatusBarManager.DISABLE_EXPAND) != 0) {
1455                Slog.d(TAG, "DISABLE_EXPAND: yes");
1456                animateCollapse();
1457            }
1458        }
1459        if ((diff & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
1460            if ((net & StatusBarManager.DISABLE_NOTIFICATION_ICONS) != 0) {
1461                Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: yes");
1462                if (mTicking) {
1463                    mNotificationIcons.setVisibility(View.INVISIBLE);
1464                    mTicker.halt();
1465                } else {
1466                    setNotificationIconVisibility(false, com.android.internal.R.anim.fade_out);
1467                }
1468            } else {
1469                Slog.d(TAG, "DISABLE_NOTIFICATION_ICONS: no");
1470                if (!mExpandedVisible) {
1471                    setNotificationIconVisibility(true, com.android.internal.R.anim.fade_in);
1472                }
1473            }
1474        } else if ((diff & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
1475            if (mTicking && (net & StatusBarManager.DISABLE_NOTIFICATION_TICKER) != 0) {
1476                mTicker.halt();
1477            }
1478        }
1479    }
1480
1481    private View.OnClickListener mClearButtonListener = new View.OnClickListener() {
1482        public void onClick(View v) {
1483            try {
1484                mBarService.onClearAllNotifications();
1485            } catch (RemoteException ex) {
1486                // system process is dead if we're here.
1487            }
1488            animateCollapse();
1489        }
1490    };
1491
1492    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
1493        public void onReceive(Context context, Intent intent) {
1494            String action = intent.getAction();
1495            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)
1496                    || Intent.ACTION_SCREEN_OFF.equals(action)) {
1497                animateCollapse();
1498            }
1499            else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
1500                updateResources();
1501            }
1502        }
1503    };
1504
1505    private void setIntruderAlertVisibility(boolean vis) {
1506        mIntruderAlertView.setVisibility(vis ? View.VISIBLE : View.GONE);
1507    }
1508
1509    /**
1510     * Reload some of our resources when the configuration changes.
1511     *
1512     * We don't reload everything when the configuration changes -- we probably
1513     * should, but getting that smooth is tough.  Someday we'll fix that.  In the
1514     * meantime, just update the things that we know change.
1515     */
1516    void updateResources() {
1517        final Context context = mContext;
1518        final Resources res = context.getResources();
1519
1520        mClearButton.setText(context.getText(R.string.status_bar_clear_all_button));
1521        mOngoingTitle.setText(context.getText(R.string.status_bar_ongoing_events_title));
1522        mLatestTitle.setText(context.getText(R.string.status_bar_latest_events_title));
1523        mNoNotificationsTitle.setText(context.getText(R.string.status_bar_no_notifications_title));
1524
1525        mEdgeBorder = res.getDimensionPixelSize(R.dimen.status_bar_edge_ignore);
1526
1527        if (false) Slog.v(TAG, "updateResources");
1528    }
1529
1530    //
1531    // tracing
1532    //
1533
1534    void postStartTracing() {
1535        mHandler.postDelayed(mStartTracing, 3000);
1536    }
1537
1538    void vibrate() {
1539        android.os.Vibrator vib = (android.os.Vibrator)mContext.getSystemService(
1540                Context.VIBRATOR_SERVICE);
1541        vib.vibrate(250);
1542    }
1543
1544    Runnable mStartTracing = new Runnable() {
1545        public void run() {
1546            vibrate();
1547            SystemClock.sleep(250);
1548            Slog.d(TAG, "startTracing");
1549            android.os.Debug.startMethodTracing("/data/statusbar-traces/trace");
1550            mHandler.postDelayed(mStopTracing, 10000);
1551        }
1552    };
1553
1554    Runnable mStopTracing = new Runnable() {
1555        public void run() {
1556            android.os.Debug.stopMethodTracing();
1557            Slog.d(TAG, "stopTracing");
1558            vibrate();
1559        }
1560    };
1561}
1562
1563