PhoneUtils.java revision 1e8a3579f8e49fd1f1a078d6be6864a6a8bac306
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.phone;
18
19import android.app.ActivityManagerNative;
20import android.app.AlertDialog;
21import android.app.Dialog;
22import android.app.KeyguardManager;
23import android.app.ProgressDialog;
24import android.content.ComponentName;
25import android.content.ContentResolver;
26import android.content.Context;
27import android.content.DialogInterface;
28import android.content.Intent;
29import android.content.ServiceConnection;
30import android.content.pm.ApplicationInfo;
31import android.content.pm.PackageManager;
32import android.graphics.drawable.Drawable;
33import android.media.AudioManager;
34import android.net.Uri;
35import android.os.AsyncResult;
36import android.os.Handler;
37import android.os.IBinder;
38import android.os.Message;
39import android.os.RemoteException;
40import android.telephony.PhoneNumberUtils;
41import android.text.TextUtils;
42import android.util.Log;
43import android.view.KeyEvent;
44import android.view.LayoutInflater;
45import android.view.View;
46import android.view.WindowManager;
47import android.widget.EditText;
48import android.widget.Toast;
49
50import com.android.internal.telephony.Call;
51import com.android.internal.telephony.CallStateException;
52import com.android.internal.telephony.CallerInfo;
53import com.android.internal.telephony.CallerInfoAsyncQuery;
54import com.android.internal.telephony.Connection;
55import com.android.internal.telephony.IExtendedNetworkService;
56import com.android.internal.telephony.MmiCode;
57import com.android.internal.telephony.Phone;
58import com.android.internal.telephony.cdma.CdmaConnection;
59
60import java.util.Hashtable;
61import java.util.Iterator;
62import java.util.List;
63
64/**
65 * Misc utilities for the Phone app.
66 */
67public class PhoneUtils {
68    private static final String LOG_TAG = "PhoneUtils";
69    private static final boolean DBG = (PhoneApp.DBG_LEVEL >= 2);
70
71    /** Control stack trace for Audio Mode settings */
72    private static final boolean DBG_SETAUDIOMODE_STACK = false;
73
74    /** Identifier for the "Add Call" intent extra. */
75    static final String ADD_CALL_MODE_KEY = "add_call_mode";
76
77    // Return codes from placeCall()
78    static final int CALL_STATUS_DIALED = 0;  // The number was successfully dialed
79    static final int CALL_STATUS_DIALED_MMI = 1;  // The specified number was an MMI code
80    static final int CALL_STATUS_FAILED = 2;  // The call failed
81
82    // State of the Phone's audio modes
83    // Each state can move to the other states, but within the state only certain
84    //  transitions for AudioManager.setMode() are allowed.
85    static final int AUDIO_IDLE = 0;  /** audio behaviour at phone idle */
86    static final int AUDIO_RINGING = 1;  /** audio behaviour while ringing */
87    static final int AUDIO_OFFHOOK = 2;  /** audio behaviour while in call. */
88    private static int sAudioBehaviourState = AUDIO_IDLE;
89
90    /** Speaker state, persisting between wired headset connection events */
91    private static boolean sIsSpeakerEnabled = false;
92
93    /** Hash table to store mute (Boolean) values based upon the connection.*/
94    private static Hashtable<Connection, Boolean> sConnectionMuteTable =
95        new Hashtable<Connection, Boolean>();
96
97    /** Static handler for the connection/mute tracking */
98    private static ConnectionHandler mConnectionHandler;
99
100    /** Phone state changed event*/
101    private static final int PHONE_STATE_CHANGED = -1;
102
103    /** Define for not a special CNAP string */
104    private static final int CNAP_SPECIAL_CASE_NO = -1;
105
106    // Extended network service interface instance
107    private static IExtendedNetworkService mNwService = null;
108    // used to cancel MMI command after 15 seconds timeout for NWService requirement
109    private static Message mMmiTimeoutCbMsg = null;
110
111    /**
112     * Handler that tracks the connections and updates the value of the
113     * Mute settings for each connection as needed.
114     */
115    private static class ConnectionHandler extends Handler {
116        @Override
117        public void handleMessage(Message msg) {
118            AsyncResult ar = (AsyncResult) msg.obj;
119            switch (msg.what) {
120                case PHONE_STATE_CHANGED:
121                    if (DBG) log("ConnectionHandler: updating mute state for each connection");
122
123                    Phone phone = (Phone) ar.userObj;
124
125                    // update the foreground connections, if there are new connections.
126                    List<Connection> fgConnections = phone.getForegroundCall().getConnections();
127                    for (Connection cn : fgConnections) {
128                        if (sConnectionMuteTable.get(cn) == null) {
129                            sConnectionMuteTable.put(cn, Boolean.FALSE);
130                        }
131                    }
132
133                    // update the background connections, if there are new connections.
134                    List<Connection> bgConnections = phone.getBackgroundCall().getConnections();
135                    for (Connection cn : bgConnections) {
136                        if (sConnectionMuteTable.get(cn) == null) {
137                            sConnectionMuteTable.put(cn, Boolean.FALSE);
138                        }
139                    }
140
141                    // Check to see if there are any lingering connections here
142                    // (disconnected connections), use old-school iterators to avoid
143                    // concurrent modification exceptions.
144                    Connection cn;
145                    for (Iterator<Connection> cnlist = sConnectionMuteTable.keySet().iterator();
146                            cnlist.hasNext();) {
147                        cn = cnlist.next();
148                        if (!fgConnections.contains(cn) && !bgConnections.contains(cn)) {
149                            if (DBG) log("connection: " + cn + "not accounted for, removing.");
150                            cnlist.remove();
151                        }
152                    }
153
154                    // Restore the mute state of the foreground call if we're not IDLE,
155                    // otherwise just clear the mute state. This is really saying that
156                    // as long as there is one or more connections, we should update
157                    // the mute state with the earliest connection on the foreground
158                    // call, and that with no connections, we should be back to a
159                    // non-mute state.
160                    if (phone.getState() != Phone.State.IDLE) {
161                        restoreMuteState(phone);
162                    } else {
163                        setMuteInternal(phone, false);
164                    }
165
166                    break;
167            }
168        }
169    }
170
171
172    private static ServiceConnection ExtendedNetworkServiceConnection = new ServiceConnection() {
173        public void onServiceConnected(ComponentName name, IBinder iBinder) {
174            if (DBG) log("Extended NW onServiceConnected");
175            mNwService = IExtendedNetworkService.Stub.asInterface(iBinder);
176        }
177
178        public void onServiceDisconnected(ComponentName arg0) {
179            if (DBG) log("Extended NW onServiceDisconnected");
180            mNwService = null;
181        }
182    };
183
184    /**
185     * Register the ConnectionHandler with the phone, to receive connection events
186     */
187    public static void initializeConnectionHandler(Phone phone) {
188        if (mConnectionHandler == null) {
189            mConnectionHandler = new ConnectionHandler();
190        }
191
192        phone.registerForPreciseCallStateChanged(mConnectionHandler, PHONE_STATE_CHANGED, phone);
193        // Extended NW service
194        Intent intent = new Intent("com.android.ussd.IExtendedNetworkService");
195        phone.getContext().bindService(intent,
196                ExtendedNetworkServiceConnection, Context.BIND_AUTO_CREATE);
197        if (DBG) log("Extended NW bindService IExtendedNetworkService");
198
199    }
200
201    /** This class is never instantiated. */
202    private PhoneUtils() {
203    }
204
205    //static method to set the audio control state.
206    static void setAudioControlState(int newState) {
207        sAudioBehaviourState = newState;
208    }
209
210    /**
211     * Answer the currently-ringing call.
212     *
213     * @return true if we answered the call, or false if there wasn't
214     *         actually a ringing incoming call, or some other error occurred.
215     *
216     * @see answerAndEndHolding()
217     * @see answerAndEndActive()
218     */
219    static boolean answerCall(Phone phone) {
220        if (DBG) log("answerCall()...");
221
222        // If the ringer is currently ringing and/or vibrating, stop it
223        // right now (before actually answering the call.)
224        PhoneApp.getInstance().getRinger().stopRing();
225
226        PhoneUtils.setAudioControlState(PhoneUtils.AUDIO_OFFHOOK);
227
228        boolean answered = false;
229        Call call = phone.getRingingCall();
230        PhoneApp app = PhoneApp.getInstance();
231        boolean phoneIsCdma = (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA);
232        BluetoothHandsfree bthf = null;
233
234        if (phoneIsCdma) {
235            // Stop any signalInfo tone being played when a Call waiting gets answered
236            if (call.getState() == Call.State.WAITING) {
237                final CallNotifier notifier = app.notifier;
238                notifier.stopSignalInfoTone();
239            }
240        }
241
242        if (call != null && call.isRinging()) {
243            if (DBG) log("answerCall: call state = " + call.getState());
244            try {
245                if (phoneIsCdma) {
246                    if (app.cdmaPhoneCallState.getCurrentCallState()
247                            == CdmaPhoneCallState.PhoneCallState.IDLE) {
248                        // This is the FIRST incoming call being answered.
249                        // Set the Phone Call State to SINGLE_ACTIVE
250                        app.cdmaPhoneCallState.setCurrentCallState(
251                                CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
252                    } else {
253                        // This is the CALL WAITING call being answered.
254                        // Set the Phone Call State to CONF_CALL
255                        app.cdmaPhoneCallState.setCurrentCallState(
256                                CdmaPhoneCallState.PhoneCallState.CONF_CALL);
257
258                        // If a BluetoothHandsfree is valid we need to set the second call state
259                        // so that the Bluetooth client can update the Call state correctly when
260                        // a call waiting is answered from the Phone.
261                        bthf = app.getBluetoothHandsfree();
262                        if (bthf != null) {
263                            bthf.cdmaSetSecondCallState(true);
264                        }
265                    }
266                }
267
268                //if (DBG) log("sPhone.acceptCall");
269                phone.acceptCall();
270                answered = true;
271                if (phoneIsCdma) {
272                    // automatically reset mute state to unmuted for CDMA
273                    // TODO: Would GSM want this also?
274                    setMute(phone, false);
275                }
276                setAudioMode(phone.getContext(), AudioManager.MODE_IN_CALL);
277            } catch (CallStateException ex) {
278                Log.w(LOG_TAG, "answerCall: caught " + ex, ex);
279
280                if (phoneIsCdma) {
281                    // restore the cdmaPhoneCallState and bthf.cdmaSetSecondCallState:
282                    app.cdmaPhoneCallState.setCurrentCallState(
283                            app.cdmaPhoneCallState.getPreviousCallState());
284                    if (bthf != null) {
285                        bthf.cdmaSetSecondCallState(false);
286                    }
287                }
288            }
289        }
290        return answered;
291    }
292
293    /**
294     * Smart "hang up" helper method which hangs up exactly one connection,
295     * based on the current Phone state, as follows:
296     * <ul>
297     * <li>If there's a ringing call, hang that up.
298     * <li>Else if there's a foreground call, hang that up.
299     * <li>Else if there's a background call, hang that up.
300     * <li>Otherwise do nothing.
301     * </ul>
302     * @return true if we successfully hung up, or false
303     *              if there were no active calls at all.
304     */
305    static boolean hangup(Phone phone) {
306        boolean hungup = false;
307        Call ringing = phone.getRingingCall();
308        Call fg = phone.getForegroundCall();
309        Call bg = phone.getBackgroundCall();
310
311        if (!ringing.isIdle()) {
312            if (DBG) log("HANGUP ringing call");
313            hungup = hangupRingingCall(phone);
314        } else if (!fg.isIdle()) {
315            if (DBG) log("HANGUP foreground call");
316            hungup = hangup(fg);
317        } else if (!bg.isIdle()) {
318            if (DBG) log("HANGUP background call");
319            hungup = hangup(bg);
320        }
321
322        if (DBG) log("hungup=" + hungup);
323
324        return hungup;
325    }
326
327    static boolean hangupRingingCall(Phone phone) {
328        if (DBG) log("hangup ringing call");
329        Call ringing = phone.getRingingCall();
330        int phoneType = phone.getPhoneType();
331
332        if (phoneType == Phone.PHONE_TYPE_CDMA) {
333            // CDMA: Ringing call and Call waiting hangup is handled differently.
334            // For Call waiting we DO NOT call the conventional hangup(call) function
335            // as in CDMA we just want to hungup the Call waiting connection.
336            Call.State state = ringing.getState();
337            if (state == Call.State.INCOMING) {
338                if (DBG) log("hangup ringing call");
339                return hangup(ringing);
340            } else if (state == Call.State.WAITING) {
341                if (DBG) log("hangup Call waiting call");
342                final CallNotifier notifier = PhoneApp.getInstance().notifier;
343                notifier.onCdmaCallWaitingReject();
344                return true;
345            } else {
346                // This should never happen cause hangupRingingCall should always be called
347                // if the call.isRinging() returns TRUE, which basically means that the call
348                // should either be in INCOMING or WAITING state
349                if (DBG) log("No Ringing call to hangup");
350                return false;
351            }
352        } else if (phoneType == Phone.PHONE_TYPE_GSM) {
353            // GSM:  Ringing Call and Call waiting, both are hungup by calling
354            // hangup(call) function.
355            if (DBG) log("hangup ringing call");
356            return hangup(ringing);
357        } else {
358            throw new IllegalStateException("Unexpected phone type: " + phoneType);
359        }
360    }
361
362    static boolean hangupActiveCall(Phone phone) {
363        if (DBG) log("hangup active call");
364        return hangup(phone.getForegroundCall());
365    }
366
367    static boolean hangupHoldingCall(Phone phone) {
368        if (DBG) log("hangup holding call");
369        return hangup(phone.getBackgroundCall());
370    }
371
372    /**
373     * Used in CDMA phones to end the complete Call session
374     * @param phone the Phone object.
375     * @return true if *any* call was successfully hung up
376     */
377    static boolean hangupRingingAndActive(Phone phone) {
378        boolean hungUpRingingCall = false;
379        boolean hungUpFgCall = false;
380        Call ringingCall = phone.getRingingCall();
381        Call fgCall = phone.getForegroundCall();
382
383        // Hang up any Ringing Call
384        if (!ringingCall.isIdle()) {
385            if (DBG) log("endCallInternal: Hang up Ringing Call");
386            hungUpRingingCall = hangupRingingCall(phone);
387        }
388
389        // Hang up any Active Call
390        if (!fgCall.isIdle()) {
391            if (DBG) log("endCallInternal: Hang up Foreground Call");
392            hungUpFgCall = hangupActiveCall(phone);
393        }
394
395        return hungUpRingingCall || hungUpFgCall;
396    }
397
398    /**
399     * Trivial wrapper around Call.hangup(), except that we return a
400     * boolean success code rather than throwing CallStateException on
401     * failure.
402     *
403     * @return true if the call was successfully hung up, or false
404     *         if the call wasn't actually active.
405     */
406    static boolean hangup(Call call) {
407        try {
408            call.hangup();
409            return true;
410        } catch (CallStateException ex) {
411            Log.e(LOG_TAG, "Call hangup: caught " + ex, ex);
412        }
413
414        return false;
415    }
416
417    /**
418     * Trivial wrapper around Connection.hangup(), except that we silently
419     * do nothing (rather than throwing CallStateException) if the
420     * connection wasn't actually active.
421     */
422    static void hangup(Connection c) {
423        try {
424            if (c != null) {
425                c.hangup();
426            }
427        } catch (CallStateException ex) {
428            Log.w(LOG_TAG, "Connection hangup: caught " + ex, ex);
429        }
430    }
431
432    static boolean answerAndEndHolding(Phone phone) {
433        if (DBG) log("end holding & answer waiting: 1");
434        if (!hangupHoldingCall(phone)) {
435            Log.e(LOG_TAG, "end holding failed!");
436            return false;
437        }
438
439        if (DBG) log("end holding & answer waiting: 2");
440        return answerCall(phone);
441
442    }
443
444    static boolean answerAndEndActive(Phone phone) {
445        if (DBG) log("answerAndEndActive()...");
446
447        // Unlike the answerCall() method, we *don't* need to stop the
448        // ringer or change audio modes here since the user is already
449        // in-call, which means that the audio mode is already set
450        // correctly, and that we wouldn't have started the ringer in the
451        // first place.
452
453        // hanging up the active call also accepts the waiting call
454        return hangupActiveCall(phone);
455    }
456
457    /**
458     * For a CDMA phone, advance the call state upon making a new
459     * outgoing call.
460     *
461     * <pre>
462     *   IDLE -> SINGLE_ACTIVE
463     * or
464     *   SINGLE_ACTIVE -> THRWAY_ACTIVE
465     * </pre>
466     * @param app The phone instance.
467     */
468    static private void updateCdmaCallStateOnNewOutgoingCall(PhoneApp app) {
469        if (app.cdmaPhoneCallState.getCurrentCallState() ==
470            CdmaPhoneCallState.PhoneCallState.IDLE) {
471            // This is the first outgoing call. Set the Phone Call State to ACTIVE
472            app.cdmaPhoneCallState.setCurrentCallState(
473                CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
474        } else {
475            // This is the second outgoing call. Set the Phone Call State to 3WAY
476            app.cdmaPhoneCallState.setCurrentCallState(
477                CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE);
478        }
479    }
480
481    /**
482     * Dial the number using the phone passed in.
483     *
484     * @param phone the Phone object.
485     * @param number to be dialed as requested by the user.
486     * @param contactRef that triggered the call. Either a 'tel:' or a
487     * 'content://contacts' uri depending on how the call was
488     * initiated (dialpad vs contact).
489     * @return either CALL_STATUS_DIALED, CALL_STATUS_DIALED_MMI, or CALL_STATUS_FAILED
490     */
491    static int placeCall(Phone phone, String number, Uri contactRef) {
492        int status = CALL_STATUS_DIALED;
493        try {
494            if (DBG) log("placeCall: '" + number + "'...");
495
496            Connection cn = phone.dial(number);
497            if (DBG) log("===> phone.dial() returned: " + cn);
498
499            int phoneType = phone.getPhoneType();
500
501            // On GSM phones, null is returned for MMI codes
502            if (cn == null) {
503                if (phoneType == Phone.PHONE_TYPE_GSM) {
504                    if (DBG) log("dialed MMI code: " + number);
505                    status = CALL_STATUS_DIALED_MMI;
506                    // Set dialed MMI command to service
507                    if (mNwService != null) {
508                        try {
509                            mNwService.setMmiString(number);
510                            if (DBG) log("Extended NW bindService setUssdString (" + number + ")");
511                        } catch (RemoteException e) {
512                            mNwService = null;
513                        }
514                    }
515                } else {
516                    status = PhoneUtils.CALL_STATUS_FAILED;
517                }
518            } else {
519                PhoneApp app = PhoneApp.getInstance();
520
521                if (phoneType == Phone.PHONE_TYPE_CDMA) {
522                    updateCdmaCallStateOnNewOutgoingCall(app);
523                }
524
525                PhoneUtils.setAudioControlState(PhoneUtils.AUDIO_OFFHOOK);
526
527                // phone.dial() succeeded: we're now in a normal phone call.
528                // attach the URI to the CallerInfo Object if it is there,
529                // otherwise just attach the Uri Reference.
530                // if the uri does not have a "content" scheme, then we treat
531                // it as if it does NOT have a unique reference.
532                String content = phone.getContext().getContentResolver().SCHEME_CONTENT;
533                if ((contactRef != null) && (contactRef.getScheme().equals(content))) {
534                    Object userDataObject = cn.getUserData();
535                    if (userDataObject == null) {
536                        cn.setUserData(contactRef);
537                    } else {
538                        // TODO: This branch is dead code, we have
539                        // just created the connection 'cn' which has
540                        // no user data (null) by default.
541                        if (userDataObject instanceof CallerInfo) {
542                            ((CallerInfo) userDataObject).contactRefUri = contactRef;
543                        } else {
544                            ((CallerInfoToken) userDataObject).currentInfo.contactRefUri =
545                                contactRef;
546                        }
547                    }
548                }
549                setAudioMode(phone.getContext(), AudioManager.MODE_IN_CALL);
550            }
551        } catch (CallStateException ex) {
552            Log.w(LOG_TAG, "Exception from phone.dial()", ex);
553            status = CALL_STATUS_FAILED;
554        }
555
556        return status;
557    }
558
559    /**
560     * Dial the number using a 3rd party provider gateway.  Should
561     * *NOT* be called if the number is either:
562     * . An emergency one
563     * . A GSM MMI code
564     * . A CDMA feature code
565     * None of the above is  checked in this method, it's the caller's
566     * responsability to make sure the number is 'valid'.
567     *
568     * If the connection is establised, this method issues a sync call
569     * that may block to query the caller info.
570     * TODO: Change the logic to use the async query.
571     *
572     * @param phone the Phone object.
573     * @param context To perform the CallerInfo query.
574     * @param number to be dialed as requested by the user. This is
575     * NOT the phone number to connect to. It is used only to build the
576     * call card and to update the call log. See above for restrictions.
577     * @param contactRef that triggered the call. Typically a 'tel:'
578     * uri but can also be a 'content://contacts' one.
579     * @param gatewayUri Is the address used to setup the connection.
580     * @return either CALL_STATUS_DIALED or CALL_STATUS_FAILED
581     */
582    static int placeCallVia(Context context, Phone phone,
583                            String number, Uri contactRef, Uri gatewayUri) {
584        if (DBG) log("placeCallVia: '" + number + "' GW:'" + gatewayUri + "'");
585
586        // TODO: 'tel' should be a contant defined in framework base
587        // somewhere (it is in webkit.)
588        if (null == gatewayUri || !"tel".equals(gatewayUri.getScheme())) {
589            Log.e(LOG_TAG, "Unsupported URL:" + gatewayUri);
590            return CALL_STATUS_FAILED;
591        }
592
593        // We can use getSchemeSpecificPart because we don't allow #
594        // in the gateway numbers (treated a fragment delim.) However
595        // if we allow more complex gateway numbers sequence (with
596        // passwords or whatnot) that use #, this may break.
597        // TODO: Need to support MMI codes.
598        String gatewayNumber = gatewayUri.getSchemeSpecificPart();
599        Connection connection;
600        try {
601            connection = phone.dial(gatewayNumber);
602        } catch (CallStateException ex) {
603            Log.e(LOG_TAG, "Exception dialing gateway", ex);
604            connection = null;
605        }
606
607        if (null == connection) {
608            Log.e(LOG_TAG, "Got null connection.");
609            return CALL_STATUS_FAILED;
610        }
611
612        PhoneApp app = PhoneApp.getInstance();
613        boolean phoneIsCdma = (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA);
614
615        if (phoneIsCdma) {
616            updateCdmaCallStateOnNewOutgoingCall(app);
617        }
618        PhoneUtils.setAudioControlState(PhoneUtils.AUDIO_OFFHOOK);
619
620        // Clean up the number to be displayed.
621        if (phoneIsCdma) {
622            number = CdmaConnection.formatDialString(number);
623        }
624        number = PhoneNumberUtils.extractNetworkPortion(number);
625        number = PhoneNumberUtils.convertKeypadLettersToDigits(number);
626        number = PhoneNumberUtils.formatNumber(number);
627
628        // Get the caller info synchronously because we need the final
629        // CallerInfo object to update the dialed number with the one
630        // requested by the user (and not the provider's gateway number).
631        CallerInfo info = null;
632
633        if (ContentResolver.SCHEME_CONTENT.equals(contactRef.getScheme())) {
634            info = CallerInfo.getCallerInfo(context, contactRef);
635        }
636
637        // Fallback, lookup contact using the phone number if the
638        // contact's URI scheme was not content:// or if is was but
639        // the lookup failed.
640        if (null == info) {
641            info = CallerInfo.getCallerInfo(context, number);
642        }
643        info.phoneNumber = number;
644        connection.setUserData(info);
645
646        setAudioMode(phone.getContext(), AudioManager.MODE_IN_CALL);
647        return CALL_STATUS_DIALED;
648    }
649
650    static void switchHoldingAndActive(Phone phone) {
651        try {
652            if (DBG) log("switchHoldingAndActive");
653            phone.switchHoldingAndActive();
654        } catch (CallStateException ex) {
655            Log.w(LOG_TAG, "switchHoldingAndActive: caught " + ex, ex);
656        }
657    }
658
659    /**
660     * Restore the mute setting from the earliest connection of the
661     * foreground call.
662     */
663    static Boolean restoreMuteState(Phone phone) {
664        //get the earliest connection
665        Connection c = phone.getForegroundCall().getEarliestConnection();
666
667        // only do this if connection is not null.
668        if (c != null) {
669
670            int phoneType = phone.getPhoneType();
671
672            // retrieve the mute value.
673            Boolean shouldMute = null;
674
675            // In CDMA, mute is not maintained per Connection. Single mute apply for
676            // a call where  call can have multiple connections such as
677            // Three way and Call Waiting.  Therefore retrieving Mute state for
678            // latest connection can apply for all connection in that call
679            if (phoneType == Phone.PHONE_TYPE_CDMA) {
680                shouldMute = sConnectionMuteTable.get(
681                        phone.getForegroundCall().getLatestConnection());
682            } else if (phoneType == Phone.PHONE_TYPE_GSM) {
683                shouldMute = sConnectionMuteTable.get(
684                        phone.getForegroundCall().getEarliestConnection());
685            }
686            if (shouldMute == null) {
687                if (DBG) log("problem retrieving mute value for this connection.");
688                shouldMute = Boolean.FALSE;
689            }
690
691            // set the mute value and return the result.
692            setMute (phone, shouldMute.booleanValue());
693            return shouldMute;
694        }
695        return Boolean.valueOf(getMute (phone));
696    }
697
698    static void mergeCalls(Phone phone) {
699        int phoneType = phone.getPhoneType();
700        if (phoneType == Phone.PHONE_TYPE_GSM) {
701            try {
702                if (DBG) log("mergeCalls");
703                phone.conference();
704            } catch (CallStateException ex) {
705                Log.w(LOG_TAG, "mergeCalls: caught " + ex, ex);
706            }
707        } else if (phoneType == Phone.PHONE_TYPE_CDMA) {
708            if (DBG) log("mergeCalls");
709            PhoneApp app = PhoneApp.getInstance();
710            if (app.cdmaPhoneCallState.getCurrentCallState()
711                    == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) {
712                // Send flash cmd
713                // TODO(Moto): Need to change the call from switchHoldingAndActive to
714                // something meaningful as we are not actually trying to swap calls but
715                // instead are merging two calls by sending a Flash command.
716                switchHoldingAndActive(phone);
717
718                // Set the Phone Call State to conference
719                app.cdmaPhoneCallState.setCurrentCallState(
720                        CdmaPhoneCallState.PhoneCallState.CONF_CALL);
721            }
722        } else {
723            throw new IllegalStateException("Unexpected phone type: " + phoneType);
724        }
725    }
726
727    static void separateCall(Connection c) {
728        try {
729            if (DBG) log("separateCall: " + c.getAddress());
730            c.separate();
731        } catch (CallStateException ex) {
732            Log.w(LOG_TAG, "separateCall: caught " + ex, ex);
733        }
734    }
735
736    /**
737     * Handle the MMIInitiate message and put up an alert that lets
738     * the user cancel the operation, if applicable.
739     *
740     * @param context context to get strings.
741     * @param mmiCode the MmiCode object being started.
742     * @param buttonCallbackMessage message to post when button is clicked.
743     * @param previousAlert a previous alert used in this activity.
744     * @return the dialog handle
745     */
746    static Dialog displayMMIInitiate(Context context,
747                                          MmiCode mmiCode,
748                                          Message buttonCallbackMessage,
749                                          Dialog previousAlert) {
750        if (DBG) log("displayMMIInitiate: " + mmiCode);
751        if (previousAlert != null) {
752            previousAlert.dismiss();
753        }
754
755        // The UI paradigm we are using now requests that all dialogs have
756        // user interaction, and that any other messages to the user should
757        // be by way of Toasts.
758        //
759        // In adhering to this request, all MMI initiating "OK" dialogs
760        // (non-cancelable MMIs) that end up being closed when the MMI
761        // completes (thereby showing a completion dialog) are being
762        // replaced with Toasts.
763        //
764        // As a side effect, moving to Toasts for the non-cancelable MMIs
765        // also means that buttonCallbackMessage (which was tied into "OK")
766        // is no longer invokable for these dialogs.  This is not a problem
767        // since the only callback messages we supported were for cancelable
768        // MMIs anyway.
769        //
770        // A cancelable MMI is really just a USSD request. The term
771        // "cancelable" here means that we can cancel the request when the
772        // system prompts us for a response, NOT while the network is
773        // processing the MMI request.  Any request to cancel a USSD while
774        // the network is NOT ready for a response may be ignored.
775        //
776        // With this in mind, we replace the cancelable alert dialog with
777        // a progress dialog, displayed until we receive a request from
778        // the the network.  For more information, please see the comments
779        // in the displayMMIComplete() method below.
780        //
781        // Anything that is NOT a USSD request is a normal MMI request,
782        // which will bring up a toast (desribed above).
783        // Optional code for Extended USSD running prompt
784        if (mNwService != null) {
785            if (DBG) log("running USSD code, displaying indeterminate progress.");
786            // create the indeterminate progress dialog and display it.
787            ProgressDialog pd = new ProgressDialog(context);
788            CharSequence textmsg = "";
789            try {
790                textmsg = mNwService.getMmiRunningText();
791
792            } catch (RemoteException e) {
793                mNwService = null;
794                textmsg = context.getText(R.string.ussdRunning);
795            }
796            if (DBG) log("Extended NW displayMMIInitiate (" + textmsg+ ")");
797            pd.setMessage(textmsg);
798            pd.setCancelable(false);
799            pd.setIndeterminate(true);
800            pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
801            pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
802            pd.show();
803            // trigger a 15 seconds timeout to clear this progress dialog
804            mMmiTimeoutCbMsg = buttonCallbackMessage;
805            try {
806                mMmiTimeoutCbMsg.getTarget().sendMessageDelayed(buttonCallbackMessage, 15000);
807            } catch(NullPointerException e) {
808                mMmiTimeoutCbMsg = null;
809            }
810            return pd;
811        }
812
813        boolean isCancelable = (mmiCode != null) && mmiCode.isCancelable();
814
815        if (!isCancelable) {
816            if (DBG) log("not a USSD code, displaying status toast.");
817            CharSequence text = context.getText(R.string.mmiStarted);
818            Toast.makeText(context, text, Toast.LENGTH_SHORT)
819                .show();
820            return null;
821        } else {
822            if (DBG) log("running USSD code, displaying indeterminate progress.");
823
824            // create the indeterminate progress dialog and display it.
825            ProgressDialog pd = new ProgressDialog(context);
826            pd.setMessage(context.getText(R.string.ussdRunning));
827            pd.setCancelable(false);
828            pd.setIndeterminate(true);
829            pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
830
831            pd.show();
832
833            return pd;
834        }
835
836    }
837
838    /**
839     * Handle the MMIComplete message and fire off an intent to display
840     * the message.
841     *
842     * @param context context to get strings.
843     * @param mmiCode MMI result.
844     * @param previousAlert a previous alert used in this activity.
845     */
846    static void displayMMIComplete(final Phone phone, Context context, final MmiCode mmiCode,
847            Message dismissCallbackMessage,
848            AlertDialog previousAlert) {
849        CharSequence text;
850        int title = 0;  // title for the progress dialog, if needed.
851        MmiCode.State state = mmiCode.getState();
852
853        if (DBG) log("displayMMIComplete: state=" + state);
854        // Clear timeout trigger message
855        if(mMmiTimeoutCbMsg != null) {
856            try{
857                mMmiTimeoutCbMsg.getTarget().removeMessages(mMmiTimeoutCbMsg.what);
858                if (DBG) log("Extended NW displayMMIComplete removeMsg");
859            } catch (NullPointerException e) {
860            }
861            mMmiTimeoutCbMsg = null;
862        }
863
864
865        switch (state) {
866            case PENDING:
867                // USSD code asking for feedback from user.
868                text = mmiCode.getMessage();
869                if (DBG) log("- using text from PENDING MMI message: '" + text + "'");
870                break;
871            case CANCELLED:
872                text = context.getText(R.string.mmiCancelled);
873                break;
874            case COMPLETE:
875                if (PhoneApp.getInstance().getPUKEntryActivity() != null) {
876                    // if an attempt to unPUK the device was made, we specify
877                    // the title and the message here.
878                    title = com.android.internal.R.string.PinMmi;
879                    text = context.getText(R.string.puk_unlocked);
880                    break;
881                }
882                // All other conditions for the COMPLETE mmi state will cause
883                // the case to fall through to message logic in common with
884                // the FAILED case.
885
886            case FAILED:
887                text = mmiCode.getMessage();
888                if (DBG) log("- using text from MMI message: '" + text + "'");
889                break;
890            default:
891                throw new IllegalStateException("Unexpected MmiCode state: " + state);
892        }
893
894        if (previousAlert != null) {
895            previousAlert.dismiss();
896        }
897
898        // Check to see if a UI exists for the PUK activation.  If it does
899        // exist, then it indicates that we're trying to unblock the PUK.
900        PhoneApp app = PhoneApp.getInstance();
901        if ((app.getPUKEntryActivity() != null) && (state == MmiCode.State.COMPLETE)) {
902            if (DBG) log("displaying PUK unblocking progress dialog.");
903
904            // create the progress dialog, make sure the flags and type are
905            // set correctly.
906            ProgressDialog pd = new ProgressDialog(app);
907            pd.setTitle(title);
908            pd.setMessage(text);
909            pd.setCancelable(false);
910            pd.setIndeterminate(true);
911            pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
912            pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
913
914            // display the dialog
915            pd.show();
916
917            // indicate to the Phone app that the progress dialog has
918            // been assigned for the PUK unlock / SIM READY process.
919            app.setPukEntryProgressDialog(pd);
920
921        } else {
922            // In case of failure to unlock, we'll need to reset the
923            // PUK unlock activity, so that the user may try again.
924            if (app.getPUKEntryActivity() != null) {
925                app.setPukEntryActivity(null);
926            }
927
928            // A USSD in a pending state means that it is still
929            // interacting with the user.
930            if (state != MmiCode.State.PENDING) {
931                if (DBG) log("MMI code has finished running.");
932
933                // Replace response message with Extended Mmi wording
934                if (mNwService != null) {
935                    try {
936                        text = mNwService.getUserMessage(text);
937                    } catch (RemoteException e) {
938                        mNwService = null;
939                    }
940                    if (DBG) log("Extended NW displayMMIInitiate (" + text + ")");
941                    if (text == null || text.length() == 0)
942                        return;
943                }
944
945                // displaying system alert dialog on the screen instead of
946                // using another activity to display the message.  This
947                // places the message at the forefront of the UI.
948                AlertDialog newDialog = new AlertDialog.Builder(context)
949                        .setMessage(text)
950                        .setPositiveButton(R.string.ok, null)
951                        .setCancelable(true)
952                        .create();
953
954                newDialog.getWindow().setType(
955                        WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
956                newDialog.getWindow().addFlags(
957                        WindowManager.LayoutParams.FLAG_DIM_BEHIND);
958
959                newDialog.show();
960            } else {
961                if (DBG) log("USSD code has requested user input. Constructing input dialog.");
962
963                // USSD MMI code that is interacting with the user.  The
964                // basic set of steps is this:
965                //   1. User enters a USSD request
966                //   2. We recognize the request and displayMMIInitiate
967                //      (above) creates a progress dialog.
968                //   3. Request returns and we get a PENDING or COMPLETE
969                //      message.
970                //   4. These MMI messages are caught in the PhoneApp
971                //      (onMMIComplete) and the InCallScreen
972                //      (mHandler.handleMessage) which bring up this dialog
973                //      and closes the original progress dialog,
974                //      respectively.
975                //   5. If the message is anything other than PENDING,
976                //      we are done, and the alert dialog (directly above)
977                //      displays the outcome.
978                //   6. If the network is requesting more information from
979                //      the user, the MMI will be in a PENDING state, and
980                //      we display this dialog with the message.
981                //   7. User input, or cancel requests result in a return
982                //      to step 1.  Keep in mind that this is the only
983                //      time that a USSD should be canceled.
984
985                // inflate the layout with the scrolling text area for the dialog.
986                LayoutInflater inflater = (LayoutInflater) context.getSystemService(
987                        Context.LAYOUT_INFLATER_SERVICE);
988                View dialogView = inflater.inflate(R.layout.dialog_ussd_response, null);
989
990                // get the input field.
991                final EditText inputText = (EditText) dialogView.findViewById(R.id.input_field);
992
993                // specify the dialog's click listener, with SEND and CANCEL logic.
994                final DialogInterface.OnClickListener mUSSDDialogListener =
995                    new DialogInterface.OnClickListener() {
996                        public void onClick(DialogInterface dialog, int whichButton) {
997                            switch (whichButton) {
998                                case DialogInterface.BUTTON1:
999                                    phone.sendUssdResponse(inputText.getText().toString());
1000                                    break;
1001                                case DialogInterface.BUTTON2:
1002                                    if (mmiCode.isCancelable()) {
1003                                        mmiCode.cancel();
1004                                    }
1005                                    break;
1006                            }
1007                        }
1008                    };
1009
1010                // build the dialog
1011                final AlertDialog newDialog = new AlertDialog.Builder(context)
1012                        .setMessage(text)
1013                        .setView(dialogView)
1014                        .setPositiveButton(R.string.send_button, mUSSDDialogListener)
1015                        .setNegativeButton(R.string.cancel, mUSSDDialogListener)
1016                        .setCancelable(false)
1017                        .create();
1018
1019                // attach the key listener to the dialog's input field and make
1020                // sure focus is set.
1021                final View.OnKeyListener mUSSDDialogInputListener =
1022                    new View.OnKeyListener() {
1023                        public boolean onKey(View v, int keyCode, KeyEvent event) {
1024                            switch (keyCode) {
1025                                case KeyEvent.KEYCODE_CALL:
1026                                case KeyEvent.KEYCODE_ENTER:
1027                                    phone.sendUssdResponse(inputText.getText().toString());
1028                                    newDialog.dismiss();
1029                                    return true;
1030                            }
1031                            return false;
1032                        }
1033                    };
1034                inputText.setOnKeyListener(mUSSDDialogInputListener);
1035                inputText.requestFocus();
1036
1037                // set the window properties of the dialog
1038                newDialog.getWindow().setType(
1039                        WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
1040                newDialog.getWindow().addFlags(
1041                        WindowManager.LayoutParams.FLAG_DIM_BEHIND);
1042
1043                // now show the dialog!
1044                newDialog.show();
1045            }
1046        }
1047    }
1048
1049    /**
1050     * Cancels the current pending MMI operation, if applicable.
1051     * @return true if we canceled an MMI operation, or false
1052     *         if the current pending MMI wasn't cancelable
1053     *         or if there was no current pending MMI at all.
1054     *
1055     * @see displayMMIInitiate
1056     */
1057    static boolean cancelMmiCode(Phone phone) {
1058        List<? extends MmiCode> pendingMmis = phone.getPendingMmiCodes();
1059        int count = pendingMmis.size();
1060        if (DBG) log("cancelMmiCode: num pending MMIs = " + count);
1061
1062        boolean canceled = false;
1063        if (count > 0) {
1064            // assume that we only have one pending MMI operation active at a time.
1065            // I don't think it's possible to enter multiple MMI codes concurrently
1066            // in the phone UI, because during the MMI operation, an Alert panel
1067            // is displayed, which prevents more MMI code from being entered.
1068            MmiCode mmiCode = pendingMmis.get(0);
1069            if (mmiCode.isCancelable()) {
1070                mmiCode.cancel();
1071                canceled = true;
1072            }
1073        }
1074
1075        //clear timeout message and pre-set MMI command
1076        if (mNwService != null) {
1077            try {
1078                mNwService.clearMmiString();
1079            } catch (RemoteException e) {
1080                mNwService = null;
1081            }
1082        }
1083        if (mMmiTimeoutCbMsg != null) {
1084            mMmiTimeoutCbMsg = null;
1085        }
1086        return canceled;
1087    }
1088
1089    public static class VoiceMailNumberMissingException extends Exception {
1090        VoiceMailNumberMissingException() {
1091            super();
1092        }
1093
1094        VoiceMailNumberMissingException(String msg) {
1095            super(msg);
1096        }
1097    }
1098
1099    /**
1100     * Gets the phone number to be called from an intent.  Requires a Context
1101     * to access the contacts database, and a Phone to access the voicemail
1102     * number.
1103     *
1104     * <p>If <code>phone</code> is <code>null</code>, the function will return
1105     * <code>null</code> for <code>voicemail:</code> URIs;
1106     * if <code>context</code> is <code>null</code>, the function will return
1107     * <code>null</code> for person/phone URIs.</p>
1108     *
1109     * @param context a context to use (or
1110     * @param phone the phone on which the number would be called
1111     * @param intent the intent
1112     *
1113     * @throws VoiceMailNumberMissingException if <code>intent</code> contains
1114     *         a <code>voicemail:</code> URI, but <code>phone</code> does not
1115     *         have a voicemail number set.
1116     *
1117     * @return the phone number that would be called by the intent,
1118     *         or <code>null</code> if the number cannot be found.
1119     */
1120    static String getNumberFromIntent(Context context, Phone phone, Intent intent)
1121            throws VoiceMailNumberMissingException {
1122        final String number = PhoneNumberUtils.getNumberFromIntent(intent, context);
1123
1124        // Check for a voicemail-dailing request.  If the voicemail number is
1125        // empty, throw a VoiceMailNumberMissingException.
1126        if (intent.getData().getScheme().equals("voicemail") &&
1127                (number == null || TextUtils.isEmpty(number)))
1128            throw new VoiceMailNumberMissingException();
1129
1130        return number;
1131    }
1132
1133    /**
1134     * Returns the caller-id info corresponding to the specified Connection.
1135     * (This is just a simple wrapper around CallerInfo.getCallerInfo(): we
1136     * extract a phone number from the specified Connection, and feed that
1137     * number into CallerInfo.getCallerInfo().)
1138     *
1139     * The returned CallerInfo may be null in certain error cases, like if the
1140     * specified Connection was null, or if we weren't able to get a valid
1141     * phone number from the Connection.
1142     *
1143     * Finally, if the getCallerInfo() call did succeed, we save the resulting
1144     * CallerInfo object in the "userData" field of the Connection.
1145     *
1146     * NOTE: This API should be avoided, with preference given to the
1147     * asynchronous startGetCallerInfo API.
1148     */
1149    static CallerInfo getCallerInfo(Context context, Connection c) {
1150        CallerInfo info = null;
1151
1152        if (c != null) {
1153            //See if there is a URI attached.  If there is, this means
1154            //that there is no CallerInfo queried yet, so we'll need to
1155            //replace the URI with a full CallerInfo object.
1156            Object userDataObject = c.getUserData();
1157            if (userDataObject instanceof Uri) {
1158                info = CallerInfo.getCallerInfo(context, (Uri) userDataObject);
1159                if (info != null) {
1160                    c.setUserData(info);
1161                }
1162            } else {
1163                if (userDataObject instanceof CallerInfoToken) {
1164                    //temporary result, while query is running
1165                    info = ((CallerInfoToken) userDataObject).currentInfo;
1166                } else {
1167                    //final query result
1168                    info = (CallerInfo) userDataObject;
1169                }
1170                if (info == null) {
1171                    // No URI, or Existing CallerInfo, so we'll have to make do with
1172                    // querying a new CallerInfo using the connection's phone number.
1173                    String number = c.getAddress();
1174
1175                    if (DBG) log("getCallerInfo: number = " + number);
1176
1177                    if (!TextUtils.isEmpty(number)) {
1178                        info = CallerInfo.getCallerInfo(context, number);
1179                        if (info != null) {
1180                            c.setUserData(info);
1181                        }
1182                    }
1183                }
1184            }
1185        }
1186        return info;
1187    }
1188
1189    /**
1190     * Class returned by the startGetCallerInfo call to package a temporary
1191     * CallerInfo Object, to be superceded by the CallerInfo Object passed
1192     * into the listener when the query with token mAsyncQueryToken is complete.
1193     */
1194    public static class CallerInfoToken {
1195        /**indicates that there will no longer be updates to this request.*/
1196        public boolean isFinal;
1197
1198        public CallerInfo currentInfo;
1199        public CallerInfoAsyncQuery asyncQuery;
1200    }
1201
1202    /**
1203     * Start a CallerInfo Query based on the earliest connection in the call.
1204     */
1205    static CallerInfoToken startGetCallerInfo(Context context, Call call,
1206            CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
1207        PhoneApp app = PhoneApp.getInstance();
1208        Connection conn = null;
1209        int phoneType = app.phone.getPhoneType();
1210        if (phoneType == Phone.PHONE_TYPE_CDMA) {
1211            conn = call.getLatestConnection();
1212        } else if (phoneType == Phone.PHONE_TYPE_GSM) {
1213            conn = call.getEarliestConnection();
1214        } else {
1215            throw new IllegalStateException("Unexpected phone type: " + phoneType);
1216        }
1217
1218        return startGetCallerInfo(context, conn, listener, cookie);
1219    }
1220
1221    /**
1222     * place a temporary callerinfo object in the hands of the caller and notify
1223     * caller when the actual query is done.
1224     */
1225    static CallerInfoToken startGetCallerInfo(Context context, Connection c,
1226            CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
1227        CallerInfoToken cit;
1228
1229        if (c == null) {
1230            //TODO: perhaps throw an exception here.
1231            cit = new CallerInfoToken();
1232            cit.asyncQuery = null;
1233            return cit;
1234        }
1235
1236        // There are now 3 states for the userdata.
1237        //   1. Uri - query has not been executed yet
1238        //   2. CallerInfoToken - query is executing, but has not completed.
1239        //   3. CallerInfo - query has executed.
1240        // In each case we have slightly different behaviour:
1241        //   1. If the query has not been executed yet (Uri or null), we start
1242        //      query execution asynchronously, and note it by attaching a
1243        //      CallerInfoToken as the userData.
1244        //   2. If the query is executing (CallerInfoToken), we've essentially
1245        //      reached a state where we've received multiple requests for the
1246        //      same callerInfo.  That means that once the query is complete,
1247        //      we'll need to execute the additional listener requested.
1248        //   3. If the query has already been executed (CallerInfo), we just
1249        //      return the CallerInfo object as expected.
1250        //   4. Regarding isFinal - there are cases where the CallerInfo object
1251        //      will not be attached, like when the number is empty (caller id
1252        //      blocking).  This flag is used to indicate that the
1253        //      CallerInfoToken object is going to be permanent since no
1254        //      query results will be returned.  In the case where a query
1255        //      has been completed, this flag is used to indicate to the caller
1256        //      that the data will not be updated since it is valid.
1257        //
1258        //      Note: For the case where a number is NOT retrievable, we leave
1259        //      the CallerInfo as null in the CallerInfoToken.  This is
1260        //      something of a departure from the original code, since the old
1261        //      code manufactured a CallerInfo object regardless of the query
1262        //      outcome.  From now on, we will append an empty CallerInfo
1263        //      object, to mirror previous behaviour, and to avoid Null Pointer
1264        //      Exceptions.
1265        Object userDataObject = c.getUserData();
1266        if (userDataObject instanceof Uri) {
1267            //create a dummy callerinfo, populate with what we know from URI.
1268            cit = new CallerInfoToken();
1269            cit.currentInfo = new CallerInfo();
1270            cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1271                    (Uri) userDataObject, sCallerInfoQueryListener, c);
1272            cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1273            cit.isFinal = false;
1274
1275            c.setUserData(cit);
1276
1277            if (DBG) log("startGetCallerInfo: query based on Uri: " + userDataObject);
1278
1279        } else if (userDataObject == null) {
1280            // No URI, or Existing CallerInfo, so we'll have to make do with
1281            // querying a new CallerInfo using the connection's phone number.
1282            String number = c.getAddress();
1283
1284            cit = new CallerInfoToken();
1285            cit.currentInfo = new CallerInfo();
1286
1287            // Store CNAP information retrieved from the Connection (we want to do this
1288            // here regardless of whether the number is empty or not).
1289            cit.currentInfo.cnapName =  c.getCnapName();
1290            cit.currentInfo.name = cit.currentInfo.cnapName; // This can still get overwritten
1291                                                             // by ContactInfo later
1292            cit.currentInfo.numberPresentation = c.getNumberPresentation();
1293            cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1294
1295            if (DBG) log("startGetCallerInfo: number = " + number);
1296            if (DBG) log("startGetCallerInfo: CNAP Info from FW(1): name="
1297                    + cit.currentInfo.cnapName
1298                    + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1299
1300            // handling case where number is null (caller id hidden) as well.
1301            if (!TextUtils.isEmpty(number)) {
1302                // Check for special CNAP cases and modify the CallerInfo accordingly
1303                // to be sure we keep the right information to display/log later
1304                number = modifyForSpecialCnapCases(context, cit.currentInfo, number,
1305                        cit.currentInfo.numberPresentation);
1306
1307                cit.currentInfo.phoneNumber = number;
1308                // For scenarios where we may receive a valid number from the network but a
1309                // restricted/unavailable presentation, we do not want to perform a contact query
1310                // (see note on isFinal above). So we set isFinal to true here as well.
1311                if (cit.currentInfo.numberPresentation != Connection.PRESENTATION_ALLOWED) {
1312                    cit.isFinal = true;
1313                } else {
1314                    cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1315                            number, sCallerInfoQueryListener, c);
1316                    cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1317                    cit.isFinal = false;
1318                }
1319            } else {
1320                // This is the case where we are querying on a number that
1321                // is null or empty, like a caller whose caller id is
1322                // blocked or empty (CLIR).  The previous behaviour was to
1323                // throw a null CallerInfo object back to the user, but
1324                // this departure is somewhat cleaner.
1325                if (DBG) log("startGetCallerInfo: No query to start, send trivial reply.");
1326                cit.isFinal = true; // please see note on isFinal, above.
1327            }
1328
1329            c.setUserData(cit);
1330
1331            if (DBG) log("startGetCallerInfo: query based on number: " + number);
1332
1333        } else if (userDataObject instanceof CallerInfoToken) {
1334            // query is running, just tack on this listener to the queue.
1335            cit = (CallerInfoToken) userDataObject;
1336
1337            // handling case where number is null (caller id hidden) as well.
1338            if (cit.asyncQuery != null) {
1339                cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1340
1341                if (DBG) log("startGetCallerInfo: query already running, adding listener: " +
1342                        listener.getClass().toString());
1343            } else {
1344                // handling case where number/name gets updated later on by the network
1345                String updatedNumber = c.getAddress();
1346                if (DBG) log("startGetCallerInfo: updatedNumber initially = " + updatedNumber);
1347                if (!TextUtils.isEmpty(updatedNumber)) {
1348                    // Store CNAP information retrieved from the Connection
1349                    cit.currentInfo.cnapName =  c.getCnapName();
1350                    // This can still get overwritten by ContactInfo
1351                    cit.currentInfo.name = cit.currentInfo.cnapName;
1352                    cit.currentInfo.numberPresentation = c.getNumberPresentation();
1353                    cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1354
1355                    updatedNumber = modifyForSpecialCnapCases(context, cit.currentInfo,
1356                            updatedNumber, cit.currentInfo.numberPresentation);
1357
1358                    cit.currentInfo.phoneNumber = updatedNumber;
1359                    if (DBG) log("startGetCallerInfo: updatedNumber=" + updatedNumber);
1360                    if (DBG) log("startGetCallerInfo: CNAP Info from FW(2): name="
1361                            + cit.currentInfo.cnapName
1362                            + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1363                    // For scenarios where we may receive a valid number from the network but a
1364                    // restricted/unavailable presentation, we do not want to perform a contact query
1365                    // (see note on isFinal above). So we set isFinal to true here as well.
1366                    if (cit.currentInfo.numberPresentation != Connection.PRESENTATION_ALLOWED) {
1367                        cit.isFinal = true;
1368                    } else {
1369                        cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
1370                                updatedNumber, sCallerInfoQueryListener, c);
1371                        cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
1372                        cit.isFinal = false;
1373                    }
1374                } else {
1375                    if (DBG) log("startGetCallerInfo: No query to attach to, send trivial reply.");
1376                    if (cit.currentInfo == null) {
1377                        cit.currentInfo = new CallerInfo();
1378                    }
1379                    // Store CNAP information retrieved from the Connection
1380                    cit.currentInfo.cnapName = c.getCnapName();  // This can still get
1381                                                                 // overwritten by ContactInfo
1382                    cit.currentInfo.name = cit.currentInfo.cnapName;
1383                    cit.currentInfo.numberPresentation = c.getNumberPresentation();
1384                    cit.currentInfo.namePresentation = c.getCnapNamePresentation();
1385
1386                    if (DBG) log("startGetCallerInfo: CNAP Info from FW(3): name="
1387                            + cit.currentInfo.cnapName
1388                            + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
1389                    cit.isFinal = true; // please see note on isFinal, above.
1390                }
1391            }
1392        } else {
1393            cit = new CallerInfoToken();
1394            cit.currentInfo = (CallerInfo) userDataObject;
1395            cit.asyncQuery = null;
1396            cit.isFinal = true;
1397            // since the query is already done, call the listener.
1398            if (DBG) log("startGetCallerInfo: query already done, returning CallerInfo");
1399        }
1400        return cit;
1401    }
1402
1403    /**
1404     * Implemented for CallerInfo.OnCallerInfoQueryCompleteListener interface.
1405     * Updates the connection's userData when called.
1406     */
1407    private static final int QUERY_TOKEN = -1;
1408    static CallerInfoAsyncQuery.OnQueryCompleteListener sCallerInfoQueryListener =
1409        new CallerInfoAsyncQuery.OnQueryCompleteListener () {
1410            public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
1411                if (DBG) log("query complete, updating connection.userdata");
1412                Connection conn = (Connection) cookie;
1413
1414                // Added a check if CallerInfo is coming from ContactInfo or from Connection.
1415                // If no ContactInfo, then we want to use CNAP information coming from network
1416                if (DBG) log("- onQueryComplete: CallerInfo:" + ci);
1417                if (ci.contactExists || ci.isEmergencyNumber() || ci.isVoiceMailNumber()) {
1418                    // If the number presentation has not been set by
1419                    // the ContactInfo, use the one from the
1420                    // connection.
1421
1422                    // TODO: Need a new util method to merge the info
1423                    // from the Connection in a CallerInfo object.
1424                    // Here 'ci' is a new CallerInfo instance read
1425                    // from the DB. It has lost all the connection
1426                    // info preset before the query (see PhoneUtils
1427                    // line 1334). We should have a method to merge
1428                    // back into this new instance the info from the
1429                    // connection object not set by the DB. If the
1430                    // Connection already has a CallerInfo instance in
1431                    // userData, then we could use this instance to
1432                    // fill 'ci' in. The same routine could be used in
1433                    // PhoneUtils.
1434                    if (0 == ci.numberPresentation) {
1435                        ci.numberPresentation = conn.getNumberPresentation();
1436                    }
1437                } else {
1438                    CallerInfo newCi = getCallerInfo(null, conn);
1439                    if (newCi != null) {
1440                        newCi.phoneNumber = ci.phoneNumber; // To get formatted phone number
1441                        ci = newCi;
1442                    }
1443                }
1444                conn.setUserData(ci);
1445            }
1446        };
1447
1448
1449    /**
1450     * Returns a single "name" for the specified given a CallerInfo object.
1451     * If the name is null, return defaultString as the default value, usually
1452     * context.getString(R.string.unknown).
1453     */
1454    static String getCompactNameFromCallerInfo(CallerInfo ci, Context context) {
1455        if (DBG) log("getCompactNameFromCallerInfo: info = " + ci);
1456
1457        String compactName = null;
1458        if (ci != null) {
1459            compactName = ci.name;
1460            if ((compactName == null) || (TextUtils.isEmpty(compactName))) {
1461                compactName = ci.phoneNumber;
1462            }
1463            // Perform any modifications for special CNAP cases to the name being displayed,
1464            // if applicable.
1465            compactName = modifyForSpecialCnapCases(context, ci, compactName, ci.numberPresentation);
1466        }
1467
1468        if ((compactName == null) || (TextUtils.isEmpty(compactName))) {
1469            // If we're still null/empty here, then check if we have a presentation
1470            // string that takes precedence that we could return, otherwise display
1471            // "unknown" string.
1472            if (ci != null && ci.numberPresentation == Connection.PRESENTATION_RESTRICTED) {
1473                compactName = context.getString(R.string.private_num);
1474            } else if (ci != null && ci.numberPresentation == Connection.PRESENTATION_PAYPHONE) {
1475                compactName = context.getString(R.string.payphone);
1476            } else {
1477                compactName = context.getString(R.string.unknown);
1478            }
1479        }
1480        if (DBG) log("getCompactNameFromCallerInfo: compactName=" + compactName);
1481        return compactName;
1482    }
1483
1484    /**
1485     * Returns true if the specified Call is a "conference call", meaning
1486     * that it owns more than one Connection object.  This information is
1487     * used to trigger certain UI changes that appear when a conference
1488     * call is active (like displaying the label "Conference call", and
1489     * enabling the "Manage conference" UI.)
1490     *
1491     * Watch out: This method simply checks the number of Connections,
1492     * *not* their states.  So if a Call has (for example) one ACTIVE
1493     * connection and one DISCONNECTED connection, this method will return
1494     * true (which is unintuitive, since the Call isn't *really* a
1495     * conference call any more.)
1496     *
1497     * @return true if the specified call has more than one connection (in any state.)
1498     */
1499    static boolean isConferenceCall(Call call) {
1500        // CDMA phones don't have the same concept of "conference call" as
1501        // GSM phones do; there's no special "conference call" state of
1502        // the UI or a "manage conference" function.  (Instead, when
1503        // you're in a 3-way call, all we can do is display the "generic"
1504        // state of the UI.)  So as far as the in-call UI is concerned,
1505        // Conference corresponds to generic display.
1506        PhoneApp app = PhoneApp.getInstance();
1507        int phoneType = app.phone.getPhoneType();
1508        if (phoneType == Phone.PHONE_TYPE_CDMA) {
1509            if (app.cdmaPhoneCallState.getCurrentCallState()
1510                    == CdmaPhoneCallState.PhoneCallState.CONF_CALL) {
1511                return true;
1512            }
1513        } else if (phoneType == Phone.PHONE_TYPE_GSM) {
1514            List<Connection> connections = call.getConnections();
1515            if (connections != null && connections.size() > 1) {
1516                return true;
1517            }
1518        } else {
1519            throw new IllegalStateException("Unexpected phone type: " + phoneType);
1520        }
1521        return false;
1522
1523        // TODO: We may still want to change the semantics of this method
1524        // to say that a given call is only really a conference call if
1525        // the number of ACTIVE connections, not the total number of
1526        // connections, is greater than one.  (See warning comment in the
1527        // javadoc above.)
1528        // Here's an implementation of that:
1529        //        if (connections == null) {
1530        //            return false;
1531        //        }
1532        //        int numActiveConnections = 0;
1533        //        for (Connection conn : connections) {
1534        //            if (DBG) log("  - CONN: " + conn + ", state = " + conn.getState());
1535        //            if (conn.getState() == Call.State.ACTIVE) numActiveConnections++;
1536        //            if (numActiveConnections > 1) {
1537        //                return true;
1538        //            }
1539        //        }
1540        //        return false;
1541    }
1542
1543    /**
1544     * Launch the Dialer to start a new call.
1545     * This is just a wrapper around the ACTION_DIAL intent.
1546     */
1547    static void startNewCall(final Phone phone) {
1548        final KeyguardManager keyguardManager = PhoneApp.getInstance().getKeyguardManager();
1549        if (!keyguardManager.inKeyguardRestrictedInputMode()) {
1550            internalStartNewCall(phone);
1551        } else {
1552            keyguardManager.exitKeyguardSecurely(new KeyguardManager.OnKeyguardExitResult() {
1553                public void onKeyguardExitResult(boolean success) {
1554                    if (success) {
1555                        internalStartNewCall(phone);
1556                    }
1557                }
1558            });
1559        }
1560    }
1561
1562    private static void internalStartNewCall(Phone phone) {
1563        // Sanity-check that this is OK given the current state of the phone.
1564        if (!okToAddCall(phone)) {
1565            Log.w(LOG_TAG, "startNewCall: can't add a new call in the current state");
1566            dumpCallState(phone);
1567            return;
1568        }
1569
1570        // if applicable, mute the call while we're showing the add call UI.
1571        if (!phone.getForegroundCall().isIdle()) {
1572            setMuteInternal(phone, true);
1573            // Inform the phone app that this mute state was NOT done
1574            // voluntarily by the User.
1575            PhoneApp.getInstance().setRestoreMuteOnInCallResume(true);
1576        }
1577
1578        Intent intent = new Intent(Intent.ACTION_DIAL);
1579        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1580
1581        // when we request the dialer come up, we also want to inform
1582        // it that we're going through the "add call" option from the
1583        // InCallScreen / PhoneUtils.
1584        intent.putExtra(ADD_CALL_MODE_KEY, true);
1585
1586        PhoneApp.getInstance().startActivity(intent);
1587    }
1588
1589    /**
1590     * Brings up the UI used to handle an incoming call.
1591     *
1592     * Originally, this brought up an IncomingCallPanel instance
1593     * (which was a subclass of Dialog) on top of whatever app
1594     * was currently running.  Now, we take you directly to the
1595     * in-call screen, whose CallCard automatically does the right
1596     * thing if there's a Call that's currently ringing.
1597     */
1598    static void showIncomingCallUi() {
1599        if (DBG) log("showIncomingCallUi()...");
1600        PhoneApp app = PhoneApp.getInstance();
1601
1602        // Before bringing up the "incoming call" UI, force any system
1603        // dialogs (like "recent tasks" or the power dialog) to close first.
1604        try {
1605            ActivityManagerNative.getDefault().closeSystemDialogs("call");
1606        } catch (RemoteException e) {
1607        }
1608
1609        // Go directly to the in-call screen.
1610        // (No need to do anything special if we're already on the in-call
1611        // screen; it'll notice the phone state change and update itself.)
1612
1613        // But first, grab a full wake lock.  We do this here, before we
1614        // even fire off the InCallScreen intent, to make sure the
1615        // ActivityManager doesn't try to pause the InCallScreen as soon
1616        // as it comes up.  (See bug 1648751.)
1617        //
1618        // And since the InCallScreen isn't visible yet (we haven't even
1619        // fired off the intent yet), we DON'T want the screen to actually
1620        // come on right now.  So *before* acquiring the wake lock we need
1621        // to call preventScreenOn(), which tells the PowerManager that
1622        // the screen should stay off even if someone's holding a full
1623        // wake lock.  (This prevents any flicker during the "incoming
1624        // call" sequence.  The corresponding preventScreenOn(false) call
1625        // will come from the InCallScreen when it's finally ready to be
1626        // displayed.)
1627        //
1628        // TODO: this is all a temporary workaround.  The real fix is to add
1629        // an Activity attribute saying "this Activity wants to wake up the
1630        // phone when it's displayed"; that way the ActivityManager could
1631        // manage the wake locks *and* arrange for the screen to come on at
1632        // the exact moment that the InCallScreen is ready to be displayed.
1633        // (See bug 1648751.)
1634        app.preventScreenOn(true);
1635        app.requestWakeState(PhoneApp.WakeState.FULL);
1636
1637        // Fire off the InCallScreen intent.
1638        app.displayCallScreen();
1639    }
1640
1641    static void turnOnSpeaker(Context context, boolean flag, boolean store) {
1642        if (DBG) log("turnOnSpeaker: " + flag);
1643        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1644
1645        audioManager.setSpeakerphoneOn(flag);
1646        // record the speaker-enable value
1647        if (store) {
1648            sIsSpeakerEnabled = flag;
1649        }
1650        if (flag) {
1651            NotificationMgr.getDefault().notifySpeakerphone();
1652        } else {
1653            NotificationMgr.getDefault().cancelSpeakerphone();
1654        }
1655
1656        // We also need to make a fresh call to PhoneApp.updateWakeState()
1657        // any time the speaker state changes, since the screen timeout is
1658        // sometimes different depending on whether or not the speaker is
1659        // in use.
1660        PhoneApp app = PhoneApp.getInstance();
1661        app.updateWakeState();
1662
1663        // Update the Proximity sensor based on speaker state
1664        app.updateProximitySensorMode(app.phone.getState());
1665    }
1666
1667    /**
1668     * Restore the speaker mode, called after a wired headset disconnect
1669     * event.
1670     */
1671    static void restoreSpeakerMode(Context context) {
1672        if (DBG) log("restoreSpeakerMode, restoring to: " + sIsSpeakerEnabled);
1673
1674        // change the mode if needed.
1675        if (isSpeakerOn(context) != sIsSpeakerEnabled) {
1676            turnOnSpeaker(context, sIsSpeakerEnabled, false);
1677        }
1678    }
1679
1680    static boolean isSpeakerOn(Context context) {
1681        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1682        return audioManager.isSpeakerphoneOn();
1683    }
1684
1685    /**
1686     * Wrapper around Phone.setMute() that also updates the mute icon in
1687     * the status bar.
1688     *
1689     * All muting / unmuting from the in-call UI should go through this
1690     * wrapper.
1691     */
1692    static void setMute(Phone phone, boolean muted) {
1693        // make the call to mute the audio
1694        setMuteInternal(phone, muted);
1695
1696        // update the foreground connections to match.  This includes
1697        // all the connections on conference calls.
1698        for (Connection cn : phone.getForegroundCall().getConnections()) {
1699            if (sConnectionMuteTable.get(cn) == null) {
1700                if (DBG) log("problem retrieving mute value for this connection.");
1701            }
1702            sConnectionMuteTable.put(cn, Boolean.valueOf(muted));
1703        }
1704    }
1705
1706    /**
1707     * Internally used muting function.  All UI calls should use {@link setMute}
1708     */
1709    static void setMuteInternal(Phone phone, boolean muted) {
1710        if (DBG) log("setMute: " + muted);
1711        phone.setMute(muted);
1712        if (muted) {
1713            NotificationMgr.getDefault().notifyMute();
1714        } else {
1715            NotificationMgr.getDefault().cancelMute();
1716        }
1717    }
1718
1719    static boolean getMute(Phone phone) {
1720        return phone.getMute();
1721    }
1722
1723    /**
1724     * A really simple wrapper around AudioManager.setMode(),
1725     * with a bit of extra logging to help debug the exact
1726     * timing (and call stacks) for all our setMode() calls.
1727     *
1728     * Also, add additional state monitoring to determine
1729     * whether or not certain calls to change the audio mode
1730     * are ignored.
1731     */
1732    /* package */ static void setAudioMode(Context context, int mode) {
1733        if (DBG) Log.d(LOG_TAG, "setAudioMode(" + audioModeToString(mode) + ")...");
1734
1735        //decide whether or not to ignore the audio setting
1736        boolean ignore = false;
1737
1738        switch (sAudioBehaviourState) {
1739            case AUDIO_RINGING:
1740                ignore = ((mode == AudioManager.MODE_NORMAL) || (mode == AudioManager.MODE_IN_CALL));
1741                break;
1742            case AUDIO_OFFHOOK:
1743                ignore = ((mode == AudioManager.MODE_NORMAL) || (mode == AudioManager.MODE_RINGTONE));
1744                break;
1745            case AUDIO_IDLE:
1746            default:
1747                ignore = (mode == AudioManager.MODE_IN_CALL);
1748                break;
1749        }
1750
1751        if (!ignore) {
1752            AudioManager audioManager =
1753                    (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
1754            // Enable stack dump only when actively debugging ("new Throwable()" is expensive!)
1755            if (DBG_SETAUDIOMODE_STACK) Log.d(LOG_TAG, "Stack:", new Throwable("stack dump"));
1756            audioManager.setMode(mode);
1757        } else {
1758            if (DBG) Log.d(LOG_TAG, "setAudioMode(), state is " + sAudioBehaviourState +
1759                    " ignoring " + audioModeToString(mode) + " request");
1760        }
1761    }
1762    private static String audioModeToString(int mode) {
1763        switch (mode) {
1764            case AudioManager.MODE_INVALID: return "MODE_INVALID";
1765            case AudioManager.MODE_CURRENT: return "MODE_CURRENT";
1766            case AudioManager.MODE_NORMAL: return "MODE_NORMAL";
1767            case AudioManager.MODE_RINGTONE: return "MODE_RINGTONE";
1768            case AudioManager.MODE_IN_CALL: return "MODE_IN_CALL";
1769            default: return String.valueOf(mode);
1770        }
1771    }
1772
1773    /**
1774     * Handles the wired headset button while in-call.
1775     *
1776     * This is called from the PhoneApp, not from the InCallScreen,
1777     * since the HEADSETHOOK button means "mute or unmute the current
1778     * call" *any* time a call is active, even if the user isn't actually
1779     * on the in-call screen.
1780     *
1781     * @return true if we consumed the event.
1782     */
1783    /* package */ static boolean handleHeadsetHook(Phone phone) {
1784        if (DBG) log("handleHeadsetHook()...");
1785
1786        // If the phone is totally idle, we ignore HEADSETHOOK events
1787        // (and instead let them fall through to the media player.)
1788        if (phone.getState() == Phone.State.IDLE) {
1789            return false;
1790        }
1791
1792        // Ok, the phone is in use.
1793        // The headset button button means "Answer" if an incoming call is
1794        // ringing.  If not, it toggles the mute / unmute state.
1795        //
1796        // And in any case we *always* consume this event; this means
1797        // that the usual mediaplayer-related behavior of the headset
1798        // button will NEVER happen while the user is on a call.
1799
1800        final boolean hasRingingCall = !phone.getRingingCall().isIdle();
1801        final boolean hasActiveCall = !phone.getForegroundCall().isIdle();
1802        final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle();
1803
1804        if (hasRingingCall) {
1805            // If an incoming call is ringing, answer it (just like with the
1806            // CALL button):
1807            int phoneType = phone.getPhoneType();
1808            if (phoneType == Phone.PHONE_TYPE_CDMA) {
1809                answerCall(phone);
1810            } else if (phoneType == Phone.PHONE_TYPE_GSM) {
1811                if (hasActiveCall && hasHoldingCall) {
1812                    if (DBG) log("handleHeadsetHook: ringing (both lines in use) ==> answer!");
1813                    answerAndEndActive(phone);
1814                } else {
1815                    if (DBG) log("handleHeadsetHook: ringing ==> answer!");
1816                    answerCall(phone);  // Automatically holds the current active call,
1817                                        // if there is one
1818                }
1819            } else {
1820                throw new IllegalStateException("Unexpected phone type: " + phoneType);
1821            }
1822        } else {
1823            // No incoming ringing call.
1824            // If it is NOT an emg #, toggle the mute state. Otherwise, ignore the hook.
1825            Connection c = phone.getForegroundCall().getLatestConnection();
1826            if (c != null && !PhoneNumberUtils.isEmergencyNumber(c.getAddress())) {
1827                if (getMute(phone)) {
1828                    if (DBG) log("handleHeadsetHook: UNmuting...");
1829                    setMute(phone, false);
1830                } else {
1831                    if (DBG) log("handleHeadsetHook: muting...");
1832                    setMute(phone, true);
1833                }
1834            }
1835        }
1836
1837        // Even if the InCallScreen is the current activity, there's no
1838        // need to force it to update, because (1) if we answered a
1839        // ringing call, the InCallScreen will imminently get a phone
1840        // state change event (causing an update), and (2) if we muted or
1841        // unmuted, the setMute() call automagically updates the status
1842        // bar, and there's no "mute" indication in the InCallScreen
1843        // itself (other than the menu item, which only ever stays
1844        // onscreen for a second anyway.)
1845        // TODO: (2) isn't entirely true anymore. Once we return our result
1846        // to the PhoneApp, we ask InCallScreen to update its control widgets
1847        // in case we changed mute or speaker state and phones with touch-
1848        // screen [toggle] buttons need to update themselves.
1849
1850        return true;
1851    }
1852
1853    /**
1854     * Look for ANY connections on the phone that qualify as being
1855     * disconnected.
1856     *
1857     * @return true if we find a connection that is disconnected over
1858     * all the phone's call objects.
1859     */
1860    /* package */ static boolean hasDisconnectedConnections(Phone phone) {
1861        return hasDisconnectedConnections(phone.getForegroundCall()) ||
1862                hasDisconnectedConnections(phone.getBackgroundCall()) ||
1863                hasDisconnectedConnections(phone.getRingingCall());
1864    }
1865
1866    /**
1867     * Iterate over all connections in a call to see if there are any
1868     * that are not alive (disconnected or idle).
1869     *
1870     * @return true if we find a connection that is disconnected, and
1871     * pending removal via
1872     * {@link com.android.internal.telephony.gsm.GsmCall#clearDisconnected()}.
1873     */
1874    private static final boolean hasDisconnectedConnections(Call call) {
1875        // look through all connections for non-active ones.
1876        for (Connection c : call.getConnections()) {
1877            if (!c.isAlive()) {
1878                return true;
1879            }
1880        }
1881        return false;
1882    }
1883
1884    //
1885    // Misc UI policy helper functions
1886    //
1887
1888    /**
1889     * @return true if we're allowed to swap calls, given the current
1890     * state of the Phone.
1891     */
1892    /* package */ static boolean okToSwapCalls(Phone phone) {
1893        int phoneType = phone.getPhoneType();
1894        if (phoneType == Phone.PHONE_TYPE_CDMA) {
1895            // CDMA: "Swap" is enabled only when the phone reaches a *generic*.
1896            // state by either accepting a Call Waiting or by merging two calls
1897            PhoneApp app = PhoneApp.getInstance();
1898            return (app.cdmaPhoneCallState.getCurrentCallState()
1899                    == CdmaPhoneCallState.PhoneCallState.CONF_CALL);
1900        } else if (phoneType == Phone.PHONE_TYPE_GSM) {
1901            // GSM: "Swap" is available if both lines are in use and there's no
1902            // incoming call.  (Actually we need to verify that the active
1903            // call really is in the ACTIVE state and the holding call really
1904            // is in the HOLDING state, since you *can't* actually swap calls
1905            // when the foreground call is DIALING or ALERTING.)
1906            return phone.getRingingCall().isIdle()
1907                    && (phone.getForegroundCall().getState() == Call.State.ACTIVE)
1908                    && (phone.getBackgroundCall().getState() == Call.State.HOLDING);
1909        } else {
1910            throw new IllegalStateException("Unexpected phone type: " + phoneType);
1911        }
1912    }
1913
1914    /**
1915     * @return true if we're allowed to merge calls, given the current
1916     * state of the Phone.
1917     */
1918    /* package */ static boolean okToMergeCalls(Phone phone) {
1919        int phoneType = phone.getPhoneType();
1920        if (phoneType == Phone.PHONE_TYPE_CDMA) {
1921            // CDMA: "Merge" is enabled only when the user is in a 3Way call.
1922            PhoneApp app = PhoneApp.getInstance();
1923            return (app.cdmaPhoneCallState.getCurrentCallState()
1924                    == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE);
1925        } else if (phoneType == Phone.PHONE_TYPE_GSM) {
1926            // GSM: "Merge" is available if both lines are in use and there's no
1927            // incoming call, *and* the current conference isn't already
1928            // "full".
1929            return phone.getRingingCall().isIdle() && phone.canConference();
1930        } else {
1931            throw new IllegalStateException("Unexpected phone type: " + phoneType);
1932        }
1933    }
1934
1935    /**
1936     * @return true if the UI should let you add a new call, given the current
1937     * state of the Phone.
1938     */
1939    /* package */ static boolean okToAddCall(Phone phone) {
1940        int phoneType = phone.getPhoneType();
1941        if (phoneType == Phone.PHONE_TYPE_CDMA) {
1942           // CDMA: "Add call" menu item is only enabled when the call is in
1943           // - SINGLE_ACTIVE state
1944           // - After 60 seconds of user Ignoring/Missing a Call Waiting call.
1945            PhoneApp app = PhoneApp.getInstance();
1946            return ((app.cdmaPhoneCallState.getCurrentCallState()
1947                    == CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE)
1948                    && (app.cdmaPhoneCallState.getAddCallMenuStateAfterCallWaiting()));
1949        } else if (phoneType == Phone.PHONE_TYPE_GSM) {
1950            // GSM: "Add call" is available only if ALL of the following are true:
1951            // - There's no incoming ringing call
1952            // - There's < 2 lines in use
1953            // - The foreground call is ACTIVE or IDLE or DISCONNECTED.
1954            //   (We mainly need to make sure it *isn't* DIALING or ALERTING.)
1955            final boolean hasRingingCall = !phone.getRingingCall().isIdle();
1956            final boolean hasActiveCall = !phone.getForegroundCall().isIdle();
1957            final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle();
1958            final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
1959            final Call.State fgCallState = phone.getForegroundCall().getState();
1960
1961            return !hasRingingCall
1962                    && !allLinesTaken
1963                    && ((fgCallState == Call.State.ACTIVE)
1964                        || (fgCallState == Call.State.IDLE)
1965                        || (fgCallState == Call.State.DISCONNECTED));
1966        } else {
1967            throw new IllegalStateException("Unexpected phone type: " + phoneType);
1968        }
1969    }
1970
1971    /**
1972     * Based on the input CNAP number string,
1973     * @return _RESTRICTED or _UNKNOWN for all the special CNAP strings.
1974     * Otherwise, return CNAP_SPECIAL_CASE_NO.
1975     */
1976    private static int checkCnapSpecialCases(String n) {
1977        if (n.equals("PRIVATE") ||
1978                n.equals("P") ||
1979                n.equals("RES")) {
1980            if (DBG) log("checkCnapSpecialCases, PRIVATE string: " + n);
1981            return Connection.PRESENTATION_RESTRICTED;
1982        } else if (n.equals("UNAVAILABLE") ||
1983                n.equals("UNKNOWN") ||
1984                n.equals("UNA") ||
1985                n.equals("U")) {
1986            if (DBG) log("checkCnapSpecialCases, UNKNOWN string: " + n);
1987            return Connection.PRESENTATION_UNKNOWN;
1988        } else {
1989            if (DBG) log("checkCnapSpecialCases, normal str. number: " + n);
1990            return CNAP_SPECIAL_CASE_NO;
1991        }
1992    }
1993
1994    /**
1995     * Handles certain "corner cases" for CNAP. When we receive weird phone numbers
1996     * from the network to indicate different number presentations, convert them to
1997     * expected number and presentation values within the CallerInfo object.
1998     * @param number number we use to verify if we are in a corner case
1999     * @param presentation presentation value used to verify if we are in a corner case
2000     * @return the new String that should be used for the phone number
2001     */
2002    /* package */ static String modifyForSpecialCnapCases(Context context, CallerInfo ci,
2003            String number, int presentation) {
2004        // Obviously we return number if ci == null, but still return number if
2005        // number == null, because in these cases the correct string will still be
2006        // displayed/logged after this function returns based on the presentation value.
2007        if (ci == null || number == null) return number;
2008
2009        if (DBG) log("modifyForSpecialCnapCases: initially, number=" + number
2010                + ", presentation=" + presentation);
2011
2012        // "ABSENT NUMBER" is a possible value we could get from the network as the
2013        // phone number, so if this happens, change it to "Unknown" in the CallerInfo
2014        // and fix the presentation to be the same.
2015        if (number.equals(context.getString(R.string.absent_num))
2016                && presentation == Connection.PRESENTATION_ALLOWED) {
2017            number = context.getString(R.string.unknown);
2018            ci.numberPresentation = Connection.PRESENTATION_UNKNOWN;
2019        }
2020
2021        // Check for other special "corner cases" for CNAP and fix them similarly. Corner
2022        // cases only apply if we received an allowed presentation from the network, so check
2023        // if we think we have an allowed presentation, or if the CallerInfo presentation doesn't
2024        // match the presentation passed in for verification (meaning we changed it previously
2025        // because it's a corner case and we're being called from a different entry point).
2026        if (ci.numberPresentation == Connection.PRESENTATION_ALLOWED
2027                || (ci.numberPresentation != presentation
2028                        && presentation == Connection.PRESENTATION_ALLOWED)) {
2029            int cnapSpecialCase = checkCnapSpecialCases(number);
2030            if (cnapSpecialCase != CNAP_SPECIAL_CASE_NO) {
2031                // For all special strings, change number & numberPresentation.
2032                if (cnapSpecialCase == Connection.PRESENTATION_RESTRICTED) {
2033                    number = context.getString(R.string.private_num);
2034                } else if (cnapSpecialCase == Connection.PRESENTATION_UNKNOWN) {
2035                    number = context.getString(R.string.unknown);
2036                }
2037                if (DBG) log("SpecialCnap: number=" + number
2038                        + "; presentation now=" + cnapSpecialCase);
2039                ci.numberPresentation = cnapSpecialCase;
2040            }
2041        }
2042        if (DBG) log("modifyForSpecialCnapCases: returning number string=" + number);
2043        return number;
2044    }
2045
2046    //
2047    // Support for 3rd party phone service providers.
2048    //
2049
2050    /**
2051     * Check if all the provider's info is present in the intent.
2052     * @param intent Expected to have the provider's extra.
2053     * @return true if the intent has all the extras to build the
2054     * in-call screen's provider info overlay.
2055     */
2056    /* package */ static boolean hasPhoneProviderExtras(Intent intent) {
2057        if (null == intent) {
2058            return false;
2059        }
2060        final String name = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE);
2061        final String gatewayUri = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI);
2062
2063        return !TextUtils.isEmpty(name) && !TextUtils.isEmpty(gatewayUri);
2064    }
2065
2066    /**
2067     * Copy all the expected extras set when a 3rd party provider is
2068     * used from the source intent to the destination one.  Checks all
2069     * the required extras are present, if any is missing, none will
2070     * be copied.
2071     * @param src Intent which may contain the provider's extras.
2072     * @param dst Intent where a copy of the extras will be added if applicable.
2073     */
2074    /* package */ static void checkAndCopyPhoneProviderExtras(Intent src, Intent dst) {
2075        if (!hasPhoneProviderExtras(src)) {
2076            Log.d(LOG_TAG, "checkAndCopyPhoneProviderExtras: some or all extras are missing.");
2077            return;
2078        }
2079
2080        dst.putExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE,
2081                     src.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE));
2082        dst.putExtra(InCallScreen.EXTRA_GATEWAY_URI,
2083                     src.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI));
2084    }
2085
2086    /**
2087     * Get the provider's label from the intent.
2088     * @param context to lookup the provider's package name.
2089     * @param intent with an extra set to the provider's package name.
2090     * @return The provider's application label. null if an error
2091     * occurred during the lookup of the package name or the label.
2092     */
2093    /* package */ static CharSequence getProviderLabel(Context context, Intent intent) {
2094        String packageName = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE);
2095        PackageManager pm = context.getPackageManager();
2096
2097        try {
2098            ApplicationInfo info = pm.getApplicationInfo(packageName, 0);
2099
2100            return pm.getApplicationLabel(info);
2101        } catch (PackageManager.NameNotFoundException e) {
2102            return null;
2103        }
2104    }
2105
2106    /**
2107     * Get the provider's icon.
2108     * @param context to lookup the provider's icon.
2109     * @param intent with an extra set to the provider's package name.
2110     * @return The provider's application icon. null if an error occured during the icon lookup.
2111     */
2112    /* package */ static Drawable getProviderIcon(Context context, Intent intent) {
2113        String packageName = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_PROVIDER_PACKAGE);
2114        PackageManager pm = context.getPackageManager();
2115
2116        try {
2117            return pm.getApplicationIcon(packageName);
2118        } catch (PackageManager.NameNotFoundException e) {
2119            return null;
2120        }
2121    }
2122
2123    /**
2124     * Return the gateway uri from the intent.
2125     * @param intent With the gateway uri extra.
2126     * @return The gateway URI or null if not found.
2127     */
2128    /* package */ static Uri getProviderGatewayUri(Intent intent) {
2129        String uri = intent.getStringExtra(InCallScreen.EXTRA_GATEWAY_URI);
2130        return TextUtils.isEmpty(uri) ? null : Uri.parse(uri);
2131    }
2132
2133    /**
2134     * Return a formatted version of the uri's scheme specific
2135     * part. E.g for 'tel:12345678', return '1-234-5678'.
2136     * @param uri A 'tel:' URI with the gateway phone number.
2137     * @return the provider's address (from the gateway uri) formatted
2138     * for user display. null if uri was null or its scheme was not 'tel:'.
2139     */
2140    /* package */ static String formatProviderUri(Uri uri) {
2141        if (null != uri) {
2142            if ("tel".equals(uri.getScheme())) {
2143                return PhoneNumberUtils.formatNumber(uri.getSchemeSpecificPart());
2144            } else {
2145                return uri.toString();
2146            }
2147        }
2148        return null;
2149    }
2150
2151    /**
2152     * Check if a phone number can be route through a 3rd party
2153     * gateway. The number must be a global phone number in numerical
2154     * form (1-800-666-SEXY won't work).
2155     *
2156     * MMI codes and the like cannot be used as a dial number for the
2157     * gateway either.
2158     *
2159     * @param number To be dialed via a 3rd party gateway.
2160     * @return true If the number can be routed through the 3rd party network.
2161     */
2162    /* package */ static boolean isRoutableViaGateway(String number) {
2163        if (TextUtils.isEmpty(number)) {
2164            return false;
2165        }
2166        number = PhoneNumberUtils.stripSeparators(number);
2167        if (!number.equals(PhoneNumberUtils.convertKeypadLettersToDigits(number))) {
2168            return false;
2169        }
2170        number = PhoneNumberUtils.extractNetworkPortion(number);
2171        return PhoneNumberUtils.isGlobalPhoneNumber(number);
2172    }
2173
2174    //
2175    // General phone and call state debugging/testing code
2176    //
2177
2178    /* package */ static void dumpCallState(Phone phone) {
2179        PhoneApp app = PhoneApp.getInstance();
2180        Log.d(LOG_TAG, "dumpCallState():");
2181        Log.d(LOG_TAG, "- Phone: " + phone + ", name = " + phone.getPhoneName()
2182              + ", state = " + phone.getState());
2183
2184        StringBuilder b = new StringBuilder(128);
2185
2186        Call call = phone.getForegroundCall();
2187        b.setLength(0);
2188        b.append("  - FG call: ").append(call.getState());
2189        b.append(" isAlive ").append(call.getState().isAlive());
2190        b.append(" isRinging ").append(call.getState().isRinging());
2191        b.append(" isDialing ").append(call.getState().isDialing());
2192        b.append(" isIdle ").append(call.isIdle());
2193        b.append(" hasConnections ").append(call.hasConnections());
2194        Log.d(LOG_TAG, b.toString());
2195
2196        call = phone.getBackgroundCall();
2197        b.setLength(0);
2198        b.append("  - BG call: ").append(call.getState());
2199        b.append(" isAlive ").append(call.getState().isAlive());
2200        b.append(" isRinging ").append(call.getState().isRinging());
2201        b.append(" isDialing ").append(call.getState().isDialing());
2202        b.append(" isIdle ").append(call.isIdle());
2203        b.append(" hasConnections ").append(call.hasConnections());
2204        Log.d(LOG_TAG, b.toString());
2205
2206        call = phone.getRingingCall();
2207        b.setLength(0);
2208        b.append("  - RINGING call: ").append(call.getState());
2209        b.append(" isAlive ").append(call.getState().isAlive());
2210        b.append(" isRinging ").append(call.getState().isRinging());
2211        b.append(" isDialing ").append(call.getState().isDialing());
2212        b.append(" isIdle ").append(call.isIdle());
2213        b.append(" hasConnections ").append(call.hasConnections());
2214        Log.d(LOG_TAG, b.toString());
2215
2216
2217        final boolean hasRingingCall = !phone.getRingingCall().isIdle();
2218        final boolean hasActiveCall = !phone.getForegroundCall().isIdle();
2219        final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle();
2220        final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
2221        b.setLength(0);
2222        b.append("  - hasRingingCall ").append(hasRingingCall);
2223        b.append(" hasActiveCall ").append(hasActiveCall);
2224        b.append(" hasHoldingCall ").append(hasHoldingCall);
2225        b.append(" allLinesTaken ").append(allLinesTaken);
2226        Log.d(LOG_TAG, b.toString());
2227
2228        // On CDMA phones, dump out the CdmaPhoneCallState too:
2229        if (phone.getPhoneType() == Phone.PHONE_TYPE_CDMA) {
2230            if (app.cdmaPhoneCallState != null) {
2231                Log.d(LOG_TAG, "  - CDMA call state: "
2232                      + app.cdmaPhoneCallState.getCurrentCallState());
2233            } else {
2234                Log.d(LOG_TAG, "  - CDMA device, but null cdmaPhoneCallState!");
2235            }
2236        }
2237
2238        // Watch out: the isRinging() call below does NOT tell us anything
2239        // about the state of the telephony layer; it merely tells us whether
2240        // the Ringer manager is currently playing the ringtone.
2241        boolean ringing = app.getRinger().isRinging();
2242        Log.d(LOG_TAG, "  - Ringer state: " + ringing);
2243    }
2244
2245    private static void log(String msg) {
2246        Log.d(LOG_TAG, msg);
2247    }
2248}
2249