Home | History | Annotate | Download | only in phone
      1 /*
      2  * Copyright (C) 2006 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.android.phone;
     18 
     19 import android.app.AlertDialog;
     20 import android.app.Dialog;
     21 import android.app.ProgressDialog;
     22 import android.bluetooth.IBluetoothHeadsetPhone;
     23 import android.content.ActivityNotFoundException;
     24 import android.content.Context;
     25 import android.content.DialogInterface;
     26 import android.content.Intent;
     27 import android.content.pm.ApplicationInfo;
     28 import android.content.pm.PackageManager;
     29 import android.content.res.Configuration;
     30 import android.graphics.drawable.Drawable;
     31 import android.media.AudioManager;
     32 import android.net.Uri;
     33 import android.net.sip.SipManager;
     34 import android.os.AsyncResult;
     35 import android.os.Handler;
     36 import android.os.Message;
     37 import android.os.RemoteException;
     38 import android.os.SystemProperties;
     39 import android.telephony.PhoneNumberUtils;
     40 import android.text.TextUtils;
     41 import android.util.Log;
     42 import android.view.KeyEvent;
     43 import android.view.LayoutInflater;
     44 import android.view.View;
     45 import android.view.WindowManager;
     46 import android.widget.EditText;
     47 import android.widget.Toast;
     48 
     49 import com.android.internal.telephony.Call;
     50 import com.android.internal.telephony.CallManager;
     51 import com.android.internal.telephony.CallStateException;
     52 import com.android.internal.telephony.CallerInfo;
     53 import com.android.internal.telephony.CallerInfoAsyncQuery;
     54 import com.android.internal.telephony.Connection;
     55 import com.android.internal.telephony.MmiCode;
     56 import com.android.internal.telephony.Phone;
     57 import com.android.internal.telephony.PhoneConstants;
     58 import com.android.internal.telephony.TelephonyCapabilities;
     59 import com.android.internal.telephony.TelephonyProperties;
     60 import com.android.internal.telephony.cdma.CdmaConnection;
     61 import com.android.internal.telephony.sip.SipPhone;
     62 import com.android.phone.CallGatewayManager.RawGatewayInfo;
     63 
     64 import java.util.ArrayList;
     65 import java.util.Arrays;
     66 import java.util.Hashtable;
     67 import java.util.Iterator;
     68 import java.util.List;
     69 
     70 /**
     71  * Misc utilities for the Phone app.
     72  */
     73 public class PhoneUtils {
     74     private static final String LOG_TAG = "PhoneUtils";
     75     private static final boolean DBG = (PhoneGlobals.DBG_LEVEL >= 2);
     76 
     77     // Do not check in with VDBG = true, since that may write PII to the system log.
     78     private static final boolean VDBG = false;
     79 
     80     /** Control stack trace for Audio Mode settings */
     81     private static final boolean DBG_SETAUDIOMODE_STACK = false;
     82 
     83     /** Identifier for the "Add Call" intent extra. */
     84     static final String ADD_CALL_MODE_KEY = "add_call_mode";
     85 
     86     // Return codes from placeCall()
     87     static final int CALL_STATUS_DIALED = 0;  // The number was successfully dialed
     88     static final int CALL_STATUS_DIALED_MMI = 1;  // The specified number was an MMI code
     89     static final int CALL_STATUS_FAILED = 2;  // The call failed
     90 
     91     // State of the Phone's audio modes
     92     // Each state can move to the other states, but within the state only certain
     93     //  transitions for AudioManager.setMode() are allowed.
     94     static final int AUDIO_IDLE = 0;  /** audio behaviour at phone idle */
     95     static final int AUDIO_RINGING = 1;  /** audio behaviour while ringing */
     96     static final int AUDIO_OFFHOOK = 2;  /** audio behaviour while in call. */
     97 
     98     // USSD string length for MMI operations
     99     static final int MIN_USSD_LEN = 1;
    100     static final int MAX_USSD_LEN = 160;
    101 
    102     /** Speaker state, persisting between wired headset connection events */
    103     private static boolean sIsSpeakerEnabled = false;
    104 
    105     /** Hash table to store mute (Boolean) values based upon the connection.*/
    106     private static Hashtable<Connection, Boolean> sConnectionMuteTable =
    107         new Hashtable<Connection, Boolean>();
    108 
    109     /** Static handler for the connection/mute tracking */
    110     private static ConnectionHandler mConnectionHandler;
    111 
    112     /** Phone state changed event*/
    113     private static final int PHONE_STATE_CHANGED = -1;
    114 
    115     /** Define for not a special CNAP string */
    116     private static final int CNAP_SPECIAL_CASE_NO = -1;
    117 
    118     /** Noise suppression status as selected by user */
    119     private static boolean sIsNoiseSuppressionEnabled = true;
    120 
    121     /**
    122      * Handler that tracks the connections and updates the value of the
    123      * Mute settings for each connection as needed.
    124      */
    125     private static class ConnectionHandler extends Handler {
    126         @Override
    127         public void handleMessage(Message msg) {
    128             AsyncResult ar = (AsyncResult) msg.obj;
    129             switch (msg.what) {
    130                 case PHONE_STATE_CHANGED:
    131                     if (DBG) log("ConnectionHandler: updating mute state for each connection");
    132 
    133                     CallManager cm = (CallManager) ar.userObj;
    134 
    135                     // update the foreground connections, if there are new connections.
    136                     // Have to get all foreground calls instead of the active one
    137                     // because there may two foreground calls co-exist in shore period
    138                     // (a racing condition based on which phone changes firstly)
    139                     // Otherwise the connection may get deleted.
    140                     List<Connection> fgConnections = new ArrayList<Connection>();
    141                     for (Call fgCall : cm.getForegroundCalls()) {
    142                         if (!fgCall.isIdle()) {
    143                             fgConnections.addAll(fgCall.getConnections());
    144                         }
    145                     }
    146                     for (Connection cn : fgConnections) {
    147                         if (sConnectionMuteTable.get(cn) == null) {
    148                             sConnectionMuteTable.put(cn, Boolean.FALSE);
    149                         }
    150                     }
    151 
    152                     // mute is connection based operation, we need loop over
    153                     // all background calls instead of the first one to update
    154                     // the background connections, if there are new connections.
    155                     List<Connection> bgConnections = new ArrayList<Connection>();
    156                     for (Call bgCall : cm.getBackgroundCalls()) {
    157                         if (!bgCall.isIdle()) {
    158                             bgConnections.addAll(bgCall.getConnections());
    159                         }
    160                     }
    161                     for (Connection cn : bgConnections) {
    162                         if (sConnectionMuteTable.get(cn) == null) {
    163                           sConnectionMuteTable.put(cn, Boolean.FALSE);
    164                         }
    165                     }
    166 
    167                     // Check to see if there are any lingering connections here
    168                     // (disconnected connections), use old-school iterators to avoid
    169                     // concurrent modification exceptions.
    170                     Connection cn;
    171                     for (Iterator<Connection> cnlist = sConnectionMuteTable.keySet().iterator();
    172                             cnlist.hasNext();) {
    173                         cn = cnlist.next();
    174                         if (!fgConnections.contains(cn) && !bgConnections.contains(cn)) {
    175                             if (DBG) log("connection '" + cn + "' not accounted for, removing.");
    176                             cnlist.remove();
    177                         }
    178                     }
    179 
    180                     // Restore the mute state of the foreground call if we're not IDLE,
    181                     // otherwise just clear the mute state. This is really saying that
    182                     // as long as there is one or more connections, we should update
    183                     // the mute state with the earliest connection on the foreground
    184                     // call, and that with no connections, we should be back to a
    185                     // non-mute state.
    186                     if (cm.getState() != PhoneConstants.State.IDLE) {
    187                         restoreMuteState();
    188                     } else {
    189                         setMuteInternal(cm.getFgPhone(), false);
    190                     }
    191 
    192                     break;
    193             }
    194         }
    195     }
    196 
    197     /**
    198      * Register the ConnectionHandler with the phone, to receive connection events
    199      */
    200     public static void initializeConnectionHandler(CallManager cm) {
    201         if (mConnectionHandler == null) {
    202             mConnectionHandler = new ConnectionHandler();
    203         }
    204 
    205         // pass over cm as user.obj
    206         cm.registerForPreciseCallStateChanged(mConnectionHandler, PHONE_STATE_CHANGED, cm);
    207 
    208     }
    209 
    210     /** This class is never instantiated. */
    211     private PhoneUtils() {
    212     }
    213 
    214     /**
    215      * Answer the currently-ringing call.
    216      *
    217      * @return true if we answered the call, or false if there wasn't
    218      *         actually a ringing incoming call, or some other error occurred.
    219      *
    220      * @see #answerAndEndHolding(CallManager, Call)
    221      * @see #answerAndEndActive(CallManager, Call)
    222      */
    223     /* package */ static boolean answerCall(Call ringingCall) {
    224         log("answerCall(" + ringingCall + ")...");
    225         final PhoneGlobals app = PhoneGlobals.getInstance();
    226         final CallNotifier notifier = app.notifier;
    227 
    228         // If the ringer is currently ringing and/or vibrating, stop it
    229         // right now (before actually answering the call.)
    230         notifier.silenceRinger();
    231 
    232         final Phone phone = ringingCall.getPhone();
    233         final boolean phoneIsCdma = (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA);
    234         boolean answered = false;
    235         IBluetoothHeadsetPhone btPhone = null;
    236 
    237         if (phoneIsCdma) {
    238             // Stop any signalInfo tone being played when a Call waiting gets answered
    239             if (ringingCall.getState() == Call.State.WAITING) {
    240                 notifier.stopSignalInfoTone();
    241             }
    242         }
    243 
    244         if (ringingCall != null && ringingCall.isRinging()) {
    245             if (DBG) log("answerCall: call state = " + ringingCall.getState());
    246             try {
    247                 if (phoneIsCdma) {
    248                     if (app.cdmaPhoneCallState.getCurrentCallState()
    249                             == CdmaPhoneCallState.PhoneCallState.IDLE) {
    250                         // This is the FIRST incoming call being answered.
    251                         // Set the Phone Call State to SINGLE_ACTIVE
    252                         app.cdmaPhoneCallState.setCurrentCallState(
    253                                 CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
    254                     } else {
    255                         // This is the CALL WAITING call being answered.
    256                         // Set the Phone Call State to CONF_CALL
    257                         app.cdmaPhoneCallState.setCurrentCallState(
    258                                 CdmaPhoneCallState.PhoneCallState.CONF_CALL);
    259                         // Enable "Add Call" option after answering a Call Waiting as the user
    260                         // should be allowed to add another call in case one of the parties
    261                         // drops off
    262                         app.cdmaPhoneCallState.setAddCallMenuStateAfterCallWaiting(true);
    263 
    264                         // If a BluetoothPhoneService is valid we need to set the second call state
    265                         // so that the Bluetooth client can update the Call state correctly when
    266                         // a call waiting is answered from the Phone.
    267                         btPhone = app.getBluetoothPhoneService();
    268                         if (btPhone != null) {
    269                             try {
    270                                 btPhone.cdmaSetSecondCallState(true);
    271                             } catch (RemoteException e) {
    272                                 Log.e(LOG_TAG, Log.getStackTraceString(new Throwable()));
    273                             }
    274                         }
    275                   }
    276                 }
    277 
    278                 final boolean isRealIncomingCall = isRealIncomingCall(ringingCall.getState());
    279 
    280                 //if (DBG) log("sPhone.acceptCall");
    281                 app.mCM.acceptCall(ringingCall);
    282                 answered = true;
    283 
    284                 // Always reset to "unmuted" for a freshly-answered call
    285                 setMute(false);
    286 
    287                 setAudioMode();
    288 
    289                 // Check is phone in any dock, and turn on speaker accordingly
    290                 final boolean speakerActivated = activateSpeakerIfDocked(phone);
    291 
    292                 final BluetoothManager btManager = app.getBluetoothManager();
    293 
    294                 // When answering a phone call, the user will move the phone near to her/his ear
    295                 // and start conversation, without checking its speaker status. If some other
    296                 // application turned on the speaker mode before the call and didn't turn it off,
    297                 // Phone app would need to be responsible for the speaker phone.
    298                 // Here, we turn off the speaker if
    299                 // - the phone call is the first in-coming call,
    300                 // - we did not activate speaker by ourselves during the process above, and
    301                 // - Bluetooth headset is not in use.
    302                 if (isRealIncomingCall && !speakerActivated && isSpeakerOn(app)
    303                         && !btManager.isBluetoothHeadsetAudioOn()) {
    304                     // This is not an error but might cause users' confusion. Add log just in case.
    305                     Log.i(LOG_TAG, "Forcing speaker off due to new incoming call...");
    306                     turnOnSpeaker(app, false, true);
    307                 }
    308             } catch (CallStateException ex) {
    309                 Log.w(LOG_TAG, "answerCall: caught " + ex, ex);
    310 
    311                 if (phoneIsCdma) {
    312                     // restore the cdmaPhoneCallState and btPhone.cdmaSetSecondCallState:
    313                     app.cdmaPhoneCallState.setCurrentCallState(
    314                             app.cdmaPhoneCallState.getPreviousCallState());
    315                     if (btPhone != null) {
    316                         try {
    317                             btPhone.cdmaSetSecondCallState(false);
    318                         } catch (RemoteException e) {
    319                             Log.e(LOG_TAG, Log.getStackTraceString(new Throwable()));
    320                         }
    321                     }
    322                 }
    323             }
    324         }
    325         return answered;
    326     }
    327 
    328     /**
    329      * Hangs up all active calls.
    330      */
    331     static void hangupAllCalls(CallManager cm) {
    332         final Call ringing = cm.getFirstActiveRingingCall();
    333         final Call fg = cm.getActiveFgCall();
    334         final Call bg = cm.getFirstActiveBgCall();
    335 
    336         // We go in reverse order, BG->FG->RINGING because hanging up a ringing call or an active
    337         // call can move a bg call to a fg call which would force us to loop over each call
    338         // several times.  This ordering works best to ensure we dont have any more calls.
    339         if (bg != null && !bg.isIdle()) {
    340             hangup(bg);
    341         }
    342         if (fg != null && !fg.isIdle()) {
    343             hangup(fg);
    344         }
    345         if (ringing != null && !ringing.isIdle()) {
    346             hangupRingingCall(fg);
    347         }
    348     }
    349 
    350     /**
    351      * Smart "hang up" helper method which hangs up exactly one connection,
    352      * based on the current Phone state, as follows:
    353      * <ul>
    354      * <li>If there's a ringing call, hang that up.
    355      * <li>Else if there's a foreground call, hang that up.
    356      * <li>Else if there's a background call, hang that up.
    357      * <li>Otherwise do nothing.
    358      * </ul>
    359      * @return true if we successfully hung up, or false
    360      *              if there were no active calls at all.
    361      */
    362     static boolean hangup(CallManager cm) {
    363         boolean hungup = false;
    364         Call ringing = cm.getFirstActiveRingingCall();
    365         Call fg = cm.getActiveFgCall();
    366         Call bg = cm.getFirstActiveBgCall();
    367 
    368         if (!ringing.isIdle()) {
    369             log("hangup(): hanging up ringing call");
    370             hungup = hangupRingingCall(ringing);
    371         } else if (!fg.isIdle()) {
    372             log("hangup(): hanging up foreground call");
    373             hungup = hangup(fg);
    374         } else if (!bg.isIdle()) {
    375             log("hangup(): hanging up background call");
    376             hungup = hangup(bg);
    377         } else {
    378             // No call to hang up!  This is unlikely in normal usage,
    379             // since the UI shouldn't be providing an "End call" button in
    380             // the first place.  (But it *can* happen, rarely, if an
    381             // active call happens to disconnect on its own right when the
    382             // user is trying to hang up..)
    383             log("hangup(): no active call to hang up");
    384         }
    385         if (DBG) log("==> hungup = " + hungup);
    386 
    387         return hungup;
    388     }
    389 
    390     static boolean hangupRingingCall(Call ringing) {
    391         if (DBG) log("hangup ringing call");
    392         int phoneType = ringing.getPhone().getPhoneType();
    393         Call.State state = ringing.getState();
    394 
    395         if (state == Call.State.INCOMING) {
    396             // Regular incoming call (with no other active calls)
    397             log("hangupRingingCall(): regular incoming call: hangup()");
    398             return hangup(ringing);
    399         } else if (state == Call.State.WAITING) {
    400             // Call-waiting: there's an incoming call, but another call is
    401             // already active.
    402             // TODO: It would be better for the telephony layer to provide
    403             // a "hangupWaitingCall()" API that works on all devices,
    404             // rather than us having to check the phone type here and do
    405             // the notifier.sendCdmaCallWaitingReject() hack for CDMA phones.
    406             if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
    407                 // CDMA: Ringing call and Call waiting hangup is handled differently.
    408                 // For Call waiting we DO NOT call the conventional hangup(call) function
    409                 // as in CDMA we just want to hangup the Call waiting connection.
    410                 log("hangupRingingCall(): CDMA-specific call-waiting hangup");
    411                 final CallNotifier notifier = PhoneGlobals.getInstance().notifier;
    412                 notifier.sendCdmaCallWaitingReject();
    413                 return true;
    414             } else {
    415                 // Otherwise, the regular hangup() API works for
    416                 // call-waiting calls too.
    417                 log("hangupRingingCall(): call-waiting call: hangup()");
    418                 return hangup(ringing);
    419             }
    420         } else {
    421             // Unexpected state: the ringing call isn't INCOMING or
    422             // WAITING, so there's no reason to have called
    423             // hangupRingingCall() in the first place.
    424             // (Presumably the incoming call went away at the exact moment
    425             // we got here, so just do nothing.)
    426             Log.w(LOG_TAG, "hangupRingingCall: no INCOMING or WAITING call");
    427             return false;
    428         }
    429     }
    430 
    431     static boolean hangupActiveCall(Call foreground) {
    432         if (DBG) log("hangup active call");
    433         return hangup(foreground);
    434     }
    435 
    436     static boolean hangupHoldingCall(Call background) {
    437         if (DBG) log("hangup holding call");
    438         return hangup(background);
    439     }
    440 
    441     /**
    442      * Used in CDMA phones to end the complete Call session
    443      * @param phone the Phone object.
    444      * @return true if *any* call was successfully hung up
    445      */
    446     static boolean hangupRingingAndActive(Phone phone) {
    447         boolean hungUpRingingCall = false;
    448         boolean hungUpFgCall = false;
    449         Call ringingCall = phone.getRingingCall();
    450         Call fgCall = phone.getForegroundCall();
    451 
    452         // Hang up any Ringing Call
    453         if (!ringingCall.isIdle()) {
    454             log("hangupRingingAndActive: Hang up Ringing Call");
    455             hungUpRingingCall = hangupRingingCall(ringingCall);
    456         }
    457 
    458         // Hang up any Active Call
    459         if (!fgCall.isIdle()) {
    460             log("hangupRingingAndActive: Hang up Foreground Call");
    461             hungUpFgCall = hangupActiveCall(fgCall);
    462         }
    463 
    464         return hungUpRingingCall || hungUpFgCall;
    465     }
    466 
    467     /**
    468      * Trivial wrapper around Call.hangup(), except that we return a
    469      * boolean success code rather than throwing CallStateException on
    470      * failure.
    471      *
    472      * @return true if the call was successfully hung up, or false
    473      *         if the call wasn't actually active.
    474      */
    475     static boolean hangup(Call call) {
    476         try {
    477             CallManager cm = PhoneGlobals.getInstance().mCM;
    478 
    479             if (call.getState() == Call.State.ACTIVE && cm.hasActiveBgCall()) {
    480                 // handle foreground call hangup while there is background call
    481                 log("- hangup(Call): hangupForegroundResumeBackground...");
    482                 cm.hangupForegroundResumeBackground(cm.getFirstActiveBgCall());
    483             } else {
    484                 log("- hangup(Call): regular hangup()...");
    485                 call.hangup();
    486             }
    487             return true;
    488         } catch (CallStateException ex) {
    489             Log.e(LOG_TAG, "Call hangup: caught " + ex, ex);
    490         }
    491 
    492         return false;
    493     }
    494 
    495     /**
    496      * Trivial wrapper around Connection.hangup(), except that we silently
    497      * do nothing (rather than throwing CallStateException) if the
    498      * connection wasn't actually active.
    499      */
    500     static void hangup(Connection c) {
    501         try {
    502             if (c != null) {
    503                 c.hangup();
    504             }
    505         } catch (CallStateException ex) {
    506             Log.w(LOG_TAG, "Connection hangup: caught " + ex, ex);
    507         }
    508     }
    509 
    510     static boolean answerAndEndHolding(CallManager cm, Call ringing) {
    511         if (DBG) log("end holding & answer waiting: 1");
    512         if (!hangupHoldingCall(cm.getFirstActiveBgCall())) {
    513             Log.e(LOG_TAG, "end holding failed!");
    514             return false;
    515         }
    516 
    517         if (DBG) log("end holding & answer waiting: 2");
    518         return answerCall(ringing);
    519 
    520     }
    521 
    522     /**
    523      * Answers the incoming call specified by "ringing", and ends the currently active phone call.
    524      *
    525      * This method is useful when's there's an incoming call which we cannot manage with the
    526      * current call. e.g. when you are having a phone call with CDMA network and has received
    527      * a SIP call, then we won't expect our telephony can manage those phone calls simultaneously.
    528      * Note that some types of network may allow multiple phone calls at once; GSM allows to hold
    529      * an ongoing phone call, so we don't need to end the active call. The caller of this method
    530      * needs to check if the network allows multiple phone calls or not.
    531      *
    532      * @see #answerCall(Call)
    533      * @see InCallScreen#internalAnswerCall()
    534      */
    535     /* package */ static boolean answerAndEndActive(CallManager cm, Call ringing) {
    536         if (DBG) log("answerAndEndActive()...");
    537 
    538         // Unlike the answerCall() method, we *don't* need to stop the
    539         // ringer or change audio modes here since the user is already
    540         // in-call, which means that the audio mode is already set
    541         // correctly, and that we wouldn't have started the ringer in the
    542         // first place.
    543 
    544         // hanging up the active call also accepts the waiting call
    545         // while active call and waiting call are from the same phone
    546         // i.e. both from GSM phone
    547         if (!hangupActiveCall(cm.getActiveFgCall())) {
    548             Log.w(LOG_TAG, "end active call failed!");
    549             return false;
    550         }
    551 
    552         // since hangupActiveCall() also accepts the ringing call
    553         // check if the ringing call was already answered or not
    554         // only answer it when the call still is ringing
    555         if (ringing.isRinging()) {
    556             return answerCall(ringing);
    557         }
    558 
    559         return true;
    560     }
    561 
    562     /**
    563      * For a CDMA phone, advance the call state upon making a new
    564      * outgoing call.
    565      *
    566      * <pre>
    567      *   IDLE -> SINGLE_ACTIVE
    568      * or
    569      *   SINGLE_ACTIVE -> THRWAY_ACTIVE
    570      * </pre>
    571      * @param app The phone instance.
    572      */
    573     private static void updateCdmaCallStateOnNewOutgoingCall(PhoneGlobals app,
    574             Connection connection) {
    575         if (app.cdmaPhoneCallState.getCurrentCallState() ==
    576             CdmaPhoneCallState.PhoneCallState.IDLE) {
    577             // This is the first outgoing call. Set the Phone Call State to ACTIVE
    578             app.cdmaPhoneCallState.setCurrentCallState(
    579                 CdmaPhoneCallState.PhoneCallState.SINGLE_ACTIVE);
    580         } else {
    581             // This is the second outgoing call. Set the Phone Call State to 3WAY
    582             app.cdmaPhoneCallState.setCurrentCallState(
    583                 CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE);
    584 
    585             app.getCallModeler().setCdmaOutgoing3WayCall(connection);
    586         }
    587     }
    588 
    589     /**
    590      * @see placeCall below
    591      */
    592     public static int placeCall(Context context, Phone phone, String number, Uri contactRef,
    593             boolean isEmergencyCall) {
    594         return placeCall(context, phone, number, contactRef, isEmergencyCall,
    595                 CallGatewayManager.EMPTY_INFO, null);
    596     }
    597 
    598     /**
    599      * Dial the number using the phone passed in.
    600      *
    601      * If the connection is establised, this method issues a sync call
    602      * that may block to query the caller info.
    603      * TODO: Change the logic to use the async query.
    604      *
    605      * @param context To perform the CallerInfo query.
    606      * @param phone the Phone object.
    607      * @param number to be dialed as requested by the user. This is
    608      * NOT the phone number to connect to. It is used only to build the
    609      * call card and to update the call log. See above for restrictions.
    610      * @param contactRef that triggered the call. Typically a 'tel:'
    611      * uri but can also be a 'content://contacts' one.
    612      * @param isEmergencyCall indicates that whether or not this is an
    613      * emergency call
    614      * @param gatewayUri Is the address used to setup the connection, null
    615      * if not using a gateway
    616      * @param callGateway Class for setting gateway data on a successful call.
    617      *
    618      * @return either CALL_STATUS_DIALED or CALL_STATUS_FAILED
    619      */
    620     public static int placeCall(Context context, Phone phone, String number, Uri contactRef,
    621             boolean isEmergencyCall, RawGatewayInfo gatewayInfo, CallGatewayManager callGateway) {
    622         final Uri gatewayUri = gatewayInfo.gatewayUri;
    623 
    624         if (VDBG) {
    625             log("placeCall()... number: '" + number + "'"
    626                     + ", GW:'" + gatewayUri + "'"
    627                     + ", contactRef:" + contactRef
    628                     + ", isEmergencyCall: " + isEmergencyCall);
    629         } else {
    630             log("placeCall()... number: " + toLogSafePhoneNumber(number)
    631                     + ", GW: " + (gatewayUri != null ? "non-null" : "null")
    632                     + ", emergency? " + isEmergencyCall);
    633         }
    634         final PhoneGlobals app = PhoneGlobals.getInstance();
    635 
    636         boolean useGateway = false;
    637         if (null != gatewayUri &&
    638             !isEmergencyCall &&
    639             PhoneUtils.isRoutableViaGateway(number)) {  // Filter out MMI, OTA and other codes.
    640             useGateway = true;
    641         }
    642 
    643         int status = CALL_STATUS_DIALED;
    644         Connection connection;
    645         String numberToDial;
    646         if (useGateway) {
    647             // TODO: 'tel' should be a constant defined in framework base
    648             // somewhere (it is in webkit.)
    649             if (null == gatewayUri || !Constants.SCHEME_TEL.equals(gatewayUri.getScheme())) {
    650                 Log.e(LOG_TAG, "Unsupported URL:" + gatewayUri);
    651                 return CALL_STATUS_FAILED;
    652             }
    653 
    654             // We can use getSchemeSpecificPart because we don't allow #
    655             // in the gateway numbers (treated a fragment delim.) However
    656             // if we allow more complex gateway numbers sequence (with
    657             // passwords or whatnot) that use #, this may break.
    658             // TODO: Need to support MMI codes.
    659             numberToDial = gatewayUri.getSchemeSpecificPart();
    660         } else {
    661             numberToDial = number;
    662         }
    663 
    664         // Remember if the phone state was in IDLE state before this call.
    665         // After calling CallManager#dial(), getState() will return different state.
    666         final boolean initiallyIdle = app.mCM.getState() == PhoneConstants.State.IDLE;
    667 
    668         try {
    669             connection = app.mCM.dial(phone, numberToDial);
    670         } catch (CallStateException ex) {
    671             // CallStateException means a new outgoing call is not currently
    672             // possible: either no more call slots exist, or there's another
    673             // call already in the process of dialing or ringing.
    674             Log.w(LOG_TAG, "Exception from app.mCM.dial()", ex);
    675             return CALL_STATUS_FAILED;
    676 
    677             // Note that it's possible for CallManager.dial() to return
    678             // null *without* throwing an exception; that indicates that
    679             // we dialed an MMI (see below).
    680         }
    681 
    682         // Now that the call is successful, we can save the gateway info for the call
    683         if (callGateway != null) {
    684             callGateway.setGatewayInfoForConnection(connection, gatewayInfo);
    685         }
    686 
    687         int phoneType = phone.getPhoneType();
    688 
    689         // On GSM phones, null is returned for MMI codes
    690         if (null == connection) {
    691             if (phoneType == PhoneConstants.PHONE_TYPE_GSM && gatewayUri == null) {
    692                 if (DBG) log("dialed MMI code: " + number);
    693                 status = CALL_STATUS_DIALED_MMI;
    694             } else {
    695                 status = CALL_STATUS_FAILED;
    696             }
    697         } else {
    698             if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
    699                 updateCdmaCallStateOnNewOutgoingCall(app, connection);
    700             }
    701 
    702             if (gatewayUri == null) {
    703                 // phone.dial() succeeded: we're now in a normal phone call.
    704                 // attach the URI to the CallerInfo Object if it is there,
    705                 // otherwise just attach the Uri Reference.
    706                 // if the uri does not have a "content" scheme, then we treat
    707                 // it as if it does NOT have a unique reference.
    708                 String content = context.getContentResolver().SCHEME_CONTENT;
    709                 if ((contactRef != null) && (contactRef.getScheme().equals(content))) {
    710                     Object userDataObject = connection.getUserData();
    711                     if (userDataObject == null) {
    712                         connection.setUserData(contactRef);
    713                     } else {
    714                         // TODO: This branch is dead code, we have
    715                         // just created the connection which has
    716                         // no user data (null) by default.
    717                         if (userDataObject instanceof CallerInfo) {
    718                         ((CallerInfo) userDataObject).contactRefUri = contactRef;
    719                         } else {
    720                         ((CallerInfoToken) userDataObject).currentInfo.contactRefUri =
    721                             contactRef;
    722                         }
    723                     }
    724                 }
    725             }
    726 
    727             startGetCallerInfo(context, connection, null, null, gatewayInfo);
    728 
    729             // Always set mute to off when we are dialing an emergency number
    730             if (isEmergencyCall) {
    731                 setMute(false);
    732             }
    733 
    734             setAudioMode();
    735 
    736             if (DBG) log("about to activate speaker");
    737             // Check is phone in any dock, and turn on speaker accordingly
    738             final boolean speakerActivated = activateSpeakerIfDocked(phone);
    739 
    740             final BluetoothManager btManager = app.getBluetoothManager();
    741 
    742             // See also similar logic in answerCall().
    743             if (initiallyIdle && !speakerActivated && isSpeakerOn(app)
    744                     && !btManager.isBluetoothHeadsetAudioOn()) {
    745                 // This is not an error but might cause users' confusion. Add log just in case.
    746                 Log.i(LOG_TAG, "Forcing speaker off when initiating a new outgoing call...");
    747                 PhoneUtils.turnOnSpeaker(app, false, true);
    748             }
    749         }
    750 
    751         return status;
    752     }
    753 
    754     /* package */ static String toLogSafePhoneNumber(String number) {
    755         // For unknown number, log empty string.
    756         if (number == null) {
    757             return "";
    758         }
    759 
    760         if (VDBG) {
    761             // When VDBG is true we emit PII.
    762             return number;
    763         }
    764 
    765         // Do exactly same thing as Uri#toSafeString() does, which will enable us to compare
    766         // sanitized phone numbers.
    767         StringBuilder builder = new StringBuilder();
    768         for (int i = 0; i < number.length(); i++) {
    769             char c = number.charAt(i);
    770             if (c == '-' || c == '@' || c == '.') {
    771                 builder.append(c);
    772             } else {
    773                 builder.append('x');
    774             }
    775         }
    776         return builder.toString();
    777     }
    778 
    779     /**
    780      * Wrapper function to control when to send an empty Flash command to the network.
    781      * Mainly needed for CDMA networks, such as scenarios when we need to send a blank flash
    782      * to the network prior to placing a 3-way call for it to be successful.
    783      */
    784     static void sendEmptyFlash(Phone phone) {
    785         if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
    786             Call fgCall = phone.getForegroundCall();
    787             if (fgCall.getState() == Call.State.ACTIVE) {
    788                 // Send the empty flash
    789                 if (DBG) Log.d(LOG_TAG, "onReceive: (CDMA) sending empty flash to network");
    790                 switchHoldingAndActive(phone.getBackgroundCall());
    791             }
    792         }
    793     }
    794 
    795     /**
    796      * @param heldCall is the background call want to be swapped
    797      */
    798     static void switchHoldingAndActive(Call heldCall) {
    799         log("switchHoldingAndActive()...");
    800         try {
    801             CallManager cm = PhoneGlobals.getInstance().mCM;
    802             if (heldCall.isIdle()) {
    803                 // no heldCall, so it is to hold active call
    804                 cm.switchHoldingAndActive(cm.getFgPhone().getBackgroundCall());
    805             } else {
    806                 // has particular heldCall, so to switch
    807                 cm.switchHoldingAndActive(heldCall);
    808             }
    809             setAudioMode(cm);
    810         } catch (CallStateException ex) {
    811             Log.w(LOG_TAG, "switchHoldingAndActive: caught " + ex, ex);
    812         }
    813     }
    814 
    815     /**
    816      * Restore the mute setting from the earliest connection of the
    817      * foreground call.
    818      */
    819     static Boolean restoreMuteState() {
    820         Phone phone = PhoneGlobals.getInstance().mCM.getFgPhone();
    821 
    822         //get the earliest connection
    823         Connection c = phone.getForegroundCall().getEarliestConnection();
    824 
    825         // only do this if connection is not null.
    826         if (c != null) {
    827 
    828             int phoneType = phone.getPhoneType();
    829 
    830             // retrieve the mute value.
    831             Boolean shouldMute = null;
    832 
    833             // In CDMA, mute is not maintained per Connection. Single mute apply for
    834             // a call where  call can have multiple connections such as
    835             // Three way and Call Waiting.  Therefore retrieving Mute state for
    836             // latest connection can apply for all connection in that call
    837             if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
    838                 shouldMute = sConnectionMuteTable.get(
    839                         phone.getForegroundCall().getLatestConnection());
    840             } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
    841                     || (phoneType == PhoneConstants.PHONE_TYPE_SIP)) {
    842                 shouldMute = sConnectionMuteTable.get(c);
    843             }
    844             if (shouldMute == null) {
    845                 if (DBG) log("problem retrieving mute value for this connection.");
    846                 shouldMute = Boolean.FALSE;
    847             }
    848 
    849             // set the mute value and return the result.
    850             setMute (shouldMute.booleanValue());
    851             return shouldMute;
    852         }
    853         return Boolean.valueOf(getMute());
    854     }
    855 
    856     static void mergeCalls() {
    857         mergeCalls(PhoneGlobals.getInstance().mCM);
    858     }
    859 
    860     static void mergeCalls(CallManager cm) {
    861         int phoneType = cm.getFgPhone().getPhoneType();
    862         if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
    863             log("mergeCalls(): CDMA...");
    864             PhoneGlobals app = PhoneGlobals.getInstance();
    865             if (app.cdmaPhoneCallState.getCurrentCallState()
    866                     == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE) {
    867                 // Set the Phone Call State to conference
    868                 app.cdmaPhoneCallState.setCurrentCallState(
    869                         CdmaPhoneCallState.PhoneCallState.CONF_CALL);
    870 
    871                 // Send flash cmd
    872                 // TODO: Need to change the call from switchHoldingAndActive to
    873                 // something meaningful as we are not actually trying to swap calls but
    874                 // instead are merging two calls by sending a Flash command.
    875                 log("- sending flash...");
    876                 switchHoldingAndActive(cm.getFirstActiveBgCall());
    877             }
    878         } else {
    879             try {
    880                 log("mergeCalls(): calling cm.conference()...");
    881                 cm.conference(cm.getFirstActiveBgCall());
    882             } catch (CallStateException ex) {
    883                 Log.w(LOG_TAG, "mergeCalls: caught " + ex, ex);
    884             }
    885         }
    886     }
    887 
    888     static void separateCall(Connection c) {
    889         try {
    890             if (DBG) log("separateCall: " + toLogSafePhoneNumber(c.getAddress()));
    891             c.separate();
    892         } catch (CallStateException ex) {
    893             Log.w(LOG_TAG, "separateCall: caught " + ex, ex);
    894         }
    895     }
    896 
    897     /**
    898      * Handle the MMIInitiate message and put up an alert that lets
    899      * the user cancel the operation, if applicable.
    900      *
    901      * @param context context to get strings.
    902      * @param mmiCode the MmiCode object being started.
    903      * @param buttonCallbackMessage message to post when button is clicked.
    904      * @param previousAlert a previous alert used in this activity.
    905      * @return the dialog handle
    906      */
    907     static Dialog displayMMIInitiate(Context context,
    908                                           MmiCode mmiCode,
    909                                           Message buttonCallbackMessage,
    910                                           Dialog previousAlert) {
    911         if (DBG) log("displayMMIInitiate: " + mmiCode);
    912         if (previousAlert != null) {
    913             previousAlert.dismiss();
    914         }
    915 
    916         // The UI paradigm we are using now requests that all dialogs have
    917         // user interaction, and that any other messages to the user should
    918         // be by way of Toasts.
    919         //
    920         // In adhering to this request, all MMI initiating "OK" dialogs
    921         // (non-cancelable MMIs) that end up being closed when the MMI
    922         // completes (thereby showing a completion dialog) are being
    923         // replaced with Toasts.
    924         //
    925         // As a side effect, moving to Toasts for the non-cancelable MMIs
    926         // also means that buttonCallbackMessage (which was tied into "OK")
    927         // is no longer invokable for these dialogs.  This is not a problem
    928         // since the only callback messages we supported were for cancelable
    929         // MMIs anyway.
    930         //
    931         // A cancelable MMI is really just a USSD request. The term
    932         // "cancelable" here means that we can cancel the request when the
    933         // system prompts us for a response, NOT while the network is
    934         // processing the MMI request.  Any request to cancel a USSD while
    935         // the network is NOT ready for a response may be ignored.
    936         //
    937         // With this in mind, we replace the cancelable alert dialog with
    938         // a progress dialog, displayed until we receive a request from
    939         // the the network.  For more information, please see the comments
    940         // in the displayMMIComplete() method below.
    941         //
    942         // Anything that is NOT a USSD request is a normal MMI request,
    943         // which will bring up a toast (desribed above).
    944 
    945         boolean isCancelable = (mmiCode != null) && mmiCode.isCancelable();
    946 
    947         if (!isCancelable) {
    948             if (DBG) log("not a USSD code, displaying status toast.");
    949             CharSequence text = context.getText(R.string.mmiStarted);
    950             Toast.makeText(context, text, Toast.LENGTH_SHORT)
    951                 .show();
    952             return null;
    953         } else {
    954             if (DBG) log("running USSD code, displaying indeterminate progress.");
    955 
    956             // create the indeterminate progress dialog and display it.
    957             ProgressDialog pd = new ProgressDialog(context);
    958             pd.setMessage(context.getText(R.string.ussdRunning));
    959             pd.setCancelable(false);
    960             pd.setIndeterminate(true);
    961             pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    962 
    963             pd.show();
    964 
    965             return pd;
    966         }
    967 
    968     }
    969 
    970     /**
    971      * Handle the MMIComplete message and fire off an intent to display
    972      * the message.
    973      *
    974      * @param context context to get strings.
    975      * @param mmiCode MMI result.
    976      * @param previousAlert a previous alert used in this activity.
    977      */
    978     static void displayMMIComplete(final Phone phone, Context context, final MmiCode mmiCode,
    979             Message dismissCallbackMessage,
    980             AlertDialog previousAlert) {
    981         final PhoneGlobals app = PhoneGlobals.getInstance();
    982         CharSequence text;
    983         int title = 0;  // title for the progress dialog, if needed.
    984         MmiCode.State state = mmiCode.getState();
    985 
    986         if (DBG) log("displayMMIComplete: state=" + state);
    987 
    988         switch (state) {
    989             case PENDING:
    990                 // USSD code asking for feedback from user.
    991                 text = mmiCode.getMessage();
    992                 if (DBG) log("- using text from PENDING MMI message: '" + text + "'");
    993                 break;
    994             case CANCELLED:
    995                 text = null;
    996                 break;
    997             case COMPLETE:
    998                 if (app.getPUKEntryActivity() != null) {
    999                     // if an attempt to unPUK the device was made, we specify
   1000                     // the title and the message here.
   1001                     title = com.android.internal.R.string.PinMmi;
   1002                     text = context.getText(R.string.puk_unlocked);
   1003                     break;
   1004                 }
   1005                 // All other conditions for the COMPLETE mmi state will cause
   1006                 // the case to fall through to message logic in common with
   1007                 // the FAILED case.
   1008 
   1009             case FAILED:
   1010                 text = mmiCode.getMessage();
   1011                 if (DBG) log("- using text from MMI message: '" + text + "'");
   1012                 break;
   1013             default:
   1014                 throw new IllegalStateException("Unexpected MmiCode state: " + state);
   1015         }
   1016 
   1017         if (previousAlert != null) {
   1018             previousAlert.dismiss();
   1019         }
   1020 
   1021         // Check to see if a UI exists for the PUK activation.  If it does
   1022         // exist, then it indicates that we're trying to unblock the PUK.
   1023         if ((app.getPUKEntryActivity() != null) && (state == MmiCode.State.COMPLETE)) {
   1024             if (DBG) log("displaying PUK unblocking progress dialog.");
   1025 
   1026             // create the progress dialog, make sure the flags and type are
   1027             // set correctly.
   1028             ProgressDialog pd = new ProgressDialog(app);
   1029             pd.setTitle(title);
   1030             pd.setMessage(text);
   1031             pd.setCancelable(false);
   1032             pd.setIndeterminate(true);
   1033             pd.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
   1034             pd.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
   1035 
   1036             // display the dialog
   1037             pd.show();
   1038 
   1039             // indicate to the Phone app that the progress dialog has
   1040             // been assigned for the PUK unlock / SIM READY process.
   1041             app.setPukEntryProgressDialog(pd);
   1042 
   1043         } else {
   1044             // In case of failure to unlock, we'll need to reset the
   1045             // PUK unlock activity, so that the user may try again.
   1046             if (app.getPUKEntryActivity() != null) {
   1047                 app.setPukEntryActivity(null);
   1048             }
   1049 
   1050             // A USSD in a pending state means that it is still
   1051             // interacting with the user.
   1052             if (state != MmiCode.State.PENDING) {
   1053                 if (DBG) log("MMI code has finished running.");
   1054 
   1055                 if (DBG) log("Extended NW displayMMIInitiate (" + text + ")");
   1056                 if (text == null || text.length() == 0)
   1057                     return;
   1058 
   1059                 // displaying system alert dialog on the screen instead of
   1060                 // using another activity to display the message.  This
   1061                 // places the message at the forefront of the UI.
   1062                 AlertDialog newDialog = new AlertDialog.Builder(context)
   1063                         .setMessage(text)
   1064                         .setPositiveButton(R.string.ok, null)
   1065                         .setCancelable(true)
   1066                         .create();
   1067 
   1068                 newDialog.getWindow().setType(
   1069                         WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
   1070                 newDialog.getWindow().addFlags(
   1071                         WindowManager.LayoutParams.FLAG_DIM_BEHIND);
   1072 
   1073                 newDialog.show();
   1074             } else {
   1075                 if (DBG) log("USSD code has requested user input. Constructing input dialog.");
   1076 
   1077                 // USSD MMI code that is interacting with the user.  The
   1078                 // basic set of steps is this:
   1079                 //   1. User enters a USSD request
   1080                 //   2. We recognize the request and displayMMIInitiate
   1081                 //      (above) creates a progress dialog.
   1082                 //   3. Request returns and we get a PENDING or COMPLETE
   1083                 //      message.
   1084                 //   4. These MMI messages are caught in the PhoneApp
   1085                 //      (onMMIComplete) and the InCallScreen
   1086                 //      (mHandler.handleMessage) which bring up this dialog
   1087                 //      and closes the original progress dialog,
   1088                 //      respectively.
   1089                 //   5. If the message is anything other than PENDING,
   1090                 //      we are done, and the alert dialog (directly above)
   1091                 //      displays the outcome.
   1092                 //   6. If the network is requesting more information from
   1093                 //      the user, the MMI will be in a PENDING state, and
   1094                 //      we display this dialog with the message.
   1095                 //   7. User input, or cancel requests result in a return
   1096                 //      to step 1.  Keep in mind that this is the only
   1097                 //      time that a USSD should be canceled.
   1098 
   1099                 // inflate the layout with the scrolling text area for the dialog.
   1100                 LayoutInflater inflater = (LayoutInflater) context.getSystemService(
   1101                         Context.LAYOUT_INFLATER_SERVICE);
   1102                 View dialogView = inflater.inflate(R.layout.dialog_ussd_response, null);
   1103 
   1104                 // get the input field.
   1105                 final EditText inputText = (EditText) dialogView.findViewById(R.id.input_field);
   1106 
   1107                 // specify the dialog's click listener, with SEND and CANCEL logic.
   1108                 final DialogInterface.OnClickListener mUSSDDialogListener =
   1109                     new DialogInterface.OnClickListener() {
   1110                         public void onClick(DialogInterface dialog, int whichButton) {
   1111                             switch (whichButton) {
   1112                                 case DialogInterface.BUTTON_POSITIVE:
   1113                                     // As per spec 24.080, valid length of ussd string
   1114                                     // is 1 - 160. If length is out of the range then
   1115                                     // display toast message & Cancel MMI operation.
   1116                                     if (inputText.length() < MIN_USSD_LEN
   1117                                             || inputText.length() > MAX_USSD_LEN) {
   1118                                         Toast.makeText(app,
   1119                                                 app.getResources().getString(R.string.enter_input,
   1120                                                 MIN_USSD_LEN, MAX_USSD_LEN),
   1121                                                 Toast.LENGTH_LONG).show();
   1122                                         if (mmiCode.isCancelable()) {
   1123                                             mmiCode.cancel();
   1124                                         }
   1125                                     } else {
   1126                                         phone.sendUssdResponse(inputText.getText().toString());
   1127                                     }
   1128                                     break;
   1129                                 case DialogInterface.BUTTON_NEGATIVE:
   1130                                     if (mmiCode.isCancelable()) {
   1131                                         mmiCode.cancel();
   1132                                     }
   1133                                     break;
   1134                             }
   1135                         }
   1136                     };
   1137 
   1138                 // build the dialog
   1139                 final AlertDialog newDialog = new AlertDialog.Builder(context)
   1140                         .setMessage(text)
   1141                         .setView(dialogView)
   1142                         .setPositiveButton(R.string.send_button, mUSSDDialogListener)
   1143                         .setNegativeButton(R.string.cancel, mUSSDDialogListener)
   1144                         .setCancelable(false)
   1145                         .create();
   1146 
   1147                 // attach the key listener to the dialog's input field and make
   1148                 // sure focus is set.
   1149                 final View.OnKeyListener mUSSDDialogInputListener =
   1150                     new View.OnKeyListener() {
   1151                         public boolean onKey(View v, int keyCode, KeyEvent event) {
   1152                             switch (keyCode) {
   1153                                 case KeyEvent.KEYCODE_CALL:
   1154                                 case KeyEvent.KEYCODE_ENTER:
   1155                                     if(event.getAction() == KeyEvent.ACTION_DOWN) {
   1156                                         phone.sendUssdResponse(inputText.getText().toString());
   1157                                         newDialog.dismiss();
   1158                                     }
   1159                                     return true;
   1160                             }
   1161                             return false;
   1162                         }
   1163                     };
   1164                 inputText.setOnKeyListener(mUSSDDialogInputListener);
   1165                 inputText.requestFocus();
   1166 
   1167                 // set the window properties of the dialog
   1168                 newDialog.getWindow().setType(
   1169                         WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);
   1170                 newDialog.getWindow().addFlags(
   1171                         WindowManager.LayoutParams.FLAG_DIM_BEHIND);
   1172 
   1173                 // now show the dialog!
   1174                 newDialog.show();
   1175             }
   1176         }
   1177     }
   1178 
   1179     /**
   1180      * Cancels the current pending MMI operation, if applicable.
   1181      * @return true if we canceled an MMI operation, or false
   1182      *         if the current pending MMI wasn't cancelable
   1183      *         or if there was no current pending MMI at all.
   1184      *
   1185      * @see displayMMIInitiate
   1186      */
   1187     static boolean cancelMmiCode(Phone phone) {
   1188         List<? extends MmiCode> pendingMmis = phone.getPendingMmiCodes();
   1189         int count = pendingMmis.size();
   1190         if (DBG) log("cancelMmiCode: num pending MMIs = " + count);
   1191 
   1192         boolean canceled = false;
   1193         if (count > 0) {
   1194             // assume that we only have one pending MMI operation active at a time.
   1195             // I don't think it's possible to enter multiple MMI codes concurrently
   1196             // in the phone UI, because during the MMI operation, an Alert panel
   1197             // is displayed, which prevents more MMI code from being entered.
   1198             MmiCode mmiCode = pendingMmis.get(0);
   1199             if (mmiCode.isCancelable()) {
   1200                 mmiCode.cancel();
   1201                 canceled = true;
   1202             }
   1203         }
   1204         return canceled;
   1205     }
   1206 
   1207     public static class VoiceMailNumberMissingException extends Exception {
   1208         VoiceMailNumberMissingException() {
   1209             super();
   1210         }
   1211 
   1212         VoiceMailNumberMissingException(String msg) {
   1213             super(msg);
   1214         }
   1215     }
   1216 
   1217     /**
   1218      * Given an Intent (which is presumably the ACTION_CALL intent that
   1219      * initiated this outgoing call), figure out the actual phone number we
   1220      * should dial.
   1221      *
   1222      * Note that the returned "number" may actually be a SIP address,
   1223      * if the specified intent contains a sip: URI.
   1224      *
   1225      * This method is basically a wrapper around PhoneUtils.getNumberFromIntent(),
   1226      * except it's also aware of the EXTRA_ACTUAL_NUMBER_TO_DIAL extra.
   1227      * (That extra, if present, tells us the exact string to pass down to the
   1228      * telephony layer.  It's guaranteed to be safe to dial: it's either a PSTN
   1229      * phone number with separators and keypad letters stripped out, or a raw
   1230      * unencoded SIP address.)
   1231      *
   1232      * @return the phone number corresponding to the specified Intent, or null
   1233      *   if the Intent has no action or if the intent's data is malformed or
   1234      *   missing.
   1235      *
   1236      * @throws VoiceMailNumberMissingException if the intent
   1237      *   contains a "voicemail" URI, but there's no voicemail
   1238      *   number configured on the device.
   1239      */
   1240     public static String getInitialNumber(Intent intent)
   1241             throws PhoneUtils.VoiceMailNumberMissingException {
   1242         if (DBG) log("getInitialNumber(): " + intent);
   1243 
   1244         String action = intent.getAction();
   1245         if (TextUtils.isEmpty(action)) {
   1246             return null;
   1247         }
   1248 
   1249         // If the EXTRA_ACTUAL_NUMBER_TO_DIAL extra is present, get the phone
   1250         // number from there.  (That extra takes precedence over the actual data
   1251         // included in the intent.)
   1252         if (intent.hasExtra(OutgoingCallBroadcaster.EXTRA_ACTUAL_NUMBER_TO_DIAL)) {
   1253             String actualNumberToDial =
   1254                     intent.getStringExtra(OutgoingCallBroadcaster.EXTRA_ACTUAL_NUMBER_TO_DIAL);
   1255             if (DBG) {
   1256                 log("==> got EXTRA_ACTUAL_NUMBER_TO_DIAL; returning '"
   1257                         + toLogSafePhoneNumber(actualNumberToDial) + "'");
   1258             }
   1259             return actualNumberToDial;
   1260         }
   1261 
   1262         return getNumberFromIntent(PhoneGlobals.getInstance(), intent);
   1263     }
   1264 
   1265     /**
   1266      * Gets the phone number to be called from an intent.  Requires a Context
   1267      * to access the contacts database, and a Phone to access the voicemail
   1268      * number.
   1269      *
   1270      * <p>If <code>phone</code> is <code>null</code>, the function will return
   1271      * <code>null</code> for <code>voicemail:</code> URIs;
   1272      * if <code>context</code> is <code>null</code>, the function will return
   1273      * <code>null</code> for person/phone URIs.</p>
   1274      *
   1275      * <p>If the intent contains a <code>sip:</code> URI, the returned
   1276      * "number" is actually the SIP address.
   1277      *
   1278      * @param context a context to use (or
   1279      * @param intent the intent
   1280      *
   1281      * @throws VoiceMailNumberMissingException if <code>intent</code> contains
   1282      *         a <code>voicemail:</code> URI, but <code>phone</code> does not
   1283      *         have a voicemail number set.
   1284      *
   1285      * @return the phone number (or SIP address) that would be called by the intent,
   1286      *         or <code>null</code> if the number cannot be found.
   1287      */
   1288     private static String getNumberFromIntent(Context context, Intent intent)
   1289             throws VoiceMailNumberMissingException {
   1290         Uri uri = intent.getData();
   1291         String scheme = uri.getScheme();
   1292 
   1293         // The sip: scheme is simple: just treat the rest of the URI as a
   1294         // SIP address.
   1295         if (Constants.SCHEME_SIP.equals(scheme)) {
   1296             return uri.getSchemeSpecificPart();
   1297         }
   1298 
   1299         // Otherwise, let PhoneNumberUtils.getNumberFromIntent() handle
   1300         // the other cases (i.e. tel: and voicemail: and contact: URIs.)
   1301 
   1302         final String number = PhoneNumberUtils.getNumberFromIntent(intent, context);
   1303 
   1304         // Check for a voicemail-dialing request.  If the voicemail number is
   1305         // empty, throw a VoiceMailNumberMissingException.
   1306         if (Constants.SCHEME_VOICEMAIL.equals(scheme) &&
   1307                 (number == null || TextUtils.isEmpty(number)))
   1308             throw new VoiceMailNumberMissingException();
   1309 
   1310         return number;
   1311     }
   1312 
   1313     /**
   1314      * Returns the caller-id info corresponding to the specified Connection.
   1315      * (This is just a simple wrapper around CallerInfo.getCallerInfo(): we
   1316      * extract a phone number from the specified Connection, and feed that
   1317      * number into CallerInfo.getCallerInfo().)
   1318      *
   1319      * The returned CallerInfo may be null in certain error cases, like if the
   1320      * specified Connection was null, or if we weren't able to get a valid
   1321      * phone number from the Connection.
   1322      *
   1323      * Finally, if the getCallerInfo() call did succeed, we save the resulting
   1324      * CallerInfo object in the "userData" field of the Connection.
   1325      *
   1326      * NOTE: This API should be avoided, with preference given to the
   1327      * asynchronous startGetCallerInfo API.
   1328      */
   1329     static CallerInfo getCallerInfo(Context context, Connection c) {
   1330         CallerInfo info = null;
   1331 
   1332         if (c != null) {
   1333             //See if there is a URI attached.  If there is, this means
   1334             //that there is no CallerInfo queried yet, so we'll need to
   1335             //replace the URI with a full CallerInfo object.
   1336             Object userDataObject = c.getUserData();
   1337             if (userDataObject instanceof Uri) {
   1338                 info = CallerInfo.getCallerInfo(context, (Uri) userDataObject);
   1339                 if (info != null) {
   1340                     c.setUserData(info);
   1341                 }
   1342             } else {
   1343                 if (userDataObject instanceof CallerInfoToken) {
   1344                     //temporary result, while query is running
   1345                     info = ((CallerInfoToken) userDataObject).currentInfo;
   1346                 } else {
   1347                     //final query result
   1348                     info = (CallerInfo) userDataObject;
   1349                 }
   1350                 if (info == null) {
   1351                     // No URI, or Existing CallerInfo, so we'll have to make do with
   1352                     // querying a new CallerInfo using the connection's phone number.
   1353                     String number = c.getAddress();
   1354 
   1355                     if (DBG) log("getCallerInfo: number = " + toLogSafePhoneNumber(number));
   1356 
   1357                     if (!TextUtils.isEmpty(number)) {
   1358                         info = CallerInfo.getCallerInfo(context, number);
   1359                         if (info != null) {
   1360                             c.setUserData(info);
   1361                         }
   1362                     }
   1363                 }
   1364             }
   1365         }
   1366         return info;
   1367     }
   1368 
   1369     /**
   1370      * Class returned by the startGetCallerInfo call to package a temporary
   1371      * CallerInfo Object, to be superceded by the CallerInfo Object passed
   1372      * into the listener when the query with token mAsyncQueryToken is complete.
   1373      */
   1374     public static class CallerInfoToken {
   1375         /**indicates that there will no longer be updates to this request.*/
   1376         public boolean isFinal;
   1377 
   1378         public CallerInfo currentInfo;
   1379         public CallerInfoAsyncQuery asyncQuery;
   1380     }
   1381 
   1382     /**
   1383      * Start a CallerInfo Query based on the earliest connection in the call.
   1384      */
   1385     static CallerInfoToken startGetCallerInfo(Context context, Call call,
   1386             CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
   1387         Connection conn = null;
   1388         int phoneType = call.getPhone().getPhoneType();
   1389         if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
   1390             conn = call.getLatestConnection();
   1391         } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
   1392                 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)) {
   1393             conn = call.getEarliestConnection();
   1394         } else {
   1395             throw new IllegalStateException("Unexpected phone type: " + phoneType);
   1396         }
   1397 
   1398         return startGetCallerInfo(context, conn, listener, cookie);
   1399     }
   1400 
   1401     static CallerInfoToken startGetCallerInfo(Context context, Connection c,
   1402             CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) {
   1403         return startGetCallerInfo(context, c, listener, cookie, null);
   1404     }
   1405 
   1406     /**
   1407      * place a temporary callerinfo object in the hands of the caller and notify
   1408      * caller when the actual query is done.
   1409      */
   1410     static CallerInfoToken startGetCallerInfo(Context context, Connection c,
   1411             CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie,
   1412             RawGatewayInfo info) {
   1413         CallerInfoToken cit;
   1414 
   1415         if (c == null) {
   1416             //TODO: perhaps throw an exception here.
   1417             cit = new CallerInfoToken();
   1418             cit.asyncQuery = null;
   1419             return cit;
   1420         }
   1421 
   1422         Object userDataObject = c.getUserData();
   1423 
   1424         // There are now 3 states for the Connection's userData object:
   1425         //
   1426         //   (1) Uri - query has not been executed yet
   1427         //
   1428         //   (2) CallerInfoToken - query is executing, but has not completed.
   1429         //
   1430         //   (3) CallerInfo - query has executed.
   1431         //
   1432         // In each case we have slightly different behaviour:
   1433         //   1. If the query has not been executed yet (Uri or null), we start
   1434         //      query execution asynchronously, and note it by attaching a
   1435         //      CallerInfoToken as the userData.
   1436         //   2. If the query is executing (CallerInfoToken), we've essentially
   1437         //      reached a state where we've received multiple requests for the
   1438         //      same callerInfo.  That means that once the query is complete,
   1439         //      we'll need to execute the additional listener requested.
   1440         //   3. If the query has already been executed (CallerInfo), we just
   1441         //      return the CallerInfo object as expected.
   1442         //   4. Regarding isFinal - there are cases where the CallerInfo object
   1443         //      will not be attached, like when the number is empty (caller id
   1444         //      blocking).  This flag is used to indicate that the
   1445         //      CallerInfoToken object is going to be permanent since no
   1446         //      query results will be returned.  In the case where a query
   1447         //      has been completed, this flag is used to indicate to the caller
   1448         //      that the data will not be updated since it is valid.
   1449         //
   1450         //      Note: For the case where a number is NOT retrievable, we leave
   1451         //      the CallerInfo as null in the CallerInfoToken.  This is
   1452         //      something of a departure from the original code, since the old
   1453         //      code manufactured a CallerInfo object regardless of the query
   1454         //      outcome.  From now on, we will append an empty CallerInfo
   1455         //      object, to mirror previous behaviour, and to avoid Null Pointer
   1456         //      Exceptions.
   1457 
   1458         if (userDataObject instanceof Uri) {
   1459             // State (1): query has not been executed yet
   1460 
   1461             //create a dummy callerinfo, populate with what we know from URI.
   1462             cit = new CallerInfoToken();
   1463             cit.currentInfo = new CallerInfo();
   1464             cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
   1465                     (Uri) userDataObject, sCallerInfoQueryListener, c);
   1466             cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
   1467             cit.isFinal = false;
   1468 
   1469             c.setUserData(cit);
   1470 
   1471             if (DBG) log("startGetCallerInfo: query based on Uri: " + userDataObject);
   1472 
   1473         } else if (userDataObject == null) {
   1474             // No URI, or Existing CallerInfo, so we'll have to make do with
   1475             // querying a new CallerInfo using the connection's phone number.
   1476             String number = c.getAddress();
   1477 
   1478             if (info != null && info != CallGatewayManager.EMPTY_INFO) {
   1479                 // Gateway number, the connection number is actually the gateway number.
   1480                 // need to lookup via dialed number.
   1481                 number = info.trueNumber;
   1482             }
   1483 
   1484             if (DBG) {
   1485                 log("PhoneUtils.startGetCallerInfo: new query for phone number...");
   1486                 log("- number (address): " + toLogSafePhoneNumber(number));
   1487                 log("- c: " + c);
   1488                 log("- phone: " + c.getCall().getPhone());
   1489                 int phoneType = c.getCall().getPhone().getPhoneType();
   1490                 log("- phoneType: " + phoneType);
   1491                 switch (phoneType) {
   1492                     case PhoneConstants.PHONE_TYPE_NONE: log("  ==> PHONE_TYPE_NONE"); break;
   1493                     case PhoneConstants.PHONE_TYPE_GSM: log("  ==> PHONE_TYPE_GSM"); break;
   1494                     case PhoneConstants.PHONE_TYPE_CDMA: log("  ==> PHONE_TYPE_CDMA"); break;
   1495                     case PhoneConstants.PHONE_TYPE_SIP: log("  ==> PHONE_TYPE_SIP"); break;
   1496                     default: log("  ==> Unknown phone type"); break;
   1497                 }
   1498             }
   1499 
   1500             cit = new CallerInfoToken();
   1501             cit.currentInfo = new CallerInfo();
   1502 
   1503             // Store CNAP information retrieved from the Connection (we want to do this
   1504             // here regardless of whether the number is empty or not).
   1505             cit.currentInfo.cnapName =  c.getCnapName();
   1506             cit.currentInfo.name = cit.currentInfo.cnapName; // This can still get overwritten
   1507                                                              // by ContactInfo later
   1508             cit.currentInfo.numberPresentation = c.getNumberPresentation();
   1509             cit.currentInfo.namePresentation = c.getCnapNamePresentation();
   1510 
   1511             if (VDBG) {
   1512                 log("startGetCallerInfo: number = " + number);
   1513                 log("startGetCallerInfo: CNAP Info from FW(1): name="
   1514                     + cit.currentInfo.cnapName
   1515                     + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
   1516             }
   1517 
   1518             // handling case where number is null (caller id hidden) as well.
   1519             if (!TextUtils.isEmpty(number)) {
   1520                 // Check for special CNAP cases and modify the CallerInfo accordingly
   1521                 // to be sure we keep the right information to display/log later
   1522                 number = modifyForSpecialCnapCases(context, cit.currentInfo, number,
   1523                         cit.currentInfo.numberPresentation);
   1524 
   1525                 cit.currentInfo.phoneNumber = number;
   1526                 // For scenarios where we may receive a valid number from the network but a
   1527                 // restricted/unavailable presentation, we do not want to perform a contact query
   1528                 // (see note on isFinal above). So we set isFinal to true here as well.
   1529                 if (cit.currentInfo.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
   1530                     cit.isFinal = true;
   1531                 } else {
   1532                     if (DBG) log("==> Actually starting CallerInfoAsyncQuery.startQuery()...");
   1533                     cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
   1534                             number, sCallerInfoQueryListener, c);
   1535                     cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
   1536                     cit.isFinal = false;
   1537                 }
   1538             } else {
   1539                 // This is the case where we are querying on a number that
   1540                 // is null or empty, like a caller whose caller id is
   1541                 // blocked or empty (CLIR).  The previous behaviour was to
   1542                 // throw a null CallerInfo object back to the user, but
   1543                 // this departure is somewhat cleaner.
   1544                 if (DBG) log("startGetCallerInfo: No query to start, send trivial reply.");
   1545                 cit.isFinal = true; // please see note on isFinal, above.
   1546             }
   1547 
   1548             c.setUserData(cit);
   1549 
   1550             if (DBG) {
   1551                 log("startGetCallerInfo: query based on number: " + toLogSafePhoneNumber(number));
   1552             }
   1553 
   1554         } else if (userDataObject instanceof CallerInfoToken) {
   1555             // State (2): query is executing, but has not completed.
   1556 
   1557             // just tack on this listener to the queue.
   1558             cit = (CallerInfoToken) userDataObject;
   1559 
   1560             // handling case where number is null (caller id hidden) as well.
   1561             if (cit.asyncQuery != null) {
   1562                 cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
   1563 
   1564                 if (DBG) log("startGetCallerInfo: query already running, adding listener: " +
   1565                         listener.getClass().toString());
   1566             } else {
   1567                 // handling case where number/name gets updated later on by the network
   1568                 String updatedNumber = c.getAddress();
   1569 
   1570                 if (info != null) {
   1571                     // Gateway number, the connection number is actually the gateway number.
   1572                     // need to lookup via dialed number.
   1573                     updatedNumber = info.trueNumber;
   1574                 }
   1575 
   1576                 if (DBG) {
   1577                     log("startGetCallerInfo: updatedNumber initially = "
   1578                             + toLogSafePhoneNumber(updatedNumber));
   1579                 }
   1580                 if (!TextUtils.isEmpty(updatedNumber)) {
   1581                     // Store CNAP information retrieved from the Connection
   1582                     cit.currentInfo.cnapName =  c.getCnapName();
   1583                     // This can still get overwritten by ContactInfo
   1584                     cit.currentInfo.name = cit.currentInfo.cnapName;
   1585                     cit.currentInfo.numberPresentation = c.getNumberPresentation();
   1586                     cit.currentInfo.namePresentation = c.getCnapNamePresentation();
   1587 
   1588                     updatedNumber = modifyForSpecialCnapCases(context, cit.currentInfo,
   1589                             updatedNumber, cit.currentInfo.numberPresentation);
   1590 
   1591                     cit.currentInfo.phoneNumber = updatedNumber;
   1592                     if (DBG) {
   1593                         log("startGetCallerInfo: updatedNumber="
   1594                                 + toLogSafePhoneNumber(updatedNumber));
   1595                     }
   1596                     if (VDBG) {
   1597                         log("startGetCallerInfo: CNAP Info from FW(2): name="
   1598                                 + cit.currentInfo.cnapName
   1599                                 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
   1600                     } else if (DBG) {
   1601                         log("startGetCallerInfo: CNAP Info from FW(2)");
   1602                     }
   1603                     // For scenarios where we may receive a valid number from the network but a
   1604                     // restricted/unavailable presentation, we do not want to perform a contact query
   1605                     // (see note on isFinal above). So we set isFinal to true here as well.
   1606                     if (cit.currentInfo.numberPresentation != PhoneConstants.PRESENTATION_ALLOWED) {
   1607                         cit.isFinal = true;
   1608                     } else {
   1609                         cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context,
   1610                                 updatedNumber, sCallerInfoQueryListener, c);
   1611                         cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie);
   1612                         cit.isFinal = false;
   1613                     }
   1614                 } else {
   1615                     if (DBG) log("startGetCallerInfo: No query to attach to, send trivial reply.");
   1616                     if (cit.currentInfo == null) {
   1617                         cit.currentInfo = new CallerInfo();
   1618                     }
   1619                     // Store CNAP information retrieved from the Connection
   1620                     cit.currentInfo.cnapName = c.getCnapName();  // This can still get
   1621                                                                  // overwritten by ContactInfo
   1622                     cit.currentInfo.name = cit.currentInfo.cnapName;
   1623                     cit.currentInfo.numberPresentation = c.getNumberPresentation();
   1624                     cit.currentInfo.namePresentation = c.getCnapNamePresentation();
   1625 
   1626                     if (VDBG) {
   1627                         log("startGetCallerInfo: CNAP Info from FW(3): name="
   1628                                 + cit.currentInfo.cnapName
   1629                                 + ", Name/Number Pres=" + cit.currentInfo.numberPresentation);
   1630                     } else if (DBG) {
   1631                         log("startGetCallerInfo: CNAP Info from FW(3)");
   1632                     }
   1633                     cit.isFinal = true; // please see note on isFinal, above.
   1634                 }
   1635             }
   1636         } else {
   1637             // State (3): query is complete.
   1638 
   1639             // The connection's userDataObject is a full-fledged
   1640             // CallerInfo instance.  Wrap it in a CallerInfoToken and
   1641             // return it to the user.
   1642 
   1643             cit = new CallerInfoToken();
   1644             cit.currentInfo = (CallerInfo) userDataObject;
   1645             cit.asyncQuery = null;
   1646             cit.isFinal = true;
   1647             // since the query is already done, call the listener.
   1648             if (DBG) log("startGetCallerInfo: query already done, returning CallerInfo");
   1649             if (DBG) log("==> cit.currentInfo = " + cit.currentInfo);
   1650         }
   1651         return cit;
   1652     }
   1653 
   1654     /**
   1655      * Static CallerInfoAsyncQuery.OnQueryCompleteListener instance that
   1656      * we use with all our CallerInfoAsyncQuery.startQuery() requests.
   1657      */
   1658     private static final int QUERY_TOKEN = -1;
   1659     static CallerInfoAsyncQuery.OnQueryCompleteListener sCallerInfoQueryListener =
   1660         new CallerInfoAsyncQuery.OnQueryCompleteListener () {
   1661             /**
   1662              * When the query completes, we stash the resulting CallerInfo
   1663              * object away in the Connection's "userData" (where it will
   1664              * later be retrieved by the in-call UI.)
   1665              */
   1666             public void onQueryComplete(int token, Object cookie, CallerInfo ci) {
   1667                 if (DBG) log("query complete, updating connection.userdata");
   1668                 Connection conn = (Connection) cookie;
   1669 
   1670                 // Added a check if CallerInfo is coming from ContactInfo or from Connection.
   1671                 // If no ContactInfo, then we want to use CNAP information coming from network
   1672                 if (DBG) log("- onQueryComplete: CallerInfo:" + ci);
   1673                 if (ci.contactExists || ci.isEmergencyNumber() || ci.isVoiceMailNumber()) {
   1674                     // If the number presentation has not been set by
   1675                     // the ContactInfo, use the one from the
   1676                     // connection.
   1677 
   1678                     // TODO: Need a new util method to merge the info
   1679                     // from the Connection in a CallerInfo object.
   1680                     // Here 'ci' is a new CallerInfo instance read
   1681                     // from the DB. It has lost all the connection
   1682                     // info preset before the query (see PhoneUtils
   1683                     // line 1334). We should have a method to merge
   1684                     // back into this new instance the info from the
   1685                     // connection object not set by the DB. If the
   1686                     // Connection already has a CallerInfo instance in
   1687                     // userData, then we could use this instance to
   1688                     // fill 'ci' in. The same routine could be used in
   1689                     // PhoneUtils.
   1690                     if (0 == ci.numberPresentation) {
   1691                         ci.numberPresentation = conn.getNumberPresentation();
   1692                     }
   1693                 } else {
   1694                     // No matching contact was found for this number.
   1695                     // Return a new CallerInfo based solely on the CNAP
   1696                     // information from the network.
   1697 
   1698                     CallerInfo newCi = getCallerInfo(null, conn);
   1699 
   1700                     // ...but copy over the (few) things we care about
   1701                     // from the original CallerInfo object:
   1702                     if (newCi != null) {
   1703                         newCi.phoneNumber = ci.phoneNumber; // To get formatted phone number
   1704                         newCi.geoDescription = ci.geoDescription; // To get geo description string
   1705                         ci = newCi;
   1706                     }
   1707                 }
   1708 
   1709                 if (DBG) log("==> Stashing CallerInfo " + ci + " into the connection...");
   1710                 conn.setUserData(ci);
   1711             }
   1712         };
   1713 
   1714 
   1715     /**
   1716      * Returns a single "name" for the specified given a CallerInfo object.
   1717      * If the name is null, return defaultString as the default value, usually
   1718      * context.getString(R.string.unknown).
   1719      */
   1720     static String getCompactNameFromCallerInfo(CallerInfo ci, Context context) {
   1721         if (DBG) log("getCompactNameFromCallerInfo: info = " + ci);
   1722 
   1723         String compactName = null;
   1724         if (ci != null) {
   1725             if (TextUtils.isEmpty(ci.name)) {
   1726                 // Perform any modifications for special CNAP cases to
   1727                 // the phone number being displayed, if applicable.
   1728                 compactName = modifyForSpecialCnapCases(context, ci, ci.phoneNumber,
   1729                                                         ci.numberPresentation);
   1730             } else {
   1731                 // Don't call modifyForSpecialCnapCases on regular name. See b/2160795.
   1732                 compactName = ci.name;
   1733             }
   1734         }
   1735 
   1736         if ((compactName == null) || (TextUtils.isEmpty(compactName))) {
   1737             // If we're still null/empty here, then check if we have a presentation
   1738             // string that takes precedence that we could return, otherwise display
   1739             // "unknown" string.
   1740             if (ci != null && ci.numberPresentation == PhoneConstants.PRESENTATION_RESTRICTED) {
   1741                 compactName = context.getString(R.string.private_num);
   1742             } else if (ci != null && ci.numberPresentation == PhoneConstants.PRESENTATION_PAYPHONE) {
   1743                 compactName = context.getString(R.string.payphone);
   1744             } else {
   1745                 compactName = context.getString(R.string.unknown);
   1746             }
   1747         }
   1748         if (VDBG) log("getCompactNameFromCallerInfo: compactName=" + compactName);
   1749         return compactName;
   1750     }
   1751 
   1752     /**
   1753      * Returns true if the specified Call is a "conference call", meaning
   1754      * that it owns more than one Connection object.  This information is
   1755      * used to trigger certain UI changes that appear when a conference
   1756      * call is active (like displaying the label "Conference call", and
   1757      * enabling the "Manage conference" UI.)
   1758      *
   1759      * Watch out: This method simply checks the number of Connections,
   1760      * *not* their states.  So if a Call has (for example) one ACTIVE
   1761      * connection and one DISCONNECTED connection, this method will return
   1762      * true (which is unintuitive, since the Call isn't *really* a
   1763      * conference call any more.)
   1764      *
   1765      * @return true if the specified call has more than one connection (in any state.)
   1766      */
   1767     static boolean isConferenceCall(Call call) {
   1768         // CDMA phones don't have the same concept of "conference call" as
   1769         // GSM phones do; there's no special "conference call" state of
   1770         // the UI or a "manage conference" function.  (Instead, when
   1771         // you're in a 3-way call, all we can do is display the "generic"
   1772         // state of the UI.)  So as far as the in-call UI is concerned,
   1773         // Conference corresponds to generic display.
   1774         final PhoneGlobals app = PhoneGlobals.getInstance();
   1775         int phoneType = call.getPhone().getPhoneType();
   1776         if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
   1777             CdmaPhoneCallState.PhoneCallState state = app.cdmaPhoneCallState.getCurrentCallState();
   1778             if ((state == CdmaPhoneCallState.PhoneCallState.CONF_CALL)
   1779                     || ((state == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE)
   1780                     && !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing())) {
   1781                 return true;
   1782             }
   1783         } else {
   1784             List<Connection> connections = call.getConnections();
   1785             if (connections != null && connections.size() > 1) {
   1786                 return true;
   1787             }
   1788         }
   1789         return false;
   1790 
   1791         // TODO: We may still want to change the semantics of this method
   1792         // to say that a given call is only really a conference call if
   1793         // the number of ACTIVE connections, not the total number of
   1794         // connections, is greater than one.  (See warning comment in the
   1795         // javadoc above.)
   1796         // Here's an implementation of that:
   1797         //        if (connections == null) {
   1798         //            return false;
   1799         //        }
   1800         //        int numActiveConnections = 0;
   1801         //        for (Connection conn : connections) {
   1802         //            if (DBG) log("  - CONN: " + conn + ", state = " + conn.getState());
   1803         //            if (conn.getState() == Call.State.ACTIVE) numActiveConnections++;
   1804         //            if (numActiveConnections > 1) {
   1805         //                return true;
   1806         //            }
   1807         //        }
   1808         //        return false;
   1809     }
   1810 
   1811     /**
   1812      * Launch the Dialer to start a new call.
   1813      * This is just a wrapper around the ACTION_DIAL intent.
   1814      */
   1815     /* package */ static boolean startNewCall(final CallManager cm) {
   1816         final PhoneGlobals app = PhoneGlobals.getInstance();
   1817 
   1818         // Sanity-check that this is OK given the current state of the phone.
   1819         if (!okToAddCall(cm)) {
   1820             Log.w(LOG_TAG, "startNewCall: can't add a new call in the current state");
   1821             dumpCallManager();
   1822             return false;
   1823         }
   1824 
   1825         Intent intent = new Intent(Intent.ACTION_DIAL);
   1826         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   1827 
   1828         // when we request the dialer come up, we also want to inform
   1829         // it that we're going through the "add call" option from the
   1830         // InCallScreen / PhoneUtils.
   1831         intent.putExtra(ADD_CALL_MODE_KEY, true);
   1832         try {
   1833             app.startActivity(intent);
   1834         } catch (ActivityNotFoundException e) {
   1835             // This is rather rare but possible.
   1836             // Note: this method is used even when the phone is encrypted. At that moment
   1837             // the system may not find any Activity which can accept this Intent.
   1838             Log.e(LOG_TAG, "Activity for adding calls isn't found.");
   1839             return false;
   1840         }
   1841 
   1842         return true;
   1843     }
   1844 
   1845     /**
   1846      * Turns on/off speaker.
   1847      *
   1848      * @param context Context
   1849      * @param flag True when speaker should be on. False otherwise.
   1850      * @param store True when the settings should be stored in the device.
   1851      */
   1852     /* package */ static void turnOnSpeaker(Context context, boolean flag, boolean store) {
   1853         if (DBG) log("turnOnSpeaker(flag=" + flag + ", store=" + store + ")...");
   1854         final PhoneGlobals app = PhoneGlobals.getInstance();
   1855 
   1856         AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
   1857         audioManager.setSpeakerphoneOn(flag);
   1858 
   1859         // record the speaker-enable value
   1860         if (store) {
   1861             sIsSpeakerEnabled = flag;
   1862         }
   1863 
   1864         // Update the status bar icon
   1865         app.notificationMgr.updateSpeakerNotification(flag);
   1866 
   1867         // We also need to make a fresh call to PhoneApp.updateWakeState()
   1868         // any time the speaker state changes, since the screen timeout is
   1869         // sometimes different depending on whether or not the speaker is
   1870         // in use.
   1871         app.updateWakeState();
   1872 
   1873         app.mCM.setEchoSuppressionEnabled(flag);
   1874     }
   1875 
   1876     /**
   1877      * Restore the speaker mode, called after a wired headset disconnect
   1878      * event.
   1879      */
   1880     static void restoreSpeakerMode(Context context) {
   1881         if (DBG) log("restoreSpeakerMode, restoring to: " + sIsSpeakerEnabled);
   1882 
   1883         // change the mode if needed.
   1884         if (isSpeakerOn(context) != sIsSpeakerEnabled) {
   1885             turnOnSpeaker(context, sIsSpeakerEnabled, false);
   1886         }
   1887     }
   1888 
   1889     static boolean isSpeakerOn(Context context) {
   1890         AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
   1891         return audioManager.isSpeakerphoneOn();
   1892     }
   1893 
   1894 
   1895     static void turnOnNoiseSuppression(Context context, boolean flag, boolean store) {
   1896         if (DBG) log("turnOnNoiseSuppression: " + flag);
   1897         AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
   1898 
   1899         if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) {
   1900             return;
   1901         }
   1902 
   1903         if (flag) {
   1904             audioManager.setParameters("noise_suppression=auto");
   1905         } else {
   1906             audioManager.setParameters("noise_suppression=off");
   1907         }
   1908 
   1909         // record the speaker-enable value
   1910         if (store) {
   1911             sIsNoiseSuppressionEnabled = flag;
   1912         }
   1913 
   1914         // TODO: implement and manage ICON
   1915 
   1916     }
   1917 
   1918     static void restoreNoiseSuppression(Context context) {
   1919         if (DBG) log("restoreNoiseSuppression, restoring to: " + sIsNoiseSuppressionEnabled);
   1920 
   1921         if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) {
   1922             return;
   1923         }
   1924 
   1925         // change the mode if needed.
   1926         if (isNoiseSuppressionOn(context) != sIsNoiseSuppressionEnabled) {
   1927             turnOnNoiseSuppression(context, sIsNoiseSuppressionEnabled, false);
   1928         }
   1929     }
   1930 
   1931     static boolean isNoiseSuppressionOn(Context context) {
   1932 
   1933         if (!context.getResources().getBoolean(R.bool.has_in_call_noise_suppression)) {
   1934             return false;
   1935         }
   1936 
   1937         AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
   1938         String noiseSuppression = audioManager.getParameters("noise_suppression");
   1939         if (DBG) log("isNoiseSuppressionOn: " + noiseSuppression);
   1940         if (noiseSuppression.contains("off")) {
   1941             return false;
   1942         } else {
   1943             return true;
   1944         }
   1945     }
   1946 
   1947     /**
   1948      *
   1949      * Mute / umute the foreground phone, which has the current foreground call
   1950      *
   1951      * All muting / unmuting from the in-call UI should go through this
   1952      * wrapper.
   1953      *
   1954      * Wrapper around Phone.setMute() and setMicrophoneMute().
   1955      * It also updates the connectionMuteTable and mute icon in the status bar.
   1956      *
   1957      */
   1958     static void setMute(boolean muted) {
   1959         CallManager cm = PhoneGlobals.getInstance().mCM;
   1960 
   1961         // Emergency calls never get muted.
   1962         if (isInEmergencyCall(cm)) {
   1963             muted = false;
   1964         }
   1965 
   1966         // make the call to mute the audio
   1967         setMuteInternal(cm.getFgPhone(), muted);
   1968 
   1969         // update the foreground connections to match.  This includes
   1970         // all the connections on conference calls.
   1971         for (Connection cn : cm.getActiveFgCall().getConnections()) {
   1972             if (sConnectionMuteTable.get(cn) == null) {
   1973                 if (DBG) log("problem retrieving mute value for this connection.");
   1974             }
   1975             sConnectionMuteTable.put(cn, Boolean.valueOf(muted));
   1976         }
   1977 
   1978         // update the background connections to match.  This includes
   1979         // all the connections on conference calls.
   1980         if (cm.hasActiveBgCall()) {
   1981             for (Connection cn : cm.getFirstActiveBgCall().getConnections()) {
   1982                 if (sConnectionMuteTable.get(cn) == null) {
   1983                     if (DBG) log("problem retrieving mute value for this connection.");
   1984                 }
   1985                 sConnectionMuteTable.put(cn, Boolean.valueOf(muted));
   1986             }
   1987         }
   1988     }
   1989 
   1990     static boolean isInEmergencyCall(CallManager cm) {
   1991         for (Connection cn : cm.getActiveFgCall().getConnections()) {
   1992             if (PhoneNumberUtils.isLocalEmergencyNumber(cn.getAddress(),
   1993                     PhoneGlobals.getInstance())) {
   1994                 return true;
   1995             }
   1996         }
   1997         return false;
   1998     }
   1999 
   2000     /**
   2001      * Internally used muting function.
   2002      */
   2003     private static void setMuteInternal(Phone phone, boolean muted) {
   2004         final PhoneGlobals app = PhoneGlobals.getInstance();
   2005         Context context = phone.getContext();
   2006         boolean routeToAudioManager =
   2007             context.getResources().getBoolean(R.bool.send_mic_mute_to_AudioManager);
   2008         if (routeToAudioManager) {
   2009             AudioManager audioManager =
   2010                 (AudioManager) phone.getContext().getSystemService(Context.AUDIO_SERVICE);
   2011             if (DBG) log("setMuteInternal: using setMicrophoneMute(" + muted + ")...");
   2012             audioManager.setMicrophoneMute(muted);
   2013         } else {
   2014             if (DBG) log("setMuteInternal: using phone.setMute(" + muted + ")...");
   2015             phone.setMute(muted);
   2016         }
   2017         app.notificationMgr.updateMuteNotification();
   2018         app.getAudioRouter().onMuteChange(muted);
   2019     }
   2020 
   2021     /**
   2022      * Get the mute state of foreground phone, which has the current
   2023      * foreground call
   2024      */
   2025     static boolean getMute() {
   2026         final PhoneGlobals app = PhoneGlobals.getInstance();
   2027 
   2028         boolean routeToAudioManager =
   2029             app.getResources().getBoolean(R.bool.send_mic_mute_to_AudioManager);
   2030         if (routeToAudioManager) {
   2031             AudioManager audioManager =
   2032                 (AudioManager) app.getSystemService(Context.AUDIO_SERVICE);
   2033             return audioManager.isMicrophoneMute();
   2034         } else {
   2035             return app.mCM.getMute();
   2036         }
   2037     }
   2038 
   2039     /* package */ static void setAudioMode() {
   2040         setAudioMode(PhoneGlobals.getInstance().mCM);
   2041     }
   2042 
   2043     /**
   2044      * Sets the audio mode per current phone state.
   2045      */
   2046     /* package */ static void setAudioMode(CallManager cm) {
   2047         if (DBG) Log.d(LOG_TAG, "setAudioMode()..." + cm.getState());
   2048 
   2049         Context context = PhoneGlobals.getInstance();
   2050         AudioManager audioManager = (AudioManager)
   2051                 context.getSystemService(Context.AUDIO_SERVICE);
   2052         int modeBefore = audioManager.getMode();
   2053         cm.setAudioMode();
   2054         int modeAfter = audioManager.getMode();
   2055 
   2056         if (modeBefore != modeAfter) {
   2057             // Enable stack dump only when actively debugging ("new Throwable()" is expensive!)
   2058             if (DBG_SETAUDIOMODE_STACK) Log.d(LOG_TAG, "Stack:", new Throwable("stack dump"));
   2059         } else {
   2060             if (DBG) Log.d(LOG_TAG, "setAudioMode() no change: "
   2061                     + audioModeToString(modeBefore));
   2062         }
   2063     }
   2064     private static String audioModeToString(int mode) {
   2065         switch (mode) {
   2066             case AudioManager.MODE_INVALID: return "MODE_INVALID";
   2067             case AudioManager.MODE_CURRENT: return "MODE_CURRENT";
   2068             case AudioManager.MODE_NORMAL: return "MODE_NORMAL";
   2069             case AudioManager.MODE_RINGTONE: return "MODE_RINGTONE";
   2070             case AudioManager.MODE_IN_CALL: return "MODE_IN_CALL";
   2071             default: return String.valueOf(mode);
   2072         }
   2073     }
   2074 
   2075     /**
   2076      * Handles the wired headset button while in-call.
   2077      *
   2078      * This is called from the PhoneApp, not from the InCallScreen,
   2079      * since the HEADSETHOOK button means "mute or unmute the current
   2080      * call" *any* time a call is active, even if the user isn't actually
   2081      * on the in-call screen.
   2082      *
   2083      * @return true if we consumed the event.
   2084      */
   2085     /* package */ static boolean handleHeadsetHook(Phone phone, KeyEvent event) {
   2086         if (DBG) log("handleHeadsetHook()..." + event.getAction() + " " + event.getRepeatCount());
   2087         final PhoneGlobals app = PhoneGlobals.getInstance();
   2088 
   2089         // If the phone is totally idle, we ignore HEADSETHOOK events
   2090         // (and instead let them fall through to the media player.)
   2091         if (phone.getState() == PhoneConstants.State.IDLE) {
   2092             return false;
   2093         }
   2094 
   2095         // Ok, the phone is in use.
   2096         // The headset button button means "Answer" if an incoming call is
   2097         // ringing.  If not, it toggles the mute / unmute state.
   2098         //
   2099         // And in any case we *always* consume this event; this means
   2100         // that the usual mediaplayer-related behavior of the headset
   2101         // button will NEVER happen while the user is on a call.
   2102 
   2103         final boolean hasRingingCall = !phone.getRingingCall().isIdle();
   2104         final boolean hasActiveCall = !phone.getForegroundCall().isIdle();
   2105         final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle();
   2106 
   2107         if (hasRingingCall &&
   2108             event.getRepeatCount() == 0 &&
   2109             event.getAction() == KeyEvent.ACTION_UP) {
   2110             // If an incoming call is ringing, answer it (just like with the
   2111             // CALL button):
   2112             int phoneType = phone.getPhoneType();
   2113             if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
   2114                 answerCall(phone.getRingingCall());
   2115             } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
   2116                     || (phoneType == PhoneConstants.PHONE_TYPE_SIP)) {
   2117                 if (hasActiveCall && hasHoldingCall) {
   2118                     if (DBG) log("handleHeadsetHook: ringing (both lines in use) ==> answer!");
   2119                     answerAndEndActive(app.mCM, phone.getRingingCall());
   2120                 } else {
   2121                     if (DBG) log("handleHeadsetHook: ringing ==> answer!");
   2122                     // answerCall() will automatically hold the current
   2123                     // active call, if there is one.
   2124                     answerCall(phone.getRingingCall());
   2125                 }
   2126             } else {
   2127                 throw new IllegalStateException("Unexpected phone type: " + phoneType);
   2128             }
   2129         } else {
   2130             // No incoming ringing call.
   2131             if (event.isLongPress()) {
   2132                 if (DBG) log("handleHeadsetHook: longpress -> hangup");
   2133                 hangup(app.mCM);
   2134             }
   2135             else if (event.getAction() == KeyEvent.ACTION_UP &&
   2136                      event.getRepeatCount() == 0) {
   2137                 Connection c = phone.getForegroundCall().getLatestConnection();
   2138                 // If it is NOT an emg #, toggle the mute state. Otherwise, ignore the hook.
   2139                 if (c != null && !PhoneNumberUtils.isLocalEmergencyNumber(c.getAddress(),
   2140                                                                           PhoneGlobals.getInstance())) {
   2141                     if (getMute()) {
   2142                         if (DBG) log("handleHeadsetHook: UNmuting...");
   2143                         setMute(false);
   2144                     } else {
   2145                         if (DBG) log("handleHeadsetHook: muting...");
   2146                         setMute(true);
   2147                     }
   2148                 }
   2149             }
   2150         }
   2151 
   2152         // Even if the InCallScreen is the current activity, there's no
   2153         // need to force it to update, because (1) if we answered a
   2154         // ringing call, the InCallScreen will imminently get a phone
   2155         // state change event (causing an update), and (2) if we muted or
   2156         // unmuted, the setMute() call automagically updates the status
   2157         // bar, and there's no "mute" indication in the InCallScreen
   2158         // itself (other than the menu item, which only ever stays
   2159         // onscreen for a second anyway.)
   2160         // TODO: (2) isn't entirely true anymore. Once we return our result
   2161         // to the PhoneApp, we ask InCallScreen to update its control widgets
   2162         // in case we changed mute or speaker state and phones with touch-
   2163         // screen [toggle] buttons need to update themselves.
   2164 
   2165         return true;
   2166     }
   2167 
   2168     /**
   2169      * Look for ANY connections on the phone that qualify as being
   2170      * disconnected.
   2171      *
   2172      * @return true if we find a connection that is disconnected over
   2173      * all the phone's call objects.
   2174      */
   2175     /* package */ static boolean hasDisconnectedConnections(Phone phone) {
   2176         return hasDisconnectedConnections(phone.getForegroundCall()) ||
   2177                 hasDisconnectedConnections(phone.getBackgroundCall()) ||
   2178                 hasDisconnectedConnections(phone.getRingingCall());
   2179     }
   2180 
   2181     /**
   2182      * Iterate over all connections in a call to see if there are any
   2183      * that are not alive (disconnected or idle).
   2184      *
   2185      * @return true if we find a connection that is disconnected, and
   2186      * pending removal via
   2187      * {@link com.android.internal.telephony.gsm.GsmCall#clearDisconnected()}.
   2188      */
   2189     private static final boolean hasDisconnectedConnections(Call call) {
   2190         // look through all connections for non-active ones.
   2191         for (Connection c : call.getConnections()) {
   2192             if (!c.isAlive()) {
   2193                 return true;
   2194             }
   2195         }
   2196         return false;
   2197     }
   2198 
   2199     //
   2200     // Misc UI policy helper functions
   2201     //
   2202 
   2203     /**
   2204      * @return true if we're allowed to hold calls, given the current
   2205      * state of the Phone.
   2206      */
   2207     /* package */ static boolean okToHoldCall(CallManager cm) {
   2208         final Call fgCall = cm.getActiveFgCall();
   2209         final boolean hasHoldingCall = cm.hasActiveBgCall();
   2210         final Call.State fgCallState = fgCall.getState();
   2211 
   2212         // The "Hold" control is disabled entirely if there's
   2213         // no way to either hold or unhold in the current state.
   2214         final boolean okToHold = (fgCallState == Call.State.ACTIVE) && !hasHoldingCall;
   2215         final boolean okToUnhold = cm.hasActiveBgCall() && (fgCallState == Call.State.IDLE);
   2216         final boolean canHold = okToHold || okToUnhold;
   2217 
   2218         return canHold;
   2219     }
   2220 
   2221     /**
   2222      * @return true if we support holding calls, given the current
   2223      * state of the Phone.
   2224      */
   2225     /* package */ static boolean okToSupportHold(CallManager cm) {
   2226         boolean supportsHold = false;
   2227 
   2228         final Call fgCall = cm.getActiveFgCall();
   2229         final boolean hasHoldingCall = cm.hasActiveBgCall();
   2230         final Call.State fgCallState = fgCall.getState();
   2231 
   2232         if (TelephonyCapabilities.supportsHoldAndUnhold(fgCall.getPhone())) {
   2233             // This phone has the concept of explicit "Hold" and "Unhold" actions.
   2234             supportsHold = true;
   2235         } else if (hasHoldingCall && (fgCallState == Call.State.IDLE)) {
   2236             // Even when foreground phone device doesn't support hold/unhold, phone devices
   2237             // for background holding calls may do.
   2238             final Call bgCall = cm.getFirstActiveBgCall();
   2239             if (bgCall != null &&
   2240                     TelephonyCapabilities.supportsHoldAndUnhold(bgCall.getPhone())) {
   2241                 supportsHold = true;
   2242             }
   2243         }
   2244         return supportsHold;
   2245     }
   2246 
   2247     /**
   2248      * @return true if we're allowed to swap calls, given the current
   2249      * state of the Phone.
   2250      */
   2251     /* package */ static boolean okToSwapCalls(CallManager cm) {
   2252         int phoneType = cm.getDefaultPhone().getPhoneType();
   2253         if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
   2254             // CDMA: "Swap" is enabled only when the phone reaches a *generic*.
   2255             // state by either accepting a Call Waiting or by merging two calls
   2256             PhoneGlobals app = PhoneGlobals.getInstance();
   2257             return (app.cdmaPhoneCallState.getCurrentCallState()
   2258                     == CdmaPhoneCallState.PhoneCallState.CONF_CALL);
   2259         } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
   2260                 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)) {
   2261             // GSM: "Swap" is available if both lines are in use and there's no
   2262             // incoming call.  (Actually we need to verify that the active
   2263             // call really is in the ACTIVE state and the holding call really
   2264             // is in the HOLDING state, since you *can't* actually swap calls
   2265             // when the foreground call is DIALING or ALERTING.)
   2266             return !cm.hasActiveRingingCall()
   2267                     && (cm.getActiveFgCall().getState() == Call.State.ACTIVE)
   2268                     && (cm.getFirstActiveBgCall().getState() == Call.State.HOLDING);
   2269         } else {
   2270             throw new IllegalStateException("Unexpected phone type: " + phoneType);
   2271         }
   2272     }
   2273 
   2274     /**
   2275      * @return true if we're allowed to merge calls, given the current
   2276      * state of the Phone.
   2277      */
   2278     /* package */ static boolean okToMergeCalls(CallManager cm) {
   2279         int phoneType = cm.getFgPhone().getPhoneType();
   2280         if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
   2281             // CDMA: "Merge" is enabled only when the user is in a 3Way call.
   2282             PhoneGlobals app = PhoneGlobals.getInstance();
   2283             return ((app.cdmaPhoneCallState.getCurrentCallState()
   2284                     == CdmaPhoneCallState.PhoneCallState.THRWAY_ACTIVE)
   2285                     && !app.cdmaPhoneCallState.IsThreeWayCallOrigStateDialing());
   2286         } else {
   2287             // GSM: "Merge" is available if both lines are in use and there's no
   2288             // incoming call, *and* the current conference isn't already
   2289             // "full".
   2290             // TODO: shall move all okToMerge logic to CallManager
   2291             return !cm.hasActiveRingingCall() && cm.hasActiveFgCall()
   2292                     && cm.hasActiveBgCall()
   2293                     && cm.canConference(cm.getFirstActiveBgCall());
   2294         }
   2295     }
   2296 
   2297     /**
   2298      * @return true if the UI should let you add a new call, given the current
   2299      * state of the Phone.
   2300      */
   2301     /* package */ static boolean okToAddCall(CallManager cm) {
   2302         Phone phone = cm.getActiveFgCall().getPhone();
   2303 
   2304         // "Add call" is never allowed in emergency callback mode (ECM).
   2305         if (isPhoneInEcm(phone)) {
   2306             return false;
   2307         }
   2308 
   2309         int phoneType = phone.getPhoneType();
   2310         final Call.State fgCallState = cm.getActiveFgCall().getState();
   2311         if (phoneType == PhoneConstants.PHONE_TYPE_CDMA) {
   2312            // CDMA: "Add call" button is only enabled when:
   2313            // - ForegroundCall is in ACTIVE state
   2314            // - After 30 seconds of user Ignoring/Missing a Call Waiting call.
   2315             PhoneGlobals app = PhoneGlobals.getInstance();
   2316             return ((fgCallState == Call.State.ACTIVE)
   2317                     && (app.cdmaPhoneCallState.getAddCallMenuStateAfterCallWaiting()));
   2318         } else if ((phoneType == PhoneConstants.PHONE_TYPE_GSM)
   2319                 || (phoneType == PhoneConstants.PHONE_TYPE_SIP)) {
   2320             // GSM: "Add call" is available only if ALL of the following are true:
   2321             // - There's no incoming ringing call
   2322             // - There's < 2 lines in use
   2323             // - The foreground call is ACTIVE or IDLE or DISCONNECTED.
   2324             //   (We mainly need to make sure it *isn't* DIALING or ALERTING.)
   2325             final boolean hasRingingCall = cm.hasActiveRingingCall();
   2326             final boolean hasActiveCall = cm.hasActiveFgCall();
   2327             final boolean hasHoldingCall = cm.hasActiveBgCall();
   2328             final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
   2329 
   2330             return !hasRingingCall
   2331                     && !allLinesTaken
   2332                     && ((fgCallState == Call.State.ACTIVE)
   2333                         || (fgCallState == Call.State.IDLE)
   2334                         || (fgCallState == Call.State.DISCONNECTED));
   2335         } else {
   2336             throw new IllegalStateException("Unexpected phone type: " + phoneType);
   2337         }
   2338     }
   2339 
   2340     /**
   2341      * Based on the input CNAP number string,
   2342      * @return _RESTRICTED or _UNKNOWN for all the special CNAP strings.
   2343      * Otherwise, return CNAP_SPECIAL_CASE_NO.
   2344      */
   2345     private static int checkCnapSpecialCases(String n) {
   2346         if (n.equals("PRIVATE") ||
   2347                 n.equals("P") ||
   2348                 n.equals("RES")) {
   2349             if (DBG) log("checkCnapSpecialCases, PRIVATE string: " + n);
   2350             return PhoneConstants.PRESENTATION_RESTRICTED;
   2351         } else if (n.equals("UNAVAILABLE") ||
   2352                 n.equals("UNKNOWN") ||
   2353                 n.equals("UNA") ||
   2354                 n.equals("U")) {
   2355             if (DBG) log("checkCnapSpecialCases, UNKNOWN string: " + n);
   2356             return PhoneConstants.PRESENTATION_UNKNOWN;
   2357         } else {
   2358             if (DBG) log("checkCnapSpecialCases, normal str. number: " + n);
   2359             return CNAP_SPECIAL_CASE_NO;
   2360         }
   2361     }
   2362 
   2363     /**
   2364      * Handles certain "corner cases" for CNAP. When we receive weird phone numbers
   2365      * from the network to indicate different number presentations, convert them to
   2366      * expected number and presentation values within the CallerInfo object.
   2367      * @param number number we use to verify if we are in a corner case
   2368      * @param presentation presentation value used to verify if we are in a corner case
   2369      * @return the new String that should be used for the phone number
   2370      */
   2371     /* package */ static String modifyForSpecialCnapCases(Context context, CallerInfo ci,
   2372             String number, int presentation) {
   2373         // Obviously we return number if ci == null, but still return number if
   2374         // number == null, because in these cases the correct string will still be
   2375         // displayed/logged after this function returns based on the presentation value.
   2376         if (ci == null || number == null) return number;
   2377 
   2378         if (DBG) {
   2379             log("modifyForSpecialCnapCases: initially, number="
   2380                     + toLogSafePhoneNumber(number)
   2381                     + ", presentation=" + presentation + " ci " + ci);
   2382         }
   2383 
   2384         // "ABSENT NUMBER" is a possible value we could get from the network as the
   2385         // phone number, so if this happens, change it to "Unknown" in the CallerInfo
   2386         // and fix the presentation to be the same.
   2387         final String[] absentNumberValues =
   2388                 context.getResources().getStringArray(R.array.absent_num);
   2389         if (Arrays.asList(absentNumberValues).contains(number)
   2390                 && presentation == PhoneConstants.PRESENTATION_ALLOWED) {
   2391             number = context.getString(R.string.unknown);
   2392             ci.numberPresentation = PhoneConstants.PRESENTATION_UNKNOWN;
   2393         }
   2394 
   2395         // Check for other special "corner cases" for CNAP and fix them similarly. Corner
   2396         // cases only apply if we received an allowed presentation from the network, so check
   2397         // if we think we have an allowed presentation, or if the CallerInfo presentation doesn't
   2398         // match the presentation passed in for verification (meaning we changed it previously
   2399         // because it's a corner case and we're being called from a different entry point).
   2400         if (ci.numberPresentation == PhoneConstants.PRESENTATION_ALLOWED
   2401                 || (ci.numberPresentation != presentation
   2402                         && presentation == PhoneConstants.PRESENTATION_ALLOWED)) {
   2403             int cnapSpecialCase = checkCnapSpecialCases(number);
   2404             if (cnapSpecialCase != CNAP_SPECIAL_CASE_NO) {
   2405                 // For all special strings, change number & numberPresentation.
   2406                 if (cnapSpecialCase == PhoneConstants.PRESENTATION_RESTRICTED) {
   2407                     number = context.getString(R.string.private_num);
   2408                 } else if (cnapSpecialCase == PhoneConstants.PRESENTATION_UNKNOWN) {
   2409                     number = context.getString(R.string.unknown);
   2410                 }
   2411                 if (DBG) {
   2412                     log("SpecialCnap: number=" + toLogSafePhoneNumber(number)
   2413                             + "; presentation now=" + cnapSpecialCase);
   2414                 }
   2415                 ci.numberPresentation = cnapSpecialCase;
   2416             }
   2417         }
   2418         if (DBG) {
   2419             log("modifyForSpecialCnapCases: returning number string="
   2420                     + toLogSafePhoneNumber(number));
   2421         }
   2422         return number;
   2423     }
   2424 
   2425     //
   2426     // Support for 3rd party phone service providers.
   2427     //
   2428 
   2429     /**
   2430      * Check if a phone number can be route through a 3rd party
   2431      * gateway. The number must be a global phone number in numerical
   2432      * form (1-800-666-SEXY won't work).
   2433      *
   2434      * MMI codes and the like cannot be used as a dial number for the
   2435      * gateway either.
   2436      *
   2437      * @param number To be dialed via a 3rd party gateway.
   2438      * @return true If the number can be routed through the 3rd party network.
   2439      */
   2440     private static boolean isRoutableViaGateway(String number) {
   2441         if (TextUtils.isEmpty(number)) {
   2442             return false;
   2443         }
   2444         number = PhoneNumberUtils.stripSeparators(number);
   2445         if (!number.equals(PhoneNumberUtils.convertKeypadLettersToDigits(number))) {
   2446             return false;
   2447         }
   2448         number = PhoneNumberUtils.extractNetworkPortion(number);
   2449         return PhoneNumberUtils.isGlobalPhoneNumber(number);
   2450     }
   2451 
   2452    /**
   2453     * This function is called when phone answers or places a call.
   2454     * Check if the phone is in a car dock or desk dock.
   2455     * If yes, turn on the speaker, when no wired or BT headsets are connected.
   2456     * Otherwise do nothing.
   2457     * @return true if activated
   2458     */
   2459     private static boolean activateSpeakerIfDocked(Phone phone) {
   2460         if (DBG) log("activateSpeakerIfDocked()...");
   2461 
   2462         boolean activated = false;
   2463         if (PhoneGlobals.mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED) {
   2464             if (DBG) log("activateSpeakerIfDocked(): In a dock -> may need to turn on speaker.");
   2465             final PhoneGlobals app = PhoneGlobals.getInstance();
   2466 
   2467             // TODO: This function should move to AudioRouter
   2468             final BluetoothManager btManager = app.getBluetoothManager();
   2469             final WiredHeadsetManager wiredHeadset = app.getWiredHeadsetManager();
   2470             final AudioRouter audioRouter = app.getAudioRouter();
   2471 
   2472             if (!wiredHeadset.isHeadsetPlugged() && !btManager.isBluetoothHeadsetAudioOn()) {
   2473                 audioRouter.setSpeaker(true);
   2474                 activated = true;
   2475             }
   2476         }
   2477         return activated;
   2478     }
   2479 
   2480 
   2481     /**
   2482      * Returns whether the phone is in ECM ("Emergency Callback Mode") or not.
   2483      */
   2484     /* package */ static boolean isPhoneInEcm(Phone phone) {
   2485         if ((phone != null) && TelephonyCapabilities.supportsEcm(phone)) {
   2486             // For phones that support ECM, return true iff PROPERTY_INECM_MODE == "true".
   2487             // TODO: There ought to be a better API for this than just
   2488             // exposing a system property all the way up to the app layer,
   2489             // probably a method like "inEcm()" provided by the telephony
   2490             // layer.
   2491             String ecmMode =
   2492                     SystemProperties.get(TelephonyProperties.PROPERTY_INECM_MODE);
   2493             if (ecmMode != null) {
   2494                 return ecmMode.equals("true");
   2495             }
   2496         }
   2497         return false;
   2498     }
   2499 
   2500     /**
   2501      * Returns the most appropriate Phone object to handle a call
   2502      * to the specified number.
   2503      *
   2504      * @param cm the CallManager.
   2505      * @param scheme the scheme from the data URI that the number originally came from.
   2506      * @param number the phone number, or SIP address.
   2507      */
   2508     public static Phone pickPhoneBasedOnNumber(CallManager cm,
   2509             String scheme, String number, String primarySipUri) {
   2510         if (DBG) {
   2511             log("pickPhoneBasedOnNumber: scheme " + scheme
   2512                     + ", number " + toLogSafePhoneNumber(number)
   2513                     + ", sipUri "
   2514                     + (primarySipUri != null ? Uri.parse(primarySipUri).toSafeString() : "null"));
   2515         }
   2516 
   2517         if (primarySipUri != null) {
   2518             Phone phone = getSipPhoneFromUri(cm, primarySipUri);
   2519             if (phone != null) return phone;
   2520         }
   2521         return cm.getDefaultPhone();
   2522     }
   2523 
   2524     public static Phone getSipPhoneFromUri(CallManager cm, String target) {
   2525         for (Phone phone : cm.getAllPhones()) {
   2526             if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_SIP) {
   2527                 String sipUri = ((SipPhone) phone).getSipUri();
   2528                 if (target.equals(sipUri)) {
   2529                     if (DBG) log("- pickPhoneBasedOnNumber:" +
   2530                             "found SipPhone! obj = " + phone + ", "
   2531                             + phone.getClass());
   2532                     return phone;
   2533                 }
   2534             }
   2535         }
   2536         return null;
   2537     }
   2538 
   2539     /**
   2540      * Returns true when the given call is in INCOMING state and there's no foreground phone call,
   2541      * meaning the call is the first real incoming call the phone is having.
   2542      */
   2543     public static boolean isRealIncomingCall(Call.State state) {
   2544         return (state == Call.State.INCOMING && !PhoneGlobals.getInstance().mCM.hasActiveFgCall());
   2545     }
   2546 
   2547     private static boolean sVoipSupported = false;
   2548     static {
   2549         PhoneGlobals app = PhoneGlobals.getInstance();
   2550         sVoipSupported = SipManager.isVoipSupported(app)
   2551                 && app.getResources().getBoolean(com.android.internal.R.bool.config_built_in_sip_phone)
   2552                 && app.getResources().getBoolean(com.android.internal.R.bool.config_voice_capable);
   2553     }
   2554 
   2555     /**
   2556      * @return true if this device supports voice calls using the built-in SIP stack.
   2557      */
   2558     static boolean isVoipSupported() {
   2559         return sVoipSupported;
   2560     }
   2561 
   2562     public static String getPresentationString(Context context, int presentation) {
   2563         String name = context.getString(R.string.unknown);
   2564         if (presentation == PhoneConstants.PRESENTATION_RESTRICTED) {
   2565             name = context.getString(R.string.private_num);
   2566         } else if (presentation == PhoneConstants.PRESENTATION_PAYPHONE) {
   2567             name = context.getString(R.string.payphone);
   2568         }
   2569         return name;
   2570     }
   2571 
   2572     public static void sendViewNotificationAsync(Context context, Uri contactUri) {
   2573         if (DBG) Log.d(LOG_TAG, "Send view notification to Contacts (uri: " + contactUri + ")");
   2574         Intent intent = new Intent("com.android.contacts.VIEW_NOTIFICATION", contactUri);
   2575         intent.setClassName("com.android.contacts",
   2576                 "com.android.contacts.ViewNotificationService");
   2577         context.startService(intent);
   2578     }
   2579 
   2580     //
   2581     // General phone and call state debugging/testing code
   2582     //
   2583 
   2584     /* package */ static void dumpCallState(Phone phone) {
   2585         PhoneGlobals app = PhoneGlobals.getInstance();
   2586         Log.d(LOG_TAG, "dumpCallState():");
   2587         Log.d(LOG_TAG, "- Phone: " + phone + ", name = " + phone.getPhoneName()
   2588               + ", state = " + phone.getState());
   2589 
   2590         StringBuilder b = new StringBuilder(128);
   2591 
   2592         Call call = phone.getForegroundCall();
   2593         b.setLength(0);
   2594         b.append("  - FG call: ").append(call.getState());
   2595         b.append(" isAlive ").append(call.getState().isAlive());
   2596         b.append(" isRinging ").append(call.getState().isRinging());
   2597         b.append(" isDialing ").append(call.getState().isDialing());
   2598         b.append(" isIdle ").append(call.isIdle());
   2599         b.append(" hasConnections ").append(call.hasConnections());
   2600         Log.d(LOG_TAG, b.toString());
   2601 
   2602         call = phone.getBackgroundCall();
   2603         b.setLength(0);
   2604         b.append("  - BG call: ").append(call.getState());
   2605         b.append(" isAlive ").append(call.getState().isAlive());
   2606         b.append(" isRinging ").append(call.getState().isRinging());
   2607         b.append(" isDialing ").append(call.getState().isDialing());
   2608         b.append(" isIdle ").append(call.isIdle());
   2609         b.append(" hasConnections ").append(call.hasConnections());
   2610         Log.d(LOG_TAG, b.toString());
   2611 
   2612         call = phone.getRingingCall();
   2613         b.setLength(0);
   2614         b.append("  - RINGING call: ").append(call.getState());
   2615         b.append(" isAlive ").append(call.getState().isAlive());
   2616         b.append(" isRinging ").append(call.getState().isRinging());
   2617         b.append(" isDialing ").append(call.getState().isDialing());
   2618         b.append(" isIdle ").append(call.isIdle());
   2619         b.append(" hasConnections ").append(call.hasConnections());
   2620         Log.d(LOG_TAG, b.toString());
   2621 
   2622 
   2623         final boolean hasRingingCall = !phone.getRingingCall().isIdle();
   2624         final boolean hasActiveCall = !phone.getForegroundCall().isIdle();
   2625         final boolean hasHoldingCall = !phone.getBackgroundCall().isIdle();
   2626         final boolean allLinesTaken = hasActiveCall && hasHoldingCall;
   2627         b.setLength(0);
   2628         b.append("  - hasRingingCall ").append(hasRingingCall);
   2629         b.append(" hasActiveCall ").append(hasActiveCall);
   2630         b.append(" hasHoldingCall ").append(hasHoldingCall);
   2631         b.append(" allLinesTaken ").append(allLinesTaken);
   2632         Log.d(LOG_TAG, b.toString());
   2633 
   2634         // On CDMA phones, dump out the CdmaPhoneCallState too:
   2635         if (phone.getPhoneType() == PhoneConstants.PHONE_TYPE_CDMA) {
   2636             if (app.cdmaPhoneCallState != null) {
   2637                 Log.d(LOG_TAG, "  - CDMA call state: "
   2638                       + app.cdmaPhoneCallState.getCurrentCallState());
   2639             } else {
   2640                 Log.d(LOG_TAG, "  - CDMA device, but null cdmaPhoneCallState!");
   2641             }
   2642         }
   2643 
   2644         // Watch out: the isRinging() call below does NOT tell us anything
   2645         // about the state of the telephony layer; it merely tells us whether
   2646         // the Ringer manager is currently playing the ringtone.
   2647         boolean ringing = app.getRinger().isRinging();
   2648         Log.d(LOG_TAG, "  - Ringer state: " + ringing);
   2649     }
   2650 
   2651     private static void log(String msg) {
   2652         Log.d(LOG_TAG, msg);
   2653     }
   2654 
   2655     static void dumpCallManager() {
   2656         Call call;
   2657         CallManager cm = PhoneGlobals.getInstance().mCM;
   2658         StringBuilder b = new StringBuilder(128);
   2659 
   2660 
   2661 
   2662         Log.d(LOG_TAG, "############### dumpCallManager() ##############");
   2663         // TODO: Don't log "cm" itself, since CallManager.toString()
   2664         // already spews out almost all this same information.
   2665         // We should fix CallManager.toString() to be more minimal, and
   2666         // use an explicit dumpState() method for the verbose dump.
   2667         // Log.d(LOG_TAG, "CallManager: " + cm
   2668         //         + ", state = " + cm.getState());
   2669         Log.d(LOG_TAG, "CallManager: state = " + cm.getState());
   2670         b.setLength(0);
   2671         call = cm.getActiveFgCall();
   2672         b.append(" - FG call: ").append(cm.hasActiveFgCall()? "YES ": "NO ");
   2673         b.append(call);
   2674         b.append( "  State: ").append(cm.getActiveFgCallState());
   2675         b.append( "  Conn: ").append(cm.getFgCallConnections());
   2676         Log.d(LOG_TAG, b.toString());
   2677         b.setLength(0);
   2678         call = cm.getFirstActiveBgCall();
   2679         b.append(" - BG call: ").append(cm.hasActiveBgCall()? "YES ": "NO ");
   2680         b.append(call);
   2681         b.append( "  State: ").append(cm.getFirstActiveBgCall().getState());
   2682         b.append( "  Conn: ").append(cm.getBgCallConnections());
   2683         Log.d(LOG_TAG, b.toString());
   2684         b.setLength(0);
   2685         call = cm.getFirstActiveRingingCall();
   2686         b.append(" - RINGING call: ").append(cm.hasActiveRingingCall()? "YES ": "NO ");
   2687         b.append(call);
   2688         b.append( "  State: ").append(cm.getFirstActiveRingingCall().getState());
   2689         Log.d(LOG_TAG, b.toString());
   2690 
   2691 
   2692 
   2693         for (Phone phone : CallManager.getInstance().getAllPhones()) {
   2694             if (phone != null) {
   2695                 Log.d(LOG_TAG, "Phone: " + phone + ", name = " + phone.getPhoneName()
   2696                         + ", state = " + phone.getState());
   2697                 b.setLength(0);
   2698                 call = phone.getForegroundCall();
   2699                 b.append(" - FG call: ").append(call);
   2700                 b.append( "  State: ").append(call.getState());
   2701                 b.append( "  Conn: ").append(call.hasConnections());
   2702                 Log.d(LOG_TAG, b.toString());
   2703                 b.setLength(0);
   2704                 call = phone.getBackgroundCall();
   2705                 b.append(" - BG call: ").append(call);
   2706                 b.append( "  State: ").append(call.getState());
   2707                 b.append( "  Conn: ").append(call.hasConnections());
   2708                 Log.d(LOG_TAG, b.toString());b.setLength(0);
   2709                 call = phone.getRingingCall();
   2710                 b.append(" - RINGING call: ").append(call);
   2711                 b.append( "  State: ").append(call.getState());
   2712                 b.append( "  Conn: ").append(call.hasConnections());
   2713                 Log.d(LOG_TAG, b.toString());
   2714             }
   2715         }
   2716 
   2717         Log.d(LOG_TAG, "############## END dumpCallManager() ###############");
   2718     }
   2719 
   2720     /**
   2721      * @return if the context is in landscape orientation.
   2722      */
   2723     public static boolean isLandscape(Context context) {
   2724         return context.getResources().getConfiguration().orientation
   2725                 == Configuration.ORIENTATION_LANDSCAPE;
   2726     }
   2727 }
   2728