BaseStatusBar.java revision cb2522c86d75fff277dc38ec7e444a5b5f5130ea
1
2/*
3 * Copyright (C) 2010 The Android Open Source Project
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *      http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package com.android.systemui.statusbar;
19
20import com.android.internal.statusbar.IStatusBarService;
21import com.android.internal.statusbar.StatusBarIcon;
22import com.android.internal.statusbar.StatusBarIconList;
23import com.android.internal.statusbar.StatusBarNotification;
24import com.android.internal.widget.SizeAdaptiveLayout;
25import com.android.systemui.R;
26import com.android.systemui.SearchPanelView;
27import com.android.systemui.SystemUI;
28import com.android.systemui.SystemUIApplication;
29import com.android.systemui.recent.RecentTasksLoader;
30import com.android.systemui.recent.RecentsActivity;
31import com.android.systemui.recent.TaskDescription;
32import com.android.systemui.statusbar.policy.NotificationRowLayout;
33import com.android.systemui.statusbar.tablet.StatusBarPanel;
34
35import android.app.ActivityManagerNative;
36import android.app.ActivityOptions;
37import android.app.KeyguardManager;
38import android.app.PendingIntent;
39import android.app.Service;
40import android.app.TaskStackBuilder;
41import android.content.ActivityNotFoundException;
42import android.content.BroadcastReceiver;
43import android.content.Context;
44import android.content.Intent;
45import android.content.IntentFilter;
46import android.content.pm.ApplicationInfo;
47import android.content.pm.PackageManager.NameNotFoundException;
48import android.content.res.Configuration;
49import android.content.res.Resources;
50import android.database.ContentObserver;
51import android.graphics.Bitmap;
52import android.graphics.Paint;
53import android.graphics.Rect;
54import android.net.Uri;
55import android.os.Build;
56import android.os.Handler;
57import android.os.IBinder;
58import android.os.Message;
59import android.os.RemoteException;
60import android.os.ServiceManager;
61import android.os.UserHandle;
62import android.provider.Settings;
63import android.text.TextUtils;
64import android.util.DisplayMetrics;
65import android.util.Log;
66import android.util.Slog;
67import android.view.Display;
68import android.view.IWindowManager;
69import android.view.LayoutInflater;
70import android.view.MenuItem;
71import android.view.MotionEvent;
72import android.view.View;
73import android.view.ViewGroup;
74import android.view.WindowManagerGlobal;
75import android.view.ViewGroup.LayoutParams;
76import android.view.WindowManager;
77import android.widget.ImageView;
78import android.widget.LinearLayout;
79import android.widget.PopupMenu;
80import android.widget.RemoteViews;
81import android.widget.TextView;
82
83import java.util.ArrayList;
84
85public abstract class BaseStatusBar extends SystemUI implements
86        CommandQueue.Callbacks {
87    static final String TAG = "StatusBar";
88    private 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_INTRUDER = 1026;
98    protected static final int MSG_HIDE_INTRUDER = 1027;
99
100    protected static final boolean ENABLE_INTRUDERS = false;
101
102    // Should match the value in PhoneWindowManager
103    public static final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
104
105    public static final int EXPANDED_LEAVE_ALONE = -10000;
106    public static final int EXPANDED_FULL_OPEN = -10001;
107
108    protected CommandQueue mCommandQueue;
109    protected IStatusBarService mBarService;
110    protected H mHandler = createHandler();
111
112    // all notifications
113    protected NotificationData mNotificationData = new NotificationData();
114    protected NotificationRowLayout mPile;
115
116    protected StatusBarNotification mCurrentlyIntrudingNotification;
117
118    // used to notify status bar for suppressing notification LED
119    protected boolean mPanelSlightlyVisible;
120
121    // Search panel
122    protected SearchPanelView mSearchPanelView;
123
124    protected PopupMenu mNotificationBlamePopup;
125
126    protected int mCurrentUserId = 0;
127
128    // UI-specific methods
129
130    /**
131     * Create all windows necessary for the status bar (including navigation, overlay panels, etc)
132     * and add them to the window manager.
133     */
134    protected abstract void createAndAddWindows();
135
136    protected WindowManager mWindowManager;
137    protected IWindowManager mWindowManagerService;
138    protected Display mDisplay;
139
140    private boolean mDeviceProvisioned = false;
141
142    public IStatusBarService getStatusBarService() {
143        return mBarService;
144    }
145
146    protected boolean isDeviceProvisioned() {
147        return mDeviceProvisioned;
148    }
149
150    private ContentObserver mProvisioningObserver = new ContentObserver(new Handler()) {
151        @Override
152        public void onChange(boolean selfChange) {
153            final boolean provisioned = 0 != Settings.Secure.getInt(
154                    mContext.getContentResolver(), Settings.Secure.DEVICE_PROVISIONED, 0);
155            if (provisioned != mDeviceProvisioned) {
156                mDeviceProvisioned = provisioned;
157                updateNotificationIcons();
158            }
159        }
160    };
161
162    private RemoteViews.OnClickHandler mOnClickHandler = new RemoteViews.OnClickHandler() {
163        @Override
164        public boolean onClickHandler(View view, PendingIntent pendingIntent, Intent fillInIntent) {
165            final boolean isActivity = pendingIntent.isActivity();
166            if (isActivity) {
167                try {
168                    // The intent we are sending is for the application, which
169                    // won't have permission to immediately start an activity after
170                    // the user switches to home.  We know it is safe to do at this
171                    // point, so make sure new activity switches are now allowed.
172                    ActivityManagerNative.getDefault().resumeAppSwitches();
173                    // Also, notifications can be launched from the lock screen,
174                    // so dismiss the lock screen when the activity starts.
175                    ActivityManagerNative.getDefault().dismissKeyguardOnNextActivity();
176                } catch (RemoteException e) {
177                }
178            }
179
180            boolean handled = super.onClickHandler(view, pendingIntent, fillInIntent);
181
182            if (isActivity && handled) {
183                // close the shade if it was open
184                animateCollapse(CommandQueue.FLAG_EXCLUDE_NONE);
185                visibilityChanged(false);
186            }
187            return handled;
188        }
189    };
190
191    public void start() {
192        mWindowManager = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
193        mWindowManagerService = WindowManagerGlobal.getWindowManagerService();
194        mDisplay = mWindowManager.getDefaultDisplay();
195
196        mProvisioningObserver.onChange(false); // set up
197        mContext.getContentResolver().registerContentObserver(
198                Settings.Secure.getUriFor(Settings.Secure.DEVICE_PROVISIONED), true,
199                mProvisioningObserver);
200
201        mBarService = IStatusBarService.Stub.asInterface(
202                ServiceManager.getService(Context.STATUS_BAR_SERVICE));
203
204        // Connect in to the status bar manager service
205        StatusBarIconList iconList = new StatusBarIconList();
206        ArrayList<IBinder> notificationKeys = new ArrayList<IBinder>();
207        ArrayList<StatusBarNotification> notifications = new ArrayList<StatusBarNotification>();
208        mCommandQueue = new CommandQueue(this, iconList);
209
210        int[] switches = new int[7];
211        ArrayList<IBinder> binders = new ArrayList<IBinder>();
212        try {
213            mBarService.registerStatusBar(mCommandQueue, iconList, notificationKeys, notifications,
214                    switches, binders);
215        } catch (RemoteException ex) {
216            // If the system process isn't there we're doomed anyway.
217        }
218
219        createAndAddWindows();
220
221        disable(switches[0]);
222        setSystemUiVisibility(switches[1], 0xffffffff);
223        topAppWindowChanged(switches[2] != 0);
224        // StatusBarManagerService has a back up of IME token and it's restored here.
225        setImeWindowStatus(binders.get(0), switches[3], switches[4]);
226        setHardKeyboardStatus(switches[5] != 0, switches[6] != 0);
227
228        // Set up the initial icon state
229        int N = iconList.size();
230        int viewIndex = 0;
231        for (int i=0; i<N; i++) {
232            StatusBarIcon icon = iconList.getIcon(i);
233            if (icon != null) {
234                addIcon(iconList.getSlot(i), i, viewIndex, icon);
235                viewIndex++;
236            }
237        }
238
239        // Set up the initial notification state
240        N = notificationKeys.size();
241        if (N == notifications.size()) {
242            for (int i=0; i<N; i++) {
243                addNotification(notificationKeys.get(i), notifications.get(i));
244            }
245        } else {
246            Log.wtf(TAG, "Notification list length mismatch: keys=" + N
247                    + " notifications=" + notifications.size());
248        }
249
250        if (DEBUG) {
251            Slog.d(TAG, String.format(
252                    "init: icons=%d disabled=0x%08x lights=0x%08x menu=0x%08x imeButton=0x%08x",
253                   iconList.size(),
254                   switches[0],
255                   switches[1],
256                   switches[2],
257                   switches[3]
258                   ));
259        }
260
261        // XXX: this is currently broken and will always return 0, but should start working at some point
262        try {
263            mCurrentUserId = ActivityManagerNative.getDefault().getCurrentUser().id;
264        } catch (RemoteException e) {
265            Log.v(TAG, "Couldn't get current user ID; guessing it's 0", e);
266        }
267
268        IntentFilter filter = new IntentFilter();
269        filter.addAction(Intent.ACTION_USER_SWITCHED);
270        mContext.registerReceiver(new BroadcastReceiver() {
271            @Override
272            public void onReceive(Context context, Intent intent) {
273                String action = intent.getAction();
274                if (Intent.ACTION_USER_SWITCHED.equals(action)) {
275                    mCurrentUserId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
276                    if (true) Slog.v(TAG, "userId " + mCurrentUserId + " is in the house");
277                    userSwitched(mCurrentUserId);
278                }
279            }}, filter);
280    }
281
282    public void userSwitched(int newUserId) {
283        // should be overridden
284    }
285
286    public boolean notificationIsForCurrentUser(StatusBarNotification n) {
287        final int thisUserId = mCurrentUserId;
288        final int notificationUserId = n.getUserId();
289        if (DEBUG && MULTIUSER_DEBUG) {
290            Slog.v(TAG, String.format("%s: current userid: %d, notification userid: %d",
291                    n, thisUserId, notificationUserId));
292        }
293        return thisUserId == notificationUserId;
294    }
295
296    protected View updateNotificationVetoButton(View row, StatusBarNotification n) {
297        View vetoButton = row.findViewById(R.id.veto);
298        if (n.isClearable()) {
299            final String _pkg = n.pkg;
300            final String _tag = n.tag;
301            final int _id = n.id;
302            vetoButton.setOnClickListener(new View.OnClickListener() {
303                    public void onClick(View v) {
304                        try {
305                            mBarService.onNotificationClear(_pkg, _tag, _id);
306                        } catch (RemoteException ex) {
307                            // system process is dead if we're here.
308                        }
309                    }
310                });
311            vetoButton.setVisibility(View.VISIBLE);
312        } else {
313            vetoButton.setVisibility(View.GONE);
314        }
315        return vetoButton;
316    }
317
318
319    protected void applyLegacyRowBackground(StatusBarNotification sbn, View content) {
320        if (sbn.notification.contentView.getLayoutId() !=
321                com.android.internal.R.layout.notification_template_base) {
322            int version = 0;
323            try {
324                ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(sbn.pkg, 0);
325                version = info.targetSdkVersion;
326            } catch (NameNotFoundException ex) {
327                Slog.e(TAG, "Failed looking up ApplicationInfo for " + sbn.pkg, ex);
328            }
329            if (version > 0 && version < Build.VERSION_CODES.GINGERBREAD) {
330                content.setBackgroundResource(R.drawable.notification_row_legacy_bg);
331            } else {
332                content.setBackgroundResource(com.android.internal.R.drawable.notification_bg);
333            }
334        }
335    }
336
337    private void startApplicationDetailsActivity(String packageName) {
338        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
339                Uri.fromParts("package", packageName, null));
340        intent.setComponent(intent.resolveActivity(mContext.getPackageManager()));
341        TaskStackBuilder.create(mContext).addNextIntentWithParentStack(intent).startActivities();
342    }
343
344    protected View.OnLongClickListener getNotificationLongClicker() {
345        return new View.OnLongClickListener() {
346            @Override
347            public boolean onLongClick(View v) {
348                final String packageNameF = (String) v.getTag();
349                if (packageNameF == null) return false;
350                if (v.getWindowToken() == null) return false;
351                mNotificationBlamePopup = new PopupMenu(mContext, v);
352                mNotificationBlamePopup.getMenuInflater().inflate(
353                        R.menu.notification_popup_menu,
354                        mNotificationBlamePopup.getMenu());
355                mNotificationBlamePopup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
356                    public boolean onMenuItemClick(MenuItem item) {
357                        if (item.getItemId() == R.id.notification_inspect_item) {
358                            startApplicationDetailsActivity(packageNameF);
359                            animateCollapse(CommandQueue.FLAG_EXCLUDE_NONE);
360                        } else {
361                            return false;
362                        }
363                        return true;
364                    }
365                });
366                mNotificationBlamePopup.show();
367
368                return true;
369            }
370        };
371    }
372
373    public void dismissPopups() {
374        if (mNotificationBlamePopup != null) {
375            mNotificationBlamePopup.dismiss();
376            mNotificationBlamePopup = null;
377        }
378    }
379
380    public void dismissIntruder() {
381        // pass
382    }
383
384    @Override
385    public void toggleRecentApps() {
386        int msg = MSG_TOGGLE_RECENTS_PANEL;
387        mHandler.removeMessages(msg);
388        mHandler.sendEmptyMessage(msg);
389    }
390
391    @Override
392    public void preloadRecentApps() {
393        int msg = MSG_PRELOAD_RECENT_APPS;
394        mHandler.removeMessages(msg);
395        mHandler.sendEmptyMessage(msg);
396    }
397
398    @Override
399    public void cancelPreloadRecentApps() {
400        int msg = MSG_CANCEL_PRELOAD_RECENT_APPS;
401        mHandler.removeMessages(msg);
402        mHandler.sendEmptyMessage(msg);
403    }
404
405    @Override
406    public void showSearchPanel() {
407        int msg = MSG_OPEN_SEARCH_PANEL;
408        mHandler.removeMessages(msg);
409        mHandler.sendEmptyMessage(msg);
410    }
411
412    @Override
413    public void hideSearchPanel() {
414        int msg = MSG_CLOSE_SEARCH_PANEL;
415        mHandler.removeMessages(msg);
416        mHandler.sendEmptyMessage(msg);
417    }
418
419    protected abstract WindowManager.LayoutParams getRecentsLayoutParams(
420            LayoutParams layoutParams);
421
422    protected abstract WindowManager.LayoutParams getSearchLayoutParams(
423            LayoutParams layoutParams);
424
425    protected RecentTasksLoader getRecentTasksLoader() {
426        final SystemUIApplication app = (SystemUIApplication) ((Service) mContext).getApplication();
427        return app.getRecentTasksLoader();
428    }
429
430    protected void updateSearchPanel() {
431        // Search Panel
432        boolean visible = false;
433        if (mSearchPanelView != null) {
434            visible = mSearchPanelView.isShowing();
435            mWindowManager.removeView(mSearchPanelView);
436        }
437
438        // Provide SearchPanel with a temporary parent to allow layout params to work.
439        LinearLayout tmpRoot = new LinearLayout(mContext);
440        mSearchPanelView = (SearchPanelView) LayoutInflater.from(mContext).inflate(
441                 R.layout.status_bar_search_panel, tmpRoot, false);
442        mSearchPanelView.setOnTouchListener(
443                 new TouchOutsideListener(MSG_CLOSE_SEARCH_PANEL, mSearchPanelView));
444        mSearchPanelView.setVisibility(View.GONE);
445
446        WindowManager.LayoutParams lp = getSearchLayoutParams(mSearchPanelView.getLayoutParams());
447
448        mWindowManager.addView(mSearchPanelView, lp);
449        mSearchPanelView.setBar(this);
450        if (visible) {
451            mSearchPanelView.show(true, false);
452        }
453    }
454
455    protected H createHandler() {
456         return new H();
457    }
458
459    static void sendCloseSystemWindows(Context context, String reason) {
460        if (ActivityManagerNative.isSystemReady()) {
461            try {
462                ActivityManagerNative.getDefault().closeSystemDialogs(reason);
463            } catch (RemoteException e) {
464            }
465        }
466    }
467
468    protected abstract View getStatusBarView();
469
470    protected void toggleRecentsActivity() {
471        try {
472            final RecentTasksLoader recentTasksLoader = getRecentTasksLoader();
473            TaskDescription firstTask = recentTasksLoader.getFirstTask();
474
475            Intent intent = new Intent(RecentsActivity.TOGGLE_RECENTS_INTENT);
476            intent.setClassName("com.android.systemui",
477                    "com.android.systemui.recent.RecentsActivity");
478            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
479                    | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
480
481            if (firstTask == null) {
482                mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
483            } else {
484                Bitmap first = firstTask.getThumbnail();
485                final Resources res = mContext.getResources();
486
487                float thumbWidth = res
488                        .getDimensionPixelSize(R.dimen.status_bar_recents_thumbnail_width);
489                float thumbHeight = res
490                        .getDimensionPixelSize(R.dimen.status_bar_recents_thumbnail_height);
491                if (first.getWidth() != thumbWidth || first.getHeight() != thumbHeight) {
492                    first = Bitmap.createScaledBitmap(first, (int) thumbWidth, (int) thumbHeight,
493                            true);
494                }
495
496                DisplayMetrics dm = new DisplayMetrics();
497                mDisplay.getMetrics(dm);
498                // calculate it here, but consider moving it elsewhere
499                // first, determine which orientation you're in.
500                // todo: move the system_bar layouts to sw600dp ?
501                final Configuration config = res.getConfiguration();
502                int x, y;
503
504                if (config.orientation == Configuration.ORIENTATION_PORTRAIT) {
505                    float appLabelLeftMargin = res
506                            .getDimensionPixelSize(R.dimen.status_bar_recents_app_label_left_margin);
507                    float appLabelWidth = res
508                            .getDimensionPixelSize(R.dimen.status_bar_recents_app_label_width);
509                    float thumbLeftMargin = res
510                            .getDimensionPixelSize(R.dimen.status_bar_recents_thumbnail_left_margin);
511                    float thumbBgPadding = res
512                            .getDimensionPixelSize(R.dimen.status_bar_recents_thumbnail_bg_padding);
513
514                    float width = appLabelLeftMargin +
515                            +appLabelWidth
516                            + thumbLeftMargin
517                            + thumbWidth
518                            + 2 * thumbBgPadding;
519
520                    x = (int) ((dm.widthPixels - width) / 2f + appLabelLeftMargin + appLabelWidth
521                            + thumbBgPadding + thumbLeftMargin);
522                    y = (int) (dm.heightPixels
523                            - res.getDimensionPixelSize(R.dimen.status_bar_recents_thumbnail_height) - thumbBgPadding);
524                } else { // if (config.orientation ==
525                         // Configuration.ORIENTATION_LANDSCAPE) {
526                    float thumbTopMargin = res
527                            .getDimensionPixelSize(R.dimen.status_bar_recents_thumbnail_top_margin);
528                    float thumbBgPadding = res
529                            .getDimensionPixelSize(R.dimen.status_bar_recents_thumbnail_bg_padding);
530                    float textPadding = res
531                            .getDimensionPixelSize(R.dimen.status_bar_recents_text_description_padding);
532                    float labelTextSize = res
533                            .getDimensionPixelSize(R.dimen.status_bar_recents_app_label_text_size);
534                    Paint p = new Paint();
535                    p.setTextSize(labelTextSize);
536                    float labelTextHeight = p.getFontMetricsInt().bottom
537                            - p.getFontMetricsInt().top;
538                    float descriptionTextSize = res
539                            .getDimensionPixelSize(R.dimen.status_bar_recents_app_description_text_size);
540                    p.setTextSize(labelTextSize);
541                    float descriptionTextHeight = p.getFontMetricsInt().bottom
542                            - p.getFontMetricsInt().top;
543
544                    float statusBarHeight = res
545                            .getDimensionPixelSize(com.android.internal.R.dimen.status_bar_height);
546                    float recentsItemTopPadding = statusBarHeight;
547
548                    float height = thumbTopMargin
549                            + thumbHeight
550                            + 2 * thumbBgPadding + textPadding + labelTextHeight
551                            + recentsItemTopPadding + textPadding + descriptionTextHeight;
552                    float recentsItemRightPadding = res
553                            .getDimensionPixelSize(R.dimen.status_bar_recents_item_padding);
554                    float recentsScrollViewRightPadding = res
555                            .getDimensionPixelSize(R.dimen.status_bar_recents_right_glow_margin);
556                    x = (int) (dm.widthPixels - res
557                            .getDimensionPixelSize(R.dimen.status_bar_recents_thumbnail_width)
558                            - thumbBgPadding - recentsItemRightPadding - recentsScrollViewRightPadding);
559                    y = (int) ((dm.heightPixels - statusBarHeight - height) / 2f + thumbTopMargin
560                            + recentsItemTopPadding + thumbBgPadding + statusBarHeight);
561                }
562
563                ActivityOptions opts = ActivityOptions.makeThumbnailScaleDownAnimation(
564                        getStatusBarView(),
565                        first, x, y,
566                        null);
567                mContext.startActivityAsUser(intent, opts.toBundle(), new UserHandle(
568                        UserHandle.USER_CURRENT));
569            }
570            return;
571        } catch (ActivityNotFoundException e) {
572            Log.e(TAG, "Failed to launch RecentAppsIntent", e);
573        }
574    }
575
576    protected class H extends Handler {
577        public void handleMessage(Message m) {
578            switch (m.what) {
579             case MSG_TOGGLE_RECENTS_PANEL:
580                 if (DEBUG) Slog.d(TAG, "toggle recents panel");
581                 toggleRecentsActivity();
582                 break;
583             case MSG_CLOSE_RECENTS_PANEL:
584                 if (DEBUG) Slog.d(TAG, "closing recents panel");
585                 Intent intent = new Intent(RecentsActivity.CLOSE_RECENTS_INTENT);
586                 intent.setPackage("com.android.systemui");
587                 mContext.sendBroadcastAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
588                 break;
589             case MSG_PRELOAD_RECENT_APPS:
590                  if (DEBUG) Slog.d(TAG, "preloading recents");
591                  {
592                      // TODO:
593                      // need to implement this
594                      //final RecentsPanelView recentsPanel = getRecentsPanel();
595                      //if (recentsPanel != null) {
596                      //recentsPanel.preloadRecentTasksList();
597                      //}
598                  }
599                  break;
600             case MSG_CANCEL_PRELOAD_RECENT_APPS:
601                  if (DEBUG) Slog.d(TAG, "cancel preloading recents");
602                  {
603                      // TODO:
604                      // need to implement this
605                      //final RecentsPanelView recentsPanel = getRecentsPanel();
606                      //if (recentsPanel != null) {
607                      //recentsPanel.clearRecentTasksList();
608                      //}
609                  }
610                  break;
611             case MSG_OPEN_SEARCH_PANEL:
612                 if (DEBUG) Slog.d(TAG, "opening search panel");
613                 if (mSearchPanelView != null && mSearchPanelView.isAssistantAvailable()) {
614                     mSearchPanelView.show(true, true);
615                 }
616                 break;
617             case MSG_CLOSE_SEARCH_PANEL:
618                 if (DEBUG) Slog.d(TAG, "closing search panel");
619                 if (mSearchPanelView != null && mSearchPanelView.isShowing()) {
620                     mSearchPanelView.show(false, true);
621                 }
622                 break;
623            }
624        }
625    }
626
627    public class TouchOutsideListener implements View.OnTouchListener {
628        private int mMsg;
629        private StatusBarPanel mPanel;
630
631        public TouchOutsideListener(int msg, StatusBarPanel panel) {
632            mMsg = msg;
633            mPanel = panel;
634        }
635
636        public boolean onTouch(View v, MotionEvent ev) {
637            final int action = ev.getAction();
638            if (action == MotionEvent.ACTION_OUTSIDE
639                || (action == MotionEvent.ACTION_DOWN
640                    && !mPanel.isInContentArea((int)ev.getX(), (int)ev.getY()))) {
641                mHandler.removeMessages(mMsg);
642                mHandler.sendEmptyMessage(mMsg);
643                return true;
644            }
645            return false;
646        }
647    }
648
649    protected void workAroundBadLayerDrawableOpacity(View v) {
650    }
651
652    protected  boolean inflateViews(NotificationData.Entry entry, ViewGroup parent) {
653        int minHeight =
654                mContext.getResources().getDimensionPixelSize(R.dimen.notification_min_height);
655        int maxHeight =
656                mContext.getResources().getDimensionPixelSize(R.dimen.notification_max_height);
657        StatusBarNotification sbn = entry.notification;
658        RemoteViews oneU = sbn.notification.contentView;
659        RemoteViews large = sbn.notification.bigContentView;
660        if (oneU == null) {
661            return false;
662        }
663
664        // create the row view
665        LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(
666                Context.LAYOUT_INFLATER_SERVICE);
667        View row = inflater.inflate(R.layout.status_bar_notification_row, parent, false);
668
669        // for blaming (see SwipeHelper.setLongPressListener)
670        row.setTag(sbn.pkg);
671
672        workAroundBadLayerDrawableOpacity(row);
673        View vetoButton = updateNotificationVetoButton(row, sbn);
674        vetoButton.setContentDescription(mContext.getString(
675                R.string.accessibility_remove_notification));
676
677        // NB: the large icon is now handled entirely by the template
678
679        // bind the click event to the content area
680        ViewGroup content = (ViewGroup)row.findViewById(R.id.content);
681        ViewGroup adaptive = (ViewGroup)row.findViewById(R.id.adaptive);
682
683        content.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
684
685        PendingIntent contentIntent = sbn.notification.contentIntent;
686        if (contentIntent != null) {
687            final View.OnClickListener listener = new NotificationClicker(contentIntent,
688                    sbn.pkg, sbn.tag, sbn.id);
689            content.setOnClickListener(listener);
690        } else {
691            content.setOnClickListener(null);
692        }
693
694        // TODO(cwren) normalize variable names with those in updateNotification
695        View expandedOneU = null;
696        View expandedLarge = null;
697        try {
698            expandedOneU = oneU.apply(mContext, adaptive, mOnClickHandler);
699            if (large != null) {
700                expandedLarge = large.apply(mContext, adaptive, mOnClickHandler);
701            }
702        }
703        catch (RuntimeException e) {
704            final String ident = sbn.pkg + "/0x" + Integer.toHexString(sbn.id);
705            Slog.e(TAG, "couldn't inflate view for notification " + ident, e);
706            return false;
707        }
708
709        if (expandedOneU != null) {
710            SizeAdaptiveLayout.LayoutParams params =
711                    new SizeAdaptiveLayout.LayoutParams(expandedOneU.getLayoutParams());
712            params.minHeight = minHeight;
713            params.maxHeight = minHeight;
714            adaptive.addView(expandedOneU, params);
715        }
716        if (expandedLarge != null) {
717            SizeAdaptiveLayout.LayoutParams params =
718                    new SizeAdaptiveLayout.LayoutParams(expandedLarge.getLayoutParams());
719            params.minHeight = minHeight+1;
720            params.maxHeight = maxHeight;
721            adaptive.addView(expandedLarge, params);
722        }
723        row.setDrawingCacheEnabled(true);
724
725        applyLegacyRowBackground(sbn, content);
726
727        row.setTag(R.id.expandable_tag, Boolean.valueOf(large != null));
728
729        if (MULTIUSER_DEBUG) {
730            TextView debug = (TextView) row.findViewById(R.id.debug_info);
731            if (debug != null) {
732                debug.setVisibility(View.VISIBLE);
733                debug.setText("U " + entry.notification.getUserId());
734            }
735        }
736        entry.row = row;
737        entry.content = content;
738        entry.expanded = expandedOneU;
739        entry.setLargeView(expandedLarge);
740
741        return true;
742    }
743
744    public NotificationClicker makeClicker(PendingIntent intent, String pkg, String tag, int id) {
745        return new NotificationClicker(intent, pkg, tag, id);
746    }
747
748    private class NotificationClicker implements View.OnClickListener {
749        private PendingIntent mIntent;
750        private String mPkg;
751        private String mTag;
752        private int mId;
753
754        NotificationClicker(PendingIntent intent, String pkg, String tag, int id) {
755            mIntent = intent;
756            mPkg = pkg;
757            mTag = tag;
758            mId = id;
759        }
760
761        public void onClick(View v) {
762            try {
763                // The intent we are sending is for the application, which
764                // won't have permission to immediately start an activity after
765                // the user switches to home.  We know it is safe to do at this
766                // point, so make sure new activity switches are now allowed.
767                ActivityManagerNative.getDefault().resumeAppSwitches();
768                // Also, notifications can be launched from the lock screen,
769                // so dismiss the lock screen when the activity starts.
770                ActivityManagerNative.getDefault().dismissKeyguardOnNextActivity();
771            } catch (RemoteException e) {
772            }
773
774            if (mIntent != null) {
775                int[] pos = new int[2];
776                v.getLocationOnScreen(pos);
777                Intent overlay = new Intent();
778                overlay.setSourceBounds(
779                        new Rect(pos[0], pos[1], pos[0]+v.getWidth(), pos[1]+v.getHeight()));
780                try {
781                    mIntent.send(mContext, 0, overlay);
782                } catch (PendingIntent.CanceledException e) {
783                    // the stack trace isn't very helpful here.  Just log the exception message.
784                    Slog.w(TAG, "Sending contentIntent failed: " + e);
785                }
786
787                KeyguardManager kgm =
788                    (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
789                if (kgm != null) kgm.exitKeyguardSecurely(null);
790            }
791
792            try {
793                mBarService.onNotificationClick(mPkg, mTag, mId);
794            } catch (RemoteException ex) {
795                // system process is dead if we're here.
796            }
797
798            // close the shade if it was open
799            animateCollapse(CommandQueue.FLAG_EXCLUDE_NONE);
800            visibilityChanged(false);
801
802            // If this click was on the intruder alert, hide that instead
803//            mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
804        }
805    }
806    /**
807     * The LEDs are turned o)ff when the notification panel is shown, even just a little bit.
808     * This was added last-minute and is inconsistent with the way the rest of the notifications
809     * are handled, because the notification isn't really cancelled.  The lights are just
810     * turned off.  If any other notifications happen, the lights will turn back on.  Steve says
811     * this is what he wants. (see bug 1131461)
812     */
813    protected void visibilityChanged(boolean visible) {
814        if (mPanelSlightlyVisible != visible) {
815            mPanelSlightlyVisible = visible;
816            try {
817                mBarService.onPanelRevealed();
818            } catch (RemoteException ex) {
819                // Won't fail unless the world has ended.
820            }
821        }
822    }
823
824    /**
825     * Cancel this notification and tell the StatusBarManagerService / NotificationManagerService
826     * about the failure.
827     *
828     * WARNING: this will call back into us.  Don't hold any locks.
829     */
830    void handleNotificationError(IBinder key, StatusBarNotification n, String message) {
831        removeNotification(key);
832        try {
833            mBarService.onNotificationError(n.pkg, n.tag, n.id, n.uid, n.initialPid, message);
834        } catch (RemoteException ex) {
835            // The end is nigh.
836        }
837    }
838
839    protected StatusBarNotification removeNotificationViews(IBinder key) {
840        NotificationData.Entry entry = mNotificationData.remove(key);
841        if (entry == null) {
842            Slog.w(TAG, "removeNotification for unknown key: " + key);
843            return null;
844        }
845        // Remove the expanded view.
846        ViewGroup rowParent = (ViewGroup)entry.row.getParent();
847        if (rowParent != null) rowParent.removeView(entry.row);
848        updateExpansionStates();
849        updateNotificationIcons();
850
851        return entry.notification;
852    }
853
854    protected StatusBarIconView addNotificationViews(IBinder key,
855            StatusBarNotification notification) {
856        if (DEBUG) {
857            Slog.d(TAG, "addNotificationViews(key=" + key + ", notification=" + notification);
858        }
859        // Construct the icon.
860        final StatusBarIconView iconView = new StatusBarIconView(mContext,
861                notification.pkg + "/0x" + Integer.toHexString(notification.id),
862                notification.notification);
863        iconView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
864
865        final StatusBarIcon ic = new StatusBarIcon(notification.pkg,
866                    notification.notification.icon,
867                    notification.notification.iconLevel,
868                    notification.notification.number,
869                    notification.notification.tickerText);
870        if (!iconView.set(ic)) {
871            handleNotificationError(key, notification, "Couldn't create icon: " + ic);
872            return null;
873        }
874        // Construct the expanded view.
875        NotificationData.Entry entry = new NotificationData.Entry(key, notification, iconView);
876        if (!inflateViews(entry, mPile)) {
877            handleNotificationError(key, notification, "Couldn't expand RemoteViews for: "
878                    + notification);
879            return null;
880        }
881
882        // Add the expanded view and icon.
883        int pos = mNotificationData.add(entry);
884        if (DEBUG) {
885            Slog.d(TAG, "addNotificationViews: added at " + pos);
886        }
887        updateExpansionStates();
888        updateNotificationIcons();
889
890        return iconView;
891    }
892
893    protected boolean expandView(NotificationData.Entry entry, boolean expand) {
894        int rowHeight =
895                mContext.getResources().getDimensionPixelSize(R.dimen.notification_row_min_height);
896        ViewGroup.LayoutParams lp = entry.row.getLayoutParams();
897        if (entry.expandable() && expand) {
898            if (DEBUG) Slog.d(TAG, "setting expanded row height to WRAP_CONTENT");
899            lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
900        } else {
901            if (DEBUG) Slog.d(TAG, "setting collapsed row height to " + rowHeight);
902            lp.height = rowHeight;
903        }
904        entry.row.setLayoutParams(lp);
905        return expand;
906    }
907
908    protected void updateExpansionStates() {
909        int N = mNotificationData.size();
910        for (int i = 0; i < N; i++) {
911            NotificationData.Entry entry = mNotificationData.get(i);
912            if (!entry.userLocked()) {
913                if (i == (N-1)) {
914                    if (DEBUG) Slog.d(TAG, "expanding top notification at " + i);
915                    expandView(entry, true);
916                } else {
917                    if (!entry.userExpanded()) {
918                        if (DEBUG) Slog.d(TAG, "collapsing notification at " + i);
919                        expandView(entry, false);
920                    } else {
921                        if (DEBUG) Slog.d(TAG, "ignoring user-modified notification at " + i);
922                    }
923                }
924            } else {
925                if (DEBUG) Slog.d(TAG, "ignoring notification being held by user at " + i);
926            }
927        }
928    }
929
930    protected abstract void haltTicker();
931    protected abstract void setAreThereNotifications();
932    protected abstract void updateNotificationIcons();
933    protected abstract void tick(IBinder key, StatusBarNotification n, boolean firstTime);
934    protected abstract void updateExpandedViewPos(int expandedPosition);
935    protected abstract int getExpandedViewMaxHeight();
936    protected abstract boolean shouldDisableNavbarGestures();
937
938    protected boolean isTopNotification(ViewGroup parent, NotificationData.Entry entry) {
939        return parent != null && parent.indexOfChild(entry.row) == 0;
940    }
941
942    public void updateNotification(IBinder key, StatusBarNotification notification) {
943        if (DEBUG) Slog.d(TAG, "updateNotification(" + key + " -> " + notification + ")");
944
945        final NotificationData.Entry oldEntry = mNotificationData.findByKey(key);
946        if (oldEntry == null) {
947            Slog.w(TAG, "updateNotification for unknown key: " + key);
948            return;
949        }
950
951        final StatusBarNotification oldNotification = oldEntry.notification;
952
953        // XXX: modify when we do something more intelligent with the two content views
954        final RemoteViews oldContentView = oldNotification.notification.contentView;
955        final RemoteViews contentView = notification.notification.contentView;
956        final RemoteViews oldBigContentView = oldNotification.notification.bigContentView;
957        final RemoteViews bigContentView = notification.notification.bigContentView;
958
959        if (DEBUG) {
960            Slog.d(TAG, "old notification: when=" + oldNotification.notification.when
961                    + " ongoing=" + oldNotification.isOngoing()
962                    + " expanded=" + oldEntry.expanded
963                    + " contentView=" + oldContentView
964                    + " bigContentView=" + oldBigContentView
965                    + " rowParent=" + oldEntry.row.getParent());
966            Slog.d(TAG, "new notification: when=" + notification.notification.when
967                    + " ongoing=" + oldNotification.isOngoing()
968                    + " contentView=" + contentView
969                    + " bigContentView=" + bigContentView);
970        }
971
972        // Can we just reapply the RemoteViews in place?  If when didn't change, the order
973        // didn't change.
974
975        // 1U is never null
976        boolean contentsUnchanged = oldEntry.expanded != null
977                && contentView.getPackage() != null
978                && oldContentView.getPackage() != null
979                && oldContentView.getPackage().equals(contentView.getPackage())
980                && oldContentView.getLayoutId() == contentView.getLayoutId();
981        // large view may be null
982        boolean bigContentsUnchanged =
983                (oldEntry.getLargeView() == null && bigContentView == null)
984                || ((oldEntry.getLargeView() != null && bigContentView != null)
985                    && bigContentView.getPackage() != null
986                    && oldBigContentView.getPackage() != null
987                    && oldBigContentView.getPackage().equals(bigContentView.getPackage())
988                    && oldBigContentView.getLayoutId() == bigContentView.getLayoutId());
989        ViewGroup rowParent = (ViewGroup) oldEntry.row.getParent();
990        boolean orderUnchanged = notification.notification.when==oldNotification.notification.when
991                && notification.score == oldNotification.score;
992                // score now encompasses/supersedes isOngoing()
993
994        boolean updateTicker = notification.notification.tickerText != null
995                && !TextUtils.equals(notification.notification.tickerText,
996                        oldEntry.notification.notification.tickerText);
997        boolean isTopAnyway = isTopNotification(rowParent, oldEntry);
998        if (contentsUnchanged && bigContentsUnchanged && (orderUnchanged || isTopAnyway)) {
999            if (DEBUG) Slog.d(TAG, "reusing notification for key: " + key);
1000            oldEntry.notification = notification;
1001            try {
1002                // Reapply the RemoteViews
1003                contentView.reapply(mContext, oldEntry.expanded, mOnClickHandler);
1004                if (bigContentView != null && oldEntry.getLargeView() != null) {
1005                    bigContentView.reapply(mContext, oldEntry.getLargeView(), mOnClickHandler);
1006                }
1007                // update the contentIntent
1008                final PendingIntent contentIntent = notification.notification.contentIntent;
1009                if (contentIntent != null) {
1010                    final View.OnClickListener listener = makeClicker(contentIntent,
1011                            notification.pkg, notification.tag, notification.id);
1012                    oldEntry.content.setOnClickListener(listener);
1013                } else {
1014                    oldEntry.content.setOnClickListener(null);
1015                }
1016                // Update the icon.
1017                final StatusBarIcon ic = new StatusBarIcon(notification.pkg,
1018                        notification.notification.icon, notification.notification.iconLevel,
1019                        notification.notification.number,
1020                        notification.notification.tickerText);
1021                if (!oldEntry.icon.set(ic)) {
1022                    handleNotificationError(key, notification, "Couldn't update icon: " + ic);
1023                    return;
1024                }
1025                updateExpansionStates();
1026            }
1027            catch (RuntimeException e) {
1028                // It failed to add cleanly.  Log, and remove the view from the panel.
1029                Slog.w(TAG, "Couldn't reapply views for package " + contentView.getPackage(), e);
1030                removeNotificationViews(key);
1031                addNotificationViews(key, notification);
1032            }
1033        } else {
1034            if (DEBUG) Slog.d(TAG, "not reusing notification for key: " + key);
1035            if (DEBUG) Slog.d(TAG, "contents was " + (contentsUnchanged ? "unchanged" : "changed"));
1036            if (DEBUG) Slog.d(TAG, "order was " + (orderUnchanged ? "unchanged" : "changed"));
1037            if (DEBUG) Slog.d(TAG, "notification is " + (isTopAnyway ? "top" : "not top"));
1038            final boolean wasExpanded = oldEntry.userExpanded();
1039            removeNotificationViews(key);
1040            addNotificationViews(key, notification);
1041            if (wasExpanded) {
1042                final NotificationData.Entry newEntry = mNotificationData.findByKey(key);
1043                expandView(newEntry, true);
1044                newEntry.setUserExpanded(true);
1045            }
1046        }
1047
1048        // Update the veto button accordingly (and as a result, whether this row is
1049        // swipe-dismissable)
1050        updateNotificationVetoButton(oldEntry.row, notification);
1051
1052        // Restart the ticker if it's still running
1053        if (updateTicker) {
1054            haltTicker();
1055            tick(key, notification, false);
1056        }
1057
1058        // Recalculate the position of the sliding windows and the titles.
1059        setAreThereNotifications();
1060        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
1061
1062        // See if we need to update the intruder.
1063        if (ENABLE_INTRUDERS && oldNotification == mCurrentlyIntrudingNotification) {
1064            if (DEBUG) Slog.d(TAG, "updating the current intruder:" + notification);
1065            // XXX: this is a hack for Alarms. The real implementation will need to *update*
1066            // the intruder.
1067            if (notification.notification.fullScreenIntent == null) { // TODO(dsandler): consistent logic with add()
1068                if (DEBUG) Slog.d(TAG, "no longer intrudes!");
1069                mHandler.sendEmptyMessage(MSG_HIDE_INTRUDER);
1070            }
1071        }
1072    }
1073
1074    // Q: What kinds of notifications should show during setup?
1075    // A: Almost none! Only things coming from the system (package is "android") that also
1076    // have special "kind" tags marking them as relevant for setup (see below).
1077    protected boolean showNotificationEvenIfUnprovisioned(StatusBarNotification sbn) {
1078        if ("android".equals(sbn.pkg)) {
1079            if (sbn.notification.kind != null) {
1080                for (String aKind : sbn.notification.kind) {
1081                    // IME switcher, created by InputMethodManagerService
1082                    if ("android.system.imeswitcher".equals(aKind)) return true;
1083                    // OTA availability & errors, created by SystemUpdateService
1084                    if ("android.system.update".equals(aKind)) return true;
1085                }
1086            }
1087        }
1088        return false;
1089    }
1090
1091    public boolean inKeyguardRestrictedInputMode() {
1092        KeyguardManager km = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
1093        return km.inKeyguardRestrictedInputMode();
1094    }
1095}
1096