Dialog.java revision c30d767628861b0bbea907824682e47732c820f9
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.app;
18
19import com.android.internal.app.ActionBarImpl;
20import com.android.internal.policy.PolicyManager;
21
22import android.content.ComponentName;
23import android.content.Context;
24import android.content.ContextWrapper;
25import android.content.DialogInterface;
26import android.graphics.drawable.Drawable;
27import android.net.Uri;
28import android.os.Bundle;
29import android.os.Handler;
30import android.os.Message;
31import android.util.TypedValue;
32import android.view.ActionMode;
33import android.view.ContextMenu;
34import android.view.ContextMenu.ContextMenuInfo;
35import android.view.ContextThemeWrapper;
36import android.view.Gravity;
37import android.view.KeyEvent;
38import android.view.LayoutInflater;
39import android.view.Menu;
40import android.view.MenuItem;
41import android.view.MotionEvent;
42import android.view.View;
43import android.view.View.OnCreateContextMenuListener;
44import android.view.ViewGroup;
45import android.view.ViewGroup.LayoutParams;
46import android.view.Window;
47import android.view.WindowManager;
48import android.view.accessibility.AccessibilityEvent;
49
50import java.lang.ref.WeakReference;
51
52/**
53 * Base class for Dialogs.
54 *
55 * <p>Note: Activities provide a facility to manage the creation, saving and
56 * restoring of dialogs. See {@link Activity#onCreateDialog(int)},
57 * {@link Activity#onPrepareDialog(int, Dialog)},
58 * {@link Activity#showDialog(int)}, and {@link Activity#dismissDialog(int)}. If
59 * these methods are used, {@link #getOwnerActivity()} will return the Activity
60 * that managed this dialog.
61 *
62 * <p>Often you will want to have a Dialog display on top of the current
63 * input method, because there is no reason for it to accept text.  You can
64 * do this by setting the {@link WindowManager.LayoutParams#FLAG_ALT_FOCUSABLE_IM
65 * WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM} window flag (assuming
66 * your Dialog takes input focus, as it the default) with the following code:
67 *
68 * <pre>
69 *     getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
70 *             WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
71 * </pre>
72 */
73public class Dialog implements DialogInterface, Window.Callback,
74        KeyEvent.Callback, OnCreateContextMenuListener {
75    private Activity mOwnerActivity;
76
77    final Context mContext;
78    final WindowManager mWindowManager;
79    Window mWindow;
80    View mDecor;
81    private ActionBarImpl mActionBar;
82    /**
83     * This field should be made private, so it is hidden from the SDK.
84     * {@hide}
85     */
86    protected boolean mCancelable = true;
87
88    private String mCancelAndDismissTaken;
89    private Message mCancelMessage;
90    private Message mDismissMessage;
91    private Message mShowMessage;
92
93    private OnKeyListener mOnKeyListener;
94
95    private boolean mCreated = false;
96    private boolean mShowing = false;
97    private boolean mCanceled = false;
98
99    private final Thread mUiThread;
100    private final Handler mHandler = new Handler();
101
102    private static final int DISMISS = 0x43;
103    private static final int CANCEL = 0x44;
104    private static final int SHOW = 0x45;
105
106    private Handler mListenersHandler;
107
108    private final Runnable mDismissAction = new Runnable() {
109        public void run() {
110            dismissDialog();
111        }
112    };
113
114    /**
115     * Create a Dialog window that uses the default dialog frame style.
116     *
117     * @param context The Context the Dialog is to run it.  In particular, it
118     *                uses the window manager and theme in this context to
119     *                present its UI.
120     */
121    public Dialog(Context context) {
122        this(context, 0, true);
123    }
124
125    /**
126     * Create a Dialog window that uses a custom dialog style.
127     *
128     * @param context The Context in which the Dialog should run. In particular, it
129     *                uses the window manager and theme from this context to
130     *                present its UI.
131     * @param theme A style resource describing the theme to use for the
132     * window. See <a href="{@docRoot}guide/topics/resources/available-resources.html#stylesandthemes">Style
133     * and Theme Resources</a> for more information about defining and using
134     * styles.  This theme is applied on top of the current theme in
135     * <var>context</var>.  If 0, the default dialog theme will be used.
136     */
137    public Dialog(Context context, int theme) {
138        this(context, theme, true);
139    }
140
141    Dialog(Context context, int theme, boolean createContextWrapper) {
142        if (theme == 0) {
143            TypedValue outValue = new TypedValue();
144            context.getTheme().resolveAttribute(com.android.internal.R.attr.dialogTheme,
145                    outValue, true);
146            theme = outValue.resourceId;
147        }
148
149        mContext = createContextWrapper ? new ContextThemeWrapper(context, theme) : context;
150        mWindowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
151        Window w = PolicyManager.makeNewWindow(mContext);
152        mWindow = w;
153        w.setCallback(this);
154        w.setWindowManager(mWindowManager, null, null);
155        w.setGravity(Gravity.CENTER);
156        mUiThread = Thread.currentThread();
157        mListenersHandler = new ListenersHandler(this);
158    }
159
160    /**
161     * @deprecated
162     * @hide
163     */
164    @Deprecated
165    protected Dialog(Context context, boolean cancelable,
166            Message cancelCallback) {
167        this(context);
168        mCancelable = cancelable;
169        mCancelMessage = cancelCallback;
170    }
171
172    protected Dialog(Context context, boolean cancelable,
173            OnCancelListener cancelListener) {
174        this(context);
175        mCancelable = cancelable;
176        setOnCancelListener(cancelListener);
177    }
178
179    /**
180     * Retrieve the Context this Dialog is running in.
181     *
182     * @return Context The Context used by the Dialog.
183     */
184    public final Context getContext() {
185        return mContext;
186    }
187
188    /**
189     * Retrieve the {@link ActionBar} attached to this dialog, if present.
190     *
191     * @return The ActionBar attached to the dialog or null if no ActionBar is present.
192     */
193    public ActionBar getActionBar() {
194        return mActionBar;
195    }
196
197    /**
198     * Sets the Activity that owns this dialog. An example use: This Dialog will
199     * use the suggested volume control stream of the Activity.
200     *
201     * @param activity The Activity that owns this dialog.
202     */
203    public final void setOwnerActivity(Activity activity) {
204        mOwnerActivity = activity;
205
206        getWindow().setVolumeControlStream(mOwnerActivity.getVolumeControlStream());
207    }
208
209    /**
210     * Returns the Activity that owns this Dialog. For example, if
211     * {@link Activity#showDialog(int)} is used to show this Dialog, that
212     * Activity will be the owner (by default). Depending on how this dialog was
213     * created, this may return null.
214     *
215     * @return The Activity that owns this Dialog.
216     */
217    public final Activity getOwnerActivity() {
218        return mOwnerActivity;
219    }
220
221    /**
222     * @return Whether the dialog is currently showing.
223     */
224    public boolean isShowing() {
225        return mShowing;
226    }
227
228    /**
229     * Start the dialog and display it on screen.  The window is placed in the
230     * application layer and opaque.  Note that you should not override this
231     * method to do initialization when the dialog is shown, instead implement
232     * that in {@link #onStart}.
233     */
234    public void show() {
235        if (mShowing) {
236            if (mDecor != null) {
237                if (mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) {
238                    mWindow.invalidatePanelMenu(Window.FEATURE_ACTION_BAR);
239                }
240                mDecor.setVisibility(View.VISIBLE);
241            }
242            return;
243        }
244
245        mCanceled = false;
246
247        if (!mCreated) {
248            dispatchOnCreate(null);
249        }
250
251        onStart();
252        mDecor = mWindow.getDecorView();
253
254        if (mActionBar == null && mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) {
255            mActionBar = new ActionBarImpl(this);
256        }
257
258        WindowManager.LayoutParams l = mWindow.getAttributes();
259        if ((l.softInputMode
260                & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) == 0) {
261            WindowManager.LayoutParams nl = new WindowManager.LayoutParams();
262            nl.copyFrom(l);
263            nl.softInputMode |=
264                    WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
265            l = nl;
266        }
267
268        try {
269            mWindowManager.addView(mDecor, l);
270            mShowing = true;
271
272            sendShowMessage();
273        } finally {
274        }
275    }
276
277    /**
278     * Hide the dialog, but do not dismiss it.
279     */
280    public void hide() {
281        if (mDecor != null) {
282            mDecor.setVisibility(View.GONE);
283        }
284    }
285
286    /**
287     * Dismiss this dialog, removing it from the screen. This method can be
288     * invoked safely from any thread.  Note that you should not override this
289     * method to do cleanup when the dialog is dismissed, instead implement
290     * that in {@link #onStop}.
291     */
292    public void dismiss() {
293        if (Thread.currentThread() != mUiThread) {
294            mHandler.post(mDismissAction);
295        } else {
296            mDismissAction.run();
297        }
298    }
299
300    private void dismissDialog() {
301        if (mDecor == null || !mShowing) {
302            return;
303        }
304
305        try {
306            mWindowManager.removeView(mDecor);
307        } finally {
308            mDecor = null;
309            mWindow.closeAllPanels();
310            onStop();
311            mShowing = false;
312
313            sendDismissMessage();
314        }
315    }
316
317    private void sendDismissMessage() {
318        if (mDismissMessage != null) {
319            // Obtain a new message so this dialog can be re-used
320            Message.obtain(mDismissMessage).sendToTarget();
321        }
322    }
323
324    private void sendShowMessage() {
325        if (mShowMessage != null) {
326            // Obtain a new message so this dialog can be re-used
327            Message.obtain(mShowMessage).sendToTarget();
328        }
329    }
330
331    // internal method to make sure mcreated is set properly without requiring
332    // users to call through to super in onCreate
333    void dispatchOnCreate(Bundle savedInstanceState) {
334        if (!mCreated) {
335            onCreate(savedInstanceState);
336            mCreated = true;
337        }
338    }
339
340    /**
341     * Similar to {@link Activity#onCreate}, you should initialize your dialog
342     * in this method, including calling {@link #setContentView}.
343     * @param savedInstanceState If this dialog is being reinitalized after a
344     *     the hosting activity was previously shut down, holds the result from
345     *     the most recent call to {@link #onSaveInstanceState}, or null if this
346     *     is the first time.
347     */
348    protected void onCreate(Bundle savedInstanceState) {
349    }
350
351    /**
352     * Called when the dialog is starting.
353     */
354    protected void onStart() {
355        if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(true);
356    }
357
358    /**
359     * Called to tell you that you're stopping.
360     */
361    protected void onStop() {
362        if (mActionBar != null) mActionBar.setShowHideAnimationEnabled(false);
363    }
364
365    private static final String DIALOG_SHOWING_TAG = "android:dialogShowing";
366    private static final String DIALOG_HIERARCHY_TAG = "android:dialogHierarchy";
367
368    /**
369     * Saves the state of the dialog into a bundle.
370     *
371     * The default implementation saves the state of its view hierarchy, so you'll
372     * likely want to call through to super if you override this to save additional
373     * state.
374     * @return A bundle with the state of the dialog.
375     */
376    public Bundle onSaveInstanceState() {
377        Bundle bundle = new Bundle();
378        bundle.putBoolean(DIALOG_SHOWING_TAG, mShowing);
379        if (mCreated) {
380            bundle.putBundle(DIALOG_HIERARCHY_TAG, mWindow.saveHierarchyState());
381        }
382        return bundle;
383    }
384
385    /**
386     * Restore the state of the dialog from a previously saved bundle.
387     *
388     * The default implementation restores the state of the dialog's view
389     * hierarchy that was saved in the default implementation of {@link #onSaveInstanceState()},
390     * so be sure to call through to super when overriding unless you want to
391     * do all restoring of state yourself.
392     * @param savedInstanceState The state of the dialog previously saved by
393     *     {@link #onSaveInstanceState()}.
394     */
395    public void onRestoreInstanceState(Bundle savedInstanceState) {
396        final Bundle dialogHierarchyState = savedInstanceState.getBundle(DIALOG_HIERARCHY_TAG);
397        if (dialogHierarchyState == null) {
398            // dialog has never been shown, or onCreated, nothing to restore.
399            return;
400        }
401        dispatchOnCreate(savedInstanceState);
402        mWindow.restoreHierarchyState(dialogHierarchyState);
403        if (savedInstanceState.getBoolean(DIALOG_SHOWING_TAG)) {
404            show();
405        }
406    }
407
408    /**
409     * Retrieve the current Window for the activity.  This can be used to
410     * directly access parts of the Window API that are not available
411     * through Activity/Screen.
412     *
413     * @return Window The current window, or null if the activity is not
414     *         visual.
415     */
416    public Window getWindow() {
417        return mWindow;
418    }
419
420    /**
421     * Call {@link android.view.Window#getCurrentFocus} on the
422     * Window if this Activity to return the currently focused view.
423     *
424     * @return View The current View with focus or null.
425     *
426     * @see #getWindow
427     * @see android.view.Window#getCurrentFocus
428     */
429    public View getCurrentFocus() {
430        return mWindow != null ? mWindow.getCurrentFocus() : null;
431    }
432
433    /**
434     * Finds a view that was identified by the id attribute from the XML that
435     * was processed in {@link #onStart}.
436     *
437     * @param id the identifier of the view to find
438     * @return The view if found or null otherwise.
439     */
440    public View findViewById(int id) {
441        return mWindow.findViewById(id);
442    }
443
444    /**
445     * Set the screen content from a layout resource.  The resource will be
446     * inflated, adding all top-level views to the screen.
447     *
448     * @param layoutResID Resource ID to be inflated.
449     */
450    public void setContentView(int layoutResID) {
451        mWindow.setContentView(layoutResID);
452    }
453
454    /**
455     * Set the screen content to an explicit view.  This view is placed
456     * directly into the screen's view hierarchy.  It can itself be a complex
457     * view hierarhcy.
458     *
459     * @param view The desired content to display.
460     */
461    public void setContentView(View view) {
462        mWindow.setContentView(view);
463    }
464
465    /**
466     * Set the screen content to an explicit view.  This view is placed
467     * directly into the screen's view hierarchy.  It can itself be a complex
468     * view hierarhcy.
469     *
470     * @param view The desired content to display.
471     * @param params Layout parameters for the view.
472     */
473    public void setContentView(View view, ViewGroup.LayoutParams params) {
474        mWindow.setContentView(view, params);
475    }
476
477    /**
478     * Add an additional content view to the screen.  Added after any existing
479     * ones in the screen -- existing views are NOT removed.
480     *
481     * @param view The desired content to display.
482     * @param params Layout parameters for the view.
483     */
484    public void addContentView(View view, ViewGroup.LayoutParams params) {
485        mWindow.addContentView(view, params);
486    }
487
488    /**
489     * Set the title text for this dialog's window.
490     *
491     * @param title The new text to display in the title.
492     */
493    public void setTitle(CharSequence title) {
494        mWindow.setTitle(title);
495        mWindow.getAttributes().setTitle(title);
496    }
497
498    /**
499     * Set the title text for this dialog's window. The text is retrieved
500     * from the resources with the supplied identifier.
501     *
502     * @param titleId the title's text resource identifier
503     */
504    public void setTitle(int titleId) {
505        setTitle(mContext.getText(titleId));
506    }
507
508    /**
509     * A key was pressed down.
510     *
511     * <p>If the focused view didn't want this event, this method is called.
512     *
513     * <p>The default implementation consumed the KEYCODE_BACK to later
514     * handle it in {@link #onKeyUp}.
515     *
516     * @see #onKeyUp
517     * @see android.view.KeyEvent
518     */
519    public boolean onKeyDown(int keyCode, KeyEvent event) {
520        if (keyCode == KeyEvent.KEYCODE_BACK) {
521            event.startTracking();
522            return true;
523        }
524
525        return false;
526    }
527
528    /**
529     * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent)
530     * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle
531     * the event).
532     */
533    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
534        return false;
535    }
536
537    /**
538     * A key was released.
539     *
540     * <p>The default implementation handles KEYCODE_BACK to close the
541     * dialog.
542     *
543     * @see #onKeyDown
544     * @see KeyEvent
545     */
546    public boolean onKeyUp(int keyCode, KeyEvent event) {
547        if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
548                && !event.isCanceled()) {
549            onBackPressed();
550            return true;
551        }
552        return false;
553    }
554
555    /**
556     * Default implementation of {@link KeyEvent.Callback#onKeyMultiple(int, int, KeyEvent)
557     * KeyEvent.Callback.onKeyMultiple()}: always returns false (doesn't handle
558     * the event).
559     */
560    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
561        return false;
562    }
563
564    /**
565     * Called when the dialog has detected the user's press of the back
566     * key.  The default implementation simply cancels the dialog (only if
567     * it is cancelable), but you can override this to do whatever you want.
568     */
569    public void onBackPressed() {
570        if (mCancelable) {
571            cancel();
572        }
573    }
574
575    /**
576     * Called when an key shortcut event is not handled by any of the views in the Dialog.
577     * Override this method to implement global key shortcuts for the Dialog.
578     * Key shortcuts can also be implemented by setting the
579     * {@link MenuItem#setShortcut(char, char) shortcut} property of menu items.
580     *
581     * @param keyCode The value in event.getKeyCode().
582     * @param event Description of the key event.
583     * @return True if the key shortcut was handled.
584     */
585    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
586        return false;
587    }
588
589    /**
590     * Called when a touch screen event was not handled by any of the views
591     * under it. This is most useful to process touch events that happen outside
592     * of your window bounds, where there is no view to receive it.
593     *
594     * @param event The touch screen event being processed.
595     * @return Return true if you have consumed the event, false if you haven't.
596     *         The default implementation will cancel the dialog when a touch
597     *         happens outside of the window bounds.
598     */
599    public boolean onTouchEvent(MotionEvent event) {
600        if (mCancelable && mShowing && mWindow.shouldCloseOnTouch(mContext, event)) {
601            cancel();
602            return true;
603        }
604
605        return false;
606    }
607
608    /**
609     * Called when the trackball was moved and not handled by any of the
610     * views inside of the activity.  So, for example, if the trackball moves
611     * while focus is on a button, you will receive a call here because
612     * buttons do not normally do anything with trackball events.  The call
613     * here happens <em>before</em> trackball movements are converted to
614     * DPAD key events, which then get sent back to the view hierarchy, and
615     * will be processed at the point for things like focus navigation.
616     *
617     * @param event The trackball event being processed.
618     *
619     * @return Return true if you have consumed the event, false if you haven't.
620     * The default implementation always returns false.
621     */
622    public boolean onTrackballEvent(MotionEvent event) {
623        return false;
624    }
625
626    /**
627     * Called when a generic motion event was not handled by any of the
628     * views inside of the dialog.
629     * <p>
630     * Generic motion events describe joystick movements, mouse hovers, track pad
631     * touches, scroll wheel movements and other input events.  The
632     * {@link MotionEvent#getSource() source} of the motion event specifies
633     * the class of input that was received.  Implementations of this method
634     * must examine the bits in the source before processing the event.
635     * The following code example shows how this is done.
636     * </p><p>
637     * Generic motion events with source class
638     * {@link android.view.InputDevice#SOURCE_CLASS_POINTER}
639     * are delivered to the view under the pointer.  All other generic motion events are
640     * delivered to the focused view.
641     * </p><p>
642     * See {@link View#onGenericMotionEvent(MotionEvent)} for an example of how to
643     * handle this event.
644     * </p>
645     *
646     * @param event The generic motion event being processed.
647     *
648     * @return Return true if you have consumed the event, false if you haven't.
649     * The default implementation always returns false.
650     */
651    public boolean onGenericMotionEvent(MotionEvent event) {
652        return false;
653    }
654
655    public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
656        if (mDecor != null) {
657            mWindowManager.updateViewLayout(mDecor, params);
658        }
659    }
660
661    public void onContentChanged() {
662    }
663
664    public void onWindowFocusChanged(boolean hasFocus) {
665    }
666
667    public void onAttachedToWindow() {
668    }
669
670    public void onDetachedFromWindow() {
671    }
672
673    /**
674     * Called to process key events.  You can override this to intercept all
675     * key events before they are dispatched to the window.  Be sure to call
676     * this implementation for key events that should be handled normally.
677     *
678     * @param event The key event.
679     *
680     * @return boolean Return true if this event was consumed.
681     */
682    public boolean dispatchKeyEvent(KeyEvent event) {
683        if ((mOnKeyListener != null) && (mOnKeyListener.onKey(this, event.getKeyCode(), event))) {
684            return true;
685        }
686        if (mWindow.superDispatchKeyEvent(event)) {
687            return true;
688        }
689        return event.dispatch(this, mDecor != null
690                ? mDecor.getKeyDispatcherState() : null, this);
691    }
692
693    /**
694     * Called to process a key shortcut event.
695     * You can override this to intercept all key shortcut events before they are
696     * dispatched to the window.  Be sure to call this implementation for key shortcut
697     * events that should be handled normally.
698     *
699     * @param event The key shortcut event.
700     * @return True if this event was consumed.
701     */
702    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
703        if (mWindow.superDispatchKeyShortcutEvent(event)) {
704            return true;
705        }
706        return onKeyShortcut(event.getKeyCode(), event);
707    }
708
709    /**
710     * Called to process touch screen events.  You can override this to
711     * intercept all touch screen events before they are dispatched to the
712     * window.  Be sure to call this implementation for touch screen events
713     * that should be handled normally.
714     *
715     * @param ev The touch screen event.
716     *
717     * @return boolean Return true if this event was consumed.
718     */
719    public boolean dispatchTouchEvent(MotionEvent ev) {
720        if (mWindow.superDispatchTouchEvent(ev)) {
721            return true;
722        }
723        return onTouchEvent(ev);
724    }
725
726    /**
727     * Called to process trackball events.  You can override this to
728     * intercept all trackball events before they are dispatched to the
729     * window.  Be sure to call this implementation for trackball events
730     * that should be handled normally.
731     *
732     * @param ev The trackball event.
733     *
734     * @return boolean Return true if this event was consumed.
735     */
736    public boolean dispatchTrackballEvent(MotionEvent ev) {
737        if (mWindow.superDispatchTrackballEvent(ev)) {
738            return true;
739        }
740        return onTrackballEvent(ev);
741    }
742
743    /**
744     * Called to process generic motion events.  You can override this to
745     * intercept all generic motion events before they are dispatched to the
746     * window.  Be sure to call this implementation for generic motion events
747     * that should be handled normally.
748     *
749     * @param ev The generic motion event.
750     *
751     * @return boolean Return true if this event was consumed.
752     */
753    public boolean dispatchGenericMotionEvent(MotionEvent ev) {
754        if (mWindow.superDispatchGenericMotionEvent(ev)) {
755            return true;
756        }
757        return onGenericMotionEvent(ev);
758    }
759
760    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
761        event.setClassName(getClass().getName());
762        event.setPackageName(mContext.getPackageName());
763
764        LayoutParams params = getWindow().getAttributes();
765        boolean isFullScreen = (params.width == LayoutParams.MATCH_PARENT) &&
766            (params.height == LayoutParams.MATCH_PARENT);
767        event.setFullScreen(isFullScreen);
768
769        return false;
770    }
771
772    /**
773     * @see Activity#onCreatePanelView(int)
774     */
775    public View onCreatePanelView(int featureId) {
776        return null;
777    }
778
779    /**
780     * @see Activity#onCreatePanelMenu(int, Menu)
781     */
782    public boolean onCreatePanelMenu(int featureId, Menu menu) {
783        if (featureId == Window.FEATURE_OPTIONS_PANEL) {
784            return onCreateOptionsMenu(menu);
785        }
786
787        return false;
788    }
789
790    /**
791     * @see Activity#onPreparePanel(int, View, Menu)
792     */
793    public boolean onPreparePanel(int featureId, View view, Menu menu) {
794        if (featureId == Window.FEATURE_OPTIONS_PANEL && menu != null) {
795            boolean goforit = onPrepareOptionsMenu(menu);
796            return goforit && menu.hasVisibleItems();
797        }
798        return true;
799    }
800
801    /**
802     * @see Activity#onMenuOpened(int, Menu)
803     */
804    public boolean onMenuOpened(int featureId, Menu menu) {
805        if (featureId == Window.FEATURE_ACTION_BAR) {
806            mActionBar.dispatchMenuVisibilityChanged(true);
807        }
808        return true;
809    }
810
811    /**
812     * @see Activity#onMenuItemSelected(int, MenuItem)
813     */
814    public boolean onMenuItemSelected(int featureId, MenuItem item) {
815        return false;
816    }
817
818    /**
819     * @see Activity#onPanelClosed(int, Menu)
820     */
821    public void onPanelClosed(int featureId, Menu menu) {
822        if (featureId == Window.FEATURE_ACTION_BAR) {
823            mActionBar.dispatchMenuVisibilityChanged(false);
824        }
825    }
826
827    /**
828     * It is usually safe to proxy this call to the owner activity's
829     * {@link Activity#onCreateOptionsMenu(Menu)} if the client desires the same
830     * menu for this Dialog.
831     *
832     * @see Activity#onCreateOptionsMenu(Menu)
833     * @see #getOwnerActivity()
834     */
835    public boolean onCreateOptionsMenu(Menu menu) {
836        return true;
837    }
838
839    /**
840     * It is usually safe to proxy this call to the owner activity's
841     * {@link Activity#onPrepareOptionsMenu(Menu)} if the client desires the
842     * same menu for this Dialog.
843     *
844     * @see Activity#onPrepareOptionsMenu(Menu)
845     * @see #getOwnerActivity()
846     */
847    public boolean onPrepareOptionsMenu(Menu menu) {
848        return true;
849    }
850
851    /**
852     * @see Activity#onOptionsItemSelected(MenuItem)
853     */
854    public boolean onOptionsItemSelected(MenuItem item) {
855        return false;
856    }
857
858    /**
859     * @see Activity#onOptionsMenuClosed(Menu)
860     */
861    public void onOptionsMenuClosed(Menu menu) {
862    }
863
864    /**
865     * @see Activity#openOptionsMenu()
866     */
867    public void openOptionsMenu() {
868        mWindow.openPanel(Window.FEATURE_OPTIONS_PANEL, null);
869    }
870
871    /**
872     * @see Activity#closeOptionsMenu()
873     */
874    public void closeOptionsMenu() {
875        mWindow.closePanel(Window.FEATURE_OPTIONS_PANEL);
876    }
877
878    /**
879     * @see Activity#invalidateOptionsMenu()
880     */
881    public void invalidateOptionsMenu() {
882        mWindow.invalidatePanelMenu(Window.FEATURE_OPTIONS_PANEL);
883    }
884
885    /**
886     * @see Activity#onCreateContextMenu(ContextMenu, View, ContextMenuInfo)
887     */
888    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
889    }
890
891    /**
892     * @see Activity#registerForContextMenu(View)
893     */
894    public void registerForContextMenu(View view) {
895        view.setOnCreateContextMenuListener(this);
896    }
897
898    /**
899     * @see Activity#unregisterForContextMenu(View)
900     */
901    public void unregisterForContextMenu(View view) {
902        view.setOnCreateContextMenuListener(null);
903    }
904
905    /**
906     * @see Activity#openContextMenu(View)
907     */
908    public void openContextMenu(View view) {
909        view.showContextMenu();
910    }
911
912    /**
913     * @see Activity#onContextItemSelected(MenuItem)
914     */
915    public boolean onContextItemSelected(MenuItem item) {
916        return false;
917    }
918
919    /**
920     * @see Activity#onContextMenuClosed(Menu)
921     */
922    public void onContextMenuClosed(Menu menu) {
923    }
924
925    /**
926     * This hook is called when the user signals the desire to start a search.
927     */
928    public boolean onSearchRequested() {
929        final SearchManager searchManager = (SearchManager) mContext
930                .getSystemService(Context.SEARCH_SERVICE);
931
932        // associate search with owner activity
933        final ComponentName appName = getAssociatedActivity();
934        if (appName != null && searchManager.getSearchableInfo(appName) != null) {
935            searchManager.startSearch(null, false, appName, null, false);
936            dismiss();
937            return true;
938        } else {
939            return false;
940        }
941    }
942
943    public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
944        if (mActionBar != null) {
945            return mActionBar.startActionMode(callback);
946        }
947        return null;
948    }
949
950    public void onActionModeStarted(ActionMode mode) {
951    }
952
953    public void onActionModeFinished(ActionMode mode) {
954    }
955
956    /**
957     * @return The activity associated with this dialog, or null if there is no associated activity.
958     */
959    private ComponentName getAssociatedActivity() {
960        Activity activity = mOwnerActivity;
961        Context context = getContext();
962        while (activity == null && context != null) {
963            if (context instanceof Activity) {
964                activity = (Activity) context;  // found it!
965            } else {
966                context = (context instanceof ContextWrapper) ?
967                        ((ContextWrapper) context).getBaseContext() : // unwrap one level
968                        null;                                         // done
969            }
970        }
971        return activity == null ? null : activity.getComponentName();
972    }
973
974
975    /**
976     * Request that key events come to this dialog. Use this if your
977     * dialog has no views with focus, but the dialog still wants
978     * a chance to process key events.
979     *
980     * @param get true if the dialog should receive key events, false otherwise
981     * @see android.view.Window#takeKeyEvents
982     */
983    public void takeKeyEvents(boolean get) {
984        mWindow.takeKeyEvents(get);
985    }
986
987    /**
988     * Enable extended window features.  This is a convenience for calling
989     * {@link android.view.Window#requestFeature getWindow().requestFeature()}.
990     *
991     * @param featureId The desired feature as defined in
992     *                  {@link android.view.Window}.
993     * @return Returns true if the requested feature is supported and now
994     *         enabled.
995     *
996     * @see android.view.Window#requestFeature
997     */
998    public final boolean requestWindowFeature(int featureId) {
999        return getWindow().requestFeature(featureId);
1000    }
1001
1002    /**
1003     * Convenience for calling
1004     * {@link android.view.Window#setFeatureDrawableResource}.
1005     */
1006    public final void setFeatureDrawableResource(int featureId, int resId) {
1007        getWindow().setFeatureDrawableResource(featureId, resId);
1008    }
1009
1010    /**
1011     * Convenience for calling
1012     * {@link android.view.Window#setFeatureDrawableUri}.
1013     */
1014    public final void setFeatureDrawableUri(int featureId, Uri uri) {
1015        getWindow().setFeatureDrawableUri(featureId, uri);
1016    }
1017
1018    /**
1019     * Convenience for calling
1020     * {@link android.view.Window#setFeatureDrawable(int, Drawable)}.
1021     */
1022    public final void setFeatureDrawable(int featureId, Drawable drawable) {
1023        getWindow().setFeatureDrawable(featureId, drawable);
1024    }
1025
1026    /**
1027     * Convenience for calling
1028     * {@link android.view.Window#setFeatureDrawableAlpha}.
1029     */
1030    public final void setFeatureDrawableAlpha(int featureId, int alpha) {
1031        getWindow().setFeatureDrawableAlpha(featureId, alpha);
1032    }
1033
1034    public LayoutInflater getLayoutInflater() {
1035        return getWindow().getLayoutInflater();
1036    }
1037
1038    /**
1039     * Sets whether this dialog is cancelable with the
1040     * {@link KeyEvent#KEYCODE_BACK BACK} key.
1041     */
1042    public void setCancelable(boolean flag) {
1043        mCancelable = flag;
1044    }
1045
1046    /**
1047     * Sets whether this dialog is canceled when touched outside the window's
1048     * bounds. If setting to true, the dialog is set to be cancelable if not
1049     * already set.
1050     *
1051     * @param cancel Whether the dialog should be canceled when touched outside
1052     *            the window.
1053     */
1054    public void setCanceledOnTouchOutside(boolean cancel) {
1055        if (cancel && !mCancelable) {
1056            mCancelable = true;
1057        }
1058
1059        mWindow.setCloseOnTouchOutside(cancel);
1060    }
1061
1062    /**
1063     * Cancel the dialog.  This is essentially the same as calling {@link #dismiss()}, but it will
1064     * also call your {@link DialogInterface.OnCancelListener} (if registered).
1065     */
1066    public void cancel() {
1067        if (!mCanceled && mCancelMessage != null) {
1068            mCanceled = true;
1069            // Obtain a new message so this dialog can be re-used
1070            Message.obtain(mCancelMessage).sendToTarget();
1071        }
1072        dismiss();
1073    }
1074
1075    /**
1076     * Set a listener to be invoked when the dialog is canceled.
1077     * <p>
1078     * This will only be invoked when the dialog is canceled, if the creator
1079     * needs to know when it is dismissed in general, use
1080     * {@link #setOnDismissListener}.
1081     *
1082     * @param listener The {@link DialogInterface.OnCancelListener} to use.
1083     */
1084    public void setOnCancelListener(final OnCancelListener listener) {
1085        if (mCancelAndDismissTaken != null) {
1086            throw new IllegalStateException(
1087                    "OnCancelListener is already taken by "
1088                    + mCancelAndDismissTaken + " and can not be replaced.");
1089        }
1090        if (listener != null) {
1091            mCancelMessage = mListenersHandler.obtainMessage(CANCEL, listener);
1092        } else {
1093            mCancelMessage = null;
1094        }
1095    }
1096
1097    /**
1098     * Set a message to be sent when the dialog is canceled.
1099     * @param msg The msg to send when the dialog is canceled.
1100     * @see #setOnCancelListener(android.content.DialogInterface.OnCancelListener)
1101     */
1102    public void setCancelMessage(final Message msg) {
1103        mCancelMessage = msg;
1104    }
1105
1106    /**
1107     * Set a listener to be invoked when the dialog is dismissed.
1108     * @param listener The {@link DialogInterface.OnDismissListener} to use.
1109     */
1110    public void setOnDismissListener(final OnDismissListener listener) {
1111        if (mCancelAndDismissTaken != null) {
1112            throw new IllegalStateException(
1113                    "OnDismissListener is already taken by "
1114                    + mCancelAndDismissTaken + " and can not be replaced.");
1115        }
1116        if (listener != null) {
1117            mDismissMessage = mListenersHandler.obtainMessage(DISMISS, listener);
1118        } else {
1119            mDismissMessage = null;
1120        }
1121    }
1122
1123    /**
1124     * Sets a listener to be invoked when the dialog is shown.
1125     * @param listener The {@link DialogInterface.OnShowListener} to use.
1126     */
1127    public void setOnShowListener(OnShowListener listener) {
1128        if (listener != null) {
1129            mShowMessage = mListenersHandler.obtainMessage(SHOW, listener);
1130        } else {
1131            mShowMessage = null;
1132        }
1133    }
1134
1135    /**
1136     * Set a message to be sent when the dialog is dismissed.
1137     * @param msg The msg to send when the dialog is dismissed.
1138     */
1139    public void setDismissMessage(final Message msg) {
1140        mDismissMessage = msg;
1141    }
1142
1143    /** @hide */
1144    public boolean takeCancelAndDismissListeners(String msg, final OnCancelListener cancel,
1145            final OnDismissListener dismiss) {
1146        if (mCancelAndDismissTaken != null) {
1147            mCancelAndDismissTaken = null;
1148        } else if (mCancelMessage != null || mDismissMessage != null) {
1149            return false;
1150        }
1151
1152        setOnCancelListener(cancel);
1153        setOnDismissListener(dismiss);
1154        mCancelAndDismissTaken = msg;
1155
1156        return true;
1157    }
1158
1159    /**
1160     * By default, this will use the owner Activity's suggested stream type.
1161     *
1162     * @see Activity#setVolumeControlStream(int)
1163     * @see #setOwnerActivity(Activity)
1164     */
1165    public final void setVolumeControlStream(int streamType) {
1166        getWindow().setVolumeControlStream(streamType);
1167    }
1168
1169    /**
1170     * @see Activity#getVolumeControlStream()
1171     */
1172    public final int getVolumeControlStream() {
1173        return getWindow().getVolumeControlStream();
1174    }
1175
1176    /**
1177     * Sets the callback that will be called if a key is dispatched to the dialog.
1178     */
1179    public void setOnKeyListener(final OnKeyListener onKeyListener) {
1180        mOnKeyListener = onKeyListener;
1181    }
1182
1183    private static final class ListenersHandler extends Handler {
1184        private WeakReference<DialogInterface> mDialog;
1185
1186        public ListenersHandler(Dialog dialog) {
1187            mDialog = new WeakReference<DialogInterface>(dialog);
1188        }
1189
1190        @Override
1191        public void handleMessage(Message msg) {
1192            switch (msg.what) {
1193                case DISMISS:
1194                    ((OnDismissListener) msg.obj).onDismiss(mDialog.get());
1195                    break;
1196                case CANCEL:
1197                    ((OnCancelListener) msg.obj).onCancel(mDialog.get());
1198                    break;
1199                case SHOW:
1200                    ((OnShowListener) msg.obj).onShow(mDialog.get());
1201                    break;
1202            }
1203        }
1204    }
1205}
1206