1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.content.Context;
20import android.content.res.Configuration;
21import android.content.res.TypedArray;
22import android.graphics.PixelFormat;
23import android.graphics.drawable.Drawable;
24import android.net.Uri;
25import android.os.Bundle;
26import android.os.IBinder;
27import android.os.SystemProperties;
28import android.view.accessibility.AccessibilityEvent;
29
30/**
31 * Abstract base class for a top-level window look and behavior policy.  An
32 * instance of this class should be used as the top-level view added to the
33 * window manager. It provides standard UI policies such as a background, title
34 * area, default key processing, etc.
35 *
36 * <p>The only existing implementation of this abstract class is
37 * android.policy.PhoneWindow, which you should instantiate when needing a
38 * Window.  Eventually that class will be refactored and a factory method
39 * added for creating Window instances without knowing about a particular
40 * implementation.
41 */
42public abstract class Window {
43    /** Flag for the "options panel" feature.  This is enabled by default. */
44    public static final int FEATURE_OPTIONS_PANEL = 0;
45    /** Flag for the "no title" feature, turning off the title at the top
46     *  of the screen. */
47    public static final int FEATURE_NO_TITLE = 1;
48    /** Flag for the progress indicator feature */
49    public static final int FEATURE_PROGRESS = 2;
50    /** Flag for having an icon on the left side of the title bar */
51    public static final int FEATURE_LEFT_ICON = 3;
52    /** Flag for having an icon on the right side of the title bar */
53    public static final int FEATURE_RIGHT_ICON = 4;
54    /** Flag for indeterminate progress */
55    public static final int FEATURE_INDETERMINATE_PROGRESS = 5;
56    /** Flag for the context menu.  This is enabled by default. */
57    public static final int FEATURE_CONTEXT_MENU = 6;
58    /** Flag for custom title. You cannot combine this feature with other title features. */
59    public static final int FEATURE_CUSTOM_TITLE = 7;
60    /**
61     * Flag for enabling the Action Bar.
62     * This is enabled by default for some devices. The Action Bar
63     * replaces the title bar and provides an alternate location
64     * for an on-screen menu button on some devices.
65     */
66    public static final int FEATURE_ACTION_BAR = 8;
67    /**
68     * Flag for requesting an Action Bar that overlays window content.
69     * Normally an Action Bar will sit in the space above window content, but if this
70     * feature is requested along with {@link #FEATURE_ACTION_BAR} it will be layered over
71     * the window content itself. This is useful if you would like your app to have more control
72     * over how the Action Bar is displayed, such as letting application content scroll beneath
73     * an Action Bar with a transparent background or otherwise displaying a transparent/translucent
74     * Action Bar over application content.
75     *
76     * <p>This mode is especially useful with {@link View#SYSTEM_UI_FLAG_FULLSCREEN
77     * View.SYSTEM_UI_FLAG_FULLSCREEN}, which allows you to seamlessly hide the
78     * action bar in conjunction with other screen decorations.
79     *
80     * <p>As of {@link android.os.Build.VERSION_CODES#JELLY_BEAN}, when an
81     * ActionBar is in this mode it will adjust the insets provided to
82     * {@link View#fitSystemWindows(android.graphics.Rect) View.fitSystemWindows(Rect)}
83     * to include the content covered by the action bar, so you can do layout within
84     * that space.
85     */
86    public static final int FEATURE_ACTION_BAR_OVERLAY = 9;
87    /**
88     * Flag for specifying the behavior of action modes when an Action Bar is not present.
89     * If overlay is enabled, the action mode UI will be allowed to cover existing window content.
90     */
91    public static final int FEATURE_ACTION_MODE_OVERLAY = 10;
92
93    /**
94     * Max value used as a feature ID
95     * @hide
96     */
97    public static final int FEATURE_MAX = FEATURE_ACTION_MODE_OVERLAY;
98
99    /** Flag for setting the progress bar's visibility to VISIBLE */
100    public static final int PROGRESS_VISIBILITY_ON = -1;
101    /** Flag for setting the progress bar's visibility to GONE */
102    public static final int PROGRESS_VISIBILITY_OFF = -2;
103    /** Flag for setting the progress bar's indeterminate mode on */
104    public static final int PROGRESS_INDETERMINATE_ON = -3;
105    /** Flag for setting the progress bar's indeterminate mode off */
106    public static final int PROGRESS_INDETERMINATE_OFF = -4;
107    /** Starting value for the (primary) progress */
108    public static final int PROGRESS_START = 0;
109    /** Ending value for the (primary) progress */
110    public static final int PROGRESS_END = 10000;
111    /** Lowest possible value for the secondary progress */
112    public static final int PROGRESS_SECONDARY_START = 20000;
113    /** Highest possible value for the secondary progress */
114    public static final int PROGRESS_SECONDARY_END = 30000;
115
116    /** The default features enabled */
117    @SuppressWarnings({"PointlessBitwiseExpression"})
118    protected static final int DEFAULT_FEATURES = (1 << FEATURE_OPTIONS_PANEL) |
119            (1 << FEATURE_CONTEXT_MENU);
120
121    /**
122     * The ID that the main layout in the XML layout file should have.
123     */
124    public static final int ID_ANDROID_CONTENT = com.android.internal.R.id.content;
125
126    private static final String PROPERTY_HARDWARE_UI = "persist.sys.ui.hw";
127
128    private final Context mContext;
129
130    private TypedArray mWindowStyle;
131    private Callback mCallback;
132    private WindowManager mWindowManager;
133    private IBinder mAppToken;
134    private String mAppName;
135    private boolean mHardwareAccelerated;
136    private Window mContainer;
137    private Window mActiveChild;
138    private boolean mIsActive = false;
139    private boolean mHasChildren = false;
140    private boolean mCloseOnTouchOutside = false;
141    private boolean mSetCloseOnTouchOutside = false;
142    private int mForcedWindowFlags = 0;
143
144    private int mFeatures = DEFAULT_FEATURES;
145    private int mLocalFeatures = DEFAULT_FEATURES;
146
147    private boolean mHaveWindowFormat = false;
148    private boolean mHaveDimAmount = false;
149    private int mDefaultWindowFormat = PixelFormat.OPAQUE;
150
151    private boolean mHasSoftInputMode = false;
152
153    private boolean mDestroyed;
154
155    // The current window attributes.
156    private final WindowManager.LayoutParams mWindowAttributes =
157        new WindowManager.LayoutParams();
158
159    /**
160     * API from a Window back to its caller.  This allows the client to
161     * intercept key dispatching, panels and menus, etc.
162     */
163    public interface Callback {
164        /**
165         * Called to process key events.  At the very least your
166         * implementation must call
167         * {@link android.view.Window#superDispatchKeyEvent} to do the
168         * standard key processing.
169         *
170         * @param event The key event.
171         *
172         * @return boolean Return true if this event was consumed.
173         */
174        public boolean dispatchKeyEvent(KeyEvent event);
175
176        /**
177         * Called to process a key shortcut event.
178         * At the very least your implementation must call
179         * {@link android.view.Window#superDispatchKeyShortcutEvent} to do the
180         * standard key shortcut processing.
181         *
182         * @param event The key shortcut event.
183         * @return True if this event was consumed.
184         */
185        public boolean dispatchKeyShortcutEvent(KeyEvent event);
186
187        /**
188         * Called to process touch screen events.  At the very least your
189         * implementation must call
190         * {@link android.view.Window#superDispatchTouchEvent} to do the
191         * standard touch screen processing.
192         *
193         * @param event The touch screen event.
194         *
195         * @return boolean Return true if this event was consumed.
196         */
197        public boolean dispatchTouchEvent(MotionEvent event);
198
199        /**
200         * Called to process trackball events.  At the very least your
201         * implementation must call
202         * {@link android.view.Window#superDispatchTrackballEvent} to do the
203         * standard trackball processing.
204         *
205         * @param event The trackball event.
206         *
207         * @return boolean Return true if this event was consumed.
208         */
209        public boolean dispatchTrackballEvent(MotionEvent event);
210
211        /**
212         * Called to process generic motion events.  At the very least your
213         * implementation must call
214         * {@link android.view.Window#superDispatchGenericMotionEvent} to do the
215         * standard processing.
216         *
217         * @param event The generic motion event.
218         *
219         * @return boolean Return true if this event was consumed.
220         */
221        public boolean dispatchGenericMotionEvent(MotionEvent event);
222
223        /**
224         * Called to process population of {@link AccessibilityEvent}s.
225         *
226         * @param event The event.
227         *
228         * @return boolean Return true if event population was completed.
229         */
230        public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event);
231
232        /**
233         * Instantiate the view to display in the panel for 'featureId'.
234         * You can return null, in which case the default content (typically
235         * a menu) will be created for you.
236         *
237         * @param featureId Which panel is being created.
238         *
239         * @return view The top-level view to place in the panel.
240         *
241         * @see #onPreparePanel
242         */
243        public View onCreatePanelView(int featureId);
244
245        /**
246         * Initialize the contents of the menu for panel 'featureId'.  This is
247         * called if onCreatePanelView() returns null, giving you a standard
248         * menu in which you can place your items.  It is only called once for
249         * the panel, the first time it is shown.
250         *
251         * <p>You can safely hold on to <var>menu</var> (and any items created
252         * from it), making modifications to it as desired, until the next
253         * time onCreatePanelMenu() is called for this feature.
254         *
255         * @param featureId The panel being created.
256         * @param menu The menu inside the panel.
257         *
258         * @return boolean You must return true for the panel to be displayed;
259         *         if you return false it will not be shown.
260         */
261        public boolean onCreatePanelMenu(int featureId, Menu menu);
262
263        /**
264         * Prepare a panel to be displayed.  This is called right before the
265         * panel window is shown, every time it is shown.
266         *
267         * @param featureId The panel that is being displayed.
268         * @param view The View that was returned by onCreatePanelView().
269         * @param menu If onCreatePanelView() returned null, this is the Menu
270         *             being displayed in the panel.
271         *
272         * @return boolean You must return true for the panel to be displayed;
273         *         if you return false it will not be shown.
274         *
275         * @see #onCreatePanelView
276         */
277        public boolean onPreparePanel(int featureId, View view, Menu menu);
278
279        /**
280         * Called when a panel's menu is opened by the user. This may also be
281         * called when the menu is changing from one type to another (for
282         * example, from the icon menu to the expanded menu).
283         *
284         * @param featureId The panel that the menu is in.
285         * @param menu The menu that is opened.
286         * @return Return true to allow the menu to open, or false to prevent
287         *         the menu from opening.
288         */
289        public boolean onMenuOpened(int featureId, Menu menu);
290
291        /**
292         * Called when a panel's menu item has been selected by the user.
293         *
294         * @param featureId The panel that the menu is in.
295         * @param item The menu item that was selected.
296         *
297         * @return boolean Return true to finish processing of selection, or
298         *         false to perform the normal menu handling (calling its
299         *         Runnable or sending a Message to its target Handler).
300         */
301        public boolean onMenuItemSelected(int featureId, MenuItem item);
302
303        /**
304         * This is called whenever the current window attributes change.
305         *
306         */
307        public void onWindowAttributesChanged(WindowManager.LayoutParams attrs);
308
309        /**
310         * This hook is called whenever the content view of the screen changes
311         * (due to a call to
312         * {@link Window#setContentView(View, android.view.ViewGroup.LayoutParams)
313         * Window.setContentView} or
314         * {@link Window#addContentView(View, android.view.ViewGroup.LayoutParams)
315         * Window.addContentView}).
316         */
317        public void onContentChanged();
318
319        /**
320         * This hook is called whenever the window focus changes.  See
321         * {@link View#onWindowFocusChanged(boolean)
322         * View.onWindowFocusChanged(boolean)} for more information.
323         *
324         * @param hasFocus Whether the window now has focus.
325         */
326        public void onWindowFocusChanged(boolean hasFocus);
327
328        /**
329         * Called when the window has been attached to the window manager.
330         * See {@link View#onAttachedToWindow() View.onAttachedToWindow()}
331         * for more information.
332         */
333        public void onAttachedToWindow();
334
335        /**
336         * Called when the window has been attached to the window manager.
337         * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()}
338         * for more information.
339         */
340        public void onDetachedFromWindow();
341
342        /**
343         * Called when a panel is being closed.  If another logical subsequent
344         * panel is being opened (and this panel is being closed to make room for the subsequent
345         * panel), this method will NOT be called.
346         *
347         * @param featureId The panel that is being displayed.
348         * @param menu If onCreatePanelView() returned null, this is the Menu
349         *            being displayed in the panel.
350         */
351        public void onPanelClosed(int featureId, Menu menu);
352
353        /**
354         * Called when the user signals the desire to start a search.
355         *
356         * @return true if search launched, false if activity refuses (blocks)
357         *
358         * @see android.app.Activity#onSearchRequested()
359         */
360        public boolean onSearchRequested();
361
362        /**
363         * Called when an action mode is being started for this window. Gives the
364         * callback an opportunity to handle the action mode in its own unique and
365         * beautiful way. If this method returns null the system can choose a way
366         * to present the mode or choose not to start the mode at all.
367         *
368         * @param callback Callback to control the lifecycle of this action mode
369         * @return The ActionMode that was started, or null if the system should present it
370         */
371        public ActionMode onWindowStartingActionMode(ActionMode.Callback callback);
372
373        /**
374         * Called when an action mode has been started. The appropriate mode callback
375         * method will have already been invoked.
376         *
377         * @param mode The new mode that has just been started.
378         */
379        public void onActionModeStarted(ActionMode mode);
380
381        /**
382         * Called when an action mode has been finished. The appropriate mode callback
383         * method will have already been invoked.
384         *
385         * @param mode The mode that was just finished.
386         */
387        public void onActionModeFinished(ActionMode mode);
388    }
389
390    public Window(Context context) {
391        mContext = context;
392    }
393
394    /**
395     * Return the Context this window policy is running in, for retrieving
396     * resources and other information.
397     *
398     * @return Context The Context that was supplied to the constructor.
399     */
400    public final Context getContext() {
401        return mContext;
402    }
403
404    /**
405     * Return the {@link android.R.styleable#Window} attributes from this
406     * window's theme.
407     */
408    public final TypedArray getWindowStyle() {
409        synchronized (this) {
410            if (mWindowStyle == null) {
411                mWindowStyle = mContext.obtainStyledAttributes(
412                        com.android.internal.R.styleable.Window);
413            }
414            return mWindowStyle;
415        }
416    }
417
418    /**
419     * Set the container for this window.  If not set, the DecorWindow
420     * operates as a top-level window; otherwise, it negotiates with the
421     * container to display itself appropriately.
422     *
423     * @param container The desired containing Window.
424     */
425    public void setContainer(Window container) {
426        mContainer = container;
427        if (container != null) {
428            // Embedded screens never have a title.
429            mFeatures |= 1<<FEATURE_NO_TITLE;
430            mLocalFeatures |= 1<<FEATURE_NO_TITLE;
431            container.mHasChildren = true;
432        }
433    }
434
435    /**
436     * Return the container for this Window.
437     *
438     * @return Window The containing window, or null if this is a
439     *         top-level window.
440     */
441    public final Window getContainer() {
442        return mContainer;
443    }
444
445    public final boolean hasChildren() {
446        return mHasChildren;
447    }
448
449    /** @hide */
450    public final void destroy() {
451        mDestroyed = true;
452    }
453
454    /** @hide */
455    public final boolean isDestroyed() {
456        return mDestroyed;
457    }
458
459    /**
460     * Set the window manager for use by this Window to, for example,
461     * display panels.  This is <em>not</em> used for displaying the
462     * Window itself -- that must be done by the client.
463     *
464     * @param wm The window manager for adding new windows.
465     */
466    public void setWindowManager(WindowManager wm, IBinder appToken, String appName) {
467        setWindowManager(wm, appToken, appName, false);
468    }
469
470    /**
471     * Set the window manager for use by this Window to, for example,
472     * display panels.  This is <em>not</em> used for displaying the
473     * Window itself -- that must be done by the client.
474     *
475     * @param wm The window manager for adding new windows.
476     */
477    public void setWindowManager(WindowManager wm, IBinder appToken, String appName,
478            boolean hardwareAccelerated) {
479        mAppToken = appToken;
480        mAppName = appName;
481        mHardwareAccelerated = hardwareAccelerated
482                || SystemProperties.getBoolean(PROPERTY_HARDWARE_UI, false);
483        if (wm == null) {
484            wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
485        }
486        mWindowManager = ((WindowManagerImpl)wm).createLocalWindowManager(this);
487    }
488
489    void adjustLayoutParamsForSubWindow(WindowManager.LayoutParams wp) {
490        CharSequence curTitle = wp.getTitle();
491        if (wp.type >= WindowManager.LayoutParams.FIRST_SUB_WINDOW &&
492            wp.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
493            if (wp.token == null) {
494                View decor = peekDecorView();
495                if (decor != null) {
496                    wp.token = decor.getWindowToken();
497                }
498            }
499            if (curTitle == null || curTitle.length() == 0) {
500                String title;
501                if (wp.type == WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA) {
502                    title="Media";
503                } else if (wp.type == WindowManager.LayoutParams.TYPE_APPLICATION_MEDIA_OVERLAY) {
504                    title="MediaOvr";
505                } else if (wp.type == WindowManager.LayoutParams.TYPE_APPLICATION_PANEL) {
506                    title="Panel";
507                } else if (wp.type == WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL) {
508                    title="SubPanel";
509                } else if (wp.type == WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG) {
510                    title="AtchDlg";
511                } else {
512                    title=Integer.toString(wp.type);
513                }
514                if (mAppName != null) {
515                    title += ":" + mAppName;
516                }
517                wp.setTitle(title);
518            }
519        } else {
520            if (wp.token == null) {
521                wp.token = mContainer == null ? mAppToken : mContainer.mAppToken;
522            }
523            if ((curTitle == null || curTitle.length() == 0)
524                    && mAppName != null) {
525                wp.setTitle(mAppName);
526            }
527        }
528        if (wp.packageName == null) {
529            wp.packageName = mContext.getPackageName();
530        }
531        if (mHardwareAccelerated) {
532            wp.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
533        }
534    }
535
536    /**
537     * Return the window manager allowing this Window to display its own
538     * windows.
539     *
540     * @return WindowManager The ViewManager.
541     */
542    public WindowManager getWindowManager() {
543        return mWindowManager;
544    }
545
546    /**
547     * Set the Callback interface for this window, used to intercept key
548     * events and other dynamic operations in the window.
549     *
550     * @param callback The desired Callback interface.
551     */
552    public void setCallback(Callback callback) {
553        mCallback = callback;
554    }
555
556    /**
557     * Return the current Callback interface for this window.
558     */
559    public final Callback getCallback() {
560        return mCallback;
561    }
562
563    /**
564     * Take ownership of this window's surface.  The window's view hierarchy
565     * will no longer draw into the surface, though it will otherwise continue
566     * to operate (such as for receiving input events).  The given SurfaceHolder
567     * callback will be used to tell you about state changes to the surface.
568     */
569    public abstract void takeSurface(SurfaceHolder.Callback2 callback);
570
571    /**
572     * Take ownership of this window's InputQueue.  The window will no
573     * longer read and dispatch input events from the queue; it is your
574     * responsibility to do so.
575     */
576    public abstract void takeInputQueue(InputQueue.Callback callback);
577
578    /**
579     * Return whether this window is being displayed with a floating style
580     * (based on the {@link android.R.attr#windowIsFloating} attribute in
581     * the style/theme).
582     *
583     * @return Returns true if the window is configured to be displayed floating
584     * on top of whatever is behind it.
585     */
586    public abstract boolean isFloating();
587
588    /**
589     * Set the width and height layout parameters of the window.  The default
590     * for both of these is MATCH_PARENT; you can change them to WRAP_CONTENT
591     * or an absolute value to make a window that is not full-screen.
592     *
593     * @param width The desired layout width of the window.
594     * @param height The desired layout height of the window.
595     *
596     * @see ViewGroup.LayoutParams#height
597     * @see ViewGroup.LayoutParams#width
598     */
599    public void setLayout(int width, int height) {
600        final WindowManager.LayoutParams attrs = getAttributes();
601        attrs.width = width;
602        attrs.height = height;
603        if (mCallback != null) {
604            mCallback.onWindowAttributesChanged(attrs);
605        }
606    }
607
608    /**
609     * Set the gravity of the window, as per the Gravity constants.  This
610     * controls how the window manager is positioned in the overall window; it
611     * is only useful when using WRAP_CONTENT for the layout width or height.
612     *
613     * @param gravity The desired gravity constant.
614     *
615     * @see Gravity
616     * @see #setLayout
617     */
618    public void setGravity(int gravity)
619    {
620        final WindowManager.LayoutParams attrs = getAttributes();
621        attrs.gravity = gravity;
622        if (mCallback != null) {
623            mCallback.onWindowAttributesChanged(attrs);
624        }
625    }
626
627    /**
628     * Set the type of the window, as per the WindowManager.LayoutParams
629     * types.
630     *
631     * @param type The new window type (see WindowManager.LayoutParams).
632     */
633    public void setType(int type) {
634        final WindowManager.LayoutParams attrs = getAttributes();
635        attrs.type = type;
636        if (mCallback != null) {
637            mCallback.onWindowAttributesChanged(attrs);
638        }
639    }
640
641    /**
642     * Set the format of window, as per the PixelFormat types.  This overrides
643     * the default format that is selected by the Window based on its
644     * window decorations.
645     *
646     * @param format The new window format (see PixelFormat).  Use
647     *               PixelFormat.UNKNOWN to allow the Window to select
648     *               the format.
649     *
650     * @see PixelFormat
651     */
652    public void setFormat(int format) {
653        final WindowManager.LayoutParams attrs = getAttributes();
654        if (format != PixelFormat.UNKNOWN) {
655            attrs.format = format;
656            mHaveWindowFormat = true;
657        } else {
658            attrs.format = mDefaultWindowFormat;
659            mHaveWindowFormat = false;
660        }
661        if (mCallback != null) {
662            mCallback.onWindowAttributesChanged(attrs);
663        }
664    }
665
666    /**
667     * Specify custom animations to use for the window, as per
668     * {@link WindowManager.LayoutParams#windowAnimations
669     * WindowManager.LayoutParams.windowAnimations}.  Providing anything besides
670     * 0 here will override the animations the window would
671     * normally retrieve from its theme.
672     */
673    public void setWindowAnimations(int resId) {
674        final WindowManager.LayoutParams attrs = getAttributes();
675        attrs.windowAnimations = resId;
676        if (mCallback != null) {
677            mCallback.onWindowAttributesChanged(attrs);
678        }
679    }
680
681    /**
682     * Specify an explicit soft input mode to use for the window, as per
683     * {@link WindowManager.LayoutParams#softInputMode
684     * WindowManager.LayoutParams.softInputMode}.  Providing anything besides
685     * "unspecified" here will override the input mode the window would
686     * normally retrieve from its theme.
687     */
688    public void setSoftInputMode(int mode) {
689        final WindowManager.LayoutParams attrs = getAttributes();
690        if (mode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
691            attrs.softInputMode = mode;
692            mHasSoftInputMode = true;
693        } else {
694            mHasSoftInputMode = false;
695        }
696        if (mCallback != null) {
697            mCallback.onWindowAttributesChanged(attrs);
698        }
699    }
700
701    /**
702     * Convenience function to set the flag bits as specified in flags, as
703     * per {@link #setFlags}.
704     * @param flags The flag bits to be set.
705     * @see #setFlags
706     * @see #clearFlags
707     */
708    public void addFlags(int flags) {
709        setFlags(flags, flags);
710    }
711
712    /**
713     * Convenience function to clear the flag bits as specified in flags, as
714     * per {@link #setFlags}.
715     * @param flags The flag bits to be cleared.
716     * @see #setFlags
717     * @see #addFlags
718     */
719    public void clearFlags(int flags) {
720        setFlags(0, flags);
721    }
722
723    /**
724     * Set the flags of the window, as per the
725     * {@link WindowManager.LayoutParams WindowManager.LayoutParams}
726     * flags.
727     *
728     * <p>Note that some flags must be set before the window decoration is
729     * created (by the first call to
730     * {@link #setContentView(View, android.view.ViewGroup.LayoutParams)} or
731     * {@link #getDecorView()}:
732     * {@link WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN} and
733     * {@link WindowManager.LayoutParams#FLAG_LAYOUT_INSET_DECOR}.  These
734     * will be set for you based on the {@link android.R.attr#windowIsFloating}
735     * attribute.
736     *
737     * @param flags The new window flags (see WindowManager.LayoutParams).
738     * @param mask Which of the window flag bits to modify.
739     * @see #addFlags
740     * @see #clearFlags
741     */
742    public void setFlags(int flags, int mask) {
743        final WindowManager.LayoutParams attrs = getAttributes();
744        attrs.flags = (attrs.flags&~mask) | (flags&mask);
745        if ((mask&WindowManager.LayoutParams.FLAG_NEEDS_MENU_KEY) != 0) {
746            attrs.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SET_NEEDS_MENU_KEY;
747        }
748        mForcedWindowFlags |= mask;
749        if (mCallback != null) {
750            mCallback.onWindowAttributesChanged(attrs);
751        }
752    }
753
754    /**
755     * Set the amount of dim behind the window when using
756     * {@link WindowManager.LayoutParams#FLAG_DIM_BEHIND}.  This overrides
757     * the default dim amount of that is selected by the Window based on
758     * its theme.
759     *
760     * @param amount The new dim amount, from 0 for no dim to 1 for full dim.
761     */
762    public void setDimAmount(float amount) {
763        final WindowManager.LayoutParams attrs = getAttributes();
764        attrs.dimAmount = amount;
765        mHaveDimAmount = true;
766        if (mCallback != null) {
767            mCallback.onWindowAttributesChanged(attrs);
768        }
769    }
770
771    /**
772     * Specify custom window attributes.  <strong>PLEASE NOTE:</strong> the
773     * layout params you give here should generally be from values previously
774     * retrieved with {@link #getAttributes()}; you probably do not want to
775     * blindly create and apply your own, since this will blow away any values
776     * set by the framework that you are not interested in.
777     *
778     * @param a The new window attributes, which will completely override any
779     *          current values.
780     */
781    public void setAttributes(WindowManager.LayoutParams a) {
782        mWindowAttributes.copyFrom(a);
783        if (mCallback != null) {
784            mCallback.onWindowAttributesChanged(mWindowAttributes);
785        }
786    }
787
788    /**
789     * Retrieve the current window attributes associated with this panel.
790     *
791     * @return WindowManager.LayoutParams Either the existing window
792     *         attributes object, or a freshly created one if there is none.
793     */
794    public final WindowManager.LayoutParams getAttributes() {
795        return mWindowAttributes;
796    }
797
798    /**
799     * Return the window flags that have been explicitly set by the client,
800     * so will not be modified by {@link #getDecorView}.
801     */
802    protected final int getForcedWindowFlags() {
803        return mForcedWindowFlags;
804    }
805
806    /**
807     * Has the app specified their own soft input mode?
808     */
809    protected final boolean hasSoftInputMode() {
810        return mHasSoftInputMode;
811    }
812
813    /** @hide */
814    public void setCloseOnTouchOutside(boolean close) {
815        mCloseOnTouchOutside = close;
816        mSetCloseOnTouchOutside = true;
817    }
818
819    /** @hide */
820    public void setCloseOnTouchOutsideIfNotSet(boolean close) {
821        if (!mSetCloseOnTouchOutside) {
822            mCloseOnTouchOutside = close;
823            mSetCloseOnTouchOutside = true;
824        }
825    }
826
827    /** @hide */
828    public abstract void alwaysReadCloseOnTouchAttr();
829
830    /** @hide */
831    public boolean shouldCloseOnTouch(Context context, MotionEvent event) {
832        if (mCloseOnTouchOutside && event.getAction() == MotionEvent.ACTION_DOWN
833                && isOutOfBounds(context, event) && peekDecorView() != null) {
834            return true;
835        }
836        return false;
837    }
838
839    private boolean isOutOfBounds(Context context, MotionEvent event) {
840        final int x = (int) event.getX();
841        final int y = (int) event.getY();
842        final int slop = ViewConfiguration.get(context).getScaledWindowTouchSlop();
843        final View decorView = getDecorView();
844        return (x < -slop) || (y < -slop)
845                || (x > (decorView.getWidth()+slop))
846                || (y > (decorView.getHeight()+slop));
847    }
848
849    /**
850     * Enable extended screen features.  This must be called before
851     * setContentView().  May be called as many times as desired as long as it
852     * is before setContentView().  If not called, no extended features
853     * will be available.  You can not turn off a feature once it is requested.
854     * You canot use other title features with {@link #FEATURE_CUSTOM_TITLE}.
855     *
856     * @param featureId The desired features, defined as constants by Window.
857     * @return The features that are now set.
858     */
859    public boolean requestFeature(int featureId) {
860        final int flag = 1<<featureId;
861        mFeatures |= flag;
862        mLocalFeatures |= mContainer != null ? (flag&~mContainer.mFeatures) : flag;
863        return (mFeatures&flag) != 0;
864    }
865
866    /**
867     * @hide Used internally to help resolve conflicting features.
868     */
869    protected void removeFeature(int featureId) {
870        final int flag = 1<<featureId;
871        mFeatures &= ~flag;
872        mLocalFeatures &= ~(mContainer != null ? (flag&~mContainer.mFeatures) : flag);
873    }
874
875    public final void makeActive() {
876        if (mContainer != null) {
877            if (mContainer.mActiveChild != null) {
878                mContainer.mActiveChild.mIsActive = false;
879            }
880            mContainer.mActiveChild = this;
881        }
882        mIsActive = true;
883        onActive();
884    }
885
886    public final boolean isActive()
887    {
888        return mIsActive;
889    }
890
891    /**
892     * Finds a view that was identified by the id attribute from the XML that
893     * was processed in {@link android.app.Activity#onCreate}.  This will
894     * implicitly call {@link #getDecorView} for you, with all of the
895     * associated side-effects.
896     *
897     * @return The view if found or null otherwise.
898     */
899    public View findViewById(int id) {
900        return getDecorView().findViewById(id);
901    }
902
903    /**
904     * Convenience for
905     * {@link #setContentView(View, android.view.ViewGroup.LayoutParams)}
906     * to set the screen content from a layout resource.  The resource will be
907     * inflated, adding all top-level views to the screen.
908     *
909     * @param layoutResID Resource ID to be inflated.
910     * @see #setContentView(View, android.view.ViewGroup.LayoutParams)
911     */
912    public abstract void setContentView(int layoutResID);
913
914    /**
915     * Convenience for
916     * {@link #setContentView(View, android.view.ViewGroup.LayoutParams)}
917     * set the screen content to an explicit view.  This view is placed
918     * directly into the screen's view hierarchy.  It can itself be a complex
919     * view hierarhcy.
920     *
921     * @param view The desired content to display.
922     * @see #setContentView(View, android.view.ViewGroup.LayoutParams)
923     */
924    public abstract void setContentView(View view);
925
926    /**
927     * Set the screen content to an explicit view.  This view is placed
928     * directly into the screen's view hierarchy.  It can itself be a complex
929     * view hierarchy.
930     *
931     * <p>Note that calling this function "locks in" various characteristics
932     * of the window that can not, from this point forward, be changed: the
933     * features that have been requested with {@link #requestFeature(int)},
934     * and certain window flags as described in {@link #setFlags(int, int)}.
935     *
936     * @param view The desired content to display.
937     * @param params Layout parameters for the view.
938     */
939    public abstract void setContentView(View view, ViewGroup.LayoutParams params);
940
941    /**
942     * Variation on
943     * {@link #setContentView(View, android.view.ViewGroup.LayoutParams)}
944     * to add an additional content view to the screen.  Added after any existing
945     * ones in the screen -- existing views are NOT removed.
946     *
947     * @param view The desired content to display.
948     * @param params Layout parameters for the view.
949     */
950    public abstract void addContentView(View view, ViewGroup.LayoutParams params);
951
952    /**
953     * Return the view in this Window that currently has focus, or null if
954     * there are none.  Note that this does not look in any containing
955     * Window.
956     *
957     * @return View The current View with focus or null.
958     */
959    public abstract View getCurrentFocus();
960
961    /**
962     * Quick access to the {@link LayoutInflater} instance that this Window
963     * retrieved from its Context.
964     *
965     * @return LayoutInflater The shared LayoutInflater.
966     */
967    public abstract LayoutInflater getLayoutInflater();
968
969    public abstract void setTitle(CharSequence title);
970
971    public abstract void setTitleColor(int textColor);
972
973    public abstract void openPanel(int featureId, KeyEvent event);
974
975    public abstract void closePanel(int featureId);
976
977    public abstract void togglePanel(int featureId, KeyEvent event);
978
979    public abstract void invalidatePanelMenu(int featureId);
980
981    public abstract boolean performPanelShortcut(int featureId,
982                                                 int keyCode,
983                                                 KeyEvent event,
984                                                 int flags);
985    public abstract boolean performPanelIdentifierAction(int featureId,
986                                                 int id,
987                                                 int flags);
988
989    public abstract void closeAllPanels();
990
991    public abstract boolean performContextMenuIdentifierAction(int id, int flags);
992
993    /**
994     * Should be called when the configuration is changed.
995     *
996     * @param newConfig The new configuration.
997     */
998    public abstract void onConfigurationChanged(Configuration newConfig);
999
1000    /**
1001     * Change the background of this window to a Drawable resource. Setting the
1002     * background to null will make the window be opaque. To make the window
1003     * transparent, you can use an empty drawable (for instance a ColorDrawable
1004     * with the color 0 or the system drawable android:drawable/empty.)
1005     *
1006     * @param resid The resource identifier of a drawable resource which will be
1007     *              installed as the new background.
1008     */
1009    public void setBackgroundDrawableResource(int resid)
1010    {
1011        setBackgroundDrawable(mContext.getResources().getDrawable(resid));
1012    }
1013
1014    /**
1015     * Change the background of this window to a custom Drawable. Setting the
1016     * background to null will make the window be opaque. To make the window
1017     * transparent, you can use an empty drawable (for instance a ColorDrawable
1018     * with the color 0 or the system drawable android:drawable/empty.)
1019     *
1020     * @param drawable The new Drawable to use for this window's background.
1021     */
1022    public abstract void setBackgroundDrawable(Drawable drawable);
1023
1024    /**
1025     * Set the value for a drawable feature of this window, from a resource
1026     * identifier.  You must have called requestFeauture(featureId) before
1027     * calling this function.
1028     *
1029     * @see android.content.res.Resources#getDrawable(int)
1030     *
1031     * @param featureId The desired drawable feature to change, defined as a
1032     * constant by Window.
1033     * @param resId Resource identifier of the desired image.
1034     */
1035    public abstract void setFeatureDrawableResource(int featureId, int resId);
1036
1037    /**
1038     * Set the value for a drawable feature of this window, from a URI. You
1039     * must have called requestFeature(featureId) before calling this
1040     * function.
1041     *
1042     * <p>The only URI currently supported is "content:", specifying an image
1043     * in a content provider.
1044     *
1045     * @see android.widget.ImageView#setImageURI
1046     *
1047     * @param featureId The desired drawable feature to change. Features are
1048     * constants defined by Window.
1049     * @param uri The desired URI.
1050     */
1051    public abstract void setFeatureDrawableUri(int featureId, Uri uri);
1052
1053    /**
1054     * Set an explicit Drawable value for feature of this window. You must
1055     * have called requestFeature(featureId) before calling this function.
1056     *
1057     * @param featureId The desired drawable feature to change.
1058     * Features are constants defined by Window.
1059     * @param drawable A Drawable object to display.
1060     */
1061    public abstract void setFeatureDrawable(int featureId, Drawable drawable);
1062
1063    /**
1064     * Set a custom alpha value for the given drawale feature, controlling how
1065     * much the background is visible through it.
1066     *
1067     * @param featureId The desired drawable feature to change.
1068     * Features are constants defined by Window.
1069     * @param alpha The alpha amount, 0 is completely transparent and 255 is
1070     *              completely opaque.
1071     */
1072    public abstract void setFeatureDrawableAlpha(int featureId, int alpha);
1073
1074    /**
1075     * Set the integer value for a feature.  The range of the value depends on
1076     * the feature being set.  For FEATURE_PROGRESSS, it should go from 0 to
1077     * 10000. At 10000 the progress is complete and the indicator hidden.
1078     *
1079     * @param featureId The desired feature to change.
1080     * Features are constants defined by Window.
1081     * @param value The value for the feature.  The interpretation of this
1082     *              value is feature-specific.
1083     */
1084    public abstract void setFeatureInt(int featureId, int value);
1085
1086    /**
1087     * Request that key events come to this activity. Use this if your
1088     * activity has no views with focus, but the activity still wants
1089     * a chance to process key events.
1090     */
1091    public abstract void takeKeyEvents(boolean get);
1092
1093    /**
1094     * Used by custom windows, such as Dialog, to pass the key press event
1095     * further down the view hierarchy. Application developers should
1096     * not need to implement or call this.
1097     *
1098     */
1099    public abstract boolean superDispatchKeyEvent(KeyEvent event);
1100
1101    /**
1102     * Used by custom windows, such as Dialog, to pass the key shortcut press event
1103     * further down the view hierarchy. Application developers should
1104     * not need to implement or call this.
1105     *
1106     */
1107    public abstract boolean superDispatchKeyShortcutEvent(KeyEvent event);
1108
1109    /**
1110     * Used by custom windows, such as Dialog, to pass the touch screen event
1111     * further down the view hierarchy. Application developers should
1112     * not need to implement or call this.
1113     *
1114     */
1115    public abstract boolean superDispatchTouchEvent(MotionEvent event);
1116
1117    /**
1118     * Used by custom windows, such as Dialog, to pass the trackball event
1119     * further down the view hierarchy. Application developers should
1120     * not need to implement or call this.
1121     *
1122     */
1123    public abstract boolean superDispatchTrackballEvent(MotionEvent event);
1124
1125    /**
1126     * Used by custom windows, such as Dialog, to pass the generic motion event
1127     * further down the view hierarchy. Application developers should
1128     * not need to implement or call this.
1129     *
1130     */
1131    public abstract boolean superDispatchGenericMotionEvent(MotionEvent event);
1132
1133    /**
1134     * Retrieve the top-level window decor view (containing the standard
1135     * window frame/decorations and the client's content inside of that), which
1136     * can be added as a window to the window manager.
1137     *
1138     * <p><em>Note that calling this function for the first time "locks in"
1139     * various window characteristics as described in
1140     * {@link #setContentView(View, android.view.ViewGroup.LayoutParams)}.</em></p>
1141     *
1142     * @return Returns the top-level window decor view.
1143     */
1144    public abstract View getDecorView();
1145
1146    /**
1147     * Retrieve the current decor view, but only if it has already been created;
1148     * otherwise returns null.
1149     *
1150     * @return Returns the top-level window decor or null.
1151     * @see #getDecorView
1152     */
1153    public abstract View peekDecorView();
1154
1155    public abstract Bundle saveHierarchyState();
1156
1157    public abstract void restoreHierarchyState(Bundle savedInstanceState);
1158
1159    protected abstract void onActive();
1160
1161    /**
1162     * Return the feature bits that are enabled.  This is the set of features
1163     * that were given to requestFeature(), and are being handled by this
1164     * Window itself or its container.  That is, it is the set of
1165     * requested features that you can actually use.
1166     *
1167     * <p>To do: add a public version of this API that allows you to check for
1168     * features by their feature ID.
1169     *
1170     * @return int The feature bits.
1171     */
1172    protected final int getFeatures()
1173    {
1174        return mFeatures;
1175    }
1176
1177    /**
1178     * Query for the availability of a certain feature.
1179     *
1180     * @param feature The feature ID to check
1181     * @return true if the feature is enabled, false otherwise.
1182     */
1183    public boolean hasFeature(int feature) {
1184        return (getFeatures() & (1 << feature)) != 0;
1185    }
1186
1187    /**
1188     * Return the feature bits that are being implemented by this Window.
1189     * This is the set of features that were given to requestFeature(), and are
1190     * being handled by only this Window itself, not by its containers.
1191     *
1192     * @return int The feature bits.
1193     */
1194    protected final int getLocalFeatures()
1195    {
1196        return mLocalFeatures;
1197    }
1198
1199    /**
1200     * Set the default format of window, as per the PixelFormat types.  This
1201     * is the format that will be used unless the client specifies in explicit
1202     * format with setFormat();
1203     *
1204     * @param format The new window format (see PixelFormat).
1205     *
1206     * @see #setFormat
1207     * @see PixelFormat
1208     */
1209    protected void setDefaultWindowFormat(int format) {
1210        mDefaultWindowFormat = format;
1211        if (!mHaveWindowFormat) {
1212            final WindowManager.LayoutParams attrs = getAttributes();
1213            attrs.format = format;
1214            if (mCallback != null) {
1215                mCallback.onWindowAttributesChanged(attrs);
1216            }
1217        }
1218    }
1219
1220    /** @hide */
1221    protected boolean haveDimAmount() {
1222        return mHaveDimAmount;
1223    }
1224
1225    public abstract void setChildDrawable(int featureId, Drawable drawable);
1226
1227    public abstract void setChildInt(int featureId, int value);
1228
1229    /**
1230     * Is a keypress one of the defined shortcut keys for this window.
1231     * @param keyCode the key code from {@link android.view.KeyEvent} to check.
1232     * @param event the {@link android.view.KeyEvent} to use to help check.
1233     */
1234    public abstract boolean isShortcutKey(int keyCode, KeyEvent event);
1235
1236    /**
1237     * @see android.app.Activity#setVolumeControlStream(int)
1238     */
1239    public abstract void setVolumeControlStream(int streamType);
1240
1241    /**
1242     * @see android.app.Activity#getVolumeControlStream()
1243     */
1244    public abstract int getVolumeControlStream();
1245
1246    /**
1247     * Set extra options that will influence the UI for this window.
1248     * @param uiOptions Flags specifying extra options for this window.
1249     */
1250    public void setUiOptions(int uiOptions) { }
1251
1252    /**
1253     * Set extra options that will influence the UI for this window.
1254     * Only the bits filtered by mask will be modified.
1255     * @param uiOptions Flags specifying extra options for this window.
1256     * @param mask Flags specifying which options should be modified. Others will remain unchanged.
1257     */
1258    public void setUiOptions(int uiOptions, int mask) { }
1259}
1260