CallsManager.java revision 6a2126477ce3f527ecaec807fe4f40cd13ff02b0
1/*
2 * Copyright (C) 2013 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.server.telecom;
18
19import android.content.Context;
20import android.net.Uri;
21import android.os.Bundle;
22import android.os.Handler;
23import android.os.Looper;
24import android.os.SystemProperties;
25import android.os.Trace;
26import android.provider.CallLog.Calls;
27import android.telecom.AudioState;
28import android.telecom.Conference;
29import android.telecom.Connection;
30import android.telecom.DisconnectCause;
31import android.telecom.GatewayInfo;
32import android.telecom.ParcelableConference;
33import android.telecom.ParcelableConnection;
34import android.telecom.PhoneAccount;
35import android.telecom.PhoneAccountHandle;
36import android.telecom.TelecomManager;
37import android.telecom.VideoProfile;
38import android.telephony.PhoneNumberUtils;
39import android.telephony.TelephonyManager;
40
41import com.android.internal.annotations.VisibleForTesting;
42import com.android.internal.telephony.PhoneConstants;
43import com.android.internal.telephony.TelephonyProperties;
44import com.android.internal.util.IndentingPrintWriter;
45
46import java.util.Collection;
47import java.util.Collections;
48import java.util.HashSet;
49import java.util.List;
50import java.util.Objects;
51import java.util.Set;
52import java.util.concurrent.ConcurrentHashMap;
53
54/**
55 * Singleton.
56 *
57 * NOTE: by design most APIs are package private, use the relevant adapter/s to allow
58 * access from other packages specifically refraining from passing the CallsManager instance
59 * beyond the com.android.server.telecom package boundary.
60 */
61@VisibleForTesting
62public class CallsManager extends Call.ListenerBase {
63
64    // TODO: Consider renaming this CallsManagerPlugin.
65    interface CallsManagerListener {
66        void onCallAdded(Call call);
67        void onCallRemoved(Call call);
68        void onCallStateChanged(Call call, int oldState, int newState);
69        void onConnectionServiceChanged(
70                Call call,
71                ConnectionServiceWrapper oldService,
72                ConnectionServiceWrapper newService);
73        void onIncomingCallAnswered(Call call);
74        void onIncomingCallRejected(Call call, boolean rejectWithMessage, String textMessage);
75        void onForegroundCallChanged(Call oldForegroundCall, Call newForegroundCall);
76        void onAudioStateChanged(AudioState oldAudioState, AudioState newAudioState);
77        void onRingbackRequested(Call call, boolean ringback);
78        void onIsConferencedChanged(Call call);
79        void onIsVoipAudioModeChanged(Call call);
80        void onVideoStateChanged(Call call);
81        void onCanAddCallChanged(boolean canAddCall);
82    }
83
84    private static final String TAG = "CallsManager";
85
86    private static final int MAXIMUM_LIVE_CALLS = 1;
87    private static final int MAXIMUM_HOLD_CALLS = 1;
88    private static final int MAXIMUM_RINGING_CALLS = 1;
89    private static final int MAXIMUM_OUTGOING_CALLS = 1;
90    private static final int MAXIMUM_TOP_LEVEL_CALLS = 2;
91
92    private static final int[] OUTGOING_CALL_STATES =
93            {CallState.CONNECTING, CallState.SELECT_PHONE_ACCOUNT, CallState.DIALING};
94
95    private static final int[] LIVE_CALL_STATES =
96            {CallState.CONNECTING, CallState.SELECT_PHONE_ACCOUNT, CallState.DIALING, CallState.ACTIVE};
97
98    /**
99     * The main call repository. Keeps an instance of all live calls. New incoming and outgoing
100     * calls are added to the map and removed when the calls move to the disconnected state.
101     *
102     * ConcurrentHashMap constructor params: 8 is initial table size, 0.9f is
103     * load factor before resizing, 1 means we only expect a single thread to
104     * access the map so make only a single shard
105     */
106    private final Set<Call> mCalls = Collections.newSetFromMap(
107            new ConcurrentHashMap<Call, Boolean>(8, 0.9f, 1));
108
109    private final ConnectionServiceRepository mConnectionServiceRepository;
110    private final DtmfLocalTonePlayer mDtmfLocalTonePlayer;
111    private final InCallController mInCallController;
112    private final CallAudioManager mCallAudioManager;
113    private RespondViaSmsManager mRespondViaSmsManager;
114    private final Ringer mRinger;
115    private final InCallWakeLockController mInCallWakeLockController;
116    // For this set initial table size to 16 because we add 13 listeners in
117    // the CallsManager constructor.
118    private final Set<CallsManagerListener> mListeners = Collections.newSetFromMap(
119            new ConcurrentHashMap<CallsManagerListener, Boolean>(16, 0.9f, 1));
120    private final HeadsetMediaButton mHeadsetMediaButton;
121    private final WiredHeadsetManager mWiredHeadsetManager;
122    private final DockManager mDockManager;
123    private final TtyManager mTtyManager;
124    private final ProximitySensorManager mProximitySensorManager;
125    private final PhoneStateBroadcaster mPhoneStateBroadcaster;
126    private final CallLogManager mCallLogManager;
127    private final Context mContext;
128    private final TelecomSystem.SyncRoot mLock;
129    private final ContactsAsyncHelper mContactsAsyncHelper;
130    private final CallerInfoAsyncQueryFactory mCallerInfoAsyncQueryFactory;
131    private final PhoneAccountRegistrar mPhoneAccountRegistrar;
132    private final MissedCallNotifier mMissedCallNotifier;
133    private final Set<Call> mLocallyDisconnectingCalls = new HashSet<>();
134    private final Set<Call> mPendingCallsToDisconnect = new HashSet<>();
135    /* Handler tied to thread in which CallManager was initialized. */
136    private final Handler mHandler = new Handler(Looper.getMainLooper());
137
138    private boolean mCanAddCall = true;
139
140    /**
141     * The call the user is currently interacting with. This is the call that should have audio
142     * focus and be visible in the in-call UI.
143     */
144    private Call mForegroundCall;
145
146    private Runnable mStopTone;
147
148    /**
149     * Initializes the required Telecom components.
150     */
151    CallsManager(
152            Context context,
153            TelecomSystem.SyncRoot lock,
154            ContactsAsyncHelper contactsAsyncHelper,
155            CallerInfoAsyncQueryFactory callerInfoAsyncQueryFactory,
156            MissedCallNotifier missedCallNotifier,
157            PhoneAccountRegistrar phoneAccountRegistrar,
158            HeadsetMediaButtonFactory headsetMediaButtonFactory,
159            ProximitySensorManagerFactory proximitySensorManagerFactory,
160            InCallWakeLockControllerFactory inCallWakeLockControllerFactory) {
161        mContext = context;
162        mLock = lock;
163        mContactsAsyncHelper = contactsAsyncHelper;
164        mCallerInfoAsyncQueryFactory = callerInfoAsyncQueryFactory;
165        mPhoneAccountRegistrar = phoneAccountRegistrar;
166        mMissedCallNotifier = missedCallNotifier;
167        StatusBarNotifier statusBarNotifier = new StatusBarNotifier(context, this);
168        mWiredHeadsetManager = new WiredHeadsetManager(context);
169        mDockManager = new DockManager(context);
170        mCallAudioManager = new CallAudioManager(
171                context, statusBarNotifier, mWiredHeadsetManager, mDockManager, this);
172        InCallTonePlayer.Factory playerFactory = new InCallTonePlayer.Factory(mCallAudioManager, lock);
173        mRinger = new Ringer(mCallAudioManager, this, playerFactory, context);
174        mHeadsetMediaButton = headsetMediaButtonFactory.create(context, this);
175        mTtyManager = new TtyManager(context, mWiredHeadsetManager);
176        mProximitySensorManager = proximitySensorManagerFactory.create(context, this);
177        mPhoneStateBroadcaster = new PhoneStateBroadcaster(this);
178        mCallLogManager = new CallLogManager(context);
179        mInCallController = new InCallController(context, mLock, this);
180        mDtmfLocalTonePlayer = new DtmfLocalTonePlayer(context);
181        mConnectionServiceRepository =
182                new ConnectionServiceRepository(mPhoneAccountRegistrar, mContext, mLock, this);
183        mInCallWakeLockController = inCallWakeLockControllerFactory.create(context, this);
184
185        mListeners.add(statusBarNotifier);
186        mListeners.add(mCallLogManager);
187        mListeners.add(mPhoneStateBroadcaster);
188        mListeners.add(mInCallController);
189        mListeners.add(mRinger);
190        mListeners.add(new RingbackPlayer(this, playerFactory));
191        mListeners.add(new InCallToneMonitor(playerFactory, this));
192        mListeners.add(mCallAudioManager);
193        mListeners.add(missedCallNotifier);
194        mListeners.add(mDtmfLocalTonePlayer);
195        mListeners.add(mHeadsetMediaButton);
196        mListeners.add(mProximitySensorManager);
197
198        mMissedCallNotifier.updateOnStartup(
199                mLock, this, mContactsAsyncHelper, mCallerInfoAsyncQueryFactory);
200    }
201
202    public void setRespondViaSmsManager(RespondViaSmsManager respondViaSmsManager) {
203        if (mRespondViaSmsManager != null) {
204            mListeners.remove(mRespondViaSmsManager);
205        }
206        mRespondViaSmsManager = respondViaSmsManager;
207        mListeners.add(respondViaSmsManager);
208    }
209
210    public RespondViaSmsManager getRespondViaSmsManager() {
211        return mRespondViaSmsManager;
212    }
213
214    @Override
215    public void onSuccessfulOutgoingCall(Call call, int callState) {
216        Log.v(this, "onSuccessfulOutgoingCall, %s", call);
217
218        setCallState(call, callState);
219        if (!mCalls.contains(call)) {
220            // Call was not added previously in startOutgoingCall due to it being a potential MMI
221            // code, so add it now.
222            addCall(call);
223        }
224
225        // The call's ConnectionService has been updated.
226        for (CallsManagerListener listener : mListeners) {
227            listener.onConnectionServiceChanged(call, null, call.getConnectionService());
228        }
229
230        markCallAsDialing(call);
231    }
232
233    @Override
234    public void onFailedOutgoingCall(Call call, DisconnectCause disconnectCause) {
235        Log.v(this, "onFailedOutgoingCall, call: %s", call);
236
237        markCallAsRemoved(call);
238    }
239
240    @Override
241    public void onSuccessfulIncomingCall(Call incomingCall) {
242        Log.d(this, "onSuccessfulIncomingCall");
243        setCallState(incomingCall, CallState.RINGING);
244
245        if (hasMaximumRingingCalls()) {
246            incomingCall.reject(false, null);
247            // since the call was not added to the list of calls, we have to call the missed
248            // call notifier and the call logger manually.
249            mMissedCallNotifier.showMissedCallNotification(incomingCall);
250            mCallLogManager.logCall(incomingCall, Calls.MISSED_TYPE);
251        } else {
252            addCall(incomingCall);
253        }
254    }
255
256    @Override
257    public void onFailedIncomingCall(Call call) {
258        setCallState(call, CallState.DISCONNECTED);
259        call.removeListener(this);
260    }
261
262    @Override
263    public void onSuccessfulUnknownCall(Call call, int callState) {
264        setCallState(call, callState);
265        Log.i(this, "onSuccessfulUnknownCall for call %s", call);
266        addCall(call);
267    }
268
269    @Override
270    public void onFailedUnknownCall(Call call) {
271        Log.i(this, "onFailedUnknownCall for call %s", call);
272        setCallState(call, CallState.DISCONNECTED);
273        call.removeListener(this);
274    }
275
276    @Override
277    public void onRingbackRequested(Call call, boolean ringback) {
278        for (CallsManagerListener listener : mListeners) {
279            listener.onRingbackRequested(call, ringback);
280        }
281    }
282
283    @Override
284    public void onPostDialWait(Call call, String remaining) {
285        mInCallController.onPostDialWait(call, remaining);
286    }
287
288    @Override
289    public void onPostDialChar(final Call call, char nextChar) {
290        if (PhoneNumberUtils.is12Key(nextChar)) {
291            // Play tone if it is one of the dialpad digits, canceling out the previously queued
292            // up stopTone runnable since playing a new tone automatically stops the previous tone.
293            if (mStopTone != null) {
294                mHandler.removeCallbacks(mStopTone);
295            }
296
297            mDtmfLocalTonePlayer.playTone(call, nextChar);
298
299            // TODO: Create a LockedRunnable class that does the synchronization automatically.
300            mStopTone = new Runnable() {
301                @Override
302                public void run() {
303                    synchronized (mLock) {
304                        // Set a timeout to stop the tone in case there isn't another tone to follow.
305                        mDtmfLocalTonePlayer.stopTone(call);
306                    }
307                }
308            };
309            mHandler.postDelayed(
310                    mStopTone,
311                    Timeouts.getDelayBetweenDtmfTonesMillis(mContext.getContentResolver()));
312        } else if (nextChar == 0 || nextChar == TelecomManager.DTMF_CHARACTER_WAIT ||
313                nextChar == TelecomManager.DTMF_CHARACTER_PAUSE) {
314            // Stop the tone if a tone is playing, removing any other stopTone callbacks since
315            // the previous tone is being stopped anyway.
316            if (mStopTone != null) {
317                mHandler.removeCallbacks(mStopTone);
318            }
319            mDtmfLocalTonePlayer.stopTone(call);
320        } else {
321            Log.w(this, "onPostDialChar: invalid value %d", nextChar);
322        }
323    }
324
325    @Override
326    public void onParentChanged(Call call) {
327        // parent-child relationship affects which call should be foreground, so do an update.
328        updateCallsManagerState();
329        for (CallsManagerListener listener : mListeners) {
330            listener.onIsConferencedChanged(call);
331        }
332    }
333
334    @Override
335    public void onChildrenChanged(Call call) {
336        // parent-child relationship affects which call should be foreground, so do an update.
337        updateCallsManagerState();
338        for (CallsManagerListener listener : mListeners) {
339            listener.onIsConferencedChanged(call);
340        }
341    }
342
343    @Override
344    public void onIsVoipAudioModeChanged(Call call) {
345        for (CallsManagerListener listener : mListeners) {
346            listener.onIsVoipAudioModeChanged(call);
347        }
348    }
349
350    @Override
351    public void onVideoStateChanged(Call call) {
352        for (CallsManagerListener listener : mListeners) {
353            listener.onVideoStateChanged(call);
354        }
355    }
356
357    @Override
358    public boolean onCanceledViaNewOutgoingCallBroadcast(final Call call) {
359        mPendingCallsToDisconnect.add(call);
360        mHandler.postDelayed(new Runnable() {
361            @Override
362            public void run() {
363                synchronized (mLock) {
364                    if (mPendingCallsToDisconnect.remove(call)) {
365                        Log.i(this, "Delayed disconnection of call: %s", call);
366                        call.disconnect();
367                    }
368                }
369            }
370        }, Timeouts.getNewOutgoingCallCancelMillis(mContext.getContentResolver()));
371
372        return true;
373    }
374
375    Collection<Call> getCalls() {
376        return Collections.unmodifiableCollection(mCalls);
377    }
378
379    Call getForegroundCall() {
380        return mForegroundCall;
381    }
382
383    Ringer getRinger() {
384        return mRinger;
385    }
386
387    InCallController getInCallController() {
388        return mInCallController;
389    }
390
391    boolean hasEmergencyCall() {
392        for (Call call : mCalls) {
393            if (call.isEmergencyCall()) {
394                return true;
395            }
396        }
397        return false;
398    }
399
400    boolean hasVideoCall() {
401        for (Call call : mCalls) {
402            if (call.getVideoState() != VideoProfile.VideoState.AUDIO_ONLY) {
403                return true;
404            }
405        }
406        return false;
407    }
408
409    AudioState getAudioState() {
410        return mCallAudioManager.getAudioState();
411    }
412
413    boolean isTtySupported() {
414        return mTtyManager.isTtySupported();
415    }
416
417    int getCurrentTtyMode() {
418        return mTtyManager.getCurrentTtyMode();
419    }
420
421    void addListener(CallsManagerListener listener) {
422        mListeners.add(listener);
423    }
424
425    void removeListener(CallsManagerListener listener) {
426        mListeners.remove(listener);
427    }
428
429    /**
430     * Starts the process to attach the call to a connection service.
431     *
432     * @param phoneAccountHandle The phone account which contains the component name of the
433     *        connection service to use for this call.
434     * @param extras The optional extras Bundle passed with the intent used for the incoming call.
435     */
436    void processIncomingCallIntent(PhoneAccountHandle phoneAccountHandle, Bundle extras) {
437        Log.d(this, "processIncomingCallIntent");
438        Uri handle = extras.getParcelable(TelephonyManager.EXTRA_INCOMING_NUMBER);
439        Call call = new Call(
440                mContext,
441                this,
442                mLock,
443                mConnectionServiceRepository,
444                mContactsAsyncHelper,
445                mCallerInfoAsyncQueryFactory,
446                handle,
447                null /* gatewayInfo */,
448                null /* connectionManagerPhoneAccount */,
449                phoneAccountHandle,
450                true /* isIncoming */,
451                false /* isConference */);
452
453        call.setExtras(extras);
454        // TODO: Move this to be a part of addCall()
455        call.addListener(this);
456        call.startCreateConnection(mPhoneAccountRegistrar);
457    }
458
459    void addNewUnknownCall(PhoneAccountHandle phoneAccountHandle, Bundle extras) {
460        Uri handle = extras.getParcelable(TelecomManager.EXTRA_UNKNOWN_CALL_HANDLE);
461        Log.i(this, "addNewUnknownCall with handle: %s", Log.pii(handle));
462        Call call = new Call(
463                mContext,
464                this,
465                mLock,
466                mConnectionServiceRepository,
467                mContactsAsyncHelper,
468                mCallerInfoAsyncQueryFactory,
469                handle,
470                null /* gatewayInfo */,
471                null /* connectionManagerPhoneAccount */,
472                phoneAccountHandle,
473                // Use onCreateIncomingConnection in TelephonyConnectionService, so that we attach
474                // to the existing connection instead of trying to create a new one.
475                true /* isIncoming */,
476                false /* isConference */);
477        call.setIsUnknown(true);
478        call.setExtras(extras);
479        call.addListener(this);
480        call.startCreateConnection(mPhoneAccountRegistrar);
481    }
482
483    private Call getNewOutgoingCall(Uri handle) {
484        // First check to see if we can reuse any of the calls that are waiting to disconnect.
485        // See {@link Call#abort} and {@link #onCanceledViaNewOutgoingCall} for more information.
486        Call reusedCall = null;
487        for (Call pendingCall : mPendingCallsToDisconnect) {
488            if (reusedCall == null && Objects.equals(pendingCall.getHandle(), handle)) {
489                mPendingCallsToDisconnect.remove(pendingCall);
490                Log.i(this, "Reusing disconnected call %s", pendingCall);
491                reusedCall = pendingCall;
492            } else {
493                pendingCall.disconnect();
494            }
495        }
496        if (reusedCall != null) {
497            return reusedCall;
498        }
499
500        // Create a call with original handle. The handle may be changed when the call is attached
501        // to a connection service, but in most cases will remain the same.
502        return new Call(
503                mContext,
504                this,
505                mLock,
506                mConnectionServiceRepository,
507                mContactsAsyncHelper,
508                mCallerInfoAsyncQueryFactory,
509                handle,
510                null /* gatewayInfo */,
511                null /* connectionManagerPhoneAccount */,
512                null /* phoneAccountHandle */,
513                false /* isIncoming */,
514                false /* isConference */);
515    }
516
517    /**
518     * Kicks off the first steps to creating an outgoing call so that InCallUI can launch.
519     *
520     * @param handle Handle to connect the call with.
521     * @param phoneAccountHandle The phone account which contains the component name of the
522     *        connection service to use for this call.
523     * @param extras The optional extras Bundle passed with the intent used for the incoming call.
524     */
525    Call startOutgoingCall(Uri handle, PhoneAccountHandle phoneAccountHandle, Bundle extras) {
526        Call call = getNewOutgoingCall(handle);
527
528        List<PhoneAccountHandle> accounts =
529                mPhoneAccountRegistrar.getCallCapablePhoneAccounts(handle.getScheme());
530
531        Log.v(this, "startOutgoingCall found accounts = " + accounts);
532
533        if (mForegroundCall != null && mForegroundCall.getTargetPhoneAccount() != null) {
534            // If there is an ongoing call, use the same phone account to place this new call.
535            phoneAccountHandle = mForegroundCall.getTargetPhoneAccount();
536        }
537
538        // Only dial with the requested phoneAccount if it is still valid. Otherwise treat this call
539        // as if a phoneAccount was not specified (does the default behavior instead).
540        // Note: We will not attempt to dial with a requested phoneAccount if it is disabled.
541        if (phoneAccountHandle != null) {
542            if (!accounts.contains(phoneAccountHandle)) {
543                phoneAccountHandle = null;
544            }
545        }
546
547        if (phoneAccountHandle == null) {
548            // No preset account, check if default exists that supports the URI scheme for the
549            // handle.
550            phoneAccountHandle =
551                    mPhoneAccountRegistrar.getOutgoingPhoneAccountForScheme(handle.getScheme());
552        }
553
554        call.setTargetPhoneAccount(phoneAccountHandle);
555
556        boolean isEmergencyCall = TelephonyUtil.shouldProcessAsEmergency(mContext,
557                call.getHandle());
558        boolean isPotentialInCallMMICode = isPotentialInCallMMICode(handle);
559
560        // Do not support any more live calls.  Our options are to move a call to hold, disconnect
561        // a call, or cancel this call altogether.
562        if (!isPotentialInCallMMICode && !makeRoomForOutgoingCall(call, isEmergencyCall)) {
563            // just cancel at this point.
564            Log.i(this, "No remaining room for outgoing call: %s", call);
565            if (mCalls.contains(call)) {
566                // This call can already exist if it is a reused call,
567                // See {@link #getNewOutgoingCall}.
568                call.disconnect();
569            }
570            return null;
571        }
572
573        boolean needsAccountSelection = phoneAccountHandle == null && accounts.size() > 1 &&
574                !isEmergencyCall;
575
576        if (needsAccountSelection) {
577            // This is the state where the user is expected to select an account
578            call.setState(CallState.SELECT_PHONE_ACCOUNT);
579            // Create our own instance to modify (since extras may be Bundle.EMPTY)
580            extras = new Bundle(extras);
581            extras.putParcelableList(android.telecom.Call.AVAILABLE_PHONE_ACCOUNTS, accounts);
582        } else {
583            call.setState(CallState.CONNECTING);
584        }
585
586        call.setExtras(extras);
587
588        // Do not add the call if it is a potential MMI code.
589        if ((isPotentialMMICode(handle) || isPotentialInCallMMICode) && !needsAccountSelection) {
590            call.addListener(this);
591        } else if (!mCalls.contains(call)) {
592            // We check if mCalls already contains the call because we could potentially be reusing
593            // a call which was previously added (See {@link #getNewOutgoingCall}).
594            addCall(call);
595        }
596
597        return call;
598    }
599
600    /**
601     * Attempts to issue/connect the specified call.
602     *
603     * @param handle Handle to connect the call with.
604     * @param gatewayInfo Optional gateway information that can be used to route the call to the
605     *        actual dialed handle via a gateway provider. May be null.
606     * @param speakerphoneOn Whether or not to turn the speakerphone on once the call connects.
607     * @param videoState The desired video state for the outgoing call.
608     */
609    void placeOutgoingCall(Call call, Uri handle, GatewayInfo gatewayInfo, boolean speakerphoneOn,
610            int videoState) {
611        if (call == null) {
612            // don't do anything if the call no longer exists
613            Log.i(this, "Canceling unknown call.");
614            return;
615        }
616
617        final Uri uriHandle = (gatewayInfo == null) ? handle : gatewayInfo.getGatewayAddress();
618
619        if (gatewayInfo == null) {
620            Log.i(this, "Creating a new outgoing call with handle: %s", Log.piiHandle(uriHandle));
621        } else {
622            Log.i(this, "Creating a new outgoing call with gateway handle: %s, original handle: %s",
623                    Log.pii(uriHandle), Log.pii(handle));
624        }
625
626        call.setHandle(uriHandle);
627        call.setGatewayInfo(gatewayInfo);
628        call.setVideoState(videoState);
629
630        if (speakerphoneOn) {
631            Log.i(this, "%s Starting with speakerphone as requested", call);
632        } else {
633            Log.i(this, "%s Starting with speakerphone because car is docked.", call);
634        }
635        call.setStartWithSpeakerphoneOn(speakerphoneOn || mDockManager.isDocked());
636
637        boolean isEmergencyCall = TelephonyUtil.shouldProcessAsEmergency(mContext,
638                call.getHandle());
639        if (isEmergencyCall) {
640            // Emergency -- CreateConnectionProcessor will choose accounts automatically
641            call.setTargetPhoneAccount(null);
642        }
643
644        if (call.getTargetPhoneAccount() != null || isEmergencyCall) {
645            // If the account has been set, proceed to place the outgoing call.
646            // Otherwise the connection will be initiated when the account is set by the user.
647            call.startCreateConnection(mPhoneAccountRegistrar);
648        }
649    }
650
651    /**
652     * Attempts to start a conference call for the specified call.
653     *
654     * @param call The call to conference.
655     * @param otherCall The other call to conference with.
656     */
657    void conference(Call call, Call otherCall) {
658        call.conferenceWith(otherCall);
659    }
660
661    /**
662     * Instructs Telecom to answer the specified call. Intended to be invoked by the in-call
663     * app through {@link InCallAdapter} after Telecom notifies it of an incoming call followed by
664     * the user opting to answer said call.
665     *
666     * @param call The call to answer.
667     * @param videoState The video state in which to answer the call.
668     */
669    void answerCall(Call call, int videoState) {
670        if (!mCalls.contains(call)) {
671            Log.i(this, "Request to answer a non-existent call %s", call);
672        } else {
673            // If the foreground call is not the ringing call and it is currently isActive() or
674            // STATE_DIALING, put it on hold before answering the call.
675            if (mForegroundCall != null && mForegroundCall != call &&
676                    (mForegroundCall.isActive() ||
677                     mForegroundCall.getState() == CallState.DIALING)) {
678                if (0 == (mForegroundCall.getConnectionCapabilities()
679                        & Connection.CAPABILITY_HOLD)) {
680                    // This call does not support hold.  If it is from a different connection
681                    // service, then disconnect it, otherwise allow the connection service to
682                    // figure out the right states.
683                    if (mForegroundCall.getConnectionService() != call.getConnectionService()) {
684                        mForegroundCall.disconnect();
685                    }
686                } else {
687                    Call heldCall = getHeldCall();
688                    if (heldCall != null) {
689                        Log.v(this, "Disconnecting held call %s before holding active call.",
690                                heldCall);
691                        heldCall.disconnect();
692                    }
693
694                    Log.v(this, "Holding active/dialing call %s before answering incoming call %s.",
695                            mForegroundCall, call);
696                    mForegroundCall.hold();
697                }
698                // TODO: Wait until we get confirmation of the active call being
699                // on-hold before answering the new call.
700                // TODO: Import logic from CallManager.acceptCall()
701            }
702
703            for (CallsManagerListener listener : mListeners) {
704                listener.onIncomingCallAnswered(call);
705            }
706
707            // We do not update the UI until we get confirmation of the answer() through
708            // {@link #markCallAsActive}.
709            call.answer(videoState);
710            if (VideoProfile.VideoState.isVideo(videoState) &&
711                !mWiredHeadsetManager.isPluggedIn() &&
712                !mCallAudioManager.isBluetoothDeviceAvailable() &&
713                isSpeakerEnabledForVideoCalls()) {
714                call.setStartWithSpeakerphoneOn(true);
715            }
716        }
717    }
718
719    private static boolean isSpeakerEnabledForVideoCalls() {
720        return (SystemProperties.getInt(TelephonyProperties.PROPERTY_VIDEOCALL_AUDIO_OUTPUT,
721                PhoneConstants.AUDIO_OUTPUT_DEFAULT) ==
722                PhoneConstants.AUDIO_OUTPUT_ENABLE_SPEAKER);
723    }
724
725    /**
726     * Instructs Telecom to reject the specified call. Intended to be invoked by the in-call
727     * app through {@link InCallAdapter} after Telecom notifies it of an incoming call followed by
728     * the user opting to reject said call.
729     */
730    void rejectCall(Call call, boolean rejectWithMessage, String textMessage) {
731        if (!mCalls.contains(call)) {
732            Log.i(this, "Request to reject a non-existent call %s", call);
733        } else {
734            for (CallsManagerListener listener : mListeners) {
735                listener.onIncomingCallRejected(call, rejectWithMessage, textMessage);
736            }
737            call.reject(rejectWithMessage, textMessage);
738        }
739    }
740
741    /**
742     * Instructs Telecom to play the specified DTMF tone within the specified call.
743     *
744     * @param digit The DTMF digit to play.
745     */
746    void playDtmfTone(Call call, char digit) {
747        if (!mCalls.contains(call)) {
748            Log.i(this, "Request to play DTMF in a non-existent call %s", call);
749        } else {
750            call.playDtmfTone(digit);
751            mDtmfLocalTonePlayer.playTone(call, digit);
752        }
753    }
754
755    /**
756     * Instructs Telecom to stop the currently playing DTMF tone, if any.
757     */
758    void stopDtmfTone(Call call) {
759        if (!mCalls.contains(call)) {
760            Log.i(this, "Request to stop DTMF in a non-existent call %s", call);
761        } else {
762            call.stopDtmfTone();
763            mDtmfLocalTonePlayer.stopTone(call);
764        }
765    }
766
767    /**
768     * Instructs Telecom to continue (or not) the current post-dial DTMF string, if any.
769     */
770    void postDialContinue(Call call, boolean proceed) {
771        if (!mCalls.contains(call)) {
772            Log.i(this, "Request to continue post-dial string in a non-existent call %s", call);
773        } else {
774            call.postDialContinue(proceed);
775        }
776    }
777
778    /**
779     * Instructs Telecom to disconnect the specified call. Intended to be invoked by the
780     * in-call app through {@link InCallAdapter} for an ongoing call. This is usually triggered by
781     * the user hitting the end-call button.
782     */
783    void disconnectCall(Call call) {
784        Log.v(this, "disconnectCall %s", call);
785
786        if (!mCalls.contains(call)) {
787            Log.w(this, "Unknown call (%s) asked to disconnect", call);
788        } else {
789            mLocallyDisconnectingCalls.add(call);
790            call.disconnect();
791        }
792    }
793
794    /**
795     * Instructs Telecom to disconnect all calls.
796     */
797    void disconnectAllCalls() {
798        Log.v(this, "disconnectAllCalls");
799
800        for (Call call : mCalls) {
801            disconnectCall(call);
802        }
803    }
804
805
806    /**
807     * Instructs Telecom to put the specified call on hold. Intended to be invoked by the
808     * in-call app through {@link InCallAdapter} for an ongoing call. This is usually triggered by
809     * the user hitting the hold button during an active call.
810     */
811    void holdCall(Call call) {
812        if (!mCalls.contains(call)) {
813            Log.w(this, "Unknown call (%s) asked to be put on hold", call);
814        } else {
815            Log.d(this, "Putting call on hold: (%s)", call);
816            call.hold();
817        }
818    }
819
820    /**
821     * Instructs Telecom to release the specified call from hold. Intended to be invoked by
822     * the in-call app through {@link InCallAdapter} for an ongoing call. This is usually triggered
823     * by the user hitting the hold button during a held call.
824     */
825    void unholdCall(Call call) {
826        if (!mCalls.contains(call)) {
827            Log.w(this, "Unknown call (%s) asked to be removed from hold", call);
828        } else {
829            Log.d(this, "unholding call: (%s)", call);
830            for (Call c : mCalls) {
831                // Only attempt to hold parent calls and not the individual children.
832                if (c != null && c.isAlive() && c != call && c.getParentCall() == null) {
833                    c.hold();
834                }
835            }
836            call.unhold();
837        }
838    }
839
840    /** Called by the in-call UI to change the mute state. */
841    void mute(boolean shouldMute) {
842        mCallAudioManager.mute(shouldMute);
843    }
844
845    /**
846      * Called by the in-call UI to change the audio route, for example to change from earpiece to
847      * speaker phone.
848      */
849    void setAudioRoute(int route) {
850        mCallAudioManager.setAudioRoute(route);
851    }
852
853    /** Called by the in-call UI to turn the proximity sensor on. */
854    void turnOnProximitySensor() {
855        mProximitySensorManager.turnOn();
856    }
857
858    /**
859     * Called by the in-call UI to turn the proximity sensor off.
860     * @param screenOnImmediately If true, the screen will be turned on immediately. Otherwise,
861     *        the screen will be kept off until the proximity sensor goes negative.
862     */
863    void turnOffProximitySensor(boolean screenOnImmediately) {
864        mProximitySensorManager.turnOff(screenOnImmediately);
865    }
866
867    void phoneAccountSelected(Call call, PhoneAccountHandle account, boolean setDefault) {
868        if (!mCalls.contains(call)) {
869            Log.i(this, "Attempted to add account to unknown call %s", call);
870        } else {
871            // TODO: There is an odd race condition here. Since NewOutgoingCallIntentBroadcaster and
872            // the SELECT_PHONE_ACCOUNT sequence run in parallel, if the user selects an account before the
873            // NEW_OUTGOING_CALL sequence finishes, we'll start the call immediately without
874            // respecting a rewritten number or a canceled number. This is unlikely since
875            // NEW_OUTGOING_CALL sequence, in practice, runs a lot faster than the user selecting
876            // a phone account from the in-call UI.
877            call.setTargetPhoneAccount(account);
878
879            // Note: emergency calls never go through account selection dialog so they never
880            // arrive here.
881            if (makeRoomForOutgoingCall(call, false /* isEmergencyCall */)) {
882                call.startCreateConnection(mPhoneAccountRegistrar);
883            } else {
884                call.disconnect();
885            }
886
887            if (setDefault) {
888                mPhoneAccountRegistrar.setUserSelectedOutgoingPhoneAccount(account);
889            }
890        }
891    }
892
893    /** Called when the audio state changes. */
894    void onAudioStateChanged(AudioState oldAudioState, AudioState newAudioState) {
895        Log.v(this, "onAudioStateChanged, audioState: %s -> %s", oldAudioState, newAudioState);
896        for (CallsManagerListener listener : mListeners) {
897            listener.onAudioStateChanged(oldAudioState, newAudioState);
898        }
899    }
900
901    void markCallAsRinging(Call call) {
902        setCallState(call, CallState.RINGING);
903    }
904
905    void markCallAsDialing(Call call) {
906        setCallState(call, CallState.DIALING);
907        maybeMoveToSpeakerPhone(call);
908    }
909
910    void markCallAsActive(Call call) {
911        setCallState(call, CallState.ACTIVE);
912        maybeMoveToSpeakerPhone(call);
913    }
914
915    void markCallAsOnHold(Call call) {
916        setCallState(call, CallState.ON_HOLD);
917    }
918
919    /**
920     * Marks the specified call as STATE_DISCONNECTED and notifies the in-call app. If this was the
921     * last live call, then also disconnect from the in-call controller.
922     *
923     * @param disconnectCause The disconnect cause, see {@link android.telecom.DisconnectCause}.
924     */
925    void markCallAsDisconnected(Call call, DisconnectCause disconnectCause) {
926        call.setDisconnectCause(disconnectCause);
927        setCallState(call, CallState.DISCONNECTED);
928    }
929
930    /**
931     * Removes an existing disconnected call, and notifies the in-call app.
932     */
933    void markCallAsRemoved(Call call) {
934        removeCall(call);
935        if (mLocallyDisconnectingCalls.contains(call)) {
936            mLocallyDisconnectingCalls.remove(call);
937            if (mForegroundCall != null && mForegroundCall.getState() == CallState.ON_HOLD) {
938                mForegroundCall.unhold();
939            }
940        }
941    }
942
943    /**
944     * Cleans up any calls currently associated with the specified connection service when the
945     * service binder disconnects unexpectedly.
946     *
947     * @param service The connection service that disconnected.
948     */
949    void handleConnectionServiceDeath(ConnectionServiceWrapper service) {
950        if (service != null) {
951            for (Call call : mCalls) {
952                if (call.getConnectionService() == service) {
953                    if (call.getState() != CallState.DISCONNECTED) {
954                        markCallAsDisconnected(call, new DisconnectCause(DisconnectCause.ERROR));
955                    }
956                    markCallAsRemoved(call);
957                }
958            }
959        }
960    }
961
962    boolean hasAnyCalls() {
963        return !mCalls.isEmpty();
964    }
965
966    boolean hasActiveOrHoldingCall() {
967        return getFirstCallWithState(CallState.ACTIVE, CallState.ON_HOLD) != null;
968    }
969
970    boolean hasRingingCall() {
971        return getFirstCallWithState(CallState.RINGING) != null;
972    }
973
974    boolean onMediaButton(int type) {
975        if (hasAnyCalls()) {
976            if (HeadsetMediaButton.SHORT_PRESS == type) {
977                Call ringingCall = getFirstCallWithState(CallState.RINGING);
978                if (ringingCall == null) {
979                    mCallAudioManager.toggleMute();
980                    return true;
981                } else {
982                    ringingCall.answer(ringingCall.getVideoState());
983                    return true;
984                }
985            } else if (HeadsetMediaButton.LONG_PRESS == type) {
986                Log.d(this, "handleHeadsetHook: longpress -> hangup");
987                Call callToHangup = getFirstCallWithState(
988                        CallState.RINGING, CallState.DIALING, CallState.ACTIVE, CallState.ON_HOLD);
989                if (callToHangup != null) {
990                    callToHangup.disconnect();
991                    return true;
992                }
993            }
994        }
995        return false;
996    }
997
998    /**
999     * Returns true if telecom supports adding another top-level call.
1000     */
1001    boolean canAddCall() {
1002        if (getFirstCallWithState(OUTGOING_CALL_STATES) != null) {
1003            return false;
1004        }
1005
1006        int count = 0;
1007        for (Call call : mCalls) {
1008            if (call.isEmergencyCall()) {
1009                // We never support add call if one of the calls is an emergency call.
1010                return false;
1011            } else if (call.getParentCall() == null) {
1012                count++;
1013            }
1014
1015            // We do not check states for canAddCall. We treat disconnected calls the same
1016            // and wait until they are removed instead. If we didn't count disconnected calls,
1017            // we could put InCallServices into a state where they are showing two calls but
1018            // also support add-call. Technically it's right, but overall looks better (UI-wise)
1019            // and acts better if we wait until the call is removed.
1020            if (count >= MAXIMUM_TOP_LEVEL_CALLS) {
1021                return false;
1022            }
1023        }
1024        return true;
1025    }
1026
1027    @VisibleForTesting
1028    public Call getRingingCall() {
1029        return getFirstCallWithState(CallState.RINGING);
1030    }
1031
1032    Call getActiveCall() {
1033        return getFirstCallWithState(CallState.ACTIVE);
1034    }
1035
1036    Call getDialingCall() {
1037        return getFirstCallWithState(CallState.DIALING);
1038    }
1039
1040    Call getHeldCall() {
1041        return getFirstCallWithState(CallState.ON_HOLD);
1042    }
1043
1044    int getNumHeldCalls() {
1045        int count = 0;
1046        for (Call call : mCalls) {
1047            if (call.getParentCall() == null && call.getState() == CallState.ON_HOLD) {
1048                count++;
1049            }
1050        }
1051        return count;
1052    }
1053
1054    Call getFirstCallWithState(int... states) {
1055        return getFirstCallWithState(null, states);
1056    }
1057
1058    /**
1059     * Returns the first call that it finds with the given states. The states are treated as having
1060     * priority order so that any call with the first state will be returned before any call with
1061     * states listed later in the parameter list.
1062     *
1063     * @param callToSkip Call that this method should skip while searching
1064     */
1065    Call getFirstCallWithState(Call callToSkip, int... states) {
1066        for (int currentState : states) {
1067            // check the foreground first
1068            if (mForegroundCall != null && mForegroundCall.getState() == currentState) {
1069                return mForegroundCall;
1070            }
1071
1072            for (Call call : mCalls) {
1073                if (Objects.equals(callToSkip, call)) {
1074                    continue;
1075                }
1076
1077                // Only operate on top-level calls
1078                if (call.getParentCall() != null) {
1079                    continue;
1080                }
1081
1082                if (currentState == call.getState()) {
1083                    return call;
1084                }
1085            }
1086        }
1087        return null;
1088    }
1089
1090    Call createConferenceCall(
1091            PhoneAccountHandle phoneAccount,
1092            ParcelableConference parcelableConference) {
1093
1094        // If the parceled conference specifies a connect time, use it; otherwise default to 0,
1095        // which is the default value for new Calls.
1096        long connectTime =
1097                parcelableConference.getConnectTimeMillis() ==
1098                        Conference.CONNECT_TIME_NOT_SPECIFIED ? 0 :
1099                        parcelableConference.getConnectTimeMillis();
1100
1101        Call call = new Call(
1102                mContext,
1103                this,
1104                mLock,
1105                mConnectionServiceRepository,
1106                mContactsAsyncHelper,
1107                mCallerInfoAsyncQueryFactory,
1108                null /* handle */,
1109                null /* gatewayInfo */,
1110                null /* connectionManagerPhoneAccount */,
1111                phoneAccount,
1112                false /* isIncoming */,
1113                true /* isConference */,
1114                connectTime);
1115
1116        setCallState(call, Call.getStateFromConnectionState(parcelableConference.getState()));
1117        call.setConnectionCapabilities(parcelableConference.getConnectionCapabilities());
1118        call.setVideoState(parcelableConference.getVideoState());
1119        call.setVideoProvider(parcelableConference.getVideoProvider());
1120        call.setStatusHints(parcelableConference.getStatusHints());
1121
1122        // TODO: Move this to be a part of addCall()
1123        call.addListener(this);
1124        addCall(call);
1125        return call;
1126    }
1127
1128    /**
1129     * @return the call state currently tracked by {@link PhoneStateBroadcaster}
1130     */
1131    int getCallState() {
1132        return mPhoneStateBroadcaster.getCallState();
1133    }
1134
1135    /**
1136     * Retrieves the {@link PhoneAccountRegistrar}.
1137     *
1138     * @return The {@link PhoneAccountRegistrar}.
1139     */
1140    PhoneAccountRegistrar getPhoneAccountRegistrar() {
1141        return mPhoneAccountRegistrar;
1142    }
1143
1144    /**
1145     * Retrieves the {@link MissedCallNotifier}
1146     * @return The {@link MissedCallNotifier}.
1147     */
1148    MissedCallNotifier getMissedCallNotifier() {
1149        return mMissedCallNotifier;
1150    }
1151
1152    /**
1153     * Adds the specified call to the main list of live calls.
1154     *
1155     * @param call The call to add.
1156     */
1157    private void addCall(Call call) {
1158        Trace.beginSection("addCall");
1159        Log.v(this, "addCall(%s)", call);
1160        call.addListener(this);
1161        mCalls.add(call);
1162
1163        // TODO: Update mForegroundCall prior to invoking
1164        // onCallAdded for calls which immediately take the foreground (like the first call).
1165        for (CallsManagerListener listener : mListeners) {
1166            if (Log.SYSTRACE_DEBUG) {
1167                Trace.beginSection(listener.getClass().toString() + " addCall");
1168            }
1169            listener.onCallAdded(call);
1170            if (Log.SYSTRACE_DEBUG) {
1171                Trace.endSection();
1172            }
1173        }
1174        updateCallsManagerState();
1175        Trace.endSection();
1176    }
1177
1178    private void removeCall(Call call) {
1179        Trace.beginSection("removeCall");
1180        Log.v(this, "removeCall(%s)", call);
1181
1182        call.setParentCall(null);  // need to clean up parent relationship before destroying.
1183        call.removeListener(this);
1184        call.clearConnectionService();
1185
1186        boolean shouldNotify = false;
1187        if (mCalls.contains(call)) {
1188            mCalls.remove(call);
1189            shouldNotify = true;
1190        }
1191
1192        call.destroy();
1193
1194        // Only broadcast changes for calls that are being tracked.
1195        if (shouldNotify) {
1196            for (CallsManagerListener listener : mListeners) {
1197                if (Log.SYSTRACE_DEBUG) {
1198                    Trace.beginSection(listener.getClass().toString() + " onCallRemoved");
1199                }
1200                listener.onCallRemoved(call);
1201                if (Log.SYSTRACE_DEBUG) {
1202                    Trace.endSection();
1203                }
1204            }
1205            updateCallsManagerState();
1206        }
1207        Trace.endSection();
1208    }
1209
1210    /**
1211     * Sets the specified state on the specified call.
1212     *
1213     * @param call The call.
1214     * @param newState The new state of the call.
1215     */
1216    private void setCallState(Call call, int newState) {
1217        if (call == null) {
1218            return;
1219        }
1220        int oldState = call.getState();
1221        Log.i(this, "setCallState %s -> %s, call: %s", CallState.toString(oldState),
1222                CallState.toString(newState), call);
1223        if (newState != oldState) {
1224            // Unfortunately, in the telephony world the radio is king. So if the call notifies
1225            // us that the call is in a particular state, we allow it even if it doesn't make
1226            // sense (e.g., STATE_ACTIVE -> STATE_RINGING).
1227            // TODO: Consider putting a stop to the above and turning CallState
1228            // into a well-defined state machine.
1229            // TODO: Define expected state transitions here, and log when an
1230            // unexpected transition occurs.
1231            call.setState(newState);
1232
1233            Trace.beginSection("onCallStateChanged");
1234            // Only broadcast state change for calls that are being tracked.
1235            if (mCalls.contains(call)) {
1236                for (CallsManagerListener listener : mListeners) {
1237                    if (Log.SYSTRACE_DEBUG) {
1238                        Trace.beginSection(listener.getClass().toString() + " onCallStateChanged");
1239                    }
1240                    listener.onCallStateChanged(call, oldState, newState);
1241                    if (Log.SYSTRACE_DEBUG) {
1242                        Trace.endSection();
1243                    }
1244                }
1245                updateCallsManagerState();
1246            }
1247            Trace.endSection();
1248        }
1249    }
1250
1251    /**
1252     * Checks which call should be visible to the user and have audio focus.
1253     */
1254    private void updateForegroundCall() {
1255        Trace.beginSection("updateForegroundCall");
1256        Call newForegroundCall = null;
1257        for (Call call : mCalls) {
1258            // TODO: Foreground-ness needs to be explicitly set. No call, regardless
1259            // of its state will be foreground by default and instead the connection service should
1260            // be notified when its calls enter and exit foreground state. Foreground will mean that
1261            // the call should play audio and listen to microphone if it wants.
1262
1263            // Only top-level calls can be in foreground
1264            if (call.getParentCall() != null) {
1265                continue;
1266            }
1267
1268            // Active calls have priority.
1269            if (call.isActive()) {
1270                newForegroundCall = call;
1271                break;
1272            }
1273
1274            if (call.isAlive() || call.getState() == CallState.RINGING) {
1275                newForegroundCall = call;
1276                // Don't break in case there's an active call that has priority.
1277            }
1278        }
1279
1280        if (newForegroundCall != mForegroundCall) {
1281            Log.v(this, "Updating foreground call, %s -> %s.", mForegroundCall, newForegroundCall);
1282            Call oldForegroundCall = mForegroundCall;
1283            mForegroundCall = newForegroundCall;
1284
1285            for (CallsManagerListener listener : mListeners) {
1286                if (Log.SYSTRACE_DEBUG) {
1287                    Trace.beginSection(listener.getClass().toString() + " updateForegroundCall");
1288                }
1289                listener.onForegroundCallChanged(oldForegroundCall, mForegroundCall);
1290                if (Log.SYSTRACE_DEBUG) {
1291                    Trace.endSection();
1292                }
1293            }
1294        }
1295        Trace.endSection();
1296    }
1297
1298    private void updateCanAddCall() {
1299        boolean newCanAddCall = canAddCall();
1300        if (newCanAddCall != mCanAddCall) {
1301            mCanAddCall = newCanAddCall;
1302            for (CallsManagerListener listener : mListeners) {
1303                if (Log.SYSTRACE_DEBUG) {
1304                    Trace.beginSection(listener.getClass().toString() + " updateCanAddCall");
1305                }
1306                listener.onCanAddCallChanged(mCanAddCall);
1307                if (Log.SYSTRACE_DEBUG) {
1308                    Trace.endSection();
1309                }
1310            }
1311        }
1312    }
1313
1314    private void updateCallsManagerState() {
1315        updateForegroundCall();
1316        updateCanAddCall();
1317    }
1318
1319    private boolean isPotentialMMICode(Uri handle) {
1320        return (handle != null && handle.getSchemeSpecificPart() != null
1321                && handle.getSchemeSpecificPart().contains("#"));
1322    }
1323
1324    /**
1325     * Determines if a dialed number is potentially an In-Call MMI code.  In-Call MMI codes are
1326     * MMI codes which can be dialed when one or more calls are in progress.
1327     * <P>
1328     * Checks for numbers formatted similar to the MMI codes defined in:
1329     * {@link com.android.internal.telephony.gsm.GSMPhone#handleInCallMmiCommands(String)}
1330     * and
1331     * {@link com.android.internal.telephony.imsphone.ImsPhone#handleInCallMmiCommands(String)}
1332     *
1333     * @param handle The URI to call.
1334     * @return {@code True} if the URI represents a number which could be an in-call MMI code.
1335     */
1336    private boolean isPotentialInCallMMICode(Uri handle) {
1337        if (handle != null && handle.getSchemeSpecificPart() != null &&
1338                handle.getScheme().equals(PhoneAccount.SCHEME_TEL)) {
1339
1340            String dialedNumber = handle.getSchemeSpecificPart();
1341            return (dialedNumber.equals("0") ||
1342                    (dialedNumber.startsWith("1") && dialedNumber.length() <= 2) ||
1343                    (dialedNumber.startsWith("2") && dialedNumber.length() <= 2) ||
1344                    dialedNumber.equals("3") ||
1345                    dialedNumber.equals("4") ||
1346                    dialedNumber.equals("5"));
1347        }
1348        return false;
1349    }
1350
1351    private int getNumCallsWithState(int... states) {
1352        int count = 0;
1353        for (int state : states) {
1354            for (Call call : mCalls) {
1355                if (call.getParentCall() == null && call.getState() == state) {
1356                    count++;
1357                }
1358            }
1359        }
1360        return count;
1361    }
1362
1363    private boolean hasMaximumLiveCalls() {
1364        return MAXIMUM_LIVE_CALLS <= getNumCallsWithState(LIVE_CALL_STATES);
1365    }
1366
1367    private boolean hasMaximumHoldingCalls() {
1368        return MAXIMUM_HOLD_CALLS <= getNumCallsWithState(CallState.ON_HOLD);
1369    }
1370
1371    private boolean hasMaximumRingingCalls() {
1372        return MAXIMUM_RINGING_CALLS <= getNumCallsWithState(CallState.RINGING);
1373    }
1374
1375    private boolean hasMaximumOutgoingCalls() {
1376        return MAXIMUM_OUTGOING_CALLS <= getNumCallsWithState(OUTGOING_CALL_STATES);
1377    }
1378
1379    private boolean makeRoomForOutgoingCall(Call call, boolean isEmergency) {
1380        if (hasMaximumLiveCalls()) {
1381            // NOTE: If the amount of live calls changes beyond 1, this logic will probably
1382            // have to change.
1383            Call liveCall = getFirstCallWithState(call, LIVE_CALL_STATES);
1384            Log.i(this, "makeRoomForOutgoingCall call = " + call + " livecall = " +
1385                   liveCall);
1386
1387            if (call == liveCall) {
1388                // If the call is already the foreground call, then we are golden.
1389                // This can happen after the user selects an account in the SELECT_PHONE_ACCOUNT
1390                // state since the call was already populated into the list.
1391                return true;
1392            }
1393
1394            if (hasMaximumOutgoingCalls()) {
1395                // Disconnect the current outgoing call if it's not an emergency call. If the user
1396                // tries to make two outgoing calls to different emergency call numbers, we will try
1397                // to connect the first outgoing call.
1398                if (isEmergency) {
1399                    Call outgoingCall = getFirstCallWithState(OUTGOING_CALL_STATES);
1400                    if (!outgoingCall.isEmergencyCall()) {
1401                        outgoingCall.disconnect();
1402                        return true;
1403                    }
1404                }
1405                return false;
1406            }
1407
1408            if (hasMaximumHoldingCalls()) {
1409                // There is no more room for any more calls, unless it's an emergency.
1410                if (isEmergency) {
1411                    // Kill the current active call, this is easier then trying to disconnect a
1412                    // holding call and hold an active call.
1413                    liveCall.disconnect();
1414                    return true;
1415                }
1416                return false;  // No more room!
1417            }
1418
1419            // We have room for at least one more holding call at this point.
1420
1421            // First thing, if we are trying to make a call with the same phone account as the live
1422            // call, then allow it so that the connection service can make its own decision about
1423            // how to handle the new call relative to the current one.
1424            if (Objects.equals(liveCall.getTargetPhoneAccount(), call.getTargetPhoneAccount())) {
1425                return true;
1426            } else if (call.getTargetPhoneAccount() == null) {
1427                // Without a phone account, we can't say reliably that the call will fail.
1428                // If the user chooses the same phone account as the live call, then it's
1429                // still possible that the call can be made (like with CDMA calls not supporting
1430                // hold but they still support adding a call by going immediately into conference
1431                // mode). Return true here and we'll run this code again after user chooses an
1432                // account.
1433                return true;
1434            }
1435
1436            // Try to hold the live call before attempting the new outgoing call.
1437            if (liveCall.can(Connection.CAPABILITY_HOLD)) {
1438                liveCall.hold();
1439                return true;
1440            }
1441
1442            // The live call cannot be held so we're out of luck here.  There's no room.
1443            return false;
1444        }
1445        return true;
1446    }
1447
1448    /**
1449     * Checks to see if the call should be on speakerphone and if so, set it.
1450     */
1451    private void maybeMoveToSpeakerPhone(Call call) {
1452        if (call.getStartWithSpeakerphoneOn()) {
1453            setAudioRoute(AudioState.ROUTE_SPEAKER);
1454            call.setStartWithSpeakerphoneOn(false);
1455        }
1456    }
1457
1458    /**
1459     * Creates a new call for an existing connection.
1460     *
1461     * @param callId The id of the new call.
1462     * @param connection The connection information.
1463     * @return The new call.
1464     */
1465    Call createCallForExistingConnection(String callId, ParcelableConnection connection) {
1466        Call call = new Call(
1467                mContext,
1468                this,
1469                mLock,
1470                mConnectionServiceRepository,
1471                mContactsAsyncHelper,
1472                mCallerInfoAsyncQueryFactory,
1473                connection.getHandle() /* handle */,
1474                null /* gatewayInfo */,
1475                null /* connectionManagerPhoneAccount */,
1476                connection.getPhoneAccount(), /* targetPhoneAccountHandle */
1477                false /* isIncoming */,
1478                false /* isConference */);
1479
1480        setCallState(call, Call.getStateFromConnectionState(connection.getState()));
1481        call.setConnectionCapabilities(connection.getConnectionCapabilities());
1482        call.setCallerDisplayName(connection.getCallerDisplayName(),
1483                connection.getCallerDisplayNamePresentation());
1484
1485        call.addListener(this);
1486        addCall(call);
1487
1488        return call;
1489    }
1490
1491    /**
1492     * Dumps the state of the {@link CallsManager}.
1493     *
1494     * @param pw The {@code IndentingPrintWriter} to write the state to.
1495     */
1496    public void dump(IndentingPrintWriter pw) {
1497        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1498        if (mCalls != null) {
1499            pw.println("mCalls: ");
1500            pw.increaseIndent();
1501            for (Call call : mCalls) {
1502                pw.println(call);
1503            }
1504            pw.decreaseIndent();
1505        }
1506        pw.println("mForegroundCall: " + (mForegroundCall == null ? "none" : mForegroundCall));
1507
1508        if (mCallAudioManager != null) {
1509            pw.println("mCallAudioManager:");
1510            pw.increaseIndent();
1511            mCallAudioManager.dump(pw);
1512            pw.decreaseIndent();
1513        }
1514
1515        if (mTtyManager != null) {
1516            pw.println("mTtyManager:");
1517            pw.increaseIndent();
1518            mTtyManager.dump(pw);
1519            pw.decreaseIndent();
1520        }
1521
1522        if (mInCallController != null) {
1523            pw.println("mInCallController:");
1524            pw.increaseIndent();
1525            mInCallController.dump(pw);
1526            pw.decreaseIndent();
1527        }
1528
1529        if (mConnectionServiceRepository != null) {
1530            pw.println("mConnectionServiceRepository:");
1531            pw.increaseIndent();
1532            mConnectionServiceRepository.dump(pw);
1533            pw.decreaseIndent();
1534        }
1535    }
1536}
1537