GsmCdmaConnection.java revision 005d0cc72ff800bc3ea66bf97b0c95acc0322e70
1/*
2 * Copyright (C) 2015 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.internal.telephony;
18import android.content.Context;
19import android.os.AsyncResult;
20import android.os.Handler;
21import android.os.Looper;
22import android.os.Message;
23import android.os.PersistableBundle;
24import android.os.PowerManager;
25import android.os.Registrant;
26import android.os.SystemClock;
27import android.telephony.CarrierConfigManager;
28import android.telephony.DisconnectCause;
29import android.telephony.PhoneNumberUtils;
30import android.telephony.Rlog;
31import android.telephony.ServiceState;
32import android.text.TextUtils;
33
34import com.android.internal.telephony.cdma.CdmaCallWaitingNotification;
35import com.android.internal.telephony.cdma.CdmaSubscriptionSourceManager;
36import com.android.internal.telephony.uicc.IccCardApplicationStatus.AppState;
37import com.android.internal.telephony.uicc.UiccCardApplication;
38
39/**
40 * {@hide}
41 */
42public class GsmCdmaConnection extends Connection {
43    private static final String LOG_TAG = "GsmCdmaConnection";
44    private static final boolean DBG = true;
45    private static final boolean VDBG = false;
46
47    //***** Instance Variables
48
49    GsmCdmaCallTracker mOwner;
50    GsmCdmaCall mParent;
51
52    boolean mDisconnected;
53
54    int mIndex;          // index in GsmCdmaCallTracker.connections[], -1 if unassigned
55                        // The GsmCdma index is 1 + this
56
57    /*
58     * These time/timespan values are based on System.currentTimeMillis(),
59     * i.e., "wall clock" time.
60     */
61    long mDisconnectTime;
62
63    UUSInfo mUusInfo;
64    int mPreciseCause = 0;
65    String mVendorCause;
66
67    Connection mOrigConnection;
68
69    Handler mHandler;
70
71    private PowerManager.WakeLock mPartialWakeLock;
72
73    private boolean mIsEmergencyCall = false;
74
75    // The cached delay to be used between DTMF tones fetched from carrier config.
76    private int mDtmfToneDelay = 0;
77
78    //***** Event Constants
79    static final int EVENT_DTMF_DONE = 1;
80    static final int EVENT_PAUSE_DONE = 2;
81    static final int EVENT_NEXT_POST_DIAL = 3;
82    static final int EVENT_WAKE_LOCK_TIMEOUT = 4;
83    static final int EVENT_DTMF_DELAY_DONE = 5;
84
85    //***** Constants
86    static final int PAUSE_DELAY_MILLIS_GSM = 3 * 1000;
87    static final int PAUSE_DELAY_MILLIS_CDMA = 2 * 1000;
88    static final int WAKE_LOCK_TIMEOUT_MILLIS = 60*1000;
89
90    //***** Inner Classes
91
92    class MyHandler extends Handler {
93        MyHandler(Looper l) {super(l);}
94
95        @Override
96        public void
97        handleMessage(Message msg) {
98
99            switch (msg.what) {
100                case EVENT_NEXT_POST_DIAL:
101                case EVENT_DTMF_DELAY_DONE:
102                case EVENT_PAUSE_DONE:
103                    processNextPostDialChar();
104                    break;
105                case EVENT_WAKE_LOCK_TIMEOUT:
106                    releaseWakeLock();
107                    break;
108                case EVENT_DTMF_DONE:
109                    // We may need to add a delay specified by carrier between DTMF tones that are
110                    // sent out.
111                    mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_DTMF_DELAY_DONE),
112                            mDtmfToneDelay);
113                    break;
114            }
115        }
116    }
117
118    //***** Constructors
119
120    /** This is probably an MT call that we first saw in a CLCC response or a hand over. */
121    public GsmCdmaConnection (GsmCdmaPhone phone, DriverCall dc, GsmCdmaCallTracker ct, int index) {
122        super(phone.getPhoneType());
123        createWakeLock(phone.getContext());
124        acquireWakeLock();
125
126        mOwner = ct;
127        mHandler = new MyHandler(mOwner.getLooper());
128
129        mAddress = dc.number;
130        mIsEmergencyCall = PhoneNumberUtils.isLocalEmergencyNumber(phone.getContext(), mAddress);
131        mIsIncoming = dc.isMT;
132        mCreateTime = System.currentTimeMillis();
133        mCnapName = dc.name;
134        mCnapNamePresentation = dc.namePresentation;
135        mNumberPresentation = dc.numberPresentation;
136        mUusInfo = dc.uusInfo;
137
138        mIndex = index;
139
140        mParent = parentFromDCState(dc.state);
141        mParent.attach(this, dc);
142
143        fetchDtmfToneDelay(phone);
144    }
145
146    /** This is an MO call, created when dialing */
147    public GsmCdmaConnection (GsmCdmaPhone phone, String dialString, GsmCdmaCallTracker ct,
148                              GsmCdmaCall parent, boolean isEmergencyCall) {
149        super(phone.getPhoneType());
150        createWakeLock(phone.getContext());
151        acquireWakeLock();
152
153        mOwner = ct;
154        mHandler = new MyHandler(mOwner.getLooper());
155
156        if (isPhoneTypeGsm()) {
157            mDialString = dialString;
158        } else {
159            Rlog.d(LOG_TAG, "[GsmCdmaConn] GsmCdmaConnection: dialString=" +
160                    maskDialString(dialString));
161            dialString = formatDialString(dialString);
162            Rlog.d(LOG_TAG,
163                    "[GsmCdmaConn] GsmCdmaConnection:formated dialString=" +
164                            maskDialString(dialString));
165        }
166
167        mAddress = PhoneNumberUtils.extractNetworkPortionAlt(dialString);
168        mIsEmergencyCall = isEmergencyCall;
169        mPostDialString = PhoneNumberUtils.extractPostDialPortion(dialString);
170
171        mIndex = -1;
172
173        mIsIncoming = false;
174        mCnapName = null;
175        mCnapNamePresentation = PhoneConstants.PRESENTATION_ALLOWED;
176        mNumberPresentation = PhoneConstants.PRESENTATION_ALLOWED;
177        mCreateTime = System.currentTimeMillis();
178
179        if (parent != null) {
180            mParent = parent;
181            if (isPhoneTypeGsm()) {
182                parent.attachFake(this, GsmCdmaCall.State.DIALING);
183            } else {
184                //for the three way call case, not change parent state
185                if (parent.mState == GsmCdmaCall.State.ACTIVE) {
186                    parent.attachFake(this, GsmCdmaCall.State.ACTIVE);
187                } else {
188                    parent.attachFake(this, GsmCdmaCall.State.DIALING);
189                }
190
191            }
192        }
193
194        fetchDtmfToneDelay(phone);
195    }
196
197    //CDMA
198    /** This is a Call waiting call*/
199    public GsmCdmaConnection(Context context, CdmaCallWaitingNotification cw, GsmCdmaCallTracker ct,
200                             GsmCdmaCall parent) {
201        super(parent.getPhone().getPhoneType());
202        createWakeLock(context);
203        acquireWakeLock();
204
205        mOwner = ct;
206        mHandler = new MyHandler(mOwner.getLooper());
207        mAddress = cw.number;
208        mNumberPresentation = cw.numberPresentation;
209        mCnapName = cw.name;
210        mCnapNamePresentation = cw.namePresentation;
211        mIndex = -1;
212        mIsIncoming = true;
213        mCreateTime = System.currentTimeMillis();
214        mConnectTime = 0;
215        mParent = parent;
216        parent.attachFake(this, GsmCdmaCall.State.WAITING);
217    }
218
219
220    public void dispose() {
221        clearPostDialListeners();
222        if (mParent != null) {
223            mParent.detach(this);
224        }
225        releaseAllWakeLocks();
226    }
227
228    static boolean equalsHandlesNulls(Object a, Object b) {
229        return (a == null) ? (b == null) : a.equals (b);
230    }
231
232    static boolean
233    equalsBaseDialString (String a, String b) {
234        return (a == null) ? (b == null) : (b != null && a.startsWith (b));
235    }
236
237    //CDMA
238    /**
239     * format original dial string
240     * 1) convert international dialing prefix "+" to
241     *    string specified per region
242     *
243     * 2) handle corner cases for PAUSE/WAIT dialing:
244     *
245     *    If PAUSE/WAIT sequence at the end, ignore them.
246     *
247     *    If consecutive PAUSE/WAIT sequence in the middle of the string,
248     *    and if there is any WAIT in PAUSE/WAIT sequence, treat them like WAIT.
249     */
250    public static String formatDialString(String phoneNumber) {
251        /**
252         * TODO(cleanup): This function should move to PhoneNumberUtils, and
253         * tests should be added.
254         */
255
256        if (phoneNumber == null) {
257            return null;
258        }
259        int length = phoneNumber.length();
260        StringBuilder ret = new StringBuilder();
261        char c;
262        int currIndex = 0;
263
264        while (currIndex < length) {
265            c = phoneNumber.charAt(currIndex);
266            if (isPause(c) || isWait(c)) {
267                if (currIndex < length - 1) {
268                    // if PW not at the end
269                    int nextIndex = findNextPCharOrNonPOrNonWCharIndex(phoneNumber, currIndex);
270                    // If there is non PW char following PW sequence
271                    if (nextIndex < length) {
272                        char pC = findPOrWCharToAppend(phoneNumber, currIndex, nextIndex);
273                        ret.append(pC);
274                        // If PW char sequence has more than 2 PW characters,
275                        // skip to the last PW character since the sequence already be
276                        // converted to WAIT character
277                        if (nextIndex > (currIndex + 1)) {
278                            currIndex = nextIndex - 1;
279                        }
280                    } else if (nextIndex == length) {
281                        // It means PW characters at the end, ignore
282                        currIndex = length - 1;
283                    }
284                }
285            } else {
286                ret.append(c);
287            }
288            currIndex++;
289        }
290        return PhoneNumberUtils.cdmaCheckAndProcessPlusCode(ret.toString());
291    }
292
293    /*package*/ boolean
294    compareTo(DriverCall c) {
295        // On mobile originated (MO) calls, the phone number may have changed
296        // due to a SIM Toolkit call control modification.
297        //
298        // We assume we know when MO calls are created (since we created them)
299        // and therefore don't need to compare the phone number anyway.
300        if (! (mIsIncoming || c.isMT)) return true;
301
302        // A new call appearing by SRVCC may have invalid number
303        //  if IMS service is not tightly coupled with cellular modem stack.
304        // Thus we prefer the preexisting handover connection instance.
305        if (isPhoneTypeGsm() && mOrigConnection != null) return true;
306
307        // ... but we can compare phone numbers on MT calls, and we have
308        // no control over when they begin, so we might as well
309
310        String cAddress = PhoneNumberUtils.stringFromStringAndTOA(c.number, c.TOA);
311        return mIsIncoming == c.isMT && equalsHandlesNulls(mAddress, cAddress);
312    }
313
314    @Override
315    public String getOrigDialString(){
316        return mDialString;
317    }
318
319    @Override
320    public GsmCdmaCall getCall() {
321        return mParent;
322    }
323
324    @Override
325    public long getDisconnectTime() {
326        return mDisconnectTime;
327    }
328
329    @Override
330    public long getHoldDurationMillis() {
331        if (getState() != GsmCdmaCall.State.HOLDING) {
332            // If not holding, return 0
333            return 0;
334        } else {
335            return SystemClock.elapsedRealtime() - mHoldingStartTime;
336        }
337    }
338
339    @Override
340    public GsmCdmaCall.State getState() {
341        if (mDisconnected) {
342            return GsmCdmaCall.State.DISCONNECTED;
343        } else {
344            return super.getState();
345        }
346    }
347
348    @Override
349    public void hangup() throws CallStateException {
350        if (!mDisconnected) {
351            mOwner.hangup(this);
352        } else {
353            throw new CallStateException ("disconnected");
354        }
355    }
356
357    @Override
358    public void separate() throws CallStateException {
359        if (!mDisconnected) {
360            mOwner.separate(this);
361        } else {
362            throw new CallStateException ("disconnected");
363        }
364    }
365
366    @Override
367    public void proceedAfterWaitChar() {
368        if (mPostDialState != PostDialState.WAIT) {
369            Rlog.w(LOG_TAG, "GsmCdmaConnection.proceedAfterWaitChar(): Expected "
370                    + "getPostDialState() to be WAIT but was " + mPostDialState);
371            return;
372        }
373
374        setPostDialState(PostDialState.STARTED);
375
376        processNextPostDialChar();
377    }
378
379    @Override
380    public void proceedAfterWildChar(String str) {
381        if (mPostDialState != PostDialState.WILD) {
382            Rlog.w(LOG_TAG, "GsmCdmaConnection.proceedAfterWaitChar(): Expected "
383                + "getPostDialState() to be WILD but was " + mPostDialState);
384            return;
385        }
386
387        setPostDialState(PostDialState.STARTED);
388
389        // make a new postDialString, with the wild char replacement string
390        // at the beginning, followed by the remaining postDialString.
391
392        StringBuilder buf = new StringBuilder(str);
393        buf.append(mPostDialString.substring(mNextPostDialChar));
394        mPostDialString = buf.toString();
395        mNextPostDialChar = 0;
396        if (Phone.DEBUG_PHONE) {
397            log("proceedAfterWildChar: new postDialString is " +
398                    mPostDialString);
399        }
400
401        processNextPostDialChar();
402    }
403
404    @Override
405    public void cancelPostDial() {
406        setPostDialState(PostDialState.CANCELLED);
407    }
408
409    /**
410     * Called when this Connection is being hung up locally (eg, user pressed "end")
411     * Note that at this point, the hangup request has been dispatched to the radio
412     * but no response has yet been received so update() has not yet been called
413     */
414    void
415    onHangupLocal() {
416        mCause = DisconnectCause.LOCAL;
417        mPreciseCause = 0;
418        mVendorCause = null;
419    }
420
421    /**
422     * Maps RIL call disconnect code to {@link DisconnectCause}.
423     * @param causeCode RIL disconnect code
424     * @return the corresponding value from {@link DisconnectCause}
425     */
426    int disconnectCauseFromCode(int causeCode) {
427        /**
428         * See 22.001 Annex F.4 for mapping of cause codes
429         * to local tones
430         */
431
432        switch (causeCode) {
433            case CallFailCause.USER_BUSY:
434                return DisconnectCause.BUSY;
435
436            case CallFailCause.NO_CIRCUIT_AVAIL:
437            case CallFailCause.TEMPORARY_FAILURE:
438            case CallFailCause.SWITCHING_CONGESTION:
439            case CallFailCause.CHANNEL_NOT_AVAIL:
440            case CallFailCause.QOS_NOT_AVAIL:
441            case CallFailCause.BEARER_NOT_AVAIL:
442                return DisconnectCause.CONGESTION;
443
444            case CallFailCause.ACM_LIMIT_EXCEEDED:
445                return DisconnectCause.LIMIT_EXCEEDED;
446
447            case CallFailCause.CALL_BARRED:
448                return DisconnectCause.CALL_BARRED;
449
450            case CallFailCause.FDN_BLOCKED:
451                return DisconnectCause.FDN_BLOCKED;
452
453            case CallFailCause.IMEI_NOT_ACCEPTED:
454                return DisconnectCause.IMEI_NOT_ACCEPTED;
455
456            case CallFailCause.UNOBTAINABLE_NUMBER:
457                return DisconnectCause.UNOBTAINABLE_NUMBER;
458
459            case CallFailCause.DIAL_MODIFIED_TO_USSD:
460                return DisconnectCause.DIAL_MODIFIED_TO_USSD;
461
462            case CallFailCause.DIAL_MODIFIED_TO_SS:
463                return DisconnectCause.DIAL_MODIFIED_TO_SS;
464
465            case CallFailCause.DIAL_MODIFIED_TO_DIAL:
466                return DisconnectCause.DIAL_MODIFIED_TO_DIAL;
467
468            case CallFailCause.CDMA_LOCKED_UNTIL_POWER_CYCLE:
469                return DisconnectCause.CDMA_LOCKED_UNTIL_POWER_CYCLE;
470
471            case CallFailCause.CDMA_DROP:
472                return DisconnectCause.CDMA_DROP;
473
474            case CallFailCause.CDMA_INTERCEPT:
475                return DisconnectCause.CDMA_INTERCEPT;
476
477            case CallFailCause.CDMA_REORDER:
478                return DisconnectCause.CDMA_REORDER;
479
480            case CallFailCause.CDMA_SO_REJECT:
481                return DisconnectCause.CDMA_SO_REJECT;
482
483            case CallFailCause.CDMA_RETRY_ORDER:
484                return DisconnectCause.CDMA_RETRY_ORDER;
485
486            case CallFailCause.CDMA_ACCESS_FAILURE:
487                return DisconnectCause.CDMA_ACCESS_FAILURE;
488
489            case CallFailCause.CDMA_PREEMPTED:
490                return DisconnectCause.CDMA_PREEMPTED;
491
492            case CallFailCause.CDMA_NOT_EMERGENCY:
493                return DisconnectCause.CDMA_NOT_EMERGENCY;
494
495            case CallFailCause.CDMA_ACCESS_BLOCKED:
496                return DisconnectCause.CDMA_ACCESS_BLOCKED;
497
498            case CallFailCause.ERROR_UNSPECIFIED:
499            case CallFailCause.NORMAL_CLEARING:
500            default:
501                GsmCdmaPhone phone = mOwner.getPhone();
502                int serviceState = phone.getServiceState().getState();
503                UiccCardApplication cardApp = phone.getUiccCardApplication();
504                AppState uiccAppState = (cardApp != null) ? cardApp.getState() :
505                        AppState.APPSTATE_UNKNOWN;
506                if (serviceState == ServiceState.STATE_POWER_OFF) {
507                    return DisconnectCause.POWER_OFF;
508                }
509                if (!mIsEmergencyCall) {
510                    // Only send OUT_OF_SERVICE if it is not an emergency call. We can still
511                    // technically be in STATE_OUT_OF_SERVICE or STATE_EMERGENCY_ONLY during
512                    // an emergency call and when it ends, we do not want to mistakenly generate
513                    // an OUT_OF_SERVICE disconnect cause during normal call ending.
514                    if ((serviceState == ServiceState.STATE_OUT_OF_SERVICE
515                            || serviceState == ServiceState.STATE_EMERGENCY_ONLY)) {
516                        return DisconnectCause.OUT_OF_SERVICE;
517                    }
518                    // If we are placing an emergency call and the SIM is currently PIN/PUK
519                    // locked the AppState will always not be equal to APPSTATE_READY.
520                    if (uiccAppState != AppState.APPSTATE_READY) {
521                        if (isPhoneTypeGsm()) {
522                            return DisconnectCause.ICC_ERROR;
523                        } else { // CDMA
524                            if (phone.mCdmaSubscriptionSource ==
525                                    CdmaSubscriptionSourceManager.SUBSCRIPTION_FROM_RUIM) {
526                                return DisconnectCause.ICC_ERROR;
527                            }
528                        }
529                    }
530                }
531                if (isPhoneTypeGsm()) {
532                    if (causeCode == CallFailCause.ERROR_UNSPECIFIED) {
533                        if (phone.mSST.mRestrictedState.isCsRestricted()) {
534                            return DisconnectCause.CS_RESTRICTED;
535                        } else if (phone.mSST.mRestrictedState.isCsEmergencyRestricted()) {
536                            return DisconnectCause.CS_RESTRICTED_EMERGENCY;
537                        } else if (phone.mSST.mRestrictedState.isCsNormalRestricted()) {
538                            return DisconnectCause.CS_RESTRICTED_NORMAL;
539                        }
540                    }
541                }
542                if (causeCode == CallFailCause.NORMAL_CLEARING) {
543                    return DisconnectCause.NORMAL;
544                }
545                // If nothing else matches, report unknown call drop reason
546                // to app, not NORMAL call end.
547                return DisconnectCause.ERROR_UNSPECIFIED;
548        }
549    }
550
551    /*package*/ void
552    onRemoteDisconnect(int causeCode, String vendorCause) {
553        this.mPreciseCause = causeCode;
554        this.mVendorCause = vendorCause;
555        onDisconnect(disconnectCauseFromCode(causeCode));
556    }
557
558    /**
559     * Called when the radio indicates the connection has been disconnected.
560     * @param cause call disconnect cause; values are defined in {@link DisconnectCause}
561     */
562    @Override
563    public boolean onDisconnect(int cause) {
564        boolean changed = false;
565
566        mCause = cause;
567
568        if (!mDisconnected) {
569            doDisconnect();
570
571            if (DBG) Rlog.d(LOG_TAG, "onDisconnect: cause=" + cause);
572
573            mOwner.getPhone().notifyDisconnect(this);
574
575            if (mParent != null) {
576                changed = mParent.connectionDisconnected(this);
577            }
578
579            mOrigConnection = null;
580        }
581        clearPostDialListeners();
582        releaseWakeLock();
583        return changed;
584    }
585
586    //CDMA
587    /** Called when the call waiting connection has been hung up */
588    /*package*/ void
589    onLocalDisconnect() {
590        if (!mDisconnected) {
591            doDisconnect();
592            if (VDBG) Rlog.d(LOG_TAG, "onLoalDisconnect" );
593
594            if (mParent != null) {
595                mParent.detach(this);
596            }
597        }
598        releaseWakeLock();
599    }
600
601    // Returns true if state has changed, false if nothing changed
602    public boolean
603    update (DriverCall dc) {
604        GsmCdmaCall newParent;
605        boolean changed = false;
606        boolean wasConnectingInOrOut = isConnectingInOrOut();
607        boolean wasHolding = (getState() == GsmCdmaCall.State.HOLDING);
608
609        newParent = parentFromDCState(dc.state);
610
611        if (Phone.DEBUG_PHONE) log("parent= " +mParent +", newParent= " + newParent);
612
613        //Ignore dc.number and dc.name in case of a handover connection
614        if (isPhoneTypeGsm() && mOrigConnection != null) {
615            if (Phone.DEBUG_PHONE) log("update: mOrigConnection is not null");
616        } else {
617            log(" mNumberConverted " + mNumberConverted);
618            if (!equalsBaseDialString(mAddress, dc.number) && (!mNumberConverted
619                    || !equalsBaseDialString(mConvertedNumber, dc.number))) {
620                if (Phone.DEBUG_PHONE) log("update: phone # changed!");
621                mAddress = dc.number;
622                changed = true;
623            }
624        }
625
626        // A null cnapName should be the same as ""
627        if (TextUtils.isEmpty(dc.name)) {
628            if (!TextUtils.isEmpty(mCnapName)) {
629                changed = true;
630                mCnapName = "";
631            }
632        } else if (!dc.name.equals(mCnapName)) {
633            changed = true;
634            mCnapName = dc.name;
635        }
636
637        if (Phone.DEBUG_PHONE) log("--dssds----"+mCnapName);
638        mCnapNamePresentation = dc.namePresentation;
639        mNumberPresentation = dc.numberPresentation;
640
641        if (newParent != mParent) {
642            if (mParent != null) {
643                mParent.detach(this);
644            }
645            newParent.attach(this, dc);
646            mParent = newParent;
647            changed = true;
648        } else {
649            boolean parentStateChange;
650            parentStateChange = mParent.update (this, dc);
651            changed = changed || parentStateChange;
652        }
653
654        /** Some state-transition events */
655
656        if (Phone.DEBUG_PHONE) log(
657                "update: parent=" + mParent +
658                ", hasNewParent=" + (newParent != mParent) +
659                ", wasConnectingInOrOut=" + wasConnectingInOrOut +
660                ", wasHolding=" + wasHolding +
661                ", isConnectingInOrOut=" + isConnectingInOrOut() +
662                ", changed=" + changed);
663
664
665        if (wasConnectingInOrOut && !isConnectingInOrOut()) {
666            onConnectedInOrOut();
667        }
668
669        if (changed && !wasHolding && (getState() == GsmCdmaCall.State.HOLDING)) {
670            // We've transitioned into HOLDING
671            onStartedHolding();
672        }
673
674        return changed;
675    }
676
677    /**
678     * Called when this Connection is in the foregroundCall
679     * when a dial is initiated.
680     * We know we're ACTIVE, and we know we're going to end up
681     * HOLDING in the backgroundCall
682     */
683    void
684    fakeHoldBeforeDial() {
685        if (mParent != null) {
686            mParent.detach(this);
687        }
688
689        mParent = mOwner.mBackgroundCall;
690        mParent.attachFake(this, GsmCdmaCall.State.HOLDING);
691
692        onStartedHolding();
693    }
694
695    /*package*/ int
696    getGsmCdmaIndex() throws CallStateException {
697        if (mIndex >= 0) {
698            return mIndex + 1;
699        } else {
700            throw new CallStateException ("GsmCdma index not yet assigned");
701        }
702    }
703
704    /**
705     * An incoming or outgoing call has connected
706     */
707    void
708    onConnectedInOrOut() {
709        mConnectTime = System.currentTimeMillis();
710        mConnectTimeReal = SystemClock.elapsedRealtime();
711        mDuration = 0;
712
713        // bug #678474: incoming call interpreted as missed call, even though
714        // it sounds like the user has picked up the call.
715        if (Phone.DEBUG_PHONE) {
716            log("onConnectedInOrOut: connectTime=" + mConnectTime);
717        }
718
719        if (!mIsIncoming) {
720            // outgoing calls only
721            processNextPostDialChar();
722        } else {
723            // Only release wake lock for incoming calls, for outgoing calls the wake lock
724            // will be released after any pause-dial is completed
725            releaseWakeLock();
726        }
727    }
728
729    private void
730    doDisconnect() {
731        mIndex = -1;
732        mDisconnectTime = System.currentTimeMillis();
733        mDuration = SystemClock.elapsedRealtime() - mConnectTimeReal;
734        mDisconnected = true;
735        clearPostDialListeners();
736    }
737
738    /*package*/ void
739    onStartedHolding() {
740        mHoldingStartTime = SystemClock.elapsedRealtime();
741    }
742
743    /**
744     * Performs the appropriate action for a post-dial char, but does not
745     * notify application. returns false if the character is invalid and
746     * should be ignored
747     */
748    private boolean
749    processPostDialChar(char c) {
750        if (PhoneNumberUtils.is12Key(c)) {
751            mOwner.mCi.sendDtmf(c, mHandler.obtainMessage(EVENT_DTMF_DONE));
752        } else if (isPause(c)) {
753            if (!isPhoneTypeGsm()) {
754                setPostDialState(PostDialState.PAUSE);
755            }
756            // From TS 22.101:
757            // It continues...
758            // Upon the called party answering the UE shall send the DTMF digits
759            // automatically to the network after a delay of 3 seconds( 20 ).
760            // The digits shall be sent according to the procedures and timing
761            // specified in 3GPP TS 24.008 [13]. The first occurrence of the
762            // "DTMF Control Digits Separator" shall be used by the ME to
763            // distinguish between the addressing digits (i.e. the phone number)
764            // and the DTMF digits. Upon subsequent occurrences of the
765            // separator,
766            // the UE shall pause again for 3 seconds ( 20 ) before sending
767            // any further DTMF digits.
768            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_PAUSE_DONE),
769                    isPhoneTypeGsm() ? PAUSE_DELAY_MILLIS_GSM: PAUSE_DELAY_MILLIS_CDMA);
770        } else if (isWait(c)) {
771            setPostDialState(PostDialState.WAIT);
772        } else if (isWild(c)) {
773            setPostDialState(PostDialState.WILD);
774        } else {
775            return false;
776        }
777
778        return true;
779    }
780
781    @Override
782    public String
783    getRemainingPostDialString() {
784        String subStr = super.getRemainingPostDialString();
785        if (!isPhoneTypeGsm() && !TextUtils.isEmpty(subStr)) {
786            int wIndex = subStr.indexOf(PhoneNumberUtils.WAIT);
787            int pIndex = subStr.indexOf(PhoneNumberUtils.PAUSE);
788
789            if (wIndex > 0 && (wIndex < pIndex || pIndex <= 0)) {
790                subStr = subStr.substring(0, wIndex);
791            } else if (pIndex > 0) {
792                subStr = subStr.substring(0, pIndex);
793            }
794        }
795        return subStr;
796    }
797
798    //CDMA
799    public void updateParent(GsmCdmaCall oldParent, GsmCdmaCall newParent){
800        if (newParent != oldParent) {
801            if (oldParent != null) {
802                oldParent.detach(this);
803            }
804            newParent.attachFake(this, GsmCdmaCall.State.ACTIVE);
805            mParent = newParent;
806        }
807    }
808
809    @Override
810    protected void finalize()
811    {
812        /**
813         * It is understood that This finalizer is not guaranteed
814         * to be called and the release lock call is here just in
815         * case there is some path that doesn't call onDisconnect
816         * and or onConnectedInOrOut.
817         */
818        if (mPartialWakeLock != null && mPartialWakeLock.isHeld()) {
819            Rlog.e(LOG_TAG, "UNEXPECTED; mPartialWakeLock is held when finalizing.");
820        }
821        clearPostDialListeners();
822        releaseWakeLock();
823    }
824
825    private void
826    processNextPostDialChar() {
827        char c = 0;
828        Registrant postDialHandler;
829
830        if (mPostDialState == PostDialState.CANCELLED) {
831            releaseWakeLock();
832            return;
833        }
834
835        if (mPostDialString == null ||
836                mPostDialString.length() <= mNextPostDialChar) {
837            setPostDialState(PostDialState.COMPLETE);
838
839            // We were holding a wake lock until pause-dial was complete, so give it up now
840            releaseWakeLock();
841
842            // notifyMessage.arg1 is 0 on complete
843            c = 0;
844        } else {
845            boolean isValid;
846
847            setPostDialState(PostDialState.STARTED);
848
849            c = mPostDialString.charAt(mNextPostDialChar++);
850
851            isValid = processPostDialChar(c);
852
853            if (!isValid) {
854                // Will call processNextPostDialChar
855                mHandler.obtainMessage(EVENT_NEXT_POST_DIAL).sendToTarget();
856                // Don't notify application
857                Rlog.e(LOG_TAG, "processNextPostDialChar: c=" + c + " isn't valid!");
858                return;
859            }
860        }
861
862        notifyPostDialListenersNextChar(c);
863
864        // TODO: remove the following code since the handler no longer executes anything.
865        postDialHandler = mOwner.getPhone().getPostDialHandler();
866
867        Message notifyMessage;
868
869        if (postDialHandler != null
870                && (notifyMessage = postDialHandler.messageForRegistrant()) != null) {
871            // The AsyncResult.result is the Connection object
872            PostDialState state = mPostDialState;
873            AsyncResult ar = AsyncResult.forMessage(notifyMessage);
874            ar.result = this;
875            ar.userObj = state;
876
877            // arg1 is the character that was/is being processed
878            notifyMessage.arg1 = c;
879
880            //Rlog.v("GsmCdma", "##### processNextPostDialChar: send msg to postDialHandler, arg1=" + c);
881            notifyMessage.sendToTarget();
882        }
883    }
884
885    /** "connecting" means "has never been ACTIVE" for both incoming
886     *  and outgoing calls
887     */
888    private boolean
889    isConnectingInOrOut() {
890        return mParent == null || mParent == mOwner.mRingingCall
891            || mParent.mState == GsmCdmaCall.State.DIALING
892            || mParent.mState == GsmCdmaCall.State.ALERTING;
893    }
894
895    private GsmCdmaCall
896    parentFromDCState (DriverCall.State state) {
897        switch (state) {
898            case ACTIVE:
899            case DIALING:
900            case ALERTING:
901                return mOwner.mForegroundCall;
902            //break;
903
904            case HOLDING:
905                return mOwner.mBackgroundCall;
906            //break;
907
908            case INCOMING:
909            case WAITING:
910                return mOwner.mRingingCall;
911            //break;
912
913            default:
914                throw new RuntimeException("illegal call state: " + state);
915        }
916    }
917
918    /**
919     * Set post dial state and acquire wake lock while switching to "started" or "pause"
920     * state, the wake lock will be released if state switches out of "started" or "pause"
921     * state or after WAKE_LOCK_TIMEOUT_MILLIS.
922     * @param s new PostDialState
923     */
924    private void setPostDialState(PostDialState s) {
925        if (s == PostDialState.STARTED ||
926                s == PostDialState.PAUSE) {
927            synchronized (mPartialWakeLock) {
928                if (mPartialWakeLock.isHeld()) {
929                    mHandler.removeMessages(EVENT_WAKE_LOCK_TIMEOUT);
930                } else {
931                    acquireWakeLock();
932                }
933                Message msg = mHandler.obtainMessage(EVENT_WAKE_LOCK_TIMEOUT);
934                mHandler.sendMessageDelayed(msg, WAKE_LOCK_TIMEOUT_MILLIS);
935            }
936        } else {
937            mHandler.removeMessages(EVENT_WAKE_LOCK_TIMEOUT);
938            releaseWakeLock();
939        }
940        mPostDialState = s;
941        notifyPostDialListeners();
942    }
943
944    private void createWakeLock(Context context) {
945        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
946        mPartialWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOG_TAG);
947    }
948
949    private void acquireWakeLock() {
950        if (mPartialWakeLock != null) {
951            synchronized (mPartialWakeLock) {
952                log("acquireWakeLock");
953                mPartialWakeLock.acquire();
954            }
955        }
956    }
957
958    private void releaseWakeLock() {
959        if (mPartialWakeLock != null) {
960            synchronized (mPartialWakeLock) {
961                if (mPartialWakeLock.isHeld()) {
962                    log("releaseWakeLock");
963                    mPartialWakeLock.release();
964                }
965            }
966        }
967    }
968
969    private void releaseAllWakeLocks() {
970        if (mPartialWakeLock != null) {
971            synchronized (mPartialWakeLock) {
972                while (mPartialWakeLock.isHeld()) {
973                    mPartialWakeLock.release();
974                }
975            }
976        }
977    }
978
979    private static boolean isPause(char c) {
980        return c == PhoneNumberUtils.PAUSE;
981    }
982
983    private static boolean isWait(char c) {
984        return c == PhoneNumberUtils.WAIT;
985    }
986
987    private static boolean isWild(char c) {
988        return c == PhoneNumberUtils.WILD;
989    }
990
991    //CDMA
992    // This function is to find the next PAUSE character index if
993    // multiple pauses in a row. Otherwise it finds the next non PAUSE or
994    // non WAIT character index.
995    private static int findNextPCharOrNonPOrNonWCharIndex(String phoneNumber, int currIndex) {
996        boolean wMatched = isWait(phoneNumber.charAt(currIndex));
997        int index = currIndex + 1;
998        int length = phoneNumber.length();
999        while (index < length) {
1000            char cNext = phoneNumber.charAt(index);
1001            // if there is any W inside P/W sequence,mark it
1002            if (isWait(cNext)) {
1003                wMatched = true;
1004            }
1005            // if any characters other than P/W chars after P/W sequence
1006            // we break out the loop and append the correct
1007            if (!isWait(cNext) && !isPause(cNext)) {
1008                break;
1009            }
1010            index++;
1011        }
1012
1013        // It means the PAUSE character(s) is in the middle of dial string
1014        // and it needs to be handled one by one.
1015        if ((index < length) && (index > (currIndex + 1))  &&
1016                ((wMatched == false) && isPause(phoneNumber.charAt(currIndex)))) {
1017            return (currIndex + 1);
1018        }
1019        return index;
1020    }
1021
1022    // CDMA
1023    // This function returns either PAUSE or WAIT character to append.
1024    // It is based on the next non PAUSE/WAIT character in the phoneNumber and the
1025    // index for the current PAUSE/WAIT character
1026    private static char findPOrWCharToAppend(String phoneNumber, int currPwIndex,
1027                                             int nextNonPwCharIndex) {
1028        char c = phoneNumber.charAt(currPwIndex);
1029        char ret;
1030
1031        // Append the PW char
1032        ret = (isPause(c)) ? PhoneNumberUtils.PAUSE : PhoneNumberUtils.WAIT;
1033
1034        // If the nextNonPwCharIndex is greater than currPwIndex + 1,
1035        // it means the PW sequence contains not only P characters.
1036        // Since for the sequence that only contains P character,
1037        // the P character is handled one by one, the nextNonPwCharIndex
1038        // equals to currPwIndex + 1.
1039        // In this case, skip P, append W.
1040        if (nextNonPwCharIndex > (currPwIndex + 1)) {
1041            ret = PhoneNumberUtils.WAIT;
1042        }
1043        return ret;
1044    }
1045
1046    private String maskDialString(String dialString) {
1047        if (VDBG) {
1048            return dialString;
1049        }
1050
1051        return "<MASKED>";
1052    }
1053
1054    private void fetchDtmfToneDelay(GsmCdmaPhone phone) {
1055        CarrierConfigManager configMgr = (CarrierConfigManager)
1056                phone.getContext().getSystemService(Context.CARRIER_CONFIG_SERVICE);
1057        PersistableBundle b = configMgr.getConfigForSubId(phone.getSubId());
1058        if (b != null) {
1059            mDtmfToneDelay = b.getInt(phone.getDtmfToneDelayKey());
1060        }
1061    }
1062
1063    private boolean isPhoneTypeGsm() {
1064        return mOwner.getPhone().getPhoneType() == PhoneConstants.PHONE_TYPE_GSM;
1065    }
1066
1067    private void log(String msg) {
1068        Rlog.d(LOG_TAG, "[GsmCdmaConn] " + msg);
1069    }
1070
1071    @Override
1072    public int getNumberPresentation() {
1073        return mNumberPresentation;
1074    }
1075
1076    @Override
1077    public UUSInfo getUUSInfo() {
1078        return mUusInfo;
1079    }
1080
1081    public int getPreciseDisconnectCause() {
1082        return mPreciseCause;
1083    }
1084
1085    @Override
1086    public String getVendorDisconnectCause() {
1087        return mVendorCause;
1088    }
1089
1090    @Override
1091    public void migrateFrom(Connection c) {
1092        if (c == null) return;
1093
1094        super.migrateFrom(c);
1095
1096        this.mUusInfo = c.getUUSInfo();
1097
1098        this.setUserData(c.getUserData());
1099    }
1100
1101    @Override
1102    public Connection getOrigConnection() {
1103        return mOrigConnection;
1104    }
1105
1106    @Override
1107    public boolean isMultiparty() {
1108        if (mOrigConnection != null) {
1109            return mOrigConnection.isMultiparty();
1110        }
1111
1112        return false;
1113    }
1114}
1115