summaryrefslogtreecommitdiffstats
path: root/src/com/android/car/dialer/ui/activecall/InCallViewModel.java
blob: 328695b52ca0da9bb3f427eba1d2a477f5b4c8cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.car.dialer.ui.activecall;

import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.telecom.Call;

import androidx.annotation.NonNull;
import androidx.core.util.Pair;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MediatorLiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;

import com.android.car.arch.common.LiveDataFunctions;
import com.android.car.dialer.livedata.AudioRouteLiveData;
import com.android.car.dialer.livedata.CallDetailLiveData;
import com.android.car.dialer.livedata.CallStateLiveData;
import com.android.car.dialer.log.L;
import com.android.car.dialer.telecom.InCallServiceImpl;
import com.android.car.telephony.common.CallDetail;

import com.google.common.base.Predicate;
import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * View model for {@link InCallActivity} and {@link OngoingCallFragment}. UI that doesn't belong to
 * in call page should use a different ViewModel.
 */
public class InCallViewModel extends AndroidViewModel implements
        InCallServiceImpl.ActiveCallListChangedCallback {
    private static final String TAG = "CD.InCallViewModel";

    private final MutableLiveData<List<Call>> mCallListLiveData;
    private final MutableLiveData<List<Call>> mOngoingCallListLiveData;
    private final Comparator<Call> mCallComparator;

    private final MutableLiveData<Call> mIncomingCallLiveData;

    private final LiveData<CallDetail> mCallDetailLiveData;
    private final LiveData<Integer> mCallStateLiveData;
    private final LiveData<Call> mPrimaryCallLiveData;
    private final LiveData<Call> mSecondaryCallLiveData;
    private final LiveData<CallDetail> mSecondaryCallDetailLiveData;
    private final LiveData<Integer> mAudioRouteLiveData;
    private final MutableLiveData<Boolean> mDialpadIsOpen;
    private final ShowOnholdCallLiveData mShowOnholdCall;
    private LiveData<Long> mCallConnectTimeLiveData;
    private LiveData<Pair<Integer, Long>> mCallStateAndConnectTimeLiveData;
    private final Context mContext;

    private InCallServiceImpl mInCallService;
    private final ServiceConnection mInCallServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            L.d(TAG, "onServiceConnected: %s, service: %s", name, binder);
            mInCallService = ((InCallServiceImpl.LocalBinder) binder).getService();
            for (Call call : mInCallService.getCalls()) {
                call.registerCallback(mCallStateChangedCallback);
            }
            updateCallList();
            mInCallService.addActiveCallListChangedCallback(InCallViewModel.this);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            L.d(TAG, "onServiceDisconnected: %s", name);
            mInCallService = null;
        }
    };

    // Reuse the same instance so the callback won't be registered more than once.
    private final Call.Callback mCallStateChangedCallback = new Call.Callback() {
        @Override
        public void onStateChanged(Call call, int state) {
            // Don't show in call activity by declining a ringing call to avoid UI flashing.
            if (call.equals(mIncomingCallLiveData.getValue()) && state == Call.STATE_DISCONNECTED) {
                return;
            }
            // Sets value to trigger incoming call and active call list to update.
            mCallListLiveData.setValue(mCallListLiveData.getValue());
        }
    };

    public InCallViewModel(@NonNull Application application) {
        super(application);
        mContext = application.getApplicationContext();

        mIncomingCallLiveData = new MutableLiveData<>();
        mOngoingCallListLiveData = new MutableLiveData<>();
        mCallComparator = new CallComparator();
        mCallListLiveData = new MutableLiveData<List<Call>>() {
            @Override
            public void setValue(List<Call> callList) {
                super.setValue(callList);
                List<Call> activeCallList = filter(callList,
                        call -> call != null && call.getState() != Call.STATE_RINGING);
                activeCallList.sort(mCallComparator);
                mOngoingCallListLiveData.setValue(activeCallList);
                mIncomingCallLiveData.setValue(firstMatch(callList,
                        call -> call != null && call.getState() == Call.STATE_RINGING));
            }
        };

        mPrimaryCallLiveData = Transformations.map(mOngoingCallListLiveData,
                input -> input.isEmpty() ? null : input.get(0));
        mCallDetailLiveData = Transformations.switchMap(mPrimaryCallLiveData,
                input -> input != null ? new CallDetailLiveData(input) : null);
        mCallStateLiveData = Transformations.switchMap(mPrimaryCallLiveData,
                input -> input != null ? new CallStateLiveData(input) : null);
        mCallConnectTimeLiveData = Transformations.map(mCallDetailLiveData, (details) -> {
            if (details == null) {
                return 0L;
            }
            return details.getConnectTimeMillis();
        });
        mCallStateAndConnectTimeLiveData =
                LiveDataFunctions.pair(mCallStateLiveData, mCallConnectTimeLiveData);

        mSecondaryCallLiveData = Transformations.map(mOngoingCallListLiveData,
                callList -> (callList != null && callList.size() > 1) ? callList.get(1) : null);

        mSecondaryCallDetailLiveData = Transformations.switchMap(mSecondaryCallLiveData,
                input -> input != null ? new CallDetailLiveData(input) : null);

        mAudioRouteLiveData = new AudioRouteLiveData(mContext);

        mDialpadIsOpen = new MutableLiveData<>();
        // Set initial value to avoid NPE
        mDialpadIsOpen.setValue(false);

        mShowOnholdCall = new ShowOnholdCallLiveData(mSecondaryCallLiveData, mDialpadIsOpen);

        Intent intent = new Intent(mContext, InCallServiceImpl.class);
        intent.setAction(InCallServiceImpl.ACTION_LOCAL_BIND);
        mContext.bindService(intent, mInCallServiceConnection, Context.BIND_AUTO_CREATE);
    }

    /** Returns the live data which monitors all the calls. */
    public LiveData<List<Call>> getAllCallList() {
        return mCallListLiveData;
    }

    /** Returns the live data which monitors the current incoming call. */
    public LiveData<Call> getIncomingCall() {
        return mIncomingCallLiveData;
    }

    /** Returns {@link LiveData} for the ongoing call list which excludes the ringing call. */
    public LiveData<List<Call>> getOngoingCallList() {
        return mOngoingCallListLiveData;
    }

    /**
     * Returns the live data which monitors the primary call details.
     */
    public LiveData<CallDetail> getPrimaryCallDetail() {
        return mCallDetailLiveData;
    }

    /**
     * Returns the live data which monitors the primary call state.
     */
    public LiveData<Integer> getPrimaryCallState() {
        return mCallStateLiveData;
    }

    /**
     * Returns the live data which monitors the primary call state and the start time of the call.
     */
    public LiveData<Pair<Integer, Long>> getCallStateAndConnectTime() {
        return mCallStateAndConnectTimeLiveData;
    }

    /**
     * Returns the live data which monitor the primary call.
     * A primary call in the first call in the ongoing call list,
     * which is sorted based on {@link CallComparator}.
     */
    public LiveData<Call> getPrimaryCall() {
        return mPrimaryCallLiveData;
    }

    /**
     * Returns the live data which monitor the secondary call.
     * A secondary call in the second call in the ongoing call list,
     * which is sorted based on {@link CallComparator}.
     * The value will be null if there is no second call in the call list.
     */
    public LiveData<Call> getSecondaryCall() {
        return mSecondaryCallLiveData;
    }

    /**
     * Returns the live data which monitors the secondary call details.
     */
    public LiveData<CallDetail> getSecondaryCallDetail() {
        return mSecondaryCallDetailLiveData;
    }

    /**
     * Returns current audio route.
     */
    public LiveData<Integer> getAudioRoute() {
        return mAudioRouteLiveData;
    }

    /** Return the {@link MutableLiveData} for dialpad open state. */
    public MutableLiveData<Boolean> getDialpadOpenState() {
        return mDialpadIsOpen;
    }

    /** Return the livedata monitors onhold call status. */
    public LiveData<Boolean> shouldShowOnholdCall() {
        return mShowOnholdCall;
    }

    @Override
    public boolean onTelecomCallAdded(Call telecomCall) {
        L.i(TAG, "onTelecomCallAdded %s %s", telecomCall, this);
        telecomCall.registerCallback(mCallStateChangedCallback);
        updateCallList();
        return false;
    }

    @Override
    public boolean onTelecomCallRemoved(Call telecomCall) {
        L.i(TAG, "onTelecomCallRemoved %s %s", telecomCall, this);
        telecomCall.unregisterCallback(mCallStateChangedCallback);
        updateCallList();
        return false;
    }

    private void updateCallList() {
        List<Call> callList = new ArrayList<>();
        callList.addAll(mInCallService.getCalls());
        mCallListLiveData.setValue(callList);
    }

    @Override
    protected void onCleared() {
        mContext.unbindService(mInCallServiceConnection);
        if (mInCallService != null) {
            for (Call call : mInCallService.getCalls()) {
                call.unregisterCallback(mCallStateChangedCallback);
            }
            mInCallService.removeActiveCallListChangedCallback(this);
        }
        mInCallService = null;
    }

    private static class CallComparator implements Comparator<Call> {
        /**
         * The rank of call state. Used for sorting active calls. Rank is listed from lowest to
         * highest.
         */
        private static final List<Integer> CALL_STATE_RANK = Lists.newArrayList(
                Call.STATE_RINGING,
                Call.STATE_DISCONNECTED,
                Call.STATE_DISCONNECTING,
                Call.STATE_NEW,
                Call.STATE_CONNECTING,
                Call.STATE_SELECT_PHONE_ACCOUNT,
                Call.STATE_HOLDING,
                Call.STATE_ACTIVE,
                Call.STATE_DIALING);

        @Override
        public int compare(Call call, Call otherCall) {
            boolean callHasParent = call.getParent() != null;
            boolean otherCallHasParent = otherCall.getParent() != null;

            if (callHasParent && !otherCallHasParent) {
                return 1;
            } else if (!callHasParent && otherCallHasParent) {
                return -1;
            }
            int carCallRank = CALL_STATE_RANK.indexOf(call.getState());
            int otherCarCallRank = CALL_STATE_RANK.indexOf(otherCall.getState());

            return otherCarCallRank - carCallRank;
        }
    }

    private static Call firstMatch(List<Call> callList, Predicate<Call> predicate) {
        List<Call> filteredResults = filter(callList, predicate);
        return filteredResults.isEmpty() ? null : filteredResults.get(0);
    }

    private static List<Call> filter(List<Call> callList, Predicate<Call> predicate) {
        if (callList == null || predicate == null) {
            return Collections.emptyList();
        }

        List<Call> filteredResults = new ArrayList<>();
        for (Call call : callList) {
            if (predicate.apply(call)) {
                filteredResults.add(call);
            }
        }
        return filteredResults;
    }

    private static class ShowOnholdCallLiveData extends MediatorLiveData<Boolean> {

        private final LiveData<Call> mSecondaryCallLiveData;
        private final MutableLiveData<Boolean> mDialpadIsOpen;

        private ShowOnholdCallLiveData(LiveData<Call> secondaryCallLiveData,
                MutableLiveData<Boolean> dialpadState) {
            mSecondaryCallLiveData = secondaryCallLiveData;
            mDialpadIsOpen = dialpadState;
            setValue(false);

            addSource(mSecondaryCallLiveData, v -> update());
            addSource(mDialpadIsOpen, v -> update());
        }

        private void update() {
            Boolean shouldShowOnholdCall = !mDialpadIsOpen.getValue();
            Call onholdCall = mSecondaryCallLiveData.getValue();
            if (shouldShowOnholdCall && onholdCall != null
                    && onholdCall.getState() == Call.STATE_HOLDING) {
                setValue(true);
            } else {
                setValue(false);
            }
        }

        @Override
        public void setValue(Boolean newValue) {
            // Only set value and notify observers when the value changes.
            if (getValue() != newValue) {
                super.setValue(newValue);
            }
        }
    }
}