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