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