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