BaseStatusBar.java revision 1e8d71b605b4872e93200706a80a88a3ff25498c
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;
18
19import android.app.ActivityManager;
20import android.app.ActivityManagerNative;
21import android.app.Notification;
22import android.app.PendingIntent;
23import android.app.TaskStackBuilder;
24import android.content.BroadcastReceiver;
25import android.content.Context;
26import android.content.Intent;
27import android.content.IntentFilter;
28import android.content.pm.ApplicationInfo;
29import android.content.pm.PackageManager;
30import android.content.pm.PackageManager.NameNotFoundException;
31import android.content.pm.UserInfo;
32import android.content.res.Configuration;
33import android.database.ContentObserver;
34import android.graphics.Rect;
35import android.graphics.drawable.Drawable;
36import android.net.Uri;
37import android.os.Build;
38import android.os.Handler;
39import android.os.IBinder;
40import android.os.Message;
41import android.os.PowerManager;
42import android.os.RemoteException;
43import android.os.ServiceManager;
44import android.os.UserHandle;
45import android.os.UserManager;
46import android.provider.Settings;
47import android.service.dreams.DreamService;
48import android.service.dreams.IDreamManager;
49import android.service.notification.StatusBarNotification;
50import android.text.TextUtils;
51import android.util.Log;
52import android.util.SparseArray;
53import android.util.SparseBooleanArray;
54import android.view.Display;
55import android.view.IWindowManager;
56import android.view.LayoutInflater;
57import android.view.MenuItem;
58import android.view.MotionEvent;
59import android.view.View;
60import android.view.ViewGroup;
61import android.view.ViewGroup.LayoutParams;
62import android.view.WindowManager;
63import android.view.WindowManagerGlobal;
64import android.widget.ImageView;
65import android.widget.LinearLayout;
66import android.widget.PopupMenu;
67import android.widget.RemoteViews;
68import android.widget.TextView;
69
70import com.android.internal.statusbar.IStatusBarService;
71import com.android.internal.statusbar.StatusBarIcon;
72import com.android.internal.statusbar.StatusBarIconList;
73import com.android.internal.util.NotificationColorUtil;
74import com.android.systemui.R;
75import com.android.systemui.RecentsComponent;
76import com.android.systemui.SearchPanelView;
77import com.android.systemui.SystemUI;
78import com.android.systemui.statusbar.phone.KeyguardTouchDelegate;
79import com.android.systemui.statusbar.stack.NotificationStackScrollLayout;
80
81import java.util.ArrayList;
82import java.util.Locale;
83
84public abstract class BaseStatusBar extends SystemUI implements
85        CommandQueue.Callbacks, ActivatableNotificationView.OnActivatedListener {
86    public static final String TAG = "StatusBar";
87    public static final boolean DEBUG = false;
88    public static final boolean MULTIUSER_DEBUG = false;
89
90    protected static final int MSG_SHOW_RECENT_APPS = 1019;
91    protected static final int MSG_HIDE_RECENT_APPS = 1020;
92    protected static final int MSG_TOGGLE_RECENTS_APPS = 1021;
93    protected static final int MSG_PRELOAD_RECENT_APPS = 1022;
94    protected static final int MSG_CANCEL_PRELOAD_RECENT_APPS = 1023;
95    protected static final int MSG_OPEN_SEARCH_PANEL = 1024;
96    protected static final int MSG_CLOSE_SEARCH_PANEL = 1025;
97    protected static final int MSG_SHOW_HEADS_UP = 1026;
98    protected static final int MSG_HIDE_HEADS_UP = 1027;
99    protected static final int MSG_ESCALATE_HEADS_UP = 1028;
100
101    protected static final boolean ENABLE_HEADS_UP = true;
102    // scores above this threshold should be displayed in heads up mode.
103    protected static final int INTERRUPTION_THRESHOLD = 10;
104    protected static final String SETTING_HEADS_UP_TICKER = "ticker_gets_heads_up";
105
106    // Should match the value in PhoneWindowManager
107    public static final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
108
109    public static final int EXPANDED_LEAVE_ALONE = -10000;
110    public static final int EXPANDED_FULL_OPEN = -10001;
111
112    protected CommandQueue mCommandQueue;
113    protected IStatusBarService mBarService;
114    protected H mHandler = createHandler();
115
116    // all notifications
117    protected NotificationData mNotificationData = new NotificationData();
118    protected NotificationStackScrollLayout mStackScroller;
119
120    protected NotificationData.Entry mInterruptingNotificationEntry;
121    protected long mInterruptingNotificationTime;
122
123    // used to notify status bar for suppressing notification LED
124    protected boolean mPanelSlightlyVisible;
125
126    // Search panel
127    protected SearchPanelView mSearchPanelView;
128
129    protected PopupMenu mNotificationBlamePopup;
130
131    protected int mCurrentUserId = 0;
132    final protected SparseArray<UserInfo> mCurrentProfiles = new SparseArray<UserInfo>();
133
134    protected int mLayoutDirection = -1; // invalid
135    private Locale mLocale;
136    protected boolean mUseHeadsUp = false;
137    protected boolean mHeadsUpTicker = false;
138
139    protected IDreamManager mDreamManager;
140    PowerManager mPowerManager;
141    protected int mRowMinHeight;
142    protected int mRowMaxHeight;
143
144    // public mode, private notifications, etc
145    private boolean mLockscreenPublicMode = false;
146    private final SparseBooleanArray mUsersAllowingPrivateNotifications = new SparseBooleanArray();
147    private NotificationColorUtil mNotificationColorUtil = NotificationColorUtil.getInstance();
148
149    private UserManager mUserManager;
150
151    // UI-specific methods
152
153    /**
154     * Create all windows necessary for the status bar (including navigation, overlay panels, etc)
155     * and add them to the window manager.
156     */
157    protected abstract void createAndAddWindows();
158
159    protected WindowManager mWindowManager;
160    protected IWindowManager mWindowManagerService;
161    protected abstract void refreshLayout(int layoutDirection);
162
163    protected Display mDisplay;
164
165    private boolean mDeviceProvisioned = false;
166
167    private RecentsComponent mRecents;
168
169    protected int mZenMode;
170
171    /**
172     * The {@link StatusBarState} of the status bar.
173     */
174    protected int mState;
175    protected boolean mBouncerShowing;
176
177    protected NotificationOverflowContainer mKeyguardIconOverflowContainer;
178
179    public boolean isDeviceProvisioned() {
180        return mDeviceProvisioned;
181    }
182
183    protected final ContentObserver mSettingsObserver = new ContentObserver(mHandler) {
184        @Override
185        public void onChange(boolean selfChange) {
186            final boolean provisioned = 0 != Settings.Global.getInt(
187                    mContext.getContentResolver(), Settings.Global.DEVICE_PROVISIONED, 0);
188            if (provisioned != mDeviceProvisioned) {
189                mDeviceProvisioned = provisioned;
190                updateNotificationIcons();
191            }
192            final int mode = Settings.Global.getInt(mContext.getContentResolver(),
193                    Settings.Global.ZEN_MODE, Settings.Global.ZEN_MODE_OFF);
194            setZenMode(mode);
195        }
196    };
197
198    private final ContentObserver mLockscreenSettingsObserver = new ContentObserver(mHandler) {
199        @Override
200        public void onChange(boolean selfChange) {
201            // We don't know which user changed LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS,
202            // so we just dump our cache ...
203            mUsersAllowingPrivateNotifications.clear();
204            // ... and refresh all the notifications
205            updateNotificationIcons();
206        }
207    };
208
209    private RemoteViews.OnClickHandler mOnClickHandler = new RemoteViews.OnClickHandler() {
210        @Override
211        public boolean onClickHandler(View view, PendingIntent pendingIntent, Intent fillInIntent) {
212            if (DEBUG) {
213                Log.v(TAG, "Notification click handler invoked for intent: " + pendingIntent);
214            }
215            final boolean isActivity = pendingIntent.isActivity();
216            if (isActivity) {
217                try {
218                    // The intent we are sending is for the application, which
219                    // won't have permission to immediately start an activity after
220                    // the user switches to home.  We know it is safe to do at this
221                    // point, so make sure new activity switches are now allowed.
222                    ActivityManagerNative.getDefault().resumeAppSwitches();
223                    // Also, notifications can be launched from the lock screen,
224                    // so dismiss the lock screen when the activity starts.
225                    ActivityManagerNative.getDefault().dismissKeyguardOnNextActivity();
226                } catch (RemoteException e) {
227                }
228            }
229
230            boolean handled = super.onClickHandler(view, pendingIntent, fillInIntent);
231
232            if (isActivity && handled) {
233                // close the shade if it was open
234                animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
235                visibilityChanged(false);
236            }
237            return handled;
238        }
239    };
240
241    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
242        @Override
243        public void onReceive(Context context, Intent intent) {
244            String action = intent.getAction();
245            if (Intent.ACTION_USER_SWITCHED.equals(action)) {
246                mCurrentUserId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
247                updateCurrentProfilesCache();
248                if (true) Log.v(TAG, "userId " + mCurrentUserId + " is in the house");
249                userSwitched(mCurrentUserId);
250            } else if (Intent.ACTION_USER_ADDED.equals(action)) {
251                updateCurrentProfilesCache();
252            }
253        }
254    };
255
256    private void updateCurrentProfilesCache() {
257        synchronized (mCurrentProfiles) {
258            mCurrentProfiles.clear();
259            if (mUserManager != null) {
260                for (UserInfo user : mUserManager.getProfiles(mCurrentUserId)) {
261                    mCurrentProfiles.put(user.id, user);
262                }
263            }
264        }
265    }
266
267    public void start() {
268        mWindowManager = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
269        mWindowManagerService = WindowManagerGlobal.getWindowManagerService();
270        mDisplay = mWindowManager.getDefaultDisplay();
271
272        mDreamManager = IDreamManager.Stub.asInterface(
273                ServiceManager.checkService(DreamService.DREAM_SERVICE));
274        mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
275
276        mSettingsObserver.onChange(false); // set up
277        mContext.getContentResolver().registerContentObserver(
278                Settings.Global.getUriFor(Settings.Global.DEVICE_PROVISIONED), true,
279                mSettingsObserver);
280        mContext.getContentResolver().registerContentObserver(
281                Settings.Global.getUriFor(Settings.Global.ZEN_MODE), false,
282                mSettingsObserver);
283
284        mContext.getContentResolver().registerContentObserver(
285                Settings.Secure.getUriFor(Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS),
286                true,
287                mLockscreenSettingsObserver,
288                UserHandle.USER_ALL);
289
290        mBarService = IStatusBarService.Stub.asInterface(
291                ServiceManager.getService(Context.STATUS_BAR_SERVICE));
292
293        mRecents = getComponent(RecentsComponent.class);
294
295        mLocale = mContext.getResources().getConfiguration().locale;
296        mLayoutDirection = TextUtils.getLayoutDirectionFromLocale(mLocale);
297
298        mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
299
300        // Connect in to the status bar manager service
301        StatusBarIconList iconList = new StatusBarIconList();
302        ArrayList<IBinder> notificationKeys = new ArrayList<IBinder>();
303        ArrayList<StatusBarNotification> notifications = new ArrayList<StatusBarNotification>();
304        mCommandQueue = new CommandQueue(this, iconList);
305
306        int[] switches = new int[8];
307        ArrayList<IBinder> binders = new ArrayList<IBinder>();
308        try {
309            mBarService.registerStatusBar(mCommandQueue, iconList, notificationKeys, notifications,
310                    switches, binders);
311        } catch (RemoteException ex) {
312            // If the system process isn't there we're doomed anyway.
313        }
314
315        createAndAddWindows();
316
317        disable(switches[0]);
318        setSystemUiVisibility(switches[1], 0xffffffff);
319        topAppWindowChanged(switches[2] != 0);
320        // StatusBarManagerService has a back up of IME token and it's restored here.
321        setImeWindowStatus(binders.get(0), switches[3], switches[4], switches[7] != 0);
322        setHardKeyboardStatus(switches[5] != 0, switches[6] != 0);
323
324        // Set up the initial icon state
325        int N = iconList.size();
326        int viewIndex = 0;
327        for (int i=0; i<N; i++) {
328            StatusBarIcon icon = iconList.getIcon(i);
329            if (icon != null) {
330                addIcon(iconList.getSlot(i), i, viewIndex, icon);
331                viewIndex++;
332            }
333        }
334
335        // Set up the initial notification state
336        N = notificationKeys.size();
337        if (N == notifications.size()) {
338            for (int i=0; i<N; i++) {
339                addNotification(notificationKeys.get(i), notifications.get(i));
340            }
341        } else {
342            Log.wtf(TAG, "Notification list length mismatch: keys=" + N
343                    + " notifications=" + notifications.size());
344        }
345
346        if (DEBUG) {
347            Log.d(TAG, String.format(
348                    "init: icons=%d disabled=0x%08x lights=0x%08x menu=0x%08x imeButton=0x%08x",
349                   iconList.size(),
350                   switches[0],
351                   switches[1],
352                   switches[2],
353                   switches[3]
354                   ));
355        }
356
357        mCurrentUserId = ActivityManager.getCurrentUser();
358
359        IntentFilter filter = new IntentFilter();
360        filter.addAction(Intent.ACTION_USER_SWITCHED);
361        filter.addAction(Intent.ACTION_USER_ADDED);
362        mContext.registerReceiver(mBroadcastReceiver, filter);
363
364        updateCurrentProfilesCache();
365    }
366
367    public void userSwitched(int newUserId) {
368        // should be overridden
369    }
370
371    public boolean notificationIsForCurrentProfiles(StatusBarNotification n) {
372        final int thisUserId = mCurrentUserId;
373        final int notificationUserId = n.getUserId();
374        if (DEBUG && MULTIUSER_DEBUG) {
375            Log.v(TAG, String.format("%s: current userid: %d, notification userid: %d",
376                    n, thisUserId, notificationUserId));
377        }
378        synchronized (mCurrentProfiles) {
379            return notificationUserId == UserHandle.USER_ALL
380                    || mCurrentProfiles.get(notificationUserId) != null;
381        }
382    }
383
384    @Override
385    protected void onConfigurationChanged(Configuration newConfig) {
386        final Locale locale = mContext.getResources().getConfiguration().locale;
387        final int ld = TextUtils.getLayoutDirectionFromLocale(locale);
388        if (! locale.equals(mLocale) || ld != mLayoutDirection) {
389            if (DEBUG) {
390                Log.v(TAG, String.format(
391                        "config changed locale/LD: %s (%d) -> %s (%d)", mLocale, mLayoutDirection,
392                        locale, ld));
393            }
394            mLocale = locale;
395            mLayoutDirection = ld;
396            refreshLayout(ld);
397        }
398    }
399
400    protected View updateNotificationVetoButton(View row, StatusBarNotification n) {
401        View vetoButton = row.findViewById(R.id.veto);
402        if (n.isClearable() || (mInterruptingNotificationEntry != null
403                && mInterruptingNotificationEntry.row == row)) {
404            final String _pkg = n.getPackageName();
405            final String _tag = n.getTag();
406            final int _id = n.getId();
407            final int _userId = n.getUserId();
408            vetoButton.setOnClickListener(new View.OnClickListener() {
409                    public void onClick(View v) {
410                        // Accessibility feedback
411                        v.announceForAccessibility(
412                                mContext.getString(R.string.accessibility_notification_dismissed));
413                        try {
414                            mBarService.onNotificationClear(_pkg, _tag, _id, _userId);
415
416                        } catch (RemoteException ex) {
417                            // system process is dead if we're here.
418                        }
419                    }
420                });
421            vetoButton.setVisibility(View.VISIBLE);
422        } else {
423            vetoButton.setVisibility(View.GONE);
424        }
425        vetoButton.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
426        return vetoButton;
427    }
428
429
430    protected void applyLegacyRowBackground(StatusBarNotification sbn,
431            NotificationData.Entry entry) {
432        if (entry.expanded.getId() != com.android.internal.R.id.status_bar_latest_event_content) {
433            int version = 0;
434            try {
435                ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(sbn.getPackageName(), 0);
436                version = info.targetSdkVersion;
437            } catch (NameNotFoundException ex) {
438                Log.e(TAG, "Failed looking up ApplicationInfo for " + sbn.getPackageName(), ex);
439            }
440            if (version > 0 && version < Build.VERSION_CODES.GINGERBREAD) {
441                entry.row.setBackgroundResource(R.drawable.notification_row_legacy_bg);
442            } else if (version < Build.VERSION_CODES.L) {
443                entry.row.setBackgroundResourceIds(
444                        com.android.internal.R.drawable.notification_bg,
445                        com.android.internal.R.drawable.notification_bg_dim);
446            }
447        }
448    }
449
450    private void startApplicationDetailsActivity(String packageName) {
451        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
452                Uri.fromParts("package", packageName, null));
453        intent.setComponent(intent.resolveActivity(mContext.getPackageManager()));
454        TaskStackBuilder.create(mContext).addNextIntentWithParentStack(intent).startActivities(
455                null, UserHandle.CURRENT);
456    }
457
458    protected View.OnLongClickListener getNotificationLongClicker() {
459        return new View.OnLongClickListener() {
460            @Override
461            public boolean onLongClick(View v) {
462                final String packageNameF = (String) v.getTag();
463                if (packageNameF == null) return false;
464                if (v.getWindowToken() == null) return false;
465                mNotificationBlamePopup = new PopupMenu(mContext, v);
466                mNotificationBlamePopup.getMenuInflater().inflate(
467                        R.menu.notification_popup_menu,
468                        mNotificationBlamePopup.getMenu());
469                mNotificationBlamePopup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
470                    public boolean onMenuItemClick(MenuItem item) {
471                        if (item.getItemId() == R.id.notification_inspect_item) {
472                            startApplicationDetailsActivity(packageNameF);
473                            animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
474                        } else {
475                            return false;
476                        }
477                        return true;
478                    }
479                });
480                mNotificationBlamePopup.show();
481
482                return true;
483            }
484        };
485    }
486
487    public void dismissPopups() {
488        if (mNotificationBlamePopup != null) {
489            mNotificationBlamePopup.dismiss();
490            mNotificationBlamePopup = null;
491        }
492    }
493
494    public void onHeadsUpDismissed() {
495    }
496
497    @Override
498    public void showRecentApps(boolean triggeredFromAltTab) {
499        int msg = MSG_SHOW_RECENT_APPS;
500        mHandler.removeMessages(msg);
501        mHandler.obtainMessage(msg, triggeredFromAltTab ? 1 : 0, 0).sendToTarget();
502    }
503
504    @Override
505    public void hideRecentApps() {
506        int msg = MSG_HIDE_RECENT_APPS;
507        mHandler.removeMessages(msg);
508        mHandler.sendEmptyMessage(msg);
509    }
510
511    @Override
512    public void toggleRecentApps() {
513        int msg = MSG_TOGGLE_RECENTS_APPS;
514        mHandler.removeMessages(msg);
515        mHandler.sendEmptyMessage(msg);
516    }
517
518    @Override
519    public void preloadRecentApps() {
520        int msg = MSG_PRELOAD_RECENT_APPS;
521        mHandler.removeMessages(msg);
522        mHandler.sendEmptyMessage(msg);
523    }
524
525    @Override
526    public void cancelPreloadRecentApps() {
527        int msg = MSG_CANCEL_PRELOAD_RECENT_APPS;
528        mHandler.removeMessages(msg);
529        mHandler.sendEmptyMessage(msg);
530    }
531
532    @Override
533    public void showSearchPanel() {
534        int msg = MSG_OPEN_SEARCH_PANEL;
535        mHandler.removeMessages(msg);
536        mHandler.sendEmptyMessage(msg);
537    }
538
539    @Override
540    public void hideSearchPanel() {
541        int msg = MSG_CLOSE_SEARCH_PANEL;
542        mHandler.removeMessages(msg);
543        mHandler.sendEmptyMessage(msg);
544    }
545
546    protected abstract WindowManager.LayoutParams getSearchLayoutParams(
547            LayoutParams layoutParams);
548
549    protected void updateSearchPanel() {
550        // Search Panel
551        boolean visible = false;
552        if (mSearchPanelView != null) {
553            visible = mSearchPanelView.isShowing();
554            mWindowManager.removeView(mSearchPanelView);
555        }
556
557        // Provide SearchPanel with a temporary parent to allow layout params to work.
558        LinearLayout tmpRoot = new LinearLayout(mContext);
559        mSearchPanelView = (SearchPanelView) LayoutInflater.from(mContext).inflate(
560                 R.layout.status_bar_search_panel, tmpRoot, false);
561        mSearchPanelView.setOnTouchListener(
562                 new TouchOutsideListener(MSG_CLOSE_SEARCH_PANEL, mSearchPanelView));
563        mSearchPanelView.setVisibility(View.GONE);
564
565        WindowManager.LayoutParams lp = getSearchLayoutParams(mSearchPanelView.getLayoutParams());
566
567        mWindowManager.addView(mSearchPanelView, lp);
568        mSearchPanelView.setBar(this);
569        if (visible) {
570            mSearchPanelView.show(true, false);
571        }
572    }
573
574    protected H createHandler() {
575         return new H();
576    }
577
578    static void sendCloseSystemWindows(Context context, String reason) {
579        if (ActivityManagerNative.isSystemReady()) {
580            try {
581                ActivityManagerNative.getDefault().closeSystemDialogs(reason);
582            } catch (RemoteException e) {
583            }
584        }
585    }
586
587    protected abstract View getStatusBarView();
588
589    protected View.OnTouchListener mRecentsPreloadOnTouchListener = new View.OnTouchListener() {
590        // additional optimization when we have software system buttons - start loading the recent
591        // tasks on touch down
592        @Override
593        public boolean onTouch(View v, MotionEvent event) {
594            int action = event.getAction() & MotionEvent.ACTION_MASK;
595            if (action == MotionEvent.ACTION_DOWN) {
596                preloadRecents();
597            } else if (action == MotionEvent.ACTION_CANCEL) {
598                cancelPreloadingRecents();
599            } else if (action == MotionEvent.ACTION_UP) {
600                if (!v.isPressed()) {
601                    cancelPreloadingRecents();
602                }
603
604            }
605            return false;
606        }
607    };
608
609    /** Proxy for RecentsComponent */
610
611    protected void showRecents(boolean triggeredFromAltTab) {
612        if (mRecents != null) {
613            sendCloseSystemWindows(mContext, SYSTEM_DIALOG_REASON_RECENT_APPS);
614            mRecents.showRecents(triggeredFromAltTab, getStatusBarView());
615        }
616    }
617
618    protected void hideRecents() {
619        if (mRecents != null) {
620            sendCloseSystemWindows(mContext, SYSTEM_DIALOG_REASON_RECENT_APPS);
621            mRecents.hideRecents();
622        }
623    }
624
625    protected void toggleRecents() {
626        if (mRecents != null) {
627            sendCloseSystemWindows(mContext, SYSTEM_DIALOG_REASON_RECENT_APPS);
628            mRecents.toggleRecents(mDisplay, mLayoutDirection, getStatusBarView());
629        }
630    }
631
632    protected void preloadRecents() {
633        if (mRecents != null) {
634            mRecents.preloadRecents();
635        }
636    }
637
638    protected void cancelPreloadingRecents() {
639        if (mRecents != null) {
640            mRecents.cancelPreloadingRecents();
641        }
642    }
643
644    public abstract void resetHeadsUpDecayTimer();
645
646    /**
647     * Save the current "public" (locked and secure) state of the lockscreen.
648     */
649    public void setLockscreenPublicMode(boolean publicMode) {
650        mLockscreenPublicMode = publicMode;
651    }
652
653    public boolean isLockscreenPublicMode() {
654        return mLockscreenPublicMode;
655    }
656
657    /**
658     * Has the given user chosen to allow their private (full) notifications to be shown even
659     * when the lockscreen is in "public" (secure & locked) mode?
660     */
661    public boolean userAllowsPrivateNotificationsInPublic(int userHandle) {
662        if (userHandle == UserHandle.USER_ALL) {
663            return true;
664        }
665
666        if (mUsersAllowingPrivateNotifications.indexOfKey(userHandle) < 0) {
667            final boolean allowed = 0 != Settings.Secure.getIntForUser(
668                    mContext.getContentResolver(),
669                    Settings.Secure.LOCK_SCREEN_ALLOW_PRIVATE_NOTIFICATIONS, 0, userHandle);
670            mUsersAllowingPrivateNotifications.append(userHandle, allowed);
671            return allowed;
672        }
673
674        return mUsersAllowingPrivateNotifications.get(userHandle);
675    }
676
677    protected class H extends Handler {
678        public void handleMessage(Message m) {
679            Intent intent;
680            switch (m.what) {
681             case MSG_SHOW_RECENT_APPS:
682                 showRecents(m.arg1 > 0);
683                 break;
684             case MSG_HIDE_RECENT_APPS:
685                 hideRecents();
686                 break;
687             case MSG_TOGGLE_RECENTS_APPS:
688                 toggleRecents();
689                 break;
690             case MSG_PRELOAD_RECENT_APPS:
691                  preloadRecents();
692                  break;
693             case MSG_CANCEL_PRELOAD_RECENT_APPS:
694                  cancelPreloadingRecents();
695                  break;
696             case MSG_OPEN_SEARCH_PANEL:
697                 if (DEBUG) Log.d(TAG, "opening search panel");
698                 if (mSearchPanelView != null && mSearchPanelView.isAssistantAvailable()) {
699                     mSearchPanelView.show(true, true);
700                     onShowSearchPanel();
701                 }
702                 break;
703             case MSG_CLOSE_SEARCH_PANEL:
704                 if (DEBUG) Log.d(TAG, "closing search panel");
705                 if (mSearchPanelView != null && mSearchPanelView.isShowing()) {
706                     mSearchPanelView.show(false, true);
707                     onHideSearchPanel();
708                 }
709                 break;
710            }
711        }
712    }
713
714    public class TouchOutsideListener implements View.OnTouchListener {
715        private int mMsg;
716        private StatusBarPanel mPanel;
717
718        public TouchOutsideListener(int msg, StatusBarPanel panel) {
719            mMsg = msg;
720            mPanel = panel;
721        }
722
723        public boolean onTouch(View v, MotionEvent ev) {
724            final int action = ev.getAction();
725            if (action == MotionEvent.ACTION_OUTSIDE
726                || (action == MotionEvent.ACTION_DOWN
727                    && !mPanel.isInContentArea((int)ev.getX(), (int)ev.getY()))) {
728                mHandler.removeMessages(mMsg);
729                mHandler.sendEmptyMessage(mMsg);
730                return true;
731            }
732            return false;
733        }
734    }
735
736    protected void workAroundBadLayerDrawableOpacity(View v) {
737    }
738
739    protected void onHideSearchPanel() {
740    }
741
742    protected void onShowSearchPanel() {
743    }
744
745    public boolean inflateViews(NotificationData.Entry entry, ViewGroup parent) {
746            return inflateViews(entry, parent, false);
747    }
748
749    public boolean inflateViewsForHeadsUp(NotificationData.Entry entry, ViewGroup parent) {
750            return inflateViews(entry, parent, true);
751    }
752
753    public boolean inflateViews(NotificationData.Entry entry, ViewGroup parent, boolean isHeadsUp) {
754        int minHeight =
755                mContext.getResources().getDimensionPixelSize(R.dimen.notification_min_height);
756        int maxHeight =
757                mContext.getResources().getDimensionPixelSize(R.dimen.notification_max_height);
758        StatusBarNotification sbn = entry.notification;
759        RemoteViews contentView = sbn.getNotification().contentView;
760        RemoteViews bigContentView = sbn.getNotification().bigContentView;
761
762        if (isHeadsUp) {
763            maxHeight =
764                    mContext.getResources().getDimensionPixelSize(R.dimen.notification_mid_height);
765            bigContentView = sbn.getNotification().headsUpContentView;
766        }
767
768        if (contentView == null) {
769            return false;
770        }
771
772        if (DEBUG) {
773            Log.v(TAG, "publicNotification: " + sbn.getNotification().publicVersion);
774        }
775
776        Notification publicNotification = sbn.getNotification().publicVersion;
777
778        // create the row view
779        LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(
780                Context.LAYOUT_INFLATER_SERVICE);
781        ExpandableNotificationRow row = (ExpandableNotificationRow) inflater.inflate(
782                R.layout.status_bar_notification_row, parent, false);
783
784        // for blaming (see SwipeHelper.setLongPressListener)
785        row.setTag(sbn.getPackageName());
786
787        workAroundBadLayerDrawableOpacity(row);
788        View vetoButton = updateNotificationVetoButton(row, sbn);
789        vetoButton.setContentDescription(mContext.getString(
790                R.string.accessibility_remove_notification));
791
792        // NB: the large icon is now handled entirely by the template
793
794        // bind the click event to the content area
795        NotificationContentView expanded =
796                (NotificationContentView) row.findViewById(R.id.expanded);
797        NotificationContentView expandedPublic =
798                (NotificationContentView) row.findViewById(R.id.expandedPublic);
799
800        row.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
801
802        PendingIntent contentIntent = sbn.getNotification().contentIntent;
803        if (contentIntent != null) {
804            final View.OnClickListener listener = makeClicker(contentIntent, sbn.getKey(),
805                    isHeadsUp);
806            row.setOnClickListener(listener);
807        } else {
808            row.setOnClickListener(null);
809        }
810
811        // set up the adaptive layout
812        View contentViewLocal = null;
813        View bigContentViewLocal = null;
814        try {
815            contentViewLocal = contentView.apply(mContext, expanded,
816                    mOnClickHandler);
817            if (bigContentView != null) {
818                bigContentViewLocal = bigContentView.apply(mContext, expanded,
819                        mOnClickHandler);
820            }
821        }
822        catch (RuntimeException e) {
823            final String ident = sbn.getPackageName() + "/0x" + Integer.toHexString(sbn.getId());
824            Log.e(TAG, "couldn't inflate view for notification " + ident, e);
825            return false;
826        }
827
828        if (contentViewLocal != null) {
829            contentViewLocal.setIsRootNamespace(true);
830            expanded.setContractedChild(contentViewLocal);
831        }
832        if (bigContentViewLocal != null) {
833            bigContentViewLocal.setIsRootNamespace(true);
834            expanded.setExpandedChild(bigContentViewLocal);
835        }
836
837        PackageManager pm = mContext.getPackageManager();
838
839        // now the public version
840        View publicViewLocal = null;
841        if (publicNotification != null) {
842            try {
843                publicViewLocal = publicNotification.contentView.apply(mContext, expandedPublic,
844                        mOnClickHandler);
845
846                if (publicViewLocal != null) {
847                    publicViewLocal.setIsRootNamespace(true);
848                    expandedPublic.setContractedChild(publicViewLocal);
849                }
850            }
851            catch (RuntimeException e) {
852                final String ident = sbn.getPackageName() + "/0x" + Integer.toHexString(sbn.getId());
853                Log.e(TAG, "couldn't inflate public view for notification " + ident, e);
854                publicViewLocal = null;
855            }
856        }
857
858        if (publicViewLocal == null) {
859            // Add a basic notification template
860            publicViewLocal = LayoutInflater.from(mContext).inflate(
861                    com.android.internal.R.layout.notification_template_quantum_base,
862                    expandedPublic, true);
863
864            final TextView title = (TextView) publicViewLocal.findViewById(com.android.internal.R.id.title);
865            try {
866                title.setText(pm.getApplicationLabel(
867                        pm.getApplicationInfo(entry.notification.getPackageName(), 0)));
868            } catch (NameNotFoundException e) {
869                title.setText(entry.notification.getPackageName());
870            }
871
872            final ImageView icon = (ImageView) publicViewLocal.findViewById(com.android.internal.R.id.icon);
873
874            final StatusBarIcon ic = new StatusBarIcon(entry.notification.getPackageName(),
875                    entry.notification.getUser(),
876                    entry.notification.getNotification().icon,
877                    entry.notification.getNotification().iconLevel,
878                    entry.notification.getNotification().number,
879                    entry.notification.getNotification().tickerText);
880
881            Drawable iconDrawable = StatusBarIconView.getIcon(mContext, ic);
882            icon.setImageDrawable(iconDrawable);
883            if (mNotificationColorUtil.isGrayscale(iconDrawable)) {
884                icon.setBackgroundResource(
885                        com.android.internal.R.drawable.notification_icon_legacy_bg_inset);
886            }
887
888            final TextView text = (TextView) publicViewLocal.findViewById(com.android.internal.R.id.text);
889            text.setText("Unlock your device to see this notification.");
890
891            // TODO: fill out "time" as well
892        }
893
894        row.setDrawingCacheEnabled(true);
895
896        if (MULTIUSER_DEBUG) {
897            TextView debug = (TextView) row.findViewById(R.id.debug_info);
898            if (debug != null) {
899                debug.setVisibility(View.VISIBLE);
900                debug.setText("CU " + mCurrentUserId +" NU " + entry.notification.getUserId());
901            }
902        }
903        entry.row = row;
904        entry.row.setHeightRange(mRowMinHeight, mRowMaxHeight);
905        entry.row.setOnActivatedListener(this);
906        entry.expanded = contentViewLocal;
907        entry.expandedPublic = publicViewLocal;
908        entry.setBigContentView(bigContentViewLocal);
909
910        applyLegacyRowBackground(sbn, entry);
911
912        return true;
913    }
914
915    public NotificationClicker makeClicker(PendingIntent intent, String notificationKey,
916            boolean forHun) {
917        return new NotificationClicker(intent, notificationKey, forHun);
918    }
919
920    protected class NotificationClicker implements View.OnClickListener {
921        private PendingIntent mIntent;
922        private final String mNotificationKey;
923        private boolean mIsHeadsUp;
924
925        public NotificationClicker(PendingIntent intent, String notificationKey, boolean forHun) {
926            mIntent = intent;
927            mNotificationKey = notificationKey;
928            mIsHeadsUp = forHun;
929        }
930
931        public void onClick(View v) {
932            try {
933                // The intent we are sending is for the application, which
934                // won't have permission to immediately start an activity after
935                // the user switches to home.  We know it is safe to do at this
936                // point, so make sure new activity switches are now allowed.
937                ActivityManagerNative.getDefault().resumeAppSwitches();
938                // Also, notifications can be launched from the lock screen,
939                // so dismiss the lock screen when the activity starts.
940                ActivityManagerNative.getDefault().dismissKeyguardOnNextActivity();
941            } catch (RemoteException e) {
942            }
943
944            if (mIntent != null) {
945                int[] pos = new int[2];
946                v.getLocationOnScreen(pos);
947                Intent overlay = new Intent();
948                overlay.setSourceBounds(
949                        new Rect(pos[0], pos[1], pos[0]+v.getWidth(), pos[1]+v.getHeight()));
950                try {
951                    mIntent.send(mContext, 0, overlay);
952                } catch (PendingIntent.CanceledException e) {
953                    // the stack trace isn't very helpful here.  Just log the exception message.
954                    Log.w(TAG, "Sending contentIntent failed: " + e);
955                }
956
957                KeyguardTouchDelegate.getInstance(mContext).dismiss();
958            }
959
960            try {
961                if (mIsHeadsUp) {
962                    mHandler.sendEmptyMessage(MSG_HIDE_HEADS_UP);
963                }
964                mBarService.onNotificationClick(mNotificationKey);
965            } catch (RemoteException ex) {
966                // system process is dead if we're here.
967            }
968
969            // close the shade if it was open
970            animateCollapsePanels(CommandQueue.FLAG_EXCLUDE_NONE);
971            visibilityChanged(false);
972        }
973    }
974
975    /**
976     * The LEDs are turned o)ff when the notification panel is shown, even just a little bit.
977     * This was added last-minute and is inconsistent with the way the rest of the notifications
978     * are handled, because the notification isn't really cancelled.  The lights are just
979     * turned off.  If any other notifications happen, the lights will turn back on.  Steve says
980     * this is what he wants. (see bug 1131461)
981     */
982    protected void visibilityChanged(boolean visible) {
983        if (mPanelSlightlyVisible != visible) {
984            mPanelSlightlyVisible = visible;
985            try {
986                if (visible) {
987                    mBarService.onPanelRevealed();
988                } else {
989                    mBarService.onPanelHidden();
990                }
991            } catch (RemoteException ex) {
992                // Won't fail unless the world has ended.
993            }
994        }
995    }
996
997    /**
998     * Cancel this notification and tell the StatusBarManagerService / NotificationManagerService
999     * about the failure.
1000     *
1001     * WARNING: this will call back into us.  Don't hold any locks.
1002     */
1003    void handleNotificationError(IBinder key, StatusBarNotification n, String message) {
1004        removeNotification(key);
1005        try {
1006            mBarService.onNotificationError(n.getPackageName(), n.getTag(), n.getId(), n.getUid(),
1007                    n.getInitialPid(), message, n.getUserId());
1008        } catch (RemoteException ex) {
1009            // The end is nigh.
1010        }
1011    }
1012
1013    protected StatusBarNotification removeNotificationViews(IBinder key) {
1014        NotificationData.Entry entry = mNotificationData.remove(key);
1015        if (entry == null) {
1016            Log.w(TAG, "removeNotification for unknown key: " + key);
1017            return null;
1018        }
1019        // Remove the expanded view.
1020        ViewGroup rowParent = (ViewGroup)entry.row.getParent();
1021        if (rowParent != null) rowParent.removeView(entry.row);
1022        updateRowStates();
1023        updateNotificationIcons();
1024
1025        return entry.notification;
1026    }
1027
1028    protected NotificationData.Entry createNotificationViews(IBinder key,
1029            StatusBarNotification notification) {
1030        if (DEBUG) {
1031            Log.d(TAG, "createNotificationViews(key=" + key + ", notification=" + notification);
1032        }
1033        // Construct the icon.
1034        final StatusBarIconView iconView = new StatusBarIconView(mContext,
1035                notification.getPackageName() + "/0x" + Integer.toHexString(notification.getId()),
1036                notification.getNotification());
1037        iconView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
1038
1039        final StatusBarIcon ic = new StatusBarIcon(notification.getPackageName(),
1040                notification.getUser(),
1041                    notification.getNotification().icon,
1042                    notification.getNotification().iconLevel,
1043                    notification.getNotification().number,
1044                    notification.getNotification().tickerText);
1045        if (!iconView.set(ic)) {
1046            handleNotificationError(key, notification, "Couldn't create icon: " + ic);
1047            return null;
1048        }
1049        // Construct the expanded view.
1050        NotificationData.Entry entry = new NotificationData.Entry(key, notification, iconView);
1051        if (!inflateViews(entry, mStackScroller)) {
1052            handleNotificationError(key, notification, "Couldn't expand RemoteViews for: "
1053                    + notification);
1054            return null;
1055        }
1056        return entry;
1057    }
1058
1059    protected void addNotificationViews(NotificationData.Entry entry) {
1060        if (entry == null) {
1061            return;
1062        }
1063        // Add the expanded view and icon.
1064        int pos = mNotificationData.add(entry);
1065        if (DEBUG) {
1066            Log.d(TAG, "addNotificationViews: added at " + pos);
1067        }
1068        updateRowStates();
1069        updateNotificationIcons();
1070    }
1071
1072    private void addNotificationViews(IBinder key, StatusBarNotification notification) {
1073        addNotificationViews(createNotificationViews(key, notification));
1074    }
1075
1076    /**
1077     * @return The number of notifications we show on Keyguard.
1078     */
1079    protected abstract int getMaxKeyguardNotifications();
1080
1081    /**
1082     * Updates expanded, dimmed and locked states of notification rows.
1083     */
1084    protected void updateRowStates() {
1085        int maxKeyguardNotifications = getMaxKeyguardNotifications();
1086        mKeyguardIconOverflowContainer.getIconsView().removeAllViews();
1087        int n = mNotificationData.size();
1088        int visibleNotifications = 0;
1089        boolean onKeyguard = mState == StatusBarState.KEYGUARD;
1090        for (int i = n-1; i >= 0; i--) {
1091            NotificationData.Entry entry = mNotificationData.get(i);
1092            if (onKeyguard) {
1093                entry.row.setExpansionDisabled(true);
1094            } else {
1095                entry.row.setExpansionDisabled(false);
1096                if (!entry.row.isUserLocked()) {
1097                    boolean top = (i == n-1);
1098                    entry.row.setSystemExpanded(top);
1099                }
1100            }
1101            boolean showOnKeyguard = shouldShowOnKeyguard(entry.notification);
1102            if (onKeyguard && (visibleNotifications >= maxKeyguardNotifications
1103                    || !showOnKeyguard)) {
1104                entry.row.setVisibility(View.GONE);
1105                if (showOnKeyguard) {
1106                    mKeyguardIconOverflowContainer.getIconsView().addNotification(entry);
1107                }
1108            } else {
1109                if (entry.row.getVisibility() == View.GONE) {
1110                    // notify the scroller of a child addition
1111                    mStackScroller.generateAddAnimation(entry.row);
1112                }
1113                entry.row.setVisibility(View.VISIBLE);
1114                visibleNotifications++;
1115            }
1116        }
1117
1118        if (onKeyguard && mKeyguardIconOverflowContainer.getIconsView().getChildCount() > 0) {
1119            mKeyguardIconOverflowContainer.setVisibility(View.VISIBLE);
1120        } else {
1121            mKeyguardIconOverflowContainer.setVisibility(View.GONE);
1122        }
1123    }
1124
1125    private boolean shouldShowOnKeyguard(StatusBarNotification sbn) {
1126        return sbn.getNotification().priority >= Notification.PRIORITY_LOW;
1127    }
1128
1129    protected void setZenMode(int mode) {
1130        if (!isDeviceProvisioned()) return;
1131        mZenMode = mode;
1132        updateNotificationIcons();
1133    }
1134
1135    protected abstract void haltTicker();
1136    protected abstract void setAreThereNotifications();
1137    protected abstract void updateNotificationIcons();
1138    protected abstract void tick(IBinder key, StatusBarNotification n, boolean firstTime);
1139    protected abstract void updateExpandedViewPos(int expandedPosition);
1140    protected abstract boolean shouldDisableNavbarGestures();
1141
1142    protected boolean isTopNotification(ViewGroup parent, NotificationData.Entry entry) {
1143        return parent != null && parent.indexOfChild(entry.row) == 0;
1144    }
1145
1146    public void updateNotification(IBinder key, StatusBarNotification notification) {
1147        if (DEBUG) Log.d(TAG, "updateNotification(" + key + " -> " + notification + ")");
1148
1149        final NotificationData.Entry oldEntry = mNotificationData.findByKey(key);
1150        if (oldEntry == null) {
1151            Log.w(TAG, "updateNotification for unknown key: " + key);
1152            return;
1153        }
1154
1155        final StatusBarNotification oldNotification = oldEntry.notification;
1156
1157        // XXX: modify when we do something more intelligent with the two content views
1158        final RemoteViews oldContentView = oldNotification.getNotification().contentView;
1159        final RemoteViews contentView = notification.getNotification().contentView;
1160        final RemoteViews oldBigContentView = oldNotification.getNotification().bigContentView;
1161        final RemoteViews bigContentView = notification.getNotification().bigContentView;
1162        final RemoteViews oldHeadsUpContentView = oldNotification.getNotification().headsUpContentView;
1163        final RemoteViews headsUpContentView = notification.getNotification().headsUpContentView;
1164        final Notification oldPublicNotification = oldNotification.getNotification().publicVersion;
1165        final RemoteViews oldPublicContentView = oldPublicNotification != null
1166                ? oldPublicNotification.contentView : null;
1167        final Notification publicNotification = notification.getNotification().publicVersion;
1168        final RemoteViews publicContentView = publicNotification != null
1169                ? publicNotification.contentView : null;
1170
1171        if (DEBUG) {
1172            Log.d(TAG, "old notification: when=" + oldNotification.getNotification().when
1173                    + " ongoing=" + oldNotification.isOngoing()
1174                    + " expanded=" + oldEntry.expanded
1175                    + " contentView=" + oldContentView
1176                    + " bigContentView=" + oldBigContentView
1177                    + " publicView=" + oldPublicContentView
1178                    + " rowParent=" + oldEntry.row.getParent());
1179            Log.d(TAG, "new notification: when=" + notification.getNotification().when
1180                    + " ongoing=" + oldNotification.isOngoing()
1181                    + " contentView=" + contentView
1182                    + " bigContentView=" + bigContentView
1183                    + " publicView=" + publicContentView);
1184        }
1185
1186        // Can we just reapply the RemoteViews in place?  If when didn't change, the order
1187        // didn't change.
1188
1189        // 1U is never null
1190        boolean contentsUnchanged = oldEntry.expanded != null
1191                && contentView.getPackage() != null
1192                && oldContentView.getPackage() != null
1193                && oldContentView.getPackage().equals(contentView.getPackage())
1194                && oldContentView.getLayoutId() == contentView.getLayoutId();
1195        // large view may be null
1196        boolean bigContentsUnchanged =
1197                (oldEntry.getBigContentView() == null && bigContentView == null)
1198                || ((oldEntry.getBigContentView() != null && bigContentView != null)
1199                    && bigContentView.getPackage() != null
1200                    && oldBigContentView.getPackage() != null
1201                    && oldBigContentView.getPackage().equals(bigContentView.getPackage())
1202                    && oldBigContentView.getLayoutId() == bigContentView.getLayoutId());
1203        boolean headsUpContentsUnchanged =
1204                (oldHeadsUpContentView == null && headsUpContentView == null)
1205                || ((oldHeadsUpContentView != null && headsUpContentView != null)
1206                    && headsUpContentView.getPackage() != null
1207                    && oldHeadsUpContentView.getPackage() != null
1208                    && oldHeadsUpContentView.getPackage().equals(headsUpContentView.getPackage())
1209                    && oldHeadsUpContentView.getLayoutId() == headsUpContentView.getLayoutId());
1210        boolean publicUnchanged  =
1211                (oldPublicContentView == null && publicContentView == null)
1212                || ((oldPublicContentView != null && publicContentView != null)
1213                        && publicContentView.getPackage() != null
1214                        && oldPublicContentView.getPackage() != null
1215                        && oldPublicContentView.getPackage().equals(publicContentView.getPackage())
1216                        && oldPublicContentView.getLayoutId() == publicContentView.getLayoutId());
1217
1218        ViewGroup rowParent = (ViewGroup) oldEntry.row.getParent();
1219        boolean orderUnchanged =
1220                   notification.getNotification().when == oldNotification.getNotification().when
1221                && notification.getScore() == oldNotification.getScore();
1222                // score now encompasses/supersedes isOngoing()
1223
1224        boolean updateTicker = notification.getNotification().tickerText != null
1225                && !TextUtils.equals(notification.getNotification().tickerText,
1226                        oldEntry.notification.getNotification().tickerText);
1227        boolean isTopAnyway = isTopNotification(rowParent, oldEntry);
1228        if (contentsUnchanged && bigContentsUnchanged && headsUpContentsUnchanged && publicUnchanged
1229                && (orderUnchanged || isTopAnyway)) {
1230            if (DEBUG) Log.d(TAG, "reusing notification for key: " + key);
1231            oldEntry.notification = notification;
1232            try {
1233                updateNotificationViews(oldEntry, notification);
1234
1235                if (ENABLE_HEADS_UP && mInterruptingNotificationEntry != null
1236                        && oldNotification == mInterruptingNotificationEntry.notification) {
1237                    if (!shouldInterrupt(notification)) {
1238                        if (DEBUG) Log.d(TAG, "no longer interrupts!");
1239                        mHandler.sendEmptyMessage(MSG_HIDE_HEADS_UP);
1240                    } else {
1241                        if (DEBUG) Log.d(TAG, "updating the current heads up:" + notification);
1242                        mInterruptingNotificationEntry.notification = notification;
1243                        updateHeadsUpViews(mInterruptingNotificationEntry, notification);
1244                    }
1245                }
1246
1247                // Update the icon.
1248                final StatusBarIcon ic = new StatusBarIcon(notification.getPackageName(),
1249                        notification.getUser(),
1250                        notification.getNotification().icon, notification.getNotification().iconLevel,
1251                        notification.getNotification().number,
1252                        notification.getNotification().tickerText);
1253                if (!oldEntry.icon.set(ic)) {
1254                    handleNotificationError(key, notification, "Couldn't update icon: " + ic);
1255                    return;
1256                }
1257                updateRowStates();
1258            }
1259            catch (RuntimeException e) {
1260                // It failed to add cleanly.  Log, and remove the view from the panel.
1261                Log.w(TAG, "Couldn't reapply views for package " + contentView.getPackage(), e);
1262                removeNotificationViews(key);
1263                addNotificationViews(key, notification);
1264            }
1265        } else {
1266            if (DEBUG) Log.d(TAG, "not reusing notification for key: " + key);
1267            if (DEBUG) Log.d(TAG, "contents was " + (contentsUnchanged ? "unchanged" : "changed"));
1268            if (DEBUG) Log.d(TAG, "order was " + (orderUnchanged ? "unchanged" : "changed"));
1269            if (DEBUG) Log.d(TAG, "notification is " + (isTopAnyway ? "top" : "not top"));
1270            removeNotificationViews(key);
1271            addNotificationViews(key, notification);  // will also replace the heads up
1272            final NotificationData.Entry newEntry = mNotificationData.findByKey(key);
1273            final boolean userChangedExpansion = oldEntry.row.hasUserChangedExpansion();
1274            if (userChangedExpansion) {
1275                boolean userExpanded = oldEntry.row.isUserExpanded();
1276                newEntry.row.setUserExpanded(userExpanded);
1277                newEntry.row.notifyHeightChanged();
1278            }
1279        }
1280
1281        // Update the veto button accordingly (and as a result, whether this row is
1282        // swipe-dismissable)
1283        updateNotificationVetoButton(oldEntry.row, notification);
1284
1285        // Is this for you?
1286        boolean isForCurrentUser = notificationIsForCurrentProfiles(notification);
1287        if (DEBUG) Log.d(TAG, "notification is " + (isForCurrentUser ? "" : "not ") + "for you");
1288
1289        // Restart the ticker if it's still running
1290        if (updateTicker && isForCurrentUser) {
1291            haltTicker();
1292            tick(key, notification, false);
1293        }
1294
1295        // Recalculate the position of the sliding windows and the titles.
1296        setAreThereNotifications();
1297        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
1298    }
1299
1300    private void updateNotificationViews(NotificationData.Entry entry,
1301            StatusBarNotification notification) {
1302        updateNotificationViews(entry, notification, false);
1303    }
1304
1305    private void updateHeadsUpViews(NotificationData.Entry entry,
1306            StatusBarNotification notification) {
1307        updateNotificationViews(entry, notification, true);
1308    }
1309
1310    private void updateNotificationViews(NotificationData.Entry entry,
1311            StatusBarNotification notification, boolean isHeadsUp) {
1312        final RemoteViews contentView = notification.getNotification().contentView;
1313        final RemoteViews bigContentView = isHeadsUp
1314                ? notification.getNotification().headsUpContentView
1315                : notification.getNotification().bigContentView;
1316        final Notification publicVersion = notification.getNotification().publicVersion;
1317        final RemoteViews publicContentView = publicVersion != null ? publicVersion.contentView
1318                : null;
1319
1320        // Reapply the RemoteViews
1321        contentView.reapply(mContext, entry.expanded, mOnClickHandler);
1322        if (bigContentView != null && entry.getBigContentView() != null) {
1323            bigContentView.reapply(mContext, entry.getBigContentView(),
1324                    mOnClickHandler);
1325        }
1326        if (publicContentView != null && entry.getPublicContentView() != null) {
1327            publicContentView.reapply(mContext, entry.getPublicContentView(), mOnClickHandler);
1328        }
1329        // update the contentIntent
1330        final PendingIntent contentIntent = notification.getNotification().contentIntent;
1331        if (contentIntent != null) {
1332            final View.OnClickListener listener = makeClicker(contentIntent, notification.getKey(),
1333                    isHeadsUp);
1334            entry.row.setOnClickListener(listener);
1335        } else {
1336            entry.row.setOnClickListener(null);
1337        }
1338        entry.row.notifyContentUpdated();
1339    }
1340
1341    protected void notifyHeadsUpScreenOn(boolean screenOn) {
1342        if (!screenOn && mInterruptingNotificationEntry != null) {
1343            mHandler.sendEmptyMessage(MSG_ESCALATE_HEADS_UP);
1344        }
1345    }
1346
1347    protected boolean shouldInterrupt(StatusBarNotification sbn) {
1348        Notification notification = sbn.getNotification();
1349        // some predicates to make the boolean logic legible
1350        boolean isNoisy = (notification.defaults & Notification.DEFAULT_SOUND) != 0
1351                || (notification.defaults & Notification.DEFAULT_VIBRATE) != 0
1352                || notification.sound != null
1353                || notification.vibrate != null;
1354        boolean isHighPriority = sbn.getScore() >= INTERRUPTION_THRESHOLD;
1355        boolean isFullscreen = notification.fullScreenIntent != null;
1356        boolean hasTicker = mHeadsUpTicker && !TextUtils.isEmpty(notification.tickerText);
1357        boolean isAllowed = notification.extras.getInt(Notification.EXTRA_AS_HEADS_UP,
1358                Notification.HEADS_UP_ALLOWED) != Notification.HEADS_UP_NEVER;
1359
1360        final KeyguardTouchDelegate keyguard = KeyguardTouchDelegate.getInstance(mContext);
1361        boolean interrupt = (isFullscreen || (isHighPriority && (isNoisy || hasTicker)))
1362                && isAllowed
1363                && mPowerManager.isScreenOn()
1364                && !keyguard.isShowingAndNotOccluded()
1365                && !keyguard.isInputRestricted();
1366        try {
1367            interrupt = interrupt && !mDreamManager.isDreaming();
1368        } catch (RemoteException e) {
1369            Log.d(TAG, "failed to query dream manager", e);
1370        }
1371        if (DEBUG) Log.d(TAG, "interrupt: " + interrupt);
1372        return interrupt;
1373    }
1374
1375    // Q: What kinds of notifications should show during setup?
1376    // A: Almost none! Only things coming from the system (package is "android") that also
1377    // have special "kind" tags marking them as relevant for setup (see below).
1378    protected boolean showNotificationEvenIfUnprovisioned(StatusBarNotification sbn) {
1379        return "android".equals(sbn.getPackageName())
1380                && sbn.getNotification().extras.getBoolean(Notification.EXTRA_ALLOW_DURING_SETUP);
1381    }
1382
1383    public boolean inKeyguardRestrictedInputMode() {
1384        return KeyguardTouchDelegate.getInstance(mContext).isInputRestricted();
1385    }
1386
1387    public void setInteracting(int barWindow, boolean interacting) {
1388        // hook for subclasses
1389    }
1390
1391    public void setBouncerShowing(boolean bouncerShowing) {
1392        mBouncerShowing = bouncerShowing;
1393    }
1394
1395    /**
1396     * @return Whether the security bouncer from Keyguard is showing.
1397     */
1398    public boolean isBouncerShowing() {
1399        return mBouncerShowing;
1400    }
1401
1402    public void destroy() {
1403        if (mSearchPanelView != null) {
1404            mWindowManager.removeViewImmediate(mSearchPanelView);
1405        }
1406        mContext.unregisterReceiver(mBroadcastReceiver);
1407    }
1408}
1409