]> nv-tegra.nvidia Code Review - android/platform/packages/apps/Phone.git/blob - src/com/android/phone/InCallScreen.java
074942f7082b8745786c0c880d7de74b5a6c6b4d
[android/platform/packages/apps/Phone.git] / src / com / android / phone / InCallScreen.java
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
17 package com.android.phone;
18
19 import com.android.internal.telephony.Call;
20 import com.android.internal.telephony.CallerInfo;
21 import com.android.internal.telephony.CallerInfoAsyncQuery;
22 import com.android.internal.telephony.Connection;
23 import com.android.internal.telephony.MmiCode;
24 import com.android.internal.telephony.Phone;
25
26 import android.app.Activity;
27 import android.app.AlertDialog;
28 import android.app.Dialog;
29 import android.bluetooth.BluetoothHeadset;
30 import android.content.BroadcastReceiver;
31 import android.content.Context;
32 import android.content.DialogInterface;
33 import android.content.DialogInterface.OnCancelListener;
34 import android.content.Intent;
35 import android.content.IntentFilter;
36 import android.content.res.Configuration;
37 import android.content.res.Resources;
38 import android.graphics.Typeface;
39 import android.media.AudioManager;
40 import android.os.AsyncResult;
41 import android.os.Bundle;
42 import android.os.Handler;
43 import android.os.Message;
44 import android.os.SystemClock;
45 import android.os.SystemProperties;
46 import android.provider.Checkin;
47 import android.provider.Settings;
48 import android.telephony.PhoneNumberUtils;
49 import android.telephony.ServiceState;
50 import android.text.TextUtils;
51 import android.text.method.DialerKeyListener;
52 import android.util.Log;
53 import android.view.KeyEvent;
54 import android.view.Menu;
55 import android.view.MotionEvent;
56 import android.view.View;
57 import android.view.ViewConfiguration;
58 import android.view.ViewGroup;
59 import android.view.Window;
60 import android.view.WindowManager;
61 import android.view.animation.Animation;
62 import android.view.animation.AnimationUtils;
63 import android.widget.Button;
64 import android.widget.Chronometer;
65 import android.widget.EditText;
66 import android.widget.ImageButton;
67 import android.widget.LinearLayout;
68 import android.widget.SlidingDrawer;
69 import android.widget.TextView;
70 import android.widget.Toast;
71
72 import java.util.List;
73
74 /**
75  * Phone app "in call" screen.
76  */
77 public class InCallScreen extends Activity
78         implements View.OnClickListener, View.OnTouchListener,
79                 CallerInfoAsyncQuery.OnQueryCompleteListener {
80     private static final String LOG_TAG = "InCallScreen";
81
82     private static final boolean DBG =
83             (PhoneApp.DBG_LEVEL >= 1) && (SystemProperties.getInt("ro.debuggable", 0) == 1);
84     private static final boolean VDBG = (PhoneApp.DBG_LEVEL >= 2);
85
86     // Enable detailed logs of user actions while on the in-call screen.
87     // TODO: For now this is totally disabled.  But for future user
88     // research, we should change the PHONE_UI_EVENT_* events to use
89     // android.util.EventLog rather than Checkin.logEvent, so that we can
90     // select which of those events to upload on a tag-by-tag basis
91     // (which means that we could actually ship devices with this logging
92     // enabled.)
93     /* package */ static final boolean ENABLE_PHONE_UI_EVENT_LOGGING = false;
94
95     /**
96      * Intent extra used to specify whether the DTMF dialpad should be
97      * initially visible when bringing up the InCallScreen.  (If this
98      * extra is present, the dialpad will be initially shown if the extra
99      * has the boolean value true, and initially hidden otherwise.)
100      */
101     static final String SHOW_DIALPAD_EXTRA = "com.android.phone.ShowDialpad";
102
103     // Event values used with Checkin.Events.Tag.PHONE_UI events:
104     /** The in-call UI became active */
105     static final String PHONE_UI_EVENT_ENTER = "enter";
106     /** User exited the in-call UI */
107     static final String PHONE_UI_EVENT_EXIT = "exit";
108     /** User clicked one of the touchable in-call buttons */
109     static final String PHONE_UI_EVENT_BUTTON_CLICK = "button_click";
110
111     // Amount of time (in msec) that we display the "Call ended" state.
112     // The "short" value is for calls ended by the local user, and the
113     // "long" value is for calls ended by the remote caller.
114     private static final int CALL_ENDED_SHORT_DELAY =  200;  // msec
115     private static final int CALL_ENDED_LONG_DELAY = 2000;  // msec
116
117     // Amount of time (in msec) that we keep the in-call menu onscreen
118     // *after* the user changes the state of one of the toggle buttons.
119     private static final int MENU_DISMISS_DELAY =  1000;  // msec
120
121     // The "touch lock" overlay timeout comes from Gservices; this is the default.
122     private static final int TOUCH_LOCK_DELAY_DEFAULT =  6000;  // msec
123
124     // See CallTracker.MAX_CONNECTIONS_PER_CALL
125     private static final int MAX_CALLERS_IN_CONFERENCE = 5;
126
127     // Message codes; see mHandler below.
128     // Note message codes < 100 are reserved for the PhoneApp.
129     private static final int PHONE_STATE_CHANGED = 101;
130     private static final int PHONE_DISCONNECT = 102;
131     private static final int EVENT_HEADSET_PLUG_STATE_CHANGED = 103;
132     private static final int POST_ON_DIAL_CHARS = 104;
133     private static final int WILD_PROMPT_CHAR_ENTERED = 105;
134     private static final int ADD_VOICEMAIL_NUMBER = 106;
135     private static final int DONT_ADD_VOICEMAIL_NUMBER = 107;
136     private static final int DELAYED_CLEANUP_AFTER_DISCONNECT = 108;
137     private static final int SUPP_SERVICE_FAILED = 110;
138     private static final int DISMISS_MENU = 111;
139     private static final int ALLOW_SCREEN_ON = 112;
140     private static final int TOUCH_LOCK_TIMER = 113;
141     private static final int BLUETOOTH_STATE_CHANGED = 114;
142
143
144     // High-level "modes" of the in-call UI.
145     private enum InCallScreenMode {
146         /**
147          * Normal in-call UI elements visible.
148          */
149         NORMAL,
150         /**
151          * "Manage conference" UI is visible, totally replacing the
152          * normal in-call UI.
153          */
154         MANAGE_CONFERENCE,
155         /**
156          * Non-interactive UI state.  Call card is visible,
157          * displaying information about the call that just ended.
158          */
159         CALL_ENDED
160     }
161     private InCallScreenMode mInCallScreenMode;
162
163     // Possible error conditions that can happen on startup.
164     // These are returned as status codes from the various helper
165     // functions we call from onCreate() and/or onResume().
166     // See syncWithPhoneState() and checkIfOkToInitiateOutgoingCall() for details.
167     private enum InCallInitStatus {
168         SUCCESS,
169         VOICEMAIL_NUMBER_MISSING,
170         POWER_OFF,
171         EMERGENCY_ONLY,
172         PHONE_NOT_IN_USE,
173         NO_PHONE_NUMBER_SUPPLIED,
174         DIALED_MMI,
175         CALL_FAILED
176     }
177     private InCallInitStatus mInCallInitialStatus;  // see onResume()
178
179     private boolean mRegisteredForPhoneStates;
180
181     private Phone mPhone;
182     private Call mForegroundCall;
183     private Call mBackgroundCall;
184     private Call mRingingCall;
185
186     private BluetoothHandsfree mBluetoothHandsfree;
187     private BluetoothHeadset mBluetoothHeadset;
188     private boolean mBluetoothConnectionPending;
189     private long mBluetoothConnectionRequestTime;
190
191     // Main in-call UI ViewGroups
192     private ViewGroup mMainFrame;
193     private ViewGroup mInCallPanel;
194
195     // Menu button hint below the "main frame"
196     private TextView mMenuButtonHint;
197
198     // Main in-call UI elements:
199     private CallCard mCallCard;
200     private InCallMenu mInCallMenu;  // created lazily on first MENU keypress
201
202     /**
203      * DTMF Dialer objects, including the model and the sliding drawer / dialer
204      * UI container and the dialer display field for landscape presentation.
205      */
206     private DTMFTwelveKeyDialer mDialer;
207     private SlidingDrawer mDialerDrawer;
208     private EditText mDTMFDisplay;
209
210     // "Manage conference" UI elements
211     private ViewGroup mManageConferencePanel;
212     private Button mButtonManageConferenceDone;
213     private ViewGroup[] mConferenceCallList;
214     private int mNumCallersInConference;
215     private Chronometer mConferenceTime;
216
217     private EditText mWildPromptText;
218
219     // "Touch lock" overlay graphic
220     private View mTouchLockOverlay;  // The overlay over the whole screen
221     private View mTouchLockIcon;  // The "lock" icon in the middle of the screen
222     private Animation mTouchLockFadeIn;
223     private long mTouchLockLastTouchTime;  // in SystemClock.uptimeMillis() time base
224
225     // Various dialogs we bring up (see dismissAllDialogs())
226     // The MMI started dialog can actually be one of 2 items:
227     //   1. An alert dialog if the MMI code is a normal MMI
228     //   2. A progress dialog if the user requested a USSD
229     private Dialog mMmiStartedDialog;
230     private AlertDialog mMissingVoicemailDialog;
231     private AlertDialog mGenericErrorDialog;
232     private AlertDialog mSuppServiceFailureDialog;
233     private AlertDialog mWaitPromptDialog;
234     private AlertDialog mWildPromptDialog;
235
236     // TODO: If the Activity class ever provides an easy way to get the
237     // current "activity lifecycle" state, we can remove these flags.
238     private boolean mIsDestroyed = false;
239     private boolean mIsForegroundActivity = false;
240
241     // Flag indicating whether or not we should bring up the Call Log when
242     // exiting the in-call UI due to the Phone becoming idle.  (This is
243     // true if the most recently disconnected Call was initiated by the
244     // user, or false if it was an incoming call.)
245     // This flag is used by delayedCleanupAfterDisconnect(), and is set by
246     // onDisconnect() (which is the only place that either posts a
247     // DELAYED_CLEANUP_AFTER_DISCONNECT event *or* calls
248     // delayedCleanupAfterDisconnect() directly.)
249     private boolean mShowCallLogAfterDisconnect;
250
251     private Handler mHandler = new Handler() {
252         @Override
253         public void handleMessage(Message msg) {
254             if (mIsDestroyed) {
255                 if (DBG) log("Handler: ignoring message " + msg + "; we're destroyed!");
256                 return;
257             }
258             if (!mIsForegroundActivity) {
259                 if (DBG) log("Handler: handling message " + msg + " while not in foreground");
260                 // Continue anyway; some of the messages below *want* to
261                 // be handled even if we're not the foreground activity
262                 // (like DELAYED_CLEANUP_AFTER_DISCONNECT), and they all
263                 // should at least be safe to handle if we're not in the
264                 // foreground...
265             }
266
267             switch (msg.what) {
268                 case SUPP_SERVICE_FAILED:
269                     onSuppServiceFailed((AsyncResult) msg.obj);
270                     break;
271
272                 case PHONE_STATE_CHANGED:
273                     onPhoneStateChanged((AsyncResult) msg.obj);
274                     break;
275
276                 case PHONE_DISCONNECT:
277                     onDisconnect((AsyncResult) msg.obj);
278                     break;
279
280                 case EVENT_HEADSET_PLUG_STATE_CHANGED:
281                     // Update the in-call UI, since some UI elements (in
282                     // particular the "Speaker" menu button) change state
283                     // depending on whether a headset is plugged in.
284                     // TODO: A full updateScreen() is overkill here, since
285                     // the value of PhoneApp.isHeadsetPlugged() only affects a
286                     // single menu item.  (But even a full updateScreen()
287                     // is still pretty cheap, so let's keep this simple
288                     // for now.)
289                     if (msg.arg1 != 1 && !isBluetoothAudioConnected()){
290                         // If the state is "not connected", restore the speaker state.
291                         // We ONLY want to do this on the wired headset connect /
292                         // disconnect events for now though, so we're only triggering
293                         // on EVENT_HEADSET_PLUG_STATE_CHANGED.
294                         PhoneUtils.restoreSpeakerMode(getApplicationContext());
295                     }
296                     updateScreen();
297                     break;
298
299                 case PhoneApp.MMI_INITIATE:
300                     onMMIInitiate((AsyncResult) msg.obj);
301                     break;
302
303                 case PhoneApp.MMI_CANCEL:
304                     onMMICancel();
305                     break;
306
307                 // handle the mmi complete message.
308                 // since the message display class has been replaced with
309                 // a system dialog in PhoneUtils.displayMMIComplete(), we
310                 // should finish the activity here to close the window.
311                 case PhoneApp.MMI_COMPLETE:
312                     // Check the code to see if the request is ready to
313                     // finish, this includes any MMI state that is not
314                     // PENDING.
315                     MmiCode mmiCode = (MmiCode) ((AsyncResult) msg.obj).result;
316                     // if phone is a CDMA phone display feature code completed message
317                     if (mPhone.getPhoneName() == "CDMA") {
318                         PhoneUtils.displayMMIComplete(mPhone, PhoneApp.getInstance(), mmiCode, null, null);
319                     } else {
320                         if (mmiCode.getState() != MmiCode.State.PENDING) {
321                             if (DBG) log("Got MMI_COMPLETE, finishing...");
322                             finish();
323                         }
324                     }
325                     break;
326
327                 case POST_ON_DIAL_CHARS:
328                     handlePostOnDialChars((AsyncResult) msg.obj, (char) msg.arg1);
329                     break;
330
331                 case ADD_VOICEMAIL_NUMBER:
332                     addVoiceMailNumberPanel();
333                     break;
334
335                 case DONT_ADD_VOICEMAIL_NUMBER:
336                     dontAddVoiceMailNumber();
337                     break;
338
339                 case DELAYED_CLEANUP_AFTER_DISCONNECT:
340                     delayedCleanupAfterDisconnect();
341                     break;
342
343                 case DISMISS_MENU:
344                     // dismissMenu() has no effect if the menu is already closed.
345                     dismissMenu(true);  // dismissImmediate = true
346                     break;
347
348                 case ALLOW_SCREEN_ON:
349                     if (VDBG) log("ALLOW_SCREEN_ON message...");
350                     // Undo our previous call to preventScreenOn(true).
351                     // (Note this will cause the screen to turn on
352                     // immediately, if it's currently off because of a
353                     // prior preventScreenOn(true) call.)
354                     PhoneApp.getInstance().preventScreenOn(false);
355                     break;
356
357                 case TOUCH_LOCK_TIMER:
358                     if (VDBG) log("TOUCH_LOCK_TIMER...");
359                     touchLockTimerExpired();
360                     break;
361
362                 case BLUETOOTH_STATE_CHANGED:
363                     if (VDBG) log("BLUETOOTH_STATE_CHANGED...");
364                     // The bluetooth headset state changed, so some UI
365                     // elements may need to update.  (There's no need to
366                     // look up the current state here, since any UI
367                     // elements that care about the bluetooth state get it
368                     // directly from PhoneApp.showBluetoothIndication().)
369                     updateScreen();
370                     break;
371             }
372         }
373     };
374
375     private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
376             @Override
377             public void onReceive(Context context, Intent intent) {
378                 String action = intent.getAction();
379                 if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
380                     // Listen for ACTION_HEADSET_PLUG broadcasts so that we
381                     // can update the onscreen UI when the headset state changes.
382                     // if (DBG) log("mReceiver: ACTION_HEADSET_PLUG");
383                     // if (DBG) log("==> intent: " + intent);
384                     // if (DBG) log("    state: " + intent.getIntExtra("state", 0));
385                     // if (DBG) log("    name: " + intent.getStringExtra("name"));
386                     // send the event and add the state as an argument.
387                     Message message = Message.obtain(mHandler, EVENT_HEADSET_PLUG_STATE_CHANGED,
388                             intent.getIntExtra("state", 0), 0);
389                     mHandler.sendMessage(message);
390                 }
391             }
392         };
393
394
395     @Override
396     protected void onCreate(Bundle icicle) {
397         if (DBG) log("onCreate()...  this = " + this);
398
399         Profiler.callScreenOnCreate();
400
401         super.onCreate(icicle);
402
403         final PhoneApp app = PhoneApp.getInstance();
404         app.setInCallScreenInstance(this);
405
406         setPhone(app.phone);  // Sets mPhone and mForegroundCall/mBackgroundCall/mRingingCall
407
408         mBluetoothHandsfree = app.getBluetoothHandsfree();
409         if (VDBG) log("- mBluetoothHandsfree: " + mBluetoothHandsfree);
410
411         if (mBluetoothHandsfree != null) {
412             // The PhoneApp only creates a BluetoothHandsfree instance in the
413             // first place if getSystemService(Context.BLUETOOTH_SERVICE)
414             // succeeds.  So at this point we know the device is BT-capable.
415             mBluetoothHeadset = new BluetoothHeadset(this, null);
416             if (VDBG) log("- Got BluetoothHeadset: " + mBluetoothHeadset);
417         }
418
419         requestWindowFeature(Window.FEATURE_NO_TITLE);
420
421         // Inflate everything in incall_screen.xml and add it to the screen.
422         setContentView(R.layout.incall_screen);
423         mDialerDrawer = (SlidingDrawer) findViewById(R.id.dialer_container);
424
425         initInCallScreen();
426
427         // Create the dtmf dialer.  Note that mDialer is instantiated
428         // regardless of screen orientation, although the onscreen touchable
429         // dialpad is used only in portrait mode.
430         mDialer = new DTMFTwelveKeyDialer(this);
431
432         registerForPhoneStates();
433
434         // No need to change wake state here; that happens in onResume() when we
435         // are actually displayed.
436
437         // Handle the Intent we were launched with, but only if this is the
438         // the very first time we're being launched (ie. NOT if we're being
439         // re-initialized after previously being shut down.)
440         // Once we're up and running, any future Intents we need
441         // to handle will come in via the onNewIntent() method.
442         if (icicle == null) {
443             if (DBG) log("onCreate(): this is our very first launch, checking intent...");
444
445             // Stash the result code from internalResolveIntent() in the
446             // mInCallInitialStatus field.  If it's an error code, we'll
447             // handle it in onResume().
448             mInCallInitialStatus = internalResolveIntent(getIntent());
449             if (mInCallInitialStatus != InCallInitStatus.SUCCESS) {
450                 Log.w(LOG_TAG, "onCreate: status " + mInCallInitialStatus
451                       + " from internalResolveIntent()");
452                 // See onResume() for the actual error handling.
453             }
454         } else {
455             mInCallInitialStatus = InCallInitStatus.SUCCESS;
456         }
457
458         // When in landscape mode, the user can enter dtmf tones
459         // at any time.  We need to make sure the DTMFDialer is
460         // setup correctly.
461         if (ConfigurationHelper.isLandscape()) {
462             mDialer.startDialerSession();
463             if (VDBG) log("Dialer initialized (in landscape mode).");
464         }
465
466         Profiler.callScreenCreated();
467     }
468
469     /**
470      * Sets the Phone object used internally by the InCallScreen.
471      *
472      * In normal operation this is called from onCreate(), and the
473      * passed-in Phone object comes from the PhoneApp.
474      * For testing, test classes can use this method to
475      * inject a test Phone instance.
476      */
477     /* package */ void setPhone(Phone phone) {
478         mPhone = phone;
479         // Hang onto the three Call objects too; they're singletons that
480         // are constant (and never null) for the life of the Phone.
481         mForegroundCall = mPhone.getForegroundCall();
482         mBackgroundCall = mPhone.getBackgroundCall();
483         mRingingCall = mPhone.getRingingCall();
484     }
485
486     @Override
487     protected void onResume() {
488         if (DBG) log("onResume()...");
489         super.onResume();
490
491         mIsForegroundActivity = true;
492
493         final PhoneApp app = PhoneApp.getInstance();
494
495         // Disable the keyguard the entire time the InCallScreen is
496         // active.  (This is necessary only for the case of receiving an
497         // incoming call while the device is locked; we need to disable
498         // the keyguard so you can answer the call and use the in-call UI,
499         // but we always re-enable the keyguard as soon as you leave this
500         // screen (see onPause().))
501         app.disableKeyguard();
502
503         // Touch events are never considered "user activity" while the
504         // InCallScreen is active, so that unintentional touches won't
505         // prevent the device from going to sleep.
506         app.setIgnoreTouchUserActivity(true);
507
508         // Disable the status bar "window shade" the entire time we're on
509         // the in-call screen.
510         NotificationMgr.getDefault().getStatusBarMgr().enableExpandedView(false);
511
512         // Listen for broadcast intents that might affect the onscreen UI.
513         registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
514
515         // Check for any failures that happened during onCreate() or onNewIntent().
516         if (DBG) log("- onResume: initial status = " + mInCallInitialStatus);
517         if (mInCallInitialStatus != InCallInitStatus.SUCCESS) {
518             if (DBG) log("- onResume: failure during startup: " + mInCallInitialStatus);
519
520             // Don't bring up the regular Phone UI!  Instead bring up
521             // something more specific to let the user deal with the
522             // problem.
523             handleStartupError(mInCallInitialStatus);
524
525             // But it *is* OK to continue with the rest of onResume(),
526             // since any further setup steps (like updateScreen() and the
527             // CallCard setup) will fall back to a "blank" state if the
528             // phone isn't in use.
529             mInCallInitialStatus = InCallInitStatus.SUCCESS;
530         }
531
532         // Set the volume control handler while we are in the foreground.
533         if (isBluetoothAudioConnected()) {
534             setVolumeControlStream(AudioManager.STREAM_BLUETOOTH_SCO);
535         } else {
536             setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
537         }
538
539         takeKeyEvents(true);
540
541         // Always start off in NORMAL mode.
542         setInCallScreenMode(InCallScreenMode.NORMAL);
543
544         // Before checking the state of the phone, clean up any
545         // connections in the DISCONNECTED state.
546         // (The DISCONNECTED state is used only to drive the "call ended"
547         // UI; it's totally useless when *entering* the InCallScreen.)
548         mPhone.clearDisconnected();
549
550         InCallInitStatus status = syncWithPhoneState();
551         if (status != InCallInitStatus.SUCCESS) {
552             if (DBG) log("- syncWithPhoneState failed! status = " + status);
553             // Couldn't update the UI, presumably because the phone is totally
554             // idle.  But don't finish() immediately, since we might still
555             // have an error dialog up that the user needs to see.
556             // (And in that case, the error dialog is responsible for calling
557             // finish() when the user dismisses it.)
558         }
559
560         if (ENABLE_PHONE_UI_EVENT_LOGGING) {
561             // InCallScreen is now active.
562             Checkin.logEvent(getContentResolver(),
563                              Checkin.Events.Tag.PHONE_UI,
564                              PHONE_UI_EVENT_ENTER);
565         }
566
567         // Update the poke lock and wake lock when we move to
568         // the foreground.
569         //
570         // But we need to do something special if we're coming
571         // to the foreground while an incoming call is ringing:
572         if (mPhone.getState() == Phone.State.RINGING) {
573             // If the phone is ringing, we *should* already be holding a
574             // full wake lock (which we would have acquired before
575             // firing off the intent that brought us here; see
576             // PhoneUtils.showIncomingCallUi().)
577             //
578             // We also called preventScreenOn(true) at that point, to
579             // avoid cosmetic glitches while we were being launched.
580             // So now we need to post an ALLOW_SCREEN_ON message to
581             // (eventually) undo the prior preventScreenOn(true) call.
582             //
583             // (In principle we shouldn't do this until after our first
584             // layout/draw pass.  But in practice, the delay caused by
585             // simply waiting for the end of the message queue is long
586             // enough to avoid any flickering of the lock screen before
587             // the InCallScreen comes up.)
588             if (VDBG) log("- posting ALLOW_SCREEN_ON message...");
589             mHandler.removeMessages(ALLOW_SCREEN_ON);
590             mHandler.sendEmptyMessage(ALLOW_SCREEN_ON);
591
592             // TODO: There ought to be a more elegant way of doing this,
593             // probably by having the PowerManager and ActivityManager
594             // work together to let apps request that the screen on/off
595             // state be synchronized with the Activity lifecycle.
596             // (See bug 1648751.)
597         } else {
598             // The phone isn't ringing; this is either an outgoing call, or
599             // we're returning to a call in progress.  There *shouldn't* be
600             // any prior preventScreenOn(true) call that we need to undo,
601             // but let's do this just to be safe:
602             app.preventScreenOn(false);
603         }
604         app.updateWakeState();
605
606         // The "touch lock" overlay is NEVER visible when we resume.
607         // (In particular, this check ensures that we won't still be
608         // locked after the user wakes up the screen by pressing MENU.)
609         enableTouchLock(false);
610         // ...but if the dialpad is open we DO need to start the timer
611         // that will eventually bring up the "touch lock" overlay.
612         if (mDialer.isOpened()) resetTouchLockTimer();
613
614         // Restore the mute state if the last mute state change was NOT
615         // done by the user.
616         if (app.getRestoreMuteOnInCallResume()) {
617             PhoneUtils.restoreMuteState(mPhone);
618             app.setRestoreMuteOnInCallResume(false);
619         }
620
621         Profiler.profileViewCreate(getWindow(), InCallScreen.class.getName());
622         if (VDBG) log("onResume() done.");
623     }
624
625     @Override
626     protected void onSaveInstanceState(Bundle outState) {
627         if (VDBG) log("onSaveInstanceState()...");
628         super.onSaveInstanceState(outState);
629
630         // TODO: Save any state of the UI that needs to persist across
631         // configuration changes (ie. switching between portrait and
632         // landscape.)
633     }
634
635     @Override
636     protected void onPause() {
637         if (DBG) log("onPause()...");
638         super.onPause();
639
640         mIsForegroundActivity = false;
641
642         final PhoneApp app = PhoneApp.getInstance();
643
644         // make sure the chronometer is stopped when we move away from
645         // the foreground.
646         if (mConferenceTime != null) {
647             mConferenceTime.stop();
648         }
649
650         // as a catch-all, make sure that any dtmf tones are stopped
651         // when the UI is no longer in the foreground.
652         mDialer.onDialerKeyUp(null);
653
654         // If the device is put to sleep as the phone call is ending,
655         // we may see cases where the DELAYED_CLEANUP_AFTER_DISCONNECT
656         // event gets handled AFTER the device goes to sleep and wakes
657         // up again.
658
659         // This is because it is possible for a sleep command
660         // (executed with the End Call key) to come during the 2
661         // seconds that the "Call Ended" screen is up.  Sleep then
662         // pauses the device (including the cleanup event) and
663         // resumes the event when it wakes up.
664
665         // To fix this, we introduce a bit of code that pushes the UI
666         // to the background if we pause and see a request to
667         // DELAYED_CLEANUP_AFTER_DISCONNECT.
668
669         // Note: We can try to finish directly, by:
670         //  1. Removing the DELAYED_CLEANUP_AFTER_DISCONNECT messages
671         //  2. Calling delayedCleanupAfterDisconnect directly
672
673         // However, doing so can cause problems between the phone
674         // app and the keyguard - the keyguard is trying to sleep at
675         // the same time that the phone state is changing.  This can
676         // end up causing the sleep request to be ignored.
677         if (mHandler.hasMessages(DELAYED_CLEANUP_AFTER_DISCONNECT)) {
678             if (DBG) log("onPause(): DELAYED_CLEANUP_AFTER_DISCONNECT detected, finishing...");
679             finish();
680         }
681
682         if (ENABLE_PHONE_UI_EVENT_LOGGING) {
683             // InCallScreen is no longer active.
684             Checkin.logEvent(getContentResolver(),
685                              Checkin.Events.Tag.PHONE_UI,
686                              PHONE_UI_EVENT_EXIT);
687         }
688
689         // Clean up the menu, in case we get paused while the menu is up
690         // for some reason.
691         dismissMenu(true);  // dismiss immediately
692
693         // Dismiss any dialogs we may have brought up, just to be 100%
694         // sure they won't still be around when we get back here.
695         dismissAllDialogs();
696
697         // Re-enable the status bar (which we disabled in onResume().)
698         NotificationMgr.getDefault().getStatusBarMgr().enableExpandedView(true);
699
700         // Unregister for broadcast intents.  (These affect the visible UI
701         // of the InCallScreen, so we only care about them while we're in the
702         // foreground.)
703         unregisterReceiver(mReceiver);
704
705         // Re-enable "user activity" for touch events.
706         // We actually do this slightly *after* onPause(), to work around a
707         // race condition where a touch can come in after we've paused
708         // but before the device actually goes to sleep.
709         // TODO: The PowerManager itself should prevent this from happening.
710         mHandler.postDelayed(new Runnable() {
711                 public void run() {
712                     app.setIgnoreTouchUserActivity(false);
713                 }
714             }, 500);
715
716         // The keyguard was disabled the entire time the InCallScreen was
717         // active (see onResume()).  Re-enable it now.
718         app.reenableKeyguard();
719
720         // Make sure we revert the poke lock and wake lock when we move to
721         // the background.
722         app.updateWakeState();
723     }
724
725     @Override
726     protected void onStop() {
727         if (VDBG) log("onStop()...");
728         super.onStop();
729
730         stopTimer();
731
732         Phone.State state = mPhone.getState();
733         if (VDBG) log("onStop: state = " + state);
734
735         if (state == Phone.State.IDLE) {
736             // we don't want the call screen to remain in the activity history
737             // if there are not active or ringing calls.
738             if (DBG) log("- onStop: calling finish() to clear activity history...");
739             finish();
740         }
741     }
742
743     @Override
744     protected void onDestroy() {
745         if (DBG) log("onDestroy()...");
746         super.onDestroy();
747
748         // Set the magic flag that tells us NOT to handle any handler
749         // messages that come in asynchronously after we get destroyed.
750         mIsDestroyed = true;
751
752         final PhoneApp app = PhoneApp.getInstance();
753         app.setInCallScreenInstance(null);
754
755         // Clear out the InCallScreen references in various helper objects
756         // (to let them know we've been destroyed).
757         if (mInCallMenu != null) {
758             mInCallMenu.clearInCallScreenReference();
759         }
760         if (mCallCard != null) {
761             mCallCard.setInCallScreenInstance(null);
762         }
763
764         // Make sure that the dialer session is over and done with.
765         // 1. In Landscape mode, we stop the tone generator directly
766         // 2. In portrait mode, the tone generator is stopped
767         // whenever the dialer is closed by the framework, (either
768         // from a user request or calling close on the drawer
769         // directly), so all we have to do is to make sure the
770         // dialer is closed {see DTMFTwelvKeyDialer.onDialerClose}
771         // (it is ok to call this even if the dialer is not open).
772         if (ConfigurationHelper.isLandscape()) {
773             mDialer.stopDialerSession();
774         } else {
775             // make sure the dialer drawer is closed.
776             mDialer.closeDialer(false);
777         }
778         mDialer.clearInCallScreenReference();
779         mDialer = null;
780
781         unregisterForPhoneStates();
782         // No need to change wake state here; that happens in onPause() when we
783         // are moving out of the foreground.
784
785         if (mBluetoothHeadset != null) {
786             mBluetoothHeadset.close();
787             mBluetoothHeadset = null;
788         }
789     }
790
791     /**
792      * Dismisses the in-call screen.
793      *
794      * We never *really* finish() the InCallScreen, since we don't want to
795      * get destroyed and then have to be re-created from scratch for the
796      * next call.  Instead, we just move ourselves to the back of the
797      * activity stack.
798      *
799      * This also means that we'll no longer be reachable via the BACK
800      * button (since moveTaskToBack() puts us behind the Home app, but the
801      * home app doesn't allow the BACK key to move you any farther down in
802      * the history stack.)
803      *
804      * (Since the Phone app itself is never killed, this basically means
805      * that we'll keep a single InCallScreen instance around for the
806      * entire uptime of the device.  This noticeably improves the UI
807      * responsiveness for incoming calls.)
808      */
809     @Override
810     public void finish() {
811         if (DBG) log("finish()...");
812         moveTaskToBack(true);
813     }
814
815     /* package */ boolean isForegroundActivity() {
816         return mIsForegroundActivity;
817     }
818
819     private void registerForPhoneStates() {
820         if (!mRegisteredForPhoneStates) {
821             mPhone.registerForPhoneStateChanged(mHandler, PHONE_STATE_CHANGED, null);
822             mPhone.registerForDisconnect(mHandler, PHONE_DISCONNECT, null);
823             mPhone.registerForMmiInitiate(mHandler, PhoneApp.MMI_INITIATE, null);
824
825             // register for the MMI complete message.  Upon completion,
826             // PhoneUtils will bring up a system dialog instead of the
827             // message display class in PhoneUtils.displayMMIComplete().
828             // We'll listen for that message too, so that we can finish
829             // the activity at the same time.
830             mPhone.registerForMmiComplete(mHandler, PhoneApp.MMI_COMPLETE, null);
831
832             mPhone.setOnPostDialCharacter(mHandler, POST_ON_DIAL_CHARS, null);
833             mPhone.registerForSuppServiceFailed(mHandler, SUPP_SERVICE_FAILED, null);
834             mRegisteredForPhoneStates = true;
835         }
836     }
837
838     private void unregisterForPhoneStates() {
839         mPhone.unregisterForPhoneStateChanged(mHandler);
840         mPhone.unregisterForDisconnect(mHandler);
841         mPhone.unregisterForMmiInitiate(mHandler);
842         mPhone.setOnPostDialCharacter(null, POST_ON_DIAL_CHARS, null);
843         mRegisteredForPhoneStates = false;
844     }
845
846     @Override
847     protected void onNewIntent(Intent intent) {
848         if (DBG) log("onNewIntent: intent=" + intent);
849
850         // We're being re-launched with a new Intent.  Since we keep
851         // around a single InCallScreen instance for the life of the phone
852         // process (see finish()), this sequence will happen EVERY time
853         // there's a new incoming or outgoing call except for the very
854         // first time the InCallScreen gets created.  This sequence will
855         // also happen if the InCallScreen is already in the foreground
856         // (e.g. getting a new ACTION_CALL intent while we were already
857         // using the other line.)
858
859         // Stash away the new intent so that we can get it in the future
860         // by calling getIntent().  (Otherwise getIntent() will return the
861         // original Intent from when we first got created!)
862         setIntent(intent);
863
864         // Activities are always paused before receiving a new intent, so
865         // we can count on our onResume() method being called next.
866
867         // Just like in onCreate(), handle this intent, and stash the
868         // result code from internalResolveIntent() in the
869         // mInCallInitialStatus field.  If it's an error code, we'll
870         // handle it in onResume().
871         mInCallInitialStatus = internalResolveIntent(intent);
872         if (mInCallInitialStatus != InCallInitStatus.SUCCESS) {
873             Log.w(LOG_TAG, "onNewIntent: status " + mInCallInitialStatus
874                   + " from internalResolveIntent()");
875             // See onResume() for the actual error handling.
876         }
877     }
878
879     private InCallInitStatus internalResolveIntent(Intent intent) {
880         if (intent == null || intent.getAction() == null) {
881             return InCallInitStatus.SUCCESS;
882         }
883
884         String action = intent.getAction();
885         if (DBG) log("internalResolveIntent: action=" + action);
886
887         // The calls to setRestoreMuteOnInCallResume() inform the phone
888         // that we're dealing with new connections (either a placing an
889         // outgoing call or answering an incoming one, and NOT handling
890         // an aborted "Add Call" request), so we should let the mute state
891         // be handled by the PhoneUtils phone state change handler.
892         final PhoneApp app = PhoneApp.getInstance();
893         if (action.equals(Intent.ACTION_ANSWER)) {
894             internalAnswerCall();
895             app.setRestoreMuteOnInCallResume(false);
896             return InCallInitStatus.SUCCESS;
897         } else if (action.equals(Intent.ACTION_CALL)
898                 || action.equals(Intent.ACTION_CALL_EMERGENCY)) {
899             app.setRestoreMuteOnInCallResume(false);
900             return placeCall(intent);
901         } else if (action.equals(intent.ACTION_MAIN)) {
902             // The MAIN action is used to bring up the in-call screen without
903             // doing any other explicit action, like when you return to the
904             // current call after previously bailing out of the in-call UI.
905             // SHOW_DIALPAD_EXTRA can be used here to specify whether the DTMF
906             // dialpad should be initially visible.  If the extra isn't
907             // present at all, we just leave the dialpad in its previous state.
908             if (intent.hasExtra(SHOW_DIALPAD_EXTRA)) {
909                 boolean showDialpad = intent.getBooleanExtra(SHOW_DIALPAD_EXTRA, false);
910                 if (VDBG) log("- internalResolveIntent: SHOW_DIALPAD_EXTRA value = " + showDialpad);
911                 if (showDialpad) {
912                     mDialer.openDialer(false);  // no "opening" animation
913                 } else {
914                     mDialer.closeDialer(false);  // no "closing" animation
915                 }
916             }
917             return InCallInitStatus.SUCCESS;
918         } else {
919             Log.w(LOG_TAG, "internalResolveIntent: unexpected intent action: " + action);
920             // But continue the best we can (basically treating this case
921             // like ACTION_MAIN...)
922             return InCallInitStatus.SUCCESS;
923         }
924     }
925
926     private void stopTimer() {
927         if (mCallCard != null) mCallCard.stopTimer();
928     }
929
930     private void initInCallScreen() {
931         if (VDBG) log("initInCallScreen()...");
932
933         // Have the WindowManager filter out touch events that are "too fat".
934         getWindow().addFlags(WindowManager.LayoutParams.FLAG_IGNORE_CHEEK_PRESSES);
935
936         mMainFrame = (ViewGroup) findViewById(R.id.mainFrame);
937         mInCallPanel = (ViewGroup) findViewById(R.id.inCallPanel);
938
939         ConfigurationHelper.initConfiguration(getResources().getConfiguration());
940
941         // Create a CallCard and add it to our View hierarchy.
942         // TODO: there's no good reason for call_card_popup to be a
943         // separate layout that we need to manually inflate here.
944         // (That design is left over from when the call card was drawn in
945         // its own PopupWindow.)
946         // Instead, the CallCard should just be <include>d directly from
947         // incall_screen.xml.
948         View callCardLayout = getLayoutInflater().inflate(
949                 R.layout.call_card_popup,
950                 mInCallPanel);
951         mCallCard = (CallCard) callCardLayout.findViewById(R.id.callCard);
952         if (VDBG) log("  - mCallCard = " + mCallCard);
953         mCallCard.setInCallScreenInstance(this);
954         mCallCard.reset();
955
956         // Menu Button hint
957         mMenuButtonHint = (TextView) findViewById(R.id.menuButtonHint);
958
959         // Make any final updates to our View hierarchy that depend on the
960         // current configuration.
961         ConfigurationHelper.applyConfigurationToLayout(this);
962     }
963
964     /**
965      * Returns true if the phone is "in use", meaning that at least one line
966      * is active (ie. off hook or ringing or dialing).  Conversely, a return
967      * value of false means there's currently no phone activity at all.
968      */
969     private boolean phoneIsInUse() {
970         return mPhone.getState() != Phone.State.IDLE;
971     }
972
973     private boolean handleDialerKeyDown(int keyCode, KeyEvent event) {
974         if (VDBG) log("handleDialerKeyDown: keyCode " + keyCode + ", event " + event + "...");
975
976         // As soon as the user starts typing valid dialable keys on the
977         // keyboard (presumably to type DTMF tones) we start passing the
978         // key events to the DTMFDialer's onDialerKeyDown.  We do so
979         // only if the okToDialDTMFTones() conditions pass.
980         if (okToDialDTMFTones()) {
981             return mDialer.onDialerKeyDown(event);
982         }
983
984         return false;
985     }
986
987     /**
988      * Handles a DOWN keypress on the BACK key.
989      */
990     private boolean handleBackKey() {
991         if (VDBG) log("handleBackKey()...");
992
993         // While an incoming call is ringing, BACK behaves just like
994         // ENDCALL: it stops the ringing and rejects the current call.
995         final CallNotifier notifier = PhoneApp.getInstance().notifier;
996         if (notifier.isRinging()) {
997             if (DBG) log("BACK key while ringing: reject the call");
998             internalHangupRingingCall();
999
1000             // Don't consume the key; instead let the BACK event *also*
1001             // get handled normally by the framework (which presumably
1002             // will cause us to exit out of this activity.)
1003             return false;
1004         }
1005
1006         // BACK is also used to exit out of any "special modes" of the
1007         // in-call UI:
1008
1009         if (mDialer.isOpened()) {
1010             // Take down the "touch lock" overlay *immediately* to let the
1011             // user clearly see the DTMF dialpad's closing animation.
1012             enableTouchLock(false);
1013
1014             mDialer.closeDialer(true);  // do the "closing" animation
1015             return true;
1016         }
1017
1018         if (mInCallScreenMode == InCallScreenMode.MANAGE_CONFERENCE) {
1019             // Hide the Manage Conference panel, return to NORMAL mode.
1020             setInCallScreenMode(InCallScreenMode.NORMAL);
1021             return true;
1022         }
1023
1024         return false;
1025     }
1026
1027     /**
1028      * Handles the green CALL key while in-call.
1029      * @return true if we consumed the event.
1030      */
1031     private boolean handleCallKey() {
1032         // The green CALL button means either "Answer", "Unhold", or
1033         // "Swap calls", or can be a no-op, depending on the current state
1034         // of the Phone.
1035
1036         final boolean hasRingingCall = !mRingingCall.isIdle();
1037         final boolean hasActiveCall = !mForegroundCall.isIdle();
1038         final boolean hasHoldingCall = !mBackgroundCall.isIdle();
1039
1040         if (mPhone.getPhoneName() == "CDMA") {
1041             // WINK:TODO Teleca is this enough?
1042
1043             // The green CALL button means either "Answer", "Swap calls/On Hold", or
1044             // "Add to 3WC", depending on the current state of the Phone.
1045
1046             if (hasRingingCall) {
1047                 if (VDBG) log("handleCallKey: ringing ==> answer!");
1048                 internalAnswerCall();  // Automatically holds the current active call,
1049                                        // if there is one
1050             } else {
1051                 // send an empty CDMA flash string
1052                 PhoneUtils.switchHoldingAndActive(mPhone);
1053             }
1054         } else {
1055             if (hasRingingCall) {
1056                 // If an incoming call is ringing, the CALL button is actually
1057                 // handled by the PhoneWindowManager.  (We do this to make
1058                 // sure that we'll respond to the key even if the InCallScreen
1059                 // hasn't come to the foreground yet.)
1060                 //
1061                 // We'd only ever get here in the extremely rare case that the
1062                 // incoming call started ringing *after*
1063                 // PhoneWindowManager.interceptKeyTq() but before the event
1064                 // got here, or else if the PhoneWindowManager had some
1065                 // problem connecting to the ITelephony service.
1066                 Log.w(LOG_TAG, "handleCallKey: incoming call is ringing!"
1067                       + " (PhoneWindowManager should have handled this key.)");
1068                 // But go ahead and handle the key as normal, since the
1069                 // PhoneWindowManager presumably did NOT handle it:
1070
1071                 // There's an incoming ringing call: CALL means "Answer".
1072                 if (hasActiveCall && hasHoldingCall) {
1073                     if (DBG) log("handleCallKey: ringing (both lines in use) ==> answer!");
1074                     internalAnswerCallBothLinesInUse();
1075                 } else {
1076                     if (DBG) log("handleCallKey: ringing ==> answer!");
1077                     internalAnswerCall();  // Automatically holds the current active call,
1078                                            // if there is one
1079                 }
1080             } else if (hasActiveCall && hasHoldingCall) {
1081                 // Two lines are in use: CALL means "Swap calls".
1082                 if (DBG) log("handleCallKey: both lines in use ==> swap calls.");
1083                 internalSwapCalls();
1084             } else if (hasHoldingCall) {
1085                 // There's only one line in use, AND it's on hold.
1086                 // In this case CALL is a shortcut for "unhold".
1087                 if (DBG) log("handleCallKey: call on hold ==> unhold.");
1088                 PhoneUtils.switchHoldingAndActive(mPhone);  // Really means "unhold" in this state
1089             } else {
1090                 // The most common case: there's only one line in use, and
1091                 // it's an active call (i.e. it's not on hold.)
1092                 // In this case CALL is a no-op.
1093                 // (This used to be a shortcut for "add call", but that was a
1094                 // bad idea because "Add call" is so infrequently-used, and
1095                 // because the user experience is pretty confusing if you
1096                 // inadvertently trigger it.)
1097                 if (VDBG) log("handleCallKey: call in foregound ==> ignoring.");
1098                 // But note we still consume this key event; see below.
1099             }
1100         }
1101
1102         // We *always* consume the CALL key, since the system-wide default
1103         // action ("go to the in-call screen") is useless here.
1104         return true;
1105     }
1106
1107     boolean isKeyEventAcceptableDTMF (KeyEvent event) {
1108         return (mDialer != null && mDialer.isKeyEventAcceptable(event));
1109     }
1110
1111     /**
1112      * Overriden to track relevant focus changes.
1113      *
1114      * If a key is down and some time later the focus changes, we may
1115      * NOT recieve the keyup event; logically the keyup event has not
1116      * occured in this window.  This issue is fixed by treating a focus
1117      * changed event as an interruption to the keydown, making sure
1118      * that any code that needs to be run in onKeyUp is ALSO run here.
1119      *
1120      * Note, this focus change event happens AFTER the in-call menu is
1121      * displayed, so mIsMenuDisplayed should always be correct by the
1122      * time this method is called in the framework, please see:
1123      * {@link onCreatePanelView}, {@link onOptionsMenuClosed}
1124      */
1125     @Override
1126     public void onWindowFocusChanged(boolean hasFocus) {
1127         // the dtmf tones should no longer be played
1128         if (VDBG) log("onWindowFocusChanged(" + hasFocus + ")...");
1129         if (!hasFocus && mDialer != null) {
1130             if (VDBG) log("- onWindowFocusChanged: faking onDialerKeyUp()...");
1131             mDialer.onDialerKeyUp(null);
1132         }
1133     }
1134
1135     @Override
1136     public boolean dispatchKeyEvent(KeyEvent event) {
1137         // if (DBG) log("dispatchKeyEvent(event " + event + ")...");
1138
1139         // Intercept some events before they get dispatched to our views.
1140         switch (event.getKeyCode()) {
1141             case KeyEvent.KEYCODE_DPAD_CENTER:
1142             case KeyEvent.KEYCODE_DPAD_UP:
1143             case KeyEvent.KEYCODE_DPAD_DOWN:
1144             case KeyEvent.KEYCODE_DPAD_LEFT:
1145             case KeyEvent.KEYCODE_DPAD_RIGHT:
1146                 // Disable DPAD keys and trackball clicks if the touch lock
1147                 // overlay is up, since "touch lock" really means "disable
1148                 // the DTMF dialpad" (rather than only disabling touch events.)
1149                 if (mDialer.isOpened() && isTouchLocked()) {
1150                     if (DBG) log("- ignoring DPAD event while touch-locked...");
1151                     return true;
1152                 }
1153                 break;
1154
1155             default:
1156                 break;
1157         }
1158
1159         return super.dispatchKeyEvent(event);
1160     }
1161
1162     @Override
1163     public boolean onKeyUp(int keyCode, KeyEvent event) {
1164         // if (DBG) log("onKeyUp(keycode " + keyCode + ")...");
1165
1166         // push input to the dialer.
1167         if ((mDialer != null) && (mDialer.onDialerKeyUp(event))){
1168             return true;
1169         } else if (keyCode == KeyEvent.KEYCODE_CALL) {
1170             // Always consume CALL to be sure the PhoneWindow won't do anything with it
1171             return true;
1172         }
1173         return super.onKeyUp(keyCode, event);
1174     }
1175
1176     @Override
1177     public boolean onKeyDown(int keyCode, KeyEvent event) {
1178         // if (DBG) log("onKeyDown(keycode " + keyCode + ")...");
1179
1180         switch (keyCode) {
1181             case KeyEvent.KEYCODE_CALL:
1182                 boolean handled = handleCallKey();
1183                 if (!handled) {
1184                     Log.w(LOG_TAG, "InCallScreen should always handle KEYCODE_CALL in onKeyDown");
1185                 }
1186                 // Always consume CALL to be sure the PhoneWindow won't do anything with it
1187                 return true;
1188
1189             // Note there's no KeyEvent.KEYCODE_ENDCALL case here.
1190             // The standard system-wide handling of the ENDCALL key
1191             // (see PhoneWindowManager's handling of KEYCODE_ENDCALL)
1192             // already implements exactly what the UI spec wants,
1193             // namely (1) "hang up" if there's a current active call,
1194             // or (2) "don't answer" if there's a current ringing call.
1195
1196             case KeyEvent.KEYCODE_BACK:
1197                 if (handleBackKey()) {
1198                     return true;
1199                 }
1200                 break;
1201
1202             case KeyEvent.KEYCODE_CAMERA:
1203                 // Disable the CAMERA button while in-call since it's too
1204                 // easy to press accidentally.
1205                 return true;
1206
1207             case KeyEvent.KEYCODE_VOLUME_UP:
1208             case KeyEvent.KEYCODE_VOLUME_DOWN:
1209                 if (mPhone.getState() == Phone.State.RINGING) {
1210                     // If an incoming call is ringing, the VOLUME buttons are
1211                     // actually handled by the PhoneWindowManager.  (We do
1212                     // this to make sure that we'll respond to them even if
1213                     // the InCallScreen hasn't come to the foreground yet.)
1214                     //
1215                     // We'd only ever get here in the extremely rare case that the
1216                     // incoming call started ringing *after*
1217                     // PhoneWindowManager.interceptKeyTq() but before the event
1218                     // got here, or else if the PhoneWindowManager had some
1219                     // problem connecting to the ITelephony service.
1220                     Log.w(LOG_TAG, "VOLUME key: incoming call is ringing!"
1221                           + " (PhoneWindowManager should have handled this key.)");
1222                     // But go ahead and handle the key as normal, since the
1223                     // PhoneWindowManager presumably did NOT handle it:
1224
1225                     final CallNotifier notifier = PhoneApp.getInstance().notifier;
1226                     if (notifier.isRinging()) {
1227                         // ringer is actually playing, so silence it.
1228                         PhoneUtils.setAudioControlState(PhoneUtils.AUDIO_IDLE);
1229                         if (DBG) log("VOLUME key: silence ringer");
1230                         notifier.silenceRinger();
1231                     }
1232
1233                     // As long as an incoming call is ringing, we always
1234                     // consume the VOLUME keys.
1235                     return true;
1236                 }
1237                 break;
1238
1239             case KeyEvent.KEYCODE_MENU:
1240                 // Special case for the MENU key: if the "touch lock"
1241                 // overlay is up (over the DTMF dialpad), allow MENU to
1242                 // dismiss the overlay just as if you had double-tapped
1243                 // the onscreen icon.
1244                 // (We do this because MENU is normally used to bring the
1245                 // UI back after the screen turns off, and the touch lock
1246                 // overlay "feels" very similar to the screen going off.
1247                 // This is also here to be "backward-compatibile" with the
1248                 // 1.0 behavior, where you *needed* to hit MENU to bring
1249                 // back the dialpad after 6 seconds of idle time.)
1250                 if (mDialer.isOpened() && isTouchLocked()) {
1251                     if (VDBG) log("- allowing MENU to dismiss touch lock overlay...");
1252                     // Take down the touch lock overlay, but post a
1253                     // message in the future to bring it back later.
1254                     enableTouchLock(false);
1255                     resetTouchLockTimer();
1256                     return true;
1257                 }
1258                 break;
1259
1260             case KeyEvent.KEYCODE_MUTE:
1261                 PhoneUtils.setMute(mPhone, !PhoneUtils.getMute(mPhone));
1262                 return true;
1263
1264             // Various testing/debugging features, enabled ONLY when VDBG == true.
1265             case KeyEvent.KEYCODE_SLASH:
1266                 if (VDBG) {
1267                     log("----------- InCallScreen View dump --------------");
1268                     // Dump starting from the top-level view of the entire activity:
1269                     Window w = this.getWindow();
1270                     View decorView = w.getDecorView();
1271                     decorView.debug();
1272                     return true;
1273                 }
1274                 break;
1275             case KeyEvent.KEYCODE_EQUALS:
1276                 if (VDBG) {
1277                     log("----------- InCallScreen call state dump --------------");
1278                     PhoneUtils.dumpCallState(mPhone);
1279                     return true;
1280                 }
1281                 break;
1282             case KeyEvent.KEYCODE_GRAVE:
1283                 if (VDBG) {
1284                     // Placeholder for other misc temp testing
1285                     log("------------ Temp testing -----------------");
1286                     return true;
1287                 }
1288                 break;
1289         }
1290
1291         if (event.getRepeatCount() == 0 && handleDialerKeyDown(keyCode, event)) {
1292             return true;
1293         }
1294
1295         return super.onKeyDown(keyCode, event);
1296     }
1297
1298     /**
1299      * Handle a failure notification for a supplementary service
1300      * (i.e. conference, switch, separate, transfer, etc.).
1301      */
1302     void onSuppServiceFailed(AsyncResult r) {
1303         Phone.SuppService service = (Phone.SuppService) r.result;
1304         if (DBG) log("onSuppServiceFailed: " + service);
1305
1306         int errorMessageResId;
1307         switch (service) {
1308             case SWITCH:
1309                 // Attempt to switch foreground and background/incoming calls failed
1310                 // ("Failed to switch calls")
1311                 errorMessageResId = R.string.incall_error_supp_service_switch;
1312                 break;
1313
1314             case SEPARATE:
1315                 // Attempt to separate a call from a conference call
1316                 // failed ("Failed to separate out call")
1317                 errorMessageResId = R.string.incall_error_supp_service_separate;
1318                 break;
1319
1320             case TRANSFER:
1321                 // Attempt to connect foreground and background calls to
1322                 // each other (and hanging up user's line) failed ("Call
1323                 // transfer failed")
1324                 errorMessageResId = R.string.incall_error_supp_service_transfer;
1325                 break;
1326
1327             case CONFERENCE:
1328                 // Attempt to add a call to conference call failed
1329                 // ("Conference call failed")
1330                 errorMessageResId = R.string.incall_error_supp_service_conference;
1331                 break;
1332
1333             case REJECT:
1334                 // Attempt to reject an incoming call failed
1335                 // ("Call rejection failed")
1336                 errorMessageResId = R.string.incall_error_supp_service_reject;
1337                 break;
1338
1339             case HANGUP:
1340                 // Attempt to release a call failed ("Failed to release call(s)")
1341                 errorMessageResId = R.string.incall_error_supp_service_hangup;
1342                 break;
1343
1344             case UNKNOWN:
1345             default:
1346                 // Attempt to use a service we don't recognize or support
1347                 // ("Unsupported service" or "Selected service failed")
1348                 errorMessageResId = R.string.incall_error_supp_service_unknown;
1349                 break;
1350         }
1351
1352         // mSuppServiceFailureDialog is a generic dialog used for any
1353         // supp service failure, and there's only ever have one
1354         // instance at a time.  So just in case a previous dialog is
1355         // still around, dismiss it.
1356         if (mSuppServiceFailureDialog != null) {
1357             if (DBG) log("- DISMISSING mSuppServiceFailureDialog.");
1358             mSuppServiceFailureDialog.dismiss();  // It's safe to dismiss() a dialog
1359                                                   // that's already dismissed.
1360             mSuppServiceFailureDialog = null;
1361         }
1362
1363         mSuppServiceFailureDialog = new AlertDialog.Builder(this)
1364                 .setMessage(errorMessageResId)
1365                 .setPositiveButton(R.string.ok, null)
1366                 .setCancelable(true)
1367                 .create();
1368         mSuppServiceFailureDialog.getWindow().addFlags(
1369                 WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
1370         mSuppServiceFailureDialog.show();
1371     }
1372
1373     /**
1374      * Something has changed in the phone's state.  Update the UI.
1375      */
1376     private void onPhoneStateChanged(AsyncResult r) {
1377         if (VDBG) log("onPhoneStateChanged()...");
1378
1379         // There's nothing to do here if we're not the foreground activity.
1380         // (When we *do* eventually come to the foreground, we'll do a
1381         // full update then.)
1382         if (!mIsForegroundActivity) {
1383             if (VDBG) log("onPhoneStateChanged: Activity not in foreground! Bailing out...");
1384             return;
1385         }
1386
1387         updateScreen();
1388
1389         // Make sure we update the poke lock and wake lock when certain
1390         // phone state changes occur.
1391         PhoneApp.getInstance().updateWakeState();
1392     }
1393
1394     /**
1395      * Updates the UI after a phone connection is disconnected, as follows:
1396      *
1397      * - If this was a missed or rejected incoming call, and no other
1398      *   calls are active, dismiss the in-call UI immediately.  (The
1399      *   CallNotifier will still create a "missed call" notification if
1400      *   necessary.)
1401      *
1402      * - With any other disconnect cause, if the phone is now totally
1403      *   idle, display the "Call ended" state for a couple of seconds.
1404      *
1405      * - Or, if the phone is still in use, stay on the in-call screen
1406      *   (and update the UI to reflect the current state of the Phone.)
1407      *
1408      * @param r r.result contains the connection that just ended
1409      */
1410     private void onDisconnect(AsyncResult r) {
1411         Connection c = (Connection) r.result;
1412         Connection.DisconnectCause cause = c.getDisconnectCause();
1413         if (DBG) log("onDisconnect: " + c + ", cause=" + cause);
1414
1415         // Any time a call disconnects, clear out the "history" of DTMF
1416         // digits you typed (to make sure it doesn't persist from one call
1417         // to the next.)
1418         mDialer.clearDigits();
1419
1420         // Under certain call disconnected states, we want to alert the user
1421         // with a dialog instead of going through the normal disconnect
1422         // routine.
1423         if (cause == Connection.DisconnectCause.CALL_BARRED) {
1424             showGenericErrorDialog(R.string.callFailed_cb_enabled, false);
1425             return;
1426         } else if (cause == Connection.DisconnectCause.FDN_BLOCKED) {
1427             showGenericErrorDialog(R.string.callFailed_fdn_only, false);
1428             return;
1429         } else if (cause == Connection.DisconnectCause.CS_RESTRICTED) {
1430             showGenericErrorDialog(R.string.callFailed_dsac_restricted, false);
1431             return;
1432         } else if (cause == Connection.DisconnectCause.CS_RESTRICTED_EMERGENCY) {
1433             showGenericErrorDialog(R.string.callFailed_dsac_restricted_emergency, false);
1434             return;
1435         } else if (cause == Connection.DisconnectCause.CS_RESTRICTED_NORMAL) {
1436             showGenericErrorDialog(R.string.callFailed_dsac_restricted_normal, false);
1437             return;
1438         }
1439
1440         final PhoneApp app = PhoneApp.getInstance();
1441         boolean currentlyIdle = !phoneIsInUse();
1442
1443         // Explicitly clean up up any DISCONNECTED connections
1444         // in a conference call.
1445         // [Background: Even after a connection gets disconnected, its
1446         // Connection object still stays around for a few seconds, in the
1447         // DISCONNECTED state.  With regular calls, this state drives the
1448         // "call ended" UI.  But when a single person disconnects from a
1449         // conference call there's no "call ended" state at all; in that
1450         // case we blow away any DISCONNECTED connections right now to make sure
1451         // the UI updates instantly to reflect the current state.]
1452         Call call = c.getCall();
1453         if (call != null) {
1454             // We only care about situation of a single caller
1455             // disconnecting from a conference call.  In that case, the
1456             // call will have more than one Connection (including the one
1457             // that just disconnected, which will be in the DISCONNECTED
1458             // state) *and* at least one ACTIVE connection.  (If the Call
1459             // has *no* ACTIVE connections, that means that the entire
1460             // conference call just ended, so we *do* want to show the
1461             // "Call ended" state.)
1462             List<Connection> connections = call.getConnections();
1463             if (connections != null && connections.size() > 1) {
1464                 for (Connection conn : connections) {
1465                     if (conn.getState() == Call.State.ACTIVE) {
1466                         // This call still has at least one ACTIVE connection!
1467                         // So blow away any DISCONNECTED connections
1468                         // (including, presumably, the one that just
1469                         // disconnected from this conference call.)
1470
1471                         // We also force the wake state to refresh, just in
1472                         // case the disconnected connections are removed
1473                         // before the phone state change.
1474                         if (VDBG) log("- Still-active conf call; clearing DISCONNECTED...");
1475                         app.updateWakeState();
1476                         mPhone.clearDisconnected();  // This happens synchronously.
1477                         break;
1478                     }
1479                 }
1480             }
1481         }
1482
1483         // Retrieve the emergency call retry count from this intent, in
1484         // case we need to retry the call again.
1485         int emergencyCallRetryCount = getIntent().getIntExtra(
1486                 EmergencyCallHandler.EMERGENCY_CALL_RETRY_KEY,
1487                 EmergencyCallHandler.INITIAL_ATTEMPT);
1488
1489         // Note: see CallNotifier.onDisconnect() for some other behavior
1490         // that might be triggered by a disconnect event, like playing the
1491         // busy/congestion tone.
1492
1493         // Keep track of whether this call was user-initiated or not.
1494         // (This affects where we take the user next; see delayedCleanupAfterDisconnect().)
1495         mShowCallLogAfterDisconnect = !c.isIncoming();
1496
1497         // We bail out immediately (and *don't* display the "call ended"
1498         // state at all) in a couple of cases, including those where we
1499         // are waiting for the radio to finish powering up for an
1500         // emergency call:
1501         boolean bailOutImmediately =
1502                 ((cause == Connection.DisconnectCause.INCOMING_MISSED)
1503                  || (cause == Connection.DisconnectCause.INCOMING_REJECTED)
1504                  || ((cause == Connection.DisconnectCause.OUT_OF_SERVICE)
1505                          && (emergencyCallRetryCount > 0)))
1506                 && currentlyIdle;
1507
1508         if (bailOutImmediately) {
1509             if (VDBG) log("- onDisconnect: bailOutImmediately...");
1510             // Exit the in-call UI!
1511             // (This is basically the same "delayed cleanup" we do below,
1512             // just with zero delay.  Since the Phone is currently idle,
1513             // this call is guaranteed to immediately finish() this activity.)
1514             delayedCleanupAfterDisconnect();
1515
1516             // Retry the call, by resending the intent to the emergency
1517             // call handler activity.
1518             if ((cause == Connection.DisconnectCause.OUT_OF_SERVICE)
1519                     && (emergencyCallRetryCount > 0)) {
1520                 startActivity(getIntent()
1521                         .setClassName(this, EmergencyCallHandler.class.getName()));
1522             }
1523         } else {
1524             if (VDBG) log("- onDisconnect: delayed bailout...");
1525             // Stay on the in-call screen for now.  (Either the phone is
1526             // still in use, or the phone is idle but we want to display
1527             // the "call ended" state for a couple of seconds.)
1528
1529             // Force a UI update in case we need to display anything
1530             // special given this connection's DisconnectCause (see
1531             // CallCard.getCallFailedString()).
1532             updateScreen();
1533
1534             // Display the special "Call ended" state when the phone is idle
1535             // but there's still a call in the DISCONNECTED state:
1536             if (currentlyIdle
1537                 && ((mForegroundCall.getState() == Call.State.DISCONNECTED)
1538                     || (mBackgroundCall.getState() == Call.State.DISCONNECTED))) {
1539                 if (VDBG) log("- onDisconnect: switching to 'Call ended' state...");
1540                 setInCallScreenMode(InCallScreenMode.CALL_ENDED);
1541             }
1542
1543             // Some other misc cleanup that we do if the call that just
1544             // disconnected was the foreground call.
1545             final boolean hasActiveCall = !mForegroundCall.isIdle();
1546             if (!hasActiveCall) {
1547                 if (VDBG) log("- onDisconnect: cleaning up after FG call disconnect...");
1548
1549                 // Dismiss any dialogs which are only meaningful for an
1550                 // active call *and* which become moot if the call ends.
1551                 if (mWaitPromptDialog != null) {
1552                     if (VDBG) log("- DISMISSING mWaitPromptDialog.");
1553                     mWaitPromptDialog.dismiss();  // safe even if already dismissed
1554                     mWaitPromptDialog = null;
1555                 }
1556                 if (mWildPromptDialog != null) {
1557                     if (VDBG) log("- DISMISSING mWildPromptDialog.");
1558                     mWildPromptDialog.dismiss();  // safe even if already dismissed
1559                     mWildPromptDialog = null;
1560                 }
1561             }
1562
1563             // Updating the screen wake state is done in onPhoneStateChanged().
1564
1565             // Finally, arrange for delayedCleanupAfterDisconnect() to get
1566             // called after a short interval (during which we display the
1567             // "call ended" state.)  At that point, if the
1568             // Phone is idle, we'll finish() out of this activity.
1569             int callEndedDisplayDelay =
1570                     (cause == Connection.DisconnectCause.LOCAL)
1571                     ? CALL_ENDED_SHORT_DELAY : CALL_ENDED_LONG_DELAY;
1572             mHandler.removeMessages(DELAYED_CLEANUP_AFTER_DISCONNECT);
1573             mHandler.sendEmptyMessageDelayed(DELAYED_CLEANUP_AFTER_DISCONNECT,
1574                                              callEndedDisplayDelay);
1575         }
1576     }
1577
1578     /**
1579      * Brings up the "MMI Started" dialog.
1580      */
1581     private void onMMIInitiate(AsyncResult r) {
1582         if (VDBG) log("onMMIInitiate()...  AsyncResult r = " + r);
1583
1584         // Watch out: don't do this if we're not the foreground activity,
1585         // mainly since in the Dialog.show() might fail if we don't have a
1586         // valid window token any more...
1587         // (Note that this exact sequence can happen if you try to start
1588         // an MMI code while the radio is off or out of service.)
1589         if (!mIsForegroundActivity) {
1590             if (VDBG) log("Activity not in foreground! Bailing out...");
1591             return;
1592         }
1593
1594         // Also, if any other dialog is up right now (presumably the
1595         // generic error dialog displaying the "Starting MMI..."  message)
1596         // take it down before bringing up the real "MMI Started" dialog
1597         // in its place.
1598         dismissAllDialogs();
1599
1600         MmiCode mmiCode = (MmiCode) r.result;
1601         if (VDBG) log("  - MmiCode: " + mmiCode);
1602
1603         Message message = Message.obtain(mHandler, PhoneApp.MMI_CANCEL);
1604         mMmiStartedDialog = PhoneUtils.displayMMIInitiate(this, mmiCode,
1605                                                           message, mMmiStartedDialog);
1606     }
1607
1608     /**
1609      * Handles an MMI_CANCEL event, which is triggered by the button
1610      * (labeled either "OK" or "Cancel") on the "MMI Started" dialog.
1611      * @see onMMIInitiate
1612      * @see PhoneUtils.cancelMmiCode
1613      */
1614     private void onMMICancel() {
1615         if (VDBG) log("onMMICancel()...");
1616
1617         // First of all, cancel the outstanding MMI code (if possible.)
1618         PhoneUtils.cancelMmiCode(mPhone);
1619
1620         // Regardless of whether the current MMI code was cancelable, the
1621         // PhoneApp will get an MMI_COMPLETE event very soon, which will
1622         // take us to the MMI Complete dialog (see
1623         // PhoneUtils.displayMMIComplete().)
1624         //
1625         // But until that event comes in, we *don't* want to stay here on
1626         // the in-call screen, since we'll be visible in a
1627         // partially-constructed state as soon as the "MMI Started" dialog
1628         // gets dismissed.  So let's forcibly bail out right now.
1629         if (DBG) log("onMMICancel: finishing...");
1630         finish();
1631     }
1632
1633     /**
1634      * Handles the POST_ON_DIAL_CHARS message from the Phone
1635      * (see our call to mPhone.setOnPostDialCharacter() above.)
1636      *
1637      * TODO: NEED TO TEST THIS SEQUENCE now that we no longer handle
1638      * "dialable" key events here in the InCallScreen: we do directly to the
1639      * Dialer UI instead.  Similarly, we may now need to go directly to the
1640      * Dialer to handle POST_ON_DIAL_CHARS too.
1641      */
1642     private void handlePostOnDialChars(AsyncResult r, char ch) {
1643         Connection c = (Connection) r.result;
1644
1645         if (c != null) {
1646             Connection.PostDialState state =
1647                     (Connection.PostDialState) r.userObj;
1648
1649             if (VDBG) log("handlePostOnDialChar: state = " +
1650                     state + ", ch = " + ch);
1651
1652             switch (state) {
1653                 case STARTED:
1654                     // TODO: is this needed, now that you can't actually
1655                     // type DTMF chars or dial directly from here?
1656                     // If so, we'd need to yank you out of the in-call screen
1657                     // here too (and take you to the 12-key dialer in "in-call" mode.)
1658                     // displayPostDialedChar(ch);
1659                     break;
1660
1661                 case WAIT:
1662                     //if (DBG) log("show wait prompt...");
1663                     String postDialStr = c.getRemainingPostDialString();
1664                     showWaitPromptDialog(c, postDialStr);
1665                     break;
1666
1667                 case WILD:
1668                     //if (DBG) log("prompt user to replace WILD char");
1669                     showWildPromptDialog(c);
1670                     break;
1671
1672                 case COMPLETE:
1673                     break;
1674
1675                 default:
1676                     break;
1677             }
1678         }
1679     }
1680
1681     private void showWaitPromptDialog(final Connection c, String postDialStr) {
1682         Resources r = getResources();
1683         StringBuilder buf = new StringBuilder();
1684         buf.append(r.getText(R.string.wait_prompt_str));
1685         buf.append(postDialStr);
1686
1687         if (mWaitPromptDialog != null) {
1688             if (VDBG) log("- DISMISSING mWaitPromptDialog.");
1689             mWaitPromptDialog.dismiss();  // safe even if already dismissed
1690             mWaitPromptDialog = null;
1691         }
1692
1693         mWaitPromptDialog = new AlertDialog.Builder(this)
1694                 .setMessage(buf.toString())
1695                 .setPositiveButton(R.string.send_button, new DialogInterface.OnClickListener() {
1696                         public void onClick(DialogInterface dialog, int whichButton) {
1697                             if (VDBG) log("handle WAIT_PROMPT_CONFIRMED, proceed...");
1698                             c.proceedAfterWaitChar();
1699                             PhoneApp.getInstance().pokeUserActivity();
1700                         }
1701                     })
1702                 .setOnCancelListener(new DialogInterface.OnCancelListener() {
1703                         public void onCancel(DialogInterface dialog) {
1704                             if (VDBG) log("handle POST_DIAL_CANCELED!");
1705                             c.cancelPostDial();
1706                             PhoneApp.getInstance().pokeUserActivity();
1707                         }
1708                     })
1709                 .create();
1710         mWaitPromptDialog.getWindow().addFlags(
1711                 WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
1712         mWaitPromptDialog.show();
1713     }
1714
1715     private View createWildPromptView() {
1716         LinearLayout result = new LinearLayout(this);
1717         result.setOrientation(LinearLayout.VERTICAL);
1718         result.setPadding(5, 5, 5, 5);
1719
1720         LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
1721                         ViewGroup.LayoutParams.FILL_PARENT,
1722                         ViewGroup.LayoutParams.WRAP_CONTENT);
1723
1724         TextView promptMsg = new TextView(this);
1725         promptMsg.setTextSize(14);
1726         promptMsg.setTypeface(Typeface.DEFAULT_BOLD);
1727         promptMsg.setText(getResources().getText(R.string.wild_prompt_str));
1728
1729         result.addView(promptMsg, lp);
1730
1731         mWildPromptText = new EditText(this);
1732         mWildPromptText.setKeyListener(DialerKeyListener.getInstance());
1733         mWildPromptText.setMovementMethod(null);
1734         mWildPromptText.setTextSize(14);
1735         mWildPromptText.setMaxLines(1);
1736         mWildPromptText.setHorizontallyScrolling(true);
1737         mWildPromptText.setBackgroundResource(android.R.drawable.editbox_background);
1738
1739         LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(
1740                         ViewGroup.LayoutParams.FILL_PARENT,
1741                         ViewGroup.LayoutParams.WRAP_CONTENT);
1742         lp2.setMargins(0, 3, 0, 0);
1743
1744         result.addView(mWildPromptText, lp2);
1745
1746         return result;
1747     }
1748
1749     private void showWildPromptDialog(final Connection c) {
1750         View v = createWildPromptView();
1751
1752         if (mWildPromptDialog != null) {
1753             if (VDBG) log("- DISMISSING mWildPromptDialog.");
1754             mWildPromptDialog.dismiss();  // safe even if already dismissed
1755             mWildPromptDialog = null;
1756         }
1757
1758         mWildPromptDialog = new AlertDialog.Builder(this)
1759                 .setView(v)
1760                 .setPositiveButton(
1761                         R.string.send_button,
1762                         new DialogInterface.OnClickListener() {
1763                             public void onClick(DialogInterface dialog, int whichButton) {
1764                                 if (VDBG) log("handle WILD_PROMPT_CHAR_ENTERED, proceed...");
1765                                 String replacement = null;
1766                                 if (mWildPromptText != null) {
1767                                     replacement = mWildPromptText.getText().toString();
1768                                     mWildPromptText = null;
1769                                 }
1770                                 c.proceedAfterWildChar(replacement);
1771                                 PhoneApp.getInstance().pokeUserActivity();
1772                             }
1773                         })
1774                 .setOnCancelListener(
1775                         new DialogInterface.OnCancelListener() {
1776                             public void onCancel(DialogInterface dialog) {
1777                                 if (VDBG) log("handle POST_DIAL_CANCELED!");
1778                                 c.cancelPostDial();
1779                                 PhoneApp.getInstance().pokeUserActivity();
1780                             }
1781                         })
1782                 .create();
1783         mWildPromptDialog.getWindow().addFlags(
1784                 WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
1785         mWildPromptDialog.show();
1786
1787         mWildPromptText.requestFocus();
1788     }
1789
1790     /**
1791      * Updates the state of the in-call UI based on the current state of
1792      * the Phone.
1793      */
1794     private void updateScreen() {
1795         if (VDBG) log("updateScreen()...");
1796
1797         // Don't update anything if we're not in the foreground (there's
1798         // no point updating our UI widgets since we're not visible!)
1799         // Also note this check also ensures we won't update while we're
1800         // in the middle of pausing, which could cause a visible glitch in
1801         // the "activity ending" transition.
1802         if (!mIsForegroundActivity) {
1803             if (VDBG) log("- updateScreen: not the foreground Activity! Bailing out...");
1804             return;
1805         }
1806
1807         // Update the state of the in-call menu items.
1808         if (mInCallMenu != null) {
1809             // TODO: do this only if the menu is visible!
1810             if (VDBG) log("- updateScreen: updating menu items...");
1811             boolean okToShowMenu = mInCallMenu.updateItems(mPhone);
1812             if (!okToShowMenu) {
1813                 // Uh oh: we were only trying to update the state of the
1814                 // menu items, but the logic in InCallMenu.updateItems()
1815                 // just decided the menu shouldn't be visible at all!
1816                 // (That's probably means that the call ended
1817                 // asynchronously while the menu was up.)
1818                 //
1819                 // So take the menu down ASAP.
1820                 if (VDBG) log("- updateScreen: Tried to update menu; now need to dismiss!");
1821                 // dismissMenu() has no effect if the menu is already closed.
1822                 dismissMenu(true);  // dismissImmediate = true
1823             }
1824         }
1825
1826         if (mInCallScreenMode == InCallScreenMode.MANAGE_CONFERENCE) {
1827             if (VDBG) log("- updateScreen: manage conference mode (NOT updating in-call UI)...");
1828             updateManageConferencePanelIfNecessary();
1829             return;
1830         } else if (mInCallScreenMode == InCallScreenMode.CALL_ENDED) {
1831             if (VDBG) log("- updateScreen: call ended state (NOT updating in-call UI)...");
1832             return;
1833         }
1834
1835         if (VDBG) log("- updateScreen: updating the in-call UI...");
1836         mCallCard.updateState(mPhone);
1837         updateDialpadVisibility();
1838         updateMenuButtonHint();
1839     }
1840
1841     /**
1842      * (Re)synchronizes the onscreen UI with the current state of the
1843      * Phone.
1844      *
1845      * @return InCallInitStatus.SUCCESS if we successfully updated the UI, or
1846      *    InCallInitStatus.PHONE_NOT_IN_USE if there was no phone state to sync
1847      *    with (ie. the phone was completely idle).  In the latter case, we
1848      *    shouldn't even be in the in-call UI in the first place, and it's
1849      *    the caller's responsibility to bail out of this activity (by
1850      *    calling finish()) if appropriate.
1851      */
1852     private InCallInitStatus syncWithPhoneState() {
1853         boolean updateSuccessful = false;
1854         if (DBG) log("syncWithPhoneState()...");
1855         if (VDBG) PhoneUtils.dumpCallState(mPhone);
1856         if (VDBG) dumpBluetoothState();
1857
1858         // Make sure the Phone is "in use".  (If not, we shouldn't be on
1859         // this screen in the first place.)
1860
1861         // Need to treat running MMI codes as a connection as well.
1862         if (!mForegroundCall.isIdle() || !mBackgroundCall.isIdle() || !mRingingCall.isIdle()
1863             || mPhone.getPhoneName() == "CDMA" || !mPhone.getPendingMmiCodes().isEmpty()) {
1864             if (VDBG) log("syncWithPhoneState: it's ok to be here; update the screen...");
1865             updateScreen();
1866             return InCallInitStatus.SUCCESS;
1867         }
1868
1869         if (DBG) log("syncWithPhoneState: phone is idle; we shouldn't be here!");
1870         return InCallInitStatus.PHONE_NOT_IN_USE;
1871     }
1872
1873     /**
1874      * Given the Intent we were initially launched with,
1875      * figure out the actual phone number we should dial.
1876      *
1877      * @return the phone number corresponding to the
1878      *   specified Intent, or null if the Intent is not
1879      *   a ACTION_CALL intent or if the intent's data is
1880      *   malformed or missing.
1881      *
1882      * @throws VoiceMailNumberMissingException if the intent
1883      *   contains a "voicemail" URI, but there's no voicemail
1884      *   number configured on the device.
1885      */
1886     private String getInitialNumber(Intent intent)
1887             throws PhoneUtils.VoiceMailNumberMissingException {
1888         String action = intent.getAction();
1889
1890         if (action == null) {
1891             return null;
1892         }
1893
1894         if (action != null && action.equals(Intent.ACTION_CALL) &&
1895                 intent.hasExtra(Intent.EXTRA_PHONE_NUMBER)) {
1896             return intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
1897         }
1898
1899         return PhoneUtils.getNumberFromIntent(this, mPhone, intent);
1900     }
1901
1902     /**
1903      * Make a call to whomever the intent tells us to.
1904      *
1905      * @param intent the Intent we were launched with
1906      * @return InCallInitStatus.SUCCESS if we successfully initiated an
1907      *    outgoing call.  If there was some kind of failure, return one of
1908      *    the other InCallInitStatus codes indicating what went wrong.
1909      */
1910     private InCallInitStatus placeCall(Intent intent) {
1911         if (VDBG) log("placeCall()...  intent = " + intent);
1912
1913         String number;
1914
1915         // Check the current ServiceState to make sure it's OK
1916         // to even try making a call.
1917         InCallInitStatus okToCallStatus = checkIfOkToInitiateOutgoingCall();
1918
1919         try {
1920             number = getInitialNumber(intent);
1921         } catch (PhoneUtils.VoiceMailNumberMissingException ex) {
1922             // If the call status is NOT in an acceptable state, it
1923             // may effect the way the voicemail number is being
1924             // retrieved.  Mask the VoiceMailNumberMissingException
1925             // with the underlying issue of the phone state.
1926             if (okToCallStatus != InCallInitStatus.SUCCESS) {
1927                 if (DBG) log("Voicemail number not reachable in current SIM card state.");
1928                 return okToCallStatus;
1929             }
1930             if (DBG) log("VoiceMailNumberMissingException from getInitialNumber()");
1931             return InCallInitStatus.VOICEMAIL_NUMBER_MISSING;
1932         }
1933
1934         if (number == null) {
1935             Log.w(LOG_TAG, "placeCall: couldn't get a phone number from Intent " + intent);
1936             return InCallInitStatus.NO_PHONE_NUMBER_SUPPLIED;
1937         }
1938
1939         boolean isEmergencyNumber = PhoneNumberUtils.isEmergencyNumber(number);
1940         boolean isEmergencyIntent = Intent.ACTION_CALL_EMERGENCY.equals(intent.getAction());
1941
1942         if (isEmergencyNumber && !isEmergencyIntent) {
1943             Log.e(LOG_TAG, "Non-CALL_EMERGENCY Intent " + intent
1944                     + " attempted to call emergency number " + number
1945                     + ".");
1946             return InCallInitStatus.CALL_FAILED;
1947         } else if (!isEmergencyNumber && isEmergencyIntent) {
1948             Log.e(LOG_TAG, "Received CALL_EMERGENCY Intent " + intent
1949                     + " with non-emergency number " + number
1950                     + " -- failing call.");
1951             return InCallInitStatus.CALL_FAILED;
1952         }
1953
1954         // need to make sure that the state is adjusted if we are ONLY
1955         // allowed to dial emergency numbers AND we encounter an
1956         // emergency number request.
1957         if (isEmergencyNumber && okToCallStatus == InCallInitStatus.EMERGENCY_ONLY) {
1958             okToCallStatus = InCallInitStatus.SUCCESS;
1959             if (DBG) log("Emergency number detected, changing state to: " + okToCallStatus);
1960         }
1961
1962         if (okToCallStatus != InCallInitStatus.SUCCESS) {
1963             // If this is an emergency call, we call the emergency call
1964             // handler activity to turn on the radio and do whatever else
1965             // is needed. For now, we finish the InCallScreen (since were
1966             // expecting a callback when the emergency call handler dictates
1967             // it) and just return the success state.
1968             if (isEmergencyNumber && (okToCallStatus == InCallInitStatus.POWER_OFF)) {
1969                 startActivity(intent.setClassName(this, EmergencyCallHandler.class.getName()));
1970                 if (DBG) log("placeCall: starting EmergencyCallHandler, finishing...");
1971                 finish();
1972                 return InCallInitStatus.SUCCESS;
1973             } else {
1974                 return okToCallStatus;
1975             }
1976         }
1977
1978         // We have a valid number, so try to actually place a call:
1979         //make sure we pass along the URI as a reference to the contact.
1980         int callStatus = PhoneUtils.placeCall(mPhone, number, intent.getData());
1981         switch (callStatus) {
1982             case PhoneUtils.CALL_STATUS_DIALED:
1983                 if (VDBG) log("placeCall: PhoneUtils.placeCall() succeeded for regular call '"
1984                              + number + "'.");
1985
1986                 // Any time we initiate a call, force the DTMF dialpad to
1987                 // close.  (We want to make sure the user can see the regular
1988                 // in-call UI while the new call is dialing, and when it
1989                 // first gets connected.)
1990                 mDialer.closeDialer(false);  // no "closing" animation
1991
1992                 // Also, in case a previous call was already active (i.e. if
1993                 // we just did "Add call"), clear out the "history" of DTMF
1994                 // digits you typed, to make sure it doesn't persist from the
1995                 // previous call to the new call.
1996                 // TODO: it would be more precise to do this when the actual
1997                 // phone state change happens (i.e. when a new foreground
1998                 // call appears and the previous call moves to the
1999                 // background), but the InCallScreen doesn't keep enough
2000                 // state right now to notice that specific transition in
2001                 // onPhoneStateChanged().
2002                 mDialer.clearDigits();
2003
2004                 return InCallInitStatus.SUCCESS;
2005             case PhoneUtils.CALL_STATUS_DIALED_MMI:
2006                 if (DBG) log("placeCall: specified number was an MMI code: '" + number + "'.");
2007                 // The passed-in number was an MMI code, not a regular phone number!
2008                 // This isn't really a failure; the Dialer may have deliberately
2009                 // fired a ACTION_CALL intent to dial an MMI code, like for a
2010                 // USSD call.
2011                 //
2012                 // Presumably an MMI_INITIATE message will come in shortly
2013                 // (and we'll bring up the "MMI Started" dialog), or else
2014                 // an MMI_COMPLETE will come in (which will take us to a
2015                 // different Activity; see PhoneUtils.displayMMIComplete()).
2016                 return InCallInitStatus.DIALED_MMI;
2017             case PhoneUtils.CALL_STATUS_FAILED:
2018                 Log.w(LOG_TAG, "placeCall: PhoneUtils.placeCall() FAILED for number '"
2019                       + number + "'.");
2020                 // We couldn't successfully place the call; there was some
2021                 // failure in the telephony layer.
2022                 return InCallInitStatus.CALL_FAILED;
2023             default:
2024                 Log.w(LOG_TAG, "placeCall: unknown callStatus " + callStatus
2025                       + " from PhoneUtils.placeCall() for number '" + number + "'.");
2026                 return InCallInitStatus.SUCCESS;  // Try to continue anyway...
2027         }
2028     }
2029
2030     /**
2031      * Checks the current ServiceState to make sure it's OK
2032      * to try making an outgoing call to the specified number.
2033      *
2034      * @return InCallInitStatus.SUCCESS if it's OK to try calling the specified
2035      *    number.  If not, like if the radio is powered off or we have no
2036      *    signal, return one of the other InCallInitStatus codes indicating what
2037      *    the problem is.
2038      */
2039     private InCallInitStatus checkIfOkToInitiateOutgoingCall() {
2040         // Watch out: do NOT use PhoneStateIntentReceiver.getServiceState() here;
2041         // that's not guaranteed to be fresh.  To synchronously get the
2042         // CURRENT service state, ask the Phone object directly:
2043         int state = mPhone.getServiceState().getState();
2044         if (VDBG) log("checkIfOkToInitiateOutgoingCall: ServiceState = " + state);
2045
2046         switch (state) {
2047             case ServiceState.STATE_IN_SERVICE:
2048                 // Normal operation.  It's OK to make outgoing calls.
2049                 return InCallInitStatus.SUCCESS;
2050
2051
2052             case ServiceState.STATE_POWER_OFF:
2053                 // Radio is explictly powered off.
2054                 return InCallInitStatus.POWER_OFF;
2055
2056             case ServiceState.STATE_OUT_OF_SERVICE:
2057             case ServiceState.STATE_EMERGENCY_ONLY:
2058                 // The phone is registered, but locked. Only emergency
2059                 // numbers are allowed.
2060                 return InCallInitStatus.EMERGENCY_ONLY;
2061             default:
2062                 throw new IllegalStateException("Unexpected ServiceState: " + state);
2063         }
2064     }
2065
2066     private void handleMissingVoiceMailNumber() {
2067         if (DBG) log("handleMissingVoiceMailNumber");
2068
2069         final Message msg = Message.obtain(mHandler);
2070         msg.what = DONT_ADD_VOICEMAIL_NUMBER;
2071
2072         final Message msg2 = Message.obtain(mHandler);
2073         msg2.what = ADD_VOICEMAIL_NUMBER;
2074
2075         mMissingVoicemailDialog = new AlertDialog.Builder(this)
2076                 .setTitle(R.string.no_vm_number)
2077                 .setMessage(R.string.no_vm_number_msg)
2078                 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2079                         public void onClick(DialogInterface dialog, int which) {
2080                             if (VDBG) log("Missing voicemail AlertDialog: POSITIVE click...");
2081                             msg.sendToTarget();  // see dontAddVoiceMailNumber()
2082                             PhoneApp.getInstance().pokeUserActivity();
2083                         }})
2084                 .setNegativeButton(R.string.add_vm_number_str,
2085                                    new DialogInterface.OnClickListener() {
2086                         public void onClick(DialogInterface dialog, int which) {
2087                             if (VDBG) log("Missing voicemail AlertDialog: NEGATIVE click...");
2088                             msg2.sendToTarget();  // see addVoiceMailNumber()
2089                             PhoneApp.getInstance().pokeUserActivity();
2090                         }})
2091                 .setOnCancelListener(new OnCancelListener() {
2092                         public void onCancel(DialogInterface dialog) {
2093                             if (VDBG) log("Missing voicemail AlertDialog: CANCEL handler...");
2094                             msg.sendToTarget();  // see dontAddVoiceMailNumber()
2095                             PhoneApp.getInstance().pokeUserActivity();
2096                         }})
2097                 .create();
2098
2099         // When the dialog is up, completely hide the in-call UI
2100         // underneath (which is in a partially-constructed state).
2101         mMissingVoicemailDialog.getWindow().addFlags(
2102                 WindowManager.LayoutParams.FLAG_DIM_BEHIND);
2103
2104         mMissingVoicemailDialog.show();
2105     }
2106
2107     private void addVoiceMailNumberPanel() {
2108         if (mMissingVoicemailDialog != null) {
2109             mMissingVoicemailDialog.dismiss();
2110             mMissingVoicemailDialog = null;
2111         }
2112         if (DBG) log("show vm setting, finishing...");
2113         finish();
2114
2115         // navigate to the Voicemail setting in the Call Settings activity.
2116         Intent intent = new Intent(CallFeaturesSetting.ACTION_ADD_VOICEMAIL);
2117         intent.setClass(this, CallFeaturesSetting.class);
2118         startActivity(intent);
2119     }
2120
2121     private void dontAddVoiceMailNumber() {
2122         if (mMissingVoicemailDialog != null) {
2123             mMissingVoicemailDialog.dismiss();
2124             mMissingVoicemailDialog = null;
2125         }
2126         if (DBG) log("dontAddVoiceMailNumber: finishing...");
2127         finish();
2128     }
2129
2130     /**
2131      * Do some delayed cleanup after a Phone call gets disconnected.
2132      *
2133      * This method gets called a couple of seconds after any DISCONNECT
2134      * event from the Phone; it's triggered by the
2135      * DELAYED_CLEANUP_AFTER_DISCONNECT message we send in onDisconnect().
2136      *
2137      * If the Phone is totally idle right now, that means we've already
2138      * shown the "call ended" state for a couple of seconds, and it's now
2139      * time to finish() this activity.
2140      *
2141      * If the Phone is *not* idle right now, that probably means that one
2142      * call ended but the other line is still in use.  In that case, we
2143      * *don't* exit the in-call screen, but we at least turn off the
2144      * backlight (which we turned on in onDisconnect().)
2145      */
2146     private void delayedCleanupAfterDisconnect() {
2147         if (VDBG) log("delayedCleanupAfterDisconnect()...  Phone state = " + mPhone.getState());
2148
2149         // Clean up any connections in the DISCONNECTED state.
2150         //
2151         // [Background: Even after a connection gets disconnected, its
2152         // Connection object still stays around, in the special
2153         // DISCONNECTED state.  This is necessary because we we need the
2154         // caller-id information from that Connection to properly draw the
2155         // "Call ended" state of the CallCard.
2156         //   But at this point we truly don't need that connection any
2157         // more, so tell the Phone that it's now OK to to clean up any
2158         // connections still in that state.]
2159         mPhone.clearDisconnected();
2160
2161         final PhoneApp app = PhoneApp.getInstance();
2162         if (!phoneIsInUse()) {
2163             // Phone is idle!  We should exit this screen now.
2164             if (DBG) log("- delayedCleanupAfterDisconnect: phone is idle...");
2165
2166             // No need to re-enable keyguard or screen wake state here;
2167             // that happens in onPause() when we actually exit.
2168
2169             // And (finally!) exit from the in-call screen
2170             // (but not if we're already in the process of pausing...)
2171             if (mIsForegroundActivity) {
2172                 if (DBG) log("- delayedCleanupAfterDisconnect: finishing...");
2173
2174                 // If this is a call that was initiated by the user, and
2175                 // we're *not* in emergency mode, finish the call by
2176                 // taking the user to the Call Log.
2177                 // Otherwise we simply call finish(), which will take us
2178                 // back to wherever we came from.
2179                 if (mShowCallLogAfterDisconnect && !isPhoneStateRestricted()) {
2180                     if (VDBG) log("- Show Call Log after disconnect...");
2181                     final Intent intent = PhoneApp.createCallLogIntent();
2182                     startActivity(intent);
2183                     // Even in this case we still call finish() (below),
2184                     // to make sure we don't stay in the activity history.
2185                 }
2186
2187                 finish();
2188             }
2189         } else {
2190             // The phone is still in use.  Stay here in this activity, but
2191             // we don't need to keep the screen on.
2192             if (DBG) log("- delayedCleanupAfterDisconnect: staying on the InCallScreen...");
2193             if (DBG) PhoneUtils.dumpCallState(mPhone);
2194             // No need to re-enable keyguard or screen wake state here;
2195             // should be taken care of in onPhoneStateChanged();
2196         }
2197     }
2198
2199
2200     //
2201     // Callbacks for buttons / menu items.
2202     //
2203
2204     public void onClick(View view) {
2205         int id = view.getId();
2206         if (VDBG) log("onClick(View " + view + ", id " + id + ")...");
2207         if (VDBG && view instanceof InCallMenuItemView) {
2208             InCallMenuItemView item = (InCallMenuItemView) view;
2209             log("  ==> menu item! " + item);
2210         }
2211
2212         // Most menu items dismiss the menu immediately once you click
2213         // them.  But some items (the "toggle" buttons) are different:
2214         // they want the menu to stay visible for a second afterwards to
2215         // give you feedback about the state change.
2216         boolean dismissMenuImmediate = true;
2217         Context context = getApplicationContext();
2218
2219         switch (id) {
2220             case R.id.menuAnswerAndHold:
2221                 if (VDBG) log("onClick: AnswerAndHold...");
2222                 internalAnswerCall();  // Automatically holds the current active call
2223                 break;
2224
2225             case R.id.menuAnswerAndEnd:
2226                 if (VDBG) log("onClick: AnswerAndEnd...");
2227                 internalAnswerAndEnd();
2228                 break;
2229
2230             case R.id.menuSwapCalls:
2231                 if (VDBG) log("onClick: SwapCalls...");
2232                 internalSwapCalls();
2233                 break;
2234
2235             case R.id.menuMergeCalls:
2236                 if (VDBG) log("onClick: MergeCalls...");
2237                 PhoneUtils.mergeCalls(mPhone);
2238                 break;
2239
2240             case R.id.menuManageConference:
2241                 if (VDBG) log("onClick: ManageConference...");
2242                 // Show the Manage Conference panel.
2243                 setInCallScreenMode(InCallScreenMode.MANAGE_CONFERENCE);
2244                 break;
2245
2246             case R.id.menuShowDialpad:
2247                 if (VDBG) log("onClick: Show/hide dialpad...");
2248                 if (mDialer.isOpened()) {
2249                     mDialer.closeDialer(true);  // do the "closing" animation
2250                 } else {
2251                     mDialer.openDialer(true);  // do the "opening" animation
2252                 }
2253                 break;
2254
2255             case R.id.manage_done:  // mButtonManageConferenceDone
2256                 if (VDBG) log("onClick: mButtonManageConferenceDone...");
2257                 // Hide the Manage Conference panel, return to NORMAL mode.
2258                 setInCallScreenMode(InCallScreenMode.NORMAL);
2259                 break;
2260
2261             case R.id.menuSpeaker:
2262                 if (VDBG) log("onClick: Speaker...");
2263                 // TODO: Turning on the speaker seems to enable the mic
2264                 //   whether or not the "mute" feature is active!
2265                 // Not sure if this is an feature of the telephony API
2266                 //   that I need to handle specially, or just a bug.
2267                 boolean newSpeakerState = !PhoneUtils.isSpeakerOn(context);
2268                 if (newSpeakerState && isBluetoothAvailable() && isBluetoothAudioConnected()) {
2269                     disconnectBluetoothAudio();
2270                 }
2271                 PhoneUtils.turnOnSpeaker(context, newSpeakerState);
2272
2273                 if (newSpeakerState) {
2274                     // The "touch lock" overlay is NEVER used when the speaker is on.
2275                     enableTouchLock(false);
2276                 } else {
2277                     // User just turned the speaker *off*.  If the dialpad
2278                     // is open, we need to start the timer that will
2279                     // eventually bring up the "touch lock" overlay.
2280                     if (mDialer.isOpened() && !isTouchLocked()) {
2281                         resetTouchLockTimer();
2282                     }
2283                 }
2284
2285                 // This is a "toggle" button; let the user see the new state for a moment.
2286                 dismissMenuImmediate = false;
2287                 break;
2288
2289             case R.id.menuBluetooth:
2290                 if (VDBG) log("onClick: Bluetooth...");
2291                 onBluetoothClick(context);
2292                 // This is a "toggle" button; let the user see the new state for a moment.
2293                 dismissMenuImmediate = false;
2294                 break;
2295
2296             case R.id.menuMute:
2297                 if (VDBG) log("onClick: Mute...");
2298                 boolean newMuteState = !PhoneUtils.getMute(mPhone);
2299                 PhoneUtils.setMute(mPhone, newMuteState);
2300                 // This is a "toggle" button; let the user see the new state for a moment.
2301                 dismissMenuImmediate = false;
2302                 break;
2303
2304             case R.id.menuHold:
2305                 if (VDBG) log("onClick: Hold...");
2306                 onHoldClick();
2307                 // This is a "toggle" button; let the user see the new state for a moment.
2308                 dismissMenuImmediate = false;
2309                 break;
2310
2311             case R.id.menuAddCall:
2312                 if (VDBG) log("onClick: AddCall...");
2313                 PhoneUtils.startNewCall(mPhone);  // Fires off a ACTION_DIAL intent
2314                 break;
2315
2316             case R.id.menuEndCall:
2317                 if (VDBG) log("onClick: EndCall...");
2318                 PhoneUtils.hangup(mPhone);
2319                 break;
2320
2321             default:
2322                 Log.w(LOG_TAG,
2323                       "Got click from unexpected View ID " + id + " (View = " + view + ")");
2324                 break;
2325         }
2326
2327         if (ENABLE_PHONE_UI_EVENT_LOGGING) {
2328             // TODO: For now we care only about whether the user uses the
2329             // in-call buttons at all.  But in the future we may want to
2330             // log exactly which buttons are being clicked.  (Maybe just
2331             // call view.getText() here, and append that to the event value?)
2332             Checkin.logEvent(getContentResolver(),
2333                              Checkin.Events.Tag.PHONE_UI,
2334                              PHONE_UI_EVENT_BUTTON_CLICK);
2335         }
2336
2337         // If the user just clicked a "stateful" menu item (i.e. one of
2338         // the toggle buttons), we keep the menu onscreen briefly to
2339         // provide visual feedback.  Since we want the user to see the
2340         // *new* current state, force the menu items to update right now.
2341         //
2342         // Note that some toggle buttons ("Hold" in particular) do NOT
2343         // immediately change the state of the Phone.  In that case, the
2344         // updateItems() call below won't have any visible effect.
2345         // Instead, the menu will get updated by the updateScreen() call
2346         // that happens from onPhoneStateChanged().
2347
2348         if (!dismissMenuImmediate) {
2349             // TODO: mInCallMenu.updateItems() is a very big hammer; it
2350             // would be more efficient to update *only* the menu item(s)
2351             // we just changed.  (Doing it this way doesn't seem to cause
2352             // a noticeable performance problem, though.)
2353             if (VDBG) log("- onClick: updating menu to show 'new' current state...");
2354             boolean okToShowMenu = mInCallMenu.updateItems(mPhone);
2355             if (!okToShowMenu) {
2356                 // Uh oh.  All we tried to do was update the state of the
2357                 // menu items, but the logic in InCallMenu.updateItems()
2358                 // just decided the menu shouldn't be visible at all!
2359                 // (That probably means that the call ended asynchronously
2360                 // while the menu was up.)
2361                 //
2362                 // That's OK; just make sure to take the menu down ASAP.
2363                 if (VDBG) log("onClick: Tried to update menu, but now need to take it down!");
2364                 dismissMenuImmediate = true;
2365             }
2366         }
2367
2368         // Any menu item counts as explicit "user activity".
2369         PhoneApp.getInstance().pokeUserActivity();
2370
2371         // Finally, *any* action handled here closes the menu (either
2372         // immediately, or after a short delay).
2373         //
2374         // Note that some of the clicks we handle here aren't even menu
2375         // items in the first place, like the mButtonManageConferenceDone
2376         // button.  That's OK; if the menu is already closed, the
2377         // dismissMenu() call does nothing.
2378         dismissMenu(dismissMenuImmediate);
2379     }
2380
2381     private void onHoldClick() {
2382         if (VDBG) log("onHoldClick()...");
2383
2384         final boolean hasActiveCall = !mForegroundCall.isIdle();
2385         final boolean hasHoldingCall = !mBackgroundCall.isIdle();
2386         if (VDBG) log("- hasActiveCall = " + hasActiveCall
2387                       + ", hasHoldingCall = " + hasHoldingCall);
2388         boolean newHoldState;
2389         boolean holdButtonEnabled;
2390         if (hasActiveCall && !hasHoldingCall) {
2391             // There's only one line in use, and that line is active.
2392             PhoneUtils.switchHoldingAndActive(mPhone);  // Really means "hold" in this state
2393             newHoldState = true;
2394             holdButtonEnabled = true;
2395         } else if (!hasActiveCall && hasHoldingCall) {
2396             // There's only one line in use, and that line is on hold.
2397             PhoneUtils.switchHoldingAndActive(mPhone);  // Really means "unhold" in this state
2398             newHoldState = false;
2399             holdButtonEnabled = true;
2400         } else {
2401             // Either zero or 2 lines are in use; "hold/unhold" is meaningless.
2402             newHoldState = false;
2403             holdButtonEnabled = false;
2404         }
2405         // TODO: we *could* now forcibly update the "Hold" button based on
2406         // "newHoldState" and "holdButtonEnabled".  But for now, do
2407         // nothing here, and instead let the menu get updated when the
2408         // onPhoneStateChanged() callback comes in.  (This seems to be
2409         // responsive enough.)
2410     }
2411
2412     private void onBluetoothClick(Context context) {
2413         if (VDBG) log("onBluetoothClick()...");
2414
2415         if (isBluetoothAvailable()) {
2416             // Toggle the bluetooth audio connection state:
2417             if (isBluetoothAudioConnected()) {
2418                 disconnectBluetoothAudio();
2419             } else {
2420                 // Manually turn the speaker phone off, instead of allowing the
2421                 // Bluetooth audio routing handle it.  This ensures that the rest
2422                 // of the speakerphone code is executed, and reciprocates the
2423                 // menuSpeaker code above in onClick().  The onClick() code
2424                 // disconnects the active bluetooth headsets when the
2425                 // speakerphone is turned on.
2426                 if (PhoneUtils.isSpeakerOn(context)) {
2427                     PhoneUtils.turnOnSpeaker(context, false);
2428                 }
2429
2430                 connectBluetoothAudio();
2431             }
2432         } else {
2433             // Bluetooth isn't available; the "Audio" button shouldn't have
2434             // been enabled in the first place!
2435             Log.w(LOG_TAG, "Got onBluetoothClick, but bluetooth is unavailable");
2436         }
2437     }
2438
2439     /**
2440      * Updates the "Press Menu for more options" hint based on the current
2441      * state of the Phone.
2442      */
2443     private void updateMenuButtonHint() {
2444         if (VDBG) log("updateMenuButtonHint()...");
2445         boolean hintVisible = true;
2446
2447         final boolean hasRingingCall = !mRingingCall.isIdle();
2448         final boolean hasActiveCall = !mForegroundCall.isIdle();
2449         final boolean hasHoldingCall = !mBackgroundCall.isIdle();
2450
2451         // The hint is hidden only when there's no menu at all,
2452         // which only happens in a few specific cases:
2453         if (mInCallScreenMode == InCallScreenMode.CALL_ENDED) {
2454             // The "Call ended" state.
2455             hintVisible = false;
2456         } else if (hasRingingCall && !(hasActiveCall && !hasHoldingCall)) {
2457             // An incoming call where you *don't* have the option to
2458             // "answer & end" or "answer & hold".
2459             hintVisible = false;
2460         } else if (!phoneIsInUse()) {
2461             // Or if the phone is totally idle (like if an error dialog
2462             // is up, or an MMI is running.)
2463             hintVisible = false;
2464         }
2465         int hintVisibility = (hintVisible) ? View.VISIBLE : View.GONE;
2466
2467         // We actually have two separate "menu button hint" TextViews; one
2468         // used only in portrait mode (part of the CallCard) and one used
2469         // only in landscape mode (part of the InCallScreen.)
2470         TextView callCardMenuButtonHint = mCallCard.getMenuButtonHint();
2471         if (ConfigurationHelper.isLandscape()) {
2472             callCardMenuButtonHint.setVisibility(View.GONE);
2473             mMenuButtonHint.setVisibility(hintVisibility);
2474         } else {
2475             callCardMenuButtonHint.setVisibility(hintVisibility);
2476             mMenuButtonHint.setVisibility(View.GONE);
2477         }
2478
2479         // TODO: Consider hiding the hint(s) whenever the menu is onscreen!
2480         // (Currently, the menu is rendered on top of the hint, but the
2481         // menu is semitransparent so you can still see the hint
2482         // underneath, and the hint is *just* visible enough to be
2483         // distracting.)
2484     }
2485
2486     /**
2487      * Brings up UI to handle the various error conditions that
2488      * can occur when first initializing the in-call UI.
2489      * This is called from onResume() if we encountered
2490      * an error while processing our initial Intent.
2491      *
2492      * @param status one of the InCallInitStatus error codes.
2493      */
2494     private void handleStartupError(InCallInitStatus status) {
2495         if (DBG) log("handleStartupError(): status = " + status);
2496
2497         // NOTE that the regular Phone UI is in an uninitialized state at
2498         // this point, so we don't ever want the user to see it.
2499         // That means:
2500         // - Any cases here that need to go to some other activity should
2501         //   call startActivity() AND immediately call finish() on this one.
2502         // - Any cases here that bring up a Dialog must ensure that the
2503         //   Dialog handles both OK *and* cancel by calling finish() on this
2504         //   Activity.  (See showGenericErrorDialog() for an example.)
2505
2506         switch(status) {
2507
2508             case VOICEMAIL_NUMBER_MISSING:
2509                 // Bring up the "Missing Voicemail Number" dialog, which
2510                 // will ultimately take us to some other Activity (or else
2511                 // just bail out of this activity.)
2512                 handleMissingVoiceMailNumber();
2513                 break;
2514
2515             case POWER_OFF:
2516                 // Radio is explictly powered off.
2517
2518                 // TODO: This UI is ultra-simple for 1.0.  It would be nicer
2519                 // to bring up a Dialog instead with the option "turn on radio
2520                 // now".  If selected, we'd turn the radio on, wait for
2521                 // network registration to complete, and then make the call.
2522
2523                 showGenericErrorDialog(R.string.incall_error_power_off, true);
2524                 break;
2525
2526             case EMERGENCY_ONLY:
2527                 // Only emergency numbers are allowed, but we tried to dial
2528                 // a non-emergency number.
2529                 showGenericErrorDialog(R.string.incall_error_emergency_only, true);
2530                 break;
2531
2532             case PHONE_NOT_IN_USE:
2533                 // This error is handled directly in onResume() (by bailing
2534                 // out of the activity.)  We should never see it here.
2535                 Log.w(LOG_TAG,
2536                       "handleStartupError: unexpected PHONE_NOT_IN_USE status");
2537                 break;
2538
2539             case NO_PHONE_NUMBER_SUPPLIED:
2540                 // The supplied Intent didn't contain a valid phone number.
2541                 // TODO: Need UI spec for this failure case; for now just
2542                 // show a generic error.
2543                 showGenericErrorDialog(R.string.incall_error_no_phone_number_supplied, true);
2544                 break;
2545
2546             case DIALED_MMI:
2547                 // Our initial phone number was actually an MMI sequence.
2548                 // There's no real "error" here, but we do bring up the
2549                 // a Toast (as requested of the New UI paradigm).
2550                 //
2551                 // In-call MMIs do not trigger the normal MMI Initiate
2552                 // Notifications, so we should notify the user here.
2553                 // Otherwise, the code in PhoneUtils.java should handle
2554                 // user notifications in the form of Toasts or Dialogs.
2555                 if (mPhone.getState() == Phone.State.OFFHOOK) {
2556                     Toast.makeText(this, R.string.incall_status_dialed_mmi, Toast.LENGTH_SHORT)
2557                         .show();
2558                 }
2559                 break;
2560
2561             case CALL_FAILED:
2562                 // We couldn't successfully place the call; there was some
2563                 // failure in the telephony layer.
2564                 // TODO: Need UI spec for this failure case; for now just
2565                 // show a generic error.
2566                 showGenericErrorDialog(R.string.incall_error_call_failed, true);
2567                 break;
2568
2569             default:
2570                 Log.w(LOG_TAG, "handleStartupError: unexpected status code " + status);
2571                 showGenericErrorDialog(R.string.incall_error_call_failed, true);
2572                 break;
2573         }
2574     }
2575
2576     /**
2577      * Utility function to bring up a generic "error" dialog, and then bail
2578      * out of the in-call UI when the user hits OK (or the BACK button.)
2579      */
2580     private void showGenericErrorDialog(int resid, boolean isStartupError) {
2581         CharSequence msg = getResources().getText(resid);
2582         if (DBG) log("showGenericErrorDialog('" + msg + "')...");
2583
2584         // create the clicklistener and cancel listener as needed.
2585         DialogInterface.OnClickListener clickListener;
2586         OnCancelListener cancelListener;
2587         if (isStartupError) {
2588             clickListener = new DialogInterface.OnClickListener() {
2589                 public void onClick(DialogInterface dialog, int which) {
2590                     bailOutAfterErrorDialog();
2591                 }};
2592             cancelListener = new OnCancelListener() {
2593                 public void onCancel(DialogInterface dialog) {
2594                     bailOutAfterErrorDialog();
2595                 }};
2596         } else {
2597             clickListener = new DialogInterface.OnClickListener() {
2598                 public void onClick(DialogInterface dialog, int which) {
2599                     delayedCleanupAfterDisconnect();
2600                 }};
2601             cancelListener = new OnCancelListener() {
2602                 public void onCancel(DialogInterface dialog) {
2603                     delayedCleanupAfterDisconnect();
2604                 }};
2605         }
2606
2607         // TODO: Consider adding a setTitle() call here (with some generic
2608         // "failure" title?)
2609         mGenericErrorDialog = new AlertDialog.Builder(this)
2610                 .setMessage(msg)
2611                 .setPositiveButton(R.string.ok, clickListener)
2612                 .setOnCancelListener(cancelListener)
2613                 .create();
2614
2615         // When the dialog is up, completely hide the in-call UI
2616         // underneath (which is in a partially-constructed state).
2617         mGenericErrorDialog.getWindow().addFlags(
2618                 WindowManager.LayoutParams.FLAG_DIM_BEHIND);
2619
2620         mGenericErrorDialog.show();
2621     }
2622
2623     private void bailOutAfterErrorDialog() {
2624         if (mGenericErrorDialog != null) {
2625             if (VDBG) log("bailOutAfterErrorDialog: DISMISSING mGenericErrorDialog.");
2626             mGenericErrorDialog.dismiss();
2627             mGenericErrorDialog = null;
2628         }
2629         if (DBG) log("bailOutAfterErrorDialog(): finishing...");
2630         finish();
2631     }
2632
2633     /**
2634      * Dismisses (and nulls out) all persistent Dialogs managed
2635      * by the InCallScreen.  Useful if (a) we're about to bring up
2636      * a dialog and want to pre-empt any currently visible dialogs,
2637      * or (b) as a cleanup step when the Activity is going away.
2638      */
2639     private void dismissAllDialogs() {
2640         if (VDBG) log("dismissAllDialogs()...");
2641
2642         // Note it's safe to dismiss() a dialog that's already dismissed.
2643         // (Even if the AlertDialog object(s) below are still around, it's
2644         // possible that the actual dialog(s) may have already been
2645         // dismissed by the user.)
2646
2647         if (mMissingVoicemailDialog != null) {
2648             if (VDBG) log("- DISMISSING mMissingVoicemailDialog.");
2649             mMissingVoicemailDialog.dismiss();
2650             mMissingVoicemailDialog = null;
2651         }
2652         if (mMmiStartedDialog != null) {
2653             if (VDBG) log("- DISMISSING mMmiStartedDialog.");
2654             mMmiStartedDialog.dismiss();
2655             mMmiStartedDialog = null;
2656         }
2657         if (mGenericErrorDialog != null) {
2658             if (VDBG) log("- DISMISSING mGenericErrorDialog.");
2659             mGenericErrorDialog.dismiss();
2660             mGenericErrorDialog = null;
2661         }
2662         if (mSuppServiceFailureDialog != null) {
2663             if (VDBG) log("- DISMISSING mSuppServiceFailureDialog.");
2664             mSuppServiceFailureDialog.dismiss();
2665             mSuppServiceFailureDialog = null;
2666         }
2667         if (mWaitPromptDialog != null) {
2668             if (VDBG) log("- DISMISSING mWaitPromptDialog.");
2669             mWaitPromptDialog.dismiss();
2670             mWaitPromptDialog = null;
2671         }
2672         if (mWildPromptDialog != null) {
2673             if (VDBG) log("- DISMISSING mWildPromptDialog.");
2674             mWildPromptDialog.dismiss();
2675             mWildPromptDialog = null;
2676         }
2677     }
2678
2679
2680     //
2681     // Helper functions for answering incoming calls.
2682     //
2683
2684     /**
2685      * Answer the ringing call.
2686      */
2687     /* package */ void internalAnswerCall() {
2688         if (DBG) log("internalAnswerCall()...");
2689         // if (DBG) PhoneUtils.dumpCallState(mPhone);
2690         PhoneUtils.answerCall(mPhone);  // Automatically holds the current active call,
2691                                         // if there is one
2692     }
2693
2694     /**
2695      * Answer the ringing call *and* hang up the ongoing call.
2696      */
2697     /* package */ void internalAnswerAndEnd() {
2698         if (DBG) log("internalAnswerAndEnd()...");
2699         // if (DBG) PhoneUtils.dumpCallState(mPhone);
2700         PhoneUtils.answerAndEndActive(mPhone);
2701     }
2702
2703     /**
2704      * Answer the ringing call, in the special case where both lines
2705      * are already in use.
2706      *
2707      * We "answer incoming, end ongoing" in this case, according to the
2708      * current UI spec.
2709      */
2710     /* package */ void internalAnswerCallBothLinesInUse() {
2711         if (DBG) log("internalAnswerCallBothLinesInUse()...");
2712         // if (DBG) PhoneUtils.dumpCallState(mPhone);
2713
2714         PhoneUtils.answerAndEndActive(mPhone);
2715         // Alternatively, we could use
2716         //    PhoneUtils.answerAndEndHolding(mPhone);
2717         // here to end the on-hold call instead.
2718     }
2719
2720     /**
2721      * Hang up the ringing call (aka "Don't answer").
2722      */
2723     /* package */ void internalHangupRingingCall() {
2724         if (DBG) log("internalHangupRingingCall()...");
2725         PhoneUtils.hangupRingingCall(mPhone);
2726     }
2727
2728     /**
2729      * InCallScreen-specific wrapper around PhoneUtils.switchHoldingAndActive().
2730      */
2731     private void internalSwapCalls() {
2732         if (VDBG) log("internalSwapCalls()...");
2733
2734         // Any time we swap calls, force the DTMF dialpad to close.
2735         // (We want the regular in-call UI to be visible right now, so the
2736         // user can clearly see which call is now in the foreground.)
2737         mDialer.closeDialer(true);  // do the "closing" animation
2738
2739         // Also, clear out the "history" of DTMF digits you typed, to make
2740         // sure you don't see digits from call #1 while call #2 is active.
2741         // (Yes, this does mean that swapping calls twice will cause you
2742         // to lose any previous digits from the current call; see the TODO
2743         // comment on DTMFTwelvKeyDialer.clearDigits() for more info.)
2744         mDialer.clearDigits();
2745
2746         // Swap the fg and bg calls.
2747         PhoneUtils.switchHoldingAndActive(mPhone);
2748     }
2749
2750     //
2751     // "Manage conference" UI.
2752     //
2753     // TODO: There's a lot of code here, and this source file is already too large.
2754     // Consider moving all this code out to a separate class.
2755     //
2756
2757     private void initManageConferencePanel() {
2758         if (VDBG) log("initManageConferencePanel()...");
2759         if (mManageConferencePanel == null) {
2760             mManageConferencePanel = (ViewGroup) findViewById(R.id.manageConferencePanel);
2761
2762             // set up the Conference Call chronometer
2763             mConferenceTime = (Chronometer) findViewById(R.id.manageConferencePanelHeader);
2764             mConferenceTime.setFormat(getString(R.string.caller_manage_header));
2765
2766             // Create list of conference call widgets
2767             mConferenceCallList = new ViewGroup[MAX_CALLERS_IN_CONFERENCE];
2768             {
2769                 final int[] viewGroupIdList = {R.id.caller0, R.id.caller1, R.id.caller2,
2770                         R.id.caller3, R.id.caller4};
2771                 for (int i = 0; i < MAX_CALLERS_IN_CONFERENCE; i++) {
2772                     mConferenceCallList[i] = (ViewGroup) findViewById(viewGroupIdList[i]);
2773                 }
2774             }
2775
2776             mButtonManageConferenceDone =
2777                     (Button) findViewById(R.id.manage_done);
2778             mButtonManageConferenceDone.setOnClickListener(this);
2779         }
2780     }
2781
2782     /**
2783      * Sets the current high-level "mode" of the in-call UI.
2784      *
2785      * NOTE: if newMode is CALL_ENDED, the caller is responsible for
2786      * posting a delayed DELAYED_CLEANUP_AFTER_DISCONNECT message, to make
2787      * sure the "call ended" state goes away after a couple of seconds.
2788      */
2789     private void setInCallScreenMode(InCallScreenMode newMode) {
2790         if (VDBG) log("setInCallScreenMode: " + newMode);
2791         mInCallScreenMode = newMode;
2792         switch (mInCallScreenMode) {
2793             case MANAGE_CONFERENCE:
2794                 if (!PhoneUtils.isConferenceCall(mForegroundCall)) {
2795                     Log.w(LOG_TAG, "MANAGE_CONFERENCE: no active conference call!");
2796                     // Hide the Manage Conference panel, return to NORMAL mode.
2797                     setInCallScreenMode(InCallScreenMode.NORMAL);
2798                     return;
2799                 }
2800                 List<Connection> connections = mForegroundCall.getConnections();
2801                 // There almost certainly will be > 1 connection,
2802                 // since isConferenceCall() just returned true.
2803                 if ((connections == null) || (connections.size() <= 1)) {
2804                     Log.w(LOG_TAG,
2805                           "MANAGE_CONFERENCE: Bogus TRUE from isConferenceCall(); connections = "
2806                           + connections);
2807                     // Hide the Manage Conference panel, return to NORMAL mode.
2808                     setInCallScreenMode(InCallScreenMode.NORMAL);
2809                     return;
2810                 }
2811
2812                 initManageConferencePanel();  // if necessary
2813                 updateManageConferencePanel(connections);
2814
2815                 // The "Manage conference" UI takes up the full main frame,
2816                 // replacing the inCallPanel and CallCard PopupWindow.
2817                 mManageConferencePanel.setVisibility(View.VISIBLE);
2818
2819                 // start the chronometer.
2820                 long callDuration = mForegroundCall.getEarliestConnection().getDurationMillis();
2821                 mConferenceTime.setBase(SystemClock.elapsedRealtime() - callDuration);
2822                 mConferenceTime.start();
2823
2824                 mInCallPanel.setVisibility(View.GONE);
2825                 mDialer.hideDTMFDisplay(true);
2826
2827                 break;
2828
2829             case CALL_ENDED:
2830                 // Display the CallCard (in the "Call ended" state)
2831                 // and hide all other UI.
2832
2833                 if (mManageConferencePanel != null) {
2834                     mManageConferencePanel.setVisibility(View.GONE);
2835                     // stop the timer if the panel is hidden.
2836                     mConferenceTime.stop();
2837                 }
2838                 updateMenuButtonHint();  // Hide the Menu button hint
2839
2840                 // Make sure the CallCard (which is a child of mInCallPanel) is visible.
2841                 mInCallPanel.setVisibility(View.VISIBLE);
2842                 mDialer.hideDTMFDisplay(false);
2843
2844                 break;
2845
2846             case NORMAL:
2847                 mInCallPanel.setVisibility(View.VISIBLE);
2848                 mDialer.hideDTMFDisplay(false);
2849                 if (mManageConferencePanel != null) {
2850                     mManageConferencePanel.setVisibility(View.GONE);
2851                     // stop the timer if the panel is hidden.
2852                     mConferenceTime.stop();
2853                 }
2854                 break;
2855         }
2856
2857         // Update the visibility of the DTMF dialer tab on any state
2858         // change.
2859         updateDialpadVisibility();
2860     }
2861
2862     /**
2863      * @return true if the "Manage conference" UI is currently visible.
2864      */
2865     /* package */ boolean isManageConferenceMode() {
2866         return (mInCallScreenMode == InCallScreenMode.MANAGE_CONFERENCE);
2867     }
2868
2869     /**
2870      * Updates the "Manage conference" UI based on the specified List of
2871      * connections.
2872      *
2873      * @param connections the List of connections belonging to
2874      *        the current foreground call; size must be greater than 1
2875      *        (or it wouldn't be a conference call in the first place.)
2876      */
2877     private void updateManageConferencePanel(List<Connection> connections) {
2878         mNumCallersInConference = connections.size();
2879         if (VDBG) log("updateManageConferencePanel()... num connections in conference = "
2880                      + mNumCallersInConference);
2881
2882         // Can we give the user the option to separate out ("go private with") a single
2883         // caller from this conference?
2884         final boolean hasActiveCall = !mForegroundCall.isIdle();
2885         final boolean hasHoldingCall = !mBackgroundCall.isIdle();
2886         boolean canSeparate = !(hasActiveCall && hasHoldingCall);
2887
2888         for (int i = 0; i < MAX_CALLERS_IN_CONFERENCE; i++) {
2889             if (i < mNumCallersInConference) {
2890                 // Fill in the row in the UI for this caller.
2891                 Connection connection = (Connection) connections.get(i);
2892                 updateManageConferenceRow(i, connection, canSeparate);
2893             } else {
2894                 // Blank out this row in the UI
2895                 updateManageConferenceRow(i, null, false);
2896             }
2897         }
2898     }
2899
2900     /**
2901      * Checks if the "Manage conference" UI needs to be updated.
2902      * If the state of the current conference call has changed
2903      * since our previous call to updateManageConferencePanel()),
2904      * do a fresh update.
2905      */
2906     private void updateManageConferencePanelIfNecessary() {
2907         if (VDBG) log("updateManageConferencePanel: mForegroundCall " + mForegroundCall + "...");
2908
2909         List<Connection> connections = mForegroundCall.getConnections();
2910         if (connections == null) {
2911             if (VDBG) log("==> no connections on foreground call!");
2912             // Hide the Manage Conference panel, return to NORMAL mode.
2913             setInCallScreenMode(InCallScreenMode.NORMAL);
2914             InCallInitStatus status = syncWithPhoneState();
2915             if (status != InCallInitStatus.SUCCESS) {
2916                 Log.w(LOG_TAG, "- syncWithPhoneState failed! status = " + status);
2917                 // We shouldn't even be in the in-call UI in the first
2918                 // place, so bail out:
2919                 if (DBG) log("updateManageConferencePanelIfNecessary: finishing...");
2920                 finish();
2921                 return;
2922             }
2923             return;
2924         }
2925
2926         int numConnections = connections.size();
2927         if (numConnections <= 1) {
2928             if (VDBG) log("==> foreground call no longer a conference!");
2929             // Hide the Manage Conference panel, return to NORMAL mode.
2930             setInCallScreenMode(InCallScreenMode.NORMAL);
2931             InCallInitStatus status = syncWithPhoneState();
2932             if (status != InCallInitStatus.SUCCESS) {
2933                 Log.w(LOG_TAG, "- syncWithPhoneState failed! status = " + status);
2934                 // We shouldn't even be in the in-call UI in the first
2935                 // place, so bail out:
2936                 if (DBG) log("updateManageConferencePanelIfNecessary: finishing...");
2937                 finish();
2938                 return;
2939             }
2940             return;
2941         }
2942         if (numConnections != mNumCallersInConference) {
2943             if (VDBG) log("==> Conference size has changed; need to rebuild UI!");
2944             updateManageConferencePanel(connections);
2945             return;
2946         }
2947     }
2948
2949     /**
2950      * Updates a single row of the "Manage conference" UI.  (One row in this
2951      * UI represents a single caller in the conference.)
2952      *
2953      * @param i the row to update
2954      * @param connection the Connection corresponding to this caller.
2955      *        If null, that means this is an "empty slot" in the conference,
2956      *        so hide this row in the UI.
2957      * @param canSeparate if true, show a "Separate" (i.e. "Private") button
2958      *        on this row in the UI.
2959      */
2960     private void updateManageConferenceRow(final int i,
2961                                            final Connection connection,
2962                                            boolean canSeparate) {
2963         if (VDBG) log("updateManageConferenceRow(" + i + ")...  connection = " + connection);
2964
2965         if (connection != null) {
2966             // Activate this row of the Manage conference panel:
2967             mConferenceCallList[i].setVisibility(View.VISIBLE);
2968
2969             // get the relevant children views
2970             ImageButton endButton = (ImageButton) mConferenceCallList[i].findViewById(
2971                     R.id.conferenceCallerDisconnect);
2972             ImageButton separateButton = (ImageButton) mConferenceCallList[i].findViewById(
2973                     R.id.conferenceCallerSeparate);
2974             TextView nameTextView = (TextView) mConferenceCallList[i].findViewById(
2975                     R.id.conferenceCallerName);
2976             TextView numberTextView = (TextView) mConferenceCallList[i].findViewById(
2977                     R.id.conferenceCallerNumber);
2978             TextView numberTypeTextView = (TextView) mConferenceCallList[i].findViewById(
2979                     R.id.conferenceCallerNumberType);
2980
2981             if (VDBG) log("- button: " + endButton + ", nameTextView: " + nameTextView);
2982
2983             // Hook up this row's buttons.
2984             View.OnClickListener endThisConnection = new View.OnClickListener() {
2985                     public void onClick(View v) {
2986                         endConferenceConnection(i, connection);
2987                         PhoneApp.getInstance().pokeUserActivity();
2988                     }
2989                 };
2990             endButton.setOnClickListener(endThisConnection);
2991             //
2992             if (canSeparate) {
2993                 View.OnClickListener separateThisConnection = new View.OnClickListener() {
2994                         public void onClick(View v) {
2995                             separateConferenceConnection(i, connection);
2996                             PhoneApp.getInstance().pokeUserActivity();
2997                         }
2998                     };
2999                 separateButton.setOnClickListener(separateThisConnection);
3000                 separateButton.setVisibility(View.VISIBLE);
3001             } else {
3002                 separateButton.setVisibility(View.INVISIBLE);
3003             }
3004
3005             // Name/number for this caller.
3006             // TODO: need to deal with private or blocked caller id?
3007             PhoneUtils.CallerInfoToken info = PhoneUtils.startGetCallerInfo(this, connection,
3008                     this, mConferenceCallList[i]);
3009
3010             // display the CallerInfo.
3011             displayCallerInfoForConferenceRow (info.currentInfo, nameTextView,
3012                     numberTypeTextView, numberTextView);
3013         } else {
3014             // Disable this row of the Manage conference panel:
3015             mConferenceCallList[i].setVisibility(View.GONE);
3016         }
3017     }
3018
3019     /**
3020      * Implemented for CallerInfoAsyncQuery.OnQueryCompleteListener interface.
3021      * refreshes the nameTextView when called.
3022      */
3023     public void onQueryComplete(int token, Object cookie, CallerInfo ci){
3024         if (VDBG) log("callerinfo query complete, updating UI.");
3025
3026         // get the viewgroup (conference call list item) and make it visible
3027         ViewGroup vg = (ViewGroup) cookie;
3028         vg.setVisibility(View.VISIBLE);
3029
3030         // update the list item with this information.
3031         displayCallerInfoForConferenceRow (ci,
3032                 (TextView) vg.findViewById(R.id.conferenceCallerName),
3033                 (TextView) vg.findViewById(R.id.conferenceCallerNumberType),
3034                 (TextView) vg.findViewById(R.id.conferenceCallerNumber));
3035     }
3036
3037     /**
3038      * Helper function to fill out the Conference Call(er) information
3039      * for each item in the "Manage Conference Call" list.
3040      */
3041     private final void displayCallerInfoForConferenceRow(CallerInfo ci, TextView nameTextView,
3042             TextView numberTypeTextView, TextView numberTextView) {
3043
3044         // gather the correct name and number information.
3045         String callerName = "";
3046         String callerNumber = "";
3047         String callerNumberType = "";
3048         if (ci != null) {
3049             callerName = ci.name;
3050             if (TextUtils.isEmpty(callerName)) {
3051                 callerName = ci.phoneNumber;
3052                 if (TextUtils.isEmpty(callerName)) {
3053                     callerName = getString(R.string.unknown);
3054                 }
3055             } else {
3056                 callerNumber = ci.phoneNumber;
3057                 callerNumberType = ci.phoneLabel;
3058             }
3059         }
3060
3061         // set the caller name
3062         nameTextView.setText(callerName);
3063
3064         // set the caller number in subscript, or make the field disappear.
3065         if (TextUtils.isEmpty(callerNumber)) {
3066             numberTextView.setVisibility(View.GONE);
3067             numberTypeTextView.setVisibility(View.GONE);
3068         } else {
3069             numberTextView.setVisibility(View.VISIBLE);
3070             numberTextView.setText(callerNumber);
3071             numberTypeTextView.setVisibility(View.VISIBLE);
3072             numberTypeTextView.setText(callerNumberType);
3073         }
3074     }
3075
3076     /**
3077      * Ends the specified connection on a conference call.  This method is
3078      * run (via a closure containing a row index and Connection) when the
3079      * user clicks the "End" button on a specific row in the Manage
3080      * conference UI.
3081      */
3082     private void endConferenceConnection(int i, Connection connection) {
3083         if (VDBG) log("===> ENDING conference connection " + i
3084                       + ": Connection " + connection);
3085         // The actual work of ending the connection:
3086         PhoneUtils.hangup(connection);
3087         // No need to manually update the "Manage conference" UI here;
3088         // that'll happen automatically very soon (when we get the
3089         // onDisconnect() callback triggered by this hangup() call.)
3090     }
3091
3092     /**
3093      * Separates out the specified connection on a conference call.  This
3094      * method is run (via a closure containing a row index and Connection)
3095      * when the user clicks the "Separate" (i.e. "Private") button on a
3096      * specific row in the Manage conference UI.
3097      */
3098     private void separateConferenceConnection(int i, Connection connection) {
3099         if (VDBG) log("===> SEPARATING conference connection " + i
3100                       + ": Connection " + connection);
3101
3102         PhoneUtils.separateCall(connection);
3103
3104         // Note that separateCall() automagically makes the
3105         // newly-separated call into the foreground call (which is the
3106         // desired UI), so there's no need to do any further
3107         // call-switching here.
3108         // There's also no need to manually update (or hide) the "Manage
3109         // conference" UI; that'll happen on its own in a moment (when we
3110         // get the phone state change event triggered by the call to
3111         // separateCall().)
3112     }
3113
3114     /**
3115      * Updates the visibility of the DTMF dialpad and the "sliding drawer"
3116      * handle, based on the current state of the phone and/or the current
3117      * InCallScreenMode.
3118      */
3119     private void updateDialpadVisibility() {
3120         //
3121         // (1) The dialpad itself:
3122         //
3123         // If an incoming call is ringing, make sure the dialpad is
3124         // closed.  (We do this to make sure we're not covering up the
3125         // "incoming call" UI, and especially to make sure that the "touch
3126         // lock" overlay won't appear.)
3127         if (mPhone.getState() == Phone.State.RINGING) {
3128             mDialer.closeDialer(false);  // don't do the "closing" animation
3129
3130             // Also, clear out the "history" of DTMF digits you may have typed
3131             // into the previous call (so you don't see the previous call's
3132             // digits if you answer this call and then bring up the dialpad.)
3133             //
3134             // TODO: it would be more precise to do this when you *answer* the
3135             // incoming call, rather than as soon as it starts ringing, but
3136             // the InCallScreen doesn't keep enough state right now to notice
3137             // that specific transition in onPhoneStateChanged().
3138             mDialer.clearDigits();
3139         }
3140
3141         //
3142         // (2) The "sliding drawer" handle:
3143         //
3144         // This handle should be visible only if it's OK to actually open
3145         // the dialpad.
3146         //
3147         if (mDialerDrawer != null) {
3148             int visibility = okToShowDialpad() ? View.VISIBLE : View.GONE;
3149             mDialerDrawer.setVisibility(visibility);
3150         }
3151     }
3152
3153     /**
3154      * @return true if the DTMF dialpad is currently visible.
3155      */
3156     /* package */ boolean isDialerOpened() {
3157         return (mDialer != null && mDialer.isOpened());
3158     }
3159
3160     /**
3161      * Called any time the DTMF dialpad is opened.
3162      * @see DTMFTwelveKeyDialer.onDialerOpen()
3163      */
3164     /* package */ void onDialerOpen() {
3165         if (VDBG) log("onDialerOpen()...");
3166
3167         // ANY time the dialpad becomes visible, start the timer that will
3168         // eventually bring up the "touch lock" overlay.
3169         resetTouchLockTimer();
3170
3171         // This counts as explicit "user activity".
3172         PhoneApp.getInstance().pokeUserActivity();
3173     }
3174
3175     /**
3176      * Called any time the DTMF dialpad is closed.
3177      * @see DTMFTwelveKeyDialer.onDialerClose()
3178      */
3179     /* package */ void onDialerClose() {
3180         if (VDBG) log("onDialerClose()...");
3181
3182         // Dismiss the "touch lock" overlay if it was visible.
3183         // (The overlay is only ever used on top of the dialpad).
3184         enableTouchLock(false);
3185
3186         // This counts as explicit "user activity".
3187         PhoneApp.getInstance().pokeUserActivity();
3188     }
3189
3190     /**
3191      * Get the DTMF dialer display field.
3192      */
3193     /* package */ EditText getDialerDisplay() {
3194         return mDTMFDisplay;
3195     }
3196
3197     /**
3198      * Determines when we can dial DTMF tones.
3199      */
3200     private boolean okToDialDTMFTones() {
3201         final boolean hasRingingCall = !mRingingCall.isIdle();
3202         final Call.State fgCallState = mForegroundCall.getState();
3203
3204         // We're allowed to send DTMF tones when there's an ACTIVE
3205         // foreground call, and not when an incoming call is ringing
3206         // (since DTMF tones are useless in that state), or if the
3207         // Manage Conference UI is visible (since the tab interferes
3208         // with the "Back to call" button.)
3209
3210         // We can also dial while in ALERTING state because there are
3211         // some connections that never update to an ACTIVE state (no
3212         // indication from the network).
3213         boolean canDial =
3214             (fgCallState == Call.State.ACTIVE || fgCallState == Call.State.ALERTING)
3215             && !hasRingingCall
3216             && (mInCallScreenMode != InCallScreenMode.MANAGE_CONFERENCE);
3217
3218         if (VDBG) log ("[okToDialDTMFTones] foreground state: " + fgCallState +
3219                 ", ringing state: " + hasRingingCall +
3220                 ", call screen mode: " + mInCallScreenMode +
3221                 ", result: " + canDial);
3222
3223         return canDial;
3224     }
3225
3226     /**
3227      * @return true if the in-call DTMF dialpad should be available to the
3228      *      user, given the current state of the phone and the in-call UI.
3229      *      (This is used to control the visiblity of the dialer's
3230      *      SlidingDrawer handle, and the enabledness of the "Show
3231      *      dialpad" menu item.)
3232      */
3233     /* package */ boolean okToShowDialpad() {
3234         // The dialpad is never used in landscape mode.  And even in
3235         // portrait mode, it's available only when it's OK to dial DTMF
3236         // tones given the current state of the current call.
3237         return !ConfigurationHelper.isLandscape() && okToDialDTMFTones();
3238     }
3239
3240     /**
3241      * Helper class to manage the (small number of) manual layout and UI
3242      * changes needed by the in-call UI when switching between landscape
3243      * and portrait mode.
3244      *
3245      * TODO: Ideally, all this information should come directly from
3246      * resources, with alternate sets of resources for for different
3247      * configurations (like alternate layouts under res/layout-land
3248      * or res/layout-finger.)
3249      *
3250      * But for now, we don't use any alternate resources.  Instead, the
3251      * resources under res/layout are hardwired for portrait mode, and we
3252      * use this class's applyConfigurationToLayout() method to reach into
3253      * our View hierarchy and manually patch up anything that needs to be
3254      * different for landscape mode.
3255      */
3256     /* package */ static class ConfigurationHelper {
3257         /** This class is never instantiated. */
3258         private ConfigurationHelper() {
3259         }
3260
3261         // "Configuration constants" set by initConfiguration()
3262         static int sOrientation = Configuration.ORIENTATION_UNDEFINED;
3263
3264         static boolean isLandscape() {
3265             return sOrientation == Configuration.ORIENTATION_LANDSCAPE;
3266         }
3267
3268         /**
3269          * Initializes the "Configuration constants" based on the
3270          * specified configuration.
3271          */
3272         static void initConfiguration(Configuration config) {
3273             if (VDBG) Log.d(LOG_TAG, "[InCallScreen.ConfigurationHelper] "
3274                            + "initConfiguration(" + config + ")...");
3275             sOrientation = config.orientation;
3276         }
3277
3278         /**
3279          * Updates the InCallScreen's View hierarchy, applying any
3280          * necessary changes given the current configuration.
3281          */
3282         static void applyConfigurationToLayout(InCallScreen inCallScreen) {
3283             if (sOrientation == Configuration.ORIENTATION_UNDEFINED) {
3284                 throw new IllegalStateException("need to call initConfiguration first");
3285             }
3286
3287             // find the landscape-only DTMF display field.
3288             inCallScreen.mDTMFDisplay = (EditText) inCallScreen.findViewById(R.id.dtmfDialerField);
3289
3290             // Our layout resources describe the *portrait mode* layout of
3291             // the Phone UI (see the TODO above in the doc comment for
3292             // the ConfigurationHelper class.)  So if we're in landscape
3293             // mode now, reach into our View hierarchy and update the
3294             // (few) layout params that need to be different.
3295             if (isLandscape()) {
3296                 // Update CallCard-related stuff
3297                 inCallScreen.mCallCard.updateForLandscapeMode();
3298
3299                 // No need to adjust the visiblity for mDTMFDisplay here because
3300                 // we're relying on the resources (layouts in layout-finger vs.
3301                 // layout-land-finger) to manage when mDTMFDisplay is shown.
3302             }
3303         }
3304     }
3305
3306     /**
3307      * @return true if we're in restricted / emergency dialing only mode.
3308      */
3309     public boolean isPhoneStateRestricted() {
3310         // TODO:  This needs to work IN TANDEM with the KeyGuardViewMediator Code.
3311         // Right now, it looks like the mInputRestricted flag is INTERNAL to the
3312         // KeyGuardViewMediator and SPECIFICALLY set to be FALSE while the emergency
3313         // phone call is being made, to allow for input into the InCallScreen.
3314         // Having the InCallScreen judge the state of the device from this flag
3315         // becomes meaningless since it is always false for us.  The mediator should
3316         // have an additional API to let this app know that it should be restricted.
3317         return ((mPhone.getServiceState().getState() == ServiceState.STATE_EMERGENCY_ONLY) ||
3318                 (mPhone.getServiceState().getState() == ServiceState.STATE_OUT_OF_SERVICE) ||
3319                 (PhoneApp.getInstance().getKeyguardManager().inKeyguardRestrictedInputMode()));
3320     }
3321
3322     //
3323     // In-call menu UI
3324     //
3325
3326     /**
3327      * Override onCreatePanelView(), in order to get complete control
3328      * over the UI that comes up when the user presses MENU.
3329      *
3330      * This callback allows me to return a totally custom View hierarchy
3331      * (with custom layout and custom "item" views) to be shown instead
3332      * of a standard android.view.Menu hierarchy.
3333      *
3334      * This gets called (with featureId == FEATURE_OPTIONS_PANEL) every
3335      * time we need to bring up the menu.  (And in cases where we return
3336      * non-null, that means that the "standard" menu callbacks
3337      * onCreateOptionsMenu() and onPrepareOptionsMenu() won't get called
3338      * at all.)
3339      */
3340     @Override
3341     public View onCreatePanelView(int featureId) {
3342         if (VDBG) log("onCreatePanelView(featureId = " + featureId + ")...");
3343
3344         // We only want this special behavior for the "options panel"
3345         // feature (i.e. the standard menu triggered by the MENU button.)
3346         if (featureId != Window.FEATURE_OPTIONS_PANEL) {
3347             return null;
3348         }
3349
3350         // TODO: May need to revisit the wake state here if this needs to be
3351         // tweaked.
3352
3353         // Make sure there are no pending messages to *dismiss* the menu.
3354         mHandler.removeMessages(DISMISS_MENU);
3355
3356         if (mInCallMenu == null) {
3357             if (VDBG) log("onCreatePanelView: creating mInCallMenu (first time)...");
3358             mInCallMenu = new InCallMenu(this);
3359             mInCallMenu.initMenu();
3360         }
3361
3362         boolean okToShowMenu = mInCallMenu.updateItems(mPhone);
3363         return okToShowMenu ? mInCallMenu.getView() : null;
3364     }
3365
3366     /**
3367      * Dismisses the menu panel (see onCreatePanelView().)
3368      *
3369      * @param dismissImmediate If true, hide the panel immediately.
3370      *            If false, leave the menu visible onscreen for
3371      *            a brief interval before dismissing it (so the
3372      *            user can see the state change resulting from
3373      *            his original click.)
3374      */
3375     /* package */ void dismissMenu(boolean dismissImmediate) {
3376         if (VDBG) log("dismissMenu(immediate = " + dismissImmediate + ")...");
3377
3378         if (dismissImmediate) {
3379             closeOptionsMenu();
3380         } else {
3381             mHandler.removeMessages(DISMISS_MENU);
3382             mHandler.sendEmptyMessageDelayed(DISMISS_MENU, MENU_DISMISS_DELAY);
3383             // This will result in a dismissMenu(true) call shortly.
3384         }
3385     }
3386
3387     /**
3388      * Override onPanelClosed() to capture the panel closing event,
3389      * allowing us to set the poke lock correctly whenever the option
3390      * menu panel goes away.
3391      */
3392     @Override
3393     public void onPanelClosed(int featureId, Menu menu) {
3394         if (VDBG) log("onPanelClosed(featureId = " + featureId + ")...");
3395
3396         // We only want this special behavior for the "options panel"
3397         // feature (i.e. the standard menu triggered by the MENU button.)
3398         if (featureId == Window.FEATURE_OPTIONS_PANEL) {
3399             // TODO: May need to return to the original wake state here
3400             // if onCreatePanelView ends up changing the wake state.
3401         }
3402
3403         super.onPanelClosed(featureId, menu);
3404     }
3405
3406     //
3407     // Bluetooth helper methods.
3408     //
3409     // - BluetoothDevice is the Bluetooth system service
3410     //   (Context.BLUETOOTH_SERVICE).  If getSystemService() returns null
3411     //   then the device is not BT capable.  Use BluetoothDevice.isEnabled()
3412     //   to see if BT is enabled on the device.
3413     //
3414     // - BluetoothHeadset is the API for the control connection to a
3415     //   Bluetooth Headset.  This lets you completely connect/disconnect a
3416     //   headset (which we don't do from the Phone UI!) but also lets you
3417     //   get the address of the currently active headset and see whether
3418     //   it's currently connected.
3419     //
3420     // - BluetoothHandsfree is the API to control the audio connection to
3421     //   a bluetooth headset. We use this API to switch the headset on and
3422     //   off when the user presses the "Bluetooth" button.
3423     //   Our BluetoothHandsfree instance (mBluetoothHandsfree) is created
3424     //   by the PhoneApp and will be null if the device is not BT capable.
3425     //
3426
3427     /**
3428      * @return true if the Bluetooth on/off switch in the UI should be
3429      *         available to the user (i.e. if the device is BT-capable
3430      *         and a headset is connected.)
3431      */
3432     /* package */ boolean isBluetoothAvailable() {
3433         if (VDBG) log("isBluetoothAvailable()...");
3434         if (mBluetoothHandsfree == null) {
3435             // Device is not BT capable.
3436             if (VDBG) log("  ==> FALSE (not BT capable)");
3437             return false;
3438         }
3439
3440         // There's no need to ask the Bluetooth system service if BT is enabled:
3441         //
3442         //    BluetoothDevice bluetoothDevice =
3443         //            (BluetoothDevice) getSystemService(Context.BLUETOOTH_SERVICE);
3444         //    if ((bluetoothDevice == null) || !bluetoothDevice.isEnabled()) {
3445         //        if (DBG) log("  ==> FALSE (BT not enabled)");
3446         //        return false;
3447         //    }
3448         //    if (DBG) log("  - BT enabled!  device name " + bluetoothDevice.getName()
3449         //                 + ", address " + bluetoothDevice.getAddress());
3450         //
3451         // ...since we already have a BluetoothHeadset instance.  We can just
3452         // call isConnected() on that, and assume it'll be false if BT isn't
3453         // enabled at all.
3454
3455         // Check if there's a connected headset, using the BluetoothHeadset API.
3456         boolean isConnected = false;
3457         if (mBluetoothHeadset != null) {
3458             if (VDBG) log("  - headset state = " + mBluetoothHeadset.getState());
3459             String headsetAddress = mBluetoothHeadset.getHeadsetAddress();
3460             if (VDBG) log("  - headset address: " + headsetAddress);
3461             if (headsetAddress != null) {
3462                 isConnected = mBluetoothHeadset.isConnected(headsetAddress);
3463                 if (VDBG) log("  - isConnected: " + isConnected);
3464             }
3465         }
3466
3467         if (VDBG) log("  ==> " + isConnected);
3468         return isConnected;
3469     }
3470
3471     /**
3472      * @return true if a BT device is available, and its audio is currently connected.
3473      */
3474     /* package */ boolean isBluetoothAudioConnected() {
3475         if (mBluetoothHandsfree == null) {
3476             if (VDBG) log("isBluetoothAudioConnected: ==> FALSE (null mBluetoothHandsfree)");
3477             return false;
3478         }
3479         boolean isAudioOn = mBluetoothHandsfree.isAudioOn();
3480         if (VDBG) log("isBluetoothAudioConnected: ==> isAudioOn = " + isAudioOn);
3481         return isAudioOn;
3482     }
3483
3484     /**
3485      * Helper method used to control the state of the green LED in the
3486      * "Bluetooth" menu item.
3487      *
3488      * @return true if a BT device is available and its audio is currently connected,
3489      *              <b>or</b> if we issued a BluetoothHandsfree.userWantsAudioOn()
3490      *              call within the last 5 seconds (which presumably means
3491      *              that the BT audio connection is currently being set
3492      *              up, and will be connected soon.)
3493      */
3494     /* package */ boolean isBluetoothAudioConnectedOrPending() {
3495         if (isBluetoothAudioConnected()) {
3496             if (VDBG) log("isBluetoothAudioConnectedOrPending: ==> TRUE (really connected)");
3497             return true;
3498         }
3499
3500         // If we issued a userWantsAudioOn() call "recently enough", even
3501         // if BT isn't actually connected yet, let's still pretend BT is
3502         // on.  This is how we make the green LED in the menu item turn on
3503         // right away.
3504         if (mBluetoothConnectionPending) {
3505             long timeSinceRequest =
3506                     SystemClock.elapsedRealtime() - mBluetoothConnectionRequestTime;
3507             if (timeSinceRequest < 5000 /* 5 seconds */) {
3508                 if (VDBG) log("isBluetoothAudioConnectedOrPending: ==> TRUE (requested "
3509                              + timeSinceRequest + " msec ago)");
3510                 return true;
3511             } else {
3512                 if (VDBG) log("isBluetoothAudioConnectedOrPending: ==> FALSE (request too old: "
3513                              + timeSinceRequest + " msec ago)");
3514                 mBluetoothConnectionPending = false;
3515                 return false;
3516             }
3517         }
3518
3519         if (VDBG) log("isBluetoothAudioConnectedOrPending: ==> FALSE");
3520         return false;
3521     }
3522
3523     /**
3524      * Posts a message to our handler saying to update the onscreen UI
3525      * based on a bluetooth headset state change.
3526      */
3527     /* package */ void updateBluetoothIndication() {
3528         if (VDBG) log("updateBluetoothIndication()...");
3529         // No need to look at the current state here; any UI elements that
3530         // care about the bluetooth state (i.e. the CallCard) get
3531         // the necessary state directly from PhoneApp.showBluetoothIndication().
3532         mHandler.removeMessages(BLUETOOTH_STATE_CHANGED);
3533         mHandler.sendEmptyMessage(BLUETOOTH_STATE_CHANGED);
3534     }
3535
3536     private void dumpBluetoothState() {
3537         log("============== dumpBluetoothState() =============");
3538         log("= isBluetoothAvailable: " + isBluetoothAvailable());
3539         log("= isBluetoothAudioConnected: " + isBluetoothAudioConnected());
3540         log("= isBluetoothAudioConnectedOrPending: " + isBluetoothAudioConnectedOrPending());
3541         log("= PhoneApp.showBluetoothIndication: "
3542             + PhoneApp.getInstance().showBluetoothIndication());
3543         log("=");
3544         if (mBluetoothHandsfree != null) {
3545             log("= BluetoothHandsfree.isAudioOn: " + mBluetoothHandsfree.isAudioOn());
3546             if (mBluetoothHeadset != null) {
3547                 String headsetAddress = mBluetoothHeadset.getHeadsetAddress();
3548                 log("= BluetoothHeadset.getHeadsetAddress: " + headsetAddress);
3549                 if (headsetAddress != null) {
3550                     log("= BluetoothHeadset.isConnected: "
3551                         + mBluetoothHeadset.isConnected(headsetAddress));
3552                 }
3553             } else {
3554                 log("= mBluetoothHeadset is null");
3555             }
3556         } else {
3557             log("= mBluetoothHandsfree is null; device is not BT capable");
3558         }
3559     }
3560
3561     /* package */ void connectBluetoothAudio() {
3562         if (VDBG) log("connectBluetoothAudio()...");
3563         if (mBluetoothHandsfree != null) {
3564             mBluetoothHandsfree.userWantsAudioOn();
3565         }
3566
3567         // Watch out: The bluetooth connection doesn't happen instantly;
3568         // the userWantsAudioOn() call returns instantly but does its real
3569         // work in another thread.  Also, in practice the BT connection
3570         // takes longer than MENU_DISMISS_DELAY to complete(!) so we need
3571         // a little trickery here to make the menu item's green LED update
3572         // instantly.
3573         // (See isBluetoothAudioConnectedOrPending() above.)
3574         mBluetoothConnectionPending = true;
3575         mBluetoothConnectionRequestTime = SystemClock.elapsedRealtime();
3576     }
3577
3578     /* package */ void disconnectBluetoothAudio() {
3579         if (VDBG) log("disconnectBluetoothAudio()...");
3580         if (mBluetoothHandsfree != null) {
3581             mBluetoothHandsfree.userWantsAudioOff();
3582         }
3583         mBluetoothConnectionPending = false;
3584     }
3585
3586     //
3587     // "Touch lock" UI.
3588     //
3589     // When the DTMF dialpad is up, after a certain amount of idle time we
3590     // display an overlay graphic on top of the dialpad and "lock" the
3591     // touch UI.  (UI Rationale: We need *some* sort of screen lock, with
3592     // a fairly short timeout, to avoid false touches from the user's face
3593     // while in-call.  But we *don't* want to do this by turning off the
3594     // screen completely, since that's confusing (the user can't tell
3595     // what's going on) *and* it's fairly cumbersome to have to hit MENU
3596     // to bring the screen back, rather than using some gesture on the
3597     // touch screen.)
3598     //
3599     // The user can dismiss the touch lock overlay by double-tapping on
3600     // the central "lock" icon.  Also, the touch lock overlay will go away
3601     // by itself if the DTMF dialpad is dismissed for any reason, such as
3602     // the current call getting disconnected (see onDialerClose()).
3603     //
3604
3605     /**
3606      * Initializes the "touch lock" UI widgets.  We do this lazily
3607      * to avoid slowing down the initial launch of the InCallScreen.
3608      */
3609     private void initTouchLock() {
3610         if (VDBG) log("initTouchLock()...");
3611         if (mTouchLockOverlay != null) {
3612             Log.w(LOG_TAG, "initTouchLock: already initialized!");
3613             return;
3614         }
3615
3616         mTouchLockOverlay = (View) findViewById(R.id.touchLockOverlay);
3617         // Note mTouchLockOverlay's visibility is initially GONE.
3618         mTouchLockIcon = (View) findViewById(R.id.touchLockIcon);
3619
3620         // Handle touch events.  (Basically mTouchLockOverlay consumes and
3621         // discards any touch events it sees, and mTouchLockIcon listens
3622         // for the "double-tap to unlock" gesture.)
3623         mTouchLockOverlay.setOnTouchListener(this);
3624         mTouchLockIcon.setOnTouchListener(this);
3625
3626         mTouchLockFadeIn = AnimationUtils.loadAnimation(this, R.anim.touch_lock_fade_in);
3627     }
3628
3629     private boolean isTouchLocked() {
3630         return (mTouchLockOverlay != null) && (mTouchLockOverlay.getVisibility() == View.VISIBLE);
3631     }
3632
3633     /**
3634      * Enables or disables the "touch lock" overlay on top of the DTMF dialpad.
3635      *
3636      * If enable=true, bring up the overlay immediately using an animated
3637      * fade-in effect.  (Or do nothing if the overlay isn't appropriate
3638      * right now, like if the dialpad isn't up, or the speaker is on.)
3639      *
3640      * If enable=false, immediately take down the overlay.  (Or do nothing
3641      * if the overlay isn't actually up right now.)
3642      *
3643      * Note that with enable=false this method will *not* automatically
3644      * start the touch lock timer.  (So when taking down the overlay while
3645      * the dialer is still up, the caller is also responsible for calling
3646      * resetTouchLockTimer(), to make sure the overlay will get
3647      * (re-)enabled later.)
3648      *
3649      */
3650     private void enableTouchLock(boolean enable) {
3651         if (VDBG) log("enableTouchLock(" + enable + ")...");
3652         if (enable) {
3653             // The "touch lock" overlay is only ever used on top of the
3654             // DTMF dialpad.
3655             if (!mDialer.isOpened()) {
3656                 if (VDBG) log("enableTouchLock: dialpad isn't up, no need to lock screen.");
3657                 return;
3658             }
3659
3660             // Also, the "touch lock" overlay NEVER appears if the speaker is in use.
3661             if (PhoneUtils.isSpeakerOn(getApplicationContext())) {
3662                 if (VDBG) log("enableTouchLock: speaker is on, no need to lock screen.");
3663                 return;
3664             }
3665
3666             // Initialize the UI elements if necessary.
3667             if (mTouchLockOverlay == null) {
3668                 initTouchLock();
3669             }
3670
3671             // First take down the menu if it's up (since it's confusing
3672             // to see a touchable menu *above* the touch lock overlay.)
3673             // Note dismissMenu() has no effect if the menu is already closed.
3674             dismissMenu(true);  // dismissImmediate = true
3675
3676             // Bring up the touch lock overlay (with an animated fade)
3677             mTouchLockOverlay.setVisibility(View.VISIBLE);
3678             mTouchLockOverlay.startAnimation(mTouchLockFadeIn);
3679         } else {
3680             // TODO: it might be nice to immediately kill the animation if
3681             // we're in the middle of fading-in:
3682             //   if (mTouchLockFadeIn.hasStarted() && !mTouchLockFadeIn.hasEnded()) {
3683             //      mTouchLockOverlay.clearAnimation();
3684             //   }
3685             // but the fade-in is so quick that this probably isn't necessary.
3686
3687             // Take down the touch lock overlay (immediately)
3688             if (mTouchLockOverlay != null) mTouchLockOverlay.setVisibility(View.GONE);
3689         }
3690     }
3691
3692     /**
3693      * Schedule the "touch lock" overlay to begin fading in after a short
3694      * delay, but only if the DTMF dialpad is currently visible.
3695      *
3696      * (This is designed to be triggered on any user activity
3697      * while the dialpad is up but not locked, and also
3698      * whenever the user "unlocks" the touch lock overlay.)
3699      *
3700      * Calling this method supersedes any previous resetTouchLockTimer()
3701      * calls (i.e. we first clear any pending TOUCH_LOCK_TIMER messages.)
3702      */
3703     private void resetTouchLockTimer() {
3704         if (VDBG) log("resetTouchLockTimer()...");
3705         mHandler.removeMessages(TOUCH_LOCK_TIMER);
3706         if (mDialer.isOpened() && !isTouchLocked()) {
3707             // The touch lock delay value comes from Gservices; we use
3708             // the same value that's used for the PowerManager's
3709             // POKE_LOCK_SHORT_TIMEOUT flag (i.e. the fastest possible
3710             // screen timeout behavior.)
3711
3712             // Do a fresh lookup each time, since Gservices values can
3713             // change on the fly.  (The Settings.Gservices helper class
3714             // caches these values so this call is usually cheap.)
3715             int touchLockDelay = Settings.Gservices.getInt(
3716                     getContentResolver(),
3717                     Settings.Gservices.SHORT_KEYLIGHT_DELAY_MS,
3718                     TOUCH_LOCK_DELAY_DEFAULT);
3719             mHandler.sendEmptyMessageDelayed(TOUCH_LOCK_TIMER, touchLockDelay);
3720         }
3721     }
3722
3723     /**
3724      * Handles the TOUCH_LOCK_TIMER event.
3725      * @see resetTouchLockTimer
3726      */
3727     private void touchLockTimerExpired() {
3728         // Ok, it's been long enough since we had any user activity with
3729         // the DTMF dialpad up.  If the dialpad is still up, start fading
3730         // in the "touch lock" overlay.
3731         enableTouchLock(true);
3732     }
3733
3734     // View.OnTouchListener implementation
3735     public boolean onTouch(View v, MotionEvent event) {
3736         if (VDBG) log ("onTouch(View " + v + ")...");
3737
3738         //
3739         // Handle touch events on the "touch lock" overlay.
3740         // (v == mTouchLockIcon) means the user hit the lock icon in the
3741         // middle of the screen, and (v == mTouchLockOverlay) is a touch
3742         // anywhere else on the overlay.
3743         //
3744
3745         // We only care about touch events while the touch lock UI is
3746         // visible (including the time during the fade-in animation.)
3747         if (((v == mTouchLockIcon) || (v == mTouchLockOverlay)) && !isTouchLocked()) {
3748             // Got an event from the touch lock UI, but we're not locked!
3749             // (This was probably a touch-UP right after we unlocked.
3750             // Ignore it.)
3751             return false;
3752         }
3753
3754         if (v == mTouchLockIcon) {
3755             // Direct hit on the "lock" icon.  Handle the double-tap gesture.
3756             if (event.getAction() == MotionEvent.ACTION_DOWN) {
3757                 long now = SystemClock.uptimeMillis();
3758                 if (VDBG) log("- touch lock icon: handling a DOWN event, t = " + now);
3759
3760                 // Look for the double-tap gesture:
3761                 if (now < mTouchLockLastTouchTime + ViewConfiguration.getDoubleTapTimeout()) {
3762                     if (VDBG) log("==> touch lock icon: DOUBLE-TAP!");
3763                     // This was the 2nd tap of a double-tap gesture.
3764                     // Take down the touch lock overlay, but post a
3765                     // message in the future to bring it back later.
3766                     enableTouchLock(false);
3767                     resetTouchLockTimer();
3768                     // This counts as explicit "user activity".
3769                     PhoneApp.getInstance().pokeUserActivity();
3770                 }
3771             } else if (event.getAction() == MotionEvent.ACTION_UP) {
3772                 // Stash away the current time in case this is the first
3773                 // tap of a double-tap gesture.  (We measure the time from
3774                 // the first tap's UP to the second tap's DOWN.)
3775                 mTouchLockLastTouchTime = SystemClock.uptimeMillis();
3776             }
3777
3778             // And regardless of what just happened, we *always* consume
3779             // touch events while the touch lock UI is (or was) visible.
3780             return true;
3781
3782         } else if (v == mTouchLockOverlay) {
3783             // User touched the "background" area of the touch lock overlay.
3784
3785             // TODO: If we're in the middle of the fade-in animation,
3786             // consider making a touch *anywhere* immediately unlock the
3787             // UI.  This could be risky, though, if the user tries to
3788             // *double-tap* during the fade-in (in which case the 2nd tap
3789             // might 't become a false touch on the dialpad!)
3790             //
3791             //if (event.getAction() == MotionEvent.ACTION_DOWN) {
3792             //    if (DBG) log("- touch lock overlay background: handling a DOWN event.");
3793             //
3794             //    if (mTouchLockFadeIn.hasStarted() && !mTouchLockFadeIn.hasEnded()) {
3795             //        // If we're still fading-in, a touch *anywhere* onscreen
3796             //        // immediately unlocks.
3797             //        if (DBG) log("==> touch lock: tap during fade-in!");
3798             //
3799             //        mTouchLockOverlay.clearAnimation();
3800             //        enableTouchLock(false);
3801             //        // ...but post a message in the future to bring it
3802             //        // back later.
3803             //        resetTouchLockTimer();
3804             //    }
3805             //}
3806
3807             // And regardless of what just happened, we *always* consume
3808             // touch events while the touch lock UI is (or was) visible.
3809             return true;
3810
3811         } else {
3812             Log.w(LOG_TAG, "onTouch: event from unexpected View: " + v);
3813             return false;
3814         }
3815     }
3816
3817     // Any user activity while the dialpad is up, but not locked, should
3818     // reset the touch lock timer back to the full delay amount.
3819     @Override
3820     public void onUserInteraction() {
3821         if (mDialer.isOpened() && !isTouchLocked()) {
3822             resetTouchLockTimer();
3823         }
3824     }
3825
3826
3827     private void log(String msg) {
3828         Log.d(LOG_TAG, msg);
3829     }
3830 }