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