OSDN Git Service

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