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