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